nex-code 0.5.9 → 0.5.11

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.
@@ -1,136 +1,136 @@
1
- var ua=Object.defineProperty;var My=Object.getOwnPropertyDescriptor;var Py=Object.getOwnPropertyNames;var Ly=Object.prototype.hasOwnProperty;var Iy=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Dy=(t,e)=>{for(var s in e)ua(t,s,{get:e[s],enumerable:!0})},jy=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Py(e))!Ly.call(t,o)&&o!==s&&ua(t,o,{get:()=>e[o],enumerable:!(n=My(e,o))||n.enumerable});return t};var qy=t=>jy(ua({},"__esModule",{value:!0}),t);var _s=Z((LT,du)=>{async function Fy(t,e){if(!t.response?.data)return t.message;let s=t.response.data;if(typeof s=="object"&&s!==null&&typeof s.pipe!="function")return e(s)||t.message;try{let n=await new Promise((r,i)=>{let a=[];s.on("data",l=>a.push(l)),s.on("end",()=>r(Buffer.concat(a).toString("utf8"))),s.on("error",i)}),o=JSON.parse(n);return e(o)||n||t.message}catch{return t.message}}var da=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,n={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};du.exports={BaseProvider:da,readStreamErrorBody:Fy}});var ks=Z((IT,hu)=>{var $s=class{buildRequestBody(e){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(e){return e}normalizeResponse(e){throw new Error("normalizeResponse() not implemented")}createStreamParser(e,s={}){throw new Error("createStreamParser() not implemented")}},bs=class{constructor(e,s={}){this.onToken=e,this.callbacks=s,this.content="",this.buffer=""}feed(e){this.buffer+=e;let s=this.buffer.split(`
2
- `);this.buffer=s.pop()||"";for(let n of s){let o=this.parseLine(n);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},gr=class extends bs{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},yr=class extends $s{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:s,max_tokens:o,temperature:r};return i&&(a.stream=!0),n&&n.length>0&&(a.tools=n),a}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}createStreamParser(e,s={}){return new gr(e,s)}},wr=class extends bs{constructor(e,s={}){super(e,s),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let s=e.trim();if(!s.startsWith("data: "))return{done:!1};let n=s.slice(6),o;try{o=JSON.parse(n)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let s={};if(e.inputJson)try{s=JSON.parse(e.inputJson)}catch{s=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:s}}})}}},fa="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",_r=class extends $s{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,max_tokens:o,temperature:r};if(i&&(l.stream=!0),a?.system){let c=a.system,u=c.indexOf(fa);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+fa.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=c}return n&&n.length>0&&(l.tools=n),l}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}createStreamParser(e,s={}){return new wr(e,s)}};function fu(t){if(t!==null&&typeof t=="object")return t;if(typeof t!="string")return t||{};try{return JSON.parse(t)}catch{}let e=t.replace(/,\s*([}\]])/g,"$1");e=e.replace(/([^\\])\n/g,"$1\\n");try{return JSON.parse(e)}catch{}return{}}var $r=class extends bs{constructor(e,s={}){super(e,s),this.toolCalls=[],this.onThinkingToken=s.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let s;try{s=JSON.parse(e)}catch{return{done:!1}}return s.message?.thinking&&this.onThinkingToken(s.message.thinking),s.message?.content&&(this.onToken(s.message.content),this.content+=s.message.content),s.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(s.message.tool_calls)),s.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,s)=>({id:e.id||`ollama-${Date.now()}-${s}`,function:{name:e.function?.name||e.name||"unknown",arguments:fu(e.function?.arguments??e.arguments)}}))}}},br=class extends $s{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(l.tools=n),l}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:(s.tool_calls||[]).map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:fu(n.function?.arguments??n.arguments)}}))}}createStreamParser(e,s={}){return new $r(e,s)}},By=new yr,Uy=new _r,Wy=new br;hu.exports={ANTHROPIC_CACHE_BOUNDARY:fa,WireProtocol:$s,StreamParser:bs,OpenAICompatibleProtocol:yr,AnthropicProtocol:_r,OllamaChatProtocol:br,OpenAIStreamParser:gr,AnthropicStreamParser:wr,OllamaStreamParser:$r,openaiProtocol:By,anthropicProtocol:Uy,ollamaProtocol:Wy}});var gu=Z((DT,mu)=>{var kr=require("axios"),Hy=require("http"),Yy=require("https"),{BaseProvider:Gy,readStreamErrorBody:zy}=_s(),{ollamaProtocol:Pn}=ks(),xr=new Hy.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Sr=new Yy.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),pu={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemma4:e2b":{id:"gemma4:e2b",name:"Gemma 4 E2B",maxTokens:8192,contextWindow:131072},"gemma4:e4b":{id:"gemma4:e4b",name:"Gemma 4 E4B",maxTokens:8192,contextWindow:131072},"gemma4:26b-a4b":{id:"gemma4:26b-a4b",name:"Gemma 4 26B A4B",maxTokens:16384,contextWindow:262144},"gemma4:31b":{id:"gemma4:31b",name:"Gemma 4 31B",maxTokens:16384,contextWindow:262144},"gemma4:31b-cloud":{id:"gemma4:31b-cloud",name:"Gemma 4 31B Cloud",maxTokens:16384,contextWindow:262144},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},ha=class extends Gy{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||pu,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){kr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:xr,httpsAgent:Sr}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await kr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:xr,httpsAgent:Sr})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:s.role,content:n.join(`
3
- `)};return o.length>0&&(r.images=o),s.tool_call_id&&(r.tool_call_id=s.tool_call_id),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=Pn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1,extra:{repeat_penalty:n.repeat_penalty}}),l;try{l=await kr.post(`${this.baseUrl}${Pn.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:xr,httpsAgent:Sr})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=c.response?.data?.error||c.message;throw new Error(`API Error${u}: ${d}`)}return Pn.normalizeResponse(l.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),l=n.onThinkingToken||(()=>{}),c=Pn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0,extra:{repeat_penalty:n.repeat_penalty}}),u;try{u=await kr.post(`${this.baseUrl}${Pn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:xr,httpsAgent:Sr})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await zy(f,_=>_?.error),g=new Error(`API Error${p}: ${m}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=Pn.createStreamParser(a,{onThinkingToken:l});return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{if(n.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,p(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Pn.normalizeResponse(e)}};mu.exports={OllamaProvider:ha,OLLAMA_MODELS:pu}});var $u=Z((jT,_u)=>{var yu=require("axios"),{BaseProvider:Ky,readStreamErrorBody:Xy}=_s(),{openaiProtocol:Ln}=ks(),wu={"gpt-4o":{id:"gpt-4o",name:"GPT-4o",maxTokens:16384,contextWindow:128e3},"gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4o Mini",maxTokens:16384,contextWindow:128e3},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",maxTokens:32768,contextWindow:128e3},"gpt-4.1-mini":{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",maxTokens:32768,contextWindow:128e3},"gpt-4.1-nano":{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",maxTokens:16384,contextWindow:128e3},o1:{id:"o1",name:"o1",maxTokens:1e5,contextWindow:2e5},o3:{id:"o3",name:"o3",maxTokens:1e5,contextWindow:2e5},"o3-mini":{id:"o3-mini",name:"o3 Mini",maxTokens:65536,contextWindow:2e5},"o4-mini":{id:"o4-mini",name:"o4 Mini",maxTokens:1e5,contextWindow:2e5}},pa=class extends Ky{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||wu,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool"){let s;return Array.isArray(e.content)?s=e.content.filter(o=>o.type==="text").map(o=>o.text).join(`
4
- `)||JSON.stringify(e.content):s=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:s,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),l=Ln.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await yu.post(`${this.baseUrl}${Ln.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Ln.normalizeResponse(c.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=Ln.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await yu.post(`${this.baseUrl}${Ln.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await Xy(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Ln.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{n.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Ln.normalizeResponse(e)}};_u.exports={OpenAIProvider:pa,OPENAI_MODELS:wu}});var Su=Z((qT,xu)=>{var bu=require("axios"),{BaseProvider:Vy,readStreamErrorBody:Jy}=_s(),{anthropicProtocol:yn}=ks(),ku={"claude-sonnet":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",maxTokens:64e3,contextWindow:2e5},"claude-opus":{id:"claude-opus-4-6",name:"Claude Opus 4.6",maxTokens:128e3,contextWindow:2e5},"claude-haiku":{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4-5":{id:"claude-sonnet-4-5-20250929",name:"Claude Sonnet 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4":{id:"claude-sonnet-4-20250514",name:"Claude Sonnet 4",maxTokens:64e3,contextWindow:2e5}},Zy="2023-06-01",ma=class extends Vy{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||ku,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Zy}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
5
-
6
- `:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}for(let o=n.length-1;o>0;o--)n[o].role==="user"&&n[o-1].role==="user"&&n.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});o=i}else o=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:o};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return yn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,{messages:l,system:c}=this.formatMessages(e),u=this.formatTools(s),d=yn.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await bu.post(`${this.baseUrl}${yn.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",g=p.response?.data?.error?.message||p.response?.data?.error||p.message;throw new Error(`API Error${m}: ${g}`)}return yn.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(s),f=yn.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await bu.post(`${this.baseUrl}${yn.getEndpoint()}`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let _=g.response?.status?` [HTTP ${g.response.status}]`:"",k=await Jy(g,A=>A?.error?.message||A?.error);throw new Error(`API Error${_}: ${k}`)}let m=yn.createStreamParser(l);return new Promise((g,_)=>{n.signal&&n.signal.addEventListener("abort",()=>{p.data.destroy(),_(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",k=>{let{done:A,result:L}=m.feed(k.toString());A&&g(L)}),p.data.on("error",k=>{n.signal?.aborted||_(new Error(`Stream error: ${k.message}`))}),p.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return yn.normalizeResponse(e)}};xu.exports={AnthropicProvider:ma,ANTHROPIC_MODELS:ku}});var Ru=Z((FT,Tu)=>{var Eu=require("axios"),{BaseProvider:Qy,readStreamErrorBody:e0}=_s(),{openaiProtocol:In}=ks(),vu={"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",maxTokens:65536,contextWindow:1048576},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:65536,contextWindow:1048576},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",maxTokens:65536,contextWindow:1048576},"gemini-2.0-flash":{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash",maxTokens:8192,contextWindow:1048576},"gemini-2.0-flash-lite":{id:"gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite",maxTokens:8192,contextWindow:1048576},"gemini-1.5-pro":{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",maxTokens:8192,contextWindow:1048576},"gemini-1.5-flash":{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",maxTokens:8192,contextWindow:1048576}},ga=class extends Qy{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||vu,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),l=In.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await Eu.post(`${this.baseUrl}${In.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return In.normalizeResponse(c.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,a=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=In.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Eu.post(`${this.baseUrl}${In.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await e0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=In.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{n.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return In.normalizeResponse(e)}};Tu.exports={GeminiProvider:ga,GEMINI_MODELS:vu}});var Ou=Z((BT,Au)=>{var Er=require("axios"),{BaseProvider:t0,readStreamErrorBody:n0}=_s(),{ollamaProtocol:Dn}=ks(),Cu="http://localhost:11434",ya=class extends t0{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Cu,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Er.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await Er.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=a.data?.model_info||a.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
7
- `)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=Dn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await Er.post(`${this.baseUrl}${Dn.getEndpoint()}`,r,{timeout:n.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let l=a.response?.status?` [HTTP ${a.response.status}]`:"",c=a.response?.data?.error||a.message;throw new Error(`API Error${l}: ${c}`)}return Dn.normalizeResponse(i.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),i=Dn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await Er.post(`${this.baseUrl}${Dn.getEndpoint()}`,i,{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=await n0(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=Dn.createStreamParser(r);return new Promise((c,u)=>{n.signal&&n.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:p}=l.feed(d.toString());f&&c(p)}),a.data.on("error",d=>{n.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{c(l.flush())})})}normalizeResponse(e){return Dn.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}};Au.exports={LocalProvider:ya,DEFAULT_LOCAL_URL:Cu}});var Ft=Z((UT,ju)=>{"use strict";var Nu="\x1B[0m",Mu="\x1B[1m",xs="\x1B[2m";function G(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function s0(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
8
- `),o=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(o){let r=parseInt(o[1].slice(0,2),16),i=parseInt(o[2].slice(0,2),16),a=parseInt(o[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function Pu(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function o0(t){try{let s=require("fs").readFileSync(Pu(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch{}return null}function r0(t,e){try{let s=require("fs"),n=require("path"),o=Pu(),r=n.dirname(o),i={};try{i=JSON.parse(s.readFileSync(o,"utf8"))}catch(l){console.error("theme cache failed:",l.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function i0(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let s=process.env.TERM_SESSION_ID||"default",n=o0(s);if(n!==null)return n;let o=s0(),r=o!==null?o:!0;return r0(s,r),r}var Lu=i0(),Iu={reset:Nu,bold:Mu,dim:xs,primary:G(80,190,255),secondary:G(60,170,190),success:G(80,210,120),warning:G(245,175,50),error:G(230,80,80),muted:xs,subtle:G(130,130,145),tool_read:G(80,190,255),tool_write:G(245,165,55),tool_exec:G(185,100,235),tool_search:G(70,185,190),tool_git:G(90,210,100),tool_web:G(100,215,250),tool_sysadmin:G(225,150,75),tool_default:G(100,205,115),syn_keyword:G(185,100,235),syn_string:G(90,210,120),syn_number:G(245,175,50),syn_comment:xs,syn_key:G(80,190,255),diff_add:G(80,210,120),diff_rem:G(230,80,80),banner_logo:G(80,200,255),banner_name:G(80,200,255),banner_version:xs,banner_model:xs,banner_yolo:G(245,175,50),banner_gemini:G(138,180,248),footer_sep:xs,footer_model:G(80,175,235),footer_branch:G(80,210,100),footer_project:G(130,130,145),footer_divider:G(80,80,95),footer_mode:G(210,150,50),white:G(210,210,220),red:G(220,85,85),green:G(80,200,110),yellow:G(230,185,60),blue:G(70,140,230),magenta:G(200,120,190),cyan:G(90,200,215),gray:G(120,120,135),bgRed:"\x1B[48;2;140;40;40m",bgGreen:"\x1B[48;2;30;100;50m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:G(110,215,230),brightMagenta:G(220,140,210),brightBlue:G(100,160,240)},Du={reset:Nu,bold:Mu,dim:G(110,110,120),primary:G(0,110,190),secondary:G(0,125,148),success:G(0,148,62),warning:G(168,92,0),error:G(188,32,32),muted:G(110,110,120),subtle:G(155,155,165),tool_read:G(0,110,190),tool_write:G(168,92,0),tool_exec:G(128,42,188),tool_search:G(0,122,148),tool_git:G(0,138,62),tool_web:G(0,112,178),tool_sysadmin:G(168,82,0),tool_default:G(0,138,62),syn_keyword:G(128,42,188),syn_string:G(0,138,62),syn_number:G(168,92,0),syn_comment:G(135,135,148),syn_key:G(0,110,190),diff_add:G(0,148,62),diff_rem:G(188,32,32),banner_logo:G(0,122,205),banner_name:G(0,122,205),banner_version:G(100,100,118),banner_model:G(100,100,118),banner_yolo:G(168,62,0),banner_gemini:G(26,115,232),footer_sep:G(168,168,178),footer_model:G(0,102,175),footer_branch:G(0,138,62),footer_project:G(135,135,148),footer_divider:G(168,168,178),footer_mode:G(148,88,0),white:G(40,40,52),red:G(188,32,32),green:G(0,148,62),yellow:G(168,92,0),blue:G(0,110,190),magenta:G(128,42,188),cyan:G(0,125,148),gray:G(132,132,142),bgRed:"\x1B[48;2;180;50;50m",bgGreen:"\x1B[48;2;30;130;60m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:G(0,158,182),brightMagenta:G(158,52,208),brightBlue:G(0,112,208)},a0=Lu?Iu:Du;ju.exports={T:a0,isDark:Lu,DARK:Iu,LIGHT:Du}});var jn=Z((WT,Fu)=>{"use strict";var bt=require("fs"),qu=require("path");function l0(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function c0(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function u0(t,e){let s=qu.dirname(t),n=qu.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{bt.existsSync(s)||bt.mkdirSync(s,{recursive:!0,mode:448}),bt.writeFileSync(n,e,{encoding:"utf-8",mode:384}),bt.renameSync(n,t)}catch(o){try{bt.unlinkSync(n)}catch{}throw o}}function d0(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=bt.openSync(o,"wx"),bt.writeSync(i,Buffer.from(String(process.pid))),bt.closeSync(i),i=-1;try{return e()}finally{try{bt.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{bt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=bt.readFileSync(o,"utf-8").trim(),c=parseInt(l,10);if(!l0(c)){try{bt.unlinkSync(o)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{bt.unlinkSync(o)}catch{}return e()}c0(n)}}}Fu.exports={atomicWrite:u0,withFileLockSync:d0}});var Tr=Z((HT,Ku)=>{var Ss=require("fs"),wa=require("path"),{T:Bu}=Ft(),{atomicWrite:f0,withFileLockSync:h0}=jn(),Uu={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},vr=[],wn={};function p0(t,e,s,n,o=0){if(vr.push({provider:t,model:e,input:s,output:n,cacheRead:o}),wn[t]!==void 0){let r=Gu(t);r.allowed||process.stderr.write(`${Bu.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${Bu.reset}
9
- `)}}function _a(t,e){let s=Uu[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Wu(t){let e=_a(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Hu(){let t={};for(let i of vr){let a=`${i.provider}:${i.model}`;t[a]||(t[a]={provider:i.provider,model:i.model,requests:0,input:0,output:0,cacheRead:0}),t[a].requests++,t[a].input+=i.input,t[a].output+=i.output,t[a].cacheRead+=i.cacheRead||0}let e=Object.values(t).map(i=>({...i,cost:Wu(i)})),s=e.reduce((i,a)=>i+a.cost,0),n=e.reduce((i,a)=>i+a.input,0),o=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:s,totalInput:n,totalOutput:o,totalCacheRead:r,breakdown:e}}function m0(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Hu();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
10
- `)}function g0(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function y0(t,e,s,n){let o=_a(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function w0(){vr=[]}function _0(t,e){wn[t]=e}function $0(t){delete wn[t]}function b0(){return{...wn}}function Yu(t){let e=0;for(let s of vr)s.provider===t&&(e+=Wu(s));return e}function Gu(t){let e=Yu(t),s=wn[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:n}}function zu(){let t=wa.join(process.cwd(),".nex","config.json");if(Ss.existsSync(t))try{let e=JSON.parse(Ss.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(wn={...e.costLimits})}catch{}}function k0(){let t=wa.join(process.cwd(),".nex"),e=wa.join(t,"config.json");Ss.existsSync(t)||Ss.mkdirSync(t,{recursive:!0}),h0(e,()=>{let s={};if(Ss.existsSync(e))try{s=JSON.parse(Ss.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=wn,f0(e,JSON.stringify(s,null,2))})}function x0(){wn={}}zu();Ku.exports={PRICING:Uu,trackUsage:p0,getSessionCosts:Hu,formatCosts:m0,formatCostHint:y0,resetCosts:w0,getPricing:_a,setCostLimit:_0,removeCostLimit:$0,getCostLimits:b0,getProviderSpend:Yu,checkBudget:Gu,loadCostLimits:zu,saveCostLimits:k0,resetCostLimits:x0,estimateTokens:g0}});var $a=Z((YT,S0)=>{S0.exports={name:"nex-code",version:"0.5.9",description:"Run 400B+ open coding models on your codebase without the hardware bill. Ollama Cloud first \u2014 OpenAI, Anthropic, and Gemini when you need them.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","examples/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --forceExit --maxWorkers=50%","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",format:"prettier --write .","install-hooks":"ln -sf ../../hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-commit, pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0",prettier:"^3.8.1",typescript:"^5.9.3"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var vs=Z((GT,Vu)=>{var{T:se}=Ft(),Ar=5,Es=(()=>{let t=[];for(let e=0;e<Ar;e++)t.push(e);for(let e=Ar-2;e>=1;e--)t.push(e);return t})(),Xu=["\u273D","\u2726","\u2727","\u2726"],ba=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Es[this.frame%Es.length],s="";for(let o=0;o<Ar;o++)s+=o===e?`${se.cyan}\u25CF${se.reset}`:" ";let n="";if(this.startTime){let o=Math.floor((Date.now()-this.startTime)/1e3);if(o>=60){let r=Math.floor(o/60),i=o%60;n=` ${se.dim}${r}m ${String(i).padStart(2,"0")}s${se.reset}`}else o>=1&&(n=` ${se.dim}${o}s${se.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${se.dim}${this.text}${se.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},ka=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=Es[this.frame%Es.length],s=`${se.cyan}\u25CF${se.reset}`,n=this._formatElapsed(),o=n?` ${se.dim}${n}${se.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let l,c;switch(this.statuses[a]){case"done":l=`${se.green}\u2713${se.reset}`,c=se.dim;break;case"error":l=`${se.red}\u2717${se.reset}`,c=se.dim;break;case"retry":l=`${se.yellow}\u21BB${se.reset}`,c=se.yellow;break;default:l=a===e?s:" ",c=""}let u=a===this.labels.length-1?o:"",d=r-4-(u?n.length+1:0),f=this.labels[a].length>d?this.labels[a].substring(0,Math.max(10,d-3))+"...":this.labels[a];i+=`\x1B[2K ${l} ${c}${f}${se.reset}${u}
1
+ var $a=Object.defineProperty;var c0=Object.getOwnPropertyDescriptor;var u0=Object.getOwnPropertyNames;var d0=Object.prototype.hasOwnProperty;var f0=(t,e)=>()=>(t&&(e=t(t=0)),e);var V=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),p0=(t,e)=>{for(var s in e)$a(t,s,{get:e[s],enumerable:!0})},h0=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of u0(e))!d0.call(t,o)&&o!==s&&$a(t,o,{get:()=>e[o],enumerable:!(n=c0(e,o))||n.enumerable});return t};var m0=t=>h0($a({},"__esModule",{value:!0}),t);var Ss=V((IR,vu)=>{async function g0(t,e){if(!t.response?.data)return t.message;let s=t.response.data;if(typeof s=="object"&&s!==null&&typeof s.pipe!="function")return e(s)||t.message;try{let n=await new Promise((r,i)=>{let a=[];s.on("data",l=>a.push(l)),s.on("end",()=>r(Buffer.concat(a).toString("utf8"))),s.on("error",i)}),o=JSON.parse(n);return e(o)||n||t.message}catch{return t.message}}var _a=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,n={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};vu.exports={BaseProvider:_a,readStreamErrorBody:g0}});var Ts=V((jR,Ru)=>{var Es=class{buildRequestBody(e){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(e){return e}normalizeResponse(e){throw new Error("normalizeResponse() not implemented")}createStreamParser(e,s={}){throw new Error("createStreamParser() not implemented")}},vs=class{constructor(e,s={}){this.onToken=e,this.callbacks=s,this.content="",this.buffer=""}feed(e){this.buffer+=e;let s=this.buffer.split(`
2
+ `);this.buffer=s.pop()||"";for(let n of s){let o=this.parseLine(n);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},xr=class extends vs{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Sr=class extends Es{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:s,max_tokens:o,temperature:r};return i&&(a.stream=!0),n&&n.length>0&&(a.tools=n),a}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}createStreamParser(e,s={}){return new xr(e,s)}},Er=class extends vs{constructor(e,s={}){super(e,s),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let s=e.trim();if(!s.startsWith("data: "))return{done:!1};let n=s.slice(6),o;try{o=JSON.parse(n)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let s={};if(e.inputJson)try{s=JSON.parse(e.inputJson)}catch{s=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:s}}})}}},ba="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",vr=class extends Es{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,max_tokens:o,temperature:r};if(i&&(l.stream=!0),a?.system){let c=a.system,u=c.indexOf(ba);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+ba.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=c}return n&&n.length>0&&(l.tools=n),l}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}createStreamParser(e,s={}){return new Er(e,s)}};function Tu(t){if(t!==null&&typeof t=="object")return t;if(typeof t!="string")return t||{};try{return JSON.parse(t)}catch{}let e=t.replace(/,\s*([}\]])/g,"$1");e=e.replace(/([^\\])\n/g,"$1\\n");try{return JSON.parse(e)}catch{}return{}}var Tr=class extends vs{constructor(e,s={}){super(e,s),this.toolCalls=[],this.onThinkingToken=s.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let s;try{s=JSON.parse(e)}catch{return{done:!1}}return s.message?.thinking&&this.onThinkingToken(s.message.thinking),s.message?.content&&(this.onToken(s.message.content),this.content+=s.message.content),s.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(s.message.tool_calls)),s.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,s)=>({id:e.id||`ollama-${Date.now()}-${s}`,function:{name:e.function?.name||e.name||"unknown",arguments:Tu(e.function?.arguments??e.arguments)}}))}}},Rr=class extends Es{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(l.tools=n),l}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:(s.tool_calls||[]).map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:Tu(n.function?.arguments??n.arguments)}}))}}createStreamParser(e,s={}){return new Tr(e,s)}},y0=new Sr,w0=new vr,$0=new Rr;Ru.exports={ANTHROPIC_CACHE_BOUNDARY:ba,WireProtocol:Es,StreamParser:vs,OpenAICompatibleProtocol:Sr,AnthropicProtocol:vr,OllamaChatProtocol:Rr,OpenAIStreamParser:xr,AnthropicStreamParser:Er,OllamaStreamParser:Tr,openaiProtocol:y0,anthropicProtocol:w0,ollamaProtocol:$0}});var Ou=V((DR,Au)=>{var Cr=require("axios"),_0=require("http"),b0=require("https"),{BaseProvider:k0,readStreamErrorBody:x0}=Ss(),{ollamaProtocol:Fn}=Ts(),Ar=new _0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Or=new b0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Cu={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemma4:e2b":{id:"gemma4:e2b",name:"Gemma 4 E2B",maxTokens:8192,contextWindow:131072},"gemma4:e4b":{id:"gemma4:e4b",name:"Gemma 4 E4B",maxTokens:8192,contextWindow:131072},"gemma4:26b-a4b":{id:"gemma4:26b-a4b",name:"Gemma 4 26B A4B",maxTokens:16384,contextWindow:262144},"gemma4:31b":{id:"gemma4:31b",name:"Gemma 4 31B",maxTokens:16384,contextWindow:262144},"gemma4:31b-cloud":{id:"gemma4:31b-cloud",name:"Gemma 4 31B Cloud",maxTokens:16384,contextWindow:262144},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},ka=class extends k0{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Cu,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){Cr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ar,httpsAgent:Or}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Cr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ar,httpsAgent:Or})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:s.role,content:n.join(`
3
+ `)};return o.length>0&&(r.images=o),s.tool_call_id&&(r.tool_call_id=s.tool_call_id),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=Fn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1,extra:{repeat_penalty:n.repeat_penalty}}),l;try{l=await Cr.post(`${this.baseUrl}${Fn.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Ar,httpsAgent:Or})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=c.response?.data?.error||c.message;throw new Error(`API Error${u}: ${d}`)}return Fn.normalizeResponse(l.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),l=n.onThinkingToken||(()=>{}),c=Fn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0,extra:{repeat_penalty:n.repeat_penalty}}),u;try{u=await Cr.post(`${this.baseUrl}${Fn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Ar,httpsAgent:Or})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await x0(f,$=>$?.error),g=new Error(`API Error${p}: ${m}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=Fn.createStreamParser(a,{onThinkingToken:l});return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),u.data.on("error",m=>{if(n.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,p(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Fn.normalizeResponse(e)}};Au.exports={OllamaProvider:ka,OLLAMA_MODELS:Cu}});var Lu=V((qR,Pu)=>{var Nu=require("axios"),{BaseProvider:S0,readStreamErrorBody:E0}=Ss(),{openaiProtocol:Bn}=Ts(),Mu={"gpt-4o":{id:"gpt-4o",name:"GPT-4o",maxTokens:16384,contextWindow:128e3},"gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4o Mini",maxTokens:16384,contextWindow:128e3},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",maxTokens:32768,contextWindow:128e3},"gpt-4.1-mini":{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",maxTokens:32768,contextWindow:128e3},"gpt-4.1-nano":{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",maxTokens:16384,contextWindow:128e3},o1:{id:"o1",name:"o1",maxTokens:1e5,contextWindow:2e5},o3:{id:"o3",name:"o3",maxTokens:1e5,contextWindow:2e5},"o3-mini":{id:"o3-mini",name:"o3 Mini",maxTokens:65536,contextWindow:2e5},"o4-mini":{id:"o4-mini",name:"o4 Mini",maxTokens:1e5,contextWindow:2e5}},xa=class extends S0{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Mu,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool"){let s;return Array.isArray(e.content)?s=e.content.filter(o=>o.type==="text").map(o=>o.text).join(`
4
+ `)||JSON.stringify(e.content):s=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:s,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),l=Bn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await Nu.post(`${this.baseUrl}${Bn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Bn.normalizeResponse(c.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=Bn.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Nu.post(`${this.baseUrl}${Bn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await E0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Bn.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),u.data.on("error",m=>{n.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Bn.normalizeResponse(e)}};Pu.exports={OpenAIProvider:xa,OPENAI_MODELS:Mu}});var qu=V((FR,Du)=>{var Iu=require("axios"),{BaseProvider:v0,readStreamErrorBody:T0}=Ss(),{anthropicProtocol:En}=Ts(),ju={"claude-sonnet":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",maxTokens:64e3,contextWindow:2e5},"claude-opus":{id:"claude-opus-4-6",name:"Claude Opus 4.6",maxTokens:128e3,contextWindow:2e5},"claude-haiku":{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4-5":{id:"claude-sonnet-4-5-20250929",name:"Claude Sonnet 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4":{id:"claude-sonnet-4-20250514",name:"Claude Sonnet 4",maxTokens:64e3,contextWindow:2e5}},R0="2023-06-01",Sa=class extends v0{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||ju,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||R0}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
5
+
6
+ `:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}for(let o=n.length-1;o>0;o--)n[o].role==="user"&&n[o-1].role==="user"&&n.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});o=i}else o=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:o};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return En.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,{messages:l,system:c}=this.formatMessages(e),u=this.formatTools(s),d=En.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Iu.post(`${this.baseUrl}${En.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",g=p.response?.data?.error?.message||p.response?.data?.error||p.message;throw new Error(`API Error${m}: ${g}`)}return En.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(s),f=En.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await Iu.post(`${this.baseUrl}${En.getEndpoint()}`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let $=g.response?.status?` [HTTP ${g.response.status}]`:"",k=await T0(g,M=>M?.error?.message||M?.error);throw new Error(`API Error${$}: ${k}`)}let m=En.createStreamParser(l);return new Promise((g,$)=>{n.signal&&n.signal.addEventListener("abort",()=>{p.data.destroy(),$(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",k=>{let{done:M,result:D}=m.feed(k.toString());M&&g(D)}),p.data.on("error",k=>{n.signal?.aborted||$(new Error(`Stream error: ${k.message}`))}),p.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return En.normalizeResponse(e)}};Du.exports={AnthropicProvider:Sa,ANTHROPIC_MODELS:ju}});var Wu=V((BR,Uu)=>{var Fu=require("axios"),{BaseProvider:C0,readStreamErrorBody:A0}=Ss(),{openaiProtocol:Un}=Ts(),Bu={"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",maxTokens:65536,contextWindow:1048576},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:65536,contextWindow:1048576},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",maxTokens:65536,contextWindow:1048576},"gemini-2.0-flash":{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash",maxTokens:8192,contextWindow:1048576},"gemini-2.0-flash-lite":{id:"gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite",maxTokens:8192,contextWindow:1048576},"gemini-1.5-pro":{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",maxTokens:8192,contextWindow:1048576},"gemini-1.5-flash":{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",maxTokens:8192,contextWindow:1048576}},Ea=class extends C0{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Bu,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),l=Un.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await Fu.post(`${this.baseUrl}${Un.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Un.normalizeResponse(c.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,a=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=Un.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Fu.post(`${this.baseUrl}${Un.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await A0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Un.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),u.data.on("error",m=>{n.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Un.normalizeResponse(e)}};Uu.exports={GeminiProvider:Ea,GEMINI_MODELS:Bu}});var Gu=V((UR,Yu)=>{var Nr=require("axios"),{BaseProvider:O0,readStreamErrorBody:N0}=Ss(),{ollamaProtocol:Wn}=Ts(),Hu="http://localhost:11434",va=class extends O0{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Hu,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Nr.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await Nr.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=a.data?.model_info||a.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
7
+ `)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=Wn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await Nr.post(`${this.baseUrl}${Wn.getEndpoint()}`,r,{timeout:n.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let l=a.response?.status?` [HTTP ${a.response.status}]`:"",c=a.response?.data?.error||a.message;throw new Error(`API Error${l}: ${c}`)}return Wn.normalizeResponse(i.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),i=Wn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await Nr.post(`${this.baseUrl}${Wn.getEndpoint()}`,i,{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=await N0(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=Wn.createStreamParser(r);return new Promise((c,u)=>{n.signal&&n.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:p}=l.feed(d.toString());f&&c(p)}),a.data.on("error",d=>{n.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{c(l.flush())})})}normalizeResponse(e){return Wn.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}};Yu.exports={LocalProvider:va,DEFAULT_LOCAL_URL:Hu}});var Ht=V((WR,Qu)=>{"use strict";var zu="\x1B[0m",Ku="\x1B[1m",Rs="\x1B[2m";function Y(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function M0(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
8
+ `),o=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(o){let r=parseInt(o[1].slice(0,2),16),i=parseInt(o[2].slice(0,2),16),a=parseInt(o[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function Xu(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function P0(t){try{let s=require("fs").readFileSync(Xu(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch(e){console.error("readThemeCache failed:",e.message)}return null}function L0(t,e){try{let s=require("fs"),n=require("path"),o=Xu(),r=n.dirname(o),i={};try{i=JSON.parse(s.readFileSync(o,"utf8"))}catch(l){console.error("theme cache failed:",l.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function I0(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let s=process.env.TERM_SESSION_ID||"default",n=P0(s);if(n!==null)return n;let o=M0(),r=o!==null?o:!0;return L0(s,r),r}var Vu=I0(),Ju={reset:zu,bold:Ku,dim:Rs,primary:Y(80,190,255),secondary:Y(60,170,190),success:Y(80,210,120),warning:Y(245,175,50),error:Y(230,80,80),muted:Rs,subtle:Y(130,130,145),tool_read:Y(80,190,255),tool_write:Y(245,165,55),tool_exec:Y(185,100,235),tool_search:Y(70,185,190),tool_git:Y(90,210,100),tool_web:Y(100,215,250),tool_sysadmin:Y(225,150,75),tool_default:Y(100,205,115),syn_keyword:Y(185,100,235),syn_string:Y(90,210,120),syn_number:Y(245,175,50),syn_comment:Rs,syn_key:Y(80,190,255),diff_add:Y(80,210,120),diff_rem:Y(230,80,80),banner_logo:Y(80,200,255),banner_name:Y(80,200,255),banner_version:Rs,banner_model:Rs,banner_yolo:Y(245,175,50),banner_gemini:Y(138,180,248),footer_sep:Rs,footer_model:Y(80,175,235),footer_branch:Y(80,210,100),footer_project:Y(130,130,145),footer_divider:Y(80,80,95),footer_mode:Y(210,150,50),white:Y(210,210,220),red:Y(220,85,85),green:Y(80,200,110),yellow:Y(230,185,60),blue:Y(70,140,230),magenta:Y(200,120,190),cyan:Y(90,200,215),gray:Y(120,120,135),bgRed:"\x1B[48;2;140;40;40m",bgGreen:"\x1B[48;2;30;100;50m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:Y(110,215,230),brightMagenta:Y(220,140,210),brightBlue:Y(100,160,240)},Zu={reset:zu,bold:Ku,dim:Y(110,110,120),primary:Y(0,110,190),secondary:Y(0,125,148),success:Y(0,148,62),warning:Y(168,92,0),error:Y(188,32,32),muted:Y(110,110,120),subtle:Y(155,155,165),tool_read:Y(0,110,190),tool_write:Y(168,92,0),tool_exec:Y(128,42,188),tool_search:Y(0,122,148),tool_git:Y(0,138,62),tool_web:Y(0,112,178),tool_sysadmin:Y(168,82,0),tool_default:Y(0,138,62),syn_keyword:Y(128,42,188),syn_string:Y(0,138,62),syn_number:Y(168,92,0),syn_comment:Y(135,135,148),syn_key:Y(0,110,190),diff_add:Y(0,148,62),diff_rem:Y(188,32,32),banner_logo:Y(0,122,205),banner_name:Y(0,122,205),banner_version:Y(100,100,118),banner_model:Y(100,100,118),banner_yolo:Y(168,62,0),banner_gemini:Y(26,115,232),footer_sep:Y(168,168,178),footer_model:Y(0,102,175),footer_branch:Y(0,138,62),footer_project:Y(135,135,148),footer_divider:Y(168,168,178),footer_mode:Y(148,88,0),white:Y(40,40,52),red:Y(188,32,32),green:Y(0,148,62),yellow:Y(168,92,0),blue:Y(0,110,190),magenta:Y(128,42,188),cyan:Y(0,125,148),gray:Y(132,132,142),bgRed:"\x1B[48;2;180;50;50m",bgGreen:"\x1B[48;2;30;130;60m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:Y(0,158,182),brightMagenta:Y(158,52,208),brightBlue:Y(0,112,208)},j0=Vu?Ju:Zu;Qu.exports={T:j0,isDark:Vu,DARK:Ju,LIGHT:Zu}});var Hn=V((HR,td)=>{"use strict";var St=require("fs"),ed=require("path");function D0(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function q0(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function F0(t,e){let s=ed.dirname(t),n=ed.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{St.existsSync(s)||St.mkdirSync(s,{recursive:!0,mode:448}),St.writeFileSync(n,e,{encoding:"utf-8",mode:384}),St.renameSync(n,t)}catch(o){try{St.unlinkSync(n)}catch{}throw o}}function B0(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=St.openSync(o,"wx"),St.writeSync(i,Buffer.from(String(process.pid))),St.closeSync(i),i=-1;try{return e()}finally{try{St.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{St.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=St.readFileSync(o,"utf-8").trim(),c=parseInt(l,10);if(!D0(c)){try{St.unlinkSync(o)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{St.unlinkSync(o)}catch{}return e()}q0(n)}}}td.exports={atomicWrite:F0,withFileLockSync:B0}});var Pr=V((YR,cd)=>{var Cs=require("fs"),Ta=require("path"),{T:nd}=Ht(),{atomicWrite:U0,withFileLockSync:W0}=Hn(),sd={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},Mr=[],vn={};function H0(t,e,s,n,o=0){if(Mr.push({provider:t,model:e,input:s,output:n,cacheRead:o}),vn[t]!==void 0){let r=ad(t);r.allowed||process.stderr.write(`${nd.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${nd.reset}
9
+ `)}}function Ra(t,e){let s=sd[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function od(t){let e=Ra(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function rd(){let t={};for(let i of Mr){let a=`${i.provider}:${i.model}`;t[a]||(t[a]={provider:i.provider,model:i.model,requests:0,input:0,output:0,cacheRead:0}),t[a].requests++,t[a].input+=i.input,t[a].output+=i.output,t[a].cacheRead+=i.cacheRead||0}let e=Object.values(t).map(i=>({...i,cost:od(i)})),s=e.reduce((i,a)=>i+a.cost,0),n=e.reduce((i,a)=>i+a.input,0),o=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:s,totalInput:n,totalOutput:o,totalCacheRead:r,breakdown:e}}function Y0(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=rd();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
10
+ `)}function G0(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function z0(t,e,s,n){let o=Ra(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function K0(){Mr=[]}function X0(t,e){vn[t]=e}function V0(t){delete vn[t]}function J0(){return{...vn}}function id(t){let e=0;for(let s of Mr)s.provider===t&&(e+=od(s));return e}function ad(t){let e=id(t),s=vn[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:n}}function ld(){let t=Ta.join(process.cwd(),".nex","config.json");if(Cs.existsSync(t))try{let e=JSON.parse(Cs.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(vn={...e.costLimits})}catch{}}function Z0(){let t=Ta.join(process.cwd(),".nex"),e=Ta.join(t,"config.json");Cs.existsSync(t)||Cs.mkdirSync(t,{recursive:!0}),W0(e,()=>{let s={};if(Cs.existsSync(e))try{s=JSON.parse(Cs.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=vn,U0(e,JSON.stringify(s,null,2))})}function Q0(){vn={}}ld();cd.exports={PRICING:sd,trackUsage:H0,getSessionCosts:rd,formatCosts:Y0,formatCostHint:z0,resetCosts:K0,getPricing:Ra,setCostLimit:X0,removeCostLimit:V0,getCostLimits:J0,getProviderSpend:id,checkBudget:ad,loadCostLimits:ld,saveCostLimits:Z0,resetCostLimits:Q0,estimateTokens:G0}});var Ca=V((GR,ew)=>{ew.exports={name:"nex-code",version:"0.5.11",description:"Run 400B+ open coding models on your codebase without the hardware bill. Ollama Cloud first \u2014 OpenAI, Anthropic, and Gemini when you need them.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","examples/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --forceExit --maxWorkers=50%","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",format:"prettier --write .","install-hooks":"ln -sf ../../hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-commit, pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0",prettier:"^3.8.1",typescript:"^5.9.3"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var Os=V((zR,dd)=>{var{T:ne}=Ht(),jr=5,As=(()=>{let t=[];for(let e=0;e<jr;e++)t.push(e);for(let e=jr-2;e>=1;e--)t.push(e);return t})(),ud=["\u273D","\u2726","\u2727","\u2726"],Aa=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=As[this.frame%As.length],s="";for(let o=0;o<jr;o++)s+=o===e?`${ne.cyan}\u25CF${ne.reset}`:" ";let n="";if(this.startTime){let o=Math.floor((Date.now()-this.startTime)/1e3);if(o>=60){let r=Math.floor(o/60),i=o%60;n=` ${ne.dim}${r}m ${String(i).padStart(2,"0")}s${ne.reset}`}else o>=1&&(n=` ${ne.dim}${o}s${ne.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${ne.dim}${this.text}${ne.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},Oa=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=As[this.frame%As.length],s=`${ne.cyan}\u25CF${ne.reset}`,n=this._formatElapsed(),o=n?` ${ne.dim}${n}${ne.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let l,c;switch(this.statuses[a]){case"done":l=`${ne.green}\u2713${ne.reset}`,c=ne.dim;break;case"error":l=`${ne.red}\u2717${ne.reset}`,c=ne.dim;break;case"retry":l=`${ne.yellow}\u21BB${ne.reset}`,c=ne.yellow;break;default:l=a===e?s:" ",c=""}let u=a===this.labels.length-1?o:"",d=r-4-(u?n.length+1:0),f=this.labels[a].length>d?this.labels[a].substring(0,Math.max(10,d-3))+"...":this.labels[a];i+=`\x1B[2K ${l} ${c}${f}${ne.reset}${u}
11
11
  `}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
12
12
  `;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let s="";for(let n=0;n<this.lineCount;n++)s+=`\x1B[2K
13
- `;this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${se.dim}${e}${se.reset}`:"",n=process.stderr.columns||80,o="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${se.green}\u2713${se.reset}`;break;case"error":i=`${se.red}\u2717${se.reset}`;break;case"retry":i=`${se.yellow}\u21BB${se.reset}`;break;default:i=`${se.yellow}\u25CB${se.reset}`}let a=r===this.labels.length-1?s:"",l=n-4-(a?e.length+1:0),c=this.labels[r].length>l?this.labels[r].substring(0,Math.max(10,l-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${se.dim}${c}${se.reset}${a}
14
- `}process.stderr.write(o)}},Rr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Cr={done:se.green,in_progress:se.cyan,pending:se.dim,failed:se.red},_n=null,xa=class{constructor(e,s){this.name=e,this.tasks=s.map(n=>({id:n.id,description:n.description,status:n.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=Xu[this.frame%Xu.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${se.dim}(${o})${se.reset}`:"",i=`\x1B[2K${se.cyan}${e}${se.reset} ${this.name}\u2026${r}
15
- `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":" ",u=Rr[l.status]||Rr.pending,d=Cr[l.status]||Cr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${se.dim}${c}${se.reset} ${d}${u}${se.reset} ${f}
13
+ `;this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${ne.dim}${e}${ne.reset}`:"",n=process.stderr.columns||80,o="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${ne.green}\u2713${ne.reset}`;break;case"error":i=`${ne.red}\u2717${ne.reset}`;break;case"retry":i=`${ne.yellow}\u21BB${ne.reset}`;break;default:i=`${ne.yellow}\u25CB${ne.reset}`}let a=r===this.labels.length-1?s:"",l=n-4-(a?e.length+1:0),c=this.labels[r].length>l?this.labels[r].substring(0,Math.max(10,l-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${ne.dim}${c}${ne.reset}${a}
14
+ `}process.stderr.write(o)}},Lr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Ir={done:ne.green,in_progress:ne.cyan,pending:ne.dim,failed:ne.red},Tn=null,Na=class{constructor(e,s){this.name=e,this.tasks=s.map(n=>({id:n.id,description:n.description,status:n.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=ud[this.frame%ud.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${ne.dim}(${o})${ne.reset}`:"",i=`\x1B[2K${ne.cyan}${e}${ne.reset} ${this.name}\u2026${r}
15
+ `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":" ",u=Lr[l.status]||Lr.pending,d=Ir[l.status]||Ir.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${ne.dim}${c}${ne.reset} ${d}${u}${ne.reset} ${f}
16
16
  `}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
17
- `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),_n=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,_n===this&&(_n=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
17
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Tn=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,Tn===this&&(Tn=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
18
18
  `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
19
- `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(a=>a.status==="done").length,n=this.tasks.filter(a=>a.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${se.green}\u2714${se.reset} ${this.name} ${se.dim}(${e} \xB7 ${r})${se.reset}
20
- `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":" ",u=Rr[l.status]||Rr.pending,d=Cr[l.status]||Cr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${se.dim}${c}${se.reset} ${d}${u}${se.reset} ${se.dim}${f}${se.reset}
21
- `}process.stderr.write(i)}},Sa=class{constructor(e,s){this.toolName=e,this.message=s||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=Es[this.frame%Es.length],s="";for(let r=0;r<Ar;r++)s+=r===e?`${se.cyan}\u25CF${se.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${se.cyan}${this.count}${se.reset}`,this.total&&(n+=`/${this.total}`),this.detail&&(n+=` ${se.dim}${this.detail}${se.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${se.dim}${r}s${se.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${se.dim}${n}${se.reset}${o}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function E0(t){_n=t}function v0(){return _n}function T0(){_n&&(_n.stop(),_n=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Vu.exports={C:se,Spinner:ba,MultiProgress:ka,TaskProgress:xa,ToolProgress:Sa,setActiveTaskProgress:E0,getActiveTaskProgress:v0,cleanupTerminal:T0}});var Ea=Z((zT,td)=>{"use strict";var{T:qn}=Ft(),ce={kw:qn.syn_keyword,str:qn.syn_string,cmt:qn.syn_comment,num:qn.syn_number,type:qn.cyan,punct:qn.magenta,reset:qn.reset},Ju={js:new Set(["const","let","var","function","return","if","else","for","while","do","class","new","this","import","export","from","default","async","await","try","catch","finally","throw","typeof","instanceof","in","of","switch","case","break","continue","null","undefined","true","false","extends","super","static","get","set","delete","void","yield","interface","type","enum","namespace","abstract","implements","declare","module","require","readonly","keyof","infer","never","unknown","any","as","satisfies"]),py:new Set(["def","class","return","if","elif","else","for","while","with","as","import","from","pass","break","continue","try","except","finally","raise","in","not","and","or","is","lambda","yield","global","nonlocal","del","assert","True","False","None","async","await","self","cls","print","range","len","type","list","dict","set","tuple","str","int","float","bool","open","super","property","staticmethod","classmethod"]),sh:new Set(["if","then","else","elif","fi","for","while","do","done","case","esac","in","function","return","local","export","source","echo","exit","break","continue","readonly","unset","shift","trap","read"]),go:new Set(["func","return","if","else","for","range","type","struct","interface","import","package","var","const","defer","go","chan","select","case","default","break","continue","fallthrough","nil","true","false","make","new","len","cap","append","copy","delete","panic","recover","map","error","string","int","int64","int32","uint","bool","byte","rune"]),rs:new Set(["fn","let","mut","return","if","else","for","while","loop","match","use","mod","pub","struct","enum","impl","trait","where","const","static","type","move","ref","in","as","unsafe","extern","crate","self","Self","super","true","false","None","Some","Ok","Err","i32","i64","u32","u64","usize","f32","f64","bool","str","String","Vec"]),java:new Set(["class","interface","extends","implements","import","package","return","if","else","for","while","do","switch","case","break","continue","new","this","super","null","true","false","public","private","protected","static","final","abstract","void","int","long","double","float","boolean","char","byte","short","try","catch","finally","throw","throws","synchronized","volatile","transient","instanceof","enum","record"])},R0={js:"js",jsx:"js",ts:"js",tsx:"js",mjs:"js",cjs:"js",py:"py",css:"css",scss:"css",less:"css",sh:"sh",bash:"sh",zsh:"sh",go:"go",rs:"rs",java:"java",json:"json",html:"html",htm:"html",xml:"xml",md:"md"};function Qu(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return R0[e]||null}var Zu=/\x1b\[[0-9;]*m/g;function an(t,e,s){let n=t.split(Zu),o=t.match(Zu)||[],r="";for(let i=0;i<n.length;i++)r+=n[i].replace(e,s),i<o.length&&(r+=o[i]);return r}function C0(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,s=>ce.type+s+ce.reset),e=an(e,/"([^"\\]|\\.)*"/g,s=>ce.str+s+ce.reset),e=an(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,s=>ce.num+s+ce.reset),e=an(e,/\b(true|false|null)\b/g,s=>ce.kw+s+ce.reset),e}function A0(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,s=>ce.cmt+s+ce.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(s,n,o)=>n+ce.type+o+ce.reset),e=an(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(s,n)=>" "+ce.kw+n+ce.reset+"="),e=an(e,/"([^"]*)"/g,s=>ce.str+s+ce.reset),e}function O0(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,s=>ce.cmt+s+ce.reset),e=an(e,/#[0-9a-fA-F]{3,8}\b/g,s=>ce.num+s+ce.reset),e=an(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(s,n,o)=>ce.num+n+ce.reset+o),e=an(e,/([a-z][a-z-]*)(\s*:)/g,(s,n,o)=>ce.type+n+ce.reset+o),e=an(e,/"[^"]*"|'[^']*'/g,s=>ce.str+s+ce.reset),e}function ed(t,e,s){if(e==="json")return C0(t);if(e==="html"||e==="xml")return A0(t);if(e==="css")return O0(t);if(e==="md")return t;let n=Ju[e]||Ju.js,o="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ce.cmt+t+ce.reset;if(o+=ce.cmt+t.slice(0,i+2)+ce.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return o}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return ce.str+t+ce.reset;if(o+=ce.str+t.slice(0,i+1)+ce.reset,s.inString=null,r=i+1,r>=t.length)return o}for(;r<t.length;){let i=t[r];if(!s.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return o+=ce.cmt+t.slice(r)+ce.reset,s.inBlockComment=!0,o;o+=ce.cmt+t.slice(r,a+2)+ce.reset,r=a+2;continue}if(!s.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return o+=ce.cmt+t.slice(r)+ce.reset,o;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,o+=ce.str+i,r++;continue}if(s.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===s.inString){o+=i+ce.reset,s.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];o+=ce.num+a+ce.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];o+=ce.punct+a+ce.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];n.has(a)?o+=ce.kw+a+ce.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=ce.type+a+ce.reset:o+=a;continue}o+=i,r++}return s.inString&&s.inString!=="`"&&(o+=ce.reset,s.inString=null),o}function N0(t,e){let s=Qu(e);if(!s)return t.split(`
19
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(a=>a.status==="done").length,n=this.tasks.filter(a=>a.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${ne.green}\u2714${ne.reset} ${this.name} ${ne.dim}(${e} \xB7 ${r})${ne.reset}
20
+ `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":" ",u=Lr[l.status]||Lr.pending,d=Ir[l.status]||Ir.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${ne.dim}${c}${ne.reset} ${d}${u}${ne.reset} ${ne.dim}${f}${ne.reset}
21
+ `}process.stderr.write(i)}},Ma=class{constructor(e,s){this.toolName=e,this.message=s||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=As[this.frame%As.length],s="";for(let r=0;r<jr;r++)s+=r===e?`${ne.cyan}\u25CF${ne.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${ne.cyan}${this.count}${ne.reset}`,this.total&&(n+=`/${this.total}`),this.detail&&(n+=` ${ne.dim}${this.detail}${ne.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${ne.dim}${r}s${ne.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${ne.dim}${n}${ne.reset}${o}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function tw(t){Tn=t}function nw(){return Tn}function sw(){Tn&&(Tn.stop(),Tn=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}dd.exports={C:ne,Spinner:Aa,MultiProgress:Oa,TaskProgress:Na,ToolProgress:Ma,setActiveTaskProgress:tw,getActiveTaskProgress:nw,cleanupTerminal:sw}});var Pa=V((KR,gd)=>{"use strict";var{T:Yn}=Ht(),le={kw:Yn.syn_keyword,str:Yn.syn_string,cmt:Yn.syn_comment,num:Yn.syn_number,type:Yn.cyan,punct:Yn.magenta,reset:Yn.reset},fd={js:new Set(["const","let","var","function","return","if","else","for","while","do","class","new","this","import","export","from","default","async","await","try","catch","finally","throw","typeof","instanceof","in","of","switch","case","break","continue","null","undefined","true","false","extends","super","static","get","set","delete","void","yield","interface","type","enum","namespace","abstract","implements","declare","module","require","readonly","keyof","infer","never","unknown","any","as","satisfies"]),py:new Set(["def","class","return","if","elif","else","for","while","with","as","import","from","pass","break","continue","try","except","finally","raise","in","not","and","or","is","lambda","yield","global","nonlocal","del","assert","True","False","None","async","await","self","cls","print","range","len","type","list","dict","set","tuple","str","int","float","bool","open","super","property","staticmethod","classmethod"]),sh:new Set(["if","then","else","elif","fi","for","while","do","done","case","esac","in","function","return","local","export","source","echo","exit","break","continue","readonly","unset","shift","trap","read"]),go:new Set(["func","return","if","else","for","range","type","struct","interface","import","package","var","const","defer","go","chan","select","case","default","break","continue","fallthrough","nil","true","false","make","new","len","cap","append","copy","delete","panic","recover","map","error","string","int","int64","int32","uint","bool","byte","rune"]),rs:new Set(["fn","let","mut","return","if","else","for","while","loop","match","use","mod","pub","struct","enum","impl","trait","where","const","static","type","move","ref","in","as","unsafe","extern","crate","self","Self","super","true","false","None","Some","Ok","Err","i32","i64","u32","u64","usize","f32","f64","bool","str","String","Vec"]),java:new Set(["class","interface","extends","implements","import","package","return","if","else","for","while","do","switch","case","break","continue","new","this","super","null","true","false","public","private","protected","static","final","abstract","void","int","long","double","float","boolean","char","byte","short","try","catch","finally","throw","throws","synchronized","volatile","transient","instanceof","enum","record"])},ow={js:"js",jsx:"js",ts:"js",tsx:"js",mjs:"js",cjs:"js",py:"py",css:"css",scss:"css",less:"css",sh:"sh",bash:"sh",zsh:"sh",go:"go",rs:"rs",java:"java",json:"json",html:"html",htm:"html",xml:"xml",md:"md"};function hd(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return ow[e]||null}var pd=/\x1b\[[0-9;]*m/g;function pn(t,e,s){let n=t.split(pd),o=t.match(pd)||[],r="";for(let i=0;i<n.length;i++)r+=n[i].replace(e,s),i<o.length&&(r+=o[i]);return r}function rw(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,s=>le.type+s+le.reset),e=pn(e,/"([^"\\]|\\.)*"/g,s=>le.str+s+le.reset),e=pn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,s=>le.num+s+le.reset),e=pn(e,/\b(true|false|null)\b/g,s=>le.kw+s+le.reset),e}function iw(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,s=>le.cmt+s+le.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(s,n,o)=>n+le.type+o+le.reset),e=pn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(s,n)=>" "+le.kw+n+le.reset+"="),e=pn(e,/"([^"]*)"/g,s=>le.str+s+le.reset),e}function aw(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,s=>le.cmt+s+le.reset),e=pn(e,/#[0-9a-fA-F]{3,8}\b/g,s=>le.num+s+le.reset),e=pn(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(s,n,o)=>le.num+n+le.reset+o),e=pn(e,/([a-z][a-z-]*)(\s*:)/g,(s,n,o)=>le.type+n+le.reset+o),e=pn(e,/"[^"]*"|'[^']*'/g,s=>le.str+s+le.reset),e}function md(t,e,s){if(e==="json")return rw(t);if(e==="html"||e==="xml")return iw(t);if(e==="css")return aw(t);if(e==="md")return t;let n=fd[e]||fd.js,o="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return le.cmt+t+le.reset;if(o+=le.cmt+t.slice(0,i+2)+le.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return o}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return le.str+t+le.reset;if(o+=le.str+t.slice(0,i+1)+le.reset,s.inString=null,r=i+1,r>=t.length)return o}for(;r<t.length;){let i=t[r];if(!s.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return o+=le.cmt+t.slice(r)+le.reset,s.inBlockComment=!0,o;o+=le.cmt+t.slice(r,a+2)+le.reset,r=a+2;continue}if(!s.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return o+=le.cmt+t.slice(r)+le.reset,o;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,o+=le.str+i,r++;continue}if(s.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===s.inString){o+=i+le.reset,s.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];o+=le.num+a+le.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];o+=le.punct+a+le.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];n.has(a)?o+=le.kw+a+le.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=le.type+a+le.reset:o+=a;continue}o+=i,r++}return s.inString&&s.inString!=="`"&&(o+=le.reset,s.inString=null),o}function lw(t,e){let s=hd(e);if(!s)return t.split(`
22
22
  `);let n=t.split(`
23
- `),o={inString:null,inBlockComment:!1};return n.map(r=>ed(r,s,o))}function M0(t,e){return e?ed(t,e,{inString:null,inBlockComment:!1}):t}td.exports={detectLang:Qu,highlightLine:M0,highlightLines:N0}});var od=Z((KT,sd)=>{var{T:R}=Ft(),st=R,P0={read_file:R.tool_read,list_directory:R.tool_read,write_file:R.tool_write,edit_file:R.tool_write,patch_file:R.tool_write,bash:R.tool_exec,grep:R.tool_search,search_files:R.tool_search,glob:R.tool_search,git_commit:R.tool_git,git_push:R.tool_git,git_pull:R.tool_git,git_status:R.tool_git,git_diff:R.tool_git,git_log:R.tool_git,git_branch:R.tool_git,git_stash:R.tool_git,web_fetch:R.tool_web,web_search:R.tool_web,sysadmin:R.tool_sysadmin,ssh_exec:R.tool_sysadmin,ssh_upload:R.tool_sysadmin,ssh_download:R.tool_sysadmin,deploy:R.tool_sysadmin},va={read_file:"Read",write_file:"Write",edit_file:"Edit",patch_file:"Edit",list_directory:"List",bash:"Bash",grep:"Grep",search_files:"Search",glob:"Glob",web_fetch:"WebFetch",web_search:"WebSearch",git_status:"Bash",git_diff:"Bash",git_log:"Bash",git_commit:"Bash",git_push:"Bash",git_pull:"Bash",git_branch:"Bash",git_stash:"Bash",task_list:"TaskList",spawn_agents:"Agent",ask_user:"AskUser",switch_model:"SwitchModel",gh_run_list:"Bash",gh_run_view:"Bash",gh_workflow_trigger:"Bash",browser_open:"Browser",browser_screenshot:"Browser",browser_click:"Browser",browser_fill:"Browser",ssh_exec:"Bash",ssh_upload:"Upload",ssh_download:"Download",service_manage:"Bash",service_logs:"Bash",container_list:"Bash",container_logs:"Bash",container_exec:"Bash",brain_write:"Write",deploy:"Bash",frontend_recon:"Search"};function Or(t,e=!1,s=null){if(e)return`${R.error}\u23FA${R.reset}`;let n=P0[t]||R.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${R.reset}`:`${n}${s!==null?s:"\u23FA"}${R.reset}`}function L0(t,e,s=!1,n=null){let o=(t||[]).filter(l=>l&&l.canExecute!==!1);if(o.length===0)return`${Or("",s,n)} Step ${e}`;if(o.length===1){let l=o[0],c=l.args||{},u=va[l.fnName]||l.fnName.replace(/_/g," "),d="";c.path?d=c._originalPath||c.path:c.command?d=String(c.command).substring(0,80):c.query?d=String(c.query).substring(0,60):c.pattern?d=String(c.pattern).substring(0,60):c.url&&(d=String(c.url).substring(0,60));let f=d?`(${st.dim}${d}${st.reset})`:"";return`${Or(l.fnName,s,n)} ${st.bold}${u}${st.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(l=>va[l.fnName]||l.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${Or(r,s,n)} ${st.bold}${a}${st.reset}`}function I0(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=e.path||"";break;case"bash":case"ssh_exec":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=va[t]||t.replace(/_/g," "),o=s?`(${st.dim}${s}${st.reset})`:"";return`${Or(t)} ${st.bold}${n}${st.reset}${o}`}function D0(t,e=8){let s=t.split(`
24
- `),n=s.slice(0,e),o=s.length-e,r=`${R.muted} \u23BF ${R.reset}`,i=" ",a=n.map((l,c)=>`${c===0?r:i}${R.success}${l}${R.reset}`).join(`
23
+ `),o={inString:null,inBlockComment:!1};return n.map(r=>md(r,s,o))}function cw(t,e){return e?md(t,e,{inString:null,inBlockComment:!1}):t}gd.exports={detectLang:hd,highlightLine:cw,highlightLines:lw}});var $d=V((XR,wd)=>{var{T:C}=Ht(),at=C,uw={read_file:C.tool_read,list_directory:C.tool_read,write_file:C.tool_write,edit_file:C.tool_write,patch_file:C.tool_write,bash:C.tool_exec,grep:C.tool_search,search_files:C.tool_search,glob:C.tool_search,git_commit:C.tool_git,git_push:C.tool_git,git_pull:C.tool_git,git_status:C.tool_git,git_diff:C.tool_git,git_log:C.tool_git,git_branch:C.tool_git,git_stash:C.tool_git,web_fetch:C.tool_web,web_search:C.tool_web,sysadmin:C.tool_sysadmin,ssh_exec:C.tool_sysadmin,ssh_upload:C.tool_sysadmin,ssh_download:C.tool_sysadmin,deploy:C.tool_sysadmin},La={read_file:"Read",write_file:"Write",edit_file:"Edit",patch_file:"Edit",list_directory:"List",bash:"Bash",grep:"Grep",search_files:"Search",glob:"Glob",web_fetch:"WebFetch",web_search:"WebSearch",git_status:"Bash",git_diff:"Bash",git_log:"Bash",git_commit:"Bash",git_push:"Bash",git_pull:"Bash",git_branch:"Bash",git_stash:"Bash",task_list:"TaskList",spawn_agents:"Agent",ask_user:"AskUser",switch_model:"SwitchModel",gh_run_list:"Bash",gh_run_view:"Bash",gh_workflow_trigger:"Bash",browser_open:"Browser",browser_screenshot:"Browser",browser_click:"Browser",browser_fill:"Browser",ssh_exec:"Bash",ssh_upload:"Upload",ssh_download:"Download",service_manage:"Bash",service_logs:"Bash",container_list:"Bash",container_logs:"Bash",container_exec:"Bash",brain_write:"Write",deploy:"Bash",frontend_recon:"Search"};function Dr(t,e=!1,s=null){if(e)return`${C.error}\u23FA${C.reset}`;let n=uw[t]||C.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${C.reset}`:`${n}${s!==null?s:"\u23FA"}${C.reset}`}function dw(t,e,s=!1,n=null){let o=(t||[]).filter(l=>l&&l.canExecute!==!1);if(o.length===0)return`${Dr("",s,n)} Step ${e}`;if(o.length===1){let l=o[0],c=l.args||{},u=La[l.fnName]||l.fnName.replace(/_/g," "),d="";c.path?d=c._originalPath||c.path:c.command?d=String(c.command).substring(0,80):c.query?d=String(c.query).substring(0,60):c.pattern?d=String(c.pattern).substring(0,60):c.url&&(d=String(c.url).substring(0,60));let f=d?`(${at.dim}${d}${at.reset})`:"";return`${Dr(l.fnName,s,n)} ${at.bold}${u}${at.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(l=>La[l.fnName]||l.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${Dr(r,s,n)} ${at.bold}${a}${at.reset}`}function fw(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=e.path||"";break;case"bash":case"ssh_exec":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=La[t]||t.replace(/_/g," "),o=s?`(${at.dim}${s}${at.reset})`:"";return`${Dr(t)} ${at.bold}${n}${at.reset}${o}`}function pw(t,e=8){let s=t.split(`
24
+ `),n=s.slice(0,e),o=s.length-e,r=`${C.muted} \u23BF ${C.reset}`,i=" ",a=n.map((l,c)=>`${c===0?r:i}${C.success}${l}${C.reset}`).join(`
25
25
  `);return o>0&&(a+=`
26
- ${R.subtle} \u2026 +${o} lines${R.reset}`),a}var Nr=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],nd=Math.floor(Math.random()*Nr.length),Ta=null;function j0(t){Ta=t}function q0(){let t=Nr[nd%Nr.length];nd++;let e=Ta?` \xB7 ${Ta}`:"";return`${t}${e}`}function F0(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading ${e.path||"file"}`;case"list_directory":return`Listing ${e.path||"."}`;case"search_files":return`Searching ${e.pattern||"..."}`;case"glob":return`Searching ${e.pattern||"..."}`;case"grep":return`Searching ${e.pattern||"..."}`;case"web_fetch":return`Fetching ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Checking git status";case"git_diff":return`Diffing${e.file?` ${e.file}`:""}`;case"git_log":return`Reading git log${e.file?` (${e.file})`:""}`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let s=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${s}: full audit...`;case"disk_usage":return`Sysadmin${s}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${s}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${s}: network status...`;case"ssl_check":return`Sysadmin${s}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${s}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${s}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${s}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${s}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${s}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${s}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${s}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${s}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${s}: cron ${e.cron_action||""}...`;default:return`Sysadmin${s}: ${e.action}...`}}case"visual_diff":return"Comparing screenshots (pixel diff)...";case"responsive_sweep":return`Responsive sweep: ${(e.url||"").substring(0,50)}...`;case"visual_annotate":return`Annotating screenshot (${(e.annotations||[]).length} markers)...`;case"visual_watch":return`Visual watch: ${(e.url||"").substring(0,50)}...`;case"design_tokens":return"Extracting design tokens...";case"design_compare":return"Comparing against reference design...";default:return`Running: ${t}`}}function B0(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
27
- `)[0];if(a.startsWith("BLOCKED:")){let d=a.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return` ${R.muted}\u23BF blocked: ${d}${R.reset}`}let l=a.replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),u=c?`
28
- ${R.muted}${c[1].substring(0,100)}${R.reset}`:"";return` ${R.error}\u23BF ${l}${R.reset}${u}`}let r;switch(t){case"read_file":{let l=o.split(`
29
- `).filter(Boolean).filter(g=>!/^File:\s/.test(g)&&!/^\[LARGE FILE:/.test(g)),c=l.length,u=l[l.length-1],d=u?parseInt(u.match(/^(\d+):/)?.[1]||"0"):0,f=e.line_start||e.line_end,p=e.path?require("path").basename(e.path):null,m=p?` ${R.muted}from ${p}${R.reset}`:"";f&&d>c?r=`Read lines ${e.line_start||1}\u2013${d}${m}`:r=`Read ${c} line${c!==1?"s":""}${m}`;break}case"write_file":{let l=(e.content||"").split(`
30
- `).length,c=e.path?require("path").basename(e.path):null,u=c?`Wrote ${c} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,{highlightLines:d}=Ea(),f=d(e.content||"",e.path||null),p=40,m=8;if(l<=p){let g=f.map(_=>` ${_}`).join(`
26
+ ${C.subtle} \u2026 +${o} lines${C.reset}`),a}var qr=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],yd=Math.floor(Math.random()*qr.length),Ia=null;function hw(t){Ia=t}function mw(){let t=qr[yd%qr.length];yd++;let e=Ia?` \xB7 ${Ia}`:"";return`${t}${e}`}function gw(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading ${e.path||"file"}`;case"list_directory":return`Listing ${e.path||"."}`;case"search_files":return`Searching ${e.pattern||"..."}`;case"glob":return`Searching ${e.pattern||"..."}`;case"grep":return`Searching ${e.pattern||"..."}`;case"web_fetch":return`Fetching ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Checking git status";case"git_diff":return`Diffing${e.file?` ${e.file}`:""}`;case"git_log":return`Reading git log${e.file?` (${e.file})`:""}`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let s=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${s}: full audit...`;case"disk_usage":return`Sysadmin${s}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${s}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${s}: network status...`;case"ssl_check":return`Sysadmin${s}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${s}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${s}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${s}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${s}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${s}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${s}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${s}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${s}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${s}: cron ${e.cron_action||""}...`;default:return`Sysadmin${s}: ${e.action}...`}}case"visual_diff":return"Comparing screenshots (pixel diff)...";case"responsive_sweep":return`Responsive sweep: ${(e.url||"").substring(0,50)}...`;case"visual_annotate":return`Annotating screenshot (${(e.annotations||[]).length} markers)...`;case"visual_watch":return`Visual watch: ${(e.url||"").substring(0,50)}...`;case"design_tokens":return"Extracting design tokens...";case"design_compare":return"Comparing against reference design...";default:return`Running: ${t}`}}function yw(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
27
+ `)[0];if(a.startsWith("BLOCKED:")){let d=a.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return` ${C.muted}\u23BF blocked: ${d}${C.reset}`}let l=a.replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),u=c?`
28
+ ${C.muted}${c[1].substring(0,100)}${C.reset}`:"";return` ${C.error}\u23BF ${l}${C.reset}${u}`}let r;switch(t){case"read_file":{let l=o.split(`
29
+ `).filter(Boolean).filter(g=>!/^File:\s/.test(g)&&!/^\[LARGE FILE:/.test(g)),c=l.length,u=l[l.length-1],d=u?parseInt(u.match(/^(\d+):/)?.[1]||"0"):0,f=e.line_start||e.line_end,p=e.path?require("path").basename(e.path):null,m=p?` ${C.muted}from ${p}${C.reset}`:"";f&&d>c?r=`Read lines ${e.line_start||1}\u2013${d}${m}`:r=`Read ${c} line${c!==1?"s":""}${m}`;break}case"write_file":{let l=(e.content||"").split(`
30
+ `).length,c=e.path?require("path").basename(e.path):null,u=c?`Wrote ${c} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,{highlightLines:d}=Pa(),f=d(e.content||"",e.path||null),p=40,m=8;if(l<=p){let g=f.map($=>` ${$}`).join(`
31
31
  `);r=`${u}
32
- ${g}`}else{let g=f.slice(0,m).map(_=>` ${_}`).join(`
32
+ ${g}`}else{let g=f.slice(0,m).map($=>` ${$}`).join(`
33
33
  `);r=`${u}
34
34
  ${g}
35
- ${R.subtle}\u2026 +${l-m} lines${R.reset}`}break}case"edit_file":{let a=(e.old_text||"").split(`
35
+ ${C.subtle}\u2026 +${l-m} lines${C.reset}`}break}case"edit_file":{let a=(e.old_text||"").split(`
36
36
  `),l=(e.new_text||"").split(`
37
- `),c=a.length,u=l.length,d=e.path?require("path").basename(e.path):null,f=d?` ${R.muted}${d}${R.reset}`:"",p=a.find(L=>L.trim()),m=l.find(L=>L.trim()),{highlightLine:g,detectLang:_}=Ea(),k=_(e.path||null),A=[];p&&A.push(` ${R.diff_rem}- ${R.reset}${g(p.trimEnd().substring(0,72),k)}${R.reset}`),m&&A.push(` ${R.diff_add}+ ${R.reset}${g(m.trimEnd().substring(0,72),k)}${R.reset}`),r=`${R.diff_rem}\u2212${c}${R.reset} ${R.diff_add}+${u}${R.reset}${f}`+(A.length>0?`
38
- `+A.join(`
37
+ `),c=a.length,u=l.length,d=e.path?require("path").basename(e.path):null,f=d?` ${C.muted}${d}${C.reset}`:"",p=a.find(D=>D.trim()),m=l.find(D=>D.trim()),{highlightLine:g,detectLang:$}=Pa(),k=$(e.path||null),M=[];p&&M.push(` ${C.diff_rem}- ${C.reset}${g(p.trimEnd().substring(0,72),k)}${C.reset}`),m&&M.push(` ${C.diff_add}+ ${C.reset}${g(m.trimEnd().substring(0,72),k)}${C.reset}`),r=`${C.diff_rem}\u2212${c}${C.reset} ${C.diff_add}+${u}${C.reset}${f}`+(M.length>0?`
38
+ `+M.join(`
39
39
  `):"");break}case"patch_file":{let a=e.patches||[],l=a.reduce((u,d)=>u+(d.old_text||"").split(`
40
40
  `).length,0),c=a.reduce((u,d)=>u+(d.new_text||"").split(`
41
- `).length,0);r=`${R.reset}${a.length} patch${a.length!==1?"es":""} ${R.diff_rem}\u2212${l}${R.reset} ${R.diff_add}+${c}${R.reset}`;break}case"bash":{let l=o.match(/^EXIT (\d+)/),c=o.split(`
42
- `).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=l?l[1]==="0"?`${R.success}\u2713${R.reset}`:`${R.error}\u2717 Exit ${l[1]}${R.reset}`:`${R.success}\u2713${R.reset}`,d=o.match(/\nHINT: (.+)/);if(d)r=`${u} ${R.muted}\u2014 ${d[1].substring(0,100)}${R.reset}`;else if(c.length===0)r=u;else{let f=l&&l[1]!=="0",p=f?c.slice(-3):c.slice(0,3),m=c.length-3,g=p.map((_,k)=>k===0?`${u} ${R.muted}${_.substring(0,120)}${R.reset}`:` ${R.muted}${_.substring(0,120)}${R.reset}`);if(m>0){let _=f?` ${R.subtle}${m} lines above\u2026${R.reset}`:` ${R.subtle}\u2026 +${m} lines${R.reset}`;f?g.unshift(_):g.push(_)}r=g.join(`
43
- `)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${R.muted}"${String(e.pattern).substring(0,40)}"${R.reset}`:""}`;else{let m=function(k){let A=k.indexOf(":");if(A===-1)return`${R.muted}${k.substring(0,90)}${R.reset}`;let L=k.substring(0,A),E=k.substring(A+1),v=E.match(/^(\d+)[:-](.*)/s),N=v?`:${v[1]}`:"",te=(v?v[2]:E).trim(),V=`${R.subtle}${a.basename(L)}${N}${R.reset}`,re=`${R.muted}${te.substring(0,80)}${te.length>80?"\u2026":""}${R.reset}`;return`${V} ${re}`};var i=m;let a=require("path"),l=o.split(`
44
- `).filter(Boolean),c=l.length,d=new Set(l.map(k=>k.split(":")[0]).filter(Boolean)).size,f=e.pattern?` ${R.muted}"${String(e.pattern).substring(0,40)}"${R.reset}`:"",p=d>1?`${c} match${c!==1?"es":""} in ${d} files${f}`:`${c} match${c!==1?"es":""}${f}`,g=l.slice(0,3).map((k,A)=>A===0?`${p}
45
- ${m(k)}`:` ${m(k)}`),_=l.length-3;_>0&&g.push(` ${R.subtle}\u2026 +${_} lines${R.reset}`),r=g.join(`
46
- `)}break}case"glob":{let a=e.pattern?` ${R.muted}${String(e.pattern).substring(0,50)}${R.reset}`:"";if(o==="(no matches)")r=`No files found${a}`;else{let l=require("path"),c=o.split(`
47
- `).filter(Boolean),u=c.length,d=c.slice(0,5).map(m=>l.basename(m)),f=u-d.length,p=d.join(", ")+(f>0?`, +${f} more`:"");r=`${u} file${u!==1?"s":""}${a} \u2014 ${R.muted}${p}${R.reset}`}break}case"list_directory":{if(o==="(empty)")r="0 entries";else{let a=o.split(`
48
- `).filter(Boolean),l=a.length,c=a.slice(0,6).join(", "),u=l-6;r=u>0?`${l} entries \u2014 ${R.muted}${c}, +${u} more${R.reset}`:`${l} entr${l!==1?"ies":"y"} \u2014 ${R.muted}${c}${R.reset}`}break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),l=o.split(`
41
+ `).length,0);r=`${C.reset}${a.length} patch${a.length!==1?"es":""} ${C.diff_rem}\u2212${l}${C.reset} ${C.diff_add}+${c}${C.reset}`;break}case"bash":{let l=o.match(/^EXIT (\d+)/),c=o.split(`
42
+ `).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=l?l[1]==="0"?`${C.success}\u2713${C.reset}`:`${C.error}\u2717 Exit ${l[1]}${C.reset}`:`${C.success}\u2713${C.reset}`,d=o.match(/\nHINT: (.+)/);if(d)r=`${u} ${C.muted}\u2014 ${d[1].substring(0,100)}${C.reset}`;else if(c.length===0)r=u;else{let f=l&&l[1]!=="0",p=f?c.slice(-3):c.slice(0,3),m=c.length-3,g=p.map(($,k)=>k===0?`${u} ${C.muted}${$.substring(0,120)}${C.reset}`:` ${C.muted}${$.substring(0,120)}${C.reset}`);if(m>0){let $=f?` ${C.subtle}${m} lines above\u2026${C.reset}`:` ${C.subtle}\u2026 +${m} lines${C.reset}`;f?g.unshift($):g.push($)}r=g.join(`
43
+ `)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${C.muted}"${String(e.pattern).substring(0,40)}"${C.reset}`:""}`;else{let m=function(k){let M=k.indexOf(":");if(M===-1)return`${C.muted}${k.substring(0,90)}${C.reset}`;let D=k.substring(0,M),v=k.substring(M+1),E=v.match(/^(\d+)[:-](.*)/s),A=E?`:${E[1]}`:"",ee=(E?E[2]:v).trim(),se=`${C.subtle}${a.basename(D)}${A}${C.reset}`,ue=`${C.muted}${ee.substring(0,80)}${ee.length>80?"\u2026":""}${C.reset}`;return`${se} ${ue}`};var i=m;let a=require("path"),l=o.split(`
44
+ `).filter(Boolean),c=l.length,d=new Set(l.map(k=>k.split(":")[0]).filter(Boolean)).size,f=e.pattern?` ${C.muted}"${String(e.pattern).substring(0,40)}"${C.reset}`:"",p=d>1?`${c} match${c!==1?"es":""} in ${d} files${f}`:`${c} match${c!==1?"es":""}${f}`,g=l.slice(0,3).map((k,M)=>M===0?`${p}
45
+ ${m(k)}`:` ${m(k)}`),$=l.length-3;$>0&&g.push(` ${C.subtle}\u2026 +${$} lines${C.reset}`),r=g.join(`
46
+ `)}break}case"glob":{let a=e.pattern?` ${C.muted}${String(e.pattern).substring(0,50)}${C.reset}`:"";if(o==="(no matches)")r=`No files found${a}`;else{let l=require("path"),c=o.split(`
47
+ `).filter(Boolean),u=c.length,d=c.slice(0,5).map(m=>l.basename(m)),f=u-d.length,p=d.join(", ")+(f>0?`, +${f} more`:"");r=`${u} file${u!==1?"s":""}${a} \u2014 ${C.muted}${p}${C.reset}`}break}case"list_directory":{if(o==="(empty)")r="0 entries";else{let a=o.split(`
48
+ `).filter(Boolean),l=a.length,c=a.slice(0,6).join(", "),u=l-6;r=u>0?`${l} entries \u2014 ${C.muted}${c}, +${u} more${C.reset}`:`${l} entr${l!==1?"ies":"y"} \u2014 ${C.muted}${c}${C.reset}`}break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),l=o.split(`
49
49
  `).filter(c=>/^\s*[MADRCU?!]/.test(c)).length;r=a?`${a[1]} \xB7 ${l} change${l!==1?"s":""}`:"Done";break}case"git_diff":{let a=(o.match(/^\+[^+]/gm)||[]).length,l=(o.match(/^-[^-]/gm)||[]).length;r=a||l?`+${a} \u2212${l} lines`:"No diff";break}case"git_log":{let a=o.split(`
50
50
  `).filter(d=>/^commit\s+[0-9a-f]{7}/.test(d)),l=a.length,c=a[0]?a[0].replace(/^commit\s+/,"").substring(0,7):null,u=(()=>{let d=o.indexOf(a[0]||"\0");return d===-1?null:o.substring(d).split(`
51
- `).find((p,m)=>m>0&&p.trim()&&!p.startsWith("Author:")&&!p.startsWith("Date:")&&!p.startsWith("Merge:"))})();if(l===0)r="Log retrieved";else if(c&&u){let d=l>1?` ${R.muted}+${l-1} more${R.reset}`:"";r=`${c} ${R.muted}${u.trim().substring(0,60)}${R.reset}${d}`}else r=`${l} commit${l!==1?"s":""}`;break}case"git_commit":{let a=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),l=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=a?`${a[1]}${l?` \u2014 ${l[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let a=o.match(/(?:->|→)\s*(\S+)/);r=a?`\u2192 ${a[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))r="Already up to date";else{let a=(o.match(/^\+/gm)||[]).length;r=a>0?`Pulled \xB7 +${a} lines`:"Pulled"}break}case"web_fetch":{let a=o.match(/<title[^>]*>([^<]{1,80})<\/title>/i),l=o.match(/^#\s+(.{1,80})/m),c=e.url||"",u="";try{u=new URL(c).hostname}catch{u=c.substring(0,60)}let d=a?a[1].trim():l?l[1].trim():null;r=d?`${u} \u2014 ${R.muted}${d.substring(0,70)}${R.reset}`:`Fetched ${u}`;break}case"web_search":{let a=o.split(`
51
+ `).find((p,m)=>m>0&&p.trim()&&!p.startsWith("Author:")&&!p.startsWith("Date:")&&!p.startsWith("Merge:"))})();if(l===0)r="Log retrieved";else if(c&&u){let d=l>1?` ${C.muted}+${l-1} more${C.reset}`:"";r=`${c} ${C.muted}${u.trim().substring(0,60)}${C.reset}${d}`}else r=`${l} commit${l!==1?"s":""}`;break}case"git_commit":{let a=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),l=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=a?`${a[1]}${l?` \u2014 ${l[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let a=o.match(/(?:->|→)\s*(\S+)/);r=a?`\u2192 ${a[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))r="Already up to date";else{let a=(o.match(/^\+/gm)||[]).length;r=a>0?`Pulled \xB7 +${a} lines`:"Pulled"}break}case"web_fetch":{let a=o.match(/<title[^>]*>([^<]{1,80})<\/title>/i),l=o.match(/^#\s+(.{1,80})/m),c=e.url||"",u="";try{u=new URL(c).hostname}catch{u=c.substring(0,60)}let d=a?a[1].trim():l?l[1].trim():null;r=d?`${u} \u2014 ${C.muted}${d.substring(0,70)}${C.reset}`:`Fetched ${u}`;break}case"web_search":{let a=o.split(`
52
52
 
53
53
  `).filter(Boolean),l=a.length,c=a[0]?a[0].split(`
54
- `)[0].replace(/^\d+\.\s*/,"").trim():null,u=c?` ${R.muted}\u2014 ${c.substring(0,70)}${R.reset}`:"";r=`${l} result${l!==1?"s":""}${u}`;break}case"task_list":r="Done";break;case"spawn_agents":{if(o.includes("Background agents started")){let c=o.match(/\bbg-[\w-]+/g),u=c?c.length:0;r=`${u} bg agent${u!==1?"s":""} started`;break}let a=(o.match(/✓ Agent/g)||[]).length,l=(o.match(/✗ Agent/g)||[]).length;r=l>0?`${a} done, ${l} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=o.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}case"ssh_exec":{let l=o.startsWith("EXIT ")||o.startsWith("Command failed"),c=o.split(`
55
- `).filter(d=>d.trim()&&!d.startsWith("EXIT ")),u=l?`${R.error}\u2717${R.reset}`:`${R.success}\u2713${R.reset}`;if(c.length===0)r=u;else{if(c.length>2&&c.every(g=>/^\[/.test(g.trim()))){r=`${u} ${c.length} log lines`;break}let f=l?c.slice(-3):c.slice(0,3),p=c.length-3,m=f.map((g,_)=>_===0?`${u} ${R.muted}${g.substring(0,120)}${R.reset}`:` ${R.muted}${g.substring(0,120)}${R.reset}`);if(p>0){let g=l?` ${R.subtle}${p} lines above\u2026${R.reset}`:` ${R.subtle}\u2026 +${p} lines${R.reset}`;l?m.unshift(g):m.push(g)}r=m.join(`
54
+ `)[0].replace(/^\d+\.\s*/,"").trim():null,u=c?` ${C.muted}\u2014 ${c.substring(0,70)}${C.reset}`:"";r=`${l} result${l!==1?"s":""}${u}`;break}case"task_list":r="Done";break;case"spawn_agents":{if(o.includes("Background agents started")){let c=o.match(/\bbg-[\w-]+/g),u=c?c.length:0;r=`${u} bg agent${u!==1?"s":""} started`;break}let a=(o.match(/✓ Agent/g)||[]).length,l=(o.match(/✗ Agent/g)||[]).length;r=l>0?`${a} done, ${l} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=o.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}case"ssh_exec":{let l=o.startsWith("EXIT ")||o.startsWith("Command failed"),c=o.split(`
55
+ `).filter(d=>d.trim()&&!d.startsWith("EXIT ")),u=l?`${C.error}\u2717${C.reset}`:`${C.success}\u2713${C.reset}`;if(c.length===0)r=u;else{if(c.length>2&&c.every(g=>/^\[/.test(g.trim()))){r=`${u} ${c.length} log lines`;break}let f=l?c.slice(-3):c.slice(0,3),p=c.length-3,m=f.map((g,$)=>$===0?`${u} ${C.muted}${g.substring(0,120)}${C.reset}`:` ${C.muted}${g.substring(0,120)}${C.reset}`);if(p>0){let g=l?` ${C.subtle}${p} lines above\u2026${C.reset}`:` ${C.subtle}\u2026 +${p} lines${C.reset}`;l?m.unshift(g):m.push(g)}r=m.join(`
56
56
  `)}break}default:{let a=o.split(`
57
- `).filter(l=>l.trim()&&!l.startsWith("EXIT ")&&!l.startsWith("HINT:"));if(a.length>0){let l=a[0].trim().substring(0,90),c=a.length>1?` ${R.subtle}\u2026 +${a.length-1} lines${R.reset}`:"";r=`${R.muted}${l}${R.reset}${c}`}else r="Done"}}return` ${R.muted}\u23BF ${r}${R.reset}`}function U0(t,e,s,n,o,r){let i=Math.round(n/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,l=`
58
- ${R.success}\u25C6${st.reset} ${st.bold}${t}${st.reset}`;return l+=`${st.dim} \xB7 ${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),l+=st.reset,l}sd.exports={C:st,formatToolCall:I0,formatResult:D0,getToolSpinnerText:F0,formatToolSummary:B0,formatSectionHeader:L0,formatMilestone:U0,getThinkingVerb:q0,setActiveModelForSpinner:j0,THINKING_VERBS:Nr}});var Je=Z((XT,id)=>{var{T:$n}=Ft(),Ra=$n,rd=["01100110","01111110","01111110","01011010","01111110","00111100"];function W0(t,e){let s=[];for(let n=0;n<t.length;n+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[n][r]==="1",a=n+1<t.length&&t[n+1][r]==="1";i&&a?o+=`${e}\u2588\x1B[0m`:i&&!a?o+=`${e}\u2580\x1B[0m`:!i&&a?o+=`${e}\u2584\x1B[0m`:o+=" "}s.push(o)}return s}function H0(t,e,s={}){let n=Ra.bold,o=Ra.reset,r=W0(rd,$n.banner_logo),i=s.yolo?` ${n}${$n.banner_yolo}\u26A1 YOLO${o}`:"",a=s.gemini?` ${n}${$n.banner_gemini}\u2726 GEMINI${o}`:"",l=$a().version,c=[` ${$n.banner_name}${n}nex-code${o} ${$n.banner_version}v${l}${o}`,` ${$n.banner_model}${t}${o} ${$n.muted}\xB7 /help${o}${a}${i}`,""],u=Math.max(r.length,c.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-c.length)/2),p=rd[0].length,m=[];for(let g=0;g<u;g++){let _=r[g-d]??" ".repeat(p),k=c[g-f]??"";m.push(_+k)}console.log(`
57
+ `).filter(l=>l.trim()&&!l.startsWith("EXIT ")&&!l.startsWith("HINT:"));if(a.length>0){let l=a[0].trim().substring(0,90),c=a.length>1?` ${C.subtle}\u2026 +${a.length-1} lines${C.reset}`:"";r=`${C.muted}${l}${C.reset}${c}`}else r="Done"}}return` ${C.muted}\u23BF ${r}${C.reset}`}function ww(t,e,s,n,o,r){let i=Math.round(n/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,l=`
58
+ ${C.success}\u25C6${at.reset} ${at.bold}${t}${at.reset}`;return l+=`${at.dim} \xB7 ${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),l+=at.reset,l}wd.exports={C:at,formatToolCall:fw,formatResult:pw,getToolSpinnerText:gw,formatToolSummary:yw,formatSectionHeader:dw,formatMilestone:ww,getThinkingVerb:mw,setActiveModelForSpinner:hw,THINKING_VERBS:qr}});var tt=V((VR,bd)=>{var{T:Rn}=Ht(),ja=Rn,_d=["01100110","01111110","01111110","01011010","01111110","00111100"];function $w(t,e){let s=[];for(let n=0;n<t.length;n+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[n][r]==="1",a=n+1<t.length&&t[n+1][r]==="1";i&&a?o+=`${e}\u2588\x1B[0m`:i&&!a?o+=`${e}\u2580\x1B[0m`:!i&&a?o+=`${e}\u2584\x1B[0m`:o+=" "}s.push(o)}return s}function _w(t,e,s={}){let n=ja.bold,o=ja.reset,r=$w(_d,Rn.banner_logo),i=s.yolo?` ${n}${Rn.banner_yolo}\u26A1 YOLO${o}`:"",a=s.gemini?` ${n}${Rn.banner_gemini}\u2726 GEMINI${o}`:"",l=Ca().version,c=[` ${Rn.banner_name}${n}nex-code${o} ${Rn.banner_version}v${l}${o}`,` ${Rn.banner_model}${t}${o} ${Rn.muted}\xB7 /help${o}${a}${i}`,""],u=Math.max(r.length,c.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-c.length)/2),p=_d[0].length,m=[];for(let g=0;g<u;g++){let $=r[g-d]??" ".repeat(p),k=c[g-f]??"";m.push($+k)}console.log(`
59
59
  `+m.join(`
60
60
  `)+`
61
- `)}var{Spinner:Y0,MultiProgress:G0,TaskProgress:z0,ToolProgress:K0,setActiveTaskProgress:X0,getActiveTaskProgress:V0,cleanupTerminal:J0}=vs(),{formatToolCall:Z0,formatResult:Q0,getToolSpinnerText:ew,formatToolSummary:tw,formatSectionHeader:nw,formatMilestone:sw,getThinkingVerb:ow,setActiveModelForSpinner:rw}=od();id.exports={C:Ra,banner:H0,Spinner:Y0,MultiProgress:G0,TaskProgress:z0,ToolProgress:K0,setActiveTaskProgress:X0,getActiveTaskProgress:V0,cleanupTerminal:J0,formatToolCall:Z0,formatResult:Q0,getToolSpinnerText:ew,formatToolSummary:tw,formatSectionHeader:nw,formatMilestone:sw,getThinkingVerb:ow,setActiveModelForSpinner:rw}});var Aa=Z((VT,ad)=>{function Ca(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var iw=Ca();function aw(...t){Ca()&&console.log(...t)}function lw(...t){Ca()&&console.warn(...t)}ad.exports={DEBUG:iw,debugLog:aw,warnLog:lw}});var ud=Z((JT,cd)=>{"use strict";var cw=new Set(["read_file","grep","glob","search_files","list_directory"]),uw=new Set(["write_file","edit_file","patch_file"]),dw=new Set(["bash"]),fw=new Set(["web_search","web_fetch","perplexity_search"]);function ld(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,l]of t)i+=l,cw.has(a)&&(s+=l),uw.has(a)&&(n+=l),dw.has(a)&&(o+=l),fw.has(a)&&(r+=l);return i===0?`Phase ${e}`:r/i>.5?"Research":s/i>.5?"Exploration":n/i>.3?"Implementation":o/i>.3&&n/i<.15?"Verification":`Phase ${e}`}var Oa=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,s,n,o){if(this._disabled)return null;this._stepsThisPhase++;for(let i of s)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:ld(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(n),filesModified:new Set(o)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};cd.exports={MilestoneTracker:Oa,_phaseName:ld}});var Mr=Z((ZT,dd)=>{var io=ot(),hw={"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",max_tokens:16384},"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",max_tokens:16384}};function pw(){return io.getActiveModel()}function mw(t){return io.setActiveModel(t)}function gw(){return io.getModelNames()}function yw(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let n=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(n)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let n=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(n)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function ww(t,e){let{C:s}=Je(),{Spinner:n}=Je(),o=new n("Thinking...");o.start();let r=!0,i="";try{let a=await io.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?o.stop():process.stdout.write(`${s.reset}
62
- `),a}catch(a){throw o.stop(),a}}async function _w(t,e){return io.callChat(t,e)}dd.exports={MODELS:hw,getActiveModel:pw,setActiveModel:mw,getModelNames:gw,callOllamaStream:ww,callOllama:_w,parseToolArgs:yw}});var lo=Z((QT,yd)=>{var $w=require("readline"),{C:Xt}=Je(),bw=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,kw=/^=([\w-]+)/;function ao(t){return typeof t!="string"?t:t.replace(bw,"").replace(kw,"$1")}var Pa=[/rm\s+-rf\s+\/(?:\s|$)/,/rm\s+-rf\s+~(?:\/|\s|$)/,/rm\s+-rf\s+\.(?:\/|\s|$)/,/rm\s+-rf\s+\*(?:\s|$)/,/mkfs/,/dd\s+if=/,/:\(\)\s*\{/,/>\/dev\/sd/,/curl.*\|\s*(?:ba)?sh/,/wget.*\|\s*(?:ba)?sh/,/cat\s+.*\.env\b/,/cat\s+.*credentials/i,/chmod\s+777/,/chown\s+root/,/passwd/,/userdel/,/useradd/,/\beval\s*\(/,/base64.*\|.*bash/,/\bprintenv\b/,/cat\s+.*\.ssh\/id_/,/cat\s+.*\.ssh\/config/,/\bnc\s+-[el]/,/\bncat\b/,/\bsocat\b/,/python3?\s+-c\s/,/node\s+-e\s/,/perl\s+-e\s/,/ruby\s+-e\s/,/(?:^|[;&|]\s*)history(?:\s|$)/,/curl.*-X\s*POST/,/curl.*--data/,/\bsed\s+-n\s+['"]?\d+,\d+p/],fd=[...Pa,/\bgrep\b.*\.env\b/,/\bawk\b.*\.env\b/,/\bsed\b.*\.env\b/,/\bhead\b.*\.env\b/,/\btail\b.*\.env\b/,/\bless\b.*\.env\b/,/\bmore\b.*\.env\b/,/\bstrings\b.*\.env\b/,/\bgrep\b.*credentials/i,/\bawk\b.*credentials/i,/\bsed\b.*credentials/i,/\bhead\b.*credentials/i,/\btail\b.*credentials/i,/\bcat\b.*private.*key/i,/\bgrep\b.*private_key/i,/\bcat\b.*google.*\.json/i,/\bcat\b.*service.?account/i];function xw(t){for(let e of fd)if(e.test(t))return e;return null}var hd=[/\.env\b/,/credentials\b/i,/\.ssh\b/,/\.gnupg\b/,/\.aws\b/,/\.npmrc\b/,/\.docker\/config/,/\.kube\/config/,/venv\b/,/\.venv\b/,/\.sqlite3\b/,/\.git\/(?!hooks)/],Sw=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Na=[/systemctl\s+(status|is-active|is-enabled|list-units|show)/,/journalctl\b/,/\btail\s/,/\bcat\s/,/\bhead\s/,/\bls\b/,/\bfind\s/,/\bgrep\s/,/\bwc\s/,/\bdf\b/,/\bfree\b/,/\buptime\b/,/\bwho\b/,/\bps\s/,/\bgit\s+(status|log|diff|branch|fetch)\b/,/\bgit\s+pull\b/,/\bss\s+-[tlnp]/,/\bnetstat\s/,/\bdu\s/,/\blscpu\b/,/\bnproc\b/,/\buname\b/,/\bhostname\b/,/\bgetent\b/,/\bid\b/,/psql\s.*-c\s/,/\bmysql\s.*-e\s/,/\bdnf\s+(check-update|list|info|history|repolist|updateinfo)\b/,/\brpm\s+-q/,/\bapt\s+list\b/,/\bopenssl\s+s_client\b/,/\bopenssl\s+x509\b/,/\bcertbot\s+certificates\b/,/\bcurl\s+-[sIkv]|curl\s+--head/,/\bdig\s/,/\bnslookup\s/,/\bping\s/,/\bgetenforce\b/,/\bsesearch\b/,/\bausearch\b/,/\bsealert\b/,/\bcrontab\s+-l\b/,/\btimedatectl\b/,/\bfirewall-cmd\s+--list/,/\bfirewall-cmd\s+--state/];function pd(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(c=>c.trim()).filter(Boolean).every(c=>o(c)):Na.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Na.some(a=>a.test(i))};return n.every(o)}var La=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/,/--no-verify\b/,/git\s+reset\s+--hard\b/,/git\s+clean\s+-[a-z]*f/,/git\s+checkout\s+--\s/,/git\s+push\s+(?:--force\b|-f\b)/,/\b(?:curl|wget|fetch)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|ksh|dash|python|python3|perl|ruby|node)\b/,/\b(?:curl|wget)\b[^;&`$()]*\$\([^)]*\)/,/\bbase64\s+(?:-d|--decode|-D)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|python|python3|perl|ruby|node)\b/,/\beval\s+["'`]?\$\(\s*(?:curl|wget|fetch)\b/,/\bbash\s+-i\s*>&?\s*\/dev\/tcp\//,/\bnc\s+(?:-[a-z]*e|-[a-z]*c)\b/,/\bmkfifo\b[^;&`]*;\s*(?:nc|ncat|telnet)\b/],md=[/git\s+push/,/npm\s+publish/,/\bHUSKY=0\b/,/\bSKIP_HUSKY=1\b/,/\bSKIP_PREFLIGHT_CHECK=true\b/,/npx\s+.*publish/,/docker\s+rm/,/ssh\s/,/wget\s/,/curl\s.*-o\s/,/pip\s+install/,/npm\s+install\s+-g/],gd=[...La,...md],Ia=!1,Fn=null,Ma=null;function Ew(t){Ia=t}function vw(t){Ma=t}function Tw(){return Ia}function Rw(t){Fn=t}function Cw(t){let e=ao(t);for(let s of Pa)if(s.test(e))return s;return null}function Aw(t){let e=ao(t);if(/ssh\s/.test(e)&&pd(e))return!1;for(let s of gd)if(s.test(e))return!0;return!1}function Ow(t){let e=ao(t);for(let s of La)if(s.test(e))return!0;return!1}function Nw(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=ao(t);if(!Sw.test(e))return null;for(let s of hd)if(s.test(e))return s;return null}function Mw(t,e={}){if(Ia)return Promise.resolve(!0);if(Ma)return Ma(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Pw(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;Fn&&Fn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-s.length-2)},a=()=>{let d=i();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${Xt.yellow}${t}${Xt.reset}`;for(let p=0;p<s.length;p++){let m=p===o,g=m?`${Xt.yellow}\u276F${Xt.reset}`:" ",_=m?`${Xt.yellow}${s[p]}${Xt.reset}`:s[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${_}`}r(f)},l=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),p=i(),m="";for(let g=0;g<s.length+1;g++)m+=`\x1B[${p+g};1H\x1B[2K`;f(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Fn&&Fn.resume(),n(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&Pr(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
63
- `){c(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,a();return}if(f==="\x1B[B"){o=(o+1)%s.length,a();return}let p=f.toLowerCase().trim();if(p==="y"){l(!0);return}if(p==="n"){l(!1);return}if(p==="a"&&e.toolName){Pr(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function Pw(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Pr(e.toolName),n(!0)):n(i!=="n")};if(Fn)Fn.question(`${Xt.yellow}${t} ${s}${Xt.reset}`,o);else{let r=$w.createInterface({input:process.stdin,output:process.stdout});r.question(`${Xt.yellow}${t} ${s}${Xt.reset}`,i=>{r.close(),o(i)})}})}var Pr=()=>{};function Lw(t){Pr=t}yd.exports={sanitizeBashCommand:ao,FORBIDDEN_PATTERNS:Pa,SSH_FORBIDDEN_PATTERNS:fd,BASH_PROTECTED_PATHS:hd,SSH_SAFE_PATTERNS:Na,isSSHReadOnly:pd,DANGEROUS_BASH:gd,CRITICAL_BASH:La,NOTABLE_BASH:md,isForbidden:Cw,isSSHForbidden:xw,isDangerous:Aw,isCritical:Ow,isBashPathForbidden:Nw,confirm:Mw,setAutoConfirm:Ew,getAutoConfirm:Tw,setConfirmHook:vw,setReadlineInterface:Rw,setAllowAlwaysHandler:Lw}});var $d=Z((tR,_d)=>{var Lr=require("path"),{C:B}=Je(),{T:Da,isDark:eR}=Ft(),{confirm:Iw,getAutoConfirm:Dw}=lo(),wd=2e3;function co(t,e){let s=t.split(`
61
+ `)}var{Spinner:bw,MultiProgress:kw,TaskProgress:xw,ToolProgress:Sw,setActiveTaskProgress:Ew,getActiveTaskProgress:vw,cleanupTerminal:Tw}=Os(),{formatToolCall:Rw,formatResult:Cw,getToolSpinnerText:Aw,formatToolSummary:Ow,formatSectionHeader:Nw,formatMilestone:Mw,getThinkingVerb:Pw,setActiveModelForSpinner:Lw}=$d();bd.exports={C:ja,banner:_w,Spinner:bw,MultiProgress:kw,TaskProgress:xw,ToolProgress:Sw,setActiveTaskProgress:Ew,getActiveTaskProgress:vw,cleanupTerminal:Tw,formatToolCall:Rw,formatResult:Cw,getToolSpinnerText:Aw,formatToolSummary:Ow,formatSectionHeader:Nw,formatMilestone:Mw,getThinkingVerb:Pw,setActiveModelForSpinner:Lw}});var qa=V((JR,kd)=>{function Da(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var Iw=Da();function jw(...t){Da()&&console.log(...t)}function Dw(...t){Da()&&console.warn(...t)}kd.exports={DEBUG:Iw,debugLog:jw,warnLog:Dw}});var Ed=V((ZR,Sd)=>{"use strict";var qw=new Set(["read_file","grep","glob","search_files","list_directory"]),Fw=new Set(["write_file","edit_file","patch_file"]),Bw=new Set(["bash"]),Uw=new Set(["web_search","web_fetch","perplexity_search"]);function xd(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,l]of t)i+=l,qw.has(a)&&(s+=l),Fw.has(a)&&(n+=l),Bw.has(a)&&(o+=l),Uw.has(a)&&(r+=l);return i===0?`Phase ${e}`:r/i>.5?"Research":s/i>.5?"Exploration":n/i>.3?"Implementation":o/i>.3&&n/i<.15?"Verification":`Phase ${e}`}var Fa=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,s,n,o){if(this._disabled)return null;this._stepsThisPhase++;for(let i of s)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:xd(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(n),filesModified:new Set(o)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};Sd.exports={MilestoneTracker:Fa,_phaseName:xd}});var Fr=V((QR,vd)=>{var co=lt(),Ww={"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",max_tokens:16384},"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",max_tokens:16384}};function Hw(){return co.getActiveModel()}function Yw(t){return co.setActiveModel(t)}function Gw(){return co.getModelNames()}function zw(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let n=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(n)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let n=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(n)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function Kw(t,e){let{C:s}=tt(),{Spinner:n}=tt(),o=new n("Thinking...");o.start();let r=!0,i="";try{let a=await co.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?o.stop():process.stdout.write(`${s.reset}
62
+ `),a}catch(a){throw o.stop(),a}}async function Xw(t,e){return co.callChat(t,e)}vd.exports={MODELS:Ww,getActiveModel:Hw,setActiveModel:Yw,getModelNames:Gw,callOllamaStream:Kw,callOllama:Xw,parseToolArgs:zw}});var fo=V((e1,Nd)=>{var Vw=require("readline"),{C:en}=tt(),Jw=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,Zw=/^=([\w-]+)/;function uo(t){return typeof t!="string"?t:t.replace(Jw,"").replace(Zw,"$1")}var Wa=[/rm\s+-rf\s+\/(?:\s|$)/,/rm\s+-rf\s+~(?:\/|\s|$)/,/rm\s+-rf\s+\.(?:\/|\s|$)/,/rm\s+-rf\s+\*(?:\s|$)/,/mkfs/,/dd\s+if=/,/:\(\)\s*\{/,/>\/dev\/sd/,/curl.*\|\s*(?:ba)?sh/,/wget.*\|\s*(?:ba)?sh/,/cat\s+.*\.env\b/,/cat\s+.*credentials/i,/chmod\s+777/,/chown\s+root/,/passwd/,/userdel/,/useradd/,/\beval\s*\(/,/base64.*\|.*bash/,/\bprintenv\b/,/cat\s+.*\.ssh\/id_/,/cat\s+.*\.ssh\/config/,/\bnc\s+-[el]/,/\bncat\b/,/\bsocat\b/,/python3?\s+-c\s/,/node\s+-e\s/,/perl\s+-e\s/,/ruby\s+-e\s/,/(?:^|[;&|]\s*)history(?:\s|$)/,/curl.*-X\s*POST/,/curl.*--data/,/\bsed\s+-n\s+['"]?\d+,\d+p/],Td=[...Wa,/\bgrep\b.*\.env\b/,/\bawk\b.*\.env\b/,/\bsed\b.*\.env\b/,/\bhead\b.*\.env\b/,/\btail\b.*\.env\b/,/\bless\b.*\.env\b/,/\bmore\b.*\.env\b/,/\bstrings\b.*\.env\b/,/\bgrep\b.*credentials/i,/\bawk\b.*credentials/i,/\bsed\b.*credentials/i,/\bhead\b.*credentials/i,/\btail\b.*credentials/i,/\bcat\b.*private.*key/i,/\bgrep\b.*private_key/i,/\bcat\b.*google.*\.json/i,/\bcat\b.*service.?account/i];function Qw(t){for(let e of Td)if(e.test(t))return e;return null}var Rd=[/\.env\b/,/credentials\b/i,/\.ssh\b/,/\.gnupg\b/,/\.aws\b/,/\.npmrc\b/,/\.docker\/config/,/\.kube\/config/,/venv\b/,/\.venv\b/,/\.sqlite3\b/,/\.git\/(?!hooks)/],e$=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Ba=[/systemctl\s+(status|is-active|is-enabled|list-units|show)/,/journalctl\b/,/\btail\s/,/\bcat\s/,/\bhead\s/,/\bls\b/,/\bfind\s/,/\bgrep\s/,/\bwc\s/,/\bdf\b/,/\bfree\b/,/\buptime\b/,/\bwho\b/,/\bps\s/,/\bgit\s+(status|log|diff|branch|fetch)\b/,/\bgit\s+pull\b/,/\bss\s+-[tlnp]/,/\bnetstat\s/,/\bdu\s/,/\blscpu\b/,/\bnproc\b/,/\buname\b/,/\bhostname\b/,/\bgetent\b/,/\bid\b/,/psql\s.*-c\s/,/\bmysql\s.*-e\s/,/\bdnf\s+(check-update|list|info|history|repolist|updateinfo)\b/,/\brpm\s+-q/,/\bapt\s+list\b/,/\bopenssl\s+s_client\b/,/\bopenssl\s+x509\b/,/\bcertbot\s+certificates\b/,/\bcurl\s+-[sIkv]|curl\s+--head/,/\bdig\s/,/\bnslookup\s/,/\bping\s/,/\bgetenforce\b/,/\bsesearch\b/,/\bausearch\b/,/\bsealert\b/,/\bcrontab\s+-l\b/,/\btimedatectl\b/,/\bfirewall-cmd\s+--list/,/\bfirewall-cmd\s+--state/];function Cd(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(c=>c.trim()).filter(Boolean).every(c=>o(c)):Ba.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Ba.some(a=>a.test(i))};return n.every(o)}var Ha=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/,/--no-verify\b/,/git\s+reset\s+--hard\b/,/git\s+clean\s+-[a-z]*f/,/git\s+checkout\s+--\s/,/git\s+push\s+(?:--force\b|-f\b)/,/\b(?:curl|wget|fetch)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|ksh|dash|python|python3|perl|ruby|node)\b/,/\b(?:curl|wget)\b[^;&`$()]*\$\([^)]*\)/,/\bbase64\s+(?:-d|--decode|-D)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|python|python3|perl|ruby|node)\b/,/\beval\s+["'`]?\$\(\s*(?:curl|wget|fetch)\b/,/\bbash\s+-i\s*>&?\s*\/dev\/tcp\//,/\bnc\s+(?:-[a-z]*e|-[a-z]*c)\b/,/\bmkfifo\b[^;&`]*;\s*(?:nc|ncat|telnet)\b/],Ad=[/git\s+push/,/npm\s+publish/,/\bHUSKY=0\b/,/\bSKIP_HUSKY=1\b/,/\bSKIP_PREFLIGHT_CHECK=true\b/,/npx\s+.*publish/,/docker\s+rm/,/ssh\s/,/wget\s/,/curl\s.*-o\s/,/pip\s+install/,/npm\s+install\s+-g/],Od=[...Ha,...Ad],Ya=!1,Gn=null,Ua=null;function t$(t){Ya=t}function n$(t){Ua=t}function s$(){return Ya}function o$(t){Gn=t}function r$(t){let e=uo(t);for(let s of Wa)if(s.test(e))return s;return null}function i$(t){let e=uo(t);if(/ssh\s/.test(e)&&Cd(e))return!1;for(let s of Od)if(s.test(e))return!0;return!1}function a$(t){let e=uo(t);for(let s of Ha)if(s.test(e))return!0;return!1}function l$(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=uo(t);if(!e$.test(e))return null;for(let s of Rd)if(s.test(e))return s;return null}function c$(t,e={}){if(Ya)return Promise.resolve(!0);if(Ua)return Ua(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return u$(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;Gn&&Gn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-s.length-2)},a=()=>{let d=i();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${en.yellow}${t}${en.reset}`;for(let p=0;p<s.length;p++){let m=p===o,g=m?`${en.yellow}\u276F${en.reset}`:" ",$=m?`${en.yellow}${s[p]}${en.reset}`:s[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${$}`}r(f)},l=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),p=i(),m="";for(let g=0;g<s.length+1;g++)m+=`\x1B[${p+g};1H\x1B[2K`;f(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Gn&&Gn.resume(),n(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&Br(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
63
+ `){c(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,a();return}if(f==="\x1B[B"){o=(o+1)%s.length,a();return}let p=f.toLowerCase().trim();if(p==="y"){l(!0);return}if(p==="n"){l(!1);return}if(p==="a"&&e.toolName){Br(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function u$(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Br(e.toolName),n(!0)):n(i!=="n")};if(Gn)Gn.question(`${en.yellow}${t} ${s}${en.reset}`,o);else{let r=Vw.createInterface({input:process.stdin,output:process.stdout});r.question(`${en.yellow}${t} ${s}${en.reset}`,i=>{r.close(),o(i)})}})}var Br=()=>{};function d$(t){Br=t}Nd.exports={sanitizeBashCommand:uo,FORBIDDEN_PATTERNS:Wa,SSH_FORBIDDEN_PATTERNS:Td,BASH_PROTECTED_PATHS:Rd,SSH_SAFE_PATTERNS:Ba,isSSHReadOnly:Cd,DANGEROUS_BASH:Od,CRITICAL_BASH:Ha,NOTABLE_BASH:Ad,isForbidden:r$,isSSHForbidden:Qw,isDangerous:i$,isCritical:a$,isBashPathForbidden:l$,confirm:c$,setAutoConfirm:t$,getAutoConfirm:s$,setConfirmHook:n$,setReadlineInterface:o$,setAllowAlwaysHandler:d$}});var Ld=V((n1,Pd)=>{var Ur=require("path"),{C:U}=tt(),{T:Ga,isDark:t1}=Ht(),{confirm:f$,getAutoConfirm:p$}=fo(),Md=2e3;function po(t,e){let s=t.split(`
64
64
  `),n=e.split(`
65
- `),o=[],r=s.length,i=n.length;if(r>wd||i>wd){for(let d of s)o.push({type:"remove",line:d});for(let d of n)o.push({type:"add",line:d});return o}let a=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let d=1;d<=r;d++)for(let f=1;f<=i;f++)s[d-1]===n[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let l=r,c=i,u=[];for(;l>0||c>0;)l>0&&c>0&&s[l-1]===n[c-1]?(u.unshift({type:"same",line:s[l-1]}),l--,c--):c>0&&(l===0||a[l][c-1]>=a[l-1][c])?(u.unshift({type:"add",line:n[c-1]}),c--):(u.unshift({type:"remove",line:s[l-1]}),l--);return u}function jw(t,e,s,n=3){console.log(`
66
- ${B.bold}${B.cyan} Diff: ${t}${B.reset}`);let o=co(e,s),r=[];if(o.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${B.gray} (no changes)${B.reset}`);return}let i=Math.max(0,r[0]-n),a=Math.min(o.length,r[r.length-1]+n+1);i>0&&console.log(`${B.gray} ...${B.reset}`);for(let l=i;l<a;l++){let c=o[l];switch(c.type){case"remove":console.log(`${B.red} - ${c.line}${B.reset}`);break;case"add":console.log(`${B.green} + ${c.line}${B.reset}`);break;default:console.log(`${B.gray} ${c.line}${B.reset}`)}}a<o.length&&console.log(`${B.gray} ...${B.reset}`),console.log()}function qw(t,e,s){console.log(`
67
- ${B.bold}${B.cyan} File exists \u2014 showing changes: ${t}${B.reset}`);let n=co(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${B.gray} (identical content)${B.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${B.gray} ...(${o-r} more changes)${B.reset}`);break}switch(i.type){case"remove":console.log(`${B.red} - ${i.line}${B.reset}`),r++;break;case"add":console.log(`${B.green} + ${i.line}${B.reset}`),r++;break;default:r>0&&console.log(`${B.gray} ${i.line}${B.reset}`)}}console.log()}function Fw(t,e){console.log(`
68
- ${B.bold}${B.cyan} New file: ${t}${B.reset}`);let s=e.split(`
69
- `),n=s.slice(0,20);for(let o of n)console.log(`${B.green} + ${o}${B.reset}`);s.length>20&&console.log(`${B.gray} ...+${s.length-20} more lines${B.reset}`),console.log()}async function Bw(t){return Dw()?!0:Iw(` ${t}?`)}function Uw(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
70
- ${B.bold}${B.cyan} Side-by-side: ${t}${B.reset}`),console.log(` ${B.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${B.reset}`);let i=co(e,s),a=[],l=0;for(;l<i.length;)if(i[l].type==="same")a.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let p=[];for(;l<i.length&&i[l].type==="remove";)p.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(p.length,m.length);for(let _=0;_<g;_++)a.push({left:_<p.length?p[_]:"",right:_<m.length?m[_]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let c=a.map((p,m)=>p.type!=="same"?m:-1).filter(p=>p>=0);if(c.length===0){console.log(` ${B.gray}(no changes)${B.reset}`);return}let u=Math.max(0,c[0]-2),d=Math.min(a.length,c[c.length-1]+3),f=(p,m)=>{let g=p.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?p.substring(0,m):p+" ".repeat(m-g.length)};u>0&&console.log(` ${B.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${B.reset}`);for(let p=u;p<d;p++){let m=a[p];if(m.type==="same")console.log(` ${B.gray}${f(m.left,r)}${B.reset}\u2502${B.gray}${f(m.right,r)}${B.reset}`);else{let g=m.left?`${B.red}${f(m.left,r)}${B.reset}`:`${f("",r)}`,_=m.right?`${B.green}${f(m.right,r)}${B.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${_}`)}}d<a.length&&console.log(` ${B.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${B.reset}`),console.log(` ${B.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${B.reset}
71
- `)}function Ww(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=Lr.isAbsolute(t)?Lr.relative(process.cwd(),t):t,l=co(e,s),c=1,u=1;for(let N of l)N.type==="same"?(N.oldLine=c++,N.newLine=u++):N.type==="remove"?(N.oldLine=c++,N.newLine=null):(N.oldLine=null,N.newLine=u++);let d=0,f=0;for(let N of l)N.type==="add"?d++:N.type==="remove"&&f++;if(console.log(`
72
- ${B.green}\u23FA${B.reset} ${B.bold}${o}(${a})${B.reset}`),d===0&&f===0){console.log(` ${B.dim}\u23BF (no changes)${B.reset}
73
- `);return}let p=[];if(d>0&&p.push(`Added ${d} line${d!==1?"s":""}`),f>0&&p.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let N=i.filter(le=>le.severity==="error").length,te=i.filter(le=>le.severity==="warn").length,V=i.filter(le=>le.severity==="info").length,re=[];N>0&&re.push(`${B.red}${N} error${N!==1?"s":""}${B.dim}`),te>0&&re.push(`${B.yellow}${te} warning${te!==1?"s":""}${B.dim}`),V>0&&re.push(`${B.cyan}${V} info${V!==1?"s":""}${B.dim}`),p.push(`found ${re.join(", ")}`)}console.log(` ${B.dim}\u23BF ${p.join(", ")}${B.reset}`);let g=[];l.forEach((N,te)=>{N.type!=="same"&&g.push(te)});let _=[],k=null,A=null;for(let N of g){let te=Math.max(0,N-r),V=Math.min(l.length-1,N+r);k===null?(k=te,A=V):(te<=A+1||(_.push([k,A]),k=te),A=V)}k!==null&&_.push([k,A]);let L=" ",E=process.stdout.columns||120;function v(N,te,V){let re=V.replace(/\x1b\[[0-9;]*m/g,""),le=V+" ".repeat(Math.max(0,E-re.length));return`${N}${te}${le}${B.reset}`}for(let N=0;N<_.length;N++){N>0&&console.log(`${L}${B.dim}\xB7\xB7\xB7${B.reset}`);let[te,V]=_[N];for(let re=te;re<=V;re++){let le=l[re],ne=le.newLine!=null?le.newLine:le.oldLine,S=String(ne).padStart(4),Ee=le.type!=="remove"?i.filter(W=>W.line===le.newLine):[];le.type==="remove"?console.log(v(Da.diff_rem_bg,B.red,`${L}${S} - ${le.line}`)):le.type==="add"?console.log(v(Da.diff_add_bg,B.green,`${L}${S} + ${le.line}`)):console.log(`${L}${B.dim}${S} ${B.reset}${le.line}`);for(let W of Ee){let J=B.cyan,he="\u2139";W.severity==="error"?(J=B.red,he="\u2716"):W.severity==="warn"&&(J=B.yellow,he="\u26A0"),console.log(`${L} ${J}${he} ${W.message}${B.reset}`)}}}console.log()}function Hw(t,e,s={}){let n=Lr.isAbsolute(t)?Lr.relative(process.cwd(),t):t,o=e.split(`
65
+ `),o=[],r=s.length,i=n.length;if(r>Md||i>Md){for(let d of s)o.push({type:"remove",line:d});for(let d of n)o.push({type:"add",line:d});return o}let a=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let d=1;d<=r;d++)for(let f=1;f<=i;f++)s[d-1]===n[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let l=r,c=i,u=[];for(;l>0||c>0;)l>0&&c>0&&s[l-1]===n[c-1]?(u.unshift({type:"same",line:s[l-1]}),l--,c--):c>0&&(l===0||a[l][c-1]>=a[l-1][c])?(u.unshift({type:"add",line:n[c-1]}),c--):(u.unshift({type:"remove",line:s[l-1]}),l--);return u}function h$(t,e,s,n=3){console.log(`
66
+ ${U.bold}${U.cyan} Diff: ${t}${U.reset}`);let o=po(e,s),r=[];if(o.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${U.gray} (no changes)${U.reset}`);return}let i=Math.max(0,r[0]-n),a=Math.min(o.length,r[r.length-1]+n+1);i>0&&console.log(`${U.gray} ...${U.reset}`);for(let l=i;l<a;l++){let c=o[l];switch(c.type){case"remove":console.log(`${U.red} - ${c.line}${U.reset}`);break;case"add":console.log(`${U.green} + ${c.line}${U.reset}`);break;default:console.log(`${U.gray} ${c.line}${U.reset}`)}}a<o.length&&console.log(`${U.gray} ...${U.reset}`),console.log()}function m$(t,e,s){console.log(`
67
+ ${U.bold}${U.cyan} File exists \u2014 showing changes: ${t}${U.reset}`);let n=po(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${U.gray} (identical content)${U.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${U.gray} ...(${o-r} more changes)${U.reset}`);break}switch(i.type){case"remove":console.log(`${U.red} - ${i.line}${U.reset}`),r++;break;case"add":console.log(`${U.green} + ${i.line}${U.reset}`),r++;break;default:r>0&&console.log(`${U.gray} ${i.line}${U.reset}`)}}console.log()}function g$(t,e){console.log(`
68
+ ${U.bold}${U.cyan} New file: ${t}${U.reset}`);let s=e.split(`
69
+ `),n=s.slice(0,20);for(let o of n)console.log(`${U.green} + ${o}${U.reset}`);s.length>20&&console.log(`${U.gray} ...+${s.length-20} more lines${U.reset}`),console.log()}async function y$(t){return p$()?!0:f$(` ${t}?`)}function w$(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
70
+ ${U.bold}${U.cyan} Side-by-side: ${t}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${U.reset}`);let i=po(e,s),a=[],l=0;for(;l<i.length;)if(i[l].type==="same")a.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let p=[];for(;l<i.length&&i[l].type==="remove";)p.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(p.length,m.length);for(let $=0;$<g;$++)a.push({left:$<p.length?p[$]:"",right:$<m.length?m[$]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let c=a.map((p,m)=>p.type!=="same"?m:-1).filter(p=>p>=0);if(c.length===0){console.log(` ${U.gray}(no changes)${U.reset}`);return}let u=Math.max(0,c[0]-2),d=Math.min(a.length,c[c.length-1]+3),f=(p,m)=>{let g=p.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?p.substring(0,m):p+" ".repeat(m-g.length)};u>0&&console.log(` ${U.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${U.reset}`);for(let p=u;p<d;p++){let m=a[p];if(m.type==="same")console.log(` ${U.gray}${f(m.left,r)}${U.reset}\u2502${U.gray}${f(m.right,r)}${U.reset}`);else{let g=m.left?`${U.red}${f(m.left,r)}${U.reset}`:`${f("",r)}`,$=m.right?`${U.green}${f(m.right,r)}${U.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${$}`)}}d<a.length&&console.log(` ${U.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${U.reset}
71
+ `)}function $$(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=Ur.isAbsolute(t)?Ur.relative(process.cwd(),t):t,l=po(e,s),c=1,u=1;for(let A of l)A.type==="same"?(A.oldLine=c++,A.newLine=u++):A.type==="remove"?(A.oldLine=c++,A.newLine=null):(A.oldLine=null,A.newLine=u++);let d=0,f=0;for(let A of l)A.type==="add"?d++:A.type==="remove"&&f++;if(console.log(`
72
+ ${U.green}\u23FA${U.reset} ${U.bold}${o}(${a})${U.reset}`),d===0&&f===0){console.log(` ${U.dim}\u23BF (no changes)${U.reset}
73
+ `);return}let p=[];if(d>0&&p.push(`Added ${d} line${d!==1?"s":""}`),f>0&&p.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let A=i.filter(ae=>ae.severity==="error").length,ee=i.filter(ae=>ae.severity==="warn").length,se=i.filter(ae=>ae.severity==="info").length,ue=[];A>0&&ue.push(`${U.red}${A} error${A!==1?"s":""}${U.dim}`),ee>0&&ue.push(`${U.yellow}${ee} warning${ee!==1?"s":""}${U.dim}`),se>0&&ue.push(`${U.cyan}${se} info${se!==1?"s":""}${U.dim}`),p.push(`found ${ue.join(", ")}`)}console.log(` ${U.dim}\u23BF ${p.join(", ")}${U.reset}`);let g=[];l.forEach((A,ee)=>{A.type!=="same"&&g.push(ee)});let $=[],k=null,M=null;for(let A of g){let ee=Math.max(0,A-r),se=Math.min(l.length-1,A+r);k===null?(k=ee,M=se):(ee<=M+1||($.push([k,M]),k=ee),M=se)}k!==null&&$.push([k,M]);let D=" ",v=process.stdout.columns||120;function E(A,ee,se){let ue=se.replace(/\x1b\[[0-9;]*m/g,""),ae=se+" ".repeat(Math.max(0,v-ue.length));return`${A}${ee}${ae}${U.reset}`}for(let A=0;A<$.length;A++){A>0&&console.log(`${D}${U.dim}\xB7\xB7\xB7${U.reset}`);let[ee,se]=$[A];for(let ue=ee;ue<=se;ue++){let ae=l[ue],te=ae.newLine!=null?ae.newLine:ae.oldLine,S=String(te).padStart(4),ve=ae.type!=="remove"?i.filter(W=>W.line===ae.newLine):[];ae.type==="remove"?console.log(E(Ga.diff_rem_bg,U.red,`${D}${S} - ${ae.line}`)):ae.type==="add"?console.log(E(Ga.diff_add_bg,U.green,`${D}${S} + ${ae.line}`)):console.log(`${D}${U.dim}${S} ${U.reset}${ae.line}`);for(let W of ve){let z=U.cyan,me="\u2139";W.severity==="error"?(z=U.red,me="\u2716"):W.severity==="warn"&&(z=U.yellow,me="\u26A0"),console.log(`${D} ${z}${me} ${W.message}${U.reset}`)}}}console.log()}function _$(t,e,s={}){let n=Ur.isAbsolute(t)?Ur.relative(process.cwd(),t):t,o=e.split(`
74
74
  `),r=s.annotations||[];console.log(`
75
- ${B.green}\u23FA${B.reset} ${B.bold}Create(${n})${B.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(g=>g.severity==="error").length,f=r.filter(g=>g.severity==="warn").length,p=r.filter(g=>g.severity==="info").length,m=[];d>0&&m.push(`${B.red}${d} error${d!==1?"s":""}${B.dim}`),f>0&&m.push(`${B.yellow}${f} warning${f!==1?"s":""}${B.dim}`),p>0&&m.push(`${B.cyan}${p} info${p!==1?"s":""}${B.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${B.dim}\u23BF ${i.join(", ")}${B.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),p=d+1,m=r.filter(A=>A.line===p),g=`${l}${f} + ${o[d]}`,_=g.replace(/\x1b\[[0-9;]*m/g,""),k=g+" ".repeat(Math.max(0,c-_.length));console.log(`${Da.diff_add_bg}${B.green}${k}${B.reset}`);for(let A of m){let L=B.cyan,E="\u2139";A.severity==="error"?(L=B.red,E="\u2716"):A.severity==="warn"&&(L=B.yellow,E="\u26A0"),console.log(`${l} ${L}${E} ${A.message}${B.reset}`)}}o.length>20&&console.log(`${l}${B.dim} ...+${o.length-20} more lines${B.reset}`),console.log()}_d.exports={diffLines:co,showEditDiff:jw,showWriteDiff:qw,showNewFilePreview:Fw,confirmFileChange:Bw,showSideBySideDiff:Uw,showDiff:Ww,showNewFile:Hw}});var jr=Z((nR,xd)=>{var bd=require("util").promisify(require("child_process").exec),Yw=require("util").promisify(require("child_process").execFile),{C:Ie}=Je();async function ja(t){try{let{stdout:e}=await bd(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Ir(...t){try{let{stdout:e}=await Yw("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Gw(){return await ja("git rev-parse --is-inside-work-tree")==="true"}async function zw(){return await ja("git branch --show-current")}async function qa(){try{let{stdout:t}=await bd("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
76
- `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Dr(t=!1){return await ja(`git diff ${t?"--cached":""}`)||""}async function Fa(){return(await qa()).map(e=>e.file)}async function kd(){let t=await Fa();if(t.length===0)return null;let e=await Dr(),n=await Dr(!0)||e,o=0,r=0;if(n){let u=n.split(`
77
- `);for(let d of u)d.startsWith("+")&&!d.startsWith("+++")&&o++,d.startsWith("-")&&!d.startsWith("---")&&r++}else o=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let l=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function Kw(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Ir("checkout","-b",s)!==null?s:null}async function Xw(t){return await Ir("add","-A"),await Ir("commit","-m",t)?await Ir("rev-parse","--short","HEAD"):null}async function Vw(){let t=await kd();if(!t)return`${Ie.dim}No changes${Ie.reset}`;let e=[];e.push(`
78
- ${Ie.bold}${Ie.cyan}Git Diff Summary:${Ie.reset}`),e.push(` ${Ie.green}+${t.stats.additions}${Ie.reset} ${Ie.red}-${t.stats.deletions}${Ie.reset} in ${t.files.length} file(s)`),e.push(`
79
- ${Ie.bold}${Ie.cyan}Files:${Ie.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Ie.dim}${s}${Ie.reset}`);return t.files.length>20&&e.push(` ${Ie.dim}...+${t.files.length-20} more${Ie.reset}`),e.push(`
80
- ${Ie.bold}${Ie.cyan}Suggested message:${Ie.reset}`),e.push(` ${Ie.cyan}${t.summary}${Ie.reset}
75
+ ${U.green}\u23FA${U.reset} ${U.bold}Create(${n})${U.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(g=>g.severity==="error").length,f=r.filter(g=>g.severity==="warn").length,p=r.filter(g=>g.severity==="info").length,m=[];d>0&&m.push(`${U.red}${d} error${d!==1?"s":""}${U.dim}`),f>0&&m.push(`${U.yellow}${f} warning${f!==1?"s":""}${U.dim}`),p>0&&m.push(`${U.cyan}${p} info${p!==1?"s":""}${U.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${U.dim}\u23BF ${i.join(", ")}${U.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),p=d+1,m=r.filter(M=>M.line===p),g=`${l}${f} + ${o[d]}`,$=g.replace(/\x1b\[[0-9;]*m/g,""),k=g+" ".repeat(Math.max(0,c-$.length));console.log(`${Ga.diff_add_bg}${U.green}${k}${U.reset}`);for(let M of m){let D=U.cyan,v="\u2139";M.severity==="error"?(D=U.red,v="\u2716"):M.severity==="warn"&&(D=U.yellow,v="\u26A0"),console.log(`${l} ${D}${v} ${M.message}${U.reset}`)}}o.length>20&&console.log(`${l}${U.dim} ...+${o.length-20} more lines${U.reset}`),console.log()}Pd.exports={diffLines:po,showEditDiff:h$,showWriteDiff:m$,showNewFilePreview:g$,confirmFileChange:y$,showSideBySideDiff:w$,showDiff:$$,showNewFile:_$}});var Yr=V((s1,Dd)=>{var Id=require("util").promisify(require("child_process").exec),b$=require("util").promisify(require("child_process").execFile),{C:qe}=tt();async function za(t){try{let{stdout:e}=await Id(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Wr(...t){try{let{stdout:e}=await b$("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function k$(){return await za("git rev-parse --is-inside-work-tree")==="true"}async function x$(){return await za("git branch --show-current")}async function Ka(){try{let{stdout:t}=await Id("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
76
+ `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Hr(t=!1){return await za(`git diff ${t?"--cached":""}`)||""}async function Xa(){return(await Ka()).map(e=>e.file)}async function jd(){let t=await Xa();if(t.length===0)return null;let e=await Hr(),n=await Hr(!0)||e,o=0,r=0;if(n){let u=n.split(`
77
+ `);for(let d of u)d.startsWith("+")&&!d.startsWith("+++")&&o++,d.startsWith("-")&&!d.startsWith("---")&&r++}else o=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let l=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function S$(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Wr("checkout","-b",s)!==null?s:null}async function E$(t){return await Wr("add","-A"),await Wr("commit","-m",t)?await Wr("rev-parse","--short","HEAD"):null}async function v$(){let t=await jd();if(!t)return`${qe.dim}No changes${qe.reset}`;let e=[];e.push(`
78
+ ${qe.bold}${qe.cyan}Git Diff Summary:${qe.reset}`),e.push(` ${qe.green}+${t.stats.additions}${qe.reset} ${qe.red}-${t.stats.deletions}${qe.reset} in ${t.files.length} file(s)`),e.push(`
79
+ ${qe.bold}${qe.cyan}Files:${qe.reset}`);for(let s of t.files.slice(0,20))e.push(` ${qe.dim}${s}${qe.reset}`);return t.files.length>20&&e.push(` ${qe.dim}...+${t.files.length-20} more${qe.reset}`),e.push(`
80
+ ${qe.bold}${qe.cyan}Suggested message:${qe.reset}`),e.push(` ${qe.cyan}${t.summary}${qe.reset}
81
81
  `),e.join(`
82
- `)}async function Jw(){return(await qa()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Zw(){let t=await Fa();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let s=await Dr();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
82
+ `)}async function T$(){return(await Ka()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function R$(){let t=await Xa();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let s=await Hr();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
83
83
  ...(truncated)`:s;e.push(`
84
84
  DIFF:
85
85
  ${n}`)}return e.join(`
86
- `)}xd.exports={isGitRepo:Gw,getCurrentBranch:zw,getStatus:qa,getDiff:Dr,getChangedFiles:Fa,analyzeDiff:kd,createBranch:Kw,commit:Xw,formatDiffSummary:Vw,getDiffContext:Zw,getMergeConflicts:Jw}});var Od=Z((oR,Ad)=>{var Ze=require("fs").promises,sR=require("fs"),Ot=require("path"),Qw=require("crypto"),{execSync:Ba,execFileSync:vd}=require("child_process"),e_=100*1024,Td=50,gt=[],Ts=[];function t_(t,e,s,n){for(gt.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});gt.length>Td;)gt.shift();Ts.length=0,Rd(gt[gt.length-1]).catch(()=>{})}async function n_(){if(gt.length===0)return null;let t=gt.pop();if(t.oldContent===null)try{await Ze.unlink(t.filePath)}catch{}else await Ze.writeFile(t.filePath,t.oldContent,"utf-8");return Ts.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function s_(){if(Ts.length===0)return null;let t=Ts.pop();return await Ze.writeFile(t.filePath,t.newContent,"utf-8"),gt.push(t),{tool:t.tool,filePath:t.filePath}}function o_(t=10){return gt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function r_(){return gt.length}function i_(){return Ts.length}function a_({diskToo:t=!0}={}){if(gt.length=0,Ts.length=0,t){let e=Fr();Ze.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&Ze.unlink(Ot.join(e,n)).catch(()=>{})}).catch(()=>{})}}function Fr(){return Ot.join(process.cwd(),".nex","history")}async function Sd(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=e_)return{inline:!0,content:t};let s=Qw.createHash("sha256").update(t,"utf-8").digest("hex"),n=Ot.join(e,"blobs");return await Ze.mkdir(n,{recursive:!0}),await Ze.writeFile(Ot.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function Rd(t){let e=Fr();await Ze.mkdir(e,{recursive:!0});let s=Ot.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await Sd(t.oldContent,e),r=await Sd(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:o.inline?{inline:!0,content:o.content}:{inline:!1,hash:o.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await Ze.writeFile(Ot.join(e,n),JSON.stringify(i),"utf-8")}async function Ed(t,e){if(!t)return null;if(t.inline)return t.content;let s=Ot.join(e,"blobs",t.hash);return Ze.readFile(s,"utf-8")}async function l_(){let t=Fr(),e;try{e=await Ze.readdir(t)}catch{return 0}let s=e.filter(o=>o.endsWith(".json")).sort(),n=0;for(let o of s)try{let r=await Ze.readFile(Ot.join(t,o),"utf-8"),i=JSON.parse(r),a=await Ed(i.oldContent,t),l=await Ed(i.newContent,t);gt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),n++}catch{}for(;gt.length>Td;)gt.shift();return n}async function c_(t=7){let e=Fr(),s;try{s=await Ze.readdir(e)}catch{return 0}let n=Date.now()-t*24*60*60*1e3,o=s.filter(c=>c.endsWith(".json")),r=0,i=new Set,a=[];for(let c of o)try{let u=await Ze.readFile(Ot.join(e,c),"utf-8"),d=JSON.parse(u);d.timestamp<n?(a.push(c),r++):(d.oldContent&&!d.oldContent.inline&&d.oldContent.hash&&i.add(d.oldContent.hash),d.newContent&&!d.newContent.inline&&d.newContent.hash&&i.add(d.newContent.hash))}catch{}for(let c of a)try{await Ze.unlink(Ot.join(e,c))}catch{}let l=Ot.join(e,"blobs");try{let c=await Ze.readdir(l);for(let u of c)if(!i.has(u))try{await Ze.unlink(Ot.join(l,u))}catch{}}catch{}return r}var qr="nex-snapshot";function u_(t,e=process.cwd()){let s=t?`${qr}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${qr}-${Date.now()}`;try{return Ba("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(vd("git",["stash","push","-u","-m",s],{cwd:e,timeout:15e3}),Ba("git stash pop",{cwd:e,timeout:1e4}),{name:s,label:s,ok:!0}):{name:s,label:s,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(n){return{name:s,label:s,ok:!1,error:n.message}}}function Cd(t=process.cwd()){try{let e=Ba("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
87
- `).map(s=>{let n=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!n)return null;let o=n[2].trim();return o.startsWith(qr)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${qr}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function d_(t,e=process.cwd()){try{let s=Cd(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let n;return t===void 0||t==="last"?n=s[0]:typeof t=="number"?n=s.find(o=>o.index===t):n=s.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),n?(vd("git",["stash","apply",`stash@{${n.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:n.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}Ad.exports={recordChange:t_,undo:n_,redo:s_,getHistory:o_,getUndoCount:r_,getRedoCount:i_,clearHistory:a_,persistEntry:Rd,loadPersistedHistory:l_,pruneHistory:c_,createSnapshot:u_,listSnapshots:Cd,restoreSnapshot:d_}});var Ga=Z((rR,Dd)=>{var Ne=require("fs"),yt=require("path"),{atomicWrite:f_,withFileLockSync:h_}=jn(),ct=[];function uo(){return yt.join(process.cwd(),".nex","skills")}function Nd(){return yt.join(process.cwd(),".nex","config.json")}function Md(){let t=uo();return Ne.existsSync(t)||Ne.mkdirSync(t,{recursive:!0}),t}function Ha(){let t=Nd();if(!Ne.existsSync(t))return[];try{let e=JSON.parse(Ne.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Pd(t){let e=Nd(),s=yt.dirname(e);Ne.existsSync(s)||Ne.mkdirSync(s,{recursive:!0}),h_(e,()=>{let n={};if(Ne.existsSync(e))try{n=JSON.parse(Ne.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t,f_(e,JSON.stringify(n,null,2))})}function Ld(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let o=t.commands[n];(!o.cmd||typeof o.cmd!="string")&&s.push(`commands[${n}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&s.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let o=t.tools[n];(!o.function||!o.function.name||typeof o.function.name!="string")&&s.push(`tools[${n}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&s.push(`tools[${n}].execute must be a function`)}return{valid:s.length===0,errors:s}}function Id(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let s=e[1],n=e[2].trim(),o=[],r=!1;for(let i of s.split(`
88
- `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:n}}function Ua(t){try{let e=Ne.readFileSync(t,"utf-8").trim();if(!e)return null;let s=yt.basename(t,".md"),{triggers:n,body:o}=Id(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function Wa(t){try{let e=require(t),{valid:s,errors:n}=Ld(e,t);return s?{name:e.name||yt.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
86
+ `)}Dd.exports={isGitRepo:k$,getCurrentBranch:x$,getStatus:Ka,getDiff:Hr,getChangedFiles:Xa,analyzeDiff:jd,createBranch:S$,commit:E$,formatDiffSummary:v$,getDiffContext:R$,getMergeConflicts:T$}});var Gd=V((r1,Yd)=>{var nt=require("fs").promises,o1=require("fs"),Lt=require("path"),C$=require("crypto"),{execSync:Va,execFileSync:Bd}=require("child_process"),A$=100*1024,Ud=50,$t=[],Ns=[];function O$(t,e,s,n){for($t.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});$t.length>Ud;)$t.shift();Ns.length=0,Wd($t[$t.length-1]).catch(()=>{})}async function N$(){if($t.length===0)return null;let t=$t.pop();if(t.oldContent===null)try{await nt.unlink(t.filePath)}catch{}else await nt.writeFile(t.filePath,t.oldContent,"utf-8");return Ns.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function M$(){if(Ns.length===0)return null;let t=Ns.pop();return await nt.writeFile(t.filePath,t.newContent,"utf-8"),$t.push(t),{tool:t.tool,filePath:t.filePath}}function P$(t=10){return $t.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function L$(){return $t.length}function I$(){return Ns.length}function j$({diskToo:t=!0}={}){if($t.length=0,Ns.length=0,t){let e=zr();nt.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&nt.unlink(Lt.join(e,n)).catch(()=>{})}).catch(()=>{})}}function zr(){return Lt.join(process.cwd(),".nex","history")}async function qd(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=A$)return{inline:!0,content:t};let s=C$.createHash("sha256").update(t,"utf-8").digest("hex"),n=Lt.join(e,"blobs");return await nt.mkdir(n,{recursive:!0}),await nt.writeFile(Lt.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function Wd(t){let e=zr();await nt.mkdir(e,{recursive:!0});let s=Lt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await qd(t.oldContent,e),r=await qd(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:o.inline?{inline:!0,content:o.content}:{inline:!1,hash:o.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await nt.writeFile(Lt.join(e,n),JSON.stringify(i),"utf-8")}async function Fd(t,e){if(!t)return null;if(t.inline)return t.content;let s=Lt.join(e,"blobs",t.hash);return nt.readFile(s,"utf-8")}async function D$(){let t=zr(),e;try{e=await nt.readdir(t)}catch{return 0}let s=e.filter(o=>o.endsWith(".json")).sort(),n=0;for(let o of s)try{let r=await nt.readFile(Lt.join(t,o),"utf-8"),i=JSON.parse(r),a=await Fd(i.oldContent,t),l=await Fd(i.newContent,t);$t.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),n++}catch{}for(;$t.length>Ud;)$t.shift();return n}async function q$(t=7){let e=zr(),s;try{s=await nt.readdir(e)}catch{return 0}let n=Date.now()-t*24*60*60*1e3,o=s.filter(c=>c.endsWith(".json")),r=0,i=new Set,a=[];for(let c of o)try{let u=await nt.readFile(Lt.join(e,c),"utf-8"),d=JSON.parse(u);d.timestamp<n?(a.push(c),r++):(d.oldContent&&!d.oldContent.inline&&d.oldContent.hash&&i.add(d.oldContent.hash),d.newContent&&!d.newContent.inline&&d.newContent.hash&&i.add(d.newContent.hash))}catch{}for(let c of a)try{await nt.unlink(Lt.join(e,c))}catch{}let l=Lt.join(e,"blobs");try{let c=await nt.readdir(l);for(let u of c)if(!i.has(u))try{await nt.unlink(Lt.join(l,u))}catch{}}catch{}return r}var Gr="nex-snapshot";function F$(t,e=process.cwd()){let s=t?`${Gr}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Gr}-${Date.now()}`;try{return Va("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Bd("git",["stash","push","-u","-m",s],{cwd:e,timeout:15e3}),Va("git stash pop",{cwd:e,timeout:1e4}),{name:s,label:s,ok:!0}):{name:s,label:s,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(n){return{name:s,label:s,ok:!1,error:n.message}}}function Hd(t=process.cwd()){try{let e=Va("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
87
+ `).map(s=>{let n=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!n)return null;let o=n[2].trim();return o.startsWith(Gr)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${Gr}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function B$(t,e=process.cwd()){try{let s=Hd(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let n;return t===void 0||t==="last"?n=s[0]:typeof t=="number"?n=s.find(o=>o.index===t):n=s.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),n?(Bd("git",["stash","apply",`stash@{${n.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:n.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}Yd.exports={recordChange:O$,undo:N$,redo:M$,getHistory:P$,getUndoCount:L$,getRedoCount:I$,clearHistory:j$,persistEntry:Wd,loadPersistedHistory:D$,pruneHistory:q$,createSnapshot:F$,listSnapshots:Hd,restoreSnapshot:B$}});var tl=V((i1,Zd)=>{var Pe=require("fs"),_t=require("path"),{atomicWrite:U$,withFileLockSync:W$}=Hn(),ft=[];function ho(){return _t.join(process.cwd(),".nex","skills")}function zd(){return _t.join(process.cwd(),".nex","config.json")}function Kd(){let t=ho();return Pe.existsSync(t)||Pe.mkdirSync(t,{recursive:!0}),t}function Qa(){let t=zd();if(!Pe.existsSync(t))return[];try{let e=JSON.parse(Pe.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Xd(t){let e=zd(),s=_t.dirname(e);Pe.existsSync(s)||Pe.mkdirSync(s,{recursive:!0}),W$(e,()=>{let n={};if(Pe.existsSync(e))try{n=JSON.parse(Pe.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t,U$(e,JSON.stringify(n,null,2))})}function Vd(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let o=t.commands[n];(!o.cmd||typeof o.cmd!="string")&&s.push(`commands[${n}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&s.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let o=t.tools[n];(!o.function||!o.function.name||typeof o.function.name!="string")&&s.push(`tools[${n}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&s.push(`tools[${n}].execute must be a function`)}return{valid:s.length===0,errors:s}}function Jd(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let s=e[1],n=e[2].trim(),o=[],r=!1;for(let i of s.split(`
88
+ `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:n}}function Ja(t){try{let e=Pe.readFileSync(t,"utf-8").trim();if(!e)return null;let s=_t.basename(t,".md"),{triggers:n,body:o}=Jd(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function Za(t){try{let e=require(t),{valid:s,errors:n}=Vd(e,t);return s?{name:e.name||_t.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
89
89
  ${n.join(`
90
- `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Ya(){ct=[];let t=Ha(),e=uo(),s=[];if(Ne.existsSync(e))try{s=Ne.readdirSync(e)}catch{s=[]}for(let o of s){let r=yt.join(e,o),i;try{i=Ne.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=Ua(r):o.endsWith(".js")&&(a=Wa(r)),a&&(a.enabled=!t.includes(a.name),ct.push(a))}let n=yt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ne.existsSync(n)){let o;try{o=Ne.readdirSync(n).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=yt.join(n,r),a=yt.basename(r,yt.extname(r));if(ct.some(u=>u.name===a))continue;let l;try{l=Ne.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?Ua(i):Wa(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),ct.push(c))}}return ct}function p_(){let t=[];for(let e of ct)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
90
+ `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function el(){ft=[];let t=Qa(),e=ho(),s=[];if(Pe.existsSync(e))try{s=Pe.readdirSync(e)}catch{s=[]}for(let o of s){let r=_t.join(e,o),i;try{i=Pe.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=Ja(r):o.endsWith(".js")&&(a=Za(r)),a&&(a.enabled=!t.includes(a.name),ft.push(a))}let n=_t.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Pe.existsSync(n)){let o;try{o=Pe.readdirSync(n).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=_t.join(n,r),a=_t.basename(r,_t.extname(r));if(ft.some(u=>u.name===a))continue;let l;try{l=Pe.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?Ja(i):Za(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),ft.push(c))}}return ft}function H$(){let t=[];for(let e of ft)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
91
91
  ${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
92
92
  ${t.join(`
93
93
 
94
- `)}`}function m_(){let t=[];for(let e of ct)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function g_(){let t=[];for(let e of ct)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function y_(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of ct)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function w_(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of ct)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(n);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function __(){return ct.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function $_(t){let e=ct.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Ha().filter(n=>n!==t);return Pd(s),!0}function b_(t){let e=ct.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Ha();return s.includes(t)||(s.push(t),Pd(s)),!0}function k_(){return ct}async function x_(t,e={}){let{execFileSync:s}=require("child_process"),n=Md(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||yt.basename(o,".git").replace(/^nex-skill-/,""),i=yt.join(n,r);if(Ne.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(o))throw new Error(`Invalid git URL: ${o}`);s("git",["clone","--depth","1",o,i],{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=yt.join(i,"skill.json"),l=Ne.existsSync(a),c=Ne.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{Ne.rmSync(i,{recursive:!0,force:!0})}catch(u){console.error("skills.js line 562 failed:",u.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let u=JSON.parse(Ne.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Ne.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Ya(),{ok:!0,name:r}}async function S_(t){let e=require("axios");try{let s=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${s}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(o=>({name:o.name.replace(/^nex-skill-/,""),description:o.description||"(no description)",url:o.clone_url,stars:o.stargazers_count,owner:o.owner.login}))}catch(s){return[{name:"error",description:`Search failed: ${s.message}`,url:"",stars:0,owner:""}]}}function E_(t){let e=yt.join(uo(),t);if(!Ne.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${uo()}`};try{return Ne.rmSync(e,{recursive:!0,force:!0}),Ya(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function v_(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let n of ct){if(!n.enabled||!n.triggers||n.triggers.length===0)continue;if(n.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(n.instructions||"").split(`
94
+ `)}`}function Y$(){let t=[];for(let e of ft)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function G$(){let t=[];for(let e of ft)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function z$(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of ft)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function K$(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of ft)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(n);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function X$(){return ft.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function V$(t){let e=ft.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Qa().filter(n=>n!==t);return Xd(s),!0}function J$(t){let e=ft.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Qa();return s.includes(t)||(s.push(t),Xd(s)),!0}function Z$(){return ft}async function Q$(t,e={}){let{execFileSync:s}=require("child_process"),n=Kd(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||_t.basename(o,".git").replace(/^nex-skill-/,""),i=_t.join(n,r);if(Pe.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(o))throw new Error(`Invalid git URL: ${o}`);s("git",["clone","--depth","1",o,i],{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=_t.join(i,"skill.json"),l=Pe.existsSync(a),c=Pe.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{Pe.rmSync(i,{recursive:!0,force:!0})}catch(u){console.error("skills.js line 562 failed:",u.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let u=JSON.parse(Pe.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Pe.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return el(),{ok:!0,name:r}}async function e_(t){let e=require("axios");try{let s=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${s}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(o=>({name:o.name.replace(/^nex-skill-/,""),description:o.description||"(no description)",url:o.clone_url,stars:o.stargazers_count,owner:o.owner.login}))}catch(s){return[{name:"error",description:`Search failed: ${s.message}`,url:"",stars:0,owner:""}]}}function t_(t){let e=_t.join(ho(),t);if(!Pe.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${ho()}`};try{return Pe.rmSync(e,{recursive:!0,force:!0}),el(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function n_(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let n of ft){if(!n.enabled||!n.triggers||n.triggers.length===0)continue;if(n.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(n.instructions||"").split(`
95
95
  `).slice(0,3).join(`
96
- `);s.push({name:n.name,instructions:r})}}return s}Dd.exports={initSkillsDir:Md,loadAllSkills:Ya,getSkillInstructions:p_,getSkillCommands:m_,getSkillToolDefinitions:g_,routeSkillCall:y_,handleSkillCommand:w_,listSkills:__,enableSkill:$_,disableSkill:b_,getLoadedSkills:k_,installSkill:x_,searchSkills:S_,removeSkill:E_,matchSkillTriggers:v_,_getSkillsDir:uo,_validateScriptSkill:Ld,_loadMarkdownSkill:Ua,_loadScriptSkill:Wa,_parseFrontmatter:Id}});var Ka=Z((iR,Wd)=>{var{spawn:T_}=require("child_process"),R_=require("path"),jd=require("fs"),ln=new Map;function C_(){return R_.join(process.cwd(),".nex","config.json")}function za(){let t=C_();if(!jd.existsSync(t))return{};try{return JSON.parse(jd.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Br(t,e,s={},n=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
96
+ `);s.push({name:n.name,instructions:r})}}return s}Zd.exports={initSkillsDir:Kd,loadAllSkills:el,getSkillInstructions:H$,getSkillCommands:Y$,getSkillToolDefinitions:G$,routeSkillCall:z$,handleSkillCommand:K$,listSkills:X$,enableSkill:V$,disableSkill:J$,getLoadedSkills:Z$,installSkill:Q$,searchSkills:e_,removeSkill:t_,matchSkillTriggers:n_,_getSkillsDir:ho,_validateScriptSkill:Vd,_loadMarkdownSkill:Ja,_loadScriptSkill:Za,_parseFrontmatter:Jd}});var sl=V((a1,of)=>{var{spawn:s_}=require("child_process"),o_=require("path"),Qd=require("fs"),hn=new Map;function r_(){return o_.join(process.cwd(),".nex","config.json")}function nl(){let t=r_();if(!Qd.existsSync(t))return{};try{return JSON.parse(Qd.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Kr(t,e,s={},n=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
97
97
  `,l="",c=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},n);function u(f){l+=f.toString();let p=l.split(`
98
- `);for(let m of p)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}l=p[p.length-1]||""}function d(){clearTimeout(c),t.stdout.removeListener("data",u)}t.stdout.on("data",u);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function qd(t,e){if(ln.has(t))return ln.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let i of s)process.env[i]&&(n[i]=process.env[i]);let o=T_(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Br(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Br(o,"tools/list",{});return r.tools=i&&i.tools||[],ln.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Fd(t){let e=ln.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return ln.delete(t),!0}function A_(){for(let[t]of ln)Fd(t)}async function Bd(t,e,s={}){let n=ln.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Br(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
99
- `):JSON.stringify(o)}function Ud(){let t=[];for(let[e,s]of ln)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function O_(){return Ud().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function N_(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let n=s[0],o=s.slice(1).join("_");return Bd(n,o,e)}function M_(){let t=za();return Object.entries(t).map(([e,s])=>{let n=ln.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function P_(){let t=za(),e=[];for(let[s,n]of Object.entries(t))try{let o=await qd(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Wd.exports={loadMCPConfig:za,sendRequest:Br,connectServer:qd,disconnectServer:Fd,disconnectAll:A_,callTool:Bd,getAllTools:Ud,getMCPToolDefinitions:O_,routeMCPCall:N_,listServers:M_,connectAll:P_}});var Wr=Z((aR,zd)=>{var Hd=require("fs"),Xa=require("path"),Ur=[],fo=[],Bn={},ho=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Yd(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let s=t.function.name;return fo.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(fo.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Gd(t,e){return ho.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Bn[t]||(Bn[t]=[]),Bn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${ho.join(", ")}`}}async function Va(t,e){let s=Bn[t]||[],n=e;for(let o of s)try{let r=await o(n);r!==void 0&&(n=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return n}function L_(){let t=Xa.join(process.cwd(),".nex","plugins"),e=[];if(!Hd.existsSync(t))return{loaded:0,errors:[]};let s=Hd.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:Yd,registerHook:Gd,EVENTS:ho};for(let o of s){let r=Xa.join(t,o);try{let i=require(r);if(typeof i=="function")i(n);else if(typeof i.setup=="function")i.setup(n);else{e.push(`${o}: Plugin must export a function or { setup: function }`);continue}Ur.push({name:i.name||Xa.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:Ur.length,errors:e}}function I_(){return fo.map(t=>t.definition)}async function D_(t,e,s={}){let n=fo.find(a=>a.definition.function.name===t);if(!n)return null;let o=await Va("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await Va("afterToolExec",{name:t,args:e,result:r})).result||r}function j_(){return[...Ur]}function q_(){let t={};for(let e of ho)t[e]=(Bn[e]||[]).length;return t}function F_(){Ur.length=0,fo.length=0;for(let t of Object.keys(Bn))delete Bn[t]}zd.exports={registerTool:Yd,registerHook:Gd,emit:Va,loadPlugins:L_,getPluginToolDefinitions:I_,executePluginTool:D_,getLoadedPlugins:j_,getHookCounts:q_,clearPlugins:F_,EVENTS:ho}});var Ja=Z((lR,Jd)=>{var{getSkillToolDefinitions:B_}=Ga(),{getMCPToolDefinitions:U_}=Ka(),{getPluginToolDefinitions:W_}=Wr(),Hr=new Map;function Kd(){let{TOOL_DEFINITIONS:t}=po();return[...t,...B_(),...U_(),...W_()]}function Xd(t){if(Hr.has(t))return Hr.get(t);let s=Kd().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return Hr.set(t,n),n}function H_(){Hr.clear()}function Yr(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Vd(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Vd(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=n;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[s][n]}function Y_(t,e){let s=Xd(t);if(s===null){let d=Kd().map(p=>p.function.name),f=Yr(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
100
- Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],a={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Yr(u,r);d&&!o.includes(d)?(a[u]=e[d],delete a[d],l=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!o.includes("-n")&&(delete a["-n"],delete a.n,l=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(s.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],l=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],l=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,l=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,l=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,l=!0));for(let u of Object.keys(a))if(!o.includes(u)){let d=Yr(u,o);if(d&&!(d in a))a[d]=a[u],delete a[u],l=!0;else if(!l){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${u}".${f}`)}}for(let u of Object.keys(a)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof a[u];d==="string"&&f==="number"?(a[u]=String(a[u]),l=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),l=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
98
+ `);for(let m of p)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}l=p[p.length-1]||""}function d(){clearTimeout(c),t.stdout.removeListener("data",u)}t.stdout.on("data",u);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function ef(t,e){if(hn.has(t))return hn.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let i of s)process.env[i]&&(n[i]=process.env[i]);let o=s_(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Kr(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Kr(o,"tools/list",{});return r.tools=i&&i.tools||[],hn.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function tf(t){let e=hn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return hn.delete(t),!0}function i_(){for(let[t]of hn)tf(t)}async function nf(t,e,s={}){let n=hn.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Kr(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
99
+ `):JSON.stringify(o)}function sf(){let t=[];for(let[e,s]of hn)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function a_(){return sf().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function l_(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let n=s[0],o=s.slice(1).join("_");return nf(n,o,e)}function c_(){let t=nl();return Object.entries(t).map(([e,s])=>{let n=hn.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function u_(){let t=nl(),e=[];for(let[s,n]of Object.entries(t))try{let o=await ef(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}of.exports={loadMCPConfig:nl,sendRequest:Kr,connectServer:ef,disconnectServer:tf,disconnectAll:i_,callTool:nf,getAllTools:sf,getMCPToolDefinitions:a_,routeMCPCall:l_,listServers:c_,connectAll:u_}});var Vr=V((l1,cf)=>{var rf=require("fs"),ol=require("path"),Xr=[],mo=[],zn={},go=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function af(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let s=t.function.name;return mo.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(mo.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function lf(t,e){return go.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(zn[t]||(zn[t]=[]),zn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${go.join(", ")}`}}async function rl(t,e){let s=zn[t]||[],n=e;for(let o of s)try{let r=await o(n);r!==void 0&&(n=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return n}function d_(){let t=ol.join(process.cwd(),".nex","plugins"),e=[];if(!rf.existsSync(t))return{loaded:0,errors:[]};let s=rf.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:af,registerHook:lf,EVENTS:go};for(let o of s){let r=ol.join(t,o);try{let i=require(r);if(typeof i=="function")i(n);else if(typeof i.setup=="function")i.setup(n);else{e.push(`${o}: Plugin must export a function or { setup: function }`);continue}Xr.push({name:i.name||ol.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:Xr.length,errors:e}}function f_(){return mo.map(t=>t.definition)}async function p_(t,e,s={}){let n=mo.find(a=>a.definition.function.name===t);if(!n)return null;let o=await rl("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await rl("afterToolExec",{name:t,args:e,result:r})).result||r}function h_(){return[...Xr]}function m_(){let t={};for(let e of go)t[e]=(zn[e]||[]).length;return t}function g_(){Xr.length=0,mo.length=0;for(let t of Object.keys(zn))delete zn[t]}cf.exports={registerTool:af,registerHook:lf,emit:rl,loadPlugins:d_,getPluginToolDefinitions:f_,executePluginTool:p_,getLoadedPlugins:h_,getHookCounts:m_,clearPlugins:g_,EVENTS:go}});var il=V((c1,pf)=>{var{getSkillToolDefinitions:y_}=tl(),{getMCPToolDefinitions:w_}=sl(),{getPluginToolDefinitions:$_}=Vr(),Jr=new Map;function uf(){let{TOOL_DEFINITIONS:t}=yo();return[...t,...y_(),...w_(),...$_()]}function df(t){if(Jr.has(t))return Jr.get(t);let s=uf().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return Jr.set(t,n),n}function __(){Jr.clear()}function Zr(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=ff(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function ff(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=n;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[s][n]}function b_(t,e){let s=df(t);if(s===null){let d=uf().map(p=>p.function.name),f=Zr(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
100
+ Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],a={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Zr(u,r);d&&!o.includes(d)?(a[u]=e[d],delete a[d],l=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!o.includes("-n")&&(delete a["-n"],delete a.n,l=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(s.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],l=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],l=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,l=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,l=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,l=!0));for(let u of Object.keys(a))if(!o.includes(u)){let d=Zr(u,o);if(d&&!(d in a))a[d]=a[u],delete a[u],l=!0;else if(!l){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${u}".${f}`)}}for(let u of Object.keys(a)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof a[u];d==="string"&&f==="number"?(a[u]=String(a[u]),l=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),l=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
101
101
  `+i.map(u=>` - ${u}`).join(`
102
102
  `)+`
103
103
 
104
- Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function G_(t,e){let s=[],n={...t};if(!n.function&&!n.name)return s.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:n,errors:s};if(!n.function&&n.name&&(n.function={name:n.name,arguments:n.arguments||n.args||{}},delete n.name,delete n.args),n.function&&n.function.args!==void 0&&n.function.arguments===void 0&&(n.function.arguments=n.function.args,delete n.function.args),n.function&&(n.function.arguments===void 0||n.function.arguments===null)&&(n.function.arguments={}),n.function&&typeof n.function.arguments=="string"){let o=n.function.arguments;if(o.trim()==="")n.function.arguments={};else try{n.function.arguments=JSON.parse(o)}catch(r){return s.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:n,errors:s}}}return n.function&&typeof n.function.arguments!="object"?(s.push(`Arguments must be an object, got ${typeof n.function.arguments}`),{valid:!1,normalized:n,errors:s}):!n.function.name||typeof n.function.name!="string"?(s.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:n,errors:s}):{valid:s.length===0,normalized:n,errors:s}}Jd.exports={validateToolArgs:Y_,validateToolCallFormat:G_,closestMatch:Yr,levenshtein:Vd,getCachedSchema:Xd,clearSchemaCache:H_}});var tf=Z((cR,ef)=>{var{levenshtein:Gr}=Ja(),z_=200,K_=.3,X_=2;function Za(t){return t.replace(/\r\n/g,`
104
+ Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function k_(t,e){let s=[],n={...t};if(!n.function&&!n.name)return s.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:n,errors:s};if(!n.function&&n.name&&(n.function={name:n.name,arguments:n.arguments||n.args||{}},delete n.name,delete n.args),n.function&&n.function.args!==void 0&&n.function.arguments===void 0&&(n.function.arguments=n.function.args,delete n.function.args),n.function&&(n.function.arguments===void 0||n.function.arguments===null)&&(n.function.arguments={}),n.function&&typeof n.function.arguments=="string"){let o=n.function.arguments;if(o.trim()==="")n.function.arguments={};else try{n.function.arguments=JSON.parse(o)}catch(r){return s.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:n,errors:s}}}return n.function&&typeof n.function.arguments!="object"?(s.push(`Arguments must be an object, got ${typeof n.function.arguments}`),{valid:!1,normalized:n,errors:s}):!n.function.name||typeof n.function.name!="string"?(s.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:n,errors:s}):{valid:s.length===0,normalized:n,errors:s}}pf.exports={validateToolArgs:b_,validateToolCallFormat:k_,closestMatch:Zr,levenshtein:ff,getCachedSchema:df,clearSchemaCache:__}});var yf=V((u1,gf)=>{var{levenshtein:Qr}=il(),x_=200,S_=.3,E_=2;function al(t){return t.replace(/\r\n/g,`
105
105
  `).replace(/\r/g,`
106
- `).replace(/\t/g," ".repeat(X_)).split(`
106
+ `).replace(/\t/g," ".repeat(E_)).split(`
107
107
  `).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,r]=n;return o+r.replace(/ {2,}/g," ")}).join(`
108
- `)}function V_(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=Za(t),n=Za(e);if(!s.includes(n))return null;let o=t.split(`
108
+ `)}function v_(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=al(t),n=al(e);if(!s.includes(n))return null;let o=t.split(`
109
109
  `),r=s.split(`
110
110
  `),i=n.split(`
111
111
  `),a=i[0],l=i[i.length-1];for(let c=0;c<=r.length-i.length;c++){let u=!0;for(let d=0;d<i.length;d++)if(r[c+d]!==i[d]){u=!1;break}if(u)return o.slice(c,c+i.length).join(`
112
- `)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(n)!==-1)return o[c]}return null}function J_(t,e){if(!t||!e)return null;let s=t.split(`
112
+ `)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(n)!==-1)return o[c]}return null}function T_(t,e){if(!t||!e)return null;let s=t.split(`
113
113
  `),o=e.split(`
114
- `).length;return s.length===0||o===0?null:o===1?Z_(s,e):e$(s,e,o)}function Zd(t){return Math.max(1,Math.floor(t/z_))}function Qd(t,e){return t<=Math.ceil(e*K_)}function Z_(t,e){let s=e.trim(),n=Zd(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=n){let a=t[i];if(!a.trim())continue;let l=Gr(a.trim(),s);l<r&&(r=l,o={text:a,distance:l,line:i+1})}return o&&n>1&&(o=Q_(t,s,o,n)||o,r=o.distance),Qd(r,e.length)?o:null}function Q_(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),i=Math.min(t.length-1,o+n),a=s.distance,l=null;for(let c=r;c<=i;c++){let u=t[c];if(!u.trim())continue;let d=Gr(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function e$(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Zd(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let l=t.slice(a,a+s).join(`
115
- `),c=Gr(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&o>1&&(r=t$(t,e,r,o,s,n)||r,i=r.distance),Qd(i,e.length)?r:null}function t$(t,e,s,n,o,r){let i=s.line-1,a=Math.max(0,i-n),l=Math.min(r-1,i+n),c=s.distance,u=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+o).join(`
116
- `),p=Gr(f,e);p<c&&(c=p,u={text:f,distance:p,line:d+1})}return u}ef.exports={normalizeWhitespace:Za,fuzzyFindText:V_,findMostSimilar:J_}});var sf=Z((dR,nf)=>{var{C:uR}=Je(),n$=[{name:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{name:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{name:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{name:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{name:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36}/i},{name:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{name:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{name:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"'][^'"']{8,}/i}],s$=[{name:"TODO",regex:/\bTODO\b/i,severity:"warn"},{name:"FIXME",regex:/\bFIXME\b/i,severity:"warn"},{name:"Debugger",regex:/\bdebugger\b/,severity:"error",ext:[".js",".ts",".jsx",".tsx"]},{name:"eval()",regex:/\beval\s*\(/,severity:"warn",ext:[".js",".ts",".jsx",".tsx"]},{name:"Console Log",regex:/\bconsole\.log\(/,severity:"info",ext:[".js",".ts",".jsx",".tsx"]},{name:"ANSI Code",regex:/\\x1b\[[0-9;]*m/,severity:"warn",message:"Avoid hardcoded ANSI codes; use cli/ui.js instead."}];function o$(t,e){let s=e.split(`
117
- `),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let l of n$)l.regex.test(i)&&n.push({line:a,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of s$)l.ext&&!l.ext.includes(o)||l.regex.test(i)&&n.push({line:a,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}function r$(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}nf.exports={runDiagnostics:o$,getMemoryUsage:r$}});var Cs=Z((fR,ff)=>{var Rs=require("fs").promises,bn=require("path"),{exec:i$}=require("util").promisify(require("child_process").exec),kn=[],nl=null,zr=!1,el=0,a$=6e4;function rf(t){return!(kn.length===0||nl!==t||Date.now()-el>a$)}async function af(t){if(!zr&&!rf(t)){zr=!0,nl=t;try{try{let{stdout:n}=await i$("rg --files",{cwd:t,timeout:5e3});kn=n.split(`
118
- `).filter(Boolean),el=Date.now(),zr=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Rs.readdir(n,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=o?`${o}/${i.name}`:i.name;i.isDirectory()?await s(bn.join(n,i.name),a):e.push(a)}};await s(t,""),kn=e,el=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{zr=!1}}}function tl(){return kn}function l$(){return nl}function c$(t){return kn.filter(e=>bn.basename(e)===t)}function u$(t){let e=t.toLowerCase();return kn.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}function lf(t,e){let s=t.length,n=e.length;if(s===0)return n;if(n===0)return s;let o=Array.from({length:n+1},(r,i)=>i);for(let r=1;r<=s;r++){let i=r-1;o[0]=r;for(let a=1;a<=n;a++){let l=t[r-1]===e[a-1]?i:1+Math.min(o[a],o[a-1],i);i=o[a],o[a]=l}}return o[n]}function cf(t,e){let s=t.toLowerCase(),n=e.toLowerCase();if(s===n)return 1e3;let o=s.split("/").filter(Boolean),r=n.split("/").filter(Boolean),i=0;for(let u=1;u<=Math.min(o.length,r.length)&&o[o.length-u]===r[r.length-u];u++)i=u;if(i>0&&i===r.length)return 500+i*100;let a=bn.basename(t).toLowerCase(),l=bn.basename(e).toLowerCase(),c=0;if(a===l)c+=80;else{let u=Math.max(a.length,l.length);if(u>0&&u<100){let f=1-lf(a,l)/u;f>=.6&&(c+=Math.round(f*50))}}if((s.includes(n)||n.includes(s))&&(c+=20),r.length>1){let u=new Set(o),d=0;for(let f of r)u.has(f)&&d++;c+=d*10}return i>0&&(c+=i*30),c}function d$(t,{limit:e=10,minScore:s=15}={}){if(!t||kn.length===0)return[];let n=[];for(let o of kn){let r=cf(o,t);r>=s&&n.push({file:o,score:r})}return n.sort((o,r)=>r.score-o.score),n.slice(0,e)}var Qa=null,of=0,f$=12e4,h$=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function uf(t,e){let s=[],n=t.split(`
119
- `);for(let o=0;o<n.length;o++){let r=n[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let c=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);c&&s.push({type:"function",name:c[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&s.push({type:"export",name:p,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];s.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let c=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);c&&s.push({type:"import",name:c[1]||c[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&s.push({type:"class",name:l[1],line:i})}}return s}async function df(t){t=t||process.cwd();let e=bn.join(t,".nex","index","content-index.json"),s={};if(Qa&&Date.now()-of<f$)return Qa;try{let i=await Rs.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}tl().length===0&&await af(t);let o={files:{}},r=!1;for(let i of tl()){let a=bn.extname(i);if(!h$.has(a))continue;let l=bn.join(t,i);try{let u=(await Rs.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){o.files[i]=s.files[i];continue}let d=await Rs.readFile(l,"utf-8"),f=uf(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=bn.join(t,".nex","index");await Rs.mkdir(i,{recursive:!0}),await Rs.writeFile(e,JSON.stringify(o),"utf-8")}return Qa=o,of=Date.now(),o}async function p$(t,e){let s=await df(),n=[],o=t.toLowerCase();for(let[r,i]of Object.entries(s.files))for(let a of i.defs)e&&a.type!==e||a.name.toLowerCase().includes(o)&&n.push({file:r,type:a.type,name:a.name,line:a.line});return n.sort((r,i)=>{let a=r.name.toLowerCase()===o?0:1,l=i.name.toLowerCase()===o?0:1;if(a!==l)return a-l;let c=r.name.toLowerCase().startsWith(o)?0:1,u=i.name.toLowerCase().startsWith(o)?0:1;return c-u}),n.slice(0,50)}ff.exports={refreshIndex:af,getFileIndex:tl,getIndexedCwd:l$,findFileInIndex:c$,searchIndex:u$,isIndexValid:rf,buildContentIndex:df,searchContentIndex:p$,extractDefinitions:uf,smartSearch:d$,scorePathMatch:cf,pathLevenshtein:lf}});var As=Z((hR,wf)=>{var Kr=require("fs"),Zr=require("path"),Qr=require("os"),{execFile:m$}=require("child_process"),{promisify:g$}=require("util"),sl=g$(m$),y$=Zr.join(Qr.homedir(),".nex","servers.json"),Xr=Zr.join(Qr.tmpdir(),"nex-ssh-sockets");function w$(){return Zr.join(process.cwd(),".nex","servers.json")}function hf(){let t=n=>{if(!Kr.existsSync(n))return{};try{return JSON.parse(Kr.readFileSync(n,"utf-8"))}catch{return{}}},e=t(y$),s=t(w$());return{...e,...s}}function _$(t){let e=hf();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let s=Object.keys(e),n=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${n}`)}function $$(){Kr.existsSync(Xr)||Kr.mkdirSync(Xr,{recursive:!0})}function pf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Qr.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),$$();let s=t.user?`${t.user}@${t.host}`:t.host,n=Zr.join(Xr,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function mf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Qr.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Vr(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=pf(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await sl("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:a,error:ei(l,t)}}}async function b$(t,e,s,{timeout:n=12e4}={}){let o=mf(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await sl("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(ei(a,t)||a)}}async function k$(t,e,s,{timeout:n=12e4}={}){let o=mf(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await sl("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(ei(a,t)||a)}}function ei(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
114
+ `).length;return s.length===0||o===0?null:o===1?R_(s,e):A_(s,e,o)}function hf(t){return Math.max(1,Math.floor(t/x_))}function mf(t,e){return t<=Math.ceil(e*S_)}function R_(t,e){let s=e.trim(),n=hf(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=n){let a=t[i];if(!a.trim())continue;let l=Qr(a.trim(),s);l<r&&(r=l,o={text:a,distance:l,line:i+1})}return o&&n>1&&(o=C_(t,s,o,n)||o,r=o.distance),mf(r,e.length)?o:null}function C_(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),i=Math.min(t.length-1,o+n),a=s.distance,l=null;for(let c=r;c<=i;c++){let u=t[c];if(!u.trim())continue;let d=Qr(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function A_(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=hf(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let l=t.slice(a,a+s).join(`
115
+ `),c=Qr(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&o>1&&(r=O_(t,e,r,o,s,n)||r,i=r.distance),mf(i,e.length)?r:null}function O_(t,e,s,n,o,r){let i=s.line-1,a=Math.max(0,i-n),l=Math.min(r-1,i+n),c=s.distance,u=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+o).join(`
116
+ `),p=Qr(f,e);p<c&&(c=p,u={text:f,distance:p,line:d+1})}return u}gf.exports={normalizeWhitespace:al,fuzzyFindText:v_,findMostSimilar:T_}});var $f=V((f1,wf)=>{var{C:d1}=tt(),N_=[{name:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{name:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{name:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{name:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{name:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36}/i},{name:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{name:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{name:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"'][^'"']{8,}/i}],M_=[{name:"TODO",regex:/\bTODO\b/i,severity:"warn"},{name:"FIXME",regex:/\bFIXME\b/i,severity:"warn"},{name:"Debugger",regex:/\bdebugger\b/,severity:"error",ext:[".js",".ts",".jsx",".tsx"]},{name:"eval()",regex:/\beval\s*\(/,severity:"warn",ext:[".js",".ts",".jsx",".tsx"]},{name:"Console Log",regex:/\bconsole\.log\(/,severity:"info",ext:[".js",".ts",".jsx",".tsx"]},{name:"ANSI Code",regex:/\\x1b\[[0-9;]*m/,severity:"warn",message:"Avoid hardcoded ANSI codes; use cli/ui.js instead."}];function P_(t,e){let s=e.split(`
117
+ `),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let l of N_)l.regex.test(i)&&n.push({line:a,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of M_)l.ext&&!l.ext.includes(o)||l.regex.test(i)&&n.push({line:a,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}function L_(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}wf.exports={runDiagnostics:P_,getMemoryUsage:L_}});var mn=V((p1,Af)=>{var Ms=require("fs").promises,Et=require("path"),{exec:I_}=require("util").promisify(require("child_process").exec),Cn=[],ul=null,ei=!1,cl=0,j_=6e4;function dl(t){return!(Cn.length===0||ul!==t||Date.now()-cl>j_)}async function Sf(t){if(!ei&&!dl(t)){ei=!0,ul=t;try{try{let{stdout:n}=await I_("rg --files",{cwd:t,timeout:5e3});Cn=n.split(`
118
+ `).filter(Boolean),cl=Date.now(),ei=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Ms.readdir(n,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=o?`${o}/${i.name}`:i.name;i.isDirectory()?await s(Et.join(n,i.name),a):e.push(a)}};await s(t,""),Cn=e,cl=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{ei=!1}}}function wo(){return Cn}function D_(){return ul}function q_(t){return Cn.filter(e=>Et.basename(e)===t)}function F_(t){let e=t.toLowerCase();return Cn.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}function Ef(t,e){let s=t.length,n=e.length;if(s===0)return n;if(n===0)return s;let o=Array.from({length:n+1},(r,i)=>i);for(let r=1;r<=s;r++){let i=r-1;o[0]=r;for(let a=1;a<=n;a++){let l=t[r-1]===e[a-1]?i:1+Math.min(o[a],o[a-1],i);i=o[a],o[a]=l}}return o[n]}function vf(t,e){let s=t.toLowerCase(),n=e.toLowerCase();if(s===n)return 1e3;let o=s.split("/").filter(Boolean),r=n.split("/").filter(Boolean),i=0;for(let u=1;u<=Math.min(o.length,r.length)&&o[o.length-u]===r[r.length-u];u++)i=u;if(i>0&&i===r.length)return 500+i*100;let a=Et.basename(t).toLowerCase(),l=Et.basename(e).toLowerCase(),c=0;if(a===l)c+=80;else{let u=Math.max(a.length,l.length);if(u>0&&u<100){let f=1-Ef(a,l)/u;f>=.6&&(c+=Math.round(f*50))}}if((s.includes(n)||n.includes(s))&&(c+=20),r.length>1){let u=new Set(o),d=0;for(let f of r)u.has(f)&&d++;c+=d*10}return i>0&&(c+=i*30),c}function B_(t,{limit:e=10,minScore:s=15}={}){if(!t||Cn.length===0)return[];let n=[];for(let o of Cn){let r=vf(o,t);r>=s&&n.push({file:o,score:r})}return n.sort((o,r)=>r.score-o.score),n.slice(0,e)}var ll=null,_f=0,bf=null,Tf=12e4,ti=null,kf=0,xf=null,Rf=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Cf(t,e){let s=[],n=t.split(`
119
+ `);for(let o=0;o<n.length;o++){let r=n[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let c=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);c&&s.push({type:"function",name:c[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&s.push({type:"export",name:p,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];s.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let c=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);c&&s.push({type:"import",name:c[1]||c[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&s.push({type:"class",name:l[1],line:i})}}return s}async function fl(t){t=t||process.cwd();let e=Et.join(t,".nex","index","content-index.json"),s={};if(ll&&bf===t&&Date.now()-_f<Tf)return ll;try{let i=await Ms.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}let n=wo();(!dl(t)||n.length===0)&&(await Sf(t),n=wo());let o={files:{}},r=!1;for(let i of wo()){let a=Et.extname(i);if(!Rf.has(a))continue;let l=Et.join(t,i);try{let u=(await Ms.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){o.files[i]=s.files[i];continue}let d=await Ms.readFile(l,"utf-8"),f=Cf(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=Et.join(t,".nex","index");await Ms.mkdir(i,{recursive:!0}),await Ms.writeFile(e,JSON.stringify(o),"utf-8")}return ll=o,_f=Date.now(),bf=t,o}async function U_(t,e,s){let n=await fl(s),o=[],r=t.toLowerCase();for(let[i,a]of Object.entries(n.files))for(let l of a.defs)e&&l.type!==e||l.name.toLowerCase().includes(r)&&o.push({file:i,type:l.type,name:l.name,line:l.line});return o.sort((i,a)=>{let l=i.name.toLowerCase()===r?0:1,c=a.name.toLowerCase()===r?0:1;if(l!==c)return l-c;let u=i.name.toLowerCase().startsWith(r)?0:1,d=a.name.toLowerCase().startsWith(r)?0:1;return u-d}),o.slice(0,50)}function W_(t,e,s){if(!e||!e.startsWith("."))return null;let n=Et.posix.dirname(t.replace(/\\/g,"/")),o=Et.posix.normalize(Et.posix.join(n==="."?"":n,e)),r=[];if(Et.posix.extname(o))r.push(o);else for(let a of Rf)r.push(`${o}${a}`),r.push(Et.posix.join(o,`index${a}`));for(let a of r)if(s.has(a))return a;return null}async function pl(t){if(t=t||process.cwd(),ti&&xf===t&&Date.now()-kf<Tf)return ti;let e=await fl(t),s=wo(),n=new Set(s.map(i=>i.replace(/\\/g,"/"))),o={},r={};for(let i of Object.keys(e.files||{})){let a=i.replace(/\\/g,"/"),l=Array.isArray(e.files[i]?.defs)?e.files[i].defs:[],c=[],u=new Set;for(let d of l){if(d.type!=="import")continue;let f=W_(a,d.name,n);!f||f===a||u.has(f)||(u.add(f),c.push(f),r[f]||(r[f]=[]),r[f].push(a))}o[a]=c}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return ti={importsByFile:o,importedByFile:r},kf=Date.now(),xf=t,ti}async function H_(t,e,s=6){if(!t)return[];let n=await pl(e),o=String(t).replace(/\\/g,"/"),r=[...n.importsByFile[o]||[],...n.importedByFile[o]||[]];return[...new Set(r)].filter(i=>i!==o).slice(0,s)}async function Y_(t,e=4){let s=await pl(t),n=new Map;for(let[o,r]of Object.entries(s.importsByFile||{}))n.set(o,(n.get(o)||0)+r.length);for(let[o,r]of Object.entries(s.importedByFile||{}))n.set(o,(n.get(o)||0)+r.length);return[...n.entries()].filter(([,o])=>o>0).sort((o,r)=>r[1]-o[1]||o[0].localeCompare(r[0])).slice(0,e).map(([o,r])=>`${o} (${r} links)`)}Af.exports={refreshIndex:Sf,getFileIndex:wo,getIndexedCwd:D_,findFileInIndex:q_,searchIndex:F_,isIndexValid:dl,buildContentIndex:fl,searchContentIndex:U_,extractDefinitions:Cf,buildImportGraph:pl,getRelatedFiles:H_,summarizeModuleHubs:Y_,smartSearch:B_,scorePathMatch:vf,pathLevenshtein:Ef}});var Ps=V((h1,If)=>{var ni=require("fs"),ii=require("path"),ai=require("os"),{execFile:G_}=require("child_process"),{promisify:z_}=require("util"),hl=z_(G_),K_=ii.join(ai.homedir(),".nex","servers.json"),si=ii.join(ai.tmpdir(),"nex-ssh-sockets");function X_(){return ii.join(process.cwd(),".nex","servers.json")}function Of(){let t=n=>{if(!ni.existsSync(n))return{};try{return JSON.parse(ni.readFileSync(n,"utf-8"))}catch{return{}}},e=t(K_),s=t(X_());return{...e,...s}}function V_(t){let e=Of();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let s=Object.keys(e),n=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${n}`)}function J_(){ni.existsSync(si)||ni.mkdirSync(si,{recursive:!0})}function Nf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,ai.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),J_();let s=t.user?`${t.user}@${t.host}`:t.host,n=ii.join(si,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Mf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,ai.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function oi(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=Nf(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await hl("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:a,error:li(l,t)}}}async function Z_(t,e,s,{timeout:n=12e4}={}){let o=Mf(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await hl("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(li(a,t)||a)}}async function Q_(t,e,s,{timeout:n=12e4}={}){let o=Mf(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await hl("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(li(a,t)||a)}}function li(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
120
120
  HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
121
121
  HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
122
122
  HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
123
123
  HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
124
124
  HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
125
- HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function x$(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${i}`}var Jr=new Map,S$=12e4;async function gf(t,e,{force:s=!1}={}){let o=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=Jr.get(o);if(!s&&r&&Date.now()-r.time<S$)return r.files;let i=`find ${e} -maxdepth 6 -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/venv/*' -not -path '*/__pycache__/*' -not -path '*/dist/*' -not -name '*.pyc' 2>/dev/null | head -5000`,{stdout:a,exitCode:l}=await Vr(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let c=e.endsWith("/")?e:e+"/",u=a.split(`
126
- `).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return Jr.set(o,{files:u,time:Date.now()}),u}async function yf(t,e,s,{limit:n=5,minScore:o=15}={}){let r=await gf(t,e);if(r.length===0)return[];let{scorePathMatch:i}=Cs(),a=[];for(let l of r){let c=i(l,s);c>=o&&a.push({file:l,score:c})}return a.sort((l,c)=>c.score-l.score),a.slice(0,n)}async function E$(t,e,s){if(!s)return{fixedPath:null,message:""};let n=s.replace(/\/+/g,"/");if(n.startsWith("~/")){let{stdout:r}=await Vr(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(n=n.replace("~/",i+"/"))}if(n.startsWith("/")){let{exitCode:r}=await Vr(t,`test -f ${JSON.stringify(n)}`,{timeout:5e3});if(r===0)return{fixedPath:n,message:"(auto-fixed: normalized path)"}}let o=await yf(t,e,s,{limit:5,minScore:15});if(o.length>0){let i=(e.endsWith("/")?e:e+"/")+o[0].file;if(o[0].score>=200||o.length===1&&o[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${o[0].file})`};if(o.length>=2&&o[0].score>=80&&o[0].score>=o[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${o[0].file})`};if(o.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
125
+ HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function eb(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${i}`}var ri=new Map,tb=12e4;async function Pf(t,e,{force:s=!1}={}){let o=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=ri.get(o);if(!s&&r&&Date.now()-r.time<tb)return r.files;let i=`find ${e} -maxdepth 6 -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/venv/*' -not -path '*/__pycache__/*' -not -path '*/dist/*' -not -name '*.pyc' 2>/dev/null | head -5000`,{stdout:a,exitCode:l}=await oi(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let c=e.endsWith("/")?e:e+"/",u=a.split(`
126
+ `).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return ri.set(o,{files:u,time:Date.now()}),u}async function Lf(t,e,s,{limit:n=5,minScore:o=15}={}){let r=await Pf(t,e);if(r.length===0)return[];let{scorePathMatch:i}=mn(),a=[];for(let l of r){let c=i(l,s);c>=o&&a.push({file:l,score:c})}return a.sort((l,c)=>c.score-l.score),a.slice(0,n)}async function nb(t,e,s){if(!s)return{fixedPath:null,message:""};let n=s.replace(/\/+/g,"/");if(n.startsWith("~/")){let{stdout:r}=await oi(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(n=n.replace("~/",i+"/"))}if(n.startsWith("/")){let{exitCode:r}=await oi(t,`test -f ${JSON.stringify(n)}`,{timeout:5e3});if(r===0)return{fixedPath:n,message:"(auto-fixed: normalized path)"}}let o=await Lf(t,e,s,{limit:5,minScore:15});if(o.length>0){let i=(e.endsWith("/")?e:e+"/")+o[0].file;if(o[0].score>=200||o.length===1&&o[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${o[0].file})`};if(o.length>=2&&o[0].score>=80&&o[0].score>=o[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${o[0].file})`};if(o.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
127
127
  ${o.map(a=>` - ${a.file}`).join(`
128
- `)}`}}return{fixedPath:null,message:""}}function v$(t){t?Jr.delete(t):Jr.clear()}wf.exports={loadServerProfiles:hf,resolveProfile:_$,buildSSHArgs:pf,sshExec:Vr,scpUpload:b$,scpDownload:k$,enrichSSHError:ei,formatProfile:x$,SSH_SOCKET_DIR:Xr,getRemoteIndex:gf,remoteSmartSearch:yf,remoteAutoFixPath:E$,clearRemoteIndex:v$}});var bf=Z((pR,$f)=>{var mo=require("fs"),ol=require("path"),T$=ol.join(".nex","deploy.json");function rl(){return ol.join(process.cwd(),T$)}function _f(){let t=rl();if(!mo.existsSync(t))return{};try{return JSON.parse(mo.readFileSync(t,"utf-8"))}catch{return{}}}function R$(t){let e=_f();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),n=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function C$(t){let e=ol.join(process.cwd(),".nex");mo.existsSync(e)||mo.mkdirSync(e,{recursive:!0}),mo.writeFileSync(rl(),JSON.stringify(t,null,2)+`
129
- `,"utf-8")}$f.exports={loadDeployConfigs:_f,resolveDeployConfig:R$,saveDeployConfigs:C$,getDeployConfigPath:rl}});var _o=Z((mR,Sf)=>{var{getActiveModel:A$,getActiveProviderName:O$}=ot(),go={essential:["bash","read_file","write_file","edit_file","list_directory"],standard:["bash","read_file","write_file","edit_file","list_directory","search_files","glob","grep","ask_user","git_status","git_diff","git_log","task_list","ssh_exec","service_manage","service_logs","container_list","container_logs","container_exec","container_manage","deploy"],full:null},yo={"qwen3-coder:480b":"full","qwen3-coder-next":"full","kimi-k2.5":"full","kimi-k2:1t":"full","kimi-k2-thinking":"full","deepseek-v3.2":"full","deepseek-v3.1:671b":"full","devstral-2:123b":"full","devstral-small-2:24b":"standard","cogito-2.1:671b":"full","qwen3-next:80b":"full","qwen3.5:397b-cloud":"full","qwen3.5:397b":"full","qwen3.5:122b-a10b":"full","qwen3.5:35b-a3b":"full","qwen3.5:27b":"full","qwen3.5:9b":"standard","qwen3.5:4b":"essential","qwen3.5:2b":"essential","qwen3.5:0.8b":"essential","mistral-large-3:675b":"full","gpt-oss:120b":"full","minimax-m2.5":"full","glm-5":"full","glm-4.7":"standard","gemma3:27b":"standard","gemma3:12b":"essential","gemma3:4b":"essential","ministral-3:14b":"standard","ministral-3:8b":"essential","gpt-4o":"full","gpt-4.1":"full",o1:"full",o3:"full","o4-mini":"full","claude-sonnet":"full","claude-sonnet-4-5":"full","claude-opus":"full","claude-haiku":"standard","claude-sonnet-4":"full","gemini-3.1-pro-preview":"full","gemini-3-flash-preview":"full","gemini-2.5-pro":"full","gemini-2.5-flash":"full","gemini-2.0-flash":"standard","gemini-2.0-flash-lite":"essential"},wo={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Vt={};function xf(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Vt=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Vt={}}}xf();function il(){let e=A$()?.id,s=O$();return e&&Vt[e]?Vt[e]:s&&Vt[`${s}:*`]?Vt[`${s}:*`]:e&&yo[e]?yo[e]:s&&wo[s]?wo[s]:"full"}var N$=new Set(["claude-sonnet","claude-sonnet-4-5","claude-sonnet-4","claude-opus","claude-haiku","gpt-4o","gpt-4.1","o1","o3","o4-mini","kimi-k2:1t","kimi-k2.5","kimi-k2-thinking","qwen3-coder:480b","qwen3-coder-next","deepseek-v3.2","deepseek-v3.1:671b"]),kf={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function M$(t,e){return t&&(N$.has(t)||t.startsWith("claude-"))?"strict":e&&kf[e]?kf[e]:"fuzzy"}function P$(t,e){return t&&Vt[t]?Vt[t]:e&&Vt[`${e}:*`]?Vt[`${e}:*`]:t&&yo[t]?yo[t]:e&&wo[e]?wo[e]:"full"}function L$(t,e){let s=e||il();if(s==="full"||!go[s])return t;let n=new Set(go[s]);return t.filter(o=>n.has(o.function.name))}function I$(){let t=il(),e=go[t]?go[t].length:"all";return{tier:t,toolCount:e}}Sf.exports={filterToolsForModel:L$,getActiveTier:il,getModelTier:P$,getEditMode:M$,getTierInfo:I$,TIERS:go,MODEL_TIERS:yo,PROVIDER_DEFAULT_TIER:wo,loadConfigOverrides:xf}});var un=Z((gR,Tf)=>{var al=null,cn=null,$o=null,Ef=`Playwright is not installed. Install with:
128
+ `)}`}}return{fixedPath:null,message:""}}function sb(t){t?ri.delete(t):ri.clear()}If.exports={loadServerProfiles:Of,resolveProfile:V_,buildSSHArgs:Nf,sshExec:oi,scpUpload:Z_,scpDownload:Q_,enrichSSHError:li,formatProfile:eb,SSH_SOCKET_DIR:si,getRemoteIndex:Pf,remoteSmartSearch:Lf,remoteAutoFixPath:nb,clearRemoteIndex:sb}});var qf=V((m1,Df)=>{var $o=require("fs"),ml=require("path"),ob=ml.join(".nex","deploy.json");function gl(){return ml.join(process.cwd(),ob)}function jf(){let t=gl();if(!$o.existsSync(t))return{};try{return JSON.parse($o.readFileSync(t,"utf-8"))}catch{return{}}}function rb(t){let e=jf();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),n=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function ib(t){let e=ml.join(process.cwd(),".nex");$o.existsSync(e)||$o.mkdirSync(e,{recursive:!0}),$o.writeFileSync(gl(),JSON.stringify(t,null,2)+`
129
+ `,"utf-8")}Df.exports={loadDeployConfigs:jf,resolveDeployConfig:rb,saveDeployConfigs:ib,getDeployConfigPath:gl}});var xo=V((g1,Uf)=>{var{getActiveModel:ab,getActiveProviderName:lb}=lt(),_o={essential:["bash","read_file","write_file","edit_file","list_directory"],standard:["bash","read_file","write_file","edit_file","list_directory","search_files","glob","grep","ask_user","git_status","git_diff","git_log","task_list","ssh_exec","service_manage","service_logs","container_list","container_logs","container_exec","container_manage","deploy"],full:null},bo={"qwen3-coder:480b":"full","qwen3-coder-next":"full","kimi-k2.5":"full","kimi-k2:1t":"full","kimi-k2-thinking":"full","deepseek-v3.2":"full","deepseek-v3.1:671b":"full","devstral-2:123b":"full","devstral-small-2:24b":"standard","cogito-2.1:671b":"full","qwen3-next:80b":"full","qwen3.5:397b-cloud":"full","qwen3.5:397b":"full","qwen3.5:122b-a10b":"full","qwen3.5:35b-a3b":"full","qwen3.5:27b":"full","qwen3.5:9b":"standard","qwen3.5:4b":"essential","qwen3.5:2b":"essential","qwen3.5:0.8b":"essential","mistral-large-3:675b":"full","gpt-oss:120b":"full","minimax-m2.5":"full","glm-5":"full","glm-4.7":"standard","gemma3:27b":"standard","gemma3:12b":"essential","gemma3:4b":"essential","ministral-3:14b":"standard","ministral-3:8b":"essential","gpt-4o":"full","gpt-4.1":"full",o1:"full",o3:"full","o4-mini":"full","claude-sonnet":"full","claude-sonnet-4-5":"full","claude-opus":"full","claude-haiku":"standard","claude-sonnet-4":"full","gemini-3.1-pro-preview":"full","gemini-3-flash-preview":"full","gemini-2.5-pro":"full","gemini-2.5-flash":"full","gemini-2.0-flash":"standard","gemini-2.0-flash-lite":"essential"},ko={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},tn={};function Bf(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(tn=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{tn={}}}Bf();function yl(){let e=ab()?.id,s=lb();return e&&tn[e]?tn[e]:s&&tn[`${s}:*`]?tn[`${s}:*`]:e&&bo[e]?bo[e]:s&&ko[s]?ko[s]:"full"}var cb=new Set(["claude-sonnet","claude-sonnet-4-5","claude-sonnet-4","claude-opus","claude-haiku","gpt-4o","gpt-4.1","o1","o3","o4-mini","kimi-k2:1t","kimi-k2.5","kimi-k2-thinking","qwen3-coder:480b","qwen3-coder-next","deepseek-v3.2","deepseek-v3.1:671b"]),Ff={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function ub(t,e){return t&&(cb.has(t)||t.startsWith("claude-"))?"strict":e&&Ff[e]?Ff[e]:"fuzzy"}function db(t,e){return t&&tn[t]?tn[t]:e&&tn[`${e}:*`]?tn[`${e}:*`]:t&&bo[t]?bo[t]:e&&ko[e]?ko[e]:"full"}function fb(t,e){let s=e||yl();if(s==="full"||!_o[s])return t;let n=new Set(_o[s]);return t.filter(o=>n.has(o.function.name))}function pb(){let t=yl(),e=_o[t]?_o[t].length:"all";return{tier:t,toolCount:e}}Uf.exports={filterToolsForModel:fb,getActiveTier:yl,getModelTier:db,getEditMode:ub,getTierInfo:pb,TIERS:_o,MODEL_TIERS:bo,PROVIDER_DEFAULT_TIER:ko,loadConfigOverrides:Bf}});var yn=V((y1,Yf)=>{var wl=null,gn=null,So=null,Wf=`Playwright is not installed. Install with:
130
130
  npm install playwright && npx playwright install chromium
131
- Then restart nex-code.`;function vf(){if($o!==null)return $o;try{require("playwright"),$o=!0}catch{$o=!1}return $o}async function ti(){if(!vf())throw new Error(Ef);return al||(al=require("playwright")),(!cn||!cn.isConnected())&&(cn=await al.chromium.launch({headless:!0})),cn}async function D$(){if(cn){try{await cn.close()}catch(t){console.error("closeBrowser failed:",t.message)}cn=null}}process.on("exit",()=>{if(cn)try{cn.close()}catch(t){console.error("Error closing browser on exit:",t.message)}});async function j$(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await ti()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(c=>c.remove()),document.body?.innerText||"")),a=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
132
- ...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function q$(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await ti()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:n}),l=require("os"),c=require("path"),u=require("fs"),d=c.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a,{mode:384}),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function F$(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await ti()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function B$(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await ti()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}Tf.exports={isPlaywrightAvailable:vf,browserNavigate:j$,browserScreenshot:q$,browserClick:F$,browserFill:B$,closeBrowser:D$,INSTALL_MSG:Ef}});var ll=Z((yR,Cf)=>{"use strict";var U$=require("util"),Rf=require("stream"),Bt=Cf.exports=function(){Rf.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};U$.inherits(Bt,Rf);Bt.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};Bt.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let s;return Buffer.isBuffer(t)?s=t:s=Buffer.from(t,e||this._encoding),this._buffers.push(s),this._buffered+=s.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Bt.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};Bt.prototype.destroySoon=Bt.prototype.end;Bt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Bt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Bt.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};Bt.prototype._processRead=function(t){this._reads.shift();let e=0,s=0,n=Buffer.alloc(t.length);for(;e<t.length;){let o=this._buffers[s++],r=Math.min(o.length,t.length-e);o.copy(n,e,0,r),e+=r,r!==o.length&&(this._buffers[--s]=o.slice(r))}s>0&&this._buffers.splice(0,s),this._buffered-=t.length,t.func.call(this,n)};Bt.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var ul=Z(cl=>{"use strict";var xn=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];cl.getImagePasses=function(t,e){let s=[],n=t%8,o=e%8,r=(t-n)/8,i=(e-o)/8;for(let a=0;a<xn.length;a++){let l=xn[a],c=r*l.x.length,u=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<n;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<o;d++)u++;c>0&&u>0&&s.push({width:c,height:u,index:a})}return s};cl.getInterlaceIterator=function(t){return function(e,s,n){let o=e%xn[n].x.length,r=(e-o)/xn[n].x.length*8+xn[n].x[o],i=s%xn[n].y.length,a=(s-i)/xn[n].y.length*8+xn[n].y[i];return r*4+a*t*4}}});var dl=Z((_R,Af)=>{"use strict";Af.exports=function(e,s,n){let o=e+s-n,r=Math.abs(o-e),i=Math.abs(o-s),a=Math.abs(o-n);return r<=i&&r<=a?e:i<=a?s:n}});var fl=Z(($R,Nf)=>{"use strict";var W$=ul(),H$=dl();function Of(t,e,s){let n=t*e;return s!==8&&(n=Math.ceil(n/(8/s))),n}var Os=Nf.exports=function(t,e){let s=t.width,n=t.height,o=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],o){let a=W$.getImagePasses(s,n);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Of(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Of(s,r,i),height:n,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Os.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Os.prototype._unFilterType1=function(t,e,s){let n=this._xComparison,o=n-1;for(let r=0;r<s;r++){let i=t[1+r],a=r>o?e[r-n]:0;e[r]=i+a}};Os.prototype._unFilterType2=function(t,e,s){let n=this._lastLine;for(let o=0;o<s;o++){let r=t[1+o],i=n?n[o]:0;e[o]=r+i}};Os.prototype._unFilterType3=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=Math.floor((c+l)/2);e[i]=a+u}};Os.prototype._unFilterType4=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=i>o&&r?r[i-n]:0,d=H$(c,l,u);e[i]=a+d}};Os.prototype._reverseFilterLine=function(t){let e=t[0],s,n=this._images[this._imageIndex],o=n.byteWidth;if(e===0)s=t.slice(1,o+1);else switch(s=Buffer.alloc(o),e){case 1:this._unFilterType1(t,s,o);break;case 2:this._unFilterType2(t,s,o);break;case 3:this._unFilterType3(t,s,o);break;case 4:this._unFilterType4(t,s,o);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(s),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=s,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Lf=Z((bR,Pf)=>{"use strict";var Y$=require("util"),Mf=ll(),G$=fl(),z$=Pf.exports=function(t){Mf.call(this);let e=[],s=this;this._filter=new G$(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};Y$.inherits(z$,Mf)});var Ns=Z((kR,If)=>{"use strict";If.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var ml=Z((xR,Df)=>{"use strict";var hl=[];(function(){for(let t=0;t<256;t++){let e=t;for(let s=0;s<8;s++)e&1?e=3988292384^e>>>1:e=e>>>1;hl[t]=e}})();var pl=Df.exports=function(){this._crc=-1};pl.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=hl[(this._crc^t[e])&255]^this._crc>>>8;return!0};pl.prototype.crc32=function(){return this._crc^-1};pl.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=hl[(e^t[s])&255]^e>>>8;return e^-1}});var gl=Z((SR,jf)=>{"use strict";var He=Ns(),K$=ml(),ze=jf.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[He.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[He.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[He.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[He.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[He.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[He.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};ze.prototype.start=function(){this.read(He.PNG_SIGNATURE.length,this._parseSignature.bind(this))};ze.prototype._parseSignature=function(t){let e=He.PNG_SIGNATURE;for(let s=0;s<e.length;s++)if(t[s]!==e[s]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};ze.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n="";for(let r=4;r<8;r++)n+=String.fromCharCode(t[r]);let o=!!(t[4]&32);if(!this._hasIHDR&&s!==He.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new K$,this._crc.write(Buffer.from(n)),this._chunks[s])return this._chunks[s](e);if(!o){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};ze.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};ze.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};ze.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),s=this._crc.crc32();if(this._options.checkCRC&&s!==e){this.error(new Error("Crc error - "+e+" - "+s));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};ze.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};ze.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n=t[8],o=t[9],r=t[10],i=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(o in He.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=o;let l=He.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:s,depth:n,interlace:!!a,palette:!!(o&He.COLORTYPE_PALETTE),color:!!(o&He.COLORTYPE_COLOR),alpha:!!(o&He.COLORTYPE_ALPHA),bpp:l,colorType:o}),this._handleChunkEnd()};ze.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};ze.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let s=0;s<e;s++)this._palette.push([t[s*3],t[s*3+1],t[s*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};ze.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};ze.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===He.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===He.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===He.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};ze.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};ze.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/He.GAMMA_DIVISION),this._handleChunkEnd()};ze.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};ze.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===He.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let s=t-e.length;s>0?this._handleIDAT(s):this._handleChunkEnd()};ze.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};ze.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var yl=Z(Ff=>{"use strict";var qf=ul(),X$=[function(){},function(t,e,s,n){if(n===e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=255},function(t,e,s,n){if(n+1>=e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=e[n+1]},function(t,e,s,n){if(n+2>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=255},function(t,e,s,n){if(n+3>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=e[n+3]}],V$=[function(){},function(t,e,s,n){let o=e[0];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=n},function(t,e,s){let n=e[0];t[s]=n,t[s+1]=n,t[s+2]=n,t[s+3]=e[1]},function(t,e,s,n){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=n},function(t,e,s){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=e[3]}];function J$(t,e){let s=[],n=0;function o(){if(n===t.length)throw new Error("Ran out of data");let r=t[n];n++;let i,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[n],n++,s.push((r<<8)+f);break;case 4:f=r&15,p=r>>4,s.push(p,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,s.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,s.push(p,f,d,u,c,l,a,i);break}}return{get:function(r){for(;s.length<r;)o();let i=s.slice(0,r);return s=s.slice(r),i},resetAfterLine:function(){s.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function Z$(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<i;u++){let d=s(u,c,l);X$[n](e,o,d,r),r+=n}return r}function Q$(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<i;u++){let d=o.get(n),f=s(u,c,l);V$[n](e,d,f,r)}o.resetAfterLine()}}Ff.dataToBitMap=function(t,e){let s=e.width,n=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=J$(t,o));let l;o<=8?l=Buffer.alloc(s*n*4):l=new Uint16Array(s*n*4);let c=Math.pow(2,o)-1,u=0,d,f;if(i)d=qf.getImagePasses(s,n),f=qf.getInterlaceIterator(s,n);else{let p=0;f=function(){let m=p;return p+=4,m},d=[{width:s,height:n}]}for(let p=0;p<d.length;p++)o===8?u=Z$(d[p],l,f,r,t,u):Q$(d[p],l,f,r,a,c);if(o===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var wl=Z((vR,Bf)=>{"use strict";function eb(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=o[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let c=0;c<4;c++)e[r+c]=l[c];r+=4}}function tb(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=!1;if(o.length===1?o[0]===t[r]&&(l=!0):o[0]===t[r]&&o[1]===t[r+1]&&o[2]===t[r+2]&&(l=!0),l)for(let c=0;c<4;c++)e[r+c]=0;r+=4}}function nb(t,e,s,n,o){let r=255,i=Math.pow(2,o)-1,a=0;for(let l=0;l<n;l++)for(let c=0;c<s;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}Bf.exports=function(t,e,s=!1){let n=e.depth,o=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,c=t;return i===3?eb(t,c,o,r,l):(a&&tb(t,c,o,r,a),n!==8&&!s&&(n===16&&(c=Buffer.alloc(o*r*4)),nb(t,c,o,r,n))),c}});var Hf=Z((TR,Wf)=>{"use strict";var sb=require("util"),_l=require("zlib"),Uf=ll(),ob=Lf(),rb=gl(),ib=yl(),ab=wl(),Jt=Wf.exports=function(t){Uf.call(this),this._parser=new rb(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};sb.inherits(Jt,Uf);Jt.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};Jt.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=_l.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let s=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(s,_l.Z_MIN_CHUNK);this._inflate=_l.createInflate({chunkSize:n});let o=s,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){o&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){o&&(a.length>o&&(a=a.slice(0,o)),o-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};Jt.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new ob(this._bitmapInfo)};Jt.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Jt.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Jt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Jt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Jt.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Jt.prototype._complete=function(t){if(this.errord)return;let e;try{let s=ib.dataToBitMap(t,this._bitmapInfo);e=ab(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var Gf=Z((RR,Yf)=>{"use strict";var Nt=Ns();Yf.exports=function(t,e,s,n){let o=[Nt.COLORTYPE_COLOR_ALPHA,Nt.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let m=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&m)return t}let r=n.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=Nt.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let l=Nt.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*s*l),u=0,d=0,f=n.bgColor||{};f.red===void 0&&(f.red=i),f.green===void 0&&(f.green=i),f.blue===void 0&&(f.blue=i);function p(){let m,g,_,k=i;switch(n.inputColorType){case Nt.COLORTYPE_COLOR_ALPHA:k=r[u+3],m=r[u],g=r[u+1],_=r[u+2];break;case Nt.COLORTYPE_COLOR:m=r[u],g=r[u+1],_=r[u+2];break;case Nt.COLORTYPE_ALPHA:k=r[u+1],m=r[u],g=m,_=m;break;case Nt.COLORTYPE_GRAYSCALE:m=r[u],g=m,_=m;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(o||(k/=i,m=Math.min(Math.max(Math.round((1-k)*f.red+k*m),0),i),g=Math.min(Math.max(Math.round((1-k)*f.green+k*g),0),i),_=Math.min(Math.max(Math.round((1-k)*f.blue+k*_),0),i))),{red:m,green:g,blue:_,alpha:k}}for(let m=0;m<s;m++)for(let g=0;g<e;g++){let _=p(r,u);switch(n.colorType){case Nt.COLORTYPE_COLOR_ALPHA:case Nt.COLORTYPE_COLOR:n.bitDepth===8?(c[d]=_.red,c[d+1]=_.green,c[d+2]=_.blue,o&&(c[d+3]=_.alpha)):(c.writeUInt16BE(_.red,d),c.writeUInt16BE(_.green,d+2),c.writeUInt16BE(_.blue,d+4),o&&c.writeUInt16BE(_.alpha,d+6));break;case Nt.COLORTYPE_ALPHA:case Nt.COLORTYPE_GRAYSCALE:{let k=(_.red+_.green+_.blue)/3;n.bitDepth===8?(c[d]=k,o&&(c[d+1]=_.alpha)):(c.writeUInt16BE(k,d),o&&c.writeUInt16BE(_.alpha,d+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}u+=a,d+=l}return c}});var Xf=Z((CR,Kf)=>{"use strict";var zf=dl();function lb(t,e,s,n,o){for(let r=0;r<s;r++)n[o+r]=t[e+r]}function cb(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++)n+=Math.abs(t[r]);return n}function ub(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;n[o+i]=l}}function db(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=t[e+r]-i;o+=Math.abs(a)}return o}function fb(t,e,s,n,o){for(let r=0;r<s;r++){let i=e>0?t[e+r-s]:0,a=t[e+r]-i;n[o+r]=a}}function hb(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++){let i=e>0?t[r-s]:0,a=t[r]-i;n+=Math.abs(a)}return n}function pb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=t[e+i]-(a+l>>1);n[o+i]=c}}function mb(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=t[e+r]-(i+a>>1);o+=Math.abs(l)}return o}function gb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=e>0&&i>=r?t[e+i-(s+r)]:0,u=t[e+i]-zf(a,l,c);n[o+i]=u}}function yb(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=e>0&&r>=n?t[e+r-(s+n)]:0,c=t[e+r]-zf(i,a,l);o+=Math.abs(c)}return o}var wb={0:lb,1:ub,2:fb,3:pb,4:gb},_b={0:cb,1:db,2:hb,3:mb,4:yb};Kf.exports=function(t,e,s,n,o){let r;if(!("filterType"in n)||n.filterType===-1)r=[0,1,2,3,4];else if(typeof n.filterType=="number")r=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(o*=2);let i=e*o,a=0,l=0,c=Buffer.alloc((i+1)*s),u=r[0];for(let d=0;d<s;d++){if(r.length>1){let f=1/0;for(let p=0;p<r.length;p++){let m=_b[r[p]](t,l,i,o);m<f&&(u=r[p],f=m)}}c[a]=u,a++,wb[u](t,l,i,c,a,o),a+=i,l+=i}return c}});var $l=Z((AR,Vf)=>{"use strict";var rt=Ns(),$b=ml(),bb=Gf(),kb=Xf(),xb=require("zlib"),Sn=Vf.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||xb.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:rt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:rt.COLORTYPE_COLOR_ALPHA,[rt.COLORTYPE_GRAYSCALE,rt.COLORTYPE_COLOR,rt.COLORTYPE_COLOR_ALPHA,rt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([rt.COLORTYPE_GRAYSCALE,rt.COLORTYPE_COLOR,rt.COLORTYPE_COLOR_ALPHA,rt.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};Sn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Sn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Sn.prototype.filterData=function(t,e,s){let n=bb(t,e,s,this._options),o=rt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return kb(n,e,s,this._options,o)};Sn.prototype._packChunk=function(t,e){let s=e?e.length:0,n=Buffer.alloc(s+12);return n.writeUInt32BE(s,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE($b.crc32(n.slice(4,n.length-4)),n.length-4),n};Sn.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*rt.GAMMA_DIVISION),0),this._packChunk(rt.TYPE_gAMA,e)};Sn.prototype.packIHDR=function(t,e){let s=Buffer.alloc(13);return s.writeUInt32BE(t,0),s.writeUInt32BE(e,4),s[8]=this._options.bitDepth,s[9]=this._options.colorType,s[10]=0,s[11]=0,s[12]=0,this._packChunk(rt.TYPE_IHDR,s)};Sn.prototype.packIDAT=function(t){return this._packChunk(rt.TYPE_IDAT,t)};Sn.prototype.packIEND=function(){return this._packChunk(rt.TYPE_IEND,null)}});var eh=Z((OR,Qf)=>{"use strict";var Sb=require("util"),Jf=require("stream"),Eb=Ns(),vb=$l(),Zf=Qf.exports=function(t){Jf.call(this);let e=t||{};this._packer=new vb(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Sb.inherits(Zf,Jf);Zf.prototype.pack=function(t,e,s,n){this.emit("data",Buffer.from(Eb.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,s)),n&&this.emit("data",this._packer.packGAMA(n));let o=this._packer.filterData(t,e,s);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(o)}});var ih=Z((bo,rh)=>{"use strict";var th=require("assert").ok,Ms=require("zlib"),Tb=require("util"),nh=require("buffer").kMaxLength;function Un(t){if(!(this instanceof Un))return new Un(t);t&&t.chunkSize<Ms.Z_MIN_CHUNK&&(t.chunkSize=Ms.Z_MIN_CHUNK),Ms.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function Rb(t){return new Un(t)}function sh(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Un.prototype._processChunk=function(t,e,s){if(typeof s=="function")return Ms.Inflate._processChunk.call(this,t,e,s);let n=this,o=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(m){u=m});function d(m,g){if(n._hadError)return;let _=r-g;if(th(_>=0,"have should not go down"),_>0){let k=n._buffer.slice(n._offset,n._offset+_);if(n._offset+=_,k.length>i&&(k=k.slice(0,i)),l.push(k),c+=k.length,i-=k.length,i===0)return!1}return(g===0||n._offset>=n._chunkSize)&&(r=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),g===0?(a+=o-m,o=m,!0):!1}th(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,o,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=nh)throw sh(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+nh.toString(16)+" bytes");let p=Buffer.concat(l,c);return sh(this),p};Tb.inherits(Un,Ms.Inflate);function Cb(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let s=t._finishFlushFlag;return s==null&&(s=Ms.Z_FINISH),t._processChunk(e,s)}function oh(t,e){return Cb(new Un(e),t)}rh.exports=bo=oh;bo.Inflate=Un;bo.createInflate=Rb;bo.inflateSync=oh});var bl=Z((NR,lh)=>{"use strict";var ah=lh.exports=function(t){this._buffer=t,this._reads=[]};ah.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};ah.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw new Error("unrecognised content at end of stream")}});var uh=Z(ch=>{"use strict";var Ab=bl(),Ob=fl();ch.process=function(t,e){let s=[],n=new Ab(t);return new Ob(e,{read:n.read.bind(n),write:function(r){s.push(r)},complete:function(){}}).start(),n.process(),Buffer.concat(s)}});var ph=Z((PR,hh)=>{"use strict";var dh=!0,fh=require("zlib"),Nb=ih();fh.deflateSync||(dh=!1);var Mb=bl(),Pb=uh(),Lb=gl(),Ib=yl(),Db=wl();hh.exports=function(t,e){if(!dh)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s;function n(E){s=E}let o;function r(E){o=E}function i(E){o.transColor=E}function a(E){o.palette=E}function l(){o.alpha=!0}let c;function u(E){c=E}let d=[];function f(E){d.push(E)}let p=new Mb(t);if(new Lb(e,{read:p.read.bind(p),error:n,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),p.process(),s)throw s;let g=Buffer.concat(d);d.length=0;let _;if(o.interlace)_=fh.inflateSync(g);else{let v=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;_=Nb(g,{chunkSize:v,maxLength:v})}if(g=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let k=Pb.process(_,o);g=null;let A=Ib.dataToBitMap(k,o);k=null;let L=Db(A,o,e.skipRescale);return o.data=L,o.gamma=c||0,o}});var wh=Z((LR,yh)=>{"use strict";var mh=!0,gh=require("zlib");gh.deflateSync||(mh=!1);var jb=Ns(),qb=$l();yh.exports=function(t,e){if(!mh)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s=e||{},n=new qb(s),o=[];o.push(Buffer.from(jb.PNG_SIGNATURE)),o.push(n.packIHDR(t.width,t.height)),t.gamma&&o.push(n.packGAMA(t.gamma));let r=n.filterData(t.data,t.width,t.height),i=gh.deflateSync(r,n.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return o.push(n.packIDAT(i)),o.push(n.packIEND()),Buffer.concat(o)}});var _h=Z(kl=>{"use strict";var Fb=ph(),Bb=wh();kl.read=function(t,e){return Fb(t,e||{})};kl.write=function(t,e){return Bb(t,e)}});var kh=Z(bh=>{"use strict";var Ub=require("util"),$h=require("stream"),Wb=Hf(),Hb=eh(),Yb=_h(),ut=bh.PNG=function(t){$h.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new Wb(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new Hb(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Ub.inherits(ut,$h);ut.sync=Yb;ut.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};ut.prototype.parse=function(t,e){if(e){let s,n;s=function(o){this.removeListener("error",n),this.data=o,e(null,this)}.bind(this),n=function(o){this.removeListener("parsed",s),e(o,null)}.bind(this),this.once("parsed",s),this.once("error",n)}return this.end(t),this};ut.prototype.write=function(t){return this._parser.write(t),!0};ut.prototype.end=function(t){this._parser.end(t)};ut.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};ut.prototype._gamma=function(t){this.gamma=t};ut.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};ut.bitblt=function(t,e,s,n,o,r,i,a){if(s|=0,n|=0,o|=0,r|=0,i|=0,a|=0,s>t.width||n>t.height||s+o>t.width||n+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+o>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<r;l++)t.data.copy(e.data,(a+l)*e.width+i<<2,(n+l)*t.width+s<<2,(n+l)*t.width+s+o<<2)};ut.prototype.bitblt=function(t,e,s,n,o,r,i){return ut.bitblt(this,t,e,s,n,o,r,i),this};ut.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let s=0;s<t.width;s++){let n=t.width*e+s<<2;for(let o=0;o<3;o++){let r=t.data[n+o]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[n+o]=Math.round(r*255)}}t.gamma=0}};ut.prototype.adjustGamma=function(){ut.adjustGamma(this)}});var Th={};Dy(Th,{default:()=>Eh});function Eh(t,e,s,n,o,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:c=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=r;if(!xl(t)||!xl(e)||s&&!xl(s))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||s&&s.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==n*o*4)throw new Error("Image data size does not match width/height.");let p=n*o,m=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),_=!0;for(let S=0;S<p;S++)if(m[S]!==g[S]){_=!1;break}if(_){if(s&&!f)for(let S=0;S<p;S++)Sh(t,4*S,a,s);return 0}let k=35215*i*i,[A,L,E]=l,[v,N,te]=c,[V,re,le]=d||c,ne=0;for(let S=0;S<o;S++)for(let Ee=0;Ee<n;Ee++){let W=S*n+Ee,J=W*4,he=m[W]===g[W]?0:vh(t,e,J,J,!1);if(Math.abs(he)>k){let Re=xh(t,Ee,S,n,o,m,g)||xh(e,Ee,S,n,o,g,m);!u&&Re?s&&!f&&si(s,J,A,L,E):(s&&(he<0?si(s,J,V,re,le):si(s,J,v,N,te)),ne++)}else s&&!f&&Sh(t,J,a,s)}return ne}function xl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function xh(t,e,s,n,o,r,i){let a=Math.max(e-1,0),l=Math.max(s-1,0),c=Math.min(e+1,n-1),u=Math.min(s+1,o-1),d=s*n+e,f=e===a||e===c||s===l||s===u?1:0,p=0,m=0,g=0,_=0,k=0,A=0;for(let L=a;L<=c;L++)for(let E=l;E<=u;E++){if(L===e&&E===s)continue;let v=vh(t,t,d*4,(E*n+L)*4,!0);if(v===0){if(f++,f>2)return!1}else v<p?(p=v,g=L,_=E):v>m&&(m=v,k=L,A=E)}return p===0||m===0?!1:ni(r,g,_,n,o)&&ni(i,g,_,n,o)||ni(r,k,A,n,o)&&ni(i,k,A,n,o)}function ni(t,e,s,n,o){let r=Math.max(e-1,0),i=Math.max(s-1,0),a=Math.min(e+1,n-1),l=Math.min(s+1,o-1),c=t[s*n+e],u=e===r||e===a||s===i||s===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===s)&&(u+=+(c===t[f*n+d]),u>2))return!0;return!1}function vh(t,e,s,n,o){let r=t[s],i=t[s+1],a=t[s+2],l=t[s+3],c=e[n],u=e[n+1],d=e[n+2],f=e[n+3],p=r-c,m=i-u,g=a-d,_=l-f;if(!p&&!m&&!g&&!_)return 0;if(l<255||f<255){let v=48+159*(s%2),N=48+159*((s/1.618033988749895|0)%2),te=48+159*((s/2.618033988749895|0)%2);p=(r*l-c*f-v*_)/255,m=(i*l-u*f-N*_)/255,g=(a*l-d*f-te*_)/255}let k=p*.29889531+m*.58662247+g*.11448223;if(o)return k;let A=p*.59597799-m*.2741761-g*.32180189,L=p*.21147017-m*.52261711+g*.31114694,E=.5053*k*k+.299*A*A+.1957*L*L;return k>0?-E:E}function si(t,e,s,n,o){t[e+0]=s,t[e+1]=n,t[e+2]=o,t[e+3]=255}function Sh(t,e,s,n){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;si(n,e,o,o,o)}var Rh=Iy(()=>{});var Wn=Z((jR,Mh)=>{var dn=require("fs"),Gb=require("path"),zb=require("os"),Kb="nex-visual-";function Ah(t){return Gb.join(zb.tmpdir(),`${Kb}${Date.now()}-${t}`)}var Sl=null;function oi(){return Sl||(Sl=kh().PNG),Sl}var El=null;function Xb(){if(!El){let t=(Rh(),qy(Th));El=t.default||t}return El}function Rl(t,e,{threshold:s=.1}={}){let n=oi(),o=Xb(),r=n.sync.read(dn.readFileSync(t)),i=n.sync.read(dn.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=Ch(r,a,l),u=Ch(i,a,l),d=new n({width:a,height:l}),f=o(c,u,d.data,a,l,{threshold:s,includeAA:!1}),p=a*l,m=(f/p*100).toFixed(1),g=Vb(d.data,a,l,3,3),_=Ah("diff.png");return dn.writeFileSync(_,n.sync.write(d),{mode:384}),{diffPath:_,diffPercent:parseFloat(m),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function Ch(t,e,s){if(t.width===e&&t.height===s)return t.data;let n=Buffer.alloc(e*s*4,0);for(let o=0;o<t.height;o++){let r=o*t.width*4,i=o*e*4;t.data.copy(n,i,r,r+t.width*4)}return n}function Vb(t,e,s,n,o){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/n),a=Math.ceil(s/o),l=[];for(let c=0;c<o;c++)for(let u=0;u<n;u++){let d=0,f=0,p=u*i,m=c*a,g=Math.min(p+i,e),_=Math.min(m+a,s);for(let k=m;k<_;k++)for(let A=p;A<g;A++){f++;let L=(k*e+A)*4;(t[L]>0||t[L+1]>0)&&d++}if(d>0){let k=(d/f*100).toFixed(1),A=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:A,changedPercent:parseFloat(k),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var Oh=[{width:320,label:"mobile-sm"},{width:768,label:"tablet"},{width:1024,label:"desktop-sm"},{width:1440,label:"desktop"},{width:1920,label:"desktop-lg"}];async function Jb(t,{viewports:e=Oh,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=un(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:s,fullPage:n,timeout:o});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function Nh(t,e=[]){let s=oi(),n=s.sync.read(dn.readFileSync(t));for(let i of e){let a=Zb(i.color||"#FF0000");i.type==="box"?(Qb(n,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Tl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(ek(n,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Tl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(tk(n,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Tl(n,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=Ah("annotated.png");dn.writeFileSync(o,s.sync.write(n),{mode:384});let r=dn.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function Zb(t){let e=t.replace("#","");return{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16),a:255}}function Zt(t,e,s,n){if(e<0||s<0||e>=t.width||s>=t.height)return;let o=(s*t.width+e)*4;t.data[o]=n.r,t.data[o+1]=n.g,t.data[o+2]=n.b,t.data[o+3]=n.a}function Qb(t,e,s,n,o,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<n;l++)Zt(t,e+l,s+a,r),Zt(t,e+l,s+o-1-a,r);for(let l=0;l<o;l++)Zt(t,e+a,s+l,r),Zt(t,e+n-1-a,s+l,r)}}function vl(t,e,s,n,o,r,i=3){let a=Math.abs(n-e),l=Math.abs(o-s),c=e<n?1:-1,u=s<o?1:-1,d=a-l,f=e,p=s;for(;;){let m=Math.floor(i/2);for(let _=-m;_<=m;_++)for(let k=-m;k<=m;k++)Zt(t,f+_,p+k,r);if(f===n&&p===o)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,p+=u)}}function ek(t,e,s,n,o,r,i=3){vl(t,e,s,n,o,r,i);let a=Math.atan2(o-s,n-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;vl(t,n,o,Math.round(n+l*Math.cos(c)),Math.round(o+l*Math.sin(c)),r,i),vl(t,n,o,Math.round(n+l*Math.cos(u)),Math.round(o+l*Math.sin(u)),r,i)}function tk(t,e,s,n,o,r=3){for(let i=0;i<r;i++){let a=n-i;for(let l=0;l<360;l+=.5){let c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(s+a*Math.sin(c));Zt(t,u,d,o)}}}function Tl(t,e,s,n,o){let i=n.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)Zt(t,e+c,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)Zt(t,e+l,s+a-1,o),Zt(t,e+l,s+a-2,o);for(let l=0;l<n.length;l++){let c=e+2+l*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)Zt(t,c+d,s+u,o)}}async function*nk(t,e,{maxIterations:s=20,hmrDelay:n=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=un(),l=sk("chokidar"),c=await a(t,{width:o,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:c.path,base64:c.base64,media_type:c.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let u=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;u<s;){await rk(()=>d,3e5),d=!1,u++,await ok(n);let p=await a(t,{width:o,height:r,timeout:i}),m=null;try{m=Rl(c.path,p.path)}catch{}c=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function sk(t){try{return require(t)}catch{return null}}function ok(t){return new Promise(e=>setTimeout(e,t))}function rk(t,e=6e4){return new Promise((s,n)=>{let o=setInterval(()=>{t()&&(clearInterval(o),clearTimeout(r),s())},200),r=setTimeout(()=>{clearInterval(o),n(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function ik(t,{sampleRate:e=4}={}){let n=oi().sync.read(dn.readFileSync(t)),o=new Map;for(let c=0;c<n.height;c+=e)for(let u=0;u<n.width;u+=e){let d=(c*n.width+u)*4,f=n.data[d],p=n.data[d+1],m=n.data[d+2];if(n.data[d+3]<128)continue;let _=Math.round(f/8)*8,k=Math.round(p/8)*8,A=Math.round(m/8)*8,L=`${_},${k},${A}`;o.set(L,(o.get(L)||0)+1)}let r=[...o.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,p]=c.split(",").map(Number);return{hex:ak(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:lk(d,f,p)}}),l=ck(n);return{colors:a,spacing:l,dimensions:{width:n.width,height:n.height},imagePath:t}}function ak(t,e,s){return"#"+[t,e,s].map(n=>Math.min(255,n).toString(16).padStart(2,"0")).join("")}function lk(t,e,s){let n=(t*299+e*587+s*114)/1e3;return n>240?"white/background":n<30?"black/text":n<80?"dark":t>200&&e<100&&s<100?"red/danger":t<100&&e>150&&s<100?"green/success":t<100&&e<100&&s>200?"blue/primary":t>200&&e>200&&s<100?"yellow/warning":t>200&&e>100&&s<50?"orange/accent":n>200?"light/subtle":"midtone"}function ck(t){let e=[],s=!1,n=0,o=uk(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let c=(i*t.width+l)*4;if(Math.abs(t.data[c]-o.r)>20||Math.abs(t.data[c+1]-o.g)>20||Math.abs(t.data[c+2]-o.b)>20){a=!1;break}}if(a&&s)s=!1,n=i;else if(!a&&!s&&(s=!0,n>0)){let l=i-n;l>=4&&l<=200&&e.push(l)}}let r=new Map;for(let i of e){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function uk(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],s=0,n=0,o=0;for(let[r,i]of e){let a=(i*t.width+r)*4;s+=t.data[a],n+=t.data[a+1],o+=t.data[a+2]}return{r:Math.round(s/4),g:Math.round(n/4),b:Math.round(o/4)}}async function dk(t,e,{width:s,height:n=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=un(),c=oi().sync.read(dn.readFileSync(e)),u=s||c.width,d=n||c.height,f=await a(t,{width:u,height:d,fullPage:o,timeout:i}),p=Rl(e,f.path,{threshold:r}),m=Nh(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,_)=>{let L=Math.ceil(p.width/3),E=Math.ceil(p.height/3),v=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],N=0,te=0;for(let V=0;V<3;V++)for(let re=0;re<3;re++)v[V][re]===g.name&&(N=re,te=V);return{type:"box",x:N*L+2,y:te*E+2,width:L-4,height:E-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:p.diffPath,annotatedPath:m.path,diffPercent:p.diffPercent,changedPixels:p.changedPixels,totalPixels:p.totalPixels,regions:p.regionSummary,liveBase64:f.base64,diffBase64:dn.readFileSync(p.diffPath).toString("base64"),annotatedBase64:m.base64}}Mh.exports={pixelDiff:Rl,responsiveSweep:Jb,annotateImage:Nh,visualWatch:nk,extractDesignTokens:ik,designCompare:dk,DEFAULT_VIEWPORTS:Oh}});var Cl=Z((qR,Ph)=>{var{C:Me}=Je(),xo="",dt=[],ko=0,Hn=null;function fk(t){Hn=t}function hk(t,e){xo=t,dt=[],ko=0;for(let n of e){ko++;let o=`t${ko}`;dt.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${ko}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=dt.map(n=>({...n}));return Hn&&Hn("create",{name:t,tasks:s}),s}function pk(t,e,s){let n=dt.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Hn&&Hn("update",{id:t,status:e,result:s}),{...n}):null}function mk(){return{name:xo,tasks:dt.map(t=>({...t}))}}function gk(){xo="",dt=[],ko=0,Hn&&Hn("clear",{})}function yk(){return dt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=dt.find(n=>n.id===e);return s&&s.status==="done"}))}function wk(){if(dt.length===0)return`${Me.dim}No active tasks${Me.reset}`;let t=[];xo&&(t.push(` ${Me.bold}${Me.cyan}Tasks: ${xo}${Me.reset}`),t.push(` ${Me.dim}${"\u2500".repeat(40)}${Me.reset}`));for(let o of dt){let r,i;switch(o.status){case"done":r="\u2713",i=Me.green;break;case"in_progress":r="\u2192",i=Me.cyan;break;case"failed":r="\u2717",i=Me.red;break;default:r="\xB7",i=Me.dim}let a=o.dependsOn.length>0?` ${Me.dim}(after: ${o.dependsOn.join(", ")})${Me.reset}`:"",l=`[${o.status}]`,c=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Me.reset} ${Me.bold}${o.id}${Me.reset} ${c.padEnd(40)} ${i}${l}${Me.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Me.dim}\u2192 ${u}${Me.reset}`)}}let e=dt.filter(o=>o.status==="done").length,s=dt.filter(o=>o.status==="failed").length,n=dt.length;return t.push(` ${Me.dim}${"\u2500".repeat(40)}${Me.reset}`),t.push(` ${Me.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Me.reset}`),t.join(`
133
- `)}function _k(){return dt.length>0&&dt.some(t=>t.status==="pending"||t.status==="in_progress")}Ph.exports={createTasks:hk,updateTask:pk,getTaskList:mk,clearTasks:gk,getReadyTasks:yk,renderTaskList:wk,setOnChange:fk,hasActiveTasks:_k}});var Ol=Z((FR,Fh)=>{var{callChat:$k}=ot(),{estimateTokens:Al}=Qt(),Lh=process.env.NEX_COMPACTION!=="false",Ih=6,Dh=2e3,jh=3,bk=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
131
+ Then restart nex-code.`;function Hf(){if(So!==null)return So;try{require("playwright"),So=!0}catch{So=!1}return So}async function ci(){if(!Hf())throw new Error(Wf);return wl||(wl=require("playwright")),(!gn||!gn.isConnected())&&(gn=await wl.chromium.launch({headless:!0})),gn}async function hb(){if(gn){try{await gn.close()}catch(t){console.error("closeBrowser failed:",t.message)}gn=null}}process.on("exit",()=>{if(gn)try{gn.close()}catch(t){console.error("Error closing browser on exit:",t.message)}});async function mb(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await ci()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(c=>c.remove()),document.body?.innerText||"")),a=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
132
+ ...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function gb(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await ci()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:n}),l=require("os"),c=require("path"),u=require("fs"),d=c.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a,{mode:384}),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function yb(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await ci()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function wb(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await ci()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}Yf.exports={isPlaywrightAvailable:Hf,browserNavigate:mb,browserScreenshot:gb,browserClick:yb,browserFill:wb,closeBrowser:hb,INSTALL_MSG:Wf}});var $l=V((w1,zf)=>{"use strict";var $b=require("util"),Gf=require("stream"),Yt=zf.exports=function(){Gf.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};$b.inherits(Yt,Gf);Yt.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};Yt.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let s;return Buffer.isBuffer(t)?s=t:s=Buffer.from(t,e||this._encoding),this._buffers.push(s),this._buffered+=s.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Yt.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};Yt.prototype.destroySoon=Yt.prototype.end;Yt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Yt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Yt.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};Yt.prototype._processRead=function(t){this._reads.shift();let e=0,s=0,n=Buffer.alloc(t.length);for(;e<t.length;){let o=this._buffers[s++],r=Math.min(o.length,t.length-e);o.copy(n,e,0,r),e+=r,r!==o.length&&(this._buffers[--s]=o.slice(r))}s>0&&this._buffers.splice(0,s),this._buffered-=t.length,t.func.call(this,n)};Yt.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var bl=V(_l=>{"use strict";var An=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];_l.getImagePasses=function(t,e){let s=[],n=t%8,o=e%8,r=(t-n)/8,i=(e-o)/8;for(let a=0;a<An.length;a++){let l=An[a],c=r*l.x.length,u=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<n;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<o;d++)u++;c>0&&u>0&&s.push({width:c,height:u,index:a})}return s};_l.getInterlaceIterator=function(t){return function(e,s,n){let o=e%An[n].x.length,r=(e-o)/An[n].x.length*8+An[n].x[o],i=s%An[n].y.length,a=(s-i)/An[n].y.length*8+An[n].y[i];return r*4+a*t*4}}});var kl=V((_1,Kf)=>{"use strict";Kf.exports=function(e,s,n){let o=e+s-n,r=Math.abs(o-e),i=Math.abs(o-s),a=Math.abs(o-n);return r<=i&&r<=a?e:i<=a?s:n}});var xl=V((b1,Vf)=>{"use strict";var _b=bl(),bb=kl();function Xf(t,e,s){let n=t*e;return s!==8&&(n=Math.ceil(n/(8/s))),n}var Ls=Vf.exports=function(t,e){let s=t.width,n=t.height,o=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],o){let a=_b.getImagePasses(s,n);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Xf(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Xf(s,r,i),height:n,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Ls.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ls.prototype._unFilterType1=function(t,e,s){let n=this._xComparison,o=n-1;for(let r=0;r<s;r++){let i=t[1+r],a=r>o?e[r-n]:0;e[r]=i+a}};Ls.prototype._unFilterType2=function(t,e,s){let n=this._lastLine;for(let o=0;o<s;o++){let r=t[1+o],i=n?n[o]:0;e[o]=r+i}};Ls.prototype._unFilterType3=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=Math.floor((c+l)/2);e[i]=a+u}};Ls.prototype._unFilterType4=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=i>o&&r?r[i-n]:0,d=bb(c,l,u);e[i]=a+d}};Ls.prototype._reverseFilterLine=function(t){let e=t[0],s,n=this._images[this._imageIndex],o=n.byteWidth;if(e===0)s=t.slice(1,o+1);else switch(s=Buffer.alloc(o),e){case 1:this._unFilterType1(t,s,o);break;case 2:this._unFilterType2(t,s,o);break;case 3:this._unFilterType3(t,s,o);break;case 4:this._unFilterType4(t,s,o);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(s),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=s,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Qf=V((k1,Zf)=>{"use strict";var kb=require("util"),Jf=$l(),xb=xl(),Sb=Zf.exports=function(t){Jf.call(this);let e=[],s=this;this._filter=new xb(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};kb.inherits(Sb,Jf)});var Is=V((x1,ep)=>{"use strict";ep.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var vl=V((S1,tp)=>{"use strict";var Sl=[];(function(){for(let t=0;t<256;t++){let e=t;for(let s=0;s<8;s++)e&1?e=3988292384^e>>>1:e=e>>>1;Sl[t]=e}})();var El=tp.exports=function(){this._crc=-1};El.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Sl[(this._crc^t[e])&255]^this._crc>>>8;return!0};El.prototype.crc32=function(){return this._crc^-1};El.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=Sl[(e^t[s])&255]^e>>>8;return e^-1}});var Tl=V((E1,np)=>{"use strict";var Ke=Is(),Eb=vl(),Ve=np.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Ke.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ke.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ke.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ke.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ke.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ke.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Ve.prototype.start=function(){this.read(Ke.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ve.prototype._parseSignature=function(t){let e=Ke.PNG_SIGNATURE;for(let s=0;s<e.length;s++)if(t[s]!==e[s]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ve.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n="";for(let r=4;r<8;r++)n+=String.fromCharCode(t[r]);let o=!!(t[4]&32);if(!this._hasIHDR&&s!==Ke.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Eb,this._crc.write(Buffer.from(n)),this._chunks[s])return this._chunks[s](e);if(!o){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};Ve.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ve.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ve.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),s=this._crc.crc32();if(this._options.checkCRC&&s!==e){this.error(new Error("Crc error - "+e+" - "+s));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};Ve.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Ve.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n=t[8],o=t[9],r=t[10],i=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(o in Ke.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=o;let l=Ke.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:s,depth:n,interlace:!!a,palette:!!(o&Ke.COLORTYPE_PALETTE),color:!!(o&Ke.COLORTYPE_COLOR),alpha:!!(o&Ke.COLORTYPE_ALPHA),bpp:l,colorType:o}),this._handleChunkEnd()};Ve.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Ve.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let s=0;s<e;s++)this._palette.push([t[s*3],t[s*3+1],t[s*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ve.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Ve.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Ke.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===Ke.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===Ke.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};Ve.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Ve.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Ke.GAMMA_DIVISION),this._handleChunkEnd()};Ve.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};Ve.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Ke.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let s=t-e.length;s>0?this._handleIDAT(s):this._handleChunkEnd()};Ve.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Ve.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Rl=V(op=>{"use strict";var sp=bl(),vb=[function(){},function(t,e,s,n){if(n===e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=255},function(t,e,s,n){if(n+1>=e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=e[n+1]},function(t,e,s,n){if(n+2>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=255},function(t,e,s,n){if(n+3>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=e[n+3]}],Tb=[function(){},function(t,e,s,n){let o=e[0];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=n},function(t,e,s){let n=e[0];t[s]=n,t[s+1]=n,t[s+2]=n,t[s+3]=e[1]},function(t,e,s,n){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=n},function(t,e,s){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=e[3]}];function Rb(t,e){let s=[],n=0;function o(){if(n===t.length)throw new Error("Ran out of data");let r=t[n];n++;let i,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[n],n++,s.push((r<<8)+f);break;case 4:f=r&15,p=r>>4,s.push(p,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,s.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,s.push(p,f,d,u,c,l,a,i);break}}return{get:function(r){for(;s.length<r;)o();let i=s.slice(0,r);return s=s.slice(r),i},resetAfterLine:function(){s.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function Cb(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<i;u++){let d=s(u,c,l);vb[n](e,o,d,r),r+=n}return r}function Ab(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<i;u++){let d=o.get(n),f=s(u,c,l);Tb[n](e,d,f,r)}o.resetAfterLine()}}op.dataToBitMap=function(t,e){let s=e.width,n=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=Rb(t,o));let l;o<=8?l=Buffer.alloc(s*n*4):l=new Uint16Array(s*n*4);let c=Math.pow(2,o)-1,u=0,d,f;if(i)d=sp.getImagePasses(s,n),f=sp.getInterlaceIterator(s,n);else{let p=0;f=function(){let m=p;return p+=4,m},d=[{width:s,height:n}]}for(let p=0;p<d.length;p++)o===8?u=Cb(d[p],l,f,r,t,u):Ab(d[p],l,f,r,a,c);if(o===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Cl=V((T1,rp)=>{"use strict";function Ob(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=o[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let c=0;c<4;c++)e[r+c]=l[c];r+=4}}function Nb(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=!1;if(o.length===1?o[0]===t[r]&&(l=!0):o[0]===t[r]&&o[1]===t[r+1]&&o[2]===t[r+2]&&(l=!0),l)for(let c=0;c<4;c++)e[r+c]=0;r+=4}}function Mb(t,e,s,n,o){let r=255,i=Math.pow(2,o)-1,a=0;for(let l=0;l<n;l++)for(let c=0;c<s;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}rp.exports=function(t,e,s=!1){let n=e.depth,o=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,c=t;return i===3?Ob(t,c,o,r,l):(a&&Nb(t,c,o,r,a),n!==8&&!s&&(n===16&&(c=Buffer.alloc(o*r*4)),Mb(t,c,o,r,n))),c}});var lp=V((R1,ap)=>{"use strict";var Pb=require("util"),Al=require("zlib"),ip=$l(),Lb=Qf(),Ib=Tl(),jb=Rl(),Db=Cl(),nn=ap.exports=function(t){ip.call(this),this._parser=new Ib(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Pb.inherits(nn,ip);nn.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};nn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Al.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let s=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(s,Al.Z_MIN_CHUNK);this._inflate=Al.createInflate({chunkSize:n});let o=s,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){o&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){o&&(a.length>o&&(a=a.slice(0,o)),o-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};nn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Lb(this._bitmapInfo)};nn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};nn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};nn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};nn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};nn.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};nn.prototype._complete=function(t){if(this.errord)return;let e;try{let s=jb.dataToBitMap(t,this._bitmapInfo);e=Db(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var up=V((C1,cp)=>{"use strict";var It=Is();cp.exports=function(t,e,s,n){let o=[It.COLORTYPE_COLOR_ALPHA,It.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let m=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&m)return t}let r=n.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=It.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let l=It.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*s*l),u=0,d=0,f=n.bgColor||{};f.red===void 0&&(f.red=i),f.green===void 0&&(f.green=i),f.blue===void 0&&(f.blue=i);function p(){let m,g,$,k=i;switch(n.inputColorType){case It.COLORTYPE_COLOR_ALPHA:k=r[u+3],m=r[u],g=r[u+1],$=r[u+2];break;case It.COLORTYPE_COLOR:m=r[u],g=r[u+1],$=r[u+2];break;case It.COLORTYPE_ALPHA:k=r[u+1],m=r[u],g=m,$=m;break;case It.COLORTYPE_GRAYSCALE:m=r[u],g=m,$=m;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(o||(k/=i,m=Math.min(Math.max(Math.round((1-k)*f.red+k*m),0),i),g=Math.min(Math.max(Math.round((1-k)*f.green+k*g),0),i),$=Math.min(Math.max(Math.round((1-k)*f.blue+k*$),0),i))),{red:m,green:g,blue:$,alpha:k}}for(let m=0;m<s;m++)for(let g=0;g<e;g++){let $=p(r,u);switch(n.colorType){case It.COLORTYPE_COLOR_ALPHA:case It.COLORTYPE_COLOR:n.bitDepth===8?(c[d]=$.red,c[d+1]=$.green,c[d+2]=$.blue,o&&(c[d+3]=$.alpha)):(c.writeUInt16BE($.red,d),c.writeUInt16BE($.green,d+2),c.writeUInt16BE($.blue,d+4),o&&c.writeUInt16BE($.alpha,d+6));break;case It.COLORTYPE_ALPHA:case It.COLORTYPE_GRAYSCALE:{let k=($.red+$.green+$.blue)/3;n.bitDepth===8?(c[d]=k,o&&(c[d+1]=$.alpha)):(c.writeUInt16BE(k,d),o&&c.writeUInt16BE($.alpha,d+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}u+=a,d+=l}return c}});var pp=V((A1,fp)=>{"use strict";var dp=kl();function qb(t,e,s,n,o){for(let r=0;r<s;r++)n[o+r]=t[e+r]}function Fb(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++)n+=Math.abs(t[r]);return n}function Bb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;n[o+i]=l}}function Ub(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=t[e+r]-i;o+=Math.abs(a)}return o}function Wb(t,e,s,n,o){for(let r=0;r<s;r++){let i=e>0?t[e+r-s]:0,a=t[e+r]-i;n[o+r]=a}}function Hb(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++){let i=e>0?t[r-s]:0,a=t[r]-i;n+=Math.abs(a)}return n}function Yb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=t[e+i]-(a+l>>1);n[o+i]=c}}function Gb(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=t[e+r]-(i+a>>1);o+=Math.abs(l)}return o}function zb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=e>0&&i>=r?t[e+i-(s+r)]:0,u=t[e+i]-dp(a,l,c);n[o+i]=u}}function Kb(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=e>0&&r>=n?t[e+r-(s+n)]:0,c=t[e+r]-dp(i,a,l);o+=Math.abs(c)}return o}var Xb={0:qb,1:Bb,2:Wb,3:Yb,4:zb},Vb={0:Fb,1:Ub,2:Hb,3:Gb,4:Kb};fp.exports=function(t,e,s,n,o){let r;if(!("filterType"in n)||n.filterType===-1)r=[0,1,2,3,4];else if(typeof n.filterType=="number")r=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(o*=2);let i=e*o,a=0,l=0,c=Buffer.alloc((i+1)*s),u=r[0];for(let d=0;d<s;d++){if(r.length>1){let f=1/0;for(let p=0;p<r.length;p++){let m=Vb[r[p]](t,l,i,o);m<f&&(u=r[p],f=m)}}c[a]=u,a++,Xb[u](t,l,i,c,a,o),a+=i,l+=i}return c}});var Ol=V((O1,hp)=>{"use strict";var ct=Is(),Jb=vl(),Zb=up(),Qb=pp(),ek=require("zlib"),On=hp.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||ek.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:ct.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:ct.COLORTYPE_COLOR_ALPHA,[ct.COLORTYPE_GRAYSCALE,ct.COLORTYPE_COLOR,ct.COLORTYPE_COLOR_ALPHA,ct.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([ct.COLORTYPE_GRAYSCALE,ct.COLORTYPE_COLOR,ct.COLORTYPE_COLOR_ALPHA,ct.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};On.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};On.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};On.prototype.filterData=function(t,e,s){let n=Zb(t,e,s,this._options),o=ct.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Qb(n,e,s,this._options,o)};On.prototype._packChunk=function(t,e){let s=e?e.length:0,n=Buffer.alloc(s+12);return n.writeUInt32BE(s,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(Jb.crc32(n.slice(4,n.length-4)),n.length-4),n};On.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*ct.GAMMA_DIVISION),0),this._packChunk(ct.TYPE_gAMA,e)};On.prototype.packIHDR=function(t,e){let s=Buffer.alloc(13);return s.writeUInt32BE(t,0),s.writeUInt32BE(e,4),s[8]=this._options.bitDepth,s[9]=this._options.colorType,s[10]=0,s[11]=0,s[12]=0,this._packChunk(ct.TYPE_IHDR,s)};On.prototype.packIDAT=function(t){return this._packChunk(ct.TYPE_IDAT,t)};On.prototype.packIEND=function(){return this._packChunk(ct.TYPE_IEND,null)}});var wp=V((N1,yp)=>{"use strict";var tk=require("util"),mp=require("stream"),nk=Is(),sk=Ol(),gp=yp.exports=function(t){mp.call(this);let e=t||{};this._packer=new sk(e),this._deflate=this._packer.createDeflate(),this.readable=!0};tk.inherits(gp,mp);gp.prototype.pack=function(t,e,s,n){this.emit("data",Buffer.from(nk.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,s)),n&&this.emit("data",this._packer.packGAMA(n));let o=this._packer.filterData(t,e,s);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(o)}});var Sp=V((Eo,xp)=>{"use strict";var $p=require("assert").ok,js=require("zlib"),ok=require("util"),_p=require("buffer").kMaxLength;function Kn(t){if(!(this instanceof Kn))return new Kn(t);t&&t.chunkSize<js.Z_MIN_CHUNK&&(t.chunkSize=js.Z_MIN_CHUNK),js.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function rk(t){return new Kn(t)}function bp(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Kn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return js.Inflate._processChunk.call(this,t,e,s);let n=this,o=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(m){u=m});function d(m,g){if(n._hadError)return;let $=r-g;if($p($>=0,"have should not go down"),$>0){let k=n._buffer.slice(n._offset,n._offset+$);if(n._offset+=$,k.length>i&&(k=k.slice(0,i)),l.push(k),c+=k.length,i-=k.length,i===0)return!1}return(g===0||n._offset>=n._chunkSize)&&(r=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),g===0?(a+=o-m,o=m,!0):!1}$p(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,o,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=_p)throw bp(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+_p.toString(16)+" bytes");let p=Buffer.concat(l,c);return bp(this),p};ok.inherits(Kn,js.Inflate);function ik(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let s=t._finishFlushFlag;return s==null&&(s=js.Z_FINISH),t._processChunk(e,s)}function kp(t,e){return ik(new Kn(e),t)}xp.exports=Eo=kp;Eo.Inflate=Kn;Eo.createInflate=rk;Eo.inflateSync=kp});var Nl=V((M1,vp)=>{"use strict";var Ep=vp.exports=function(t){this._buffer=t,this._reads=[]};Ep.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Ep.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw new Error("unrecognised content at end of stream")}});var Rp=V(Tp=>{"use strict";var ak=Nl(),lk=xl();Tp.process=function(t,e){let s=[],n=new ak(t);return new lk(e,{read:n.read.bind(n),write:function(r){s.push(r)},complete:function(){}}).start(),n.process(),Buffer.concat(s)}});var Np=V((L1,Op)=>{"use strict";var Cp=!0,Ap=require("zlib"),ck=Sp();Ap.deflateSync||(Cp=!1);var uk=Nl(),dk=Rp(),fk=Tl(),pk=Rl(),hk=Cl();Op.exports=function(t,e){if(!Cp)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s;function n(v){s=v}let o;function r(v){o=v}function i(v){o.transColor=v}function a(v){o.palette=v}function l(){o.alpha=!0}let c;function u(v){c=v}let d=[];function f(v){d.push(v)}let p=new uk(t);if(new fk(e,{read:p.read.bind(p),error:n,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),p.process(),s)throw s;let g=Buffer.concat(d);d.length=0;let $;if(o.interlace)$=Ap.inflateSync(g);else{let E=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;$=ck(g,{chunkSize:E,maxLength:E})}if(g=null,!$||!$.length)throw new Error("bad png - invalid inflate data response");let k=dk.process($,o);g=null;let M=pk.dataToBitMap(k,o);k=null;let D=hk(M,o,e.skipRescale);return o.data=D,o.gamma=c||0,o}});var Ip=V((I1,Lp)=>{"use strict";var Mp=!0,Pp=require("zlib");Pp.deflateSync||(Mp=!1);var mk=Is(),gk=Ol();Lp.exports=function(t,e){if(!Mp)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s=e||{},n=new gk(s),o=[];o.push(Buffer.from(mk.PNG_SIGNATURE)),o.push(n.packIHDR(t.width,t.height)),t.gamma&&o.push(n.packGAMA(t.gamma));let r=n.filterData(t.data,t.width,t.height),i=Pp.deflateSync(r,n.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return o.push(n.packIDAT(i)),o.push(n.packIEND()),Buffer.concat(o)}});var jp=V(Ml=>{"use strict";var yk=Np(),wk=Ip();Ml.read=function(t,e){return yk(t,e||{})};Ml.write=function(t,e){return wk(t,e)}});var Fp=V(qp=>{"use strict";var $k=require("util"),Dp=require("stream"),_k=lp(),bk=wp(),kk=jp(),pt=qp.PNG=function(t){Dp.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new _k(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new bk(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};$k.inherits(pt,Dp);pt.sync=kk;pt.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};pt.prototype.parse=function(t,e){if(e){let s,n;s=function(o){this.removeListener("error",n),this.data=o,e(null,this)}.bind(this),n=function(o){this.removeListener("parsed",s),e(o,null)}.bind(this),this.once("parsed",s),this.once("error",n)}return this.end(t),this};pt.prototype.write=function(t){return this._parser.write(t),!0};pt.prototype.end=function(t){this._parser.end(t)};pt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};pt.prototype._gamma=function(t){this.gamma=t};pt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};pt.bitblt=function(t,e,s,n,o,r,i,a){if(s|=0,n|=0,o|=0,r|=0,i|=0,a|=0,s>t.width||n>t.height||s+o>t.width||n+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+o>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<r;l++)t.data.copy(e.data,(a+l)*e.width+i<<2,(n+l)*t.width+s<<2,(n+l)*t.width+s+o<<2)};pt.prototype.bitblt=function(t,e,s,n,o,r,i){return pt.bitblt(this,t,e,s,n,o,r,i),this};pt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let s=0;s<t.width;s++){let n=t.width*e+s<<2;for(let o=0;o<3;o++){let r=t.data[n+o]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[n+o]=Math.round(r*255)}}t.gamma=0}};pt.prototype.adjustGamma=function(){pt.adjustGamma(this)}});var Yp={};p0(Yp,{default:()=>Wp});function Wp(t,e,s,n,o,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:c=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=r;if(!Pl(t)||!Pl(e)||s&&!Pl(s))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||s&&s.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==n*o*4)throw new Error("Image data size does not match width/height.");let p=n*o,m=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),$=!0;for(let S=0;S<p;S++)if(m[S]!==g[S]){$=!1;break}if($){if(s&&!f)for(let S=0;S<p;S++)Up(t,4*S,a,s);return 0}let k=35215*i*i,[M,D,v]=l,[E,A,ee]=c,[se,ue,ae]=d||c,te=0;for(let S=0;S<o;S++)for(let ve=0;ve<n;ve++){let W=S*n+ve,z=W*4,me=m[W]===g[W]?0:Hp(t,e,z,z,!1);if(Math.abs(me)>k){let Ce=Bp(t,ve,S,n,o,m,g)||Bp(e,ve,S,n,o,g,m);!u&&Ce?s&&!f&&di(s,z,M,D,v):(s&&(me<0?di(s,z,se,ue,ae):di(s,z,E,A,ee)),te++)}else s&&!f&&Up(t,z,a,s)}return te}function Pl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Bp(t,e,s,n,o,r,i){let a=Math.max(e-1,0),l=Math.max(s-1,0),c=Math.min(e+1,n-1),u=Math.min(s+1,o-1),d=s*n+e,f=e===a||e===c||s===l||s===u?1:0,p=0,m=0,g=0,$=0,k=0,M=0;for(let D=a;D<=c;D++)for(let v=l;v<=u;v++){if(D===e&&v===s)continue;let E=Hp(t,t,d*4,(v*n+D)*4,!0);if(E===0){if(f++,f>2)return!1}else E<p?(p=E,g=D,$=v):E>m&&(m=E,k=D,M=v)}return p===0||m===0?!1:ui(r,g,$,n,o)&&ui(i,g,$,n,o)||ui(r,k,M,n,o)&&ui(i,k,M,n,o)}function ui(t,e,s,n,o){let r=Math.max(e-1,0),i=Math.max(s-1,0),a=Math.min(e+1,n-1),l=Math.min(s+1,o-1),c=t[s*n+e],u=e===r||e===a||s===i||s===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===s)&&(u+=+(c===t[f*n+d]),u>2))return!0;return!1}function Hp(t,e,s,n,o){let r=t[s],i=t[s+1],a=t[s+2],l=t[s+3],c=e[n],u=e[n+1],d=e[n+2],f=e[n+3],p=r-c,m=i-u,g=a-d,$=l-f;if(!p&&!m&&!g&&!$)return 0;if(l<255||f<255){let E=48+159*(s%2),A=48+159*((s/1.618033988749895|0)%2),ee=48+159*((s/2.618033988749895|0)%2);p=(r*l-c*f-E*$)/255,m=(i*l-u*f-A*$)/255,g=(a*l-d*f-ee*$)/255}let k=p*.29889531+m*.58662247+g*.11448223;if(o)return k;let M=p*.59597799-m*.2741761-g*.32180189,D=p*.21147017-m*.52261711+g*.31114694,v=.5053*k*k+.299*M*M+.1957*D*D;return k>0?-v:v}function di(t,e,s,n,o){t[e+0]=s,t[e+1]=n,t[e+2]=o,t[e+3]=255}function Up(t,e,s,n){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;di(n,e,o,o,o)}var Gp=f0(()=>{});var Xn=V((q1,Jp)=>{var wn=require("fs"),xk=require("path"),Sk=require("os"),Ek="nex-visual-";function Kp(t){return xk.join(Sk.tmpdir(),`${Ek}${Date.now()}-${t}`)}var Ll=null;function fi(){return Ll||(Ll=Fp().PNG),Ll}var Il=null;function vk(){if(!Il){let t=(Gp(),m0(Yp));Il=t.default||t}return Il}function ql(t,e,{threshold:s=.1}={}){let n=fi(),o=vk(),r=n.sync.read(wn.readFileSync(t)),i=n.sync.read(wn.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=zp(r,a,l),u=zp(i,a,l),d=new n({width:a,height:l}),f=o(c,u,d.data,a,l,{threshold:s,includeAA:!1}),p=a*l,m=(f/p*100).toFixed(1),g=Tk(d.data,a,l,3,3),$=Kp("diff.png");return wn.writeFileSync($,n.sync.write(d),{mode:384}),{diffPath:$,diffPercent:parseFloat(m),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function zp(t,e,s){if(t.width===e&&t.height===s)return t.data;let n=Buffer.alloc(e*s*4,0);for(let o=0;o<t.height;o++){let r=o*t.width*4,i=o*e*4;t.data.copy(n,i,r,r+t.width*4)}return n}function Tk(t,e,s,n,o){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/n),a=Math.ceil(s/o),l=[];for(let c=0;c<o;c++)for(let u=0;u<n;u++){let d=0,f=0,p=u*i,m=c*a,g=Math.min(p+i,e),$=Math.min(m+a,s);for(let k=m;k<$;k++)for(let M=p;M<g;M++){f++;let D=(k*e+M)*4;(t[D]>0||t[D+1]>0)&&d++}if(d>0){let k=(d/f*100).toFixed(1),M=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:M,changedPercent:parseFloat(k),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var Xp=[{width:320,label:"mobile-sm"},{width:768,label:"tablet"},{width:1024,label:"desktop-sm"},{width:1440,label:"desktop"},{width:1920,label:"desktop-lg"}];async function Rk(t,{viewports:e=Xp,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=yn(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:s,fullPage:n,timeout:o});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function Vp(t,e=[]){let s=fi(),n=s.sync.read(wn.readFileSync(t));for(let i of e){let a=Ck(i.color||"#FF0000");i.type==="box"?(Ak(n,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Dl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(Ok(n,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Dl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(Nk(n,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Dl(n,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=Kp("annotated.png");wn.writeFileSync(o,s.sync.write(n),{mode:384});let r=wn.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function Ck(t){let e=t.replace("#","");return{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16),a:255}}function sn(t,e,s,n){if(e<0||s<0||e>=t.width||s>=t.height)return;let o=(s*t.width+e)*4;t.data[o]=n.r,t.data[o+1]=n.g,t.data[o+2]=n.b,t.data[o+3]=n.a}function Ak(t,e,s,n,o,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<n;l++)sn(t,e+l,s+a,r),sn(t,e+l,s+o-1-a,r);for(let l=0;l<o;l++)sn(t,e+a,s+l,r),sn(t,e+n-1-a,s+l,r)}}function jl(t,e,s,n,o,r,i=3){let a=Math.abs(n-e),l=Math.abs(o-s),c=e<n?1:-1,u=s<o?1:-1,d=a-l,f=e,p=s;for(;;){let m=Math.floor(i/2);for(let $=-m;$<=m;$++)for(let k=-m;k<=m;k++)sn(t,f+$,p+k,r);if(f===n&&p===o)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,p+=u)}}function Ok(t,e,s,n,o,r,i=3){jl(t,e,s,n,o,r,i);let a=Math.atan2(o-s,n-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;jl(t,n,o,Math.round(n+l*Math.cos(c)),Math.round(o+l*Math.sin(c)),r,i),jl(t,n,o,Math.round(n+l*Math.cos(u)),Math.round(o+l*Math.sin(u)),r,i)}function Nk(t,e,s,n,o,r=3){for(let i=0;i<r;i++){let a=n-i;for(let l=0;l<360;l+=.5){let c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(s+a*Math.sin(c));sn(t,u,d,o)}}}function Dl(t,e,s,n,o){let i=n.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)sn(t,e+c,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)sn(t,e+l,s+a-1,o),sn(t,e+l,s+a-2,o);for(let l=0;l<n.length;l++){let c=e+2+l*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)sn(t,c+d,s+u,o)}}async function*Mk(t,e,{maxIterations:s=20,hmrDelay:n=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=yn(),l=Pk("chokidar"),c=await a(t,{width:o,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:c.path,base64:c.base64,media_type:c.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let u=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;u<s;){await Ik(()=>d,3e5),d=!1,u++,await Lk(n);let p=await a(t,{width:o,height:r,timeout:i}),m=null;try{m=ql(c.path,p.path)}catch{}c=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function Pk(t){try{return require(t)}catch{return null}}function Lk(t){return new Promise(e=>setTimeout(e,t))}function Ik(t,e=6e4){return new Promise((s,n)=>{let o=setInterval(()=>{t()&&(clearInterval(o),clearTimeout(r),s())},200),r=setTimeout(()=>{clearInterval(o),n(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function jk(t,{sampleRate:e=4}={}){let n=fi().sync.read(wn.readFileSync(t)),o=new Map;for(let c=0;c<n.height;c+=e)for(let u=0;u<n.width;u+=e){let d=(c*n.width+u)*4,f=n.data[d],p=n.data[d+1],m=n.data[d+2];if(n.data[d+3]<128)continue;let $=Math.round(f/8)*8,k=Math.round(p/8)*8,M=Math.round(m/8)*8,D=`${$},${k},${M}`;o.set(D,(o.get(D)||0)+1)}let r=[...o.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,p]=c.split(",").map(Number);return{hex:Dk(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:qk(d,f,p)}}),l=Fk(n);return{colors:a,spacing:l,dimensions:{width:n.width,height:n.height},imagePath:t}}function Dk(t,e,s){return"#"+[t,e,s].map(n=>Math.min(255,n).toString(16).padStart(2,"0")).join("")}function qk(t,e,s){let n=(t*299+e*587+s*114)/1e3;return n>240?"white/background":n<30?"black/text":n<80?"dark":t>200&&e<100&&s<100?"red/danger":t<100&&e>150&&s<100?"green/success":t<100&&e<100&&s>200?"blue/primary":t>200&&e>200&&s<100?"yellow/warning":t>200&&e>100&&s<50?"orange/accent":n>200?"light/subtle":"midtone"}function Fk(t){let e=[],s=!1,n=0,o=Bk(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let c=(i*t.width+l)*4;if(Math.abs(t.data[c]-o.r)>20||Math.abs(t.data[c+1]-o.g)>20||Math.abs(t.data[c+2]-o.b)>20){a=!1;break}}if(a&&s)s=!1,n=i;else if(!a&&!s&&(s=!0,n>0)){let l=i-n;l>=4&&l<=200&&e.push(l)}}let r=new Map;for(let i of e){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function Bk(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],s=0,n=0,o=0;for(let[r,i]of e){let a=(i*t.width+r)*4;s+=t.data[a],n+=t.data[a+1],o+=t.data[a+2]}return{r:Math.round(s/4),g:Math.round(n/4),b:Math.round(o/4)}}async function Uk(t,e,{width:s,height:n=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=yn(),c=fi().sync.read(wn.readFileSync(e)),u=s||c.width,d=n||c.height,f=await a(t,{width:u,height:d,fullPage:o,timeout:i}),p=ql(e,f.path,{threshold:r}),m=Vp(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,$)=>{let D=Math.ceil(p.width/3),v=Math.ceil(p.height/3),E=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],A=0,ee=0;for(let se=0;se<3;se++)for(let ue=0;ue<3;ue++)E[se][ue]===g.name&&(A=ue,ee=se);return{type:"box",x:A*D+2,y:ee*v+2,width:D-4,height:v-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:p.diffPath,annotatedPath:m.path,diffPercent:p.diffPercent,changedPixels:p.changedPixels,totalPixels:p.totalPixels,regions:p.regionSummary,liveBase64:f.base64,diffBase64:wn.readFileSync(p.diffPath).toString("base64"),annotatedBase64:m.base64}}Jp.exports={pixelDiff:ql,responsiveSweep:Rk,annotateImage:Vp,visualWatch:Mk,extractDesignTokens:jk,designCompare:Uk,DEFAULT_VIEWPORTS:Xp}});var Fl=V((F1,Zp)=>{var{C:Le}=tt(),To="",ht=[],vo=0,Vn=null;function Wk(t){Vn=t}function Hk(t,e){To=t,ht=[],vo=0;for(let n of e){vo++;let o=`t${vo}`;ht.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${vo}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=ht.map(n=>({...n}));return Vn&&Vn("create",{name:t,tasks:s}),s}function Yk(t,e,s){let n=ht.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Vn&&Vn("update",{id:t,status:e,result:s}),{...n}):null}function Gk(){return{name:To,tasks:ht.map(t=>({...t}))}}function zk(){To="",ht=[],vo=0,Vn&&Vn("clear",{})}function Kk(){return ht.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=ht.find(n=>n.id===e);return s&&s.status==="done"}))}function Xk(){if(ht.length===0)return`${Le.dim}No active tasks${Le.reset}`;let t=[];To&&(t.push(` ${Le.bold}${Le.cyan}Tasks: ${To}${Le.reset}`),t.push(` ${Le.dim}${"\u2500".repeat(40)}${Le.reset}`));for(let o of ht){let r,i;switch(o.status){case"done":r="\u2713",i=Le.green;break;case"in_progress":r="\u2192",i=Le.cyan;break;case"failed":r="\u2717",i=Le.red;break;default:r="\xB7",i=Le.dim}let a=o.dependsOn.length>0?` ${Le.dim}(after: ${o.dependsOn.join(", ")})${Le.reset}`:"",l=`[${o.status}]`,c=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Le.reset} ${Le.bold}${o.id}${Le.reset} ${c.padEnd(40)} ${i}${l}${Le.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Le.dim}\u2192 ${u}${Le.reset}`)}}let e=ht.filter(o=>o.status==="done").length,s=ht.filter(o=>o.status==="failed").length,n=ht.length;return t.push(` ${Le.dim}${"\u2500".repeat(40)}${Le.reset}`),t.push(` ${Le.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Le.reset}`),t.join(`
133
+ `)}function Vk(){return ht.length>0&&ht.some(t=>t.status==="pending"||t.status==="in_progress")}Zp.exports={createTasks:Hk,updateTask:Yk,getTaskList:Gk,clearTasks:zk,getReadyTasks:Kk,renderTaskList:Xk,setOnChange:Wk,hasActiveTasks:Vk}});var Ul=V((B1,oh)=>{var{callChat:Jk}=lt(),{estimateTokens:Bl}=on(),Qp=process.env.NEX_COMPACTION!=="false",eh=6,th=2e3,nh=3,Zk=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
134
134
  This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
135
135
 
136
136
  Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
@@ -162,38 +162,38 @@ Format your output as:
162
162
 
163
163
  <summary>
164
164
  [Sections 1-9 above]
165
- </summary>`,Yn=0;async function kk(t){if(!Lh||t.length<Ih||Yn>=jh)return null;let e=[{role:"system",content:bk},{role:"user",content:qh(t)}];try{let n=((await $k(e,[],{temperature:0,maxTokens:Dh})).content||"").trim();if(!n)return Yn++,null;let o=n.match(/<summary>([\s\S]*?)<\/summary>/);if(o?n=o[1].trim():n=n.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!n)return Yn++,null;let r=t.reduce((a,l)=>a+Al(l.content||"")+(l.tool_calls?Al(JSON.stringify(l.tool_calls)):0),0),i=Al(n);return i>=r*.8?(Yn++,null):(Yn=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
166
- ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Yn++,null}}function xk(){Yn=0}function qh(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${n}
165
+ </summary>`,Jn=0;async function Qk(t){if(!Qp||t.length<eh||Jn>=nh)return null;let e=[{role:"system",content:Zk},{role:"user",content:sh(t)}];try{let n=((await Jk(e,[],{temperature:0,maxTokens:th})).content||"").trim();if(!n)return Jn++,null;let o=n.match(/<summary>([\s\S]*?)<\/summary>/);if(o?n=o[1].trim():n=n.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!n)return Jn++,null;let r=t.reduce((a,l)=>a+Bl(l.content||"")+(l.tool_calls?Bl(JSON.stringify(l.tool_calls)):0),0),i=Bl(n);return i>=r*.8?(Jn++,null):(Jn=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
166
+ ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Jn++,null}}function ex(){Jn=0}function sh(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${n}
167
167
  tools: ${o}`}return`[${s}] ${n}`}).join(`
168
168
 
169
- `)}Fh.exports={compactMessages:kk,formatMessagesForSummary:qh,resetCompactionFailures:xk,COMPACTION_ENABLED:Lh,COMPACTION_MIN_MESSAGES:Ih,COMPACTION_SUMMARY_BUDGET:Dh,MAX_CONSECUTIVE_FAILURES:jh}});var Qt=Z((BR,Vh)=>{var Sk=require("path");function Uh(){return ot().getActiveModel()}var Ek={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},vk={devstral:3.8,mistral:3.8,ministral:3.8,codestral:3.8,qwen:3.5,deepseek:3.6,kimi:3.7,gemma:4,llama:3.8,cogito:3.6,phi:4},Gn=new Map,Bh=1e3,Nl=new WeakMap,zn=null;function Tk(){if(zn!==null)return zn;try{let t=Uh(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(vk))if(s.startsWith(n))return zn=o,zn;return zn=Ek[e]||4,zn}catch{return 4}}function Rk(){zn=null}function Kn(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,s=Gn.get(e);if(s!==void 0)return Gn.delete(e),Gn.set(e,s),s;let n=Math.ceil(t.length/Tk());if(Gn.size>=Bh){let o=Bh>>1,r=Gn.keys();for(let i=0;i<o;i++)Gn.delete(r.next().value)}return Gn.set(e,n),n}function Ck(t){if(Nl.has(t))return Nl.get(t);let e=JSON.stringify(t);return Nl.set(t,e),e}function Xn(t){let s=4;if(t.content&&(s+=Kn(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=Kn(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=Kn(o):o&&(s+=Kn(JSON.stringify(o)))}return s}function Ut(t){let e=0;for(let s of t)e+=Xn(s);return e}function Ak(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=Xn(e[r]);return o}var Ml=new WeakMap;function ri(t){if(!t||t.length===0)return 0;if(Ml.has(t))return Ml.get(t);let e=Kn(JSON.stringify(t));return Ml.set(t,e),e}function ii(){return Uh()?.contextWindow||32768}var ft={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function Ok(t,e){let s=t.length>0?t[t.length-1]:null,n=e?e.length:0;if(ft.result&&t.length===ft.msgCount&&s===ft.lastMsgRef&&n===ft.toolCount)return ft.result;let o,r,i,a;if(ft.messagesRef===t&&t.length>ft.msgCount&&ft.msgCount>=0){o=ft.messageTokens,r=ft.systemTokens,i=ft.conversationTokens,a=ft.toolResultTokens;for(let p=ft.msgCount;p<t.length;p++){let m=Xn(t[p]);o+=m,t[p].role==="system"?r+=m:t[p].role==="tool"?a+=m:i+=m}}else{o=0,r=0,i=0,a=0;for(let p of t){let m=Xn(p);o+=m,p.role==="system"?r+=m:p.role==="tool"?a+=m:i+=m}}let l=ri(e),c=o+l,u=ii(),d=u>0?c/u*100:0,f={used:c,limit:u,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return ft={msgCount:t.length,lastMsgRef:s,toolCount:n,result:f,messagesRef:t,messageTokens:o,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var So=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Wh=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Hh=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Yh={essential:.6,standard:.65,full:Math.min(So,.75)};function Gh(){if(process.env.NEX_COMPRESSION_THRESHOLD)return So;try{let{getActiveTier:t}=_o(),e=t();return Yh[e]??So}catch{return So}}var Nk=200,Mk=1e3;function zh(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
170
- `);if(o.length<=10){let m=Math.floor(n*.6),g=Math.floor(n*.4),_=t.substring(0,m),k=t.substring(t.length-g);return _+`
169
+ `)}oh.exports={compactMessages:Qk,formatMessagesForSummary:sh,resetCompactionFailures:ex,COMPACTION_ENABLED:Qp,COMPACTION_MIN_MESSAGES:eh,COMPACTION_SUMMARY_BUDGET:th,MAX_CONSECUTIVE_FAILURES:nh}});var on=V((U1,hh)=>{var tx=require("path");function ih(){return lt().getActiveModel()}var nx={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},sx={devstral:3.8,mistral:3.8,ministral:3.8,codestral:3.8,qwen:3.5,deepseek:3.6,kimi:3.7,gemma:4,llama:3.8,cogito:3.6,phi:4},Zn=new Map,rh=1e3,Wl=new WeakMap,Qn=null;function ox(){if(Qn!==null)return Qn;try{let t=ih(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(sx))if(s.startsWith(n))return Qn=o,Qn;return Qn=nx[e]||4,Qn}catch{return 4}}function rx(){Qn=null}function es(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,s=Zn.get(e);if(s!==void 0)return Zn.delete(e),Zn.set(e,s),s;let n=Math.ceil(t.length/ox());if(Zn.size>=rh){let o=rh>>1,r=Zn.keys();for(let i=0;i<o;i++)Zn.delete(r.next().value)}return Zn.set(e,n),n}function ix(t){if(Wl.has(t))return Wl.get(t);let e=JSON.stringify(t);return Wl.set(t,e),e}function ts(t){let s=4;if(t.content&&(s+=es(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=es(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=es(o):o&&(s+=es(JSON.stringify(o)))}return s}function Gt(t){let e=0;for(let s of t)e+=ts(s);return e}function ax(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=ts(e[r]);return o}var Hl=new WeakMap;function pi(t){if(!t||t.length===0)return 0;if(Hl.has(t))return Hl.get(t);let e=es(JSON.stringify(t));return Hl.set(t,e),e}function hi(){return ih()?.contextWindow||32768}var mt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function lx(t,e){let s=t.length>0?t[t.length-1]:null,n=e?e.length:0;if(mt.result&&t.length===mt.msgCount&&s===mt.lastMsgRef&&n===mt.toolCount)return mt.result;let o,r,i,a;if(mt.messagesRef===t&&t.length>mt.msgCount&&mt.msgCount>=0){o=mt.messageTokens,r=mt.systemTokens,i=mt.conversationTokens,a=mt.toolResultTokens;for(let p=mt.msgCount;p<t.length;p++){let m=ts(t[p]);o+=m,t[p].role==="system"?r+=m:t[p].role==="tool"?a+=m:i+=m}}else{o=0,r=0,i=0,a=0;for(let p of t){let m=ts(p);o+=m,p.role==="system"?r+=m:p.role==="tool"?a+=m:i+=m}}let l=pi(e),c=o+l,u=hi(),d=u>0?c/u*100:0,f={used:c,limit:u,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return mt={msgCount:t.length,lastMsgRef:s,toolCount:n,result:f,messagesRef:t,messageTokens:o,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Ro=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,ah=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,lh=parseInt(process.env.NEX_KEEP_RECENT,10)||10,ch={essential:.6,standard:.65,full:Math.min(Ro,.75)};function uh(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Ro;try{let{getActiveTier:t}=xo(),e=t();return ch[e]??Ro}catch{return Ro}}var cx=200,ux=1e3;function dh(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
170
+ `);if(o.length<=10){let m=Math.floor(n*.6),g=Math.floor(n*.4),$=t.substring(0,m),k=t.substring(t.length-g);return $+`
171
171
  ...(${t.length} chars total)...
172
172
  `+k}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),a=[],l=0,c=Math.floor(n*.4);for(let m=0;m<r&&l<c;m++)if(l+o[m].length+1>c&&o[m].trim().startsWith("```")){a.push(o[m]),l+=o[m].length+1;let g=m+1;for(;g<o.length&&l<c*1.5&&!o[g].trim().startsWith("```");)a.push(o[g]),l+=o[g].length+1,g++;g<o.length&&o[g].trim().startsWith("```")&&(a.push(o[g]),l+=o[g].length+1),m=g}else a.push(o[m]),l+=o[m].length+1;let u=[],d=0,f=Math.floor(n*.4);for(let m=o.length-1;m>=o.length-i&&d<f;m--)if(d+o[m].length+1>f&&o[m].trim().startsWith("```")){u.push(o[m]),d+=o[m].length+1;let g=m-1;for(;g>=0&&d<f*1.5&&!o[g].trim().startsWith("```");)u.push(o[g]),d+=o[g].length+1,g--;g>=0&&o[g].trim().startsWith("```")&&(u.push(o[g]),d+=o[g].length+1),m=g}else u.push(o[m]),d+=o[m].length+1;u.reverse();let p=o.length-a.length-u.length;return a.join(`
173
173
  `)+`
174
174
  ...(${p} lines omitted, ${o.length} total)...
175
175
  `+u.join(`
176
- `)}function Ls(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Mk,n=e==="aggressive"?50:e==="medium"?100:Nk;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:zh(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
177
- ...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}function Kh(t,e,s,n){let o=0;if(t.role==="system")return 100;if(t.role==="user")o+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?o+=30:o+=15}else t.role==="assistant"&&(o+=t.tool_calls?20:10);let r=s>1?e/(s-1):1;if(o+=Math.round(r*30),n&&n.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let l of n)(i.includes(l)||i.includes(Sk.basename(l)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function Xh(t,e=10){let s=new Set,n=t.slice(-e),o=/(?:\/[\w.-]+)+\.\w+/g;for(let r of n){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(o);a&&a.forEach(l=>s.add(l))}return s}function Pk(t,{filesModified:e=new Set,currentPhase:s=null}={}){let n=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");n.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}s&&n.push(`Current phase: ${s}`);let o=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return o.length>0&&n.push(`Recent progress:
176
+ `)}function qs(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:ux,n=e==="aggressive"?50:e==="medium"?100:cx;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:dh(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
177
+ ...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}function fh(t,e,s,n){let o=0;if(t.role==="system")return 100;if(t.role==="user")o+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?o+=30:o+=15}else t.role==="assistant"&&(o+=t.tool_calls?20:10);let r=s>1?e/(s-1):1;if(o+=Math.round(r*30),n&&n.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let l of n)(i.includes(l)||i.includes(tx.basename(l)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function ph(t,e=10){let s=new Set,n=t.slice(-e),o=/(?:\/[\w.-]+)+\.\w+/g;for(let r of n){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(o);a&&a.forEach(l=>s.add(l))}return s}function dx(t,{filesModified:e=new Set,currentPhase:s=null}={}){let n=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");n.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}s&&n.push(`Current phase: ${s}`);let o=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return o.length>0&&n.push(`Recent progress:
178
178
  `+o.map(r=>`- ${r}`).join(`
179
179
  `)),n.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
180
180
  ${n.join(`
181
- `)}`,_pinned:!0,_progressSnapshot:!0}}var Ps={msgCount:-1,lastMsgRef:null,result:null};function Lk(){Ps={msgCount:-1,lastMsgRef:null,result:null},ft={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function Ik(t,e,s={}){let n=t.length>0?t[t.length-1]:null;if(!s.force&&Ps.result&&t.length===Ps.msgCount&&n===Ps.lastMsgRef)return Ps.result;let o=s.threshold??Gh(),r=s.safetyMargin??Wh,i=s.keepRecent??Hh,a=ii(),l=ri(e),c=Math.floor(a*(o-r)),u=c-l,d=Ut(t);if(d+l<=c){let ne={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Ps={msgCount:t.length,lastMsgRef:n,result:ne},ne}let p=d,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let _=Math.max(g,t.length-i),k=t.slice(g,_),A=t.slice(_),L=k.map(ne=>Ls(ne,"light")),E=En(m,L,A),v=Ut(E);if(v+l<=c)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};if(L=k.map(ne=>Ls(ne,"medium")),E=En(m,L,A),v=Ut(E),v+l<=c)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};if(L=k.map(ne=>Ls(ne,"aggressive")),E=En(m,L,A),v=Ut(E),v+l<=c)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};let N=process.env.NEX_SKIP_COMPACTOR==="1",te=k.filter(ne=>ne._pinned),V=k.filter(ne=>!ne._compacted&&!ne._pinned);if(!N&&V.length>=6)try{let{compactMessages:ne}=Ol(),S=await ne(V);if(S){let Ee=k.filter(Re=>Re._compacted&&!Re._pinned),W=[...te,...Ee,S.message],J=En(m,W,A),he=Ut(J);if(he+l<=c)return{messages:J,compressed:!0,compacted:!0,tokensRemoved:p-he};k=W}}catch(ne){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",ne.message)}let re=Xh([...L,...A]),le=L.map((ne,S)=>({msg:ne,score:ne._pinned?1/0:Kh(ne,S,L.length,re),tokens:Xn(ne)}));for(;le.length>0&&v>u;){let ne=-1;for(let S=0;S<le.length;S++)le[S].score!==1/0&&(ne===-1||le[S].score<le[ne].score)&&(ne=S);if(ne===-1)break;v-=le[ne].tokens,le.splice(ne,1)}return L=le.map(ne=>ne.msg),E=En(m,L,A),v=Ut(E),{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v}}function En(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Dk(t,e){if(!t)return"";if(Kn(t)<=e)return t;let n=e*4,o=t.split(`
181
+ `)}`,_pinned:!0,_progressSnapshot:!0}}var Ds={msgCount:-1,lastMsgRef:null,result:null};function fx(){Ds={msgCount:-1,lastMsgRef:null,result:null},mt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function px(t,e,s={}){let n=t.length>0?t[t.length-1]:null;if(!s.force&&Ds.result&&t.length===Ds.msgCount&&n===Ds.lastMsgRef)return Ds.result;let o=s.threshold??uh(),r=s.safetyMargin??ah,i=s.keepRecent??lh,a=hi(),l=pi(e),c=Math.floor(a*(o-r)),u=c-l,d=Gt(t);if(d+l<=c){let te={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Ds={msgCount:t.length,lastMsgRef:n,result:te},te}let p=d,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let $=Math.max(g,t.length-i),k=t.slice(g,$),M=t.slice($),D=k.map(te=>qs(te,"light")),v=Nn(m,D,M),E=Gt(v);if(E+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-E};if(D=k.map(te=>qs(te,"medium")),v=Nn(m,D,M),E=Gt(v),E+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-E};if(D=k.map(te=>qs(te,"aggressive")),v=Nn(m,D,M),E=Gt(v),E+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-E};let A=process.env.NEX_SKIP_COMPACTOR==="1",ee=k.filter(te=>te._pinned),se=k.filter(te=>!te._compacted&&!te._pinned);if(!A&&se.length>=6)try{let{compactMessages:te}=Ul(),S=await te(se);if(S){let ve=k.filter(Ce=>Ce._compacted&&!Ce._pinned),W=[...ee,...ve,S.message],z=Nn(m,W,M),me=Gt(z);if(me+l<=c)return{messages:z,compressed:!0,compacted:!0,tokensRemoved:p-me};k=W}}catch(te){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",te.message)}let ue=ph([...D,...M]),ae=D.map((te,S)=>({msg:te,score:te._pinned?1/0:fh(te,S,D.length,ue),tokens:ts(te)}));for(;ae.length>0&&E>u;){let te=-1;for(let S=0;S<ae.length;S++)ae[S].score!==1/0&&(te===-1||ae[S].score<ae[te].score)&&(te=S);if(te===-1)break;E-=ae[te].tokens,ae.splice(te,1)}return D=ae.map(te=>te.msg),v=Nn(m,D,M),E=Gt(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-E}}function Nn(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function hx(t,e){if(!t)return"";if(es(t)<=e)return t;let n=e*4,o=t.split(`
182
182
  `),r=Math.floor(n*.6),i=Math.floor(n*.4),a="",l=0;for(let p of o){if(a.length+p.length+1>r)break;a+=(a?`
183
183
  `:"")+p,l++}let c="",u=0;for(let p=o.length-1;p>=l;p--){let m=o[p]+(c?`
184
184
  `:"")+c;if(m.length>i)break;c=m,u++}let f=`
185
185
 
186
186
  ... (${o.length-l-u} lines omitted, ${o.length} total) ...
187
187
 
188
- `;return a+f+c}var jk=6;function qk(t,e,s=!1){let n=ii(),o=ri(e),r=Math.floor(n*(s?.35:.5))-o,i=Ut(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let l=null,c=0;t.length>0&&t[0].role==="system"&&(l=t[0],c=1);let u=s?2:jk,d=Math.max(c,t.length-u),f=t.slice(c,d),p=t.slice(d),m=f.map(v=>Ls(v,"aggressive"));s&&(p=p.map(v=>Ls(v,"aggressive")));let g=En(l,m,p),_=Ut(g);for(;m.length>0&&_>r;){let v=m.shift();_-=Xn(v)}s&&_>r&&(p=p.filter(N=>N.role==="user").slice(-1),g=En(l,[],p),_=Ut(g)),g=En(l,m,p);let k=t.filter(v=>v.role==="user"),A=v=>{let N=typeof v.content=="string"?v.content:"";return N.startsWith("[SYSTEM WARNING]")||N.startsWith("[SYSTEM:")||N.startsWith("BLOCKED:")},L=k.find(v=>!A(v)),E=[...k].reverse().find(v=>!A(v));if(L&&!g.find(v=>v===L)){let v=g.findIndex(te=>te.role==="system"),N=v>=0?v+1:0;g.splice(N,0,L)}return E&&E!==L&&!g.find(v=>v===E)&&g.push(E),{messages:g,tokensRemoved:i-Ut(g)}}Vh.exports={estimateTokens:Kn,estimateMessageTokens:Xn,estimateMessagesTokens:Ut,estimateDeltaTokens:Ak,estimateToolsTokens:ri,serializeMessage:Ck,getContextWindow:ii,getUsage:Ok,compressMessage:Ls,compressToolResult:zh,scoreMessageRelevance:Kh,extractActiveFiles:Xh,buildProgressSnapshot:Pk,fitToContext:Ik,forceCompress:qk,truncateFileContent:Dk,invalidateTokenRatioCache:Rk,invalidateFitToContextCache:Lk,getEffectiveCompressionThreshold:Gh,COMPRESSION_THRESHOLD:So,TIER_COMPRESSION_THRESHOLDS:Yh,SAFETY_MARGIN:Wh,KEEP_RECENT:Hh}});var Bl=Z((UR,up)=>{var qe=require("fs"),fn=require("path"),{atomicWrite:Jh,withFileLockSync:Zh}=jn(),Fk=new Set(["the","a","an","is","are","and","or","but","in","on","at","to","for","of","with","this","that","it","as","be","by","from","was","were","has","have","had","not","do","does","did","so","if","its","my","me","we","you","he","she","they","our","your","their","can","will","would","could","should","may","might","then","than","also","which","when","where","how","what","who","all","any","each","more","most","use","used","using","get","set","new","add","make","der","die","das","den","dem","des","ein","eine","einen","einem","eines","und","oder","aber","von","zu","mit","auf","bei","nach","aus","vor","ist","sind","war","hat","haben","wird","kann","soll","muss","nicht","auch","als","durch"]);function Ds(){let t=fn.join(process.cwd(),".nex","brain");return qe.existsSync(t)||qe.mkdirSync(t,{recursive:!0}),t}function li(){return fn.join(Ds(),".brain-index.json")}function Il(){return fn.join(Ds(),".embeddings.json")}function Eo(){let t=fn.join(process.cwd(),".nex","brain");if(!qe.existsSync(t))return[];try{return qe.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=fn.join(t,e),n=qe.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function vo(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
189
- `);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[a]=l.slice(1,-1).split(",").map(c=>c.trim()).filter(Boolean):e[a]=l}s=n[2]}return{frontmatter:e,body:s}}function Qh(t){let e=fn.join(Ds(),`${t}.md`);if(!qe.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=qe.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=vo(s);return{name:t,content:s,body:o,frontmatter:n}}function Bk(t,e){let s=fn.join(Ds(),`${t}.md`);Jh(s,e),Hk(t,e),Uk()}function Uk(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Il();qe.existsSync(t)&&setImmediate(async()=>{try{await ip()}catch{}})}function Wk(t){let e=fn.join(Ds(),`${t}.md`);return qe.existsSync(e)?(qe.unlinkSync(e),Yk(t),!0):!1}function ai(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Fk.has(e))}function Dl(t){let e={},{frontmatter:s,body:n}=vo(t),o=Array.isArray(s.tags)?s.tags:[];for(let i of o){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(n||t).split(`
190
- `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of ai(a))e[l]=(e[l]||0)+3}for(let i of ai(n||t))e[i]=(e[i]||0)+1;return e}function jl(){let t=li();if(!qe.existsSync(t))return{documents:{}};try{return JSON.parse(qe.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function ql(t){Jh(li(),JSON.stringify(t,null,2))}function Hk(t,e){Zh(li(),()=>{let s=jl(),{frontmatter:n}=vo(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:Dl(e),tags:o,modified:new Date().toISOString()},ql(s)})}function Yk(t){Zh(li(),()=>{let e=jl();delete e.documents[t],ql(e)})}function Ll(){let t=Eo(),e={documents:{}};for(let s of t){let n=qe.readFileSync(s.path,"utf-8"),{frontmatter:o}=vo(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:Dl(n),tags:r,modified:s.modified.toISOString()}}return ql(e),e}function ep(){let t=jl(),e=Eo();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return Ll()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return Ll();return t}function tp(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ai(t);if(o.length===0)return[];let r=ep(),i=[];for(let[a,l]of Object.entries(r.documents)){let c=0;for(let u of o){l.keywords[u]&&(c+=l.keywords[u]);for(let[d,f]of Object.entries(l.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(c+=f*.3)}c>=n&&i.push({name:a,score:c})}return i.sort((a,l)=>l.score-a.score),i.slice(0,s)}var np=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Pl=400,Gk=50;async function sp(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),n=new URL(`${t}/api/tags`),o=n.protocol==="https:"?s:e;return((await new Promise((a,l)=>{let c=o.get(n.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{l(new Error("bad json"))}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(np.split(":")[0]))}catch{return!1}}async function Fl(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,i=JSON.stringify({model:np,prompt:t});return new Promise((a,l)=>{let c=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){l(f)}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("embedding timeout"))}),c.write(i),c.end()})}function op(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],n+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function rp(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+Pl).join(" ");if(s.push({text:o,offset:n}),n+Pl>=e.length)break;n+=Pl-Gk}return s}async function ip(){let t=Eo(),e={documents:{}},s=Il();if(qe.existsSync(s))try{e=JSON.parse(qe.readFileSync(s,"utf-8"))}catch{}for(let n of t){let o=e.documents[n.name];if(o&&new Date(o.modified)>=n.modified)continue;let r=qe.readFileSync(n.path,"utf-8"),i=rp(r),a=[];for(let l of i){let c=await Fl(l.text);a.push({text:l.text,embedding:c,offset:l.offset})}e.documents[n.name]={chunks:a,modified:n.modified.toISOString()}}for(let n of Object.keys(e.documents))t.some(o=>o.name===n)||delete e.documents[n];return qe.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function ap(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=Il();if(!qe.existsSync(o))return[];let r;try{r=JSON.parse(qe.readFileSync(o,"utf-8"))}catch{return[]}let i=await Fl(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let p=op(i,f.embedding);p>u&&(u=p,d=f.text)}u>=n&&a.push({name:l,score:u,bestChunk:d})}return a.sort((l,c)=>c.score-l.score),a.slice(0,s)}function lp(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,o)}async function cp(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=tp(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await sp()){let a=await ap(t,{topK:s});r=lp(o,a,{topK:s})}}catch{}return r.map(i=>{let a=Qh(i.name),l=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:l}})}var Is={queryKey:null,result:null,ts:0},zk=3e5;async function Kk(t){if(!t||!t.trim())return"";let e=fn.join(process.cwd(),".nex","brain");if(!qe.existsSync(e)||Eo().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(Is.result!==null&&Is.queryKey===n&&Date.now()-Is.ts<zk)return Is.result;let o;try{o=await cp(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=Qt().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],l=0;for(let u of o){let d=u.content||"",f=r(d);if(l+f>i){let m=i-l;if(m<100)break;let g=m/f;d=d.slice(0,Math.floor(d.length*g))+`
188
+ `;return a+f+c}var mx=6;function gx(t,e,s=!1){let n=hi(),o=pi(e),r=Math.floor(n*(s?.35:.5))-o,i=Gt(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let l=null,c=0;t.length>0&&t[0].role==="system"&&(l=t[0],c=1);let u=s?2:mx,d=Math.max(c,t.length-u),f=t.slice(c,d),p=t.slice(d),m=f.map(E=>qs(E,"aggressive"));s&&(p=p.map(E=>qs(E,"aggressive")));let g=Nn(l,m,p),$=Gt(g);for(;m.length>0&&$>r;){let E=m.shift();$-=ts(E)}s&&$>r&&(p=p.filter(A=>A.role==="user").slice(-1),g=Nn(l,[],p),$=Gt(g)),g=Nn(l,m,p);let k=t.filter(E=>E.role==="user"),M=E=>{let A=typeof E.content=="string"?E.content:"";return A.startsWith("[SYSTEM WARNING]")||A.startsWith("[SYSTEM:")||A.startsWith("BLOCKED:")},D=k.find(E=>!M(E)),v=[...k].reverse().find(E=>!M(E));if(D&&!g.find(E=>E===D)){let E=g.findIndex(ee=>ee.role==="system"),A=E>=0?E+1:0;g.splice(A,0,D)}return v&&v!==D&&!g.find(E=>E===v)&&g.push(v),{messages:g,tokensRemoved:i-Gt(g)}}hh.exports={estimateTokens:es,estimateMessageTokens:ts,estimateMessagesTokens:Gt,estimateDeltaTokens:ax,estimateToolsTokens:pi,serializeMessage:ix,getContextWindow:hi,getUsage:lx,compressMessage:qs,compressToolResult:dh,scoreMessageRelevance:fh,extractActiveFiles:ph,buildProgressSnapshot:dx,fitToContext:px,forceCompress:gx,truncateFileContent:hx,invalidateTokenRatioCache:rx,invalidateFitToContextCache:fx,getEffectiveCompressionThreshold:uh,COMPRESSION_THRESHOLD:Ro,TIER_COMPRESSION_THRESHOLDS:ch,SAFETY_MARGIN:ah,KEEP_RECENT:lh}});var Zl=V((W1,Rh)=>{var We=require("fs"),$n=require("path"),{atomicWrite:mh,withFileLockSync:gh}=Hn(),yx=new Set(["the","a","an","is","are","and","or","but","in","on","at","to","for","of","with","this","that","it","as","be","by","from","was","were","has","have","had","not","do","does","did","so","if","its","my","me","we","you","he","she","they","our","your","their","can","will","would","could","should","may","might","then","than","also","which","when","where","how","what","who","all","any","each","more","most","use","used","using","get","set","new","add","make","der","die","das","den","dem","des","ein","eine","einen","einem","eines","und","oder","aber","von","zu","mit","auf","bei","nach","aus","vor","ist","sind","war","hat","haben","wird","kann","soll","muss","nicht","auch","als","durch"]);function Bs(){let t=$n.join(process.cwd(),".nex","brain");return We.existsSync(t)||We.mkdirSync(t,{recursive:!0}),t}function gi(){return $n.join(Bs(),".brain-index.json")}function zl(){return $n.join(Bs(),".embeddings.json")}function Co(){let t=$n.join(process.cwd(),".nex","brain");if(!We.existsSync(t))return[];try{return We.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=$n.join(t,e),n=We.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function Ao(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
189
+ `);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[a]=l.slice(1,-1).split(",").map(c=>c.trim()).filter(Boolean):e[a]=l}s=n[2]}return{frontmatter:e,body:s}}function yh(t){let e=$n.join(Bs(),`${t}.md`);if(!We.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=We.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=Ao(s);return{name:t,content:s,body:o,frontmatter:n}}function wx(t,e){let s=$n.join(Bs(),`${t}.md`);mh(s,e),bx(t,e),$x()}function $x(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=zl();We.existsSync(t)&&setImmediate(async()=>{try{await Sh()}catch{}})}function _x(t){let e=$n.join(Bs(),`${t}.md`);return We.existsSync(e)?(We.unlinkSync(e),kx(t),!0):!1}function mi(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!yx.has(e))}function Kl(t){let e={},{frontmatter:s,body:n}=Ao(t),o=Array.isArray(s.tags)?s.tags:[];for(let i of o){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(n||t).split(`
190
+ `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of mi(a))e[l]=(e[l]||0)+3}for(let i of mi(n||t))e[i]=(e[i]||0)+1;return e}function Xl(){let t=gi();if(!We.existsSync(t))return{documents:{}};try{return JSON.parse(We.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Vl(t){mh(gi(),JSON.stringify(t,null,2))}function bx(t,e){gh(gi(),()=>{let s=Xl(),{frontmatter:n}=Ao(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:Kl(e),tags:o,modified:new Date().toISOString()},Vl(s)})}function kx(t){gh(gi(),()=>{let e=Xl();delete e.documents[t],Vl(e)})}function Gl(){let t=Co(),e={documents:{}};for(let s of t){let n=We.readFileSync(s.path,"utf-8"),{frontmatter:o}=Ao(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:Kl(n),tags:r,modified:s.modified.toISOString()}}return Vl(e),e}function wh(){let t=Xl(),e=Co();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return Gl()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return Gl();return t}function $h(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=mi(t);if(o.length===0)return[];let r=wh(),i=[];for(let[a,l]of Object.entries(r.documents)){let c=0;for(let u of o){l.keywords[u]&&(c+=l.keywords[u]);for(let[d,f]of Object.entries(l.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(c+=f*.3)}c>=n&&i.push({name:a,score:c})}return i.sort((a,l)=>l.score-a.score),i.slice(0,s)}var _h=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Yl=400,xx=50;async function bh(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),n=new URL(`${t}/api/tags`),o=n.protocol==="https:"?s:e;return((await new Promise((a,l)=>{let c=o.get(n.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{l(new Error("bad json"))}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(_h.split(":")[0]))}catch{return!1}}async function Jl(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,i=JSON.stringify({model:_h,prompt:t});return new Promise((a,l)=>{let c=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){l(f)}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("embedding timeout"))}),c.write(i),c.end()})}function kh(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],n+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function xh(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+Yl).join(" ");if(s.push({text:o,offset:n}),n+Yl>=e.length)break;n+=Yl-xx}return s}async function Sh(){let t=Co(),e={documents:{}},s=zl();if(We.existsSync(s))try{e=JSON.parse(We.readFileSync(s,"utf-8"))}catch{}for(let n of t){let o=e.documents[n.name];if(o&&new Date(o.modified)>=n.modified)continue;let r=We.readFileSync(n.path,"utf-8"),i=xh(r),a=[];for(let l of i){let c=await Jl(l.text);a.push({text:l.text,embedding:c,offset:l.offset})}e.documents[n.name]={chunks:a,modified:n.modified.toISOString()}}for(let n of Object.keys(e.documents))t.some(o=>o.name===n)||delete e.documents[n];return We.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Eh(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=zl();if(!We.existsSync(o))return[];let r;try{r=JSON.parse(We.readFileSync(o,"utf-8"))}catch{return[]}let i=await Jl(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let p=kh(i,f.embedding);p>u&&(u=p,d=f.text)}u>=n&&a.push({name:l,score:u,bestChunk:d})}return a.sort((l,c)=>c.score-l.score),a.slice(0,s)}function vh(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,o)}async function Th(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=$h(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await bh()){let a=await Eh(t,{topK:s});r=vh(o,a,{topK:s})}}catch{}return r.map(i=>{let a=yh(i.name),l=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:l}})}var Fs={queryKey:null,result:null,ts:0},Sx=3e5;async function Ex(t){if(!t||!t.trim())return"";let e=$n.join(process.cwd(),".nex","brain");if(!We.existsSync(e)||Co().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(Fs.result!==null&&Fs.queryKey===n&&Date.now()-Fs.ts<Sx)return Fs.result;let o;try{o=await Th(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=on().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],l=0;for(let u of o){let d=u.content||"",f=r(d);if(l+f>i){let m=i-l;if(m<100)break;let g=m/f;d=d.slice(0,Math.floor(d.length*g))+`
191
191
  ...(truncated)`}let p=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${p}) ---
192
- ${d}`),l+=r(d),l>=i)break}if(a.length===0)return Is={queryKey:n,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
192
+ ${d}`),l+=r(d),l>=i)break}if(a.length===0)return Fs={queryKey:n,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
193
193
 
194
194
  ${a.join(`
195
195
 
196
- `)}`;return Is={queryKey:n,result:c,ts:Date.now()},c}up.exports={getBrainDir:Ds,listDocuments:Eo,readDocument:Qh,writeDocument:Bk,removeDocument:Wk,buildIndex:Ll,getIndex:ep,query:cp,getBrainContext:Kk,isEmbeddingAvailable:sp,generateEmbedding:Fl,buildEmbeddingIndex:ip,semanticQuery:ap,cosineSimilarity:op,_keywordQuery:tp,_extractKeywords:Dl,_chunkText:rp,parseFrontmatter:vo,tokenize:ai,_fuseResults:lp}});var Co=Z((WR,kp)=>{var Le=require("fs"),kt=require("path"),Xk=require("os"),{atomicWrite:ci,withFileLockSync:dp}=jn(),To=["user","feedback","project","reference"],Vk=50;function Vn(){return kt.join(process.cwd(),".nex","memory")}function js(){return kt.join(Vn(),"memory.json")}function fp(){return kt.join(Vn(),"MEMORY.md")}function Jk(){return kt.join(process.cwd(),"NEX.md")}function hp(){return kt.join(Xk.homedir(),".nex","NEX.md")}function ui(){let t=Vn();Le.existsSync(t)||Le.mkdirSync(t,{recursive:!0})}function pp(t){let e=kt.join(Vn(),t);return Le.existsSync(e)||Le.mkdirSync(e,{recursive:!0}),e}function Ro(){let t=js();if(!Le.existsSync(t))return{};try{return JSON.parse(Le.readFileSync(t,"utf-8"))}catch{return{}}}function mp(t){ui(),ci(js(),JSON.stringify(t,null,2))}function gp(){let t=js();if(!Le.existsSync(t))return;let e=Ro(),s=Object.keys(e);if(s.length===0){try{Le.renameSync(t,t+".bak")}catch{}return}for(let n of s){let o=e[n],r=o.value||String(o),i=n.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=pp("project"),l=kt.join(a,`${i}.md`),c=r.split(`
196
+ `)}`;return Fs={queryKey:n,result:c,ts:Date.now()},c}Rh.exports={getBrainDir:Bs,listDocuments:Co,readDocument:yh,writeDocument:wx,removeDocument:_x,buildIndex:Gl,getIndex:wh,query:Th,getBrainContext:Ex,isEmbeddingAvailable:bh,generateEmbedding:Jl,buildEmbeddingIndex:Sh,semanticQuery:Eh,cosineSimilarity:kh,_keywordQuery:$h,_extractKeywords:Kl,_chunkText:xh,parseFrontmatter:Ao,tokenize:mi,_fuseResults:vh}});var Mo=V((H1,Fh)=>{var Ie=require("fs"),vt=require("path"),vx=require("os"),{atomicWrite:yi,withFileLockSync:Ch}=Hn(),Oo=["user","feedback","project","reference"],Tx=50;function ns(){return vt.join(process.cwd(),".nex","memory")}function Us(){return vt.join(ns(),"memory.json")}function Ah(){return vt.join(ns(),"MEMORY.md")}function Rx(){return vt.join(process.cwd(),"NEX.md")}function Oh(){return vt.join(vx.homedir(),".nex","NEX.md")}function wi(){let t=ns();Ie.existsSync(t)||Ie.mkdirSync(t,{recursive:!0})}function Nh(t){let e=vt.join(ns(),t);return Ie.existsSync(e)||Ie.mkdirSync(e,{recursive:!0}),e}function No(){let t=Us();if(!Ie.existsSync(t))return{};try{return JSON.parse(Ie.readFileSync(t,"utf-8"))}catch{return{}}}function Mh(t){wi(),yi(Us(),JSON.stringify(t,null,2))}function Ph(){let t=Us();if(!Ie.existsSync(t))return;let e=No(),s=Object.keys(e);if(s.length===0){try{Ie.renameSync(t,t+".bak")}catch{}return}for(let n of s){let o=e[n],r=o.value||String(o),i=n.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=Nh("project"),l=vt.join(a,`${i}.md`),c=r.split(`
197
197
  `)[0].slice(0,100),u=`---
198
198
  name: ${n}
199
199
  description: ${c}
@@ -201,7 +201,7 @@ type: project
201
201
  ---
202
202
 
203
203
  ${r}
204
- `;ci(l,u)}di();try{Le.renameSync(t,t+".bak")}catch{}}function Zk(t,e,s,n){if(!To.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${To.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!s||typeof s!="string"||s.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let o=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!o)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=pp(t),i=kt.join(r,`${o}.md`);if(Le.existsSync(i))try{if(Ul(Le.readFileSync(i,"utf-8")).body.slice(0,200)===s.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=n||s.split(`
204
+ `;yi(l,u)}$i();try{Ie.renameSync(t,t+".bak")}catch{}}function Cx(t,e,s,n){if(!Oo.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Oo.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!s||typeof s!="string"||s.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let o=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!o)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=Nh(t),i=vt.join(r,`${o}.md`);if(Ie.existsSync(i))try{if(Ql(Ie.readFileSync(i,"utf-8")).body.slice(0,200)===s.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=n||s.split(`
205
205
  `)[0].slice(0,100),l=`---
206
206
  name: ${e}
207
207
  description: ${a}
@@ -209,11 +209,11 @@ type: ${t}
209
209
  ---
210
210
 
211
211
  ${s}
212
- `;return ci(i,l),di(),{ok:!0,path:i,updated:!0}}function Qk(t,e){if(!To.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=kt.join(Vn(),t,`${s}.md`);if(!Le.existsSync(n))return!1;try{return Le.unlinkSync(n),di(),!0}catch{return!1}}function Ul(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let s=e[1],n=(e[2]||"").trim(),o=r=>{let i=s.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:o("name"),description:o("description"),type:o("type"),body:n}}function yp(){let t=[],e=Vn();for(let s of To){let n=kt.join(e,s);if(!Le.existsSync(n))continue;let o;try{o=Le.readdirSync(n).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=kt.join(n,r);try{let a=Le.readFileSync(i,"utf-8"),l=Ul(a);t.push({type:s,name:l.name||kt.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function di(){let t=yp(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=Vk+2)break;let n=`${s.type}/${kt.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}ui(),ci(fp(),e.join(`
212
+ `;return yi(i,l),$i(),{ok:!0,path:i,updated:!0}}function Ax(t,e){if(!Oo.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=vt.join(ns(),t,`${s}.md`);if(!Ie.existsSync(n))return!1;try{return Ie.unlinkSync(n),$i(),!0}catch{return!1}}function Ql(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let s=e[1],n=(e[2]||"").trim(),o=r=>{let i=s.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:o("name"),description:o("description"),type:o("type"),body:n}}function Lh(){let t=[],e=ns();for(let s of Oo){let n=vt.join(e,s);if(!Ie.existsSync(n))continue;let o;try{o=Ie.readdirSync(n).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=vt.join(n,r);try{let a=Ie.readFileSync(i,"utf-8"),l=Ql(a);t.push({type:s,name:l.name||vt.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function $i(){let t=Lh(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=Tx+2)break;let n=`${s.type}/${vt.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}wi(),yi(Ah(),e.join(`
213
213
  `)+`
214
- `)}function wp(){let t=fp();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function ex(t,e){ui(),dp(js(),()=>{let s=Ro();s[t]={value:e,updatedAt:new Date().toISOString()},mp(s)})}function tx(t){let e=Ro();return e[t]?e[t].value:null}function nx(t){return ui(),dp(js(),()=>{let e=Ro();return t in e?(delete e[t],mp(e),!0):!1})}function _p(){let t=Ro();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function $p(){let t=hp();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function bp(){let t=Jk();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function sx(){gp();let t=[],e=$p();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
215
- ${e}`);let s=bp();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
216
- ${s}`);let n="",o=wp();if(o)n=o;else{let d=_p();d.length>0&&(n=`PROJECT MEMORY:
214
+ `)}function Ih(){let t=Ah();if(!Ie.existsSync(t))return"";try{return Ie.readFileSync(t,"utf-8").trim()}catch{return""}}function Ox(t,e){wi(),Ch(Us(),()=>{let s=No();s[t]={value:e,updatedAt:new Date().toISOString()},Mh(s)})}function Nx(t){let e=No();return e[t]?e[t].value:null}function Mx(t){return wi(),Ch(Us(),()=>{let e=No();return t in e?(delete e[t],Mh(e),!0):!1})}function jh(){let t=No();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Dh(){let t=Oh();if(!Ie.existsSync(t))return"";try{return Ie.readFileSync(t,"utf-8").trim()}catch{return""}}function qh(){let t=Rx();if(!Ie.existsSync(t))return"";try{return Ie.readFileSync(t,"utf-8").trim()}catch{return""}}function Px(){Ph();let t=[],e=Dh();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
215
+ ${e}`);let s=qh();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
216
+ ${s}`);let n="",o=Ih();if(o)n=o;else{let d=jh();d.length>0&&(n=`PROJECT MEMORY:
217
217
  ${d.map(p=>` ${p.key}: ${p.value}`).join(`
218
218
  `)}`)}let r=t.join(`
219
219
 
@@ -222,83 +222,80 @@ ${d.map(p=>` ${p.key}: ${p.value}`).join(`
222
222
  `}n=f.trimEnd()+`
223
223
  [Memory index truncated \u2014 use delete_memory to prune old entries]`}else n.length>c&&(n="");let u=[...t];return n&&u.push(n),u.length>0&&u.push(i),u.join(`
224
224
 
225
- `)}kp.exports={saveMemory:Zk,deleteMemory:Qk,scanMemories:yp,rebuildIndex:di,loadMemoryIndex:wp,remember:ex,recall:tx,forget:nx,listMemories:_p,loadGlobalInstructions:$p,loadProjectInstructions:bp,getMemoryContext:sx,_getMemoryDir:Vn,_getMemoryFile:js,_getGlobalNexMdPath:hp,_parseMemoryFile:Ul,_migrateIfNeeded:gp,VALID_TYPES:To}});var Rp=Z((HR,Tp)=>{var Ao=require("fs"),Wl=require("path"),Hl=process.env.NEX_AUDIT!=="false",Jn=null;function xp(){return Jn||(Jn=Wl.join(process.cwd(),".nex","audit"),Ao.existsSync(Jn)||Ao.mkdirSync(Jn,{recursive:!0}),Jn)}function Sp(){let t=new Date().toISOString().split("T")[0];return Wl.join(xp(),`${t}.jsonl`)}function ox(t){if(Hl)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Ep(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},s=JSON.stringify(e)+`
226
- `;Ao.appendFileSync(Sp(),s,"utf-8")}catch{}}function Ep(t){if(!t||typeof t!="object")return{};let e={};for(let[s,n]of Object.entries(t))/key|token|password|secret|credential/i.test(s)?e[s]="***":typeof n=="string"&&n.length>500?e[s]=n.substring(0,500)+`... (${n.length} chars)`:e[s]=n;return e}function vp(t={}){let e=xp(),s=t.days||1,n=[];for(let o=0;o<s;o++){let r=t.date||new Date(Date.now()-o*864e5).toISOString().split("T")[0],i=Wl.join(e,`${r}.jsonl`);if(!Ao.existsSync(i))continue;let a=Ao.readFileSync(i,"utf-8").split(`
227
- `).filter(l=>l.trim());for(let l of a)try{let c=JSON.parse(l);if(t.tool&&c.tool!==t.tool)continue;n.push(c)}catch{}if(t.date)break}return n}function rx(t=1){let e=vp({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let s={},n=0,o=0;for(let r of e)s[r.tool]=(s[r.tool]||0)+1,n+=r.duration||0,r.success&&o++;return{totalCalls:e.length,byTool:s,avgDuration:Math.round(n/e.length),successRate:o/e.length}}function ix(t){Hl=t}function ax(){return Hl}function lx(){Jn=null}Tp.exports={logToolExecution:ox,sanitizeArgs:Ep,readAuditLog:vp,getAuditSummary:rx,setAuditEnabled:ix,isAuditEnabled:ax,getAuditLogPath:Sp,_reset:lx}});var Fp=Z((zR,qp)=>{var Fe=require("fs").promises,qs=require("fs"),pe=require("path"),De=require("util").promisify(require("child_process").exec),Zn=require("util").promisify(require("child_process").execFile),{spawnSync:cx}=require("child_process"),Yl=require("axios"),{isForbidden:ux,isSSHForbidden:dx,isDangerous:fx,isCritical:Cp,isBashPathForbidden:hx,confirm:Wt}=lo(),{showDiff:fi,showNewFile:px,showEditDiff:YR,confirmFileChange:Oo}=$d(),{C:ae,Spinner:mx,getToolSpinnerText:gx}=Je(),{isGitRepo:Gl,getCurrentBranch:Ap,getStatus:yx,getDiff:wx}=jr(),{recordChange:hi}=Od(),{fuzzyFindText:Op,findMostSimilar:Po}=tf(),{runDiagnostics:No}=sf(),{findFileInIndex:_x,getFileIndex:GR}=Cs(),{resolveProfile:Mt,sshExec:ht,scpUpload:$x,scpDownload:Np}=As(),{resolveDeployConfig:bx,loadDeployConfigs:kx}=bf(),{getEditMode:Mp}=_o(),xx=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|telnet\s|screen|tmux|fzf|gum|dialog|whiptail|man\s|node\s*$|python3?\s*$|irb\s*$|rails\s*c|psql\s|mysql\s|redis-cli|mongosh?|sqlite3)\b/,Sx=/^ssh\s/,Ex=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function xt(t){return Fe.access(t).then(()=>!0).catch(()=>!1)}var pi=null,Pp=0,vx=12e4;function Tx(){let t=Date.now();if(pi&&t-Pp<vx)return pi;let e=pe.dirname(process.cwd());try{let s=qs.readdirSync(e,{withFileTypes:!0}),n=pe.basename(process.cwd()),o=s.filter(r=>r.isDirectory()&&r.name!==n&&!r.name.startsWith(".")).map(r=>r.name).sort();return pi=o.length>0?o:null,Pp=t,pi}catch{return null}}function zl(t){if(t&&pe.resolve(t)!==process.cwd())return"";let e=Tx();if(!e)return"";let s=pe.dirname(process.cwd());return`
225
+ `)}Fh.exports={saveMemory:Cx,deleteMemory:Ax,scanMemories:Lh,rebuildIndex:$i,loadMemoryIndex:Ih,remember:Ox,recall:Nx,forget:Mx,listMemories:jh,loadGlobalInstructions:Dh,loadProjectInstructions:qh,getMemoryContext:Px,_getMemoryDir:ns,_getMemoryFile:Us,_getGlobalNexMdPath:Oh,_parseMemoryFile:Ql,_migrateIfNeeded:Ph,VALID_TYPES:Oo}});var Gh=V((Y1,Yh)=>{var Po=require("fs"),ec=require("path"),tc=process.env.NEX_AUDIT!=="false",ss=null;function Bh(){return ss||(ss=ec.join(process.cwd(),".nex","audit"),Po.existsSync(ss)||Po.mkdirSync(ss,{recursive:!0}),ss)}function Uh(){let t=new Date().toISOString().split("T")[0];return ec.join(Bh(),`${t}.jsonl`)}function Lx(t){if(tc)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Wh(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},s=JSON.stringify(e)+`
226
+ `;Po.appendFileSync(Uh(),s,"utf-8")}catch{}}function Wh(t){if(!t||typeof t!="object")return{};let e={};for(let[s,n]of Object.entries(t))/key|token|password|secret|credential/i.test(s)?e[s]="***":typeof n=="string"&&n.length>500?e[s]=n.substring(0,500)+`... (${n.length} chars)`:e[s]=n;return e}function Hh(t={}){let e=Bh(),s=t.days||1,n=[];for(let o=0;o<s;o++){let r=t.date||new Date(Date.now()-o*864e5).toISOString().split("T")[0],i=ec.join(e,`${r}.jsonl`);if(!Po.existsSync(i))continue;let a=Po.readFileSync(i,"utf-8").split(`
227
+ `).filter(l=>l.trim());for(let l of a)try{let c=JSON.parse(l);if(t.tool&&c.tool!==t.tool)continue;n.push(c)}catch{}if(t.date)break}return n}function Ix(t=1){let e=Hh({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let s={},n=0,o=0;for(let r of e)s[r.tool]=(s[r.tool]||0)+1,n+=r.duration||0,r.success&&o++;return{totalCalls:e.length,byTool:s,avgDuration:Math.round(n/e.length),successRate:o/e.length}}function jx(t){tc=t}function Dx(){return tc}function qx(){ss=null}Yh.exports={logToolExecution:Lx,sanitizeArgs:Wh,readAuditLog:Hh,getAuditSummary:Ix,setAuditEnabled:jx,isAuditEnabled:Dx,getAuditLogPath:Uh,_reset:qx}});var dm=V((z1,um)=>{var He=require("fs").promises,Kt=require("fs"),ce=require("path"),Fe=require("util").promisify(require("child_process").exec),os=require("util").promisify(require("child_process").execFile),{spawnSync:Fx}=require("child_process"),nc=require("axios"),{isForbidden:Bx,isSSHForbidden:Ux,isDangerous:Wx,isCritical:zh,isBashPathForbidden:Hx,confirm:zt}=fo(),{showDiff:_i,showNewFile:Yx,showEditDiff:G1,confirmFileChange:Lo}=Ld(),{C:ie,Spinner:Gx,getToolSpinnerText:zx}=tt(),{isGitRepo:sc,getCurrentBranch:Kh,getStatus:Kx,getDiff:Xx}=Yr(),{recordChange:bi}=Gd(),{fuzzyFindText:Xh,findMostSimilar:Fo}=yf(),{runDiagnostics:Io}=$f(),{findFileInIndex:Vx,getFileIndex:Vh,searchContentIndex:Jx,scorePathMatch:Jh,refreshIndex:Zx,isIndexValid:Qx}=mn(),{resolveProfile:jt,sshExec:gt,scpUpload:eS,scpDownload:Zh}=Ps(),{resolveDeployConfig:tS,loadDeployConfigs:nS}=qf(),{getEditMode:Qh}=xo(),sS=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|telnet\s|screen|tmux|fzf|gum|dialog|whiptail|man\s|node\s*$|python3?\s*$|irb\s*$|rails\s*c|psql\s|mysql\s|redis-cli|mongosh?|sqlite3)\b/,oS=/^ssh\s/,rS=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Tt(t){return He.access(t).then(()=>!0).catch(()=>!1)}var ki=null,em=0,iS=12e4;function aS(){let t=Date.now();if(ki&&t-em<iS)return ki;let e=ce.dirname(process.cwd());try{let s=Kt.readdirSync(e,{withFileTypes:!0}),n=ce.basename(process.cwd()),o=s.filter(r=>r.isDirectory()&&r.name!==n&&!r.name.startsWith(".")).map(r=>r.name).sort();return ki=o.length>0?o:null,em=t,ki}catch{return null}}function oc(t){if(t&&ce.resolve(t)!==process.cwd())return"";let e=aS();if(!e)return"";let s=ce.dirname(process.cwd());return`
228
228
  Hint: no matches in current project. Sibling directories in ${s}/:
229
229
  ${e.join(", ")}
230
- You can search there with: grep pattern --path ${s}/<dir>`}async function mi(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=Qe(e);if(s&&await xt(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=pe.extname(t);if(!o)for(let i of n){let a=Qe(t+i);if(a&&await xt(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let a of n){if(a===o)continue;let l=Qe(i+a);if(l&&await xt(l))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=pe.basename(t);if(r&&r.length>2)try{let i=_x(r).map(a=>Qe(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${pe.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
231
- ${i.map(l=>pe.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
232
- `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=Cs(),l=a().filter(c=>pe.basename(c).toLowerCase()===i).map(c=>Qe(c));if(l.length===1)return{fixedPath:l[0],message:`(auto-fixed: case-insensitive match \u2192 ${pe.relative(process.cwd(),l[0])})`};if(l.length>1&&l.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
233
- ${l.map(u=>pe.relative(process.cwd(),u)).map(u=>` - ${u}`).join(`
234
- `)}`}}catch{}try{let{smartSearch:i}=Cs(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=Qe(a[0].file);if(a[0].score>=200||a.length===1&&a[0].score>=50)return{fixedPath:l,message:`(auto-fixed: smart matched ${t} \u2192 ${pe.relative(process.cwd(),l)})`};if(a.length>=2&&a[0].score>=80&&a[0].score>=a[1].score*1.5)return{fixedPath:l,message:`(auto-fixed: best match ${t} \u2192 ${pe.relative(process.cwd(),l)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
235
- ${a.map(u=>pe.relative(process.cwd(),Qe(u.file))).map(u=>` - ${u}`).join(`
236
- `)}`}}}catch{}return{fixedPath:null,message:""}}function Rx(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":/\bsed\s+-n\s+['"]?\d+,\d+p/.test(t)?'sed -n line-range scrolling floods context with irrelevant lines. Use targeted grep instead: grep -n "ERROR\\|pattern" <logfile> | tail -20':""}function Dp(t,e){let s=[];if(/command not found|: not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&s.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&s.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),s.length===0?t:t+`
230
+ You can search there with: grep pattern --path ${s}/<dir>`}async function xi(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=st(e);if(s&&await Tt(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=ce.extname(t);if(!o)for(let i of n){let a=st(t+i);if(a&&await Tt(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let a of n){if(a===o)continue;let l=st(i+a);if(l&&await Tt(l))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=ce.basename(t);if(r&&r.length>2)try{let i=Vx(r).map(a=>st(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${ce.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
231
+ ${i.map(l=>ce.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
232
+ `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=mn(),l=a().filter(c=>ce.basename(c).toLowerCase()===i).map(c=>st(c));if(l.length===1)return{fixedPath:l[0],message:`(auto-fixed: case-insensitive match \u2192 ${ce.relative(process.cwd(),l[0])})`};if(l.length>1&&l.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
233
+ ${l.map(u=>ce.relative(process.cwd(),u)).map(u=>` - ${u}`).join(`
234
+ `)}`}}catch{}try{let{smartSearch:i}=mn(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=st(a[0].file);if(a[0].score>=200||a.length===1&&a[0].score>=50)return{fixedPath:l,message:`(auto-fixed: smart matched ${t} \u2192 ${ce.relative(process.cwd(),l)})`};if(a.length>=2&&a[0].score>=80&&a[0].score>=a[1].score*1.5)return{fixedPath:l,message:`(auto-fixed: best match ${t} \u2192 ${ce.relative(process.cwd(),l)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
235
+ ${a.map(u=>ce.relative(process.cwd(),st(u.file))).map(u=>` - ${u}`).join(`
236
+ `)}`}}}catch{}return{fixedPath:null,message:""}}function lS(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":/\bsed\s+-n\s+['"]?\d+,\d+p/.test(t)?'sed -n line-range scrolling floods context with irrelevant lines. Use targeted grep instead: grep -n "ERROR\\|pattern" <logfile> | tail -20':""}function om(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e||/[()[\]{}|^$\\]/.test(e))return null;let s=e.replace(/\*\*/g," ").replace(/[*?]/g," ").replace(/[:=><!]+/g," ").replace(/\s+/g," ").trim();if(!s)return null;let n=s.split(/[\/\s,]+/).map(o=>o.trim()).filter(Boolean).filter(o=>o!=="."&&o!=="..").filter(o=>!/^\.[a-z0-9]+$/i.test(o)).filter(o=>o.length>=3);return n.length===0?null:(n.sort((o,r)=>r.length-o.length),n[0])}async function rm(t,e){let s=om(t);if(!s)return new Map;try{let n=await Jx(s,void 0,e||process.cwd()),o=new Map;for(let r of n){let a=r.name.toLowerCase()===s.toLowerCase()?140:90;o.set(r.file,(o.get(r.file)||0)+a)}return o}catch{return new Map}}function tm(t,e){if(!t)return"";let s=e||process.cwd(),n=ce.isAbsolute(t)?t:ce.resolve(s,t),o=ce.relative(s,n);return o&&!o.startsWith("..")&&!ce.isAbsolute(o)?o:ce.relative(process.cwd(),n)}function jo(t,e){let s=(t||"").trim();return s?e==="files_with_matches"||e==="count"?s.split(`
237
+ `).filter(n=>n.trim()):s.split(`
238
+ `).filter(n=>n.trim()):[]}function im(t,{query:e,basePath:s,definitionScores:n=new Map,mtimeByPath:o=new Map}={}){let r=om(e);return[...t].sort((i,a)=>{let l=tm(i,s),c=tm(a,s),u=0,d=0;if(r&&(u+=Jh(l,r),d+=Jh(c,r)),u+=n.get(l)||0,d+=n.get(c)||0,u!==d)return d-u;let f=o.get(i)||0,p=o.get(a)||0;return f!==p?p-f:l.localeCompare(c)})}async function rc(t,{query:e,basePath:s,outputMode:n}={}){if(!Array.isArray(t)||t.length<=1)return t;let o=new Map,r=[];for(let c of t){if(!c)continue;let u=c;(n==="count"||n!=="files_with_matches")&&(u=c.split(":")[0]),o.has(u)||(o.set(u,[]),r.push(u)),o.get(u).push(c)}let i=await rm(e,s),a=im(r,{query:e,basePath:s,definitionScores:i}),l=[];for(let c of a)l.push(...o.get(c)||[]);return l}function am(t,e){let s=[];if(/command not found|: not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&s.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&s.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),s.length===0?t:t+`
237
239
 
238
240
  `+s.join(`
239
- `)}function jp(t,e,s){let n=Po(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var Lp=!1,Qn=null;function Cx(){Qn&&(Qn(),Qn=null)}var Xl=null;function Ax(t){Xl=t}async function Kl(){if(!Lp){Lp=!0;try{let{stdout:t}=await De("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await De('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await De("git stash pop",{cwd:process.cwd(),timeout:1e4}),await De("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Ox=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function Qe(t){let e=pe.isAbsolute(t)?pe.resolve(t):pe.resolve(process.cwd(),t);for(let s of Ox)if(s.test(e))return null;return e}var Nx=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Optionally use include to filter by file type (e.g. '*.js') but OMIT it when first searching \u2014 code may live in .html, .vue, .py or other unexpected file types. Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"visual_review",description:"Screenshot a URL, analyze the visual result, and return structured feedback about layout, design, and usability issues. Use this to visually inspect web pages, check CSS changes, or verify UI fixes. Returns the screenshot path + analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot and analyze"},focus:{type:"string",description:"What to focus on: layout, colors, typography, spacing, responsiveness, accessibility, or a custom description (e.g. 'check the navbar alignment')"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"},full_page:{type:"boolean",description:"Capture full scrollable page (default: false)"},compare_with:{type:"string",description:"Path to a previous screenshot to compare against (optional). Enables before/after analysis."}},required:["url"]}}},{type:"function",function:{name:"clipboard_image",description:"Grab the current image from the system clipboard (macOS). Returns the screenshot path for visual analysis. Use when the user says 'clipboard', 'pasteboard', or wants to analyze a copied screenshot.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"visual_diff",description:"Compare two screenshots pixel-by-pixel and compute a visual diff. Returns the percentage of changed pixels and which screen regions (top-left, center, bottom-right, etc.) were affected. Use after making CSS/HTML changes to quantify what changed. Example: take a before screenshot, make changes, take an after screenshot, then visual_diff both paths.",parameters:{type:"object",properties:{before:{type:"string",description:"Path to the 'before' screenshot (PNG)"},after:{type:"string",description:"Path to the 'after' screenshot (PNG)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1). Lower = more sensitive."}},required:["before","after"]}}},{type:"function",function:{name:"responsive_sweep",description:"Screenshot a URL at 5 viewport widths (320, 768, 1024, 1440, 1920) and return all screenshots for breakpoint analysis. Quickly identifies responsive layout issues across mobile, tablet, and desktop. Returns images for visual analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot at each viewport"},viewports:{type:"array",items:{type:"object",properties:{width:{type:"number"},label:{type:"string"}}},description:"Custom viewport list (default: 320/768/1024/1440/1920)"},full_page:{type:"boolean",description:"Capture full scrollable page at each viewport (default: false)"}},required:["url"]}}},{type:"function",function:{name:"visual_annotate",description:"Draw annotations (red boxes, arrows, circles) directly on a screenshot to mark problem areas. Returns the annotated image. Use instead of describing locations verbally \u2014 visual markers are unambiguous.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to the screenshot (PNG) to annotate"},annotations:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"box, arrow, or circle"},x:{type:"number",description:"X position (px)"},y:{type:"number",description:"Y position (px)"},width:{type:"number",description:"Width for box (px)"},height:{type:"number",description:"Height for box (px)"},toX:{type:"number",description:"Arrow end X (px)"},toY:{type:"number",description:"Arrow end Y (px)"},radius:{type:"number",description:"Circle radius (px)"},label:{type:"string",description:"Text label for the annotation"},color:{type:"string",description:"Hex color (default: #FF0000)"}},required:["type","x","y"]},description:"List of annotations to draw"}},required:["image","annotations"]}}},{type:"function",function:{name:"visual_watch",description:"Hot-reload visual feedback loop: watches source files for changes, waits for HMR to settle, takes a new screenshot, diffs it against the previous one, and reports what changed. Runs up to N iterations (default: 10). Requires a running dev server (Vite, Next, etc.) and chokidar. Use for autonomous visual polish loops.",parameters:{type:"object",properties:{url:{type:"string",description:"Dev server URL to screenshot (e.g. http://localhost:5173)"},watch:{type:"array",items:{type:"string"},description:"File paths or directories to watch for changes (e.g. ['src/components', 'src/styles'])"},max_iterations:{type:"number",description:"Max number of change\u2192screenshot\u2192diff cycles (default: 10)"},hmr_delay:{type:"number",description:"Milliseconds to wait after file change for HMR to settle (default: 1500)"}},required:["url","watch"]}}},{type:"function",function:{name:"design_tokens",description:"Extract design tokens from a screenshot: dominant colors (with hex/rgb/frequency/category), detected vertical spacing values, and image dimensions. Use to audit visual consistency, compare against a design system, or reverse-engineer CSS variables from a rendered page.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to screenshot (PNG) to analyze"},sample_rate:{type:"number",description:"Pixel sampling interval \u2014 lower = more accurate but slower (default: 4)"}},required:["image"]}}},{type:"function",function:{name:"design_compare",description:"Compare a live web page against a reference design (Figma export, mockup PNG). Screenshots the URL at the reference image's dimensions, computes pixel-level diff, and returns annotated images highlighting deviations. Use to verify implementation matches the design spec.",parameters:{type:"object",properties:{url:{type:"string",description:"Live URL to compare against the reference"},reference:{type:"string",description:"Path to reference design image (PNG)"},width:{type:"number",description:"Override viewport width (default: match reference image width)"},height:{type:"number",description:"Override viewport height (default: 800)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1)"}},required:["url","reference"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'},background:{type:"boolean",description:"Run this agent non-blocking in the background. The main session continues immediately; results are injected as [BACKGROUND AGENT COMPLETED] user messages when the agent finishes. Use for tasks that can run in parallel to your main work."}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl) that live on almalinux9. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/deploy/app). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "my-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "my-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function Mo(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function Ip(t,e,s={}){switch(t){case"bash":{let n=e.command,o=ux(n);if(o){let d=Rx(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
240
- HINT: ${d}`:""}`}let r=hx(n);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
241
- HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?Cp(n):fx(n)){let d=Cp(n)?"\u26D4":"\u26A0";if(!await Wt(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),qs.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${ae.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${ae.reset}`)}let l=Sx.test(n.trim())&&!Ex.test(n.trim());if(xx.test(n.trim())||l){s.silent||console.log(`${ae.dim} \u25B6 interactive: ${n}${ae.reset}`);let d=cx("sh",["-c",n],{stdio:"inherit",cwd:a});return d.error?`ERROR: ${d.error.message}`:d.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${d.status})`}let{ToolProgress:c}=vs(),u=s.silent?null:new c("bash",n.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await De(n,{cwd:a,timeout:9e4,maxBuffer:5242880});return u&&u.stop(),d||f||"(no output)"}catch(d){u&&u.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),p=Dp(f,n);return`EXIT ${d.code||1}
242
- ${p}`}}case"read_file":{let n=Qe(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await xt(n)){let N=await mi(e.path);if(N.fixedPath)n=N.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${pe.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${N.message?`
243
- `+N.message:""}`}let r=Buffer.alloc(8192),i=await qs.promises.open(n,"r"),{bytesRead:a}=await i.read(r,0,8192,0);await i.close();for(let N=0;N<a;N++)if(r[N]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await Fe.readFile(n,"utf-8");if(!l&&(await Fe.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let c=l.split(`
244
- `),u=await Fe.stat(n),d=c.length,f=350,p=!e.line_start&&!e.line_end,m=p&&d>f,g=(e.line_start||1)-1,_=m?f:e.line_end||c.length,k=pe.relative(process.cwd(),n),A=m?`showing lines 1-${f} of ${d}`:e.line_start||e.line_end?`lines ${g+1}-${_} of ${d}`:`${d} lines`,L=`File: ${k} (${A}, ${u.size} bytes)`,E=c.slice(g,_).map((N,te)=>`${g+te+1}: ${N}`).join(`
245
- `),v=m?`
246
-
247
- [\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${f} of ${d} total lines. The rest of the file is HIDDEN. You MUST use line_start and line_end to read further down (e.g. line_start=${f+1}), or use grep_search to find specific keywords.]`:!p&&d>_?`
248
-
249
- [\u{1F6A8} FILE CONTINUES: This is only lines ${g+1} to ${_} of ${d} total. The rest is HIDDEN. Use line_start=${_+1} to read the next section, or grep_search for keywords.]`:"";return`${L}
250
- ${E}${v}`}case"write_file":{await Kl();let n=Qe(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await xt(n),r=null;if(s.autoConfirm)o&&(r=await Fe.readFile(n,"utf-8"));else if(o){r=await Fe.readFile(n,"utf-8");let u=await No(n,e.content);if(fi(n,r,e.content,{annotations:u}),!await Oo("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await No(n,e.content);if(px(n,e.content,{annotations:u}),!await Oo("Create"))return"CANCELLED: User declined to create file."}let i=pe.dirname(n);await xt(i)||await Fe.mkdir(i,{recursive:!0}),await Fe.writeFile(n,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");l&&await Fe.chmod(n,493),hi("write_file",n,r,e.content);let c=l?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${c}`}case"edit_file":{await Kl();let n=Qe(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await xt(n)){let u=await mi(e.path);if(u.fixedPath)n=u.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${pe.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${u.message?`
251
- `+u.message:""}`}let r=await Fe.readFile(n,"utf-8"),i=e.old_text,a=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:u,getActiveProviderName:d}=ot();if(Mp(u(),d())==="strict"){let m=Po(r,e.old_text);return m?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
241
+ `)}function lm(t,e,s){let n=Fo(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var nm=!1,rs=null;function cS(){rs&&(rs(),rs=null)}var cc=null;function uS(t){cc=t}async function ic(){if(!nm){nm=!0;try{let{stdout:t}=await Fe("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Fe('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Fe("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Fe("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var dS=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function fS(){let t=process.cwd();try{return Kt.realpathSync(t)}catch{return ce.resolve(t)}}function pS(t,e){let s=ce.relative(e,t);return s===""||!s.startsWith("..")&&!ce.isAbsolute(s)}function hS(t){if(Kt.existsSync(t))return Kt.realpathSync(t);let e=ce.dirname(t);for(;e&&e!==ce.dirname(e);){if(Kt.existsSync(e)){let s=Kt.realpathSync(e),n=ce.relative(e,t);return ce.resolve(s,n)}e=ce.dirname(e)}return t}function st(t){let e=ce.isAbsolute(t)?ce.resolve(t):ce.resolve(process.cwd(),t);for(let n of dS)if(n.test(e))return null;let s=hS(e);return pS(s,fS())?s:null}function xe(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function cm(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function mS(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function gS(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function ac(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function yS(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Do(t,e="user"){return cm(t)?null:`ERROR: ${e} contains unsafe characters`}function lc(t,e="service"){return mS(t)?null:`ERROR: ${e} contains unsafe characters`}var wS=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Optionally use include to filter by file type (e.g. '*.js') but OMIT it when first searching \u2014 code may live in .html, .vue, .py or other unexpected file types. Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"visual_review",description:"Screenshot a URL, analyze the visual result, and return structured feedback about layout, design, and usability issues. Use this to visually inspect web pages, check CSS changes, or verify UI fixes. Returns the screenshot path + analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot and analyze"},focus:{type:"string",description:"What to focus on: layout, colors, typography, spacing, responsiveness, accessibility, or a custom description (e.g. 'check the navbar alignment')"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"},full_page:{type:"boolean",description:"Capture full scrollable page (default: false)"},compare_with:{type:"string",description:"Path to a previous screenshot to compare against (optional). Enables before/after analysis."}},required:["url"]}}},{type:"function",function:{name:"clipboard_image",description:"Grab the current image from the system clipboard (macOS). Returns the screenshot path for visual analysis. Use when the user says 'clipboard', 'pasteboard', or wants to analyze a copied screenshot.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"visual_diff",description:"Compare two screenshots pixel-by-pixel and compute a visual diff. Returns the percentage of changed pixels and which screen regions (top-left, center, bottom-right, etc.) were affected. Use after making CSS/HTML changes to quantify what changed. Example: take a before screenshot, make changes, take an after screenshot, then visual_diff both paths.",parameters:{type:"object",properties:{before:{type:"string",description:"Path to the 'before' screenshot (PNG)"},after:{type:"string",description:"Path to the 'after' screenshot (PNG)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1). Lower = more sensitive."}},required:["before","after"]}}},{type:"function",function:{name:"responsive_sweep",description:"Screenshot a URL at 5 viewport widths (320, 768, 1024, 1440, 1920) and return all screenshots for breakpoint analysis. Quickly identifies responsive layout issues across mobile, tablet, and desktop. Returns images for visual analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot at each viewport"},viewports:{type:"array",items:{type:"object",properties:{width:{type:"number"},label:{type:"string"}}},description:"Custom viewport list (default: 320/768/1024/1440/1920)"},full_page:{type:"boolean",description:"Capture full scrollable page at each viewport (default: false)"}},required:["url"]}}},{type:"function",function:{name:"visual_annotate",description:"Draw annotations (red boxes, arrows, circles) directly on a screenshot to mark problem areas. Returns the annotated image. Use instead of describing locations verbally \u2014 visual markers are unambiguous.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to the screenshot (PNG) to annotate"},annotations:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"box, arrow, or circle"},x:{type:"number",description:"X position (px)"},y:{type:"number",description:"Y position (px)"},width:{type:"number",description:"Width for box (px)"},height:{type:"number",description:"Height for box (px)"},toX:{type:"number",description:"Arrow end X (px)"},toY:{type:"number",description:"Arrow end Y (px)"},radius:{type:"number",description:"Circle radius (px)"},label:{type:"string",description:"Text label for the annotation"},color:{type:"string",description:"Hex color (default: #FF0000)"}},required:["type","x","y"]},description:"List of annotations to draw"}},required:["image","annotations"]}}},{type:"function",function:{name:"visual_watch",description:"Hot-reload visual feedback loop: watches source files for changes, waits for HMR to settle, takes a new screenshot, diffs it against the previous one, and reports what changed. Runs up to N iterations (default: 10). Requires a running dev server (Vite, Next, etc.) and chokidar. Use for autonomous visual polish loops.",parameters:{type:"object",properties:{url:{type:"string",description:"Dev server URL to screenshot (e.g. http://localhost:5173)"},watch:{type:"array",items:{type:"string"},description:"File paths or directories to watch for changes (e.g. ['src/components', 'src/styles'])"},max_iterations:{type:"number",description:"Max number of change\u2192screenshot\u2192diff cycles (default: 10)"},hmr_delay:{type:"number",description:"Milliseconds to wait after file change for HMR to settle (default: 1500)"}},required:["url","watch"]}}},{type:"function",function:{name:"design_tokens",description:"Extract design tokens from a screenshot: dominant colors (with hex/rgb/frequency/category), detected vertical spacing values, and image dimensions. Use to audit visual consistency, compare against a design system, or reverse-engineer CSS variables from a rendered page.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to screenshot (PNG) to analyze"},sample_rate:{type:"number",description:"Pixel sampling interval \u2014 lower = more accurate but slower (default: 4)"}},required:["image"]}}},{type:"function",function:{name:"design_compare",description:"Compare a live web page against a reference design (Figma export, mockup PNG). Screenshots the URL at the reference image's dimensions, computes pixel-level diff, and returns annotated images highlighting deviations. Use to verify implementation matches the design spec.",parameters:{type:"object",properties:{url:{type:"string",description:"Live URL to compare against the reference"},reference:{type:"string",description:"Path to reference design image (PNG)"},width:{type:"number",description:"Override viewport width (default: match reference image width)"},height:{type:"number",description:"Override viewport height (default: 800)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1)"}},required:["url","reference"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'},background:{type:"boolean",description:"Run this agent non-blocking in the background. The main session continues immediately; results are injected as [BACKGROUND AGENT COMPLETED] user messages when the agent finishes. Use for tasks that can run in parallel to your main work."}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl) that live on almalinux9. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/deploy/app). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "my-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "my-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function qo(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function sm(t,e,s={}){switch(t){case"bash":{let n=e.command,o=Bx(n);if(o){let d=lS(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
242
+ HINT: ${d}`:""}`}let r=Hx(n);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
243
+ HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?zh(n):Wx(n)){let d=zh(n)?"\u26D4":"\u26A0";if(!await zt(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Kt.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${ie.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${ie.reset}`)}let l=oS.test(n.trim())&&!rS.test(n.trim());if(sS.test(n.trim())||l){s.silent||console.log(`${ie.dim} \u25B6 interactive: ${n}${ie.reset}`);let d=Fx("sh",["-c",n],{stdio:"inherit",cwd:a});return d.error?`ERROR: ${d.error.message}`:d.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${d.status})`}let{ToolProgress:c}=Os(),u=s.silent?null:new c("bash",n.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await Fe(n,{cwd:a,timeout:9e4,maxBuffer:5242880});return u&&u.stop(),d||f||"(no output)"}catch(d){u&&u.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),p=am(f,n);return`EXIT ${d.code||1}
244
+ ${p}`}}case"read_file":{let n=st(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Tt(n)){let A=await xi(e.path);if(A.fixedPath)n=A.fixedPath,console.log(`${ie.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ce.relative(process.cwd(),n)}${ie.reset}`);else return`ERROR: File not found: ${e.path}${A.message?`
245
+ `+A.message:""}`}let r=Buffer.alloc(8192),i=await Kt.promises.open(n,"r"),{bytesRead:a}=await i.read(r,0,8192,0);await i.close();for(let A=0;A<a;A++)if(r[A]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await He.readFile(n,"utf-8");if(!l&&(await He.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let c=l.split(`
246
+ `),u=await He.stat(n),d=c.length,f=350,p=!e.line_start&&!e.line_end,m=p&&d>f,g=(e.line_start||1)-1,$=m?f:e.line_end||c.length,k=ce.relative(process.cwd(),n),M=m?`showing lines 1-${f} of ${d}`:e.line_start||e.line_end?`lines ${g+1}-${$} of ${d}`:`${d} lines`,D=`File: ${k} (${M}, ${u.size} bytes)`,v=c.slice(g,$).map((A,ee)=>`${g+ee+1}: ${A}`).join(`
247
+ `),E=m?`
248
+
249
+ [\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${f} of ${d} total lines. The rest of the file is HIDDEN. You MUST use line_start and line_end to read further down (e.g. line_start=${f+1}), or use grep_search to find specific keywords.]`:!p&&d>$?`
250
+
251
+ [\u{1F6A8} FILE CONTINUES: This is only lines ${g+1} to ${$} of ${d} total. The rest is HIDDEN. Use line_start=${$+1} to read the next section, or grep_search for keywords.]`:"";return`${D}
252
+ ${v}${E}`}case"write_file":{await ic();let n=st(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await Tt(n),r=null;if(s.autoConfirm)o&&(r=await He.readFile(n,"utf-8"));else if(o){r=await He.readFile(n,"utf-8");let u=await Io(n,e.content);if(_i(n,r,e.content,{annotations:u}),!await Lo("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await Io(n,e.content);if(Yx(n,e.content,{annotations:u}),!await Lo("Create"))return"CANCELLED: User declined to create file."}let i=ce.dirname(n);await Tt(i)||await He.mkdir(i,{recursive:!0}),await He.writeFile(n,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");l&&await He.chmod(n,493),bi("write_file",n,r,e.content);let c=l?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${c}`}case"edit_file":{await ic();let n=st(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Tt(n)){let u=await xi(e.path);if(u.fixedPath)n=u.fixedPath,console.log(`${ie.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ce.relative(process.cwd(),n)}${ie.reset}`);else return`ERROR: File not found: ${e.path}${u.message?`
253
+ `+u.message:""}`}let r=await He.readFile(n,"utf-8"),i=e.old_text,a=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:u,getActiveProviderName:d}=lt();if(Qh(u(),d())==="strict"){let m=Fo(r,e.old_text);return m?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
252
254
  Most similar text (line ${m.line}, distance ${m.distance}):
253
- ${m.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let p=Op(r,e.old_text);if(p)i=p,a=!0,console.log(`${ae.dim} \u2713 fuzzy whitespace match applied${ae.reset}`);else{let m=jp(r,e.old_text,e.new_text);if(m){if(!s.autoConfirm){let L=await No(n,m.content);if(fi(n,r,m.content,{annotations:L}),!await Oo(`Apply (auto-fix, line ${m.line}, distance ${m.distance})`))return"CANCELLED: User declined to apply edit."}await Fe.writeFile(n,m.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||m.content.startsWith("#!"))&&await Fe.chmod(n,493),hi("edit_file",n,r,m.content);let A=m.matchText.length>80?m.matchText.substring(0,77)+"...":m.matchText;return console.log(`${ae.dim} \u2713 auto-fixed edit: line ${m.line}, distance ${m.distance}${ae.reset}`),`Edited: ${n} (auto-fixed, line ${m.line}, distance ${m.distance}, matched: "${A}")`}let g=Po(r,e.old_text);if(g){let A=r.split(`
254
- `),L=Math.max(0,g.line-6),E=Math.min(A.length,g.line+10),v=A.slice(L,E).map((te,V)=>`${L+V+1}: ${te}`).join(`
255
- `),N=`line_start=${Math.max(1,g.line-5)} line_end=${Math.min(A.length,g.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${g.line}, distance ${g.distance})
255
+ ${m.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let p=Xh(r,e.old_text);if(p)i=p,a=!0,console.log(`${ie.dim} \u2713 fuzzy whitespace match applied${ie.reset}`);else{let m=lm(r,e.old_text,e.new_text);if(m){if(!s.autoConfirm){let D=await Io(n,m.content);if(_i(n,r,m.content,{annotations:D}),!await Lo(`Apply (auto-fix, line ${m.line}, distance ${m.distance})`))return"CANCELLED: User declined to apply edit."}await He.writeFile(n,m.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||m.content.startsWith("#!"))&&await He.chmod(n,493),bi("edit_file",n,r,m.content);let M=m.matchText.length>80?m.matchText.substring(0,77)+"...":m.matchText;return console.log(`${ie.dim} \u2713 auto-fixed edit: line ${m.line}, distance ${m.distance}${ie.reset}`),`Edited: ${n} (auto-fixed, line ${m.line}, distance ${m.distance}, matched: "${M}")`}let g=Fo(r,e.old_text);if(g){let M=r.split(`
256
+ `),D=Math.max(0,g.line-6),v=Math.min(M.length,g.line+10),E=M.slice(D,v).map((ee,se)=>`${D+se+1}: ${ee}`).join(`
257
+ `),A=`line_start=${Math.max(1,g.line-5)} line_end=${Math.min(M.length,g.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${g.line}, distance ${g.distance})
256
258
 
257
259
  Actual file content around line ${g.line} \u2014 use this to correct old_text:
258
- ${v}
260
+ ${E}
259
261
 
260
- Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${N}`}let _=(e.old_text||"").trim().split(`
261
- `)[0].slice(0,60),k=_?`
262
- Recovery: grep -n "${_.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
263
- Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${n}${k}`}}if(!s.autoConfirm){let u=r.split(i).join(e.new_text),d=await No(n,u);if(fi(n,r,u,{annotations:d}),!await Oo(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let c=r.split(i).join(e.new_text);return await Fe.writeFile(n,c,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||c.startsWith("#!"))&&await Fe.chmod(n,493),hi("edit_file",n,r,c),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=Qe(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await xt(n)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=Qe(c),d=await xt(u);if(u&&d)n=u;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let c=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${c}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],l=async(c,u,d)=>{if(u>r)return;let f;try{f=await Fe.readdir(c,{withFileTypes:!0})}catch{return}f=f.filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules");for(let p of f){if(i&&!p.isDirectory()&&!i.test(p.name))continue;let m=p.isDirectory()?"/":"";a.push(`${d}${p.name}${m}`),p.isDirectory()&&await l(pe.join(c,p.name),u+1,d+" ")}};return await l(n,1,""),a.join(`
264
- `)||"(empty)"}case"search_files":{let n=Qe(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","--null","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await Zn("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),a=[];for(let l=0;l<i.length;l+=2){let c=i[l],u=i[l+1];if(c&&u){let d=u.split(`
265
- `).filter(f=>f.trim());for(let f of d)if(a.push(`${c}:${f}`),a.length>=50)break}if(a.length>=50)break}return a.join(`
266
- `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?Qe(e.path):o,i=e.pattern,a=V=>{let re=V.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${re}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=vs(),f=new d("glob","Finding files...");f.start();let{getFileIndex:p,getIndexedCwd:m,refreshIndex:g,isIndexValid:_}=Cs(),k=p(),A=m();_(r)||(await g(r),k=p());let L=k.filter(V=>l.test(V)||u.test(pe.basename(V))).map(V=>pe.join(r,V));if(L.length===0)return f.stop(),"(no matches)"+zl(e.path);let E=await Promise.all(L.slice(0,210).map(async V=>{try{let re=await Fe.stat(V);return{path:V,mtime:re.mtimeMs}}catch{return{path:V,mtime:0}}}));E.sort((V,re)=>re.mtime-V.mtime);let v=E.map(V=>V.path),N=L.length>200,te=v.slice(0,200).join(`
267
- `);return f.update({count:L.length,detail:e.pattern}),f.stop(),N?`${te}
268
-
269
- \u26A0 Results truncated at 200. Use a more specific pattern.`:te}case"grep":{let n=e.path?Qe(e.path):process.cwd();if(e.staged){let{getDiff:l}=jr(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
270
- `);for(let _ of d)if(_.startsWith("diff --git")){let k=_.match(/diff --git a\/(.+) b\/(.+)/);k&&u.add(k[2])}let f=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&f.push("-i"),e.include&&f.push(`--include=${e.include}`),e.type&&f.push(`--include=*.${e.type}`),e.context?f.push("-C",String(e.context)):(e.before_context&&f.push("-B",String(e.before_context)),e.after_context&&f.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?f.push("-l"):e.output_mode==="count"&&f.push("-c"),f.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:p}=vs(),m=new p("grep","Searching staged content...");m.start();let g=[];for(let _ of u)try{let k=pe.join(process.cwd(),_);if(await xt(k)){let A=[...f];A.push(e.pattern,k);let{stdout:L}=await Zn("grep",A,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let E=L.trim().split(`
271
- `).filter(v=>v.trim());g=g.concat(E)}else{let E=L.split("\0");for(let v=0;v<E.length;v+=2){let N=E[v+1];if(N){let te=N.split(`
272
- `).filter(V=>V.trim());for(let V of te)g.push(`${_}:${V}`)}}}}}catch{}return m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
273
- `).trim()||"(no matches in staged files)"}let o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);let{ToolProgress:i}=vs(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await Zn("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;if(e.output_mode==="files_with_matches"||e.output_mode==="count")c=l.trim().split(`
274
- `).filter(p=>p.trim());else{let p=l.split("\0");c=[];for(let m=0;m<p.length;m+=2){let g=p[m],_=p[m+1];if(g&&_){let k=_.split(`
275
- `).filter(A=>A.trim());for(let A of k)c.push(`${g}:${A}`)}}}let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=c.slice(u,u+d),a.update({count:c.length,detail:`in ${n}`}),a.stop(),c.join(`
276
- `).trim()||"(no matches)"+zl(e.path)}catch(l){if(a.stop(),l.code===2){let c=(l.stderr||l.message||"").toString().trim();return c.includes("No such file or directory")?`ERROR: Directory not found: ${n}`:c.includes("Invalid")||c.includes("Unmatched")||c.includes("unterminated")||c.includes("unclosed")||c.includes("parse error")||c.includes("brackets")||c.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${c.slice(0,200)||"exit code 2"}`}return"(no matches)"+zl(e.path)}}case"patch_file":{await Kl();let n=Qe(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await xt(n)){let k=await mi(e.path);if(k.fixedPath)n=k.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${pe.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${k.message?`
277
- `+k.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await Fe.readFile(n,"utf-8"),{getActiveModelId:a,getActiveProviderName:l}=ot(),c=Mp(a(),l()),u=[],d=!1,f=!1;for(let k=0;k<r.length;k++){let{old_text:A,new_text:L}=r[k];if(i.includes(A))u.push({old_text:A,new_text:L});else if(c==="strict"){let E=Po(i,A);return E?`ERROR: Patch ${k+1} old_text not found in ${n} (strict mode \u2014 exact match required)
278
- Most similar text (line ${E.line}, distance ${E.distance}):
279
- ${E.text}`:`ERROR: Patch ${k+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let E=Op(i,A);if(E)u.push({old_text:E,new_text:L}),d=!0;else{let v=Po(i,A);if(v){let N=Math.max(3,Math.ceil(A.length*.05));if(v.distance<=N)u.push({old_text:v.text,new_text:L}),f=!0;else return`ERROR: Patch ${k+1} old_text not found in ${n}
262
+ Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${A}`}let $=(e.old_text||"").trim().split(`
263
+ `)[0].slice(0,60),k=$?`
264
+ Recovery: grep -n "${$.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
265
+ Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${n}${k}`}}if(!s.autoConfirm){let u=r.split(i).join(e.new_text),d=await Io(n,u);if(_i(n,r,u,{annotations:d}),!await Lo(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let c=r.split(i).join(e.new_text);return await He.writeFile(n,c,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||c.startsWith("#!"))&&await He.chmod(n,493),bi("edit_file",n,r,c),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=st(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Tt(n)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=st(c),d=await Tt(u);if(u&&d)n=u;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let c=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${c}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],l=async(c,u,d)=>{if(u>r)return;let f;try{f=await He.readdir(c,{withFileTypes:!0})}catch{return}f=f.filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules");for(let p of f){if(i&&!p.isDirectory()&&!i.test(p.name))continue;let m=p.isDirectory()?"/":"";a.push(`${d}${p.name}${m}`),p.isDirectory()&&await l(ce.join(c,p.name),u+1,d+" ")}};return await l(n,1,""),a.join(`
266
+ `)||"(empty)"}case"search_files":{let n=st(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await os("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=jo(r).slice(0,50);return(await rc(i,{query:e.pattern,basePath:n})).join(`
267
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?st(e.path):o,i=e.pattern,a=E=>{let A=E.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${A}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=Os(),f=new d("glob","Finding files...");f.start();let p=Vh();Qx(r)||(await Zx(r),p=Vh());let m=p.filter(E=>l.test(E)||u.test(ce.basename(E))).map(E=>ce.join(r,E));if(m.length===0)return f.stop(),"(no matches)"+oc(e.path);let g=await Promise.all(m.slice(0,210).map(async E=>{try{let A=await He.stat(E);return{path:E,mtime:A.mtimeMs}}catch{return{path:E,mtime:0}}})),$=new Map(g.map(E=>[E.path,E.mtime])),k=await rm(i,r),M=im(g.map(E=>E.path),{query:i,basePath:r,definitionScores:k,mtimeByPath:$}),D=m.length>200,v=M.slice(0,200).join(`
268
+ `);return f.update({count:m.length,detail:e.pattern}),f.stop(),D?`${v}
269
+
270
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:v}case"grep":{let n=e.path?st(e.path):process.cwd();if(e.staged){let{getDiff:l}=Yr(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
271
+ `);for(let $ of d)if($.startsWith("diff --git")){let k=$.match(/diff --git a\/(.+) b\/(.+)/);k&&u.add(k[2])}let f=["-rn","-E","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&f.push("-i"),e.include&&f.push(`--include=${e.include}`),e.type&&f.push(`--include=*.${e.type}`),e.context?f.push("-C",String(e.context)):(e.before_context&&f.push("-B",String(e.before_context)),e.after_context&&f.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?f.push("-l"):e.output_mode==="count"&&f.push("-c"),f.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:p}=Os(),m=new p("grep","Searching staged content...");m.start();let g=[];for(let $ of u)try{let k=ce.join(process.cwd(),$);if(await Tt(k)){let M=[...f];M.push(e.pattern,k);let{stdout:D}=await os("grep",M,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let v=jo(D,e.output_mode);g=g.concat(v)}else g=g.concat(jo(D))}}catch{}return g=await rc(g,{query:e.pattern,basePath:process.cwd(),outputMode:e.output_mode}),m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
272
+ `).trim()||"(no matches in staged files)"}let o=["-rn","-E","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);let{ToolProgress:i}=Os(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await os("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;e.output_mode==="files_with_matches"||e.output_mode==="count"?c=jo(l,e.output_mode):c=jo(l);let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=await rc(c,{query:e.pattern,basePath:n,outputMode:e.output_mode}),c=c.slice(u,u+d),a.update({count:c.length,detail:`in ${n}`}),a.stop(),c.join(`
273
+ `).trim()||"(no matches)"+oc(e.path)}catch(l){if(a.stop(),l.code===2){let c=(l.stderr||l.message||"").toString().trim();return c.includes("No such file or directory")?`ERROR: Directory not found: ${n}`:c.includes("Invalid")||c.includes("Unmatched")||c.includes("unterminated")||c.includes("unclosed")||c.includes("parse error")||c.includes("brackets")||c.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${c.slice(0,200)||"exit code 2"}`}return"(no matches)"+oc(e.path)}}case"patch_file":{await ic();let n=st(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Tt(n)){let k=await xi(e.path);if(k.fixedPath)n=k.fixedPath,console.log(`${ie.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ce.relative(process.cwd(),n)}${ie.reset}`);else return`ERROR: File not found: ${e.path}${k.message?`
274
+ `+k.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await He.readFile(n,"utf-8"),{getActiveModelId:a,getActiveProviderName:l}=lt(),c=Qh(a(),l()),u=[],d=!1,f=!1;for(let k=0;k<r.length;k++){let{old_text:M,new_text:D}=r[k];if(i.includes(M))u.push({old_text:M,new_text:D});else if(c==="strict"){let v=Fo(i,M);return v?`ERROR: Patch ${k+1} old_text not found in ${n} (strict mode \u2014 exact match required)
280
275
  Most similar text (line ${v.line}, distance ${v.distance}):
281
- ${v.text}`}else return`ERROR: Patch ${k+1} old_text not found in ${n}`}}}let p=i;for(let{old_text:k,new_text:A}of u)p=p.split(k).join(A);if(!s.autoConfirm){let k=await No(n,p);if(fi(n,i,p,{annotations:k}),!await Oo(d?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await Fe.writeFile(n,p,"utf-8");let m=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||p.startsWith("#!");m&&await Fe.chmod(n,493),hi("patch_file",n,i,p);let g=f?" (auto-fixed)":d?" (fuzzy match)":"",_=m?" [chmod +x applied]":"";return`Patched: ${n} (${r.length} replacements)${g}${_}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let i=new URL(n).hostname;if(/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|localhost$|\[::1?\]|\[fd|fc)/i.test(i))return"ERROR: Fetching private/internal addresses is not allowed.";let a=await Yl.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${n}: ${r.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await Yl.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=o.data?.choices?.[0]?.message?.content||"",i=o.data?.citations||[],a=`[Perplexity grounded search]
276
+ ${v.text}`:`ERROR: Patch ${k+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let v=Xh(i,M);if(v)u.push({old_text:v,new_text:D}),d=!0;else{let E=Fo(i,M);if(E){let A=Math.max(3,Math.ceil(M.length*.05));if(E.distance<=A)u.push({old_text:E.text,new_text:D}),f=!0;else return`ERROR: Patch ${k+1} old_text not found in ${n}
277
+ Most similar text (line ${E.line}, distance ${E.distance}):
278
+ ${E.text}`}else return`ERROR: Patch ${k+1} old_text not found in ${n}`}}}let p=i;for(let{old_text:k,new_text:M}of u)p=p.split(k).join(M);if(!s.autoConfirm){let k=await Io(n,p);if(_i(n,i,p,{annotations:k}),!await Lo(d?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await He.writeFile(n,p,"utf-8");let m=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||p.startsWith("#!");m&&await He.chmod(n,493),bi("patch_file",n,i,p);let g=f?" (auto-fixed)":d?" (fuzzy match)":"",$=m?" [chmod +x applied]":"";return`Patched: ${n} (${r.length} replacements)${g}${$}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let i=new URL(n).hostname;if(/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|localhost$|\[::1?\]|\[fd|fc)/i.test(i))return"ERROR: Fetching private/internal addresses is not allowed.";let a=await nc.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${n}: ${r.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await nc.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=o.data?.choices?.[0]?.message?.content||"",i=o.data?.citations||[],a=`[Perplexity grounded search]
282
279
 
283
280
  ${r}`;return i.length>0&&(a+=`
284
281
 
285
282
  Sources:
286
283
  `+i.slice(0,n).map((l,c)=>`${c+1}. ${l}`).join(`
287
- `)),a}catch(o){console.error(`${ae.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${ae.reset}`)}try{let r=(await Yl.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],a=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=a.exec(r))!==null&&i.length<n;){let c=l[1].replace(/.*uddg=/,"").split("&")[0],u=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(c)})}catch{i.push({title:u,url:c})}}return i.length===0?"(no results)":i.map((c,u)=>`${u+1}. ${c.title}
284
+ `)),a}catch(o){console.error(`${ie.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${ie.reset}`)}try{let r=(await nc.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],a=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=a.exec(r))!==null&&i.length<n;){let c=l[1].replace(/.*uddg=/,"").split("&")[0],u=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(c)})}catch{i.push({title:u,url:c})}}return i.length===0?"(no results)":i.map((c,u)=>`${u+1}. ${c.title}
288
285
  ${c.url}`).join(`
289
286
 
290
- `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=un();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
287
+ `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=yn();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
291
288
 
292
289
  Links:
293
290
  `+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
294
291
  `):"";return`Title: ${o.title}
295
292
  URL: ${o.url}
296
293
 
297
- ${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=un();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
294
+ ${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=yn();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
298
295
  Title: ${o.title}
299
296
  URL: ${o.url}
300
297
 
301
- To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"visual_review":{let{browserScreenshot:n}=un();try{let o=await n(e.url,{width:e.width||1280,height:e.height||800,fullPage:e.full_page||!1}),r=e.focus||"general layout, spacing, typography, colors, and usability",i=`VISUAL REVIEW \u2014 Screenshot captured
298
+ To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"visual_review":{let{browserScreenshot:n}=yn();try{let o=await n(e.url,{width:e.width||1280,height:e.height||800,fullPage:e.full_page||!1}),r=e.focus||"general layout, spacing, typography, colors, and usability",i=`VISUAL REVIEW \u2014 Screenshot captured
302
299
  URL: ${o.url}
303
300
  Title: ${o.title}
304
301
  Screenshot: ${o.path}
@@ -313,12 +310,12 @@ Analyze the screenshot above and provide structured feedback:
313
310
  2. Visual hierarchy (typography, contrast, colors)
314
311
  3. Consistency (margins, padding patterns)
315
312
  4. Responsiveness concerns at this viewport
316
- 5. Specific issues related to: ${r}`;return e.compare_with&&qs.existsSync(e.compare_with)&&(i+=`
313
+ 5. Specific issues related to: ${r}`;return e.compare_with&&Kt.existsSync(e.compare_with)&&(i+=`
317
314
 
318
- COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:o.path,base64:o.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(o){return`ERROR: ${o.message}`}}case"clipboard_image":try{let{_grabClipboardImage:n}=Vl(),o=n();return o?{text:`Clipboard image captured: ${o.path}
315
+ COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:o.path,base64:o.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(o){return`ERROR: ${o.message}`}}case"clipboard_image":try{let{_grabClipboardImage:n}=uc(),o=n();return o?{text:`Clipboard image captured: ${o.path}
319
316
  Size: ${Math.round(Buffer.from(o.data,"base64").length/1024)} KB
320
317
 
321
- [Clipboard image is attached for visual analysis]`,images:[{path:o.path,base64:o.data,media_type:o.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(n){return`ERROR: ${n.message}`}case"browser_click":{let{browserClick:n}=un();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=un();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"visual_diff":try{let{pixelDiff:n}=Wn(),o=n(e.before,e.after,{threshold:e.threshold}),r=o.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
318
+ [Clipboard image is attached for visual analysis]`,images:[{path:o.path,base64:o.data,media_type:o.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(n){return`ERROR: ${n.message}`}case"browser_click":{let{browserClick:n}=yn();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=yn();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"visual_diff":try{let{pixelDiff:n}=Xn(),o=n(e.before,e.after,{threshold:e.threshold}),r=o.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
322
319
  `):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${o.diffPercent}% of pixels changed
323
320
  Changed: ${o.changedPixels.toLocaleString()} / ${o.totalPixels.toLocaleString()} pixels
324
321
  Canvas: ${o.width}\xD7${o.height}
@@ -327,7 +324,7 @@ Diff image: ${o.diffPath}
327
324
  Regional breakdown:
328
325
  ${i}
329
326
 
330
- [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:o.diffPath,base64:qs.readFileSync(o.diffPath).toString("base64"),media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"responsive_sweep":try{let{responsiveSweep:n}=Wn(),o=await n(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=o.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
327
+ [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:o.diffPath,base64:Kt.readFileSync(o.diffPath).toString("base64"),media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"responsive_sweep":try{let{responsiveSweep:n}=Xn(),o=await n(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=o.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
331
328
  `);return{text:`RESPONSIVE SWEEP \u2014 ${o.length} viewports captured
332
329
  URL: ${e.url}
333
330
 
@@ -341,15 +338,15 @@ Analyze these screenshots for:
341
338
  2. Typography scaling (text too small on mobile, too large on desktop)
342
339
  3. Navigation pattern changes across viewports
343
340
  4. Image/media sizing and aspect ratio issues
344
- 5. Touch target sizes on mobile viewports`,images:o.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(n){return`ERROR: ${n.message}`}case"visual_annotate":try{let{annotateImage:n}=Wn(),o=n(e.image,e.annotations),r=e.annotations.length,i=[...new Set(e.annotations.map(a=>a.type))].join(", ");return{text:`ANNOTATED IMAGE \u2014 ${r} annotation(s) added (${i})
341
+ 5. Touch target sizes on mobile viewports`,images:o.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(n){return`ERROR: ${n.message}`}case"visual_annotate":try{let{annotateImage:n}=Xn(),o=n(e.image,e.annotations),r=e.annotations.length,i=[...new Set(e.annotations.map(a=>a.type))].join(", ");return{text:`ANNOTATED IMAGE \u2014 ${r} annotation(s) added (${i})
345
342
  Source: ${e.image}
346
343
  Output: ${o.path}
347
344
 
348
- [Annotated image attached with visual markers]`,images:[{path:o.path,base64:o.base64,media_type:o.media_type}]}}catch(n){return`ERROR: ${n.message}`}case"visual_watch":try{let{visualWatch:n}=Wn(),o=n(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await o.next();if(r.value?.type==="error")return`ERROR: ${r.value.message}`;let i=[];i.push(`VISUAL WATCH \u2014 monitoring ${e.watch.length} path(s)`,`URL: ${e.url}`,`Baseline screenshot: ${r.value?.path}`,"","Watching for file changes... (will capture up to "+(e.max_iterations||10)+" iterations)");let a=await o.next();if(!a.done&&a.value){let l=a.value;i.push("",`--- Iteration ${l.iteration} ---`,`Screenshot: ${l.path}`),l.diff&&i.push(`Diff: ${l.diff.diffPercent}% changed (${l.diff.changedPixels} pixels)`,`Regions: ${l.diff.regions.map(u=>`${u.name}:${u.changedPercent}%`).join(", ")}`);let c=[{path:l.path,base64:l.base64,media_type:l.media_type}];return l.diff?.diffPath&&c.push({path:l.diff.diffPath,base64:qs.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
345
+ [Annotated image attached with visual markers]`,images:[{path:o.path,base64:o.base64,media_type:o.media_type}]}}catch(n){return`ERROR: ${n.message}`}case"visual_watch":try{let{visualWatch:n}=Xn(),o=n(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await o.next();if(r.value?.type==="error")return`ERROR: ${r.value.message}`;let i=[];i.push(`VISUAL WATCH \u2014 monitoring ${e.watch.length} path(s)`,`URL: ${e.url}`,`Baseline screenshot: ${r.value?.path}`,"","Watching for file changes... (will capture up to "+(e.max_iterations||10)+" iterations)");let a=await o.next();if(!a.done&&a.value){let l=a.value;i.push("",`--- Iteration ${l.iteration} ---`,`Screenshot: ${l.path}`),l.diff&&i.push(`Diff: ${l.diff.diffPercent}% changed (${l.diff.changedPixels} pixels)`,`Regions: ${l.diff.regions.map(u=>`${u.name}:${u.changedPercent}%`).join(", ")}`);let c=[{path:l.path,base64:l.base64,media_type:l.media_type}];return l.diff?.diffPath&&c.push({path:l.diff.diffPath,base64:Kt.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
349
346
  `),images:c}}return{text:i.join(`
350
347
  `)+`
351
348
 
352
- No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(n){return`ERROR: ${n.message}`}case"design_tokens":try{let{extractDesignTokens:n}=Wn(),o=n(e.image,{sampleRate:e.sample_rate}),r=o.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
349
+ No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(n){return`ERROR: ${n.message}`}case"design_tokens":try{let{extractDesignTokens:n}=Xn(),o=n(e.image,{sampleRate:e.sample_rate}),r=o.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
353
350
  `),i=o.spacing.length?o.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
354
351
  `):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${o.dimensions.width}\xD7${o.dimensions.height} image
355
352
  Source: ${o.imagePath}
@@ -363,7 +360,7 @@ ${i}
363
360
  Use these values to:
364
361
  - Compare against CSS variables / design system tokens
365
362
  - Identify inconsistent colors or spacing
366
- - Generate a color palette from the rendered output`}catch(n){return`ERROR: ${n.message}`}case"design_compare":try{let{designCompare:n}=Wn(),o=await n(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=o.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
363
+ - Generate a color palette from the rendered output`}catch(n){return`ERROR: ${n.message}`}case"design_compare":try{let{designCompare:n}=Xn(),o=await n(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=o.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
367
364
  `)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${o.diffPercent}% deviation from reference
368
365
  Reference: ${o.referencePath}
369
366
  Live: ${o.livePath}
@@ -375,89 +372,89 @@ Pixel deviation: ${o.changedPixels.toLocaleString()} / ${o.totalPixels.toLocaleS
375
372
  Regional breakdown:
376
373
  ${r}
377
374
 
378
- [Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:o.livePath,base64:o.liveBase64,media_type:"image/png"},{path:o.diffPath,base64:o.diffBase64,media_type:"image/png"},{path:o.annotatedPath,base64:o.annotatedBase64,media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"ask_user":{let{question:n,options:o=[]}=e;return Xl?new Promise(r=>{Qn=()=>r("CANCELLED"),Xl(n,o).then(i=>{Qn=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});Qn=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
375
+ [Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:o.livePath,base64:o.liveBase64,media_type:"image/png"},{path:o.diffPath,base64:o.diffBase64,media_type:"image/png"},{path:o.annotatedPath,base64:o.annotatedBase64,media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"ask_user":{let{question:n,options:o=[]}=e;return cc?new Promise(r=>{rs=()=>r("CANCELLED"),cc(n,o).then(i=>{rs=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});rs=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
379
376
  ${o.map((l,c)=>` ${c+1}. ${l}`).join(`
380
377
  `)}
381
378
  `:"";console.log(`
382
- ${ae.cyan}${ae.bold} ? ${n}${ae.reset}${a}`),i.question(`${ae.cyan} > ${ae.reset}`,l=>{Qn=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Gl())return"ERROR: Not a git repository";let n=await Ap()||"(detached)",o=await yx();if(o.length===0)return`Branch: ${n}
379
+ ${ie.cyan}${ie.bold} ? ${n}${ie.reset}${a}`),i.question(`${ie.cyan} > ${ie.reset}`,l=>{rs=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await sc())return"ERROR: Not a git repository";let n=await Kh()||"(detached)",o=await Kx();if(o.length===0)return`Branch: ${n}
383
380
  Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let i of o){let a=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${a}: ${i.file}`)}return r.join(`
384
- `)}case"git_diff":{if(!await Gl())return"ERROR: Not a git repository";let n;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{n=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await wx(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Gl())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=Cl(),{getActiveTaskProgress:l}=Je(),c=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let u=n(e.name,e.tasks);return c||console.log(`
381
+ `)}case"git_diff":{if(!await sc())return"ERROR: Not a git repository";let n;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{n=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await Xx(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await sc())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=Fl(),{getActiveTaskProgress:l}=tt(),c=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let u=n(e.name,e.tasks);return c||console.log(`
385
382
  `+i()),`Created task list "${e.name}" with ${u.length} tasks:
386
383
  `+u.map(d=>` ${d.id}: ${d.description}`).join(`
387
384
  `)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(c||console.log(`
388
385
  `+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let u=r();return u.tasks.length===0?"No active tasks":(c||console.log(`
389
- `+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n,executeSpawnAgentsBackground:o}=gi();return e.agents?.some(r=>r.background)?o(e):n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=ot();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await Zn("gh",o,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let c=l.conclusion||l.status||"unknown",u=c==="success"?"\u2713":c==="failure"?"\u2717":c==="in_progress"?"\u283F":"\u25CB",d=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${c} \xB7 ${d}`}).join(`
386
+ `+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n,executeSpawnAgentsBackground:o}=Si();return e.agents?.some(r=>r.background)?o(e):n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=lt();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await os("gh",o,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let c=l.conclusion||l.status||"unknown",u=c==="success"?"\u2713":c==="failure"?"\u2717":c==="in_progress"?"\u283F":"\u25CB",d=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${c} \xB7 ${d}`}).join(`
390
387
  `)}catch(r){let i=(r.stderr||r.message||"").toString();return i.includes("not found")||i.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${i.split(`
391
- `)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";if(!/^\d+$/.test(String(e.run_id)))return"ERROR: run_id must be numeric";try{if(e.log){let{stdout:i}=await Zn("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
392
- ...(truncated)`:"")}let{stdout:n}=await Zn("gh",["run","view",String(e.run_id),"--json","status,conclusion,name,headBranch,createdAt,updatedAt,jobs"],{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of o.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let c=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${c} ${l.name}`)}}return r.join(`
388
+ `)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";if(!/^\d+$/.test(String(e.run_id)))return"ERROR: run_id must be numeric";try{if(e.log){let{stdout:i}=await os("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
389
+ ...(truncated)`:"")}let{stdout:n}=await os("gh",["run","view",String(e.run_id),"--json","status,conclusion,name,headBranch,createdAt,updatedAt,jobs"],{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of o.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let c=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${c} ${l.name}`)}}return r.join(`
393
390
  `)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
394
- `)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";if(!/^[\w./-]+$/.test(e.workflow))return"ERROR: invalid workflow name";let{confirm:n}=lo(),o=e.branch||await Ap()||"main";if(!/^[\w./-]+$/.test(o))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",o];if(e.inputs)for(let[a,l]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${l}`)}if(console.log(`
395
- ${ae.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${ae.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Zn("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
396
- `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=Mo(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await De(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
397
- `)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Mo(r,e);try{let{stdout:a,stderr:l}=await De(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
391
+ `)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";if(!/^[\w./-]+$/.test(e.workflow))return"ERROR: invalid workflow name";let{confirm:n}=fo(),o=e.branch||await Kh()||"main";if(!/^[\w./-]+$/.test(o))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",o];if(e.inputs)for(let[a,l]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${l}`)}if(console.log(`
392
+ ${ie.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${ie.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await os("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
393
+ `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=qo(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await Fe(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
394
+ `)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=qo(r,e);try{let{stdout:a,stderr:l}=await Fe(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
398
395
  ...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
399
396
  `)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let n=e.namespace||"default";if(console.log(`
400
- ${ae.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${ae.reset}`),console.log(`${ae.dim} Command: ${e.command}${ae.reset}`),!await Wt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Mo(r,e);try{let{stdout:a,stderr:l}=await De(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
397
+ ${ie.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${ie.reset}`),console.log(`${ie.dim} Command: ${e.command}${ie.reset}`),!await zt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=qo(r,e);try{let{stdout:a,stderr:l}=await Fe(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
401
398
  `)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let i=e.file;if(console.log(`
402
- ${ae.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ae.reset}`),!await Wt(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),n&&(o+=" --dry-run=client");let r=Mo(o,e);try{let{stdout:i,stderr:a}=await De(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
399
+ ${ie.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ie.reset}`),!await zt(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),n&&(o+=" --dry-run=client");let r=qo(o,e);try{let{stdout:i,stderr:a}=await Fe(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
403
400
  `)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let n=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let a=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
404
- ${ae.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${n})${ae.reset}`),!await Wt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=Mo(r,e);try{let{stdout:a,stderr:l}=await De(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
405
- `)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=Bl(),{name:r,content:i,mode:a}=e;if(a==="create"&&o(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let l=o(r),c=l.content?l.content+`
401
+ ${ie.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${n})${ie.reset}`),!await zt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=qo(r,e);try{let{stdout:a,stderr:l}=await Fe(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
402
+ `)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=Zl(),{name:r,content:i,mode:a}=e;if(a==="create"&&o(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let l=o(r),c=l.content?l.content+`
406
403
 
407
- `+i:i;return n(r,c),`Appended to brain document: ${r}.md`}return n(r,i),`${a==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=Mt(e.server)}catch(N){return`ERROR: ${N.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=dx(o);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(o)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
404
+ `+i:i;return n(r,c),`Appended to brain document: ${r}.md`}return n(r,i),`${a==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=jt(e.server)}catch(A){return`ERROR: ${A.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=Ux(o);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(o)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
408
405
  grep -n "pattern" /path/to/file -A 50
409
406
  or to read the whole file:
410
407
  cat /path/to/file
411
408
  NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
412
- HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(o=o.replace(/(-[BAC])\s*(\d+)/g,(N,te,V)=>{let re=Math.min(Number(V),20);return`${te} ${re}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(N,te,V)=>te+Math.min(Number(V),20)),/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(o)){let N=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
413
- ${ae.yellow} \u26A0 Remote command on ${N}: ${o}${ae.reset}`),!await Wt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(n,o,{timeout:i,sudo:r}),p=[c,u].filter(Boolean).join(`
414
- `).trim();if(d!==0){if(/no such file or directory/i.test(p)){let te=p.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),V=o.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),re=te&&te[1]||V&&V[1];if(re)try{let{remoteAutoFixPath:le}=As(),ne=re.startsWith("/")?re.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(n.user||"root"),S=await le(n,ne,re);if(S.fixedPath){let Ee=o.replace(re,S.fixedPath);console.log(`${ae.dim} \u2713 remote auto-fix: ${re} \u2192 ${S.fixedPath}${ae.reset}`);let W=await ht(n,Ee,{timeout:i,sudo:r}),J=[W.stdout,W.stderr].filter(Boolean).join(`
409
+ HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(o=o.replace(/(-[BAC])\s*(\d+)/g,(A,ee,se)=>{let ue=Math.min(Number(se),20);return`${ee} ${ue}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(A,ee,se)=>ee+Math.min(Number(se),20)),/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(o)){let A=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
410
+ ${ie.yellow} \u26A0 Remote command on ${A}: ${o}${ie.reset}`),!await zt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await gt(n,o,{timeout:i,sudo:r}),p=[c,u].filter(Boolean).join(`
411
+ `).trim();if(d!==0){if(/no such file or directory/i.test(p)){let ee=p.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),se=o.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),ue=ee&&ee[1]||se&&se[1];if(ue)try{let{remoteAutoFixPath:ae}=Ps(),te=ue.startsWith("/")?ue.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(n.user||"root"),S=await ae(n,te,ue);if(S.fixedPath){let ve=o.replace(ue,S.fixedPath);console.log(`${ie.dim} \u2713 remote auto-fix: ${ue} \u2192 ${S.fixedPath}${ie.reset}`);let W=await gt(n,ve,{timeout:i,sudo:r}),z=[W.stdout,W.stderr].filter(Boolean).join(`
415
412
  `).trim();if(W.exitCode===0)return`${S.message}
416
- ${J}`||"(command completed, no output)"}else if(S.message)return`EXIT ${d}
413
+ ${z}`||"(command completed, no output)"}else if(S.message)return`EXIT ${d}
417
414
  ${f||p}
418
415
 
419
416
  ${S.message}`}catch{}}return`EXIT ${d}
420
417
  ${f||p||"(no output)"}`}let m=/\bgrep\b/.test(o),g=p;m&&(g=g.split(`
421
- `).filter(N=>N!=="--").join(`
422
- `));let _=m?60:100,k=g.split(`
423
- `);k.length>_&&(g=`(${k.length-_} earlier lines omitted \u2014 showing last ${_})
424
- `+k.slice(-_).join(`
425
- `));let A=4,L=g.split(`
426
- `),E=[],v=0;for(;v<L.length;){let N=v+1;for(;N<L.length&&L[N]===L[v];)N++;let te=N-v;if(E.push(L[v]),te>A)E.push(`... (${te-1} identical lines omitted)`);else for(let V=1;V<te;V++)E.push(L[v]);v=N}return E.join(`
427
- `)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=Mt(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
428
- ${ae.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${ae.reset}`),!await Wt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await $x(n,e.local_path,e.remote_path);try{As().clearRemoteIndex()}catch{}return i}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=Mt(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await Np(n,e.remote_path,e.local_path)}catch(o){if(/no such file|not found/i.test(o.message))try{let{remoteAutoFixPath:r}=As(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(n,i,e.remote_path);if(a.fixedPath){console.log(`${ae.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${ae.reset}`);let l=await Np(n,a.fixedPath,e.local_path);return`${a.message}
418
+ `).filter(A=>A!=="--").join(`
419
+ `));let $=m?60:100,k=g.split(`
420
+ `);k.length>$&&(g=`(${k.length-$} earlier lines omitted \u2014 showing last ${$})
421
+ `+k.slice(-$).join(`
422
+ `));let M=4,D=g.split(`
423
+ `),v=[],E=0;for(;E<D.length;){let A=E+1;for(;A<D.length&&D[A]===D[E];)A++;let ee=A-E;if(v.push(D[E]),ee>M)v.push(`... (${ee-1} identical lines omitted)`);else for(let se=1;se<ee;se++)v.push(D[E]);E=A}return v.join(`
424
+ `)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=jt(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
425
+ ${ie.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${ie.reset}`),!await zt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await eS(n,e.local_path,e.remote_path);try{Ps().clearRemoteIndex()}catch{}return i}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=jt(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await Zh(n,e.remote_path,e.local_path)}catch(o){if(/no such file|not found/i.test(o.message))try{let{remoteAutoFixPath:r}=Ps(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(n,i,e.remote_path);if(a.fixedPath){console.log(`${ie.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${ie.reset}`);let l=await Zh(n,a.fixedPath,e.local_path);return`${a.message}
429
426
  ${l}`}if(a.message)return`ERROR: ${o.message}
430
427
 
431
- ${a.message}`}catch{}return`ERROR: ${o.message}`}}case"remote_agent":{let n=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(n,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],a=(e.project_path||o?.home||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),l=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),u=['TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt) && chmod 600 "$TMPFILE"',`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=accept-new","-o","ConnectTimeout=10",r,`bash -c '${u}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let p=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
432
- ${p.slice(-2e3)}`:p.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!o)try{i=Mt(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=o?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
433
- ${ae.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${ae.reset}`),!await Wt(" Execute?"))return"CANCELLED: User declined service action."}let a=`systemctl ${e.action} ${e.service}`;if(o){let c=e.action!=="status"?`sudo ${a}`:a;try{let{stdout:u,stderr:d}=await De(c,{timeout:15e3});return(u||d||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(u){let d=(u.stderr||u.message||"").toString().trim();return/not found|loaded.*not-found/i.test(d)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${u.code||1}
434
- ${d}`}}else{let{stdout:l,stderr:c,exitCode:u,error:d}=await ht(i,a,{timeout:15e3,sudo:!0}),f=[l,c].filter(Boolean).join(`
435
- `).trim();return u!==0?/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${u}
436
- ${d||f||"(no output)"}`:f||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",a=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:m,stderr:g}=await De(a,{timeout:15e3});return(m||g||"(no log output)").trim()}catch(m){return`EXIT ${m.code||1}
437
- ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Mt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(l,a,{timeout:2e4}),p=[c,u].filter(Boolean).join(`
438
- `).trim();return d!==0?`EXIT ${d}
439
- ${f||p||"(no output)"}`:p||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:f,stderr:p}=await De(r,{timeout:1e4});return(f||p||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
440
- ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=Mt(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await ht(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
428
+ ${a.message}`}catch{}return`ERROR: ${o.message}`}}case"remote_agent":{let n=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(n,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],a=(e.project_path||o?.home||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),l=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),u=['TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt) && chmod 600 "$TMPFILE"',`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",r,`bash -c '${u}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let p=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
429
+ ${p.slice(-2e3)}`:p.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=lc(e.service);if(n)return n;let o=["status","start","stop","restart","reload","enable","disable"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let r=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",a=null;if(!r)try{a=jt(e.server)}catch(u){return`ERROR: ${u.message}`}if(!i){let u=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
430
+ ${ie.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${u}${ie.reset}`),!await zt(" Execute?"))return"CANCELLED: User declined service action."}let l=e.service.includes(".")?e.service:`${e.service}.service`,c=`systemctl ${e.action} ${xe(l)}`;if(r){let d=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:f,stderr:p}=await Fe(d,{timeout:15e3});return(f||p||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(f){let p=(f.stderr||f.message||"").toString().trim();return/not found|loaded.*not-found/i.test(p)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${f.code||1}
431
+ ${p}`}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await gt(a,c,{timeout:15e3,sudo:!0}),m=[u,d].filter(Boolean).join(`
432
+ `).trim();return f!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${a.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${f}
433
+ ${p||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=lc(e.service);if(n)return n;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.lines||50,i=e.service.includes(".")?e.service:`${e.service}.service`,a=e.since?`--since ${xe(e.since)}`:"",l=e.follow?"-f":"",c=`journalctl -u ${xe(i)} -n ${r} ${a} ${l} --no-pager`.trim().replace(/\s+/g," ");if(o)try{let{stdout:$,stderr:k}=await Fe(c,{timeout:15e3});return($||k||"(no log output)").trim()}catch($){return`EXIT ${$.code||1}
434
+ ${($.stderr||$.message||"").toString().trim()}`}let u;try{u=jt(e.server)}catch($){return`ERROR: ${$.message}`}let{stdout:d,stderr:f,exitCode:p,error:m}=await gt(u,c,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
435
+ `).trim();return p!==0?`EXIT ${p}
436
+ ${m||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:f,stderr:p}=await Fe(r,{timeout:1e4});return(f||p||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
437
+ ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=jt(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await gt(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
441
438
  `).trim();return c!==0?`EXIT ${c}
442
- ${u||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:m}=await De(i,{timeout:15e3});return(p||m||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
443
- ${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=Mt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await ht(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
439
+ ${u||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:m}=await Fe(i,{timeout:15e3});return(p||m||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
440
+ ${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=jt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await gt(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
444
441
  `).trim();return u!==0?`EXIT ${u}
445
442
  ${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let m=n?"local":e.server;if(console.log(`
446
- ${ae.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${ae.reset}`),!await Wt(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let a=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:m,stderr:g}=await De(a,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
447
- ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Mt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
443
+ ${ie.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${ie.reset}`),!await zt(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let a=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:m,stderr:g}=await Fe(a,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
444
+ ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=jt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await gt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
448
445
  `).trim();return d!==0?`EXIT ${d}
449
446
  ${f||p}`:p||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let m=o?"local":e.server;if(console.log(`
450
- ${ae.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${ae.reset}`),!await Wt(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(o)try{let{stdout:m,stderr:g}=await De(a,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
451
- ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Mt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
447
+ ${ie.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${ie.reset}`),!await zt(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(o)try{let{stdout:m,stderr:g}=await Fe(a,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
448
+ ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=jt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await gt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
452
449
  `).trim();return d!==0?`EXIT ${d}
453
- ${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...bx(e.config),...e},delete e.config,delete e._name}catch(u){return`ERROR: ${u.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let n=e.method||"rsync";if(n==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let o;try{o=Mt(e.server)}catch(u){return`ERROR: ${u.message}`}let r=o.user?`${o.user}@${o.host}`:o.host;if(!e.dry_run&&!s.autoConfirm){if(n==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
454
- ${ae.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${ae.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
455
- ${ae.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ae.reset}`)}if(e.deploy_script&&console.log(`${ae.yellow} Then run: ${e.deploy_script}${ae.reset}`),e.health_check&&console.log(`${ae.yellow} Health check: ${e.health_check}${ae.reset}`),!await Wt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(n==="git"){let u=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&u!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=u?`cd '${d}' && git fetch origin && git checkout '${u}' && git pull origin '${u}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
450
+ ${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...tS(e.config),...e},delete e.config,delete e._name}catch(u){return`ERROR: ${u.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let n=e.method||"rsync";if(n==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let o;try{o=jt(e.server)}catch(u){return`ERROR: ${u.message}`}let r=o.user?`${o.user}@${o.host}`:o.host;if(!e.dry_run&&!s.autoConfirm){if(n==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
451
+ ${ie.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${ie.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
452
+ ${ie.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ie.reset}`)}if(e.deploy_script&&console.log(`${ie.yellow} Then run: ${e.deploy_script}${ie.reset}`),e.health_check&&console.log(`${ie.yellow} Health check: ${e.health_check}${ie.reset}`),!await zt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(n==="git"){let u=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&u!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=u?`cd '${d}' && git fetch origin && git checkout '${u}' && git pull origin '${u}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
456
453
  ${f}${e.deploy_script?`
457
- ${e.deploy_script}`:""}`;let{stdout:p,stderr:m,exitCode:g,error:_}=await ht(o,f,{timeout:12e4});if(i=[p,m].filter(Boolean).join(`
454
+ ${e.deploy_script}`:""}`;let{stdout:p,stderr:m,exitCode:g,error:$}=await gt(o,f,{timeout:12e4});if(i=[p,m].filter(Boolean).join(`
458
455
  `).trim(),g!==0)return`ERROR (git pull, exit ${g}):
459
- ${_||i}`}else{let u=o.key?`-e "ssh -i ${o.key.replace(/^~/,require("os").homedir())}${o.port&&Number(o.port)!==22?` -p ${o.port}`:""}"`:o.port&&Number(o.port)!==22?`-e "ssh -p ${o.port}"`:"",d=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),f=e.dry_run?"--dry-run":"",p=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,m=`rsync -avz --delete ${f} ${d} ${u} ${p} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:_}=await De(m,{timeout:12e4});i=(g||_||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
460
- ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await ht(o,e.deploy_script,{timeout:12e4}),m=[u,d].filter(Boolean).join(`
456
+ ${$||i}`}else{let u=o.key?`-e "ssh -i ${o.key.replace(/^~/,require("os").homedir())}${o.port&&Number(o.port)!==22?` -p ${o.port}`:""}"`:o.port&&Number(o.port)!==22?`-e "ssh -p ${o.port}"`:"",d=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),f=e.dry_run?"--dry-run":"",p=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,m=`rsync -avz --delete ${f} ${d} ${u} ${p} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:$}=await Fe(m,{timeout:12e4});i=(g||$||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
457
+ ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await gt(o,e.deploy_script,{timeout:12e4}),m=[u,d].filter(Boolean).join(`
461
458
  `).trim();if(f!==0)return`${n==="git"?"git pull":"rsync"} OK
462
459
 
463
460
  ERROR (deploy_script, exit ${f}):
@@ -470,67 +467,69 @@ Health check: \u2713 ${u} \u2192 ${p.status}`;else return l=`
470
467
 
471
468
  Health check FAILED: ${u} \u2192 HTTP ${p.status}`,(n==="git"?"git pull OK":"rsync OK")+i+a+l}catch(f){return l=`
472
469
 
473
- Health check FAILED: ${u} \u2192 ${f.message}`,(n==="git"?"git pull OK":"rsync OK")+i+a+l}else{let{stdout:f,stderr:p,exitCode:m}=await ht(o,u,{timeout:15e3}),g=[f,p].filter(Boolean).join(`
470
+ Health check FAILED: ${u} \u2192 ${f.message}`,(n==="git"?"git pull OK":"rsync OK")+i+a+l}else{let{stdout:f,stderr:p,exitCode:m}=await gt(o,u,{timeout:15e3}),g=[f,p].filter(Boolean).join(`
474
471
  `).trim();if(m!==0)return l=`
475
472
 
476
473
  Health check FAILED (exit ${m}): ${g}`,(n==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
477
474
 
478
475
  Health check: \u2713 ${g||"(exit 0)"}`}}let c=n==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${n}] ${c}
479
- ${i}${a}${l}`.trim()}case"deployment_status":{let n=kx(),o=e.config?[e.config]:Object.keys(n);if(o.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of o){let a=n[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let l=Mt(a.server||i),u=(await ht(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await ht(l,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let m=require("node-fetch"),g=await Promise.race([m(p),new Promise((_,k)=>setTimeout(()=>k(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(m){f=`unhealthy: ${m.message.substring(0,50)}`}else try{f=(await ht(l,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
476
+ ${i}${a}${l}`.trim()}case"deployment_status":{let n=nS(),o=e.config?[e.config]:Object.keys(n);if(o.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of o){let a=n[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let l=jt(a.server||i),u=(await gt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await gt(l,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let m=require("node-fetch"),g=await Promise.race([m(p),new Promise(($,k)=>setTimeout(()=>k(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(m){f=`unhealthy: ${m.message.substring(0,50)}`}else try{f=(await gt(l,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
480
477
  ${r.join(`
481
- `)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(E,v=120)=>{try{let N=pe.isAbsolute(E)?E:pe.join(n,E),V=(await Fe.readFile(N,"utf8")).split(`
482
- `),re=V.slice(0,v).join(`
483
- `);return V.length>v?re+`
484
- ... (${V.length-v} more lines \u2014 use read_file for full content)`:re}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(E=>`-not -path "*/${E}/*"`).join(" "),c=async E=>{try{let{stdout:v}=await De(`find "${n}" -type f -name "${E}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return v.trim().split(`
485
- `).filter(Boolean)}catch{return[]}},u=async(E,v)=>{try{let{stdout:N}=await De(`grep -rl "${E}" "${n}" --include="${v}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return N.trim().split(`
478
+ `)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(v,E=120)=>{try{let A=ce.isAbsolute(v)?v:ce.join(n,v),se=(await He.readFile(A,"utf8")).split(`
479
+ `),ue=se.slice(0,E).join(`
480
+ `);return se.length>E?ue+`
481
+ ... (${se.length-E} more lines \u2014 use read_file for full content)`:ue}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(v=>`-not -path "*/${v}/*"`).join(" "),c=async v=>{try{let{stdout:E}=await Fe(`find "${n}" -type f -name "${v}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return E.trim().split(`
482
+ `).filter(Boolean)}catch{return[]}},u=async(v,E)=>{try{let{stdout:A}=await Fe(`grep -rl "${v}" "${n}" --include="${E}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return A.trim().split(`
486
483
  `).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
487
- `);let d=[...await c("tailwind.config.js"),...await c("tailwind.config.ts"),...await c("tailwind.config.mjs")];if(d.length>0){let E=await i(d[0],80);E&&r.push(`### Tailwind config (${pe.relative(n,d[0])})
484
+ `);let d=[...await c("tailwind.config.js"),...await c("tailwind.config.ts"),...await c("tailwind.config.mjs")];if(d.length>0){let v=await i(d[0],80);v&&r.push(`### Tailwind config (${ce.relative(n,d[0])})
488
485
  \`\`\`js
489
- ${E}
490
- \`\`\``)}else r.push("(no tailwind.config found)");let f=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],p=!1;for(let E of f){let v=await c(E);for(let N of v){let te=await i(N,100);if(te&&te.includes(":root")){r.push(`### CSS Variables (${pe.relative(n,N)})
486
+ ${v}
487
+ \`\`\``)}else r.push("(no tailwind.config found)");let f=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],p=!1;for(let v of f){let E=await c(v);for(let A of E){let ee=await i(A,100);if(ee&&ee.includes(":root")){r.push(`### CSS Variables (${ce.relative(n,A)})
491
488
  \`\`\`css
492
- ${te}
493
- \`\`\``),p=!0;break}}if(p)break}if(!p){let E=await u(":root","*.css");if(E.length>0){let v=await i(E[0],100);v&&r.push(`### CSS Variables (${pe.relative(n,E[0])})
489
+ ${ee}
490
+ \`\`\``),p=!0;break}}if(p)break}if(!p){let v=await u(":root","*.css");if(v.length>0){let E=await i(v[0],100);E&&r.push(`### CSS Variables (${ce.relative(n,v[0])})
494
491
  \`\`\`css
495
- ${v}
492
+ ${E}
496
493
  \`\`\``),p=!0}}p||r.push("(no CSS custom properties / :root found)"),r.push(`
497
494
  ## STEP 2: Main Layout / Index Page
498
- `);let m=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let E of m){let v=await c(E);if(v.length>0){let N=await i(v[0],150);if(N){r.push(`### Main layout: ${pe.relative(n,v[0])}
495
+ `);let m=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let v of m){let E=await c(v);if(E.length>0){let A=await i(E[0],150);if(A){r.push(`### Main layout: ${ce.relative(n,E[0])}
499
496
  \`\`\`html
500
- ${N}
497
+ ${A}
501
498
  \`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
502
499
  ## STEP 3: Reference Component (same type)
503
- `);let _=[];if(o){for(let E of["*.html","*.vue","*.jsx","*.tsx"])if(_=await u(o,E),_.length>0)break}if(_.length===0)try{let{stdout:E}=await De(`find "${n}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});_=E.trim().split(`
504
- `).filter(Boolean)}catch{_=[]}if(_.length>0){let E=_[0],v=await i(E,150);v?r.push(`### Reference: ${pe.relative(n,E)}
500
+ `);let $=[];if(o){for(let v of["*.html","*.vue","*.jsx","*.tsx"])if($=await u(o,v),$.length>0)break}if($.length===0)try{let{stdout:v}=await Fe(`find "${n}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});$=v.trim().split(`
501
+ `).filter(Boolean)}catch{$=[]}if($.length>0){let v=$[0],E=await i(v,150);E?r.push(`### Reference: ${ce.relative(n,v)}
505
502
  \`\`\`html
506
- ${v}
503
+ ${E}
507
504
  \`\`\``):r.push("(reference file found but could not be read)")}else r.push("(no reference component found \u2014 check manually with glob or list_directory)");r.push(`
508
505
  ## STEP 4: Framework Stack
509
- `);let k=[],A=await i(pe.join(n,"package.json"),999);if(A){if((A.includes('"react"')||A.includes("'react'"))&&k.push("React"),A.includes('"vue"')||A.includes("'vue'")){let v=A.match(/"vue":\s*"[\^~]?(\d+)/);k.push(v?`Vue.js v${v[1]}`:"Vue.js")}let E=A.match(/"alpinejs":\s*"[\^~]?(\d+)/);E&&k.push(`Alpine.js v${E[1]} (\u26A0 v2 vs v3 API differs!)`),(A.includes('"htmx')||A.includes("'htmx"))&&k.push("HTMX"),A.includes('"tailwindcss"')&&k.push("Tailwind CSS"),A.includes('"bootstrap"')&&k.push("Bootstrap")}if((await xt(pe.join(n,"manage.py"))||(await i(pe.join(n,"requirements.txt"),50)||"").includes("Django"))&&k.push("Django (server-rendered templates)"),!k.some(E=>E.includes("Alpine"))){let E=await u("alpinejs","*.html");if(E.length>0){let N=(await i(E[0],30)||"").match(/alpinejs[@/]v?(\d)/);k.push(N?`Alpine.js v${N[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return k.some(E=>E.includes("HTMX"))||(await u("htmx","*.html")).length>0&&k.push("HTMX (via CDN)"),k.length>0?(r.push(k.map(E=>`- ${E}`).join(`
506
+ `);let k=[],M=await i(ce.join(n,"package.json"),999);if(M){if((M.includes('"react"')||M.includes("'react'"))&&k.push("React"),M.includes('"vue"')||M.includes("'vue'")){let E=M.match(/"vue":\s*"[\^~]?(\d+)/);k.push(E?`Vue.js v${E[1]}`:"Vue.js")}let v=M.match(/"alpinejs":\s*"[\^~]?(\d+)/);v&&k.push(`Alpine.js v${v[1]} (\u26A0 v2 vs v3 API differs!)`),(M.includes('"htmx')||M.includes("'htmx"))&&k.push("HTMX"),M.includes('"tailwindcss"')&&k.push("Tailwind CSS"),M.includes('"bootstrap"')&&k.push("Bootstrap")}if((await Tt(ce.join(n,"manage.py"))||(await i(ce.join(n,"requirements.txt"),50)||"").includes("Django"))&&k.push("Django (server-rendered templates)"),!k.some(v=>v.includes("Alpine"))){let v=await u("alpinejs","*.html");if(v.length>0){let A=(await i(v[0],30)||"").match(/alpinejs[@/]v?(\d)/);k.push(A?`Alpine.js v${A[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return k.some(v=>v.includes("HTMX"))||(await u("htmx","*.html")).length>0&&k.push("HTMX (via CDN)"),k.length>0?(r.push(k.map(v=>`- ${v}`).join(`
510
507
  `)),r.push(`
511
508
  \u26A0 Use ONLY the frameworks listed above. Do NOT mix (e.g. no fetch() when HTMX is used for the same action).`)):r.push("(framework not detected \u2014 check package.json or script tags manually)"),r.push(`
512
509
  ---
513
510
  \u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
514
- `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let n=!e.server||e.server==="local"||e.server==="localhost",o;if(!n)try{o=Mt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(n)try{let{stdout:u,stderr:d}=await De(l,{timeout:c});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await ht(o,l,{timeout:c}),m=[u,d].filter(Boolean).join(`
511
+ `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let n=!e.server||e.server==="local"||e.server==="localhost",o;if(!n)try{o=jt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(n)try{let{stdout:u,stderr:d}=await Fe(l,{timeout:c});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await gt(o,l,{timeout:c}),m=[u,d].filter(Boolean).join(`
515
512
  `).trim();return{out:p&&f!==0&&!u.trim()?(p+`
516
- `+m).trim():m,exitCode:f}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!s.autoConfirm){let l=n?"local":e.server;if(!await Wt(`sysadmin [${e.action}] on ${l} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let l=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:c,exitCode:u}=await r(l,45e3);return c||`EXIT ${u}
517
- (no output)`}case"disk_usage":{let l=e.path||"/",c=`df -h ${l}; echo '--- Top subdirs ---'; du -d1 -x -h ${l} 2>/dev/null | sort -rh | head -20`,{out:u,exitCode:d}=await r(c,3e4);return d!==0?`EXIT ${d}
518
- ${u}`:u}case"process_list":{let l=e.sort_by==="mem"?"4":"3",c=(e.limit||20)+1,u=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${c} || ps aux | awk 'NR==1{print; next} {print | "sort -k${l} -rn"}' | head -${c}`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
513
+ `+m).trim():m,exitCode:f}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!s.autoConfirm){let l=n?"local":e.server;if(!await zt(`sysadmin [${e.action}] on ${l} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let l=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:c,exitCode:u}=await r(l,45e3);return c||`EXIT ${u}
514
+ (no output)`}case"disk_usage":{let l=e.path||"/",c=xe(l),u=`df -h ${c}; echo '--- Top subdirs ---'; du -d1 -x -h ${c} 2>/dev/null | sort -rh | head -20`,{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
515
+ ${d}`:d}case"process_list":{let l=e.sort_by==="mem"?"4":"3",c=(e.limit||20)+1,u=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${c} || ps aux | awk 'NR==1{print; next} {print | "sort -k${l} -rn"}' | head -${c}`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
519
516
  ${d}`:d}case"network_status":{let l="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:c,exitCode:u}=await r(l,15e3);return u!==0?`EXIT ${u}
520
- ${c}`:c}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:l}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),c=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!c)return"ERROR: No supported package manager found (dnf/apt)";let u=(e.packages||[]).join(" "),d;switch(e.package_action){case"list":d=c==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let m=c==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:g}=await r(m,6e4);return g||"(no output from package check)"}case"install":if(!u)return"ERROR: packages required for install";d=c==="dnf"?`dnf install -y ${u}`:`apt-get install -y ${u}`;break;case"remove":if(!u)return"ERROR: packages required for remove";d=c==="dnf"?`dnf remove -y ${u}`:`apt-get remove -y ${u}`;break;case"update":if(!u)return"ERROR: packages required for update (use upgrade for full system upgrade)";d=c==="dnf"?`dnf update -y ${u}`:`apt-get install -y --only-upgrade ${u}`;break;case"upgrade":d=c==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:f,exitCode:p}=await r(d,12e4);return p!==0?`EXIT ${p}
521
- ${f}`:f||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let l=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:c,exitCode:u}=await r(l,1e4);return u!==0?`EXIT ${u}
522
- ${c}`:c||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=`id ${e.user} && echo '--- Groups ---' && groups ${e.user} && echo '--- Last login ---' && lastlog -u ${e.user} 2>/dev/null`,{out:c,exitCode:u}=await r(l,1e4);return u!==0?`EXIT ${u}
523
- ${c}`:c}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let c=`useradd -m ${(e.groups||[]).map(f=>`-G ${f}`).join(" ")} ${e.user} && echo "User ${e.user} created"`,{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
524
- ${u}`:u}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=`userdel -r ${e.user} && echo "User ${e.user} deleted"`,{out:c,exitCode:u}=await r(l,15e3);return u!==0?`EXIT ${u}
525
- ${c}`:c}case"add_ssh_key":{if(!e.user)return"ERROR: user is required for user_action=add_ssh_key";if(!e.ssh_key)return"ERROR: ssh_key is required for user_action=add_ssh_key";let l=e.ssh_key.replace(/'/g,"'\\''"),c=`mkdir -p /home/${e.user}/.ssh && chmod 700 /home/${e.user}/.ssh && echo '${l}' >> /home/${e.user}/.ssh/authorized_keys && chmod 600 /home/${e.user}/.ssh/authorized_keys && chown -R ${e.user}:${e.user} /home/${e.user}/.ssh && echo "SSH key added for ${e.user}"`,{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
526
- ${u}`:u}default:return`ERROR: Unknown user_action: ${e.user_action}`}}case"firewall":{if(!e.firewall_action)return"ERROR: firewall_action is required for action=firewall";let{out:l}=await r("which firewall-cmd 2>/dev/null && echo firewalld || (which ufw 2>/dev/null && echo ufw) || echo iptables",1e4),c=l.includes("firewalld")?"firewalld":l.includes("ufw")?"ufw":"iptables",u;switch(e.firewall_action){case"status":u=c==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":c==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';u=c==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw allow ${e.port}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT`;break;case"deny":if(!e.port)return"ERROR: port is required for firewall deny";u=c==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw deny ${e.port}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j DROP`;break;case"remove":if(!e.port)return"ERROR: port is required for firewall remove";u=c==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw delete allow ${e.port}`:`iptables -D INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT 2>/dev/null || true`;break;case"reload":u=c==="firewalld"?"firewall-cmd --reload":c==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
527
- ${d}`:d||`firewall ${e.firewall_action} OK`}case"cron":{if(!e.cron_action)return"ERROR: cron_action is required for action=cron";let l=e.user?`-u ${e.user}`:"";switch(e.cron_action){case"list":{let c=`crontab ${l} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:u}=await r(c,1e4);return u||"(empty crontab)"}case"add":{if(!e.schedule)return"ERROR: schedule is required for cron add";if(!e.command)return"ERROR: command is required for cron add";let c=`${e.schedule} ${e.command}`,u=`(crontab ${l} -l 2>/dev/null; echo "${c}") | crontab ${l} - && echo "Cron entry added: ${c}"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
517
+ ${c}`:c}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:l}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),c=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!c)return"ERROR: No supported package manager found (dnf/apt)";let u=e.packages||[];if(!u.every(gS))return"ERROR: package names contain unsafe characters";let d=u.map(xe).join(" "),f;switch(e.package_action){case"list":f=c==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=c==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:$}=await r(g,6e4);return $||"(no output from package check)"}case"install":if(!d)return"ERROR: packages required for install";f=c==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=c==="dnf"?`dnf remove -y ${d}`:`apt-get remove -y ${d}`;break;case"update":if(!d)return"ERROR: packages required for update (use upgrade for full system upgrade)";f=c==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=c==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:p,exitCode:m}=await r(f,12e4);return m!==0?`EXIT ${m}
518
+ ${p}`:p||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let l=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:c,exitCode:u}=await r(l,1e4);return u!==0?`EXIT ${u}
519
+ ${c}`:c||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=Do(e.user);if(l)return l;let c=xe(e.user),u=`id ${c} && echo '--- Groups ---' && groups ${c} && echo '--- Last login ---' && lastlog -u ${c} 2>/dev/null`,{out:d,exitCode:f}=await r(u,1e4);return f!==0?`EXIT ${f}
520
+ ${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=Do(e.user);if(l)return l;if(!(e.groups||[]).every(cm))return"ERROR: groups contain unsafe characters";let c=(e.groups||[]).map(m=>`-G ${xe(m)}`).join(" "),u=xe(e.user),d=`useradd -m ${c} ${u} && echo "User ${e.user} created"`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
521
+ ${f}`:f}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=Do(e.user);if(l)return l;let u=`userdel -r ${xe(e.user)} && echo "User ${e.user} deleted"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
522
+ ${d}`:d}case"add_ssh_key":{if(!e.user)return"ERROR: user is required for user_action=add_ssh_key";if(!e.ssh_key)return"ERROR: ssh_key is required for user_action=add_ssh_key";let l=Do(e.user);if(l)return l;let u=`${`/home/${e.user}`}/.ssh`,d=`${u}/authorized_keys`,f=xe(e.user),p=`mkdir -p ${xe(u)} && chmod 700 ${xe(u)} && printf '%s
523
+ ' ${xe(e.ssh_key)} >> ${xe(d)} && chmod 600 ${xe(d)} && chown -R ${xe(`${e.user}:${e.user}`)} ${xe(u)} && echo "SSH key added for ${e.user}"`,{out:m,exitCode:g}=await r(p,15e3);return g!==0?`EXIT ${g}
524
+ ${m}`:m}default:return`ERROR: Unknown user_action: ${e.user_action}`}}case"firewall":{if(!e.firewall_action)return"ERROR: firewall_action is required for action=firewall";let{out:l}=await r("which firewall-cmd 2>/dev/null && echo firewalld || (which ufw 2>/dev/null && echo ufw) || echo iptables",1e4),c=l.includes("firewalld")?"firewalld":l.includes("ufw")?"ufw":"iptables",u;switch(e.firewall_action){case"status":u=c==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":c==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';if(!ac(e.port))return"ERROR: port contains unsafe characters";u=c==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw allow ${xe(e.port)}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT`;break;case"deny":if(!e.port)return"ERROR: port is required for firewall deny";if(!ac(e.port))return"ERROR: port contains unsafe characters";u=c==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw deny ${xe(e.port)}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j DROP`;break;case"remove":if(!e.port)return"ERROR: port is required for firewall remove";if(!ac(e.port))return"ERROR: port contains unsafe characters";u=c==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw delete allow ${xe(e.port)}`:`iptables -D INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT 2>/dev/null || true`;break;case"reload":u=c==="firewalld"?"firewall-cmd --reload":c==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
525
+ ${d}`:d||`firewall ${e.firewall_action} OK`}case"cron":{if(!e.cron_action)return"ERROR: cron_action is required for action=cron";if(e.user){let c=Do(e.user);if(c)return c}let l=e.user?`-u ${xe(e.user)}`:"";switch(e.cron_action){case"list":{let c=`crontab ${l} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:u}=await r(c,1e4);return u||"(empty crontab)"}case"add":{if(!e.schedule)return"ERROR: schedule is required for cron add";if(!e.command)return"ERROR: command is required for cron add";let c=`${e.schedule} ${e.command}`,u=`(crontab ${l} -l 2>/dev/null; printf '%s
526
+ ' ${xe(c)}) | crontab ${l} - && echo "Cron entry added: ${c}"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
528
527
  ${d}`:d}case"remove":{if(!e.command)return"ERROR: command (substring to match) is required for cron remove";let c=e.command.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=`crontab ${l} -l 2>/dev/null | grep -v "${c}" | crontab ${l} - && echo "Matching cron entries removed"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
529
528
  ${d}`:d}default:return`ERROR: Unknown cron_action: ${e.cron_action}`}}case"ssl_check":{if(!e.domain&&!e.cert_path)return"ERROR: domain or cert_path is required for ssl_check";let l;e.cert_path?l=`
530
- CERT="${e.cert_path}"
529
+ CERT=${xe(e.cert_path)}
531
530
  openssl x509 -in "$CERT" -noout -subject -issuer -startdate -enddate -ext subjectAltName 2>&1 && EXPIRY=$(openssl x509 -in "$CERT" -noout -enddate 2>/dev/null | cut -d= -f2) && DAYS=$(( ( $(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null) - $(date +%s) ) / 86400 )) && echo "Days until expiry: $DAYS"
532
531
  `.trim():l=`
533
- DOMAIN="${e.domain}"
532
+ DOMAIN=${xe(e.domain)}
534
533
  LECP="/etc/letsencrypt/live/$DOMAIN/cert.pem"
535
534
  if [ -f "$LECP" ]; then
536
535
  echo "Source: Let's Encrypt $LECP"
@@ -550,13 +549,13 @@ if [ -n "$EXPIRY" ]; then
550
549
  [ "$DAYS" -lt 0 ] && echo "CRITICAL: Certificate has EXPIRED!"
551
550
  fi
552
551
  `.trim();let{out:c,exitCode:u}=await r(l,25e3),d=/notAfter=|Days until expiry:/i.test(c);return u!==0&&!d?`EXIT ${u}
553
- ${c}`:c||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let c=`tail -n ${e.lines||100} ${e.path} 2>&1`,{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
554
- ${u}`:u||"(empty log)"}case"find_large":{let l=e.path||"/",c=e.limit||20,u=e.min_size||"100M",d=`find ${l} -xdev -type f -size +${u} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${c}`,{out:f,exitCode:p}=await r(d,6e4);return p!==0?`EXIT ${p}
555
- ${f}`:f||`(no files larger than ${u} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",c;switch(e.service_action){case"status":c=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":c="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":c=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":c=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":c=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":c=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":c=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":c=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(c,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
556
- ${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let l=e.signal||"SIGTERM",c;e.pid?c=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${l} ${e.pid} && echo "Sent ${l} to PID ${e.pid}"`:c=`pgrep -a "${e.process_name}" 2>/dev/null | head -5 && pkill -${l} "${e.process_name}" && echo "Sent ${l} to all '${e.process_name}' processes"`;let{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
552
+ ${c}`:c||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let c=`tail -n ${e.lines||100} ${xe(e.path)} 2>&1`,{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
553
+ ${u}`:u||"(empty log)"}case"find_large":{let l=e.path||"/",c=e.limit||20,u=e.min_size||"100M",d=`find ${xe(l)} -xdev -type f -size +${xe(u)} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${c}`,{out:f,exitCode:p}=await r(d,6e4);return p!==0?`EXIT ${p}
554
+ ${f}`:f||`(no files larger than ${u} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";if(e.service_name){let p=lc(e.service_name,"service_name");if(p)return p}let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",c;switch(e.service_action){case"status":c=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":c="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":c=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":c=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":c=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":c=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":c=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":c=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(c,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
555
+ ${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let l=e.signal||"SIGTERM";if(!yS(l))return"ERROR: signal contains unsafe characters";let c;if(e.pid){if(!/^\d+$/.test(String(e.pid)))return"ERROR: pid must be numeric";c=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${l} ${e.pid} && echo "Sent ${l} to PID ${e.pid}"`}else c=`pgrep -a ${xe(e.process_name)} 2>/dev/null | head -5 && pkill -${l} ${xe(e.process_name)} && echo "Sent ${l} to all '${e.process_name}' processes"`;let{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
557
556
  ${u}`:u}case"journalctl":{let l=e.lines||100,c=["journalctl","--no-pager","-n",String(l)];e.unit&&c.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&c.push("-p",e.priority),e.since&&c.push(`--since="${e.since}"`),c.push('2>/dev/null || echo "(journalctl not available)"');let{out:u,exitCode:d}=await r(c.join(" "),2e4);return d!==0?`EXIT ${d}
558
- ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=Co(),o=n(e.type,e.name,e.content,e.description);return o.ok?o.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${o.path}`:`ERROR: ${o.error}`}case"delete_memory":{let{deleteMemory:n}=Co();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=Wr(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function Mx(t,e,s={}){let{emit:n}=Wr(),{logToolExecution:o}=Rp(),r=Date.now(),i=s.silent?null:gx(t,e);if(!i){let l=await Ip(t,e,s);return o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:l}),l}let a=new mx(i);a.start();try{let l=await Ip(t,e,s);return a.stop(),o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw a.stop(),o({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}qp.exports={TOOL_DEFINITIONS:Nx,executeTool:Mx,resolvePath:Qe,autoFixPath:mi,autoFixEdit:jp,enrichBashError:Dp,cancelPendingAskUser:Cx,setAskUserHandler:Ax,fileExists:xt}});var po=Z((KR,Bp)=>{Bp.exports=Fp()});var Zl=Z((VR,Up)=>{var{loadServerProfiles:Lo,resolveProfile:XR,sshExec:Px}=As(),Jl={almalinux9:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all. Open port: firewall-cmd --permanent --add-port=PORT/tcp && firewall-cmd --reload.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent | audit2why. Fix context: restorecon -Rv /path.","Nginx config: /etc/nginx/. Test: nginx -t. Reload: systemctl reload nginx.","Process list: ps aux. Ports: ss -tuln.","Python: python3. Pip: pip3. Virtualenv: python3 -m venv."],almalinux8:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent."],ubuntu:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw. Status: ufw status. Allow port: ufw allow PORT/tcp.","SELinux NOT active by default (AppArmor instead). Check: aa-status."],debian:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw or iptables."],macos:["Package manager: Homebrew (brew). Install: brew install <pkg>. Update: brew update && brew upgrade.","Service manager: launchctl (NOT systemctl). Start: brew services start <name>. List: brew services list.",`No systemd. No journalctl. Use: log show --predicate 'process == "nginx"' --last 1h instead.`,"Firewall: macOS built-in (pfctl or System Settings). Check: pfctl -s rules.","Process list: ps aux. Ports: lsof -i -n -P | grep LISTEN."]};function Lx(){let t=Lo();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",c=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${a}${l}${c}`)}let n=new Set;for(let o of Object.values(t))o.os&&Jl[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${r} Notes`);for(let i of Jl[o])s.push(`- ${i}`)}}return s.join(`
559
- `)}function Ix(t){let e=Lo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function Dx(){return Object.keys(Lo())}function jx(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=Lo(),r=Object.keys(o);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=n.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let c=r.map(f=>{let p=o[f],m=p.user?`${p.user}@${p.host}`:p.host,g=p.port&&Number(p.port)!==22?`:${p.port}`:"";return` - **${f}**: ${m}${g}${p.os?` (${p.os})`:""}`}).join(`
557
+ ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=Mo(),o=n(e.type,e.name,e.content,e.description);return o.ok?o.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${o.path}`:`ERROR: ${o.error}`}case"delete_memory":{let{deleteMemory:n}=Mo();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=Vr(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function $S(t,e,s={}){let{emit:n}=Vr(),{logToolExecution:o}=Gh(),r=Date.now(),i=s.silent?null:zx(t,e);if(!i){let l=await sm(t,e,s);return o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:l}),l}let a=new Gx(i);a.start();try{let l=await sm(t,e,s);return a.stop(),o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw a.stop(),o({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}um.exports={TOOL_DEFINITIONS:wS,executeTool:$S,resolvePath:st,autoFixPath:xi,autoFixEdit:lm,enrichBashError:am,cancelPendingAskUser:cS,setAskUserHandler:uS,fileExists:Tt}});var yo=V((K1,fm)=>{fm.exports=dm()});var fc=V((V1,pm)=>{var{loadServerProfiles:Bo,resolveProfile:X1,sshExec:_S}=Ps(),dc={almalinux9:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all. Open port: firewall-cmd --permanent --add-port=PORT/tcp && firewall-cmd --reload.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent | audit2why. Fix context: restorecon -Rv /path.","Nginx config: /etc/nginx/. Test: nginx -t. Reload: systemctl reload nginx.","Process list: ps aux. Ports: ss -tuln.","Python: python3. Pip: pip3. Virtualenv: python3 -m venv."],almalinux8:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent."],ubuntu:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw. Status: ufw status. Allow port: ufw allow PORT/tcp.","SELinux NOT active by default (AppArmor instead). Check: aa-status."],debian:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw or iptables."],macos:["Package manager: Homebrew (brew). Install: brew install <pkg>. Update: brew update && brew upgrade.","Service manager: launchctl (NOT systemctl). Start: brew services start <name>. List: brew services list.",`No systemd. No journalctl. Use: log show --predicate 'process == "nginx"' --last 1h instead.`,"Firewall: macOS built-in (pfctl or System Settings). Check: pfctl -s rules.","Process list: ps aux. Ports: lsof -i -n -P | grep LISTEN."]};function bS(){let t=Bo();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",c=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${a}${l}${c}`)}let n=new Set;for(let o of Object.values(t))o.os&&dc[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${r} Notes`);for(let i of dc[o])s.push(`- ${i}`)}}return s.join(`
558
+ `)}function kS(t){let e=Bo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function xS(){return Object.keys(Bo())}function SS(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=Bo(),r=Object.keys(o);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=n.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let c=r.map(f=>{let p=o[f],m=p.user?`${p.user}@${p.host}`:p.host,g=p.port&&Number(p.port)!==22?`:${p.port}`:"";return` - **${f}**: ${m}${g}${p.os?` (${p.os})`:""}`}).join(`
560
559
  `),u=r.map(f=>o[f].log_path).filter(Boolean),d=u.length>0?`
561
560
  - Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
562
561
 
@@ -574,7 +573,7 @@ ${c}
574
573
  - \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
575
574
  - \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
576
575
 
577
- **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${qx(o)}`}function qx(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
576
+ **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${ES(o)}`}function ES(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
578
577
 
579
578
  ## Server Debugging Rules
580
579
 
@@ -585,35 +584,36 @@ ${c}
585
584
  - CRITICAL: When the user pastes a server error message (error logs), this is NEVER a "simple question" to answer from training knowledge. You MUST ssh_exec to verify if the error is still occurring BEFORE writing any explanation. Do NOT explain from memory \u2014 investigate first, always.
586
585
  - LOG FILES: Always check the CURRENT log first: /home/deploy/server-agent/logs/api-error.log (no date suffix). Log files WITH a date suffix (e.g. api-error.log-20260322) are ROTATED/OLD \u2014 errors there may already be fixed. Only look at dated logs if the current log is empty or the error is absent from the current log.
587
586
  - FIX WORKFLOW (YOLO): Once you identify a fixable bug via SSH investigation: (1) edit the file on server using ssh_exec with tee or sed -i (NOT sed -n), (2) restart the affected service with systemctl restart, (3) verify with tail logs. Do NOT produce a report \u2014 execute the fix.
588
- - READING REMOTE FILES: NEVER use sed -n (always blocked). To read a specific function in a remote file: ssh_exec 'grep -n "functionName" /path/file -A 50'. To read the whole file: ssh_exec 'cat /path/file'. These are the only two options.`:""}async function Fx(t){if(typeof t!="string")return null;let e=[...t.matchAll(/https?:\/\/([a-zA-Z0-9._-]+)/g)];if(e.length===0)return null;let s=Lo();if(Object.keys(s).length===0)return null;let n=null,o=null;for(let[,i]of e){let a=i.toLowerCase().split(".");for(let[l,c]of Object.entries(s))if(a.includes(l.toLowerCase())){n=c,o=l;break}if(n)break;for(let[l,c]of Object.entries(s))if(c.host===i){n=c,o=l;break}if(n)break}if(!n||!o)return null;let r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await Px(n,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=n.user?`${n.user}@${n.host}`:n.host;return`[Server context for "${o}" (${a}) \u2014 probed at task start]
589
- `+i.trim()}catch{return null}}Up.exports={getServerContext:Lx,getDeploymentContextBlock:jx,hasServerOS:Ix,getProfileNames:Dx,probeUrlServer:Fx,OS_HINTS:Jl}});var zp=Z((JR,Gp)=>{var pt=require("fs").promises,Hp=require("fs"),Ye=require("path"),yi=require("util").promisify(require("child_process").exec),{C:Fs}=Je(),{getMergeConflicts:Yp}=jr(),{getServerContext:Bx}=Zl(),Ux=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function Wx(t){try{return Hp.readFileSync(t,"utf-8").split(`
590
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function Hx(t,e){for(let s of e)if(s===t||s.includes("*")&&new RegExp("^"+s.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function Yx(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=Ye.join(t,".gitignore"),r=[...n,...Wx(o)],i=0,a=[Ye.basename(t)+"/"];function l(c,u,d){if(d>e||i>=s)return;let f;try{f=Hp.readdirSync(c,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let p=f.filter(m=>!(Ux.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||Hx(m.name,r)));for(let m=0;m<p.length;m++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=p[m],_=m===p.length-1,k=_?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",A=u+(_?" ":"\u2502 "),L=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${k}${L}`),i++,g.isDirectory()&&l(Ye.join(c,g.name),A,d+1)}}return l(t,"",1),a.join(`
591
- `)}var Ql=new Map,Us=new Map,wi=null,Wp=3e4,Bs={result:null,expiry:0,cwd:null};async function en(t){try{return await t()}catch{return null}}async function Gx(){if(!wi||Date.now()>wi)return!1;let t=[Ye.join(process.cwd(),"package.json"),Ye.join(process.cwd(),"README.md"),Ye.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await pt.stat(e),n=Us.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Us.has(e))return!1}try{let e=Ye.join(process.cwd(),".git","HEAD"),s=await pt.stat(e),n=Us.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function zx(){let t=[Ye.join(process.cwd(),"package.json"),Ye.join(process.cwd(),"README.md"),Ye.join(process.cwd(),".gitignore"),Ye.join(process.cwd(),".git","HEAD"),Ye.join(process.cwd(),"CLAUDE.md"),Ye.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let s=await pt.stat(e);Us.set(e,s.mtimeMs)}catch{Us.delete(e)}}async function Kx(t){let e="fileContext",s=Ql.get(e),n=!1;if(s&&await Gx()&&(n=!0),!n){let c=[],u=Ye.join(t,"package.json");if(await en(()=>pt.access(u).then(()=>!0).catch(()=>!1)))try{let E=await pt.readFile(u,"utf-8"),v=JSON.parse(E),N={name:v.name,version:v.version};v.scripts&&(N.scripts=Object.keys(v.scripts).slice(0,15)),v.dependencies&&(N.deps=Object.keys(v.dependencies).length),v.devDependencies&&(N.devDeps=Object.keys(v.devDependencies).length),c.push(`PACKAGE: ${JSON.stringify(N)}`)}catch{}let f=Ye.join(t,"README.md");if(await en(()=>pt.access(f).then(()=>!0).catch(()=>!1))){let v=(await pt.readFile(f,"utf-8")).split(`
587
+ - READING REMOTE FILES: NEVER use sed -n (always blocked). To read a specific function in a remote file: ssh_exec 'grep -n "functionName" /path/file -A 50'. To read the whole file: ssh_exec 'cat /path/file'. These are the only two options.`:""}async function vS(t){if(typeof t!="string")return null;let e=[...t.matchAll(/https?:\/\/([a-zA-Z0-9._-]+)/g)];if(e.length===0)return null;let s=Bo();if(Object.keys(s).length===0)return null;let n=null,o=null;for(let[,i]of e){let a=i.toLowerCase().split(".");for(let[l,c]of Object.entries(s))if(a.includes(l.toLowerCase())){n=c,o=l;break}if(n)break;for(let[l,c]of Object.entries(s))if(c.host===i){n=c,o=l;break}if(n)break}if(!n||!o)return null;let r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await _S(n,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=n.user?`${n.user}@${n.host}`:n.host;return`[Server context for "${o}" (${a}) \u2014 probed at task start]
588
+ `+i.trim()}catch{return null}}pm.exports={getServerContext:bS,getDeploymentContextBlock:SS,hasServerOS:kS,getProfileNames:xS,probeUrlServer:vS,OS_HINTS:dc}});var ym=V((J1,gm)=>{var yt=require("fs").promises,vi=require("fs"),Be=require("path"),Ei=require("util").promisify(require("child_process").exec),{C:Ws}=tt(),{getMergeConflicts:mm}=Yr(),{getServerContext:TS}=fc(),{refreshIndex:RS,getFileIndex:CS,buildContentIndex:AS,summarizeModuleHubs:OS}=mn(),NS=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),MS=[{file:"tsconfig.json",label:"TypeScript"},{file:"jest.config.js",label:"Jest"},{file:"jest.config.cjs",label:"Jest"},{file:"jest.config.mjs",label:"Jest"},{file:"vitest.config.js",label:"Vitest"},{file:"vitest.config.ts",label:"Vitest"},{file:"vite.config.js",label:"Vite"},{file:"vite.config.ts",label:"Vite"},{file:"next.config.js",label:"Next.js"},{file:"next.config.mjs",label:"Next.js"},{file:"tailwind.config.js",label:"Tailwind"},{file:"tailwind.config.ts",label:"Tailwind"},{file:"docker-compose.yml",label:"Docker Compose"},{file:"docker-compose.yaml",label:"Docker Compose"},{file:".github/workflows",label:"GitHub Actions"}];function PS(t,e=6){let s=new Map;for(let n of t){let o=n.includes("/")?n.split("/")[0]:"(root)";!o||o.startsWith(".")||s.set(o,(s.get(o)||0)+1)}return[...s.entries()].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0])).slice(0,e).map(([n,o])=>`${n} (${o})`)}function LS(t){let e=new Set(t),s=new Set;for(let n of MS)(e.has(n.file)||[...e].some(o=>o.startsWith(`${n.file}/`)))&&s.add(n.label);return e.has("package.json")&&s.add("Node.js"),[...e].some(n=>/^tests?\//.test(n)||/\.test\./.test(n)||/\.spec\./.test(n))&&s.add("Tests"),[...e].some(n=>n.startsWith("vscode/"))&&s.add("VS Code Extension"),[...s]}function IS(t){let e=["package.json","cli/index.js","src/index.ts","src/index.js","index.ts","index.js","bin/nex-code.js","dist/nex-code.js","README.md"],s=[];for(let n of e)if(t.includes(n)&&s.push(n),s.length>=5)break;return s}function jS(t,e=6){let s=t.filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(s.length===0)return[];let n=t.filter(r=>!/^tests?\//.test(r)&&!/\.test\./.test(r)&&!/\.spec\./.test(r)&&/\.(js|jsx|ts|tsx|py|go|rs|java)$/.test(r)),o=[];for(let r of n){let i=Be.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=s.filter(l=>l.includes(i));if(a.length>0&&o.push(`${r} -> ${a.slice(0,2).join(", ")}`),o.length>=e)break}return o}function DS(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function qS(t){try{await RS(t);let e=CS();if(!e||e.length===0)return"";let s=LS(e),n=PS(e),o=IS(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=jS(e),a=[];try{let d=Be.join(t,"package.json");if(vi.existsSync(d)){let f=JSON.parse(vi.readFileSync(d,"utf-8"));a=DS(f)}}catch{}let l="",c="";try{let d=await AS(t),f=Object.entries(d.files||{}).map(([p,m])=>({file:p,defs:Array.isArray(m.defs)?m.defs.length:0})).filter(p=>p.defs>0).sort((p,m)=>m.defs-p.defs||p.file.localeCompare(m.file)).slice(0,4).map(p=>`${p.file} (${p.defs} defs)`);f.length>0&&(l=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await OS(t,4);d.length>0&&(c=`MODULE HUBS: ${d.join(", ")}`)}catch{}let u=[`REPO MAP: ${e.length} indexed files${s.length?` | stack: ${s.join(", ")}`:""}`];return n.length>0&&u.push(`WORK AREAS: ${n.join(", ")}`),o.length>0&&u.push(`LIKELY ENTRY POINTS: ${o.join(", ")}`),a.length>0&&u.push(`WORKSPACES: ${a.join(", ")}`),r>0&&u.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&u.push(`TEST MAP: ${i.join(" | ")}`),l&&u.push(l),c&&u.push(c),u.push("RETRIEVAL RULE: Prefer the smallest verified path set first \u2014 identify likely files, then read only the exact symbols/sections you need before editing."),u.join(`
589
+ `)}catch{return""}}function FS(t){try{return vi.readFileSync(t,"utf-8").split(`
590
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function BS(t,e){for(let s of e)if(s===t||s.includes("*")&&new RegExp("^"+s.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function US(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=Be.join(t,".gitignore"),r=[...n,...FS(o)],i=0,a=[Be.basename(t)+"/"];function l(c,u,d){if(d>e||i>=s)return;let f;try{f=vi.readdirSync(c,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let p=f.filter(m=>!(NS.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||BS(m.name,r)));for(let m=0;m<p.length;m++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=p[m],$=m===p.length-1,k=$?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",M=u+($?" ":"\u2502 "),D=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${k}${D}`),i++,g.isDirectory()&&l(Be.join(c,g.name),M,d+1)}}return l(t,"",1),a.join(`
591
+ `)}var pc=new Map,Ys=new Map,Ti=null,hm=3e4,Hs={result:null,expiry:0,cwd:null};async function rn(t){try{return await t()}catch{return null}}async function WS(){if(!Ti||Date.now()>Ti)return!1;let t=[Be.join(process.cwd(),"package.json"),Be.join(process.cwd(),"README.md"),Be.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await yt.stat(e),n=Ys.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Ys.has(e))return!1}try{let e=Be.join(process.cwd(),".git","HEAD"),s=await yt.stat(e),n=Ys.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function HS(){let t=[Be.join(process.cwd(),"package.json"),Be.join(process.cwd(),"README.md"),Be.join(process.cwd(),".gitignore"),Be.join(process.cwd(),".git","HEAD"),Be.join(process.cwd(),"CLAUDE.md"),Be.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let s=await yt.stat(e);Ys.set(e,s.mtimeMs)}catch{Ys.delete(e)}}async function YS(t){let e="fileContext",s=pc.get(e),n=!1;if(s&&await WS()&&(n=!0),!n){let c=[],u=Be.join(t,"package.json");if(await rn(()=>yt.access(u).then(()=>!0).catch(()=>!1)))try{let E=await yt.readFile(u,"utf-8"),A=JSON.parse(E),ee={name:A.name,version:A.version};A.scripts&&(ee.scripts=Object.keys(A.scripts).slice(0,15)),A.dependencies&&(ee.deps=Object.keys(A.dependencies).length),A.devDependencies&&(ee.devDeps=Object.keys(A.devDependencies).length),c.push(`PACKAGE: ${JSON.stringify(ee)}`)}catch{}let f=Be.join(t,"README.md");if(await rn(()=>yt.access(f).then(()=>!0).catch(()=>!1))){let A=(await yt.readFile(f,"utf-8")).split(`
592
592
  `).slice(0,50);c.push(`README (first 50 lines):
593
- ${v.join(`
594
- `)}`)}let m=Ye.join(t,".gitignore");if(await en(()=>pt.access(m).then(()=>!0).catch(()=>!1))){let E=await pt.readFile(m,"utf-8");c.push(`GITIGNORE:
595
- ${E.trim()}`)}let _=Ye.join(t,"CLAUDE.md");if(await en(()=>pt.access(_).then(()=>!0).catch(()=>!1))){let E=await pt.readFile(_,"utf-8");E.trim()&&c.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
596
- ${E.trim()}`)}let A=Ye.join(t,".nex","CLAUDE.md");if(await en(()=>pt.access(A).then(()=>!0).catch(()=>!1))){let E=await pt.readFile(A,"utf-8");E.trim()&&c.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
597
- ${E.trim()}`)}s=c.join(`
593
+ ${A.join(`
594
+ `)}`)}let m=Be.join(t,".gitignore");if(await rn(()=>yt.access(m).then(()=>!0).catch(()=>!1))){let E=await yt.readFile(m,"utf-8");c.push(`GITIGNORE:
595
+ ${E.trim()}`)}let $=Be.join(t,"CLAUDE.md");if(await rn(()=>yt.access($).then(()=>!0).catch(()=>!1))){let E=await yt.readFile($,"utf-8");E.trim()&&c.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
596
+ ${E.trim()}`)}let M=Be.join(t,".nex","CLAUDE.md");if(await rn(()=>yt.access(M).then(()=>!0).catch(()=>!1))){let E=await yt.readFile(M,"utf-8");E.trim()&&c.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
597
+ ${E.trim()}`)}let v=await qS(t);v&&c.push(v),s=c.join(`
598
598
 
599
- `),Ql.set(e,s),wi=Date.now()+Wp,await zx()}let o=[s],r,i,a,l;if(Bs.result&&Date.now()<Bs.expiry&&Bs.cwd===t?{branch:r,status:i,log:a,conflicts:l}=Bs.result:([r,i,a,l]=await Promise.all([en(async()=>{let{stdout:c}=await yi("git branch --show-current",{cwd:t,timeout:5e3});return c.trim()}),en(async()=>{let{stdout:c}=await yi("git status --short",{cwd:t,timeout:5e3});return c.trim()}),en(async()=>{let{stdout:c}=await yi("git log --oneline -5",{cwd:t,timeout:5e3});return c.trim()}),Yp()]),Bs={result:{branch:r,status:i,log:a,conflicts:l},expiry:Date.now()+Wp,cwd:t}),r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
599
+ `),pc.set(e,s),Ti=Date.now()+hm,await HS()}let o=[s],r,i,a,l;if(Hs.result&&Date.now()<Hs.expiry&&Hs.cwd===t?{branch:r,status:i,log:a,conflicts:l}=Hs.result:([r,i,a,l]=await Promise.all([rn(async()=>{let{stdout:c}=await Ei("git branch --show-current",{cwd:t,timeout:5e3});return c.trim()}),rn(async()=>{let{stdout:c}=await Ei("git status --short",{cwd:t,timeout:5e3});return c.trim()}),rn(async()=>{let{stdout:c}=await Ei("git log --oneline -5",{cwd:t,timeout:5e3});return c.trim()}),mm()]),Hs={result:{branch:r,status:i,log:a,conflicts:l},expiry:Date.now()+hm,cwd:t}),r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
600
600
  ${i}`),a&&o.push(`RECENT COMMITS:
601
601
  ${a}`),l&&l.length>0){let c=l.map(u=>` ${u.file}`).join(`
602
602
  `);o.push(`MERGE CONFLICTS (resolve before editing these files):
603
- ${c}`)}try{let c=Bx();c&&o.push(c)}catch{}return o.join(`
603
+ ${c}`)}try{let c=TS();c&&o.push(c)}catch{}return o.join(`
604
604
 
605
- `)}async function Xx(t){let e=Ye.join(t,"package.json"),s="";if(await en(()=>pt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await pt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([en(async()=>{let{stdout:i}=await yi("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Yp()]);if(r&&r.length>0){console.log(`${Fs.red} \u26A0 ${r.length} unresolved merge conflict(s):${Fs.reset}`);for(let i of r)console.log(`${Fs.red} ${i.file}${Fs.reset}`);console.log(`${Fs.yellow} \u2192 Resolve conflicts before starting tasks${Fs.reset}`)}console.log()}Gp.exports={gatherProjectContext:Kx,printContext:Xx,generateFileTree:Yx,_clearContextCache:()=>{Ql.clear(),Us.clear(),wi=null,Bs={result:null,expiry:0,cwd:null}}}});var $i=Z((ZR,Vp)=>{var Ht=require("fs"),_i=require("path"),{atomicWrite:Vx}=jn();function Do(){return _i.join(process.cwd(),".nex","sessions")}function ec(){let t=Do();Ht.existsSync(t)||Ht.mkdirSync(t,{recursive:!0,mode:448})}function tc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return _i.join(Do(),`${e}.json`)}function nc(t,e,s={}){ec();let n=tc(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return Vx(n,JSON.stringify(o,null,2)),{path:n,name:t}}function Kp(t){let e=tc(t);if(!Ht.existsSync(e))return null;try{return JSON.parse(Ht.readFileSync(e,"utf-8"))}catch{return null}}function Xp(){ec();let t=Do(),e=Ht.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Ht.readFileSync(_i.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function Jx(t){let e=tc(t);return Ht.existsSync(e)?(Ht.unlinkSync(e),!0):!1}function Zx(){let t=Xp();return t.length===0?null:Kp(t[0].name)}var es=null,hn=null,Io=null;function Qx(t,e={}){t.length!==0&&(es&&clearTimeout(es),hn=t,Io=e||{},es=setTimeout(()=>{hn&&hn.length>0&&nc("_autosave",hn,Io),es=null,hn=null,Io=null},5e3))}function eS(){es&&(clearTimeout(es),es=null),hn&&hn.length>0&&(nc("_autosave",hn,Io),hn=null,Io=null)}function tS(){ec();let t=Do(),e=Ht.readdirSync(t).filter(r=>r.endsWith(".json")),s=new Date,n=new Date(s.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=_i.join(t,r);try{let a=Ht.statSync(i);new Date(a.mtime)<n&&(Ht.unlinkSync(i),o++)}catch{}}return o}Vp.exports={saveSession:nc,loadSession:Kp,listSessions:Xp,deleteSession:Jx,getLastSession:Zx,autoSave:Qx,flushAutoSave:eS,clearOldSessions:tS,_getSessionsDir:Do}});var rm=Z((QR,om)=>{"use strict";var jo=require("fs"),Jp=require("path");function Zp(t){let e=[];return t.forEach((s,n)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:n,id:o.id||null})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:n,id:o.id||null})}))}),e}function nS(t){let e=new Set;return t.forEach(s=>{s.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&s.tool_call_id&&e.add(s.tool_call_id),s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_result"&&n.tool_use_id&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&e.add(n.tool_use_id)})}),e}function Qp(t){let e=[];return t.forEach((s,n)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:n})}}),s.role==="tool"){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:o,index:n})}}),e}function em(t){for(let e=t.length-1;e>=0;e--){let s=t[e];if(s.role==="assistant"){if(typeof s.content=="string")return s.content.trim();if(Array.isArray(s.content)){let n=s.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(n)return n}}}return""}function tm(t,e){let s=[];for(let n=t.length-1;n>=0&&s.length<e;n--){let o=t[n];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&s.push(r)}return s}function nm(t){let e=new Map;for(let s of t){let n;try{n=JSON.stringify(s.input)}catch{n=String(s.input)}let o=`${s.name}|${n}`;e.set(o,(e.get(o)||0)+1)}return e}function sm(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,s=[],n=Zp(t),o=Qp(t),r=n.length,i=nS(t),a=n.filter($=>!$.id||!i.has($.id));t.some($=>$.role==="user"&&typeof $.content=="string"&&$.content.startsWith("[SYSTEM WARNING]")&&($.content.includes("edited")||$.content.includes("bash command")||$.content.includes("grep pattern")||$.content.includes("re-read")||$.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let c=n.find($=>{let I=$.input?.command||$.input?.cmd||"";return/\bsed\s+-n\b/.test(I)});if(c){let $=(c.input?.command||c.input?.cmd||"").slice(0,80);o.some(H=>H.content.includes("BLOCKED: sed -n is forbidden")||H.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${$}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${$}`))}n.find($=>{if($.name!=="grep"&&$.name!=="bash"&&$.name!=="ssh_exec")return!1;let I=$.input?.command||$.input?.cmd||"",H=$.input?.pattern||"",O=`${I} ${H}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(O)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(O)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some($=>$.role==="assistant"),f=em(t),m=tm(t,3).some($=>$.length>100&&!/^[^.!]{0,40}\?$/.test($));if(d&&!m&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let $=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";s.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${$}`)}r>40?(e-=1.5,s.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,s.push(`High tool call count: ${r} (>25 threshold)`)),t.some($=>{let I=typeof $.content=="string"?$.content:Array.isArray($.content)?$.content.map(H=>typeof H=="string"?H:H.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(I)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let k=nm(a),A=0,L="";for(let[$,I]of k)I>A&&(A=I,L=$);if(A>=3){let[$]=L.split("|");e-=1,s.push(`Same tool call repeated ${A}\xD7 (tool: ${$})`)}let E=!1,v=t.findIndex($=>$.role==="user"&&typeof $.content=="string"&&$.content.includes("[SYSTEM STOP]")&&$.content.includes('"valid":true'));v>=0&&n.filter(I=>I.index>v).length>0&&(E=!0),E&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let N=n.filter($=>$.name==="ssh_exec");if(N.length>=8){let $=0,I=1;for(let H=1;H<N.length;H++)N[H].index<=N[H-1].index+2?I++:($=Math.max($,I),I=1);$=Math.max($,I),$>=8&&(e-=.5,s.push(`SSH reconnect storm: ${$} consecutive SSH calls`))}d&&N.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,s.push("Surrender: model asked user to manually provide server output instead of gathering it"));let te=new Map;for(let $ of a)if($.name==="read_file"&&$.input?.path){let I=$.input.path;te.has(I)||te.set(I,{count:0,ranges:[]});let H=te.get(I);if(H.count++,$.input.line_start!=null){let O=$.input.line_start||1,q=$.input.line_end||O+350;H.ranges.push([O,q])}}function V($,I,H){for(let[O,q]of H){let b=Math.max($,O),Y=Math.min(I,q);if(Y>b){let ke=Y-b,fe=I-$||1;if(ke/fe>=.7)return!0}}return!1}let re=0,le="";for(let[$,I]of te){if(I.count<3)continue;if(I.ranges.length===I.count){let q=!1,b=[];for(let[Y,ke]of I.ranges){if(b.length>0&&V(Y,ke,b)){q=!0;break}b.push([Y,ke])}if(!q)continue}if(I.count-I.ranges.length<=2&&I.ranges.length>=1){let q=!1,b=[];for(let[Y,ke]of I.ranges){if(b.length>0&&V(Y,ke,b)){q=!0;break}b.push([Y,ke])}if(!q)continue}I.count>re&&(re=I.count,le=$)}if(re>=3){e-=1;let $=le.split("/").slice(-2).join("/");s.push(`read_file loop: "${$}" read ${re}\xD7 (file already in context)`)}let ne=0,S="";for(let[$,I]of te){if(I.ranges.length<4)continue;let H=[],O=!1;for(let[q,b]of I.ranges){if(H.length>0&&V(q,b,H)){O=!0;break}H.push([q,b])}!O&&I.ranges.length>ne&&(ne=I.ranges.length,S=$)}if(ne>=4){e-=.5;let $=S.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${$}" read in ${ne} sequential sections \u2014 use grep instead`)}let Ee=new Map;for(let $ of a)if($.name==="grep"&&$.input?.path&&$.input?.pattern){let I=$.input.path;Ee.has(I)||Ee.set(I,new Set),Ee.get(I).add($.input.pattern)}let W=0,J="";for(let[$,I]of Ee)$.split("/").pop().includes(".")&&I.size>W&&(W=I.size,J=$);if(W>=3){e-=.75;let $=J.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${$}" searched ${W}\xD7 with different patterns (file already in context)`)}{let $=new Set,I=new Set,H=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let q of n){if(q.name==="write_file"&&q.input?.path){let b=q.input.path.split("/").pop(),Y=q.input.path.includes("/tests/");H.test(b)&&!Y&&$.add(q.input.path)}if((q.name==="bash"||q.name==="ssh_exec")&&q.input?.command){let b=q.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(b)for(let Y of b){let ke=Y.split(/\s+/),fe=ke[ke.length-1];for(let at of $)(at.endsWith(fe)||fe.endsWith(at.split("/").pop()))&&I.add(at)}}}let O=I.size;if(O>=1){let q=Math.min(O*.25,.5);e-=q;let b=[...I].map(Y=>Y.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${b} \u2014 write inline logic or use tests/ instead`)}}let he=o.filter($=>$.content.startsWith("EXIT")).length;he>=10?(e-=1,s.push(`Bash exit-error storm: ${he} tool results started with EXIT (repeated failing commands)`)):he>=5&&(e-=.5,s.push(`Repeated bash errors: ${he} tool results with non-zero exit code`));for(let $ of t){if($.role!=="assistant")continue;let I="";if(typeof $.content=="string"?I=$.content:Array.isArray($.content)&&(I=$.content.filter(fe=>fe&&(fe.type==="text"||typeof fe=="string")).map(fe=>typeof fe=="string"?fe:fe.text||"").join("")),I.length<=5e3)continue;let H=I.split(/(?<=\. )/).filter(fe=>fe.trim().length>0);if(H.length<6)continue;let O=new Map;for(let fe=0;fe<=H.length-3;fe++){let at=H.slice(fe,fe+3).join("").trim();at.length>30&&O.set(at,(O.get(at)||0)+1)}let q=0,b="";for(let[fe,at]of O)at>q&&(q=at,b=fe);if(q<3)continue;let ke=b.length*q/I.length;if(ke>=.4||q>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${q}\xD7 same paragraph, ${Math.round(ke*100)}% repeated)`);break}}{let $=new Set(["read_file","list_directory","search_files","glob","grep"]),I=t.some(O=>Array.isArray(O.tool_calls)?O.tool_calls.some(q=>$.has(q.function?.name)):Array.isArray(O.content)?O.content.some(q=>q.type==="tool_use"&&$.has(q.name)):!1);t.some(O=>O.role==="assistant"&&typeof O.content=="string"&&(O.content.includes("## Steps")||O.content.includes("/plan approve")))&&!I&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Re=o.filter($=>$.content.startsWith("BLOCKED:")&&!$.content.includes("BLOCKED: sed -n")&&!$.content.includes("SSH paused")&&!$.content.includes("SSH temporarily paused"));if(Re.length>0){let $=Math.min(Re.length*.5,1.5);e-=$,s.push(`${Re.length} tool call${Re.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Ue=t.filter($=>{let I=typeof $.content=="string"?$.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(I)}).length;if(Ue>0){let $=Math.min(Ue*1,2);e-=$,s.push(`Super-nuclear context wipe fired ${Ue}\xD7 (context collapse \u2014 task too large or read loops)`)}{let $=!1,I=!1,H=!1;for(let q of n){if(q.name!=="bash")continue;let b=(q.input?.command||q.input?.cmd||"").trim();!(/cat\s*>/.test(b)||/<</.test(b))&&/\bcat\s+\S/.test(b)&&($=!0),/^\s*ls(\s|$)/.test(b)&&!/npm|yarn|pnpm|make|git\b/.test(b)&&(I=!0),/\bfind\s+\S/.test(b)&&!/git\b|npm\b|-exec\b/.test(b)&&(H=!0)}let O=[$,I,H].filter(Boolean).length;if(O>0){let q=Math.min(O*.25,.75);e-=q;let b=[];$&&b.push("cat (use read_file)"),I&&b.push("ls (use list_directory)"),H&&b.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${b.join(", ")}`)}}{let $=n.some(b=>(b.name==="write_file"||b.name==="Write")&&b.input?.path&&(b.input.path.endsWith("requirements.txt")||b.input.path.endsWith("Pipfile")||b.input.path.endsWith("pyproject.toml"))),I=n.some(b=>(b.name==="write_file"||b.name==="Write")&&b.input?.path&&b.input.path.endsWith("package.json")),H=n.filter(b=>(b.name==="bash"||b.name==="Bash")&&b.input?.command).map(b=>b.input.command),O=H.some(b=>/pip\s+install|python\s+-m\s+venv/.test(b)),q=H.some(b=>/npm\s+install/.test(b));$&&!O?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):I&&!q&&n.some(Y=>(Y.name==="write_file"||Y.name==="Write")&&Y.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(Y.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let $=t.find(b=>b.role==="assistant"),I="";$&&(typeof $.content=="string"?I=$.content:Array.isArray($.content)&&(I=$.content.filter(b=>b&&(b.type==="text"||typeof b=="string")).map(b=>typeof b=="string"?b:b.text||"").join("")));let H=I.slice(0,400),O=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,q=H.split(`
606
- `).find(b=>{let Y=b.trim();return Y.length>0&&Y.length<=30&&/^\d/.test(Y)&&/=/.test(Y)&&!/[a-zA-Z]/.test(Y)});if(O.test(H)||q){e-=1.5;let b=(q||H.split(`
607
- `)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${b}"`)}}if(d&&r>0){let $=t.findIndex(H=>H.role==="assistant"),I=t.findIndex(H=>!!(Array.isArray(H.tool_calls)&&H.tool_calls.length>0||Array.isArray(H.content)&&H.content.some(O=>O&&O.type==="tool_use")));if($!==-1&&I!==-1&&$<I){let H=t[$],O="";typeof H.content=="string"?O=H.content:Array.isArray(H.content)&&(O=H.content.filter(Y=>Y&&(Y.type==="text"||typeof Y=="string")).map(Y=>typeof Y=="string"?Y:Y.text||"").join(""));let q=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(O),b=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(O);(q||b)&&(e-=1,s.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(d){let $=f;if($.length>100){let H=($.match(/^```/gm)||[]).length%2!==0,O=/"\s*:\s*$/.test($.trimEnd()),q=/[,\[{]\s*$/.test($.trimEnd());(H||O||q)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let $=[];t.forEach((H,O)=>{let q=[];Array.isArray(H.tool_calls)&&H.tool_calls.forEach(b=>{if((b.function?.name||b.name||"")==="read_file"){let ke={};try{ke=typeof b.function?.arguments=="string"?JSON.parse(b.function.arguments):b.function?.arguments||{}}catch{}(ke.path||"").endsWith(".json")&&q.push({id:b.id,path:ke.path})}}),Array.isArray(H.content)&&H.content.forEach(b=>{b&&b.type==="tool_use"&&b.name==="read_file"&&(b.input?.path||"").endsWith(".json")&&q.push({id:b.id,path:b.input.path})}),q.forEach(b=>$.push({...b,msgIdx:O}))});let I=0;for(let H of $){let O=null;for(let b of t){if(b.role==="tool"&&b.tool_call_id===H.id&&typeof b.content=="string"){O=b.content;break}if(b.role==="user"&&Array.isArray(b.content)){let Y=b.content.find(ke=>ke&&ke.type==="tool_result"&&ke.tool_use_id===H.id);if(Y){O=typeof Y.content=="string"?Y.content:"";break}}}if(!O)continue;O.split(`
608
- `).filter(b=>b.trim()).length<5&&/^\s*\[/.test(O)&&!/\]\s*$/.test(O.trimEnd())&&I++}I>=1&&(e-=.75,s.push(`Shallow JSON read: ${I} .json file${I>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let $=o.filter(I=>/argument errors?/i.test(I.content)||/missing required (argument|parameter)/i.test(I.content)||/invalid argument/i.test(I.content));$.length>=3?(e-=.75,s.push(`Repeated tool argument errors: ${$.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):$.length>=2&&(e-=.25,s.push(`Tool argument errors: ${$.length} tool calls returned argument errors`))}{let $=!1,I=0,H=0;for(let O of a){if((O.name==="bash"||O.name==="Bash")&&O.input?.command&&/git\s+commit\b/.test(O.input.command)){$&&(H=Math.max(H,I)),$=!0,I=0;continue}$&&(O.name==="bash"||O.name==="Bash")&&O.input?.command&&/git\s+(status|diff|log|show)\b/.test(O.input.command)&&I++}H=Math.max(H,I),H>=3&&(e-=.75,s.push(`Post-commit verification waste: ${H} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let be=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",$e=s.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${s.length} issue${s.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:be,issues:s,summary:$e}}function sS(t){try{let{loadSession:e}=$i(),s=e(t);return s?sm(s.messages||[]):null}catch{return null}}function oS(t,e=null){let{score:s,issues:n}=t,o=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(s>=8||n.length===0)return"";let a=n.map(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(s>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
605
+ `)}async function GS(t){let e=Be.join(t,"package.json"),s="";if(await rn(()=>yt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await yt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([rn(async()=>{let{stdout:i}=await Ei("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),mm()]);if(r&&r.length>0){console.log(`${Ws.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ws.reset}`);for(let i of r)console.log(`${Ws.red} ${i.file}${Ws.reset}`);console.log(`${Ws.yellow} \u2192 Resolve conflicts before starting tasks${Ws.reset}`)}console.log()}gm.exports={gatherProjectContext:YS,printContext:GS,generateFileTree:US,_clearContextCache:()=>{pc.clear(),Ys.clear(),Ti=null,Hs={result:null,expiry:0,cwd:null}}}});var Ci=V((Z1,_m)=>{var Xt=require("fs"),Ri=require("path"),{atomicWrite:zS}=Hn();function Wo(){return Ri.join(process.cwd(),".nex","sessions")}function hc(){let t=Wo();Xt.existsSync(t)||Xt.mkdirSync(t,{recursive:!0,mode:448})}function mc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ri.join(Wo(),`${e}.json`)}function gc(t,e,s={}){hc();let n=mc(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return zS(n,JSON.stringify(o,null,2)),{path:n,name:t}}function wm(t){let e=mc(t);if(!Xt.existsSync(e))return null;try{return JSON.parse(Xt.readFileSync(e,"utf-8"))}catch{return null}}function $m(){hc();let t=Wo(),e=Xt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Xt.readFileSync(Ri.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function KS(t){let e=mc(t);return Xt.existsSync(e)?(Xt.unlinkSync(e),!0):!1}function XS(){let t=$m();return t.length===0?null:wm(t[0].name)}var is=null,_n=null,Uo=null;function VS(t,e={}){t.length!==0&&(is&&clearTimeout(is),_n=t,Uo=e||{},is=setTimeout(()=>{_n&&_n.length>0&&gc("_autosave",_n,Uo),is=null,_n=null,Uo=null},5e3))}function JS(){is&&(clearTimeout(is),is=null),_n&&_n.length>0&&(gc("_autosave",_n,Uo),_n=null,Uo=null)}function ZS(){hc();let t=Wo(),e=Xt.readdirSync(t).filter(r=>r.endsWith(".json")),s=new Date,n=new Date(s.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Ri.join(t,r);try{let a=Xt.statSync(i);new Date(a.mtime)<n&&(Xt.unlinkSync(i),o++)}catch{}}return o}_m.exports={saveSession:gc,loadSession:wm,listSessions:$m,deleteSession:KS,getLastSession:XS,autoSave:VS,flushAutoSave:JS,clearOldSessions:ZS,_getSessionsDir:Wo}});var Cm=V((Q1,Rm)=>{"use strict";var Ho=require("fs"),bm=require("path");function km(t){let e=[];return t.forEach((s,n)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:n,id:o.id||null})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:n,id:o.id||null})}))}),e}function QS(t){let e=new Set;return t.forEach(s=>{s.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&s.tool_call_id&&e.add(s.tool_call_id),s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_result"&&n.tool_use_id&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&e.add(n.tool_use_id)})}),e}function xm(t){let e=[];return t.forEach((s,n)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:n})}}),s.role==="tool"){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:o,index:n})}}),e}function Sm(t){for(let e=t.length-1;e>=0;e--){let s=t[e];if(s.role==="assistant"){if(typeof s.content=="string")return s.content.trim();if(Array.isArray(s.content)){let n=s.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(n)return n}}}return""}function Em(t,e){let s=[];for(let n=t.length-1;n>=0&&s.length<e;n--){let o=t[n];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&s.push(r)}return s}function vm(t){let e=new Map;for(let s of t){let n;try{n=JSON.stringify(s.input)}catch{n=String(s.input)}let o=`${s.name}|${n}`;e.set(o,(e.get(o)||0)+1)}return e}function Tm(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,s=[],n=km(t),o=xm(t),r=n.length,i=QS(t),a=n.filter(b=>!b.id||!i.has(b.id));t.some(b=>b.role==="user"&&typeof b.content=="string"&&b.content.startsWith("[SYSTEM WARNING]")&&(b.content.includes("edited")||b.content.includes("bash command")||b.content.includes("grep pattern")||b.content.includes("re-read")||b.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let c=n.find(b=>{let I=b.input?.command||b.input?.cmd||"";return/\bsed\s+-n\b/.test(I)});if(c){let b=(c.input?.command||c.input?.cmd||"").slice(0,80);o.some(H=>H.content.includes("BLOCKED: sed -n is forbidden")||H.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${b}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${b}`))}n.find(b=>{if(b.name!=="grep"&&b.name!=="bash"&&b.name!=="ssh_exec")return!1;let I=b.input?.command||b.input?.cmd||"",H=b.input?.pattern||"",N=`${I} ${H}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(N)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(N)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(b=>b.role==="assistant"),f=Sm(t),m=Em(t,3).some(b=>b.length>100&&!/^[^.!]{0,40}\?$/.test(b));if(d&&!m&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let b=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";s.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${b}`)}r>40?(e-=1.5,s.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,s.push(`High tool call count: ${r} (>25 threshold)`)),t.some(b=>{let I=typeof b.content=="string"?b.content:Array.isArray(b.content)?b.content.map(H=>typeof H=="string"?H:H.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(I)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let k=vm(a),M=0,D="";for(let[b,I]of k)I>M&&(M=I,D=b);if(M>=3){let[b]=D.split("|");e-=1,s.push(`Same tool call repeated ${M}\xD7 (tool: ${b})`)}let v=!1,E=t.findIndex(b=>b.role==="user"&&typeof b.content=="string"&&b.content.includes("[SYSTEM STOP]")&&b.content.includes('"valid":true'));E>=0&&n.filter(I=>I.index>E).length>0&&(v=!0),v&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let A=n.filter(b=>b.name==="ssh_exec");if(A.length>=8){let b=0,I=1;for(let H=1;H<A.length;H++)A[H].index<=A[H-1].index+2?I++:(b=Math.max(b,I),I=1);b=Math.max(b,I),b>=8&&(e-=.5,s.push(`SSH reconnect storm: ${b} consecutive SSH calls`))}d&&A.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,s.push("Surrender: model asked user to manually provide server output instead of gathering it"));let ee=new Map;for(let b of a)if(b.name==="read_file"&&b.input?.path){let I=b.input.path;ee.has(I)||ee.set(I,{count:0,ranges:[]});let H=ee.get(I);if(H.count++,b.input.line_start!=null){let N=b.input.line_start||1,L=b.input.line_end||N+350;H.ranges.push([N,L])}}function se(b,I,H){for(let[N,L]of H){let _=Math.max(b,N),J=Math.min(I,L);if(J>_){let de=J-_,fe=I-b||1;if(de/fe>=.7)return!0}}return!1}let ue=0,ae="";for(let[b,I]of ee){if(I.count<3)continue;if(I.ranges.length===I.count){let L=!1,_=[];for(let[J,de]of I.ranges){if(_.length>0&&se(J,de,_)){L=!0;break}_.push([J,de])}if(!L)continue}if(I.count-I.ranges.length<=2&&I.ranges.length>=1){let L=!1,_=[];for(let[J,de]of I.ranges){if(_.length>0&&se(J,de,_)){L=!0;break}_.push([J,de])}if(!L)continue}I.count>ue&&(ue=I.count,ae=b)}if(ue>=3){e-=1;let b=ae.split("/").slice(-2).join("/");s.push(`read_file loop: "${b}" read ${ue}\xD7 (file already in context)`)}let te=0,S="";for(let[b,I]of ee){if(I.ranges.length<4)continue;let H=[],N=!1;for(let[L,_]of I.ranges){if(H.length>0&&se(L,_,H)){N=!0;break}H.push([L,_])}!N&&I.ranges.length>te&&(te=I.ranges.length,S=b)}if(te>=4){e-=.5;let b=S.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${b}" read in ${te} sequential sections \u2014 use grep instead`)}let ve=new Map;for(let b of a)if(b.name==="grep"&&b.input?.path&&b.input?.pattern){let I=b.input.path;ve.has(I)||ve.set(I,new Set),ve.get(I).add(b.input.pattern)}let W=0,z="";for(let[b,I]of ve)b.split("/").pop().includes(".")&&I.size>W&&(W=I.size,z=b);if(W>=3){e-=.75;let b=z.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${b}" searched ${W}\xD7 with different patterns (file already in context)`)}{let b=new Set,I=new Set,H=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let L of n){if(L.name==="write_file"&&L.input?.path){let _=L.input.path.split("/").pop(),J=L.input.path.includes("/tests/");H.test(_)&&!J&&b.add(L.input.path)}if((L.name==="bash"||L.name==="ssh_exec")&&L.input?.command){let _=L.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(_)for(let J of _){let de=J.split(/\s+/),fe=de[de.length-1];for(let Je of b)(Je.endsWith(fe)||fe.endsWith(Je.split("/").pop()))&&I.add(Je)}}}let N=I.size;if(N>=1){let L=Math.min(N*.25,.5);e-=L;let _=[...I].map(J=>J.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${_} \u2014 write inline logic or use tests/ instead`)}}let me=o.filter(b=>b.content.startsWith("EXIT")).length;me>=10?(e-=1,s.push(`Bash exit-error storm: ${me} tool results started with EXIT (repeated failing commands)`)):me>=5&&(e-=.5,s.push(`Repeated bash errors: ${me} tool results with non-zero exit code`));for(let b of t){if(b.role!=="assistant")continue;let I="";if(typeof b.content=="string"?I=b.content:Array.isArray(b.content)&&(I=b.content.filter(fe=>fe&&(fe.type==="text"||typeof fe=="string")).map(fe=>typeof fe=="string"?fe:fe.text||"").join("")),I.length<=5e3)continue;let H=I.split(/(?<=\. )/).filter(fe=>fe.trim().length>0);if(H.length<6)continue;let N=new Map;for(let fe=0;fe<=H.length-3;fe++){let Je=H.slice(fe,fe+3).join("").trim();Je.length>30&&N.set(Je,(N.get(Je)||0)+1)}let L=0,_="";for(let[fe,Je]of N)Je>L&&(L=Je,_=fe);if(L<3)continue;let de=_.length*L/I.length;if(de>=.4||L>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${L}\xD7 same paragraph, ${Math.round(de*100)}% repeated)`);break}}{let b=new Set(["read_file","list_directory","search_files","glob","grep"]),I=t.some(N=>Array.isArray(N.tool_calls)?N.tool_calls.some(L=>b.has(L.function?.name)):Array.isArray(N.content)?N.content.some(L=>L.type==="tool_use"&&b.has(L.name)):!1);t.some(N=>N.role==="assistant"&&typeof N.content=="string"&&(N.content.includes("## Steps")||N.content.includes("/plan approve")))&&!I&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Ce=o.filter(b=>b.content.startsWith("BLOCKED:")&&!b.content.includes("BLOCKED: sed -n")&&!b.content.includes("SSH paused")&&!b.content.includes("SSH temporarily paused"));if(Ce.length>0){let b=Math.min(Ce.length*.5,1.5);e-=b,s.push(`${Ce.length} tool call${Ce.length===1?"":"s"} blocked (agent attempted denied actions)`)}let De=t.filter(b=>{let I=typeof b.content=="string"?b.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(I)}).length;if(De>0){let b=Math.min(De*1,2);e-=b,s.push(`Super-nuclear context wipe fired ${De}\xD7 (context collapse \u2014 task too large or read loops)`)}{let b=!1,I=!1,H=!1;for(let L of n){if(L.name!=="bash")continue;let _=(L.input?.command||L.input?.cmd||"").trim();!(/cat\s*>/.test(_)||/<</.test(_))&&/\bcat\s+\S/.test(_)&&(b=!0),/^\s*ls(\s|$)/.test(_)&&!/npm|yarn|pnpm|make|git\b/.test(_)&&(I=!0),/\bfind\s+\S/.test(_)&&!/git\b|npm\b|-exec\b/.test(_)&&(H=!0)}let N=[b,I,H].filter(Boolean).length;if(N>0){let L=Math.min(N*.25,.75);e-=L;let _=[];b&&_.push("cat (use read_file)"),I&&_.push("ls (use list_directory)"),H&&_.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${_.join(", ")}`)}}{let b=n.some(_=>(_.name==="write_file"||_.name==="Write")&&_.input?.path&&(_.input.path.endsWith("requirements.txt")||_.input.path.endsWith("Pipfile")||_.input.path.endsWith("pyproject.toml"))),I=n.some(_=>(_.name==="write_file"||_.name==="Write")&&_.input?.path&&_.input.path.endsWith("package.json")),H=n.filter(_=>(_.name==="bash"||_.name==="Bash")&&_.input?.command).map(_=>_.input.command),N=H.some(_=>/pip\s+install|python\s+-m\s+venv/.test(_)),L=H.some(_=>/npm\s+install/.test(_));b&&!N?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):I&&!L&&n.some(J=>(J.name==="write_file"||J.name==="Write")&&J.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(J.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let b=t.find(_=>_.role==="assistant"),I="";b&&(typeof b.content=="string"?I=b.content:Array.isArray(b.content)&&(I=b.content.filter(_=>_&&(_.type==="text"||typeof _=="string")).map(_=>typeof _=="string"?_:_.text||"").join("")));let H=I.slice(0,400),N=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,L=H.split(`
606
+ `).find(_=>{let J=_.trim();return J.length>0&&J.length<=30&&/^\d/.test(J)&&/=/.test(J)&&!/[a-zA-Z]/.test(J)});if(N.test(H)||L){e-=1.5;let _=(L||H.split(`
607
+ `)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${_}"`)}}if(d&&r>0){let b=t.findIndex(H=>H.role==="assistant"),I=t.findIndex(H=>!!(Array.isArray(H.tool_calls)&&H.tool_calls.length>0||Array.isArray(H.content)&&H.content.some(N=>N&&N.type==="tool_use")));if(b!==-1&&I!==-1&&b<I){let H=t[b],N="";typeof H.content=="string"?N=H.content:Array.isArray(H.content)&&(N=H.content.filter(J=>J&&(J.type==="text"||typeof J=="string")).map(J=>typeof J=="string"?J:J.text||"").join(""));let L=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(N),_=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(N);(L||_)&&(e-=1,s.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(d){let b=f;if(b.length>100){let H=(b.match(/^```/gm)||[]).length%2!==0,N=/"\s*:\s*$/.test(b.trimEnd()),L=/[,\[{]\s*$/.test(b.trimEnd());(H||N||L)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let b=[];t.forEach((H,N)=>{let L=[];Array.isArray(H.tool_calls)&&H.tool_calls.forEach(_=>{if((_.function?.name||_.name||"")==="read_file"){let de={};try{de=typeof _.function?.arguments=="string"?JSON.parse(_.function.arguments):_.function?.arguments||{}}catch{}(de.path||"").endsWith(".json")&&L.push({id:_.id,path:de.path})}}),Array.isArray(H.content)&&H.content.forEach(_=>{_&&_.type==="tool_use"&&_.name==="read_file"&&(_.input?.path||"").endsWith(".json")&&L.push({id:_.id,path:_.input.path})}),L.forEach(_=>b.push({..._,msgIdx:N}))});let I=0;for(let H of b){let N=null;for(let _ of t){if(_.role==="tool"&&_.tool_call_id===H.id&&typeof _.content=="string"){N=_.content;break}if(_.role==="user"&&Array.isArray(_.content)){let J=_.content.find(de=>de&&de.type==="tool_result"&&de.tool_use_id===H.id);if(J){N=typeof J.content=="string"?J.content:"";break}}}if(!N)continue;N.split(`
608
+ `).filter(_=>_.trim()).length<5&&/^\s*\[/.test(N)&&!/\]\s*$/.test(N.trimEnd())&&I++}I>=1&&(e-=.75,s.push(`Shallow JSON read: ${I} .json file${I>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let b=o.filter(I=>/argument errors?/i.test(I.content)||/missing required (argument|parameter)/i.test(I.content)||/invalid argument/i.test(I.content));b.length>=3?(e-=.75,s.push(`Repeated tool argument errors: ${b.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):b.length>=2&&(e-=.25,s.push(`Tool argument errors: ${b.length} tool calls returned argument errors`))}{let b=!1,I=0,H=0;for(let N of a){if((N.name==="bash"||N.name==="Bash")&&N.input?.command&&/git\s+commit\b/.test(N.input.command)){b&&(H=Math.max(H,I)),b=!0,I=0;continue}b&&(N.name==="bash"||N.name==="Bash")&&N.input?.command&&/git\s+(status|diff|log|show)\b/.test(N.input.command)&&I++}H=Math.max(H,I),H>=3&&(e-=.75,s.push(`Post-commit verification waste: ${H} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let ke=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",be=s.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${s.length} issue${s.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:ke,issues:s,summary:be}}function eE(t){try{let{loadSession:e}=Ci(),s=e(t);return s?Tm(s.messages||[]):null}catch{return null}}function tE(t,e=null){let{score:s,issues:n}=t,o=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(s>=8||n.length===0)return"";let a=n.map(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(s>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
609
609
  ${o}${f}${r}`}let l="";for(let u of a.slice(0,4))l+=`
610
610
  ${i}\u26A0${r} ${o}${u}${r}`;let c=a.length-4;return c>0&&(l+=`
611
- ${o}(+${c} more)${r}`),l}function rS(t,e={}){try{let s=Jp.join(process.cwd(),".nex");jo.existsSync(s)||jo.mkdirSync(s,{recursive:!0});let n=Jp.join(s,"benchmark-history.json"),o=[];if(jo.existsSync(n))try{o=JSON.parse(jo.readFileSync(n,"utf-8"))}catch{o=[]}Array.isArray(o)||(o=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};o.push(i),o.length>100&&(o=o.slice(o.length-100)),jo.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}om.exports={scoreMessages:sm,scoreSession:sS,formatScore:oS,appendScoreHistory:rS,_extractToolCalls:Zp,_extractToolResults:Qp,_getLastAssistantText:em,_getLastNAssistantTexts:tm,_countDuplicateToolCalls:nm}});var Bo=Z((e1,um)=>{"use strict";var iS=require("os"),sc=require("path"),vn=require("fs"),qo=sc.join(iS.homedir(),".nex-code","model-routing.json"),bi={frontend:{id:"frontend",label:"Frontend",icon:"\u2B21",envVar:"NEX_ROUTE_FRONTEND",pattern:/\b(react|vue|angular|svelte|jsx|tsx|html|css|scss|sass|tailwind|bootstrap|component|dom\b|ui\s|button|modal|navbar|sidebar|stylesheet|responsive|flexbox|grid|animation|frontend|front.end|onclick|hover|transition|web\s+design|landing\s+page|browser\s+event)\b/i},sysadmin:{id:"sysadmin",label:"Sysadmin",icon:"\u2699",envVar:"NEX_ROUTE_SYSADMIN",pattern:/\b(nginx|apache|docker|kubernetes|k8s|systemd|systemctl|deploy(ment)?|server\s+config|firewall|iptables\b|ssh\s+key|cron(job)?|ansible|terraform|ci\/cd|pipeline|container\b|pod\b|apt\s+install|yum\s+install|daemon|pm2|supervisor|logrotate|ssl\s+cert|lets.encrypt|reverse\s+proxy|load\s+balanc|haproxy|vhost|virtual\s+host)\b/i},data:{id:"data",label:"Data",icon:"\u2B21",envVar:"NEX_ROUTE_DATA",pattern:/\b(sql\b|mysql|postgres(ql)?|sqlite|mongodb|redis\b|query\b|database|db\s+migration|schema\s+change|table\s+join|aggregate\b|pandas\b|dataframe|\.csv\b|etl\b|data\s+transform|data\s+pipeline|analytics|data\s+warehouse|dbt\b|orm\b|knex|sequelize|prisma\s+schema)\b/i},agentic:{id:"agentic",label:"Agentic",icon:"\u2B21",envVar:"NEX_ROUTE_AGENTIC",pattern:/\b(spawn\s+agent|agent\s+swarm|multi.?agent|parallel\s+agent|orchestrat|coordinate\s+multiple\s+agent|delegate.+agent|sub.?agent|architect.*coder)\b/i},coding:{id:"coding",label:"Coding",icon:"\u2B21",envVar:"NEX_ROUTE_CODING",pattern:null}},im=["agentic","frontend","sysadmin","data","coding"];function aS(t){if(!t||t.length<8)return null;for(let e of im){let s=bi[e];if(!s.pattern||s.pattern.test(t))return s}return bi.coding}function Fo(){try{if(vn.existsSync(qo))return JSON.parse(vn.readFileSync(qo,"utf-8"))}catch{}return{}}function am(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=bi[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Fo()[t]||null}var lm={explore:10,plan:10,implement:35,verify:8},oc={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function cm(){let t=Fo();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=ot();if(e()==="ollama")return oc}catch{}return process.env.NEX_PHASE_ROUTING==="1"?oc:null}function lS(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let s=cm();return s?.[t]?s[t]:e?am(e):null}function cS(t){return Fo().phaseBudgets?.[t]||lm[t]||20}function uS(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:cm()!==null}function dS(t){let e=sc.dirname(qo);vn.existsSync(e)||vn.mkdirSync(e,{recursive:!0});let s=Fo(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),vn.writeFileSync(qo,JSON.stringify(n,null,2));try{let o=sc.join(e,".env"),r="";vn.existsSync(o)&&(r=vn.readFileSync(o,"utf-8"));let i=r.split(/\r?\n/),a=(l,c)=>{let u=i.findIndex(d=>d.startsWith(l+"="));u>=0?i[u]=`${l}=${c}`:i.push(`${l}=${c}`)};n.coding&&a("NEX_ROUTE_CODING",n.coding),n.frontend&&a("NEX_ROUTE_FRONTEND",n.frontend),n.sysadmin&&a("NEX_ROUTE_SYSADMIN",n.sysadmin),n.data&&a("NEX_ROUTE_DATA",n.data),n.agentic&&a("NEX_ROUTE_AGENTIC",n.agentic),n.phases&&(n.phases.plan&&a("NEX_PHASE_PLAN_MODEL",n.phases.plan),n.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",n.phases.implement),n.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",n.phases.verify)),vn.writeFileSync(o,i.filter(l=>l.trim()!=="").join(`
611
+ ${o}(+${c} more)${r}`),l}function nE(t,e={}){try{let s=bm.join(process.cwd(),".nex");Ho.existsSync(s)||Ho.mkdirSync(s,{recursive:!0});let n=bm.join(s,"benchmark-history.json"),o=[];if(Ho.existsSync(n))try{o=JSON.parse(Ho.readFileSync(n,"utf-8"))}catch{o=[]}Array.isArray(o)||(o=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};o.push(i),o.length>100&&(o=o.slice(o.length-100)),Ho.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}Rm.exports={scoreMessages:Tm,scoreSession:eE,formatScore:tE,appendScoreHistory:nE,_extractToolCalls:km,_extractToolResults:xm,_getLastAssistantText:Sm,_getLastNAssistantTexts:Em,_countDuplicateToolCalls:vm}});var zo=V((eC,Pm)=>{"use strict";var sE=require("os"),yc=require("path"),Mn=require("fs"),Yo=yc.join(sE.homedir(),".nex-code","model-routing.json"),Ai={frontend:{id:"frontend",label:"Frontend",icon:"\u2B21",envVar:"NEX_ROUTE_FRONTEND",pattern:/\b(react|vue|angular|svelte|jsx|tsx|html|css|scss|sass|tailwind|bootstrap|component|dom\b|ui\s|button|modal|navbar|sidebar|stylesheet|responsive|flexbox|grid|animation|frontend|front.end|onclick|hover|transition|web\s+design|landing\s+page|browser\s+event)\b/i},sysadmin:{id:"sysadmin",label:"Sysadmin",icon:"\u2699",envVar:"NEX_ROUTE_SYSADMIN",pattern:/\b(nginx|apache|docker|kubernetes|k8s|systemd|systemctl|deploy(ment)?|server\s+config|firewall|iptables\b|ssh\s+key|cron(job)?|ansible|terraform|ci\/cd|pipeline|container\b|pod\b|apt\s+install|yum\s+install|daemon|pm2|supervisor|logrotate|ssl\s+cert|lets.encrypt|reverse\s+proxy|load\s+balanc|haproxy|vhost|virtual\s+host)\b/i},data:{id:"data",label:"Data",icon:"\u2B21",envVar:"NEX_ROUTE_DATA",pattern:/\b(sql\b|mysql|postgres(ql)?|sqlite|mongodb|redis\b|query\b|database|db\s+migration|schema\s+change|table\s+join|aggregate\b|pandas\b|dataframe|\.csv\b|etl\b|data\s+transform|data\s+pipeline|analytics|data\s+warehouse|dbt\b|orm\b|knex|sequelize|prisma\s+schema)\b/i},agentic:{id:"agentic",label:"Agentic",icon:"\u2B21",envVar:"NEX_ROUTE_AGENTIC",pattern:/\b(spawn\s+agent|agent\s+swarm|multi.?agent|parallel\s+agent|orchestrat|coordinate\s+multiple\s+agent|delegate.+agent|sub.?agent|architect.*coder)\b/i},coding:{id:"coding",label:"Coding",icon:"\u2B21",envVar:"NEX_ROUTE_CODING",pattern:null}},Am=["agentic","frontend","sysadmin","data","coding"];function oE(t){if(!t||t.length<8)return null;for(let e of Am){let s=Ai[e];if(!s.pattern||s.pattern.test(t))return s}return Ai.coding}function Go(){try{if(Mn.existsSync(Yo))return JSON.parse(Mn.readFileSync(Yo,"utf-8"))}catch{}return{}}function Om(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=Ai[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Go()[t]||null}var Nm={explore:10,plan:10,implement:35,verify:8},wc={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Mm(){let t=Go();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=lt();if(e()==="ollama")return wc}catch{}return process.env.NEX_PHASE_ROUTING==="1"?wc:null}function rE(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let s=Mm();return s?.[t]?s[t]:e?Om(e):null}function iE(t){return Go().phaseBudgets?.[t]||Nm[t]||20}function aE(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:Mm()!==null}function lE(t){let e=yc.dirname(Yo);Mn.existsSync(e)||Mn.mkdirSync(e,{recursive:!0});let s=Go(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),Mn.writeFileSync(Yo,JSON.stringify(n,null,2));try{let o=yc.join(e,".env"),r="";Mn.existsSync(o)&&(r=Mn.readFileSync(o,"utf-8"));let i=r.split(/\r?\n/),a=(l,c)=>{let u=i.findIndex(d=>d.startsWith(l+"="));u>=0?i[u]=`${l}=${c}`:i.push(`${l}=${c}`)};n.coding&&a("NEX_ROUTE_CODING",n.coding),n.frontend&&a("NEX_ROUTE_FRONTEND",n.frontend),n.sysadmin&&a("NEX_ROUTE_SYSADMIN",n.sysadmin),n.data&&a("NEX_ROUTE_DATA",n.data),n.agentic&&a("NEX_ROUTE_AGENTIC",n.agentic),n.phases&&(n.phases.plan&&a("NEX_PHASE_PLAN_MODEL",n.phases.plan),n.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",n.phases.implement),n.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",n.phases.verify)),Mn.writeFileSync(o,i.filter(l=>l.trim()!=="").join(`
612
612
  `)+`
613
- `)}catch{}}um.exports={CATEGORIES:bi,DETECTION_ORDER:im,detectCategory:aS,getModelForCategory:am,getModelForPhase:lS,getPhaseBudget:cS,isPhaseRoutingEnabled:uS,DEFAULT_PHASE_BUDGETS:lm,BUILTIN_PHASE_DEFAULTS:oc,saveRoutingConfig:dS,loadRoutingConfig:Fo,ROUTING_CONFIG_PATH:qo}});var pm=Z((t1,hm)=>{"use strict";var ts=require("fs"),Uo=require("path"),fS=require("os"),{detectCategory:hS}=Bo(),Ws=Uo.join(fS.homedir(),".nex-code","examples"),rc=Uo.join(__dirname,"..","examples");function dm(t){try{let s=ts.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),n=s.match(/^user:\s*(.+)$/m);if(!n)return null;let o=n[1].trim(),r=s.indexOf(`
613
+ `)}catch{}}Pm.exports={CATEGORIES:Ai,DETECTION_ORDER:Am,detectCategory:oE,getModelForCategory:Om,getModelForPhase:rE,getPhaseBudget:iE,isPhaseRoutingEnabled:aE,DEFAULT_PHASE_BUDGETS:Nm,BUILTIN_PHASE_DEFAULTS:wc,saveRoutingConfig:lE,loadRoutingConfig:Go,ROUTING_CONFIG_PATH:Yo}});var Dm=V((tC,jm)=>{"use strict";var as=require("fs"),Ko=require("path"),cE=require("os"),{detectCategory:uE}=zo(),Gs=Ko.join(cE.homedir(),".nex-code","examples"),$c=Ko.join(__dirname,"..","examples");function Lm(t){try{let s=as.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),n=s.match(/^user:\s*(.+)$/m);if(!n)return null;let o=n[1].trim(),r=s.indexOf(`
614
614
  A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],l=0;for(let u of i.split(`
615
615
  `))if(u.startsWith(" ")){for(;l>0;)a.push(""),l--;a.push(u.slice(2))}else if(u.trim()==="")a.length>0&&l++;else break;if(a.length===0)return null;let c=a.join(`
616
- `).trim();return{user:o,assistant:c}}catch{return null}}function fm(t){let e=`${t}.md`,s=Uo.join(Ws,e);if(ts.existsSync(s)){let o=dm(s);if(o)return o}let n=Uo.join(rc,e);return ts.existsSync(n)?dm(n):null}function pS(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=hS(t);return!e||e.id==="coding"&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port)\b/i.test(t)?null:fm(e.id)}function mS(){let t=new Set;for(let e of[Ws,rc])try{for(let s of ts.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function gS(t,e){ts.existsSync(Ws)||ts.mkdirSync(Ws,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
616
+ `).trim();return{user:o,assistant:c}}catch{return null}}function Im(t){let e=`${t}.md`,s=Ko.join(Gs,e);if(as.existsSync(s)){let o=Lm(s);if(o)return o}let n=Ko.join($c,e);return as.existsSync(n)?Lm(n):null}function dE(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=uE(t);return!e||e.id==="coding"&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port)\b/i.test(t)?null:Im(e.id)}function fE(){let t=new Set;for(let e of[Gs,$c])try{for(let s of as.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function pE(t,e){as.existsSync(Gs)||as.mkdirSync(Gs,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
617
617
 
618
618
  user: ${e.user}
619
619
 
@@ -621,14 +621,14 @@ A: |
621
621
  ${e.assistant.split(`
622
622
  `).map(n=>` ${n}`).join(`
623
623
  `)}
624
- `;ts.writeFileSync(Uo.join(Ws,`${t}.md`),s,"utf-8")}hm.exports={getFewShotForInput:pS,loadExampleForCategory:fm,listAvailableExamples:mS,savePrivateExample:gS,PRIVATE_EXAMPLES_DIR:Ws,BUNDLED_EXAMPLES_DIR:rc}});var $m=Z((s1,_m)=>{var St=require("fs"),Hs=require("path"),{C:n1}=Je(),{atomicWrite:yS,withFileLockSync:wS}=jn(),ki={bash:"ask",read_file:"allow",write_file:"ask",edit_file:"ask",list_directory:"allow",search_files:"allow",glob:"allow",grep:"allow",patch_file:"ask",web_fetch:"allow",web_search:"allow",ask_user:"allow",task_list:"allow",spawn_agents:"ask",ssh_exec:"allow",ssh_upload:"ask",ssh_download:"ask"},Ys={...ki};function mm(){let t=Hs.join(process.cwd(),".nex","config.json");if(St.existsSync(t))try{let e=JSON.parse(St.readFileSync(t,"utf-8"));e.permissions&&(Ys={...ki,...e.permissions})}catch{}}function _S(){let t=Hs.join(process.cwd(),".nex"),e=Hs.join(t,"config.json");St.existsSync(t)||St.mkdirSync(t,{recursive:!0}),wS(e,()=>{let s={};if(St.existsSync(e))try{s=JSON.parse(St.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Ys,yS(e,JSON.stringify(s,null,2))})}function gm(t){return Ys[t]||"ask"}function $S(t,e){return["allow","ask","deny"].includes(e)?(Ys[t]=e,!0):!1}function bS(t){return gm(t)}function kS(){return Object.entries(Ys).map(([t,e])=>({tool:t,mode:e}))}function xS(){Ys={...ki}}var Wo={readonly:{description:"Read-only access \u2014 can search and read but not modify",allowedTools:["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","ask_user","web_fetch","web_search","browser_open","browser_screenshot","task_list"],blockedTools:["bash","write_file","edit_file","patch_file","deploy","ssh_exec","service_manage","container_manage","container_exec","remote_agent"],autoConfirm:!1,allowDangerous:!1},developer:{description:"Standard developer access \u2014 can read, write, and run commands",allowedTools:null,blockedTools:["deploy","service_manage","container_manage","remote_agent"],autoConfirm:!1,allowDangerous:!1},admin:{description:"Full access \u2014 all tools, including deployment and infrastructure",allowedTools:null,blockedTools:[],autoConfirm:!1,allowDangerous:!0}};function ym(){let t=Hs.join(process.cwd(),".nex","config.json");try{return St.existsSync(t)&&JSON.parse(St.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function SS(t){let e=Hs.join(process.cwd(),".nex"),s=Hs.join(e,"config.json");St.existsSync(e)||St.mkdirSync(e,{recursive:!0});let n={};try{St.existsSync(s)&&(n=JSON.parse(St.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,St.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function wm(){let t=ym();if(!t)return Wo.admin;let e=t.role||"admin",s=Wo[e]||Wo.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function ES(t){let e=wm();return e.blockedTools&&e.blockedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is blocked by permission preset "${e.description||"custom"}"`}:e.allowedTools&&!e.allowedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is not in the allowed list for this permission level`}:{allowed:!0}}function vS(){return Object.entries(Wo).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}mm();_m.exports={getPermission:gm,setPermission:$S,checkPermission:bS,listPermissions:kS,loadPermissions:mm,savePermissions:_S,resetPermissions:xS,DEFAULT_PERMISSIONS:ki,PERMISSION_PRESETS:Wo,loadPresetConfig:ym,savePresetConfig:SS,getEffectivePreset:wm,isToolAllowed:ES,listPresets:vS}});var Ei=Z((r1,Em)=>{var ss=require("fs"),xi=require("path"),o1=require("readline"),{C:Te}=Je(),Se=null,ac=!1,lc=null,bm=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Si(){return xi.join(process.cwd(),".nex","plans")}function km(){let t=Si();ss.existsSync(t)||ss.mkdirSync(t,{recursive:!0})}function TS(t,e=[]){return Se={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Se}function RS(){return Se}function CS(t){ac=t}function AS(){return ac}function OS(){return!Se||Se.status!=="draft"?!1:(Se.status="approved",Se.updatedAt=new Date().toISOString(),!0)}function NS(){return!Se||Se.status!=="approved"?!1:(Se.status="executing",!0)}function ic(t,e){return!Se||t<0||t>=Se.steps.length?!1:(Se.steps[t].status=e,Se.updatedAt=new Date().toISOString(),Se.steps.every(s=>s.status==="done"||s.status==="skipped")&&(Se.status="completed"),!0)}function MS(t){if(!t)return`${Te.dim}No active plan${Te.reset}`;let e={draft:`${Te.yellow}DRAFT${Te.reset}`,approved:`${Te.green}APPROVED${Te.reset}`,executing:`${Te.blue}EXECUTING${Te.reset}`,completed:`${Te.green}COMPLETED${Te.reset}`},s=[];s.push(`
625
- ${Te.bold}${Te.cyan}Plan: ${t.task}${Te.reset}`),s.push(`${Te.dim}Status: ${e[t.status]||t.status}${Te.reset}
626
- `);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${Te.green}\u2713${Te.reset}`;break;case"in_progress":r=`${Te.blue}\u2192${Te.reset}`;break;case"skipped":r=`${Te.dim}\u25CB${Te.reset}`;break;default:r=`${Te.dim} ${Te.reset}`}s.push(` ${r} ${Te.bold}Step ${n+1}:${Te.reset} ${o.description}`),o.files.length>0&&s.push(` ${Te.dim}Files: ${o.files.join(", ")}${Te.reset}`)}return s.push(""),s.join(`
627
- `)}function PS(t){if(t||(t=Se),!t)return null;km();let e=xi.join(Si(),`${t.name}.json`);return ss.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function LS(t){let e=xi.join(Si(),`${t}.json`);if(!ss.existsSync(e))return null;try{let s=JSON.parse(ss.readFileSync(e,"utf-8"));return Se=s,s}catch{return null}}function IS(){km();let t=Si(),e=ss.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(ss.readFileSync(xi.join(t,n),"utf-8"));s.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return s.sort((n,o)=>(o.createdAt||"").localeCompare(n.createdAt||""))}function DS(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),n=s?s[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(n))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let l=0;l<Math.min(e.length,a.length);l++){let c=a[l][1];e[l].files=c.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function jS(t){lc=t}function qS(){return lc}function FS(){Se=null,ac=!1,lc=null,HS()}function BS(){return`
624
+ `;as.writeFileSync(Ko.join(Gs,`${t}.md`),s,"utf-8")}jm.exports={getFewShotForInput:dE,loadExampleForCategory:Im,listAvailableExamples:fE,savePrivateExample:pE,PRIVATE_EXAMPLES_DIR:Gs,BUNDLED_EXAMPLES_DIR:$c}});var Hm=V((sC,Wm)=>{var Rt=require("fs"),zs=require("path"),{C:nC}=tt(),{atomicWrite:hE,withFileLockSync:mE}=Hn(),Oi={bash:"ask",read_file:"allow",write_file:"ask",edit_file:"ask",list_directory:"allow",search_files:"allow",glob:"allow",grep:"allow",patch_file:"ask",web_fetch:"allow",web_search:"allow",ask_user:"allow",task_list:"allow",spawn_agents:"ask",ssh_exec:"allow",ssh_upload:"ask",ssh_download:"ask"},Ks={...Oi};function qm(){let t=zs.join(process.cwd(),".nex","config.json");if(Rt.existsSync(t))try{let e=JSON.parse(Rt.readFileSync(t,"utf-8"));e.permissions&&(Ks={...Oi,...e.permissions})}catch{}}function gE(){let t=zs.join(process.cwd(),".nex"),e=zs.join(t,"config.json");Rt.existsSync(t)||Rt.mkdirSync(t,{recursive:!0}),mE(e,()=>{let s={};if(Rt.existsSync(e))try{s=JSON.parse(Rt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Ks,hE(e,JSON.stringify(s,null,2))})}function Fm(t){return Ks[t]||"ask"}function yE(t,e){return["allow","ask","deny"].includes(e)?(Ks[t]=e,!0):!1}function wE(t){return Fm(t)}function $E(){return Object.entries(Ks).map(([t,e])=>({tool:t,mode:e}))}function _E(){Ks={...Oi}}var Xo={readonly:{description:"Read-only access \u2014 can search and read but not modify",allowedTools:["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","ask_user","web_fetch","web_search","browser_open","browser_screenshot","task_list"],blockedTools:["bash","write_file","edit_file","patch_file","deploy","ssh_exec","service_manage","container_manage","container_exec","remote_agent"],autoConfirm:!1,allowDangerous:!1},developer:{description:"Standard developer access \u2014 can read, write, and run commands",allowedTools:null,blockedTools:["deploy","service_manage","container_manage","remote_agent"],autoConfirm:!1,allowDangerous:!1},admin:{description:"Full access \u2014 all tools, including deployment and infrastructure",allowedTools:null,blockedTools:[],autoConfirm:!1,allowDangerous:!0}};function Bm(){let t=zs.join(process.cwd(),".nex","config.json");try{return Rt.existsSync(t)&&JSON.parse(Rt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function bE(t){let e=zs.join(process.cwd(),".nex"),s=zs.join(e,"config.json");Rt.existsSync(e)||Rt.mkdirSync(e,{recursive:!0});let n={};try{Rt.existsSync(s)&&(n=JSON.parse(Rt.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,Rt.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function Um(){let t=Bm();if(!t)return Xo.admin;let e=t.role||"admin",s=Xo[e]||Xo.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function kE(t){let e=Um();return e.blockedTools&&e.blockedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is blocked by permission preset "${e.description||"custom"}"`}:e.allowedTools&&!e.allowedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is not in the allowed list for this permission level`}:{allowed:!0}}function xE(){return Object.entries(Xo).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}qm();Wm.exports={getPermission:Fm,setPermission:yE,checkPermission:wE,listPermissions:$E,loadPermissions:qm,savePermissions:gE,resetPermissions:_E,DEFAULT_PERMISSIONS:Oi,PERMISSION_PRESETS:Xo,loadPresetConfig:Bm,savePresetConfig:bE,getEffectivePreset:Um,isToolAllowed:kE,listPresets:xE}});var Pi=V((rC,Xm)=>{var cs=require("fs"),Ni=require("path"),oC=require("readline"),{C:Re}=tt(),Ee=null,bc=!1,kc=null,Ym=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Mi(){return Ni.join(process.cwd(),".nex","plans")}function Gm(){let t=Mi();cs.existsSync(t)||cs.mkdirSync(t,{recursive:!0})}function SE(t,e=[]){return Ee={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Ee}function EE(){return Ee}function vE(t){bc=t}function TE(){return bc}function RE(){return!Ee||Ee.status!=="draft"?!1:(Ee.status="approved",Ee.updatedAt=new Date().toISOString(),!0)}function CE(){return!Ee||Ee.status!=="approved"?!1:(Ee.status="executing",!0)}function _c(t,e){return!Ee||t<0||t>=Ee.steps.length?!1:(Ee.steps[t].status=e,Ee.updatedAt=new Date().toISOString(),Ee.steps.every(s=>s.status==="done"||s.status==="skipped")&&(Ee.status="completed"),!0)}function AE(t){if(!t)return`${Re.dim}No active plan${Re.reset}`;let e={draft:`${Re.yellow}DRAFT${Re.reset}`,approved:`${Re.green}APPROVED${Re.reset}`,executing:`${Re.blue}EXECUTING${Re.reset}`,completed:`${Re.green}COMPLETED${Re.reset}`},s=[];s.push(`
625
+ ${Re.bold}${Re.cyan}Plan: ${t.task}${Re.reset}`),s.push(`${Re.dim}Status: ${e[t.status]||t.status}${Re.reset}
626
+ `);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${Re.green}\u2713${Re.reset}`;break;case"in_progress":r=`${Re.blue}\u2192${Re.reset}`;break;case"skipped":r=`${Re.dim}\u25CB${Re.reset}`;break;default:r=`${Re.dim} ${Re.reset}`}s.push(` ${r} ${Re.bold}Step ${n+1}:${Re.reset} ${o.description}`),o.files.length>0&&s.push(` ${Re.dim}Files: ${o.files.join(", ")}${Re.reset}`)}return s.push(""),s.join(`
627
+ `)}function OE(t){if(t||(t=Ee),!t)return null;Gm();let e=Ni.join(Mi(),`${t.name}.json`);return cs.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function NE(t){let e=Ni.join(Mi(),`${t}.json`);if(!cs.existsSync(e))return null;try{let s=JSON.parse(cs.readFileSync(e,"utf-8"));return Ee=s,s}catch{return null}}function ME(){Gm();let t=Mi(),e=cs.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(cs.readFileSync(Ni.join(t,n),"utf-8"));s.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return s.sort((n,o)=>(o.createdAt||"").localeCompare(n.createdAt||""))}function PE(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),n=s?s[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(n))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let l=0;l<Math.min(e.length,a.length);l++){let c=a[l][1];e[l].files=c.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function LE(t){kc=t}function IE(){return kc}function jE(){Ee=null,bc=!1,kc=null,BE()}function DE(){return`
628
628
  PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
629
629
 
630
630
  # Allowed Tools (read-only)
631
- You may ONLY use these tools: ${[...bm].join(", ")}
631
+ You may ONLY use these tools: ${[...Ym].join(", ")}
632
632
  Any other tool call will be blocked and returned with an error.
633
633
 
634
634
  # MANDATORY: Read Before You Plan
@@ -649,6 +649,13 @@ Thoroughly investigate before writing a plan:
649
649
  - Architecture: How does the current code work? What patterns does it follow?
650
650
  - Dependencies: What depends on the code being changed? What might break?
651
651
  - Tests: What test coverage exists? What new tests are needed?
652
+ - Retrieval: Which 2-5 files are the highest-confidence targets? Start there instead of broad scans.
653
+
654
+ # Precision Rules
655
+ - Use the repo map, package scripts, and symbol/definition hints from context before searching blindly.
656
+ - Prefer one focused glob/grep/search followed by narrow reads over many overlapping reads.
657
+ - Each step must name a concrete verification action when applicable (test, lint, typecheck, benchmark, or a specific manual check).
658
+ - If the task is a bug fix, identify the current failing path first and include the smallest safe verification loop.
652
659
 
653
660
  # Required Plan Format
654
661
  After analysis, output a plan in this exact markdown format:
@@ -661,6 +668,7 @@ Numbered list. Each step:
661
668
  - **What**: Clear description of the change
662
669
  - **Where**: Specific file(s) and line ranges
663
670
  - **How**: Implementation approach (edit, create, delete)
671
+ - **Verify**: Exact command or check that proves the step worked
664
672
 
665
673
  ## Files Affected
666
674
  Bullet list of all files that will be modified or created.
@@ -672,26 +680,26 @@ Bullet list of potential issues and mitigations.
672
680
  - Order steps by dependency (later steps may depend on earlier ones).
673
681
  - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
674
682
  - Do NOT make any file changes \u2014 your role is analysis and planning only.
675
- - Do NOT call ask_user. If anything is ambiguous, add an "## Assumptions" section to the plan and state your assumption. The user approves or rejects the whole plan \u2014 that is the only gate.`}var ns=0;function US(){!Se||Se.status!=="executing"||(ns>0&&ic(ns-1,"done"),ns<Se.steps.length&&(ic(ns,"in_progress"),ns++))}function WS(){if(!Se||Se.status!=="executing"||Se.steps.length===0)return null;let t=Math.min(ns,Se.steps.length),e=Se.steps.length,s=Math.max(0,t-1),n=Se.steps[s]?.description||"";return{current:t,total:e,description:n}}function HS(){ns=0}var xm=["interactive","semi-auto","autonomous"],Sm="interactive";function YS(t){return xm.includes(t)?(Sm=t,!0):!1}function GS(){return Sm}Em.exports={createPlan:TS,getActivePlan:RS,setPlanMode:CS,isPlanMode:AS,approvePlan:OS,startExecution:NS,updateStep:ic,formatPlan:MS,savePlan:PS,loadPlan:LS,listPlans:IS,clearPlan:FS,getPlanModePrompt:BS,setPlanContent:jS,getPlanContent:qS,extractStepsFromText:DS,advancePlanStep:US,getPlanStepInfo:WS,PLAN_MODE_ALLOWED_TOOLS:bm,setAutonomyLevel:YS,getAutonomyLevel:GS,AUTONOMY_LEVELS:xm}});var Im=Z((i1,Lm)=>{var{C:x}=Je();function vm(){return Math.max(10,(process.stdout.columns||80)-2)}function zS(t){if(!t)return"";let e=t.split(`
676
- `),s=[],n=!1,o="";for(let r of e){let i=vm();if(r.trim().startsWith("```")){if(n)s.push(`${x.dim}${"\u2500".repeat(40)}${x.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${x.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${x.reset}`)}continue}if(n){s.push(` ${uc(r,o)}`);continue}if(r.startsWith("###### ")){s.push(`${x.bold}${x.cyan} ${Et(r.substring(7))}${x.reset}`);continue}if(r.startsWith("##### ")){s.push(`${x.bold}${x.cyan} ${Et(r.substring(6))}${x.reset}`);continue}if(r.startsWith("#### ")){s.push(`${x.bold}${x.cyan} ${Et(r.substring(5))}${x.reset}`);continue}if(r.startsWith("### ")){s.push(`${x.bold}${x.cyan} ${Et(r.substring(4))}${x.reset}`);continue}if(r.startsWith("## ")){s.push(`${x.bold}${x.cyan} ${Et(r.substring(3))}${x.reset}`);continue}if(r.startsWith("# ")){s.push(`${x.bold}${x.cyan}${Et(r.substring(2))}${x.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${x.cyan}\u2022${x.reset} ${os(l)}`;s.push(rs(c,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let l=a[1],c=a[2],u=a[3],d=`${l}${x.cyan}${c}.${x.reset} ${os(u)}`,f=l+" ".repeat(c.length+2);s.push(rs(d,i,f));continue}}s.push(rs(os(r),i))}return s.join(`
677
- `)}function Et(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function os(t){return t?t.replace(/`([^`]+)`/g,`${x.cyan}$1${x.reset}`).replace(/\*\*([^*]+)\*\*/g,`${x.bold}$1${x.reset}`).replace(/\*([^*]+)\*/g,`${x.dim}$1${x.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${x.cyan}$1${x.reset} ${x.dim}($2)${x.reset}`):""}function uc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Tm(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Rm(t):e==="json"||e==="jsonc"?Cm(t):e==="python"||e==="py"?Am(t):e==="go"||e==="golang"?Om(t):e==="rust"||e==="rs"?Nm(t):e==="css"||e==="scss"||e==="less"?Mm(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Pm(t):t:""}function Tm(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${x.yellow}$1${x.reset}`),r=r.replace(e,`${x.magenta}$1${x.reset}`),r=r.replace(s,`${x.green}$&${x.reset}`),r=r.replace(n,`${x.dim}$1${x.reset}`),r}function Rm(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${x.cyan}$1${x.reset}`),r=r.replace(e,`$1${x.green}$2${x.reset}`),r=r.replace(n,`${x.yellow}$&${x.reset}`),r=r.replace(o,`${x.dim}$1${x.reset}`),r}function Cm(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${x.cyan}$1${x.reset}:`),r=r.replace(s,`: ${x.green}$1${x.reset}`),r=r.replace(n,`: ${x.yellow}$1${x.reset}`),r=r.replace(o,`: ${x.magenta}$1${x.reset}`),r}function Am(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${x.yellow}$1${x.reset}`),i=i.replace(e,`${x.magenta}$1${x.reset}`),i=i.replace(r,`${x.cyan}$1${x.reset}`),i=i.replace(s,`${x.green}$&${x.reset}`),i=i.replace(n,`${x.dim}$1${x.reset}`),i}function Om(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${x.yellow}$1${x.reset}`),i=i.replace(s,`${x.cyan}$1${x.reset}`),i=i.replace(e,`${x.magenta}$1${x.reset}`),i=i.replace(n,`${x.green}$&${x.reset}`),i=i.replace(o,`${x.dim}$1${x.reset}`),i}function Nm(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${x.yellow}$1${x.reset}`),a=a.replace(s,`${x.cyan}$1${x.reset}`),a=a.replace(e,`${x.magenta}$1${x.reset}`),a=a.replace(i,`${x.yellow}$1${x.reset}`),a=a.replace(n,`${x.green}$&${x.reset}`),a=a.replace(o,`${x.dim}$1${x.reset}`),a}function Mm(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${x.yellow}$1${x.reset}`),a=a.replace(o,`${x.yellow}$1${x.reset}`),a=a.replace(e,`$1${x.cyan}$2${x.reset}:`),a=a.replace(n,`$1${x.magenta}$&${x.reset}`),a=a.replace(r,`${x.dim}$1${x.reset}`),a}function Pm(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${x.dim}$1${x.reset}`),i=i.replace(n,`${x.green}$&${x.reset}`),i=i.replace(e,`<${x.magenta}$1${x.reset}`),i=i.replace(s,` ${x.cyan}$1${x.reset}=`),i=i.replace(r,`${x.yellow}$1${x.reset}`),i}function rs(t,e,s=""){if(!e||e<10)return t;let n="",o=0,r=-1,i=0,a=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let c=i+1;if(c<l&&t[c]==="["){for(c++;c<l&&!/[a-zA-Z]/.test(t[c]);)c++;c<l&&c++}i=c;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){n+=t.slice(a,r)+`
683
+ - Do NOT call ask_user. If anything is ambiguous, add an "## Assumptions" section to the plan and state your assumption. The user approves or rejects the whole plan \u2014 that is the only gate.`}var ls=0;function qE(){!Ee||Ee.status!=="executing"||(ls>0&&_c(ls-1,"done"),ls<Ee.steps.length&&(_c(ls,"in_progress"),ls++))}function FE(){if(!Ee||Ee.status!=="executing"||Ee.steps.length===0)return null;let t=Math.min(ls,Ee.steps.length),e=Ee.steps.length,s=Math.max(0,t-1),n=Ee.steps[s]?.description||"";return{current:t,total:e,description:n}}function BE(){ls=0}var zm=["interactive","semi-auto","autonomous"],Km="interactive";function UE(t){return zm.includes(t)?(Km=t,!0):!1}function WE(){return Km}Xm.exports={createPlan:SE,getActivePlan:EE,setPlanMode:vE,isPlanMode:TE,approvePlan:RE,startExecution:CE,updateStep:_c,formatPlan:AE,savePlan:OE,loadPlan:NE,listPlans:ME,clearPlan:jE,getPlanModePrompt:DE,setPlanContent:LE,getPlanContent:IE,extractStepsFromText:PE,advancePlanStep:qE,getPlanStepInfo:FE,PLAN_MODE_ALLOWED_TOOLS:Ym,setAutonomyLevel:UE,getAutonomyLevel:WE,AUTONOMY_LEVELS:zm}});var ig=V((iC,rg)=>{var{C:x}=tt();function Vm(){return Math.max(10,(process.stdout.columns||80)-2)}function HE(t){if(!t)return"";let e=t.split(`
684
+ `),s=[],n=!1,o="";for(let r of e){let i=Vm();if(r.trim().startsWith("```")){if(n)s.push(`${x.dim}${"\u2500".repeat(40)}${x.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${x.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${x.reset}`)}continue}if(n){s.push(` ${Sc(r,o)}`);continue}if(r.startsWith("###### ")){s.push(`${x.bold}${x.cyan} ${Ct(r.substring(7))}${x.reset}`);continue}if(r.startsWith("##### ")){s.push(`${x.bold}${x.cyan} ${Ct(r.substring(6))}${x.reset}`);continue}if(r.startsWith("#### ")){s.push(`${x.bold}${x.cyan} ${Ct(r.substring(5))}${x.reset}`);continue}if(r.startsWith("### ")){s.push(`${x.bold}${x.cyan} ${Ct(r.substring(4))}${x.reset}`);continue}if(r.startsWith("## ")){s.push(`${x.bold}${x.cyan} ${Ct(r.substring(3))}${x.reset}`);continue}if(r.startsWith("# ")){s.push(`${x.bold}${x.cyan}${Ct(r.substring(2))}${x.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${x.cyan}\u2022${x.reset} ${us(l)}`;s.push(ds(c,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let l=a[1],c=a[2],u=a[3],d=`${l}${x.cyan}${c}.${x.reset} ${us(u)}`,f=l+" ".repeat(c.length+2);s.push(ds(d,i,f));continue}}s.push(ds(us(r),i))}return s.join(`
685
+ `)}function Ct(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function us(t){return t?t.replace(/`([^`]+)`/g,`${x.cyan}$1${x.reset}`).replace(/\*\*([^*]+)\*\*/g,`${x.bold}$1${x.reset}`).replace(/\*([^*]+)\*/g,`${x.dim}$1${x.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${x.cyan}$1${x.reset} ${x.dim}($2)${x.reset}`):""}function Sc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Jm(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Zm(t):e==="json"||e==="jsonc"?Qm(t):e==="python"||e==="py"?eg(t):e==="go"||e==="golang"?tg(t):e==="rust"||e==="rs"?ng(t):e==="css"||e==="scss"||e==="less"?sg(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?og(t):t:""}function Jm(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${x.yellow}$1${x.reset}`),r=r.replace(e,`${x.magenta}$1${x.reset}`),r=r.replace(s,`${x.green}$&${x.reset}`),r=r.replace(n,`${x.dim}$1${x.reset}`),r}function Zm(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${x.cyan}$1${x.reset}`),r=r.replace(e,`$1${x.green}$2${x.reset}`),r=r.replace(n,`${x.yellow}$&${x.reset}`),r=r.replace(o,`${x.dim}$1${x.reset}`),r}function Qm(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${x.cyan}$1${x.reset}:`),r=r.replace(s,`: ${x.green}$1${x.reset}`),r=r.replace(n,`: ${x.yellow}$1${x.reset}`),r=r.replace(o,`: ${x.magenta}$1${x.reset}`),r}function eg(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${x.yellow}$1${x.reset}`),i=i.replace(e,`${x.magenta}$1${x.reset}`),i=i.replace(r,`${x.cyan}$1${x.reset}`),i=i.replace(s,`${x.green}$&${x.reset}`),i=i.replace(n,`${x.dim}$1${x.reset}`),i}function tg(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${x.yellow}$1${x.reset}`),i=i.replace(s,`${x.cyan}$1${x.reset}`),i=i.replace(e,`${x.magenta}$1${x.reset}`),i=i.replace(n,`${x.green}$&${x.reset}`),i=i.replace(o,`${x.dim}$1${x.reset}`),i}function ng(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${x.yellow}$1${x.reset}`),a=a.replace(s,`${x.cyan}$1${x.reset}`),a=a.replace(e,`${x.magenta}$1${x.reset}`),a=a.replace(i,`${x.yellow}$1${x.reset}`),a=a.replace(n,`${x.green}$&${x.reset}`),a=a.replace(o,`${x.dim}$1${x.reset}`),a}function sg(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${x.yellow}$1${x.reset}`),a=a.replace(o,`${x.yellow}$1${x.reset}`),a=a.replace(e,`$1${x.cyan}$2${x.reset}:`),a=a.replace(n,`$1${x.magenta}$&${x.reset}`),a=a.replace(r,`${x.dim}$1${x.reset}`),a}function og(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${x.dim}$1${x.reset}`),i=i.replace(n,`${x.green}$&${x.reset}`),i=i.replace(e,`<${x.magenta}$1${x.reset}`),i=i.replace(s,` ${x.cyan}$1${x.reset}=`),i=i.replace(r,`${x.yellow}$1${x.reset}`),i}function ds(t,e,s=""){if(!e||e<10)return t;let n="",o=0,r=-1,i=0,a=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let c=i+1;if(c<l&&t[c]==="["){for(c++;c<l&&!/[a-zA-Z]/.test(t[c]);)c++;c<l&&c++}i=c;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){n+=t.slice(a,r)+`
678
686
  `+s,a=r+1,i=a,o=s.length,r=-1;continue}o>e&&r===-1&&(n+=t.slice(a,i)+`
679
- `+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function KS(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let l=e.reduce((c,u)=>Math.max(c,(u[a]||"").length),0);return Math.max(i.length,l)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,a)=>` ${x.bold}${i.padEnd(s[a])}${x.reset} `).join("\u2502"),r=[];r.push(`${x.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${x.reset}`),r.push(`${x.dim}\u2502${x.reset}${o}${x.dim}\u2502${x.reset}`),r.push(`${x.dim}\u251C${n}\u2524${x.reset}`);for(let i of e){let a=t.map((l,c)=>` ${(i[c]||"").padEnd(s[c])} `).join(`${x.dim}\u2502${x.reset}`);r.push(`${x.dim}\u2502${x.reset}${a}${x.dim}\u2502${x.reset}`)}return r.push(`${x.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${x.reset}`),r.join(`
680
- `)}function XS(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,a=o>=100?x.green:o>50?x.yellow:x.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${x.dim}${"\u2591".repeat(i)}${x.reset} ${o}% (${e}/${s})`}var cc=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let s=[0,1,2,3,4,3,2,1],n=s[this._cursorFrame%s.length],o="";for(let r=0;r<5;r++)o+=r===n?`${Ft().T.cyan}\u25CF${Ft().T.reset}`:" ";this._cursorWrite(`\x1B[2K\r${o}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
687
+ `+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function YE(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let l=e.reduce((c,u)=>Math.max(c,(u[a]||"").length),0);return Math.max(i.length,l)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,a)=>` ${x.bold}${i.padEnd(s[a])}${x.reset} `).join("\u2502"),r=[];r.push(`${x.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${x.reset}`),r.push(`${x.dim}\u2502${x.reset}${o}${x.dim}\u2502${x.reset}`),r.push(`${x.dim}\u251C${n}\u2524${x.reset}`);for(let i of e){let a=t.map((l,c)=>` ${(i[c]||"").padEnd(s[c])} `).join(`${x.dim}\u2502${x.reset}`);r.push(`${x.dim}\u2502${x.reset}${a}${x.dim}\u2502${x.reset}`)}return r.push(`${x.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${x.reset}`),r.join(`
688
+ `)}function GE(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,a=o>=100?x.green:o>50?x.yellow:x.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${x.dim}${"\u2591".repeat(i)}${x.reset} ${o}% (${e}/${s})`}var xc=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let s=[0,1,2,3,4,3,2,1],n=s[this._cursorFrame%s.length],o="";for(let r=0;r<5;r++)o+=r===n?`${Ht().T.cyan}\u25CF${Ht().T.reset}`:" ";this._cursorWrite(`\x1B[2K\r${o}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
681
689
  `))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${x.dim}${"\u2500".repeat(40)}${x.reset}
682
- `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=vm();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${x.dim}${"\u2500".repeat(40)}${x.reset}
690
+ `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=Vm();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${x.dim}${"\u2500".repeat(40)}${x.reset}
683
691
  `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${x.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${x.reset}
684
- `)}return}if(this.inCodeBlock){this._safeWrite(` ${uc(e,this.codeBlockLang)}
685
- `);return}if(e.startsWith("###### ")){this._safeWrite(`${x.bold}${x.cyan} ${Et(e.substring(7))}${x.reset}
686
- `);return}if(e.startsWith("##### ")){this._safeWrite(`${x.bold}${x.cyan} ${Et(e.substring(6))}${x.reset}
687
- `);return}if(e.startsWith("#### ")){this._safeWrite(`${x.bold}${x.cyan} ${Et(e.substring(5))}${x.reset}
688
- `);return}if(e.startsWith("### ")){this._safeWrite(`${x.bold}${x.cyan} ${Et(e.substring(4))}${x.reset}
689
- `);return}if(e.startsWith("## ")){this._safeWrite(`${x.bold}${x.cyan} ${Et(e.substring(3))}${x.reset}
690
- `);return}if(e.startsWith("# ")){this._safeWrite(`${x.bold}${x.cyan}${Et(e.substring(2))}${x.reset}
691
- `);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${x.cyan}\u2022${x.reset} ${os(r)}`,a=rs(i,s,o+" ");this._safeWrite(`${a}
692
- `);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){let r=o[1],i=o[2],a=o[3],l=`${r}${x.cyan}${i}.${x.reset} ${os(a)}`,c=r+" ".repeat(i.length+2),u=rs(l,s,c);this._safeWrite(`${u}
693
- `);return}}let n=rs(os(e),s);this._safeWrite(`${n}
694
- `)}};Lm.exports={renderMarkdown:zS,renderInline:os,stripHeadingMarkers:Et,highlightCode:uc,highlightJS:Tm,highlightBash:Rm,highlightJSON:Cm,highlightPython:Am,highlightGo:Om,highlightRust:Nm,highlightCSS:Mm,highlightHTML:Pm,renderTable:KS,renderProgress:XS,wrapAnsi:rs,StreamRenderer:cc}});var Bm=Z((a1,Fm)=>{var{execSync:VS}=require("child_process"),dc=require("path"),Ho=require("fs"),fc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Dm(){return dc.join(process.cwd(),".nex","hooks")}function JS(){return dc.join(process.cwd(),".nex","config.json")}function jm(){let t=JS();if(!Ho.existsSync(t))return{};try{return JSON.parse(Ho.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function vi(t){if(!fc.includes(t))return[];let e=[],s=Dm(),n=dc.join(s,t);Ho.existsSync(n)&&e.push(n);let o=jm();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function qm(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:VS(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){let o=typeof n.status=="number"?n.status:1;return{success:!1,exitCode:o,blocked:o===2,output:n.stdout?n.stdout.trim():"",error:n.stderr?n.stderr.trim():n.message}}}function ZS(t,e={}){let s=vi(t);if(s.length===0)return{results:[],blocked:!1};let n={};for(let[r,i]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of s){let i=qm(r,n);if(o.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:o,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:o,blocked:!1}}function QS(t){return vi(t).length>0}function eE(){let t=[];for(let e of fc){let s=vi(e);s.length>0&&t.push({event:e,commands:s})}return t}function tE(){let t=Dm();return Ho.existsSync(t)||Ho.mkdirSync(t,{recursive:!0}),t}Fm.exports={HOOK_EVENTS:fc,loadHookConfig:jm,getHooksForEvent:vi,executeHook:qm,runHooks:ZS,hasHooks:QS,listHooks:eE,initHooksDir:tE}});var Ti=Z((l1,Wm)=>{var Yo={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
692
+ `)}return}if(this.inCodeBlock){this._safeWrite(` ${Sc(e,this.codeBlockLang)}
693
+ `);return}if(e.startsWith("###### ")){this._safeWrite(`${x.bold}${x.cyan} ${Ct(e.substring(7))}${x.reset}
694
+ `);return}if(e.startsWith("##### ")){this._safeWrite(`${x.bold}${x.cyan} ${Ct(e.substring(6))}${x.reset}
695
+ `);return}if(e.startsWith("#### ")){this._safeWrite(`${x.bold}${x.cyan} ${Ct(e.substring(5))}${x.reset}
696
+ `);return}if(e.startsWith("### ")){this._safeWrite(`${x.bold}${x.cyan} ${Ct(e.substring(4))}${x.reset}
697
+ `);return}if(e.startsWith("## ")){this._safeWrite(`${x.bold}${x.cyan} ${Ct(e.substring(3))}${x.reset}
698
+ `);return}if(e.startsWith("# ")){this._safeWrite(`${x.bold}${x.cyan}${Ct(e.substring(2))}${x.reset}
699
+ `);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${x.cyan}\u2022${x.reset} ${us(r)}`,a=ds(i,s,o+" ");this._safeWrite(`${a}
700
+ `);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){let r=o[1],i=o[2],a=o[3],l=`${r}${x.cyan}${i}.${x.reset} ${us(a)}`,c=r+" ".repeat(i.length+2),u=ds(l,s,c);this._safeWrite(`${u}
701
+ `);return}}let n=ds(us(e),s);this._safeWrite(`${n}
702
+ `)}};rg.exports={renderMarkdown:HE,renderInline:us,stripHeadingMarkers:Ct,highlightCode:Sc,highlightJS:Jm,highlightBash:Zm,highlightJSON:Qm,highlightPython:eg,highlightGo:tg,highlightRust:ng,highlightCSS:sg,highlightHTML:og,renderTable:YE,renderProgress:GE,wrapAnsi:ds,StreamRenderer:xc}});var dg=V((aC,ug)=>{var{execSync:zE}=require("child_process"),Ec=require("path"),Vo=require("fs"),vc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function ag(){return Ec.join(process.cwd(),".nex","hooks")}function KE(){return Ec.join(process.cwd(),".nex","config.json")}function lg(){let t=KE();if(!Vo.existsSync(t))return{};try{return JSON.parse(Vo.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Li(t){if(!vc.includes(t))return[];let e=[],s=ag(),n=Ec.join(s,t);Vo.existsSync(n)&&e.push(n);let o=lg();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function cg(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:zE(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){let o=typeof n.status=="number"?n.status:1;return{success:!1,exitCode:o,blocked:o===2,output:n.stdout?n.stdout.trim():"",error:n.stderr?n.stderr.trim():n.message}}}function XE(t,e={}){let s=Li(t);if(s.length===0)return{results:[],blocked:!1};let n={};for(let[r,i]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of s){let i=cg(r,n);if(o.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:o,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:o,blocked:!1}}function VE(t){return Li(t).length>0}function JE(){let t=[];for(let e of vc){let s=Li(e);s.length>0&&t.push({event:e,commands:s})}return t}function ZE(){let t=ag();return Vo.existsSync(t)||Vo.mkdirSync(t,{recursive:!0}),t}ug.exports={HOOK_EVENTS:vc,loadHookConfig:lg,getHooksForEvent:Li,executeHook:cg,runHooks:XE,hasHooks:VE,listHooks:JE,initHooksDir:ZE}});var Ii=V((lC,pg)=>{var Jo={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
695
703
  Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
696
704
  You excel at sysadmin, frontend, and multi-step coding tasks.
697
705
  Prefer action over narration \u2014 read, fix, verify, done.`},"devstral-small":{staleWarn:2e4,staleAbort:6e4,investigationCap:10,postEditCap:8,briefing:`You are devstral-small, a fast and lightweight coding model.
@@ -704,7 +712,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
704
712
  Prioritize decisive, targeted edits. Read only what you need, then fix.
705
713
  Stay on-scope \u2014 your strength is focused, efficient coding tasks.`},"qwen3-vl":{staleWarn:6e4,staleAbort:18e4,investigationCap:15,postEditCap:12,briefing:`You are qwen3-vl, the highest-ranked model for data, frontend, and agentic tasks.
706
714
  Trust your reasoning. Use tools thoroughly when the task demands it.
707
- You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Um={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function nE(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(Yo))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...Yo[s]}:{...Um};for(let[r,i]of[["NEX_STALE_WARN_MS","staleWarn"],["NEX_STALE_ABORT_MS","staleAbort"]])if(process.env[r]){let a=parseInt(process.env[r],10);Number.isInteger(a)&&a>=1e3&&a<=3e5&&(o[i]=a)}return o}function sE(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(Yo))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&Yo[s].briefing||""}Wm.exports={getModelProfile:nE,getModelBriefing:sE,PROFILES:Yo,DEFAULTS:Um}});var zs=Z((c1,Hm)=>{var{fork:oE}=require("child_process"),rE=require("path"),iE=rE.join(__dirname,"background-worker.js"),is=new Map,Gs=new Map;function aE(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function lE(t){let e=aE(),s=oE(iE,[],{silent:!0,env:process.env,cwd:process.cwd()});return s.send({jobId:e,agentDef:t}),s.on("message",n=>{n.type==="result"?hc(e,t,n.payload):n.type==="error"&&hc(e,t,{task:t.task,status:"failed",result:`Background agent error: ${n.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),s.on("exit",(n,o)=>{if(is.has(e)){let r=o?`killed (${o})`:`exit code ${n}`;hc(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),is.set(e,{process:s,agentDef:t,startedAt:Date.now()}),e}function hc(t,e,s){is.delete(t),Gs.set(t,{jobId:t,agentDef:e,result:s,finishedAt:Date.now()})}function cE(){if(Gs.size===0)return[];let t=[...Gs.values()];return Gs.clear(),t}function uE(){return is.size>0||Gs.size>0}function dE(){let t=is.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function fE(){for(let[t,e]of is){try{e.process.kill("SIGTERM")}catch{}is.delete(t)}Gs.clear()}Hm.exports={createJob:lE,getCompletedJobs:cE,getPendingJobSummary:dE,hasPendingOrCompletedJobs:uE,cancelAllJobs:fE}});var rg=Z((h1,og)=>{"use strict";var{callWithRetry:Gm,runSubAgent:hE,clearAllLocks:pE}=gi(),{parseModelSpec:zm,getActiveProviderName:u1,getActiveModelId:d1}=ot(),{detectCategory:mE,getModelForCategory:Ym}=Bo(),{MultiProgress:gE,C:ue}=Je(),{getModelBriefing:f1}=Ti(),Km=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Ri=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Xm="devstral-2:123b",Vm="kimi-k2.5",Jm=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
715
+ You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},fg={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function QE(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(Jo))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...Jo[s]}:{...fg};for(let[r,i]of[["NEX_STALE_WARN_MS","staleWarn"],["NEX_STALE_ABORT_MS","staleAbort"]])if(process.env[r]){let a=parseInt(process.env[r],10);Number.isInteger(a)&&a>=1e3&&a<=3e5&&(o[i]=a)}return o}function ev(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(Jo))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&Jo[s].briefing||""}pg.exports={getModelProfile:QE,getModelBriefing:ev,PROFILES:Jo,DEFAULTS:fg}});var Vs=V((cC,hg)=>{var{fork:tv}=require("child_process"),nv=require("path"),sv=nv.join(__dirname,"background-worker.js"),fs=new Map,Xs=new Map;function ov(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function rv(t){let e=ov(),s=tv(sv,[],{silent:!0,env:process.env,cwd:process.cwd()});return s.send({jobId:e,agentDef:t}),s.on("message",n=>{n.type==="result"?Tc(e,t,n.payload):n.type==="error"&&Tc(e,t,{task:t.task,status:"failed",result:`Background agent error: ${n.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),s.on("exit",(n,o)=>{if(fs.has(e)){let r=o?`killed (${o})`:`exit code ${n}`;Tc(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),fs.set(e,{process:s,agentDef:t,startedAt:Date.now()}),e}function Tc(t,e,s){fs.delete(t),Xs.set(t,{jobId:t,agentDef:e,result:s,finishedAt:Date.now()})}function iv(){if(Xs.size===0)return[];let t=[...Xs.values()];return Xs.clear(),t}function av(){return fs.size>0||Xs.size>0}function lv(){let t=fs.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function cv(){for(let[t,e]of fs){try{e.process.kill("SIGTERM")}catch{}fs.delete(t)}Xs.clear()}hg.exports={createJob:rv,getCompletedJobs:iv,getPendingJobSummary:lv,hasPendingOrCompletedJobs:av,cancelAllJobs:cv}});var Ng=V((pC,Og)=>{"use strict";var{callWithRetry:yg,runSubAgent:mg,clearAllLocks:uv}=Si(),{parseModelSpec:wg,getActiveProviderName:uC,getActiveModelId:dC}=lt(),{detectCategory:dv,getModelForCategory:gg}=zo(),{MultiProgress:fv,C:pe}=tt(),{getModelBriefing:fC}=Ii(),$g=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),ji=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),_g="devstral-2:123b",bg="kimi-k2.5",kg=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
708
716
 
709
717
  RULES:
710
718
  - Output ONLY a JSON array, no markdown fences, no explanation.
@@ -719,7 +727,7 @@ RULES:
719
727
  - If the request is simple (single goal), return an array with exactly 1 item.
720
728
 
721
729
  USER REQUEST:
722
- {prompt}`,Zm=`You are a result synthesis engine. Given the results of multiple sub-agents that worked on parts of a larger task, produce a unified summary.
730
+ {prompt}`,xg=`You are a result synthesis engine. Given the results of multiple sub-agents that worked on parts of a larger task, produce a unified summary.
723
731
 
724
732
  RULES:
725
733
  - Output ONLY a JSON object with these fields:
@@ -733,16 +741,16 @@ ORIGINAL REQUEST:
733
741
  {prompt}
734
742
 
735
743
  SUB-AGENT RESULTS:
736
- {results}`;async function Qm(t,e=1,s=2e3){for(let n=0;n<=e;n++)try{return await t()}catch(o){if(n===e)throw o;await new Promise(r=>setTimeout(r,s))}}function eg(t){let e=0,s=[];return function(){return new Promise(o=>{let r=()=>{e<t?(e++,o(()=>{e--,s.length>0&&s.shift()()})):s.push(r)};r()})}}function yE(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,s=[],n=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);n&&n.length>=2&&(e=Math.max(e,n.length),s.push(`${n.length} numbered items`));let o=t.match(/(?:^|\n)\s*[-*]\s+\S/g);o&&o.length>=3&&(e=Math.max(e,o.length),s.push(`${o.length} bullet points`));let r=t.split(/;\s*/).filter(c=>c.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),s.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),s.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:s.length>0?s.join(", "):"single goal"}}function pc(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let s=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(s)try{return JSON.parse(s[1].trim())}catch{}let n=e.search(/[[\{]/);if(n>=0){let o=e.slice(n);try{return JSON.parse(o)}catch{}}throw new Error(`Could not extract valid JSON from response:
737
- ${e.slice(0,200)}`)}async function tg(t,e,s={}){let n=s.maxSubTasks||Ri,r=[{role:"system",content:Jm.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=zm(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await Gm(r,[],i)).content||"",c=pc(l);if(!Array.isArray(c))throw new Error(`Decompose returned non-array: ${typeof c}`);let u=10,f=c.slice(0,n).map((g,_)=>({id:g.id||`t${_+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,u):8,priority:typeof g.priority=="number"?g.priority:_+1})).filter(g=>g.task.length>0),p=f.reduce((g,_)=>g+_.estimatedCalls,0),m=Ri*u;if(p>m){let{debugLog:g}=Aa();g(`${Ft().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${m} \u2014 consider raising maxSubTasks${Ft().T.reset}`)}return f}async function ng(t,e,s){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let n=t.map((u,d)=>{let f=u.status==="done"?"SUCCESS":u.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
744
+ {results}`;async function Sg(t,e=1,s=2e3){for(let n=0;n<=e;n++)try{return await t()}catch(o){if(n===e)throw o;await new Promise(r=>setTimeout(r,s))}}function Eg(t){let e=0,s=[];return function(){return new Promise(o=>{let r=()=>{e<t?(e++,o(()=>{e--,s.length>0&&s.shift()()})):s.push(r)};r()})}}function pv(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,s=[],n=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);n&&n.length>=2&&(e=Math.max(e,n.length),s.push(`${n.length} numbered items`));let o=t.match(/(?:^|\n)\s*[-*]\s+\S/g);o&&o.length>=3&&(e=Math.max(e,o.length),s.push(`${o.length} bullet points`));let r=t.split(/;\s*/).filter(c=>c.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),s.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),s.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:s.length>0?s.join(", "):"single goal"}}function Rc(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let s=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(s)try{return JSON.parse(s[1].trim())}catch{}let n=e.search(/[[\{]/);if(n>=0){let o=e.slice(n);try{return JSON.parse(o)}catch{}}throw new Error(`Could not extract valid JSON from response:
745
+ ${e.slice(0,200)}`)}async function vg(t,e,s={}){let n=s.maxSubTasks||ji,r=[{role:"system",content:kg.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=wg(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await yg(r,[],i)).content||"",c=Rc(l);if(!Array.isArray(c))throw new Error(`Decompose returned non-array: ${typeof c}`);let u=10,f=c.slice(0,n).map((g,$)=>({id:g.id||`t${$+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,u):8,priority:typeof g.priority=="number"?g.priority:$+1})).filter(g=>g.task.length>0),p=f.reduce((g,$)=>g+$.estimatedCalls,0),m=ji*u;if(p>m){let{debugLog:g}=qa();g(`${Ht().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${m} \u2014 consider raising maxSubTasks${Ht().T.reset}`)}return f}async function Tg(t,e,s){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let n=t.map((u,d)=>{let f=u.status==="done"?"SUCCESS":u.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
738
746
  Task: ${u.task}
739
747
  Result: ${u.result}
740
748
  Tools: ${(u.toolsUsed||[]).join(", ")||"none"}`}).join(`
741
749
 
742
- `),r=[{role:"system",content:Zm.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=zm(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let l=(await Gm(r,[],i)).content||"",c=pc(l);return{summary:String(c.summary||""),conflicts:Array.isArray(c.conflicts)?c.conflicts:[],commitMessage:String(c.commitMessage||""),filesChanged:Array.isArray(c.filesChanged)?c.filesChanged:[]}}async function wE(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Vm,n=e.workerModel||Xm,o=e.maxParallel||Km,r=e.maxSubTasks||Ri,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
743
- ${ue.bold}Orchestrator${ue.reset} ${ue.dim}model: ${s} | workers: ${n} | max parallel: ${o}${ue.reset}
744
- `),i("decomposing"),console.log(`${ue.dim}Phase 1: Decomposing prompt into sub-tasks...${ue.reset}`);let l;try{l=await tg(t,s,{maxSubTasks:r})}catch(W){return console.log(`${ue.red}Decompose failed: ${W.message}${ue.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${W.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${ue.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ue.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${ue.green}Decomposed into ${l.length} sub-tasks:${ue.reset}`);for(let W of l){console.log(` ${ue.dim}${W.id}:${ue.reset} ${W.task}`);let J=W.scope.filter(Boolean);J.length>0&&console.log(` ${ue.dim}scope: ${J.join(", ")}${ue.reset}`)}console.log("");let c=new Map;for(let W=0;W<l.length;W++)for(let J of l[W].scope)J&&!c.has(J)&&c.set(J,W);i("executing"),console.log(`${ue.dim}Phase 2: Running ${l.length} sub-agents (max ${o} parallel)...${ue.reset}
745
- `);let u=Date.now(),d=eg(o),f={findings:[],_lock:!1},p=l.map(W=>{let J=mE(W.task);return(J?Ym(J.id):null)||n}),m=l.map((W,J)=>{let he=`Agent ${J+1} [${p[J]}]: `,Re=Math.max(20,60-he.length),Ue=W.task.substring(0,Re)+(W.task.length>Re?"...":"");return he+Ue}),g=new gE(m);g.start();let _=`
750
+ `),r=[{role:"system",content:xg.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=wg(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let l=(await yg(r,[],i)).content||"",c=Rc(l);return{summary:String(c.summary||""),conflicts:Array.isArray(c.conflicts)?c.conflicts:[],commitMessage:String(c.commitMessage||""),filesChanged:Array.isArray(c.filesChanged)?c.filesChanged:[]}}async function hv(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||bg,n=e.workerModel||_g,o=e.maxParallel||$g,r=e.maxSubTasks||ji,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
751
+ ${pe.bold}Orchestrator${pe.reset} ${pe.dim}model: ${s} | workers: ${n} | max parallel: ${o}${pe.reset}
752
+ `),i("decomposing"),console.log(`${pe.dim}Phase 1: Decomposing prompt into sub-tasks...${pe.reset}`);let l;try{l=await vg(t,s,{maxSubTasks:r})}catch(W){return console.log(`${pe.red}Decompose failed: ${W.message}${pe.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${W.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${pe.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${pe.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${pe.green}Decomposed into ${l.length} sub-tasks:${pe.reset}`);for(let W of l){console.log(` ${pe.dim}${W.id}:${pe.reset} ${W.task}`);let z=W.scope.filter(Boolean);z.length>0&&console.log(` ${pe.dim}scope: ${z.join(", ")}${pe.reset}`)}console.log("");let c=new Map;for(let W=0;W<l.length;W++)for(let z of l[W].scope)z&&!c.has(z)&&c.set(z,W);i("executing"),console.log(`${pe.dim}Phase 2: Running ${l.length} sub-agents (max ${o} parallel)...${pe.reset}
753
+ `);let u=Date.now(),d=Eg(o),f={findings:[],_lock:!1},p=l.map(W=>{let z=dv(W.task);return(z?gg(z.id):null)||n}),m=l.map((W,z)=>{let me=`Agent ${z+1} [${p[z]}]: `,Ce=Math.max(20,60-me.length),De=W.task.substring(0,Ce)+(W.task.length>Ce?"...":"");return me+De}),g=new fv(m);g.start();let $=`
746
754
  You are a focused coding agent executing ONE specific sub-task.
747
755
  Your scope is limited to the files listed in your task definition.
748
756
 
@@ -763,16 +771,28 @@ RULES:
763
771
  - If your task says "add X to README" \u2014 add it, don't check if it exists first.
764
772
  - Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
765
773
  - When done: stop calling tools and write a one-line summary of what you changed.
766
- `,k=new Map;for(let W=0;W<l.length;W++){let J=l[W].priority||1;k.has(J)||k.set(J,[]),k.get(J).push({st:l[W],idx:W})}let A=[...k.keys()].sort((W,J)=>W-J),L=new Array(l.length);for(let W of A){let he=k.get(W).map(async({st:Re,idx:Ue})=>{let be=await d();try{let $e=await E(Re,Ue,{acquire:d,subTaskModels:p,labels:m,progress:g,sharedContext:f,_fileOwnership:c,workerModel:n,WORKER_SYSTEM_PROMPT:_});return L[Ue]=$e,$e}finally{be()}});await Promise.all(he)}async function E(W,J,he){try{let Re=f.findings.filter(Y=>Y.agentId!==W.id).map(Y=>`Agent ${Y.agentId} found: ${Y.summary}`).join(`
767
- `),Ue=[...c.entries()].filter(([,Y])=>Y===J).map(([Y])=>Y),be=[...c.entries()].filter(([,Y])=>Y!==J).map(([Y])=>Y),$e=[Re?`Prior agent findings:
768
- ${Re}
769
- `:"",W.scope.length>0?`Focus on files: ${W.scope.join(", ")}`:"",Ue.length>0?`You OWN these files (may read+write): ${Ue.join(", ")}`:"",be.length>0?`READ ONLY (owned by other agents, do NOT write): ${be.join(", ")}`:""].filter(Boolean),$=sg(W.task),I=p[J],H=process.env.NEX_FALLBACK_MODEL||Ym("agentic")||n,O=0,q=await Qm(async()=>{let Y=O>0;Y&&(g.update(J,"retry"),process.stderr.write(` ${ue.dim}[Agent ${J+1}] retrying after error...${ue.reset}
770
- `)),O++;let ke=Y&&I!==H?H:I;return hE({task:W.task,type:$,context:$e.length>0?$e.join(`
771
- `):void 0,max_iterations:Math.min(W.estimatedCalls||10,15),model:ke,_skipLog:!0,_systemPrompt:_,_readOnlyFiles:be},{onUpdate:fe=>{if(fe&&fe.type==="tool_call"&&process.stderr.isTTY){let at=`Agent ${J+1} [${ke}]`,no=fe.tool||"...";g.labels[J]=`${at}: ${no}`}}})},1,2e3),b=typeof q.result=="string"?q.result.slice(0,200):String(q.result||"").slice(0,200);return f.findings.push({agentId:W.id,summary:b,files:Array.isArray(W.scope)?W.scope:[]}),g.labels[J]=m[J],g.update(J,q.status==="failed"?"error":"done"),a.input+=q.tokensUsed?.input||0,a.output+=q.tokensUsed?.output||0,q.tokensUsed?._estimated&&(a._estimated=!0),{...q,_scope:W.scope,_idx:J}}catch(Re){return g.labels[J]=m[J],g.update(J,"error"),{task:W.task,status:"failed",result:`Error: ${Re.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let v;try{v=L}finally{g.stop({silent:!0}),pE()}console.log("");let N=Math.round((Date.now()-u)/1e3),te=N>=60?`${Math.floor(N/60)}m ${N%60}s`:`${N}s`;for(let W=0;W<v.length;W++){let J=v[W],Re=J.status==="done"||J.status==="truncated"&&J.result&&!J.result.startsWith("Error")?`${ue.green}\u2713${ue.reset}`:`${ue.red}\u2717${ue.reset}`,Ue=J._scope&&J._scope.length>0?J._scope.map($=>$.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],be=Ue.length>0?Ue.join(", "):J.task.substring(0,35)+(J.task.length>35?"...":""),$e=W===v.length-1;console.log(` ${Re} Agent ${W+1} ${ue.dim}${be}${ue.reset}${$e?` ${ue.dim}${te}${ue.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ue.dim}Phase 3: Synthesizing results...${ue.reset}`);let V;try{V=await ng(v,t,s)}catch(W){console.log(`${ue.yellow}Synthesize failed: ${W.message} \u2014 using raw results.${ue.reset}`),V={summary:v.map(J=>J.result).join(`
772
- `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let re=f.findings.flatMap(W=>W.files),le=new Map;for(let W of re)le.set(W,(le.get(W)||0)+1);let ne=[...le.values()].some(W=>W>1),S=f.findings.length>1&&ne?` ${ue.dim}(agents shared context)${ue.reset}`:"";if(console.log(`
773
- ${ue.bold}Summary:${ue.reset} ${V.summary}${S}`),V.conflicts.length>0){console.log(`${ue.yellow}Conflicts:${ue.reset}`);for(let W of V.conflicts)console.log(` - ${W}`)}V.commitMessage&&console.log(`${ue.dim}Suggested commit: ${V.commitMessage}${ue.reset}`);let Ee=a.input===0&&a.output===0?"n/a (provider does not report token counts)":a._estimated?`~${a.input} input / ~${a.output} output (est.)`:`${a.input} input + ${a.output} output`;return console.log(`${ue.dim}Tokens: ${Ee}${ue.reset}
774
- `),{results:v,synthesis:V,totalTokens:a}}var _E=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,$E=/\b(fix|implement|create|add|update|modify|change|write|refactor|remove|delete|install|configure|setup|deploy|build|migrate|optimize|improve|patch|rewrite|replace)\b/i;function sg(t){if(!t)return"implement";let e=_E.test(t);return $E.test(t)?"implement":e?"explore":"implement"}og.exports={runOrchestrated:wE,decompose:tg,synthesize:ng,detectComplexPrompt:yE,extractJSON:pc,createSemaphore:eg,DECOMPOSE_PROMPT:Jm,SYNTHESIZE_PROMPT:Zm,DEFAULT_ORCHESTRATOR_MODEL:Vm,DEFAULT_WORKER_MODEL:Xm,DEFAULT_MAX_PARALLEL:Km,DEFAULT_MAX_SUBTASKS:Ri,withRetry:Qm,_classifyWorkerType:sg}});var Vl=Z((_1,Pg)=>{var{C:h,Spinner:Xs,TaskProgress:bE,formatToolCall:kE,formatToolSummary:Tc,formatSectionHeader:Ci,formatMilestone:xE,setActiveTaskProgress:p1,getThinkingVerb:mc,setActiveModelForSpinner:ig}=Je(),{debugLog:j,warnLog:m1}=Aa(),{MilestoneTracker:SE}=ud(),{callStream:ag}=ot(),{parseToolArgs:EE}=Mr(),{executeTool:vE}=po(),{gatherProjectContext:TE}=zp(),{fitToContext:RE,forceCompress:tn,getUsage:Yt,estimateTokens:CE,buildProgressSnapshot:AE}=Qt(),{autoSave:OE,flushAutoSave:NE}=$i(),{scoreMessages:ME,formatScore:PE,appendScoreHistory:LE}=rm(),{detectCategory:IE,getModelForPhase:Rc,getPhaseBudget:as,isPhaseRoutingEnabled:DE}=Bo();function Ce(t){OE(t),NE()}function jE(t){if(!t||typeof t!="string")return!0;let e=t.trim();return!!(e.length<80||/^(done|complete|finished|all done|analysis complete|finally done)[.!]*$/i.test(e)||/^[^.!]{0,40}\?$/.test(e))}function Ai(t){try{if(!t.some(n=>n.role!=="assistant"?!1:!!(Array.isArray(n.content)&&n.content.some(o=>o&&o.type==="tool_use")||Array.isArray(n.tool_calls)&&n.tool_calls.length>0)))return;let s=ME(t);if(!s)return;console.log(PE(s,h));try{let{_getSessionsDir:n}=$i(),o=require("fs"),r=require("path").join(n(),"_autosave.json");if(o.existsSync(r)){let i=JSON.parse(o.readFileSync(r,"utf-8"));i.score=s.score,i.scoreGrade=s.grade,i.scoreIssues=s.issues,o.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:n}=Mr(),o=$a();LE(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:qE}=Co(),{getDeploymentContextBlock:FE,probeUrlServer:BE}=Zl(),{getFewShotForInput:UE}=pm(),{checkPermission:WE,setPermission:HE,savePermissions:YE}=$m(),{confirm:$g,setAllowAlwaysHandler:GE,getAutoConfirm:er}=lo(),{isPlanMode:tr,getPlanModePrompt:zE,PLAN_MODE_ALLOWED_TOOLS:bg,setPlanContent:KE,extractStepsFromText:XE,createPlan:VE,getActivePlan:g1,startExecution:y1,advancePlanStep:JE,getPlanStepInfo:ZE}=Ei(),{StreamRenderer:QE}=Im(),{runHooks:lg}=Bm(),{routeMCPCall:ev,getMCPToolDefinitions:tv}=Ka(),{getSkillInstructions:nv,getSkillToolDefinitions:sv,routeSkillCall:ov,matchSkillTriggers:rv}=Ga(),{trackUsage:cg,estimateTokens:ug}=Tr();function dg(t){return!t||typeof t!="string"?0:typeof ug=="function"?ug(t):Math.ceil(t.length/4)}var{validateToolArgs:iv}=Ja(),{filterToolsForModel:fg,getModelTier:av,PROVIDER_DEFAULT_TIER:w1}=_o(),{getConfiguredProviders:lv,getActiveProviderName:Vs,getActiveModelId:Kt,setActiveModel:gc,MODEL_EQUIVALENTS:Gi}=ot(),{getModelProfile:cv,getModelBriefing:uv}=Ti(),Cn=require("fs"),eo=require("path"),dv=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function fv(t){let e=xE(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
775
- `)}var hg=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,pg=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,hv=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function pv(t){let e=[],s;for(hg.lastIndex=0;(s=hg.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):eo.resolve(n);Cn.existsSync(o)&&e.push({raw:n,abs:o})}return e}function kg(t){let e=[],s;for(pg.lastIndex=0;(s=pg.exec(t))!==null;)e.push(s[1].trim());return e}async function xg(t){try{let s=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),n=s.headers["content-type"]||"",o=n.startsWith("image/")?n.split(";")[0]:mv(t);return{data:Buffer.from(s.data).toString("base64"),media_type:o}}catch{return null}}function mv(t){let e=t.toLowerCase();return e.includes(".jpg")||e.includes(".jpeg")?"image/jpeg":e.includes(".gif")?"image/gif":e.includes(".webp")?"image/webp":"image/png"}function Sg(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=eo.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&Cn.existsSync(e)){let o=Cn.readFileSync(e);if(o.length>100)return{data:o.toString("base64"),media_type:"image/png",path:e};try{Cn.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let n=t("osascript",["-e",`try
774
+ - You are part of a team of agents. Respect file ownership strictly: write only to files you own; other scoped files are read-only context.
775
+ - Start with symbol-aware reads inside your scope: locate the target function/class/module, then read the exact section instead of scanning broadly.
776
+ - Before finishing, run the smallest relevant verification for your scope and report any residual risk explicitly.
777
+ - If your sub-task is review/audit/verify-oriented, output findings first with severity, file, and impact. If nothing is wrong, say so explicitly and mention remaining risk.
778
+ `,k=new Map;for(let W=0;W<l.length;W++){let z=l[W].priority||1;k.has(z)||k.set(z,[]),k.get(z).push({st:l[W],idx:W})}let M=[...k.keys()].sort((W,z)=>W-z),D=new Array(l.length);for(let W of M){let me=k.get(W).map(async({st:Ce,idx:De})=>{let ke=await d();try{let be=await v(Ce,De,{acquire:d,subTaskModels:p,labels:m,progress:g,sharedContext:f,_fileOwnership:c,workerModel:n,WORKER_SYSTEM_PROMPT:$});return D[De]=be,be}finally{ke()}});await Promise.all(me)}async function v(W,z,me){try{let Ce=f.findings.filter(de=>de.agentId!==W.id).map(de=>`Agent ${de.agentId} found: ${de.summary}`).join(`
779
+ `),De=[...c.entries()].filter(([,de])=>de===z).map(([de])=>de),ke=[...c.entries()].filter(([,de])=>de!==z).map(([de])=>de),be=[Ce?`Prior agent findings:
780
+ ${Ce}
781
+ `:"",W.scope.length>0?`Focus on files: ${W.scope.join(", ")}`:"",De.length>0?`You OWN these files (may read+write): ${De.join(", ")}`:"",ke.length>0?`READ ONLY (owned by other agents, do NOT write): ${ke.join(", ")}`:""].filter(Boolean),b=Ag(W.task),I=p[z],H=process.env.NEX_FALLBACK_MODEL||gg("agentic")||n,N=0,L=await Sg(async()=>{let de=N>0;de&&(g.update(z,"retry"),process.stderr.write(` ${pe.dim}[Agent ${z+1}] retrying after error...${pe.reset}
782
+ `)),N++;let fe=de&&I!==H?H:I;return mg({task:W.task,type:b,context:be.length>0?be.join(`
783
+ `):void 0,max_iterations:Math.min(W.estimatedCalls||10,15),model:fe,_skipLog:!0,_systemPrompt:$,_readOnlyFiles:ke},{onUpdate:Je=>{if(Je&&Je.type==="tool_call"&&process.stderr.isTTY){let ro=`Agent ${z+1} [${fe}]`,xn=Je.tool||"...";g.labels[z]=`${ro}: ${xn}`}}})},1,2e3),_="";if(Cg(b,L,W,De)){let de=[...new Set([...De,...Array.isArray(L.filesModified)?L.filesModified:[],...Array.isArray(W.scope)?W.scope:[]])].filter(Boolean);try{g.labels[z]=`Agent ${z+1} [${I}] review`,g.update(z,"retry");let fe=await mg({task:`Review the completed changes for: ${W.task}`,type:"review",context:wv(W,L,de),max_iterations:4,model:I,_skipLog:!0,_systemPrompt:$},{onUpdate:()=>{}},1);Rg(fe.result)?(_=`
784
+
785
+ Reviewer findings:
786
+ ${fe.result}`,f.findings.push({agentId:`${W.id}-review`,summary:String(fe.result||"").slice(0,200),files:de})):fe.result&&(_=`
787
+
788
+ Reviewer: ${fe.result}`)}catch(fe){_=`
789
+
790
+ Reviewer note: review pass failed (${fe.message})`}}let J=typeof L.result=="string"?`${L.result}${_}`.slice(0,200):`${String(L.result||"")}${_}`.slice(0,200);return f.findings.push({agentId:W.id,summary:J,files:Array.isArray(W.scope)?W.scope:[]}),g.labels[z]=m[z],g.update(z,L.status==="failed"?"error":"done"),a.input+=L.tokensUsed?.input||0,a.output+=L.tokensUsed?.output||0,L.tokensUsed?._estimated&&(a._estimated=!0),{...L,result:`${String(L.result||"")}${_}`,_scope:W.scope,_idx:z}}catch(Ce){return g.labels[z]=m[z],g.update(z,"error"),{task:W.task,status:"failed",result:`Error: ${Ce.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let E;try{E=D}finally{g.stop({silent:!0}),uv()}console.log("");let A=Math.round((Date.now()-u)/1e3),ee=A>=60?`${Math.floor(A/60)}m ${A%60}s`:`${A}s`;for(let W=0;W<E.length;W++){let z=E[W],Ce=z.status==="done"||z.status==="truncated"&&z.result&&!z.result.startsWith("Error")?`${pe.green}\u2713${pe.reset}`:`${pe.red}\u2717${pe.reset}`,De=z._scope&&z._scope.length>0?z._scope.map(b=>b.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],ke=De.length>0?De.join(", "):z.task.substring(0,35)+(z.task.length>35?"...":""),be=W===E.length-1;console.log(` ${Ce} Agent ${W+1} ${pe.dim}${ke}${pe.reset}${be?` ${pe.dim}${ee}${pe.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${pe.dim}Phase 3: Synthesizing results...${pe.reset}`);let se;try{se=await Tg(E,t,s)}catch(W){console.log(`${pe.yellow}Synthesize failed: ${W.message} \u2014 using raw results.${pe.reset}`),se={summary:E.map(z=>z.result).join(`
791
+ `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ue=f.findings.flatMap(W=>W.files),ae=new Map;for(let W of ue)ae.set(W,(ae.get(W)||0)+1);let te=[...ae.values()].some(W=>W>1),S=f.findings.length>1&&te?` ${pe.dim}(agents shared context)${pe.reset}`:"";if(console.log(`
792
+ ${pe.bold}Summary:${pe.reset} ${se.summary}${S}`),se.conflicts.length>0){console.log(`${pe.yellow}Conflicts:${pe.reset}`);for(let W of se.conflicts)console.log(` - ${W}`)}se.commitMessage&&console.log(`${pe.dim}Suggested commit: ${se.commitMessage}${pe.reset}`);let ve=a.input===0&&a.output===0?"n/a (provider does not report token counts)":a._estimated?`~${a.input} input / ~${a.output} output (est.)`:`${a.input} input + ${a.output} output`;return console.log(`${pe.dim}Tokens: ${ve}${pe.reset}
793
+ `),{results:E,synthesis:se,totalTokens:a}}var mv=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,gv=/\b(review|audit|verify|validate|inspect|critique)\b/i,yv=/\b(fix|implement|create|add|update|modify|change|write|refactor|remove|delete|install|configure|setup|deploy|build|migrate|optimize|improve|patch|rewrite|replace)\b/i;function wv(t,e,s){let n=Array.isArray(s)&&s.length>0?`Files to review: ${s.join(", ")}`:"Files to review: inspect the files touched by the implementing agent";return["Review the finished implementation for correctness, regressions, and missing verification.",`Original task: ${t.task}`,n,`Implementation summary: ${String(e.result||"").slice(0,600)}`,'Report findings first. If no material issue exists, say "No material findings" and mention the main residual risk.'].join(`
794
+ `)}function Rg(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function Cg(t,e,s,n){if(t!=="implement"||!e||e.status==="failed")return!1;let o=Array.isArray(s?.scope)?s.scope.length:0,r=Array.isArray(e.filesModified)?e.filesModified.length:0,i=Array.isArray(n)?n.length:0;return o+r+i>0}function Ag(t){if(!t)return"implement";let e=mv.test(t),s=gv.test(t);return yv.test(t)?"implement":s?"review":e?"explore":"implement"}Og.exports={runOrchestrated:hv,decompose:vg,synthesize:Tg,detectComplexPrompt:pv,extractJSON:Rc,createSemaphore:Eg,DECOMPOSE_PROMPT:kg,SYNTHESIZE_PROMPT:xg,DEFAULT_ORCHESTRATOR_MODEL:bg,DEFAULT_WORKER_MODEL:_g,DEFAULT_MAX_PARALLEL:$g,DEFAULT_MAX_SUBTASKS:ji,withRetry:Sg,_classifyWorkerType:Ag,_hasMaterialReviewFindings:Rg,_shouldRunFollowUpReview:Cg}});var uc=V(($C,uy)=>{var{C:h,Spinner:Zs,TaskProgress:$v,formatToolCall:_v,formatToolSummary:Bc,formatSectionHeader:Di,formatMilestone:bv,setActiveTaskProgress:hC,getThinkingVerb:Cc,setActiveModelForSpinner:Mg}=tt(),{debugLog:j,warnLog:mC}=qa(),{MilestoneTracker:kv}=Ed(),{callStream:Pg}=lt(),{parseToolArgs:xv}=Fr(),{executeTool:Sv}=yo(),{gatherProjectContext:Ev}=ym(),{fitToContext:vv,forceCompress:an,getUsage:Vt,estimateTokens:Tv,buildProgressSnapshot:Rv}=on(),{autoSave:Cv,flushAutoSave:Av}=Ci(),{scoreMessages:Ov,formatScore:Nv,appendScoreHistory:Mv}=Cm(),{detectCategory:Pv,getModelForPhase:Uc,getPhaseBudget:ps,isPhaseRoutingEnabled:Lv}=zo();function Ae(t){Cv(t),Av()}function Iv(t){if(!t||typeof t!="string")return!0;let e=t.trim();return!!(e.length<80||/^(done|complete|finished|all done|analysis complete|finally done)[.!]*$/i.test(e)||/^[^.!]{0,40}\?$/.test(e))}function qi(t){try{if(!t.some(n=>n.role!=="assistant"?!1:!!(Array.isArray(n.content)&&n.content.some(o=>o&&o.type==="tool_use")||Array.isArray(n.tool_calls)&&n.tool_calls.length>0)))return;let s=Ov(t);if(!s)return;console.log(Nv(s,h));try{let{_getSessionsDir:n}=Ci(),o=require("fs"),r=require("path").join(n(),"_autosave.json");if(o.existsSync(r)){let i=JSON.parse(o.readFileSync(r,"utf-8"));i.score=s.score,i.scoreGrade=s.grade,i.scoreIssues=s.issues,o.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:n}=Fr(),o=Ca();Mv(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:jv}=Mo(),{getDeploymentContextBlock:Dv,probeUrlServer:qv}=fc(),{getFewShotForInput:Fv}=Dm(),{checkPermission:Bv,setPermission:Uv,savePermissions:Wv}=Hm(),{confirm:zg,setAllowAlwaysHandler:Hv,getAutoConfirm:ir}=fo(),{isPlanMode:ar,getPlanModePrompt:Yv,PLAN_MODE_ALLOWED_TOOLS:Kg,setPlanContent:Gv,extractStepsFromText:zv,createPlan:Kv,getActivePlan:gC,startExecution:yC,advancePlanStep:Xv,getPlanStepInfo:Vv}=Pi(),{StreamRenderer:Jv}=ig(),{runHooks:Lg}=dg(),{routeMCPCall:Zv,getMCPToolDefinitions:Qv}=sl(),{getSkillInstructions:eT,getSkillToolDefinitions:tT,routeSkillCall:nT,matchSkillTriggers:sT}=tl(),{trackUsage:Ig,estimateTokens:jg}=Pr();function Dg(t){return!t||typeof t!="string"?0:typeof jg=="function"?jg(t):Math.ceil(t.length/4)}var{validateToolArgs:oT}=il(),{filterToolsForModel:qg,getModelTier:rT,PROVIDER_DEFAULT_TIER:wC}=xo(),{getConfiguredProviders:iT,getActiveProviderName:Qs,getActiveModelId:Qt,setActiveModel:Ac,MODEL_EQUIVALENTS:ta}=lt(),{getModelProfile:aT,getModelBriefing:lT}=Ii(),je=require("fs"),Ye=require("path"),cT=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function uT(t){let e=bv(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
795
+ `)}var Fg=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,Bg=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,dT=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function fT(t){let e=[],s;for(Fg.lastIndex=0;(s=Fg.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):Ye.resolve(n);je.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Xg(t){let e=[],s;for(Bg.lastIndex=0;(s=Bg.exec(t))!==null;)e.push(s[1].trim());return e}async function Vg(t){try{let s=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),n=s.headers["content-type"]||"",o=n.startsWith("image/")?n.split(";")[0]:pT(t);return{data:Buffer.from(s.data).toString("base64"),media_type:o}}catch{return null}}function pT(t){let e=t.toLowerCase();return e.includes(".jpg")||e.includes(".jpeg")?"image/jpeg":e.includes(".gif")?"image/gif":e.includes(".webp")?"image/webp":"image/png"}function Jg(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=Ye.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&je.existsSync(e)){let o=je.readFileSync(e);if(o.length>100)return{data:o.toString("base64"),media_type:"image/png",path:e};try{je.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let n=t("osascript",["-e",`try
776
796
  set imgData to the clipboard as \xABclass PNGf\xBB
777
797
  return "has_image"
778
798
  on error
@@ -783,64 +803,77 @@ end try`],{timeout:3e3});if(n.stdout&&n.stdout.toString().trim()==="has_image"){
783
803
  set fRef to open for access filePath with write permission
784
804
  write imgData to fRef
785
805
  close access fRef
786
- `;if(t("osascript",["-e",o],{timeout:5e3}).status===0&&Cn.existsSync(e)){let i=Cn.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function mg(t){let e=Cn.readFileSync(t),s=eo.extname(t).toLowerCase().replace(".",""),n=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function Eg(t){let e=pv(t),s=kg(t),n=hv.test(t),o=s.length>0||n;if(e.length===0&&!o)return t;if(!o){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=mg(i.abs);r.push({type:"image",media_type:l,data:a})}catch{}return r.length>1?r:t}return(async()=>{let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=mg(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){j(`${h.yellow} \u26A0 Path resolution failed: ${a.message}${h.reset}`)}if(s.length>0){let i=await Promise.all(s.map(xg));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(n){let i=Sg();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
806
+ `;if(t("osascript",["-e",o],{timeout:5e3}).status===0&&je.existsSync(e)){let i=je.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function Ug(t){let e=je.readFileSync(t),s=Ye.extname(t).toLowerCase().replace(".",""),n=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function Zg(t){let e=fT(t),s=Xg(t),n=dT.test(t),o=s.length>0||n;if(e.length===0&&!o)return t;if(!o){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=Ug(i.abs);r.push({type:"image",media_type:l,data:a})}catch{}return r.length>1?r:t}return(async()=>{let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=Ug(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){j(`${h.yellow} \u26A0 Path resolution failed: ${a.message}${h.reset}`)}if(s.length>0){let i=await Promise.all(s.map(Vg));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(n){let i=Jg();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
787
807
  [Clipboard image attached: ${i.path}]`):r[0].text+=`
788
- [No image found in clipboard]`}return r.length>1?r:t})()}var gv=[/\bwtf\b/i,/\buff\b/i,/\bugh\b/i,/\bffs\b/i,/\bargh\b/i,/why (?:isn'?t|doesn'?t|won'?t|can'?t|don'?t)/i,/(?:still|again) (?:broken|not working|failing|wrong)/i,/already told you/i,/come on[!.]/i,/seriously\?/i,/how (?:many|much) (?:times|more)/i,/nothing (?:works?|is working)/i];function vg(t){return typeof t!="string"||!t?!1:gv.some(e=>e.test(t))}function yv(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let s=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(s.length<6)return{text:t,truncated:!1,repeatCount:0};let n=new Map;for(let l=0;l<=s.length-3;l++){let c=s.slice(l,l+3).join("").trim();c.length>30&&n.set(c,(n.get(c)||0)+1)}let o=0,r="";for(let[l,c]of n)c>o&&(o=c,r=l);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
808
+ [No image found in clipboard]`}return r.length>1?r:t})()}var hT=[/\bwtf\b/i,/\buff\b/i,/\bugh\b/i,/\bffs\b/i,/\bargh\b/i,/why (?:isn'?t|doesn'?t|won'?t|can'?t|don'?t)/i,/(?:still|again) (?:broken|not working|failing|wrong)/i,/already told you/i,/come on[!.]/i,/seriously\?/i,/how (?:many|much) (?:times|more)/i,/nothing (?:works?|is working)/i];function Qg(t){return typeof t!="string"||!t?!1:hT.some(e=>e.test(t))}function mT(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let s=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(s.length<6)return{text:t,truncated:!1,repeatCount:0};let n=new Map;for(let l=0;l<=s.length-3;l++){let c=s.slice(l,l+3).join("").trim();c.length>30&&n.set(c,(n.get(c)||0)+1)}let o=0,r="";for(let[l,c]of n)c>o&&(o=c,r=l);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
789
809
 
790
- [SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let l=0,c=-1,u=0;for(;l<2;){let d=t.indexOf(r,u);if(d===-1)break;l++,c=d+r.length,u=d+1}a=c>0?t.slice(0,c)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function Cc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
810
+ [SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let l=0,c=-1,u=0;for(;l<2;){let d=t.indexOf(r,u);if(d===-1)break;l++,c=d+r.length,u=d+1}a=c>0?t.slice(0,c)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function Wc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
791
811
  `),n=new Map;for(let p of s){let m=p.trim();m.length>=20&&n.set(m,(n.get(m)||0)+1)}let o=0,r="";for(let[p,m]of n)m>o&&(o=m,r=p);let a=r.toLowerCase().includes("read_file")||r.toLowerCase().includes("reading")?2:e;if(o<=a)return{text:t,truncated:!1,repeatCount:o};let l=`
792
812
 
793
- \u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let p=t.indexOf(r,d);if(p===-1)break;c++,u=p+r.length,d=p+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:o}}var yc=null,wc=null,_c=null;function it(){if(yc===null){let{TOOL_DEFINITIONS:t}=po();yc=t}return wc===null&&(wc=sv()),_c===null&&(_c=tv()),[...yc,...wc,..._c]}var Ac=50;function wv(t){Number.isFinite(t)&&t>0&&(Ac=t)}var Pi=()=>null;function _v(t){Pi=t}var Xo=null,Oc=null,Js=null,Li=new Map,$v=1e4,bv=6e3,kv=/\b((?:API|ACCESS|AUTH|BEARER|CLIENT|GITHUB|GITLAB|SLACK|STRIPE|TWILIO|SENDGRID|AWS|GCP|AZURE|OPENAI|ANTHROPIC|GEMINI|OLLAMA)[_A-Z0-9]*(?:KEY|TOKEN|SECRET|PASS(?:WORD)?|CREDENTIAL)[_A-Z0-9]*)\s*=\s*["']?([A-Za-z0-9\-_.+/=]{10,})["']?/g;function xv(t){return!t||typeof t!="string"?t:t.replace(kv,(e,s)=>`${s}=***REDACTED***`)}var Sv=7e3,Ev=4e3;function vv(t,e=null){let s=xv(t),n=CE(s),o=e==="read_file"?Sv:$v,r=e==="read_file"?Ev:bv;if(n>o)try{let{compressToolResult:i}=Qt();return i(s,r)}catch{return s}return s}function Tg(t){try{let{getActiveModel:e}=ot(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Li.has(n))return Li.get(n);let o=fg(t);return Li.set(n,o),o}catch{return fg(t)}}function Tv(){Li.clear()}var Vo={hash:null,ts:0},Rv=3e4;async function Rg(){if(Vo.hash&&Date.now()-Vo.ts<Rv)return Vo.hash;try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=Co(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Cn.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return Vo={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Nc(){Xo=null,Oc=null,Vo={hash:null,ts:0},Js=null}var Cv=new Set(["spawn_agents"]),$c=10,bc=10,Oi=5,gg=6e4,kc=12e4,Av=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Ov(t){try{let e=require("fs"),s=require("path"),n=s.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let o=s.join(n,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}GE(t=>{HE(t,"allow"),YE(),console.log(`${h.green} \u2713 ${t}: always allow${h.reset}`)});async function Nv(t){let e=t.function.name,s=EE(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let d=it().find(p=>p.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return j(`${h.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${h.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
813
+ \u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let p=t.indexOf(r,d);if(p===-1)break;c++,u=p+r.length,d=p+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:o}}var Oc=null,Nc=null,Mc=null;function ut(){if(Oc===null){let{TOOL_DEFINITIONS:t}=yo();Oc=t}return Nc===null&&(Nc=tT()),Mc===null&&(Mc=Qv()),[...Oc,...Nc,...Mc]}var Hc=50;function gT(t){Number.isFinite(t)&&t>0&&(Hc=t)}var Wi=()=>null;function yT(t){Wi=t}var tr=null,Yc=null,eo=null,Hi=new Map,wT=1e4,$T=6e3,_T=/\b((?:API|ACCESS|AUTH|BEARER|CLIENT|GITHUB|GITLAB|SLACK|STRIPE|TWILIO|SENDGRID|AWS|GCP|AZURE|OPENAI|ANTHROPIC|GEMINI|OLLAMA)[_A-Z0-9]*(?:KEY|TOKEN|SECRET|PASS(?:WORD)?|CREDENTIAL)[_A-Z0-9]*)\s*=\s*["']?([A-Za-z0-9\-_.+/=]{10,})["']?/g;function bT(t){return!t||typeof t!="string"?t:t.replace(_T,(e,s)=>`${s}=***REDACTED***`)}var kT=7e3,xT=4e3;function ST(t,e=null){let s=bT(t),n=Tv(s),o=e==="read_file"?kT:wT,r=e==="read_file"?xT:$T;if(n>o)try{let{compressToolResult:i}=on();return i(s,r)}catch{return s}return s}function ey(t){try{let{getActiveModel:e}=lt(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Hi.has(n))return Hi.get(n);let o=qg(t);return Hi.set(n,o),o}catch{return qg(t)}}function ET(){Hi.clear()}var nr={hash:null,ts:0},vT=3e4;async function ty(){if(nr.hash&&Date.now()-nr.ts<vT)return nr.hash;try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=Mo(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(je.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return nr={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Gc(){tr=null,Yc=null,nr={hash:null,ts:0},eo=null}var TT=new Set(["spawn_agents"]),Pc=10,Lc=10,Fi=5,Wg=6e4,Ic=12e4,RT=process.env.NEX_STALE_AUTO_SWITCH!=="0";function CT(t){try{let e=require("fs"),s=require("path"),n=s.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let o=s.join(n,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}Hv(t=>{Uv(t,"allow"),Wv(),console.log(`${h.green} \u2713 ${t}: always allow${h.reset}`)});async function AT(t){let e=t.function.name,s=xv(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let d=ut().find(p=>p.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return j(`${h.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${h.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
794
814
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
795
815
 
796
816
  Expected JSON schema for "${e}":
797
817
  ${f}
798
818
 
799
- Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}if(s&&typeof s.path=="string")try{let u=require("os"),d=eo.resolve(process.cwd(),s.path.replace(/^~/,u.homedir())),f=s.path;s.path=eo.relative(process.cwd(),d)||".",Object.defineProperty(s,"_originalPath",{value:f,enumerable:!1})}catch(u){console.error("path resolution failed:",u.message)}let o=iv(e,s);if(!o.valid){j(`${h.yellow} \u26A0 ${e}: ${o.error.split(`
800
- `)[0]}${h.reset}`);let u=(wg.get(e)||0)+1;wg.set(e,u);let d=u>=2?`${o.error}
819
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}if(s&&typeof s.path=="string")try{let u=require("os"),d=Ye.resolve(process.cwd(),s.path.replace(/^~/,u.homedir())),f=s.path;s.path=Ye.relative(process.cwd(),d)||".",Object.defineProperty(s,"_originalPath",{value:f,enumerable:!1})}catch(u){console.error("path resolution failed:",u.message)}let o=oT(e,s);if(!o.valid){j(`${h.yellow} \u26A0 ${e}: ${o.error.split(`
820
+ `)[0]}${h.reset}`);let u=(Yg.get(e)||0)+1;Yg.set(e,u);let d=u>=2?`${o.error}
801
821
 
802
- [SYSTEM: This is argument error #${u} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:o.error;return{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:n}}}let r=o.corrected||s;if(o.corrected){let u=Object.keys(s),d=Object.keys(o.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${h.dim} \u2713 ${e}: corrected args (${f.join(", ")})${h.reset}`)}if(tr()&&!bg.has(e))return console.log(`${h.yellow} \u2717 ${e}: blocked in plan mode${h.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),a=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),l=e==="spawn_agents"&&Array.isArray(r?.agents)&&r.agents.length>0&&r.agents.every(u=>u.background===!0);if(we&&Pe==="plan"&&!i.has(e)&&!e.startsWith("skill_")&&!l)return An++,j(`${h.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${An})${h.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${e}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:n}};if(we&&Pe==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return j(`${h.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${h.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${e}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:n}};let c=WE(e);if(c==="deny")return console.log(`${h.red} \u2717 ${e}: denied by permissions${h.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(c==="ask"){let u=` Allow ${e}?`;return e==="bash"&&r.command&&(u=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await $g(u,{toolName:e})?{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function Mv(t,e,s={}){let n=await ov(t,e);if(n!==null)return n;let o=await ev(t,e);return o!==null?o:vE(t,e,s)}function Pv(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e._originalPath||e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function xc(t,e=!1){e||console.log(kE(t.fnName,t.args));let s=lg("pre-tool",{tool_name:t.fnName}),n=s.results;if(s.blocked){let _=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${s.blockReason}`;e||console.log(`${h.yellow} [hook pre-tool] BLOCKED: ${s.blockReason}${h.reset}`);let k=Tc(t.fnName,t.args,_,!0);return e||console.log(k),{msg:{role:"tool",content:_,tool_call_id:t.callId},summary:k}}if(!e&&n.length>0)for(let _ of n)_.success?console.log(`${h.dim} [hook pre-tool] ${_.command} \u2192 ${_.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook pre-tool] ${_.command} \u2192 ERROR: ${_.error}${h.reset}`);sn?.onToolStart&&sn.onToolStart(t.fnName,t.args);let o=await Mv(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;o&&typeof o=="object"&&o.text?(i=String(o.text),Array.isArray(o.images)&&o.images.length>0&&(r=o.images)):i=String(o??"");let a=i.length>5e4?i.substring(0,5e4)+`
822
+ [SYSTEM: This is argument error #${u} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:o.error;return{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:n}}}let r=o.corrected||s;if(o.corrected){let u=Object.keys(s),d=Object.keys(o.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${h.dim} \u2713 ${e}: corrected args (${f.join(", ")})${h.reset}`)}if(ar()&&!Kg.has(e))return console.log(`${h.yellow} \u2717 ${e}: blocked in plan mode${h.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),a=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),l=e==="spawn_agents"&&Array.isArray(r?.agents)&&r.agents.length>0&&r.agents.every(u=>u.background===!0);if($e&&Me==="plan"&&!i.has(e)&&!e.startsWith("skill_")&&!l)return In++,j(`${h.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${In})${h.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${e}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:n}};if($e&&Me==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return j(`${h.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${h.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${e}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:n}};let c=Bv(e);if(c==="deny")return console.log(`${h.red} \u2717 ${e}: denied by permissions${h.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(c==="ask"){let u=` Allow ${e}?`;return e==="bash"&&r.command&&(u=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await zg(u,{toolName:e})?{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function OT(t,e,s={}){let n=await nT(t,e);if(n!==null)return n;let o=await Zv(t,e);return o!==null?o:Sv(t,e,s)}function NT(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e._originalPath||e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function jc(t,e=!1){e||console.log(_v(t.fnName,t.args));let s=Lg("pre-tool",{tool_name:t.fnName}),n=s.results;if(s.blocked){let $=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${s.blockReason}`;e||console.log(`${h.yellow} [hook pre-tool] BLOCKED: ${s.blockReason}${h.reset}`);let k=Bc(t.fnName,t.args,$,!0);return e||console.log(k),{msg:{role:"tool",content:$,tool_call_id:t.callId},summary:k}}if(!e&&n.length>0)for(let $ of n)$.success?console.log(`${h.dim} [hook pre-tool] ${$.command} \u2192 ${$.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook pre-tool] ${$.command} \u2192 ERROR: ${$.error}${h.reset}`);un?.onToolStart&&un.onToolStart(t.fnName,t.args);let o=await OT(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;o&&typeof o=="object"&&o.text?(i=String(o.text),Array.isArray(o.images)&&o.images.length>0&&(r=o.images)):i=String(o??"");let a=i.length>5e4?i.substring(0,5e4)+`
803
823
  ...(truncated ${i.length-5e4} chars)`:i,l=a.split(`
804
- `)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=Tc(t.fnName,t.args,a,c);e||console.log(u),sn?.onToolEnd&&sn.onToolEnd(t.fnName,u,!c);let f=lg("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let _ of f)_.success?console.log(`${h.dim} [hook post-tool] ${_.command} \u2192 ${_.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook post-tool] ${_.command} \u2192 ERROR: ${_.error}${h.reset}`);let m=vv(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let _=t.args.command.trim();!/cat\s*>|<</.test(_)&&/\bcat\s+\S/.test(_)?m+=`
805
- HINT: use read_file instead of bash cat \u2014 it is faster, context-efficient, and the preferred tool for reading files.`:/^\s*ls(\s|$)/.test(_)&&!/npm|yarn|pnpm|make|git\b/.test(_)?m+=`
806
- HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(_)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(_)&&(m+=`
807
- HINT: use glob instead of bash find for file discovery \u2014 it is faster and the preferred tool (e.g. glob('**/*.jsx')).`)}return{msg:{role:"tool",content:r?[{type:"text",text:m},...r.map(_=>({type:"image",media_type:_.media_type,data:_.base64}))]:m,tool_call_id:t.callId},summary:u}}var Lv=[{re:/TypeError:\s*([^\n]{0,120})/i,label:"TypeError"},{re:/SyntaxError:\s*([^\n]{0,120})/i,label:"SyntaxError"},{re:/ReferenceError:\s*([^\n]{0,120})/i,label:"ReferenceError"},{re:/Cannot find module\s*'([^']+)'/i,label:"Cannot find module"},{re:/Error:\s*ENOENT[^\n]{0,120}/i,label:"ENOENT"},{re:/Error:\s*EACCES[^\n]{0,120}/i,label:"EACCES"},{re:/Error:\s*EADDRINUSE[^\n]{0,120}/i,label:"EADDRINUSE"},{re:/ImportError:\s*([^\n]{0,120})/i,label:"ImportError"},{re:/ModuleNotFoundError:\s*([^\n]{0,120})/i,label:"ModuleNotFoundError"},{re:/NameError:\s*([^\n]{0,120})/i,label:"NameError"},{re:/AttributeError:\s*([^\n]{0,120})/i,label:"AttributeError"},{re:/KeyError:\s*([^\n]{0,120})/i,label:"KeyError"},{re:/ValueError:\s*([^\n]{0,120})/i,label:"ValueError"},{re:/panic:\s*([^\n]{0,120})/i,label:"Go panic"},{re:/java\.lang\.\w+Exception[^\n]{0,80}/i,label:"Java exception"}];function Sc(t){for(let{re:e,label:s}of Lv){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function Iv(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=null;if(e&&!s.skipSpinner){let l=t.filter(c=>c.canExecute);if(l.length>0){let c;if(l.length===1){let u=l[0],d=Pv(u.fnName,u.args);c=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=l.map(d=>d.fnName).join(", ");c=`\u23FA ${l.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new Xs(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await xc(t[l],e);n[l]=c,o.push(u)}else{let l=r.map(u=>xc(t[u],e)),c=await Promise.all(l);for(let u=0;u<r.length;u++)n[r[u]]=c[u].msg,o.push(c[u].summary)}r=[]}}for(let l=0;l<t.length;l++){let c=t[l];if(!c.canExecute){await a(),n[l]=c.errorResult,o.push(Tc(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(Cv.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await xc(c,e);n[l]=u,o.push(d)}else r.push(l)}if(await a(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return{results:n,summaries:o}}var P=[],yg=300,Cg=900*1e3;function nn(t,e){let s=t.get(e);return s?Date.now()-s.ts>Cg?(t.delete(e),0):s.count:0}function ls(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=Cg?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function Ec(t,e,s){t.set(e,{count:s,ts:Date.now()})}var Bc=new Map,Ag=new Map,Ii=new Map,nr=new Set,Og=new Map,Di=new Map,sr=new Set,pn=new Map,Rn=new Map,or=new Map,Pt=new Map,fs=new Map,wg=new Map,zi=new Map,Mc=new Map,Lt=0,Jo=0,ji=0,Pc="",qi=0,vt=!1,Ni=0,Fi=0,cs=-1,Lc=!1,Bi=0,Ui=!1,Dt=0,jt=!1,Gt=0,zt=0,et=!1,wt="",Zo=0,Tn=0,Wi="",us=0,ds=0,Hi="",Go=0,It=!1,Ic=!1,rr=new Map,ir=new Set,Qo=null,vc=!1,zo=0,_g=!1,Pe="plan",Ki=0,we=!1,An=0,mn=null,Dc=null,jc=null,Zs=0,Qs=null,hs=[];function Ks(t,e){t===Pc?(qi++,debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${qi})${h.reset}
808
- `)):(Pc=t,qi=1,j(`${e} \u26A0 ${t}${h.reset}`))}var Yi=[];function Dv(t){Yi.push(t.trim())}function jv(){return Yi.length===0?null:Yi.splice(0,Yi.length).join(`
809
- `)}function qv(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,s=e!==null?`
824
+ `)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=Bc(t.fnName,t.args,a,c);e||console.log(u),un?.onToolEnd&&un.onToolEnd(t.fnName,u,!c);let f=Lg("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let $ of f)$.success?console.log(`${h.dim} [hook post-tool] ${$.command} \u2192 ${$.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook post-tool] ${$.command} \u2192 ERROR: ${$.error}${h.reset}`);let m=ST(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let $=t.args.command.trim();!/cat\s*>|<</.test($)&&/\bcat\s+\S/.test($)?m+=`
825
+ HINT: use read_file instead of bash cat \u2014 it is faster, context-efficient, and the preferred tool for reading files.`:/^\s*ls(\s|$)/.test($)&&!/npm|yarn|pnpm|make|git\b/.test($)?m+=`
826
+ HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test($)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test($)&&(m+=`
827
+ HINT: use glob instead of bash find for file discovery \u2014 it is faster and the preferred tool (e.g. glob('**/*.jsx')).`)}return{msg:{role:"tool",content:r?[{type:"text",text:m},...r.map($=>({type:"image",media_type:$.media_type,data:$.base64}))]:m,tool_call_id:t.callId},summary:u}}var MT=[{re:/TypeError:\s*([^\n]{0,120})/i,label:"TypeError"},{re:/SyntaxError:\s*([^\n]{0,120})/i,label:"SyntaxError"},{re:/ReferenceError:\s*([^\n]{0,120})/i,label:"ReferenceError"},{re:/Cannot find module\s*'([^']+)'/i,label:"Cannot find module"},{re:/Error:\s*ENOENT[^\n]{0,120}/i,label:"ENOENT"},{re:/Error:\s*EACCES[^\n]{0,120}/i,label:"EACCES"},{re:/Error:\s*EADDRINUSE[^\n]{0,120}/i,label:"EADDRINUSE"},{re:/ImportError:\s*([^\n]{0,120})/i,label:"ImportError"},{re:/ModuleNotFoundError:\s*([^\n]{0,120})/i,label:"ModuleNotFoundError"},{re:/NameError:\s*([^\n]{0,120})/i,label:"NameError"},{re:/AttributeError:\s*([^\n]{0,120})/i,label:"AttributeError"},{re:/KeyError:\s*([^\n]{0,120})/i,label:"KeyError"},{re:/ValueError:\s*([^\n]{0,120})/i,label:"ValueError"},{re:/panic:\s*([^\n]{0,120})/i,label:"Go panic"},{re:/java\.lang\.\w+Exception[^\n]{0,80}/i,label:"Java exception"}];function Dc(t){for(let{re:e,label:s}of MT){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function PT(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=null;if(e&&!s.skipSpinner){let l=t.filter(c=>c.canExecute);if(l.length>0){let c;if(l.length===1){let u=l[0],d=NT(u.fnName,u.args);c=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=l.map(d=>d.fnName).join(", ");c=`\u23FA ${l.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new Zs(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await jc(t[l],e);n[l]=c,o.push(u)}else{let l=r.map(u=>jc(t[u],e)),c=await Promise.all(l);for(let u=0;u<r.length;u++)n[r[u]]=c[u].msg,o.push(c[u].summary)}r=[]}}for(let l=0;l<t.length;l++){let c=t[l];if(!c.canExecute){await a(),n[l]=c.errorResult,o.push(Bc(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(TT.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await jc(c,e);n[l]=u,o.push(d)}else r.push(l)}if(await a(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return{results:n,summaries:o}}var P=[],Hg=300,ny=900*1e3;function ln(t,e){let s=t.get(e);return s?Date.now()-s.ts>ny?(t.delete(e),0):s.count:0}function hs(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=ny?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function qc(t,e,s){t.set(e,{count:s,ts:Date.now()})}var tu=new Map,sy=new Map,Yi=new Map,lr=new Set,oy=new Map,Gi=new Map,cr=new Set,bn=new Map,Ln=new Map,ur=new Map,Dt=new Map,ws=new Map,Yg=new Map,na=new Map,zc=new Map,qt=0,sr=0,zi=0,Kc="",Ki=0,At=!1,Bi=0,Xi=0,ms=-1,Xc=!1,Vi=0,Ji=!1,Bt=0,Ut=!1,Jt=0,Zt=0,ot=!1,bt="",or=0,Pn=0,Zi="",gs=0,ys=0,Qi="",Zo=0,Ft=!1,Vc=!1,fr=new Map,pr=new Set,rr=null,Fc=!1,Qo=0,Gg=!1,Me="plan",sa=0,$e=!1,In=0,kn=null,Jc=null,Zc=null,to=0,dr=0,no=0,so=null,$s=[];function Js(t,e){t===Kc?(Ki++,debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Ki})${h.reset}
828
+ `)):(Kc=t,Ki=1,j(`${e} \u26A0 ${t}${h.reset}`))}var ea=[];function LT(t){ea.push(t.trim())}function IT(){return ea.length===0?null:ea.splice(0,ea.length).join(`
829
+ `)}function jT(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,s=e!==null?`
810
830
  Duration: ${e}s`:"",n=typeof t.result.result=="string"?t.result.result.slice(0,4e3):JSON.stringify(t.result.result||"").slice(0,4e3),o=t.result.filesModified&&t.result.filesModified.length>0?`
811
831
  Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
812
832
  Job: ${t.jobId}
813
833
  Task: "${t.agentDef.task}"`+s+`
814
834
  Status: ${t.result.status||"done"}`+o+`
815
- Result: ${n}`}function Mi(t,e){let{getCompletedJobs:s}=zs(),n=s();for(let o of n){let r={role:"user",content:qv(o)};t.push(r),e.push(r);let i=o.result?.status||"done",a=i==="failed"?h.red+" \u2717":h.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${o.agentDef.task.slice(0,50)} \u2014 ${String(o.result?.result||"").slice(0,80)}${h.reset}
816
- `)}}function Ng(t,e){let s=[],n=new Set([...e.keys(),...nr,...sr]);if(!n.size||!t)return s;for(let o of n){let r=o.split("/").pop();if(r&&(t.includes(r)||t.includes(o))){let a=t.split(`
817
- `).find(l=>l.includes(r)||l.includes(o));s.push({file:o,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return s}function Ko(t,e,s,n){if(!we)return null;let o=Pe;Pe=t,Ki=0,mn=Rc(t,Qs),Dt=0,jt=!1,Gt=0,zt=0,fs.clear(),zi.clear(),Bc.clear(),or.clear(),t==="implement"&&(hs=Ng(e||"",pn));let r=hs.length>0?`
835
+ Result: ${n}`}function Ui(t,e){let{getCompletedJobs:s}=Vs(),n=s();for(let o of n){let r={role:"user",content:jT(o)};t.push(r),e.push(r);let i=o.result?.status||"done",a=i==="failed"?h.red+" \u2717":h.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${o.agentDef.task.slice(0,50)} \u2014 ${String(o.result?.result||"").slice(0,80)}${h.reset}
836
+ `)}}function ry(t,e){let s=[],n=new Set([...e.keys(),...lr,...cr]);if(!n.size||!t)return s;for(let o of n){let r=o.split("/").pop();if(r&&(t.includes(r)||t.includes(o))){let a=t.split(`
837
+ `).find(l=>l.includes(r)||l.includes(o));s.push({file:o,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return s}function DT(t){if(!t||typeof t!="string")return[];let e=t.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g)||[],s=new Set(["the","and","for","with","from","into","that","this","when","then","have","your","just","read","write","edit","file","files","test","tests","verify","phase","implement","summary","report","pass","fail","changes","change","address","original","task","user","request","code","module","function","class"]),n=new Set,o=[];for(let r of e){let i=r.toLowerCase();s.has(i)||n.has(i)||(n.add(i),o.push(r))}return o.sort((r,i)=>i.length-r.length),o.slice(0,6)}function qT(){return je.existsSync(Ye.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":je.existsSync(Ye.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function cn(t){let e=qT();return t==="test"?e==="yarn"?"yarn test":e==="pnpm"?"pnpm test":"npm test":e==="yarn"?`yarn ${t}`:e==="pnpm"?`pnpm run ${t}`:`npm run ${t}`}async function iy(t){let e=DT(t);if(e.length===0)return[];let{searchContentIndex:s}=mn(),n=[],o=new Set;for(let r of e)try{let i=await s(r,void 0,process.cwd());for(let a of i.slice(0,3)){let l=`${a.file}:${a.name}:${a.line}`;if(!o.has(l)&&(o.add(l),n.push(a),n.length>=5))return n}}catch{}return n}async function ay(t){let e=await iy(t);if(e.length===0)return"";let{getRelatedFiles:s}=mn(),n=["Likely symbol targets:"];for(let o=0;o<e.length;o++){let r=e[o],i=Math.max(1,r.line-20),a=r.line+40;n.push(`${o+1}. ${r.name} (${r.type}) in ${r.file}:${r.line} -> read_file(path='${r.file}', line_start=${i}, line_end=${a})`);try{let l=await s(r.file,process.cwd(),3);l.length>0&&n.push(` Follow-up files: ${l.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}}return`${n.join(`
838
+ `)}
839
+ Use these exact targeted reads before broader searching.
840
+
841
+ `}function nu(t){let{getFileIndex:e}=mn(),n=e().filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(n.length===0)return[];let o=new Set;for(let r of t||[]){let i=Ye.basename(String(r)).replace(/\.[^.]+$/,"");if(!(i.length<3)){for(let a of n)if(a.includes(i)&&o.add(a),o.size>=4)return[...o]}}return[...o]}function FT(t,e={}){if(!Array.isArray(t)||t.length===0)return[];let s=t.slice(0,4).join(" "),n=[],o=String(e.test||"");return/vitest/.test(o)||je.existsSync(Ye.join(process.cwd(),"vitest.config.ts"))||je.existsSync(Ye.join(process.cwd(),"vitest.config.js"))?n.push(`npx vitest run ${s}`):(/jest/.test(o)||je.existsSync(Ye.join(process.cwd(),"jest.config.js"))||je.existsSync(Ye.join(process.cwd(),"jest.config.cjs"))||je.existsSync(Ye.join(process.cwd(),"jest.config.mjs")))&&n.push(`npx jest --runInBand ${s}`),(je.existsSync(Ye.join(process.cwd(),"pytest.ini"))||je.existsSync(Ye.join(process.cwd(),"pyproject.toml")))&&t.some(r=>/\.py$/i.test(r))&&n.push(`pytest ${t.filter(r=>/\.py$/i.test(r)).slice(0,4).join(" ")}`),n}async function er(t,e,s,n){if(!$e)return null;let o=Me;Me=t,sa=0,kn=Uc(t,so),t==="verify"&&(dr=0,no=0),Bt=0,Ut=!1,Jt=0,Zt=0,ws.clear(),na.clear(),tu.clear(),ur.clear(),t==="implement"&&($s=ry(e||"",bn));let r=$s.length>0?`
818
842
 
819
843
  ACTION ITEMS (execute these in order, do NOT re-read these files):
820
- `+hs.map((a,l)=>`${l+1}. ${a.file} \u2014 ${a.action}`).join(`
821
- `):"",i;if(t==="implement")Dc=e?.slice(0,2e3)||"",i=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
822
- ${Dc}
823
-
824
- Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){jc=e?.slice(0,500)||"";let a=s?[...s].join(", "):"none";i=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
825
- 1. Read each modified file and confirm changes are correct
826
- 2. If test command exists (npm test / pytest): run it
827
- 3. If linter exists: run it
844
+ `+$s.map((l,c)=>`${c+1}. ${l.file} \u2014 ${l.action}`).join(`
845
+ `):"",i=await ay(t==="verify"?n:e||n||""),a;if(t==="implement")Jc=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
846
+ ${Jc}
847
+
848
+ ${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){Zc=e?.slice(0,500)||"";let l=s?[...s].join(", "):"none",c=ly(s),u=nu(s),d=c.length>0?`Suggested checks (run the narrowest ones that fit the change):
849
+ ${c.map((p,m)=>`${m+1}. ${p}`).join(`
850
+ `)}
851
+
852
+ `:"",f=u.length>0?`Likely related tests:
853
+ ${u.map((p,m)=>`${m+1}. ${p}`).join(`
854
+ `)}
855
+ Prefer these before broader suites when a targeted run is possible.
856
+
857
+ `:"";a=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
858
+ 1. Read only the modified sections/files and confirm the final code matches intent
859
+ 2. Run the smallest relevant verification command(s)
860
+ 3. If one check fails, explain the failure precisely and loop back with a focused fix
828
861
  4. Does the implementation address: "${(n||"").slice(0,200)}"?
829
862
  Report PASS (all good) or FAIL (list specific issues).
830
863
 
831
- Files modified: ${a}
832
- Summary: ${jc}`}return j(`${h.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${mn||"default"})${h.reset}`),i?{role:"user",content:i}:null}function Fv(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
833
- `];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),er()?o.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files, documentation): ALWAYS use write_file to create the file on disk. In auto mode the user cannot see your text output \u2014 only files on disk matter."):o.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files): paste the COMPLETE file content in a fenced code block in your TEXT RESPONSE \u2014 writing a file with a tool does NOT make it visible. The fenced code block MUST appear in your response, not just via write_file."),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(' \u2022 For Makefiles, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),o.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),o.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),o.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),o.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),o.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),o.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),o.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),o.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),o.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let r=e||"English";o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||"English";return o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),n&&o.push(`
864
+ Files modified: ${l}
865
+ ${i}${d}${f}Summary: ${Zc}`}return j(`${h.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${kn||"default"})${h.reset}`),a?{role:"user",content:a}:null}function ly(t){let e=[],n=[...t||[]].map(l=>String(l).toLowerCase()),o={};try{let l=Ye.join(process.cwd(),"package.json");if(je.existsSync(l)){o=JSON.parse(je.readFileSync(l,"utf-8")).scripts||{};let u=[["test",cn("test")],["lint",cn("lint")],["typecheck",cn("typecheck")],["check",cn("check")],["build",cn("build")]];for(let[d,f]of u)o[d]&&e.push(f)}}catch{}e.length===0&&(je.existsSync(Ye.join(process.cwd(),"package.json"))&&e.push(cn("test")),(je.existsSync(Ye.join(process.cwd(),"pytest.ini"))||je.existsSync(Ye.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=nu(t);e.unshift(...FT(r,o));let i=n.some(l=>/\.(ts|tsx)$/.test(l)),a=n.some(l=>/\.(js|jsx|ts|tsx)$/.test(l));return i&&!e.includes(cn("typecheck"))&&e.push(cn("typecheck")),a&&!e.includes(cn("lint"))&&e.push(cn("lint")),[...new Set(e)].slice(0,4)}function BT(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
866
+ `];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),ir()?o.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files, documentation): ALWAYS use write_file to create the file on disk. In auto mode the user cannot see your text output \u2014 only files on disk matter."):o.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files): paste the COMPLETE file content in a fenced code block in your TEXT RESPONSE \u2014 writing a file with a tool does NOT make it visible. The fenced code block MUST appear in your response, not just via write_file."),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(' \u2022 For Makefiles, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),o.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),o.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),o.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),o.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),o.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),o.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),o.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),o.push(" \u2022 Express/fetch error handling: When adding error handling to an Express route that fetches by ID: (1) validate the ID parameter first (check it exists and is a valid format), (2) wrap fetch in try-catch, (3) check response.ok and handle 404 specifically, (4) call next(error) to pass errors to Express error\u2011handling middleware \u2014 do not just send a raw 500 response."),o.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),o.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let r=e||"English";o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||"English";return o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),n&&o.push(`
834
867
  This is a hard requirement. Always respond in ${n}. Do NOT switch to any other language \u2014 even if the user writes to you in German, French, or any other language, your reply MUST be in ${n}.`),o.join(`
835
868
  `)+`
836
869
 
837
- `}function Bv(){if(Js!==null)return Js;try{let e=lv().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:av(r.id,o.name),name:r.name})));if(e.length<2)return Js="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
870
+ `}function UT(){if(eo!==null)return eo;try{let e=iT().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:rT(r.id,o.name),name:r.name})));if(e.length<2)return eo="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
838
871
  # Sub-Agent Model Routing
839
872
 
840
873
  `;n+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',n+=`| Model | Tier | Auto-assigned for |
841
874
  |---|---|---|
842
875
  `;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
843
- `;return Js=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Js="",""}}var qc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function Uv(t){let e=t.indexOf(qc);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+qc.length).trimStart()}}async function Fc(){let t=await Rg()+":"+Kt();if(Xo!==null&&t===Oc)return Xo;let e=await TE(process.cwd()),s=qE(),n=nv(),o=tr()?zE():"",r=Fv(),i=FE(),a=uv(Kt());return Xo=`${a?`## Model Briefing
876
+ `;return eo=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),eo="",""}}var Qc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function WT(t){let e=t.indexOf(Qc);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Qc.length).trimStart()}}async function eu(){let t=await ty()+":"+Qt();if(tr!==null&&t===Yc)return tr;let e=await Ev(process.cwd()),s=jv(),n=eT(),o=ar()?Yv():"",r=BT(),i=Dv(),a=lT(Qt());return tr=`${a?`## Model Briefing
844
877
  ${a}
845
878
 
846
879
  ---
@@ -861,7 +894,7 @@ ${o}
861
894
  ${r?`${r}
862
895
  `:""}${i?`${i}
863
896
 
864
- `:""}${er()?`# YOLO Mode \u2014 Auto-Execute
897
+ `:""}${ir()?`# YOLO Mode \u2014 Auto-Execute
865
898
 
866
899
  You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
867
900
  - NEVER ask for confirmation \u2014 just execute tasks directly
@@ -892,6 +925,9 @@ Plan mode is ONLY active when explicitly activated via the /plan command or show
892
925
  - Be concise but complete. Keep responses focused while ensuring the user gets the information they asked for.
893
926
  - When referencing code, include file:line (e.g. src/app.js:42) so the user can navigate.
894
927
  - Do not make up file paths or URLs. Use tools to discover them.
928
+ - Treat the repo map in PROJECT CONTEXT as your first navigation aid. Start with the most likely 2-5 files or symbols, not a repo-wide wander.
929
+ - Prefer symbol-aware, high-signal retrieval: first locate the owning file/module, then read the exact function/class/section you need, then edit.
930
+ - For implementation tasks, keep the loop tight: diagnose -> edit the smallest viable surface -> run the narrowest meaningful verification -> continue only if still failing.
895
931
 
896
932
  # Response Quality (Critical)
897
933
 
@@ -1098,7 +1134,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
1098
1134
  - Instead: use bash with inline node -e '...' for quick one-off checks.
1099
1135
  - If the test is worth keeping, write it to tests/ with a proper name.
1100
1136
  - Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
1101
- ${Bv()}
1137
+ ${UT()}
1102
1138
 
1103
1139
  # Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
1104
1140
 
@@ -1148,6 +1184,7 @@ When a tool call returns ERROR \u2014 follow these exact recovery sequences:
1148
1184
  **After 2 consecutive failures at the same operation** \u2192 stop and explain the issue to the user.
1149
1185
 
1150
1186
  # Git Workflow
1187
+ - Always verify current branch before committing
1151
1188
 
1152
1189
  - Before committing, review changes with git_diff. Write messages that explain WHY, not WHAT.
1153
1190
  - Stage specific files rather than git add -A to avoid committing unrelated changes.
@@ -1289,86 +1326,86 @@ class ErrorBoundary extends React.Component {
1289
1326
  - Use migrations for schema changes, never manual ALTER TABLE
1290
1327
  - Add database-level constraints (unique, foreign key, check) not just app-level
1291
1328
 
1292
- `,Oc=t,Xo}function Mg(){Bc.clear(),Ag.clear(),Ii.clear(),nr.clear(),Og.clear(),Di.clear(),sr.clear(),pn.clear(),Rn.clear(),or.clear(),Pt.clear(),fs.clear(),zi.clear(),Mc.clear(),Lt=0,Jo=0,ji=0,vt=!1,Fi=0,cs=-1,Lc=!1,Bi=0,Ui=!1,Dt=0,jt=!1,Gt=0,zt=0,et=!1,wt="",Zo=0,Wi="",us=0,Hi="",ds=0,It=!1,Ic=!1,Pe="plan",Ki=0,we=!1,mn=null,Dc=null,jc=null,hs=[],Zs=0,An=0,Qs=null,rr.clear(),ir.clear(),Pc="",qi=0}function Wv(){P=[],Qo=null,Mg();try{let{resetCompactionFailures:t}=Ol();t()}catch{}try{let{cancelAllJobs:t}=zs();t()}catch{}}function Hv(){P.length>yg&&P.splice(0,P.length-yg)}function Yv(){return P.length}function Gv(){return P}function zv(t){P=t}async function Kv(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(d,f)=>new Promise(p=>{t(d,f,{cwd:s,timeout:3e3},(m,g)=>{p(m?"":(g||"").trim())})}),[o]=await Promise.all([n("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
1293
- `):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let c=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=eo.join(s,"package.json");if(e.existsSync(u))try{let d=JSON.parse(e.readFileSync(u,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let p=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";c+=`
1294
- \u{1F4E6} ${p}${m}`}}catch{}return c}function Xv(t){if(process.platform==="darwin")try{let{execFileSync:e}=require("child_process");e("osascript",["-e",`display notification "${t.replace(/"/g,'\\"')}" with title "nex-code"`],{timeout:3e3,stdio:"ignore"})}catch{}}function Oe(t,e,s,n,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((c,u)=>c+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,l=0;if(o){let c=Date.now()-o;l=Math.round(c/1e3),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1295
- ${h.dim} ${a}${h.reset}`),l>=30&&process.stdout.isTTY){let c=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;Xv(c)}if(ir.size>0&&rr.size>0)for(let c of ir){let u=rr.get(c);u&&console.log(`${h.dim} \u2714 task #${c} auto-matched: ${u.slice(0,60)}${h.reset}`)}s.size>0?console.log(`${h.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${h.reset}`):!r&&n.size>=5&&s.size===0&&t>=3?console.log(`${h.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${h.reset}`):n.size>0&&t>=2&&console.log(`${h.dim} \u{1F4A1} /save \xB7 /clear${h.reset}`)}async function Vv(){if(!process.stdout.isTTY)return{action:"quit"};let t=Vs(),e=Kt(),s=Gi.fast?.[t],n=Gi.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${h.dim}(${e})${h.reset}`}),o&&i.push({key:"f",label:`Switch to ${h.bold}${s}${h.reset} ${h.dim}\u2014 fast, low latency${h.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${h.bold}${n}${h.reset} ${h.dim}\u2014 reliable tool-calling, medium speed${h.reset}`,model:n}),i.push({key:"q",label:`${h.dim}Quit${h.reset}`}),console.log(),console.log(`${h.yellow} Stream stale \u2014 all retries exhausted.${h.reset} What would you like to do?`);for(let a of i)console.log(` ${h.cyan}[${a.key}]${h.reset} ${a.label}`);return process.stdout.write(` ${h.yellow}> ${h.reset}`),new Promise(a=>{let l=process.stdin,c=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,l.removeListener("data",d),l.setRawMode(c||!1),l.pause();let p=f.toLowerCase().trim();if(process.stdout.write(`${p}
1296
- `),f==="")return a({action:"quit"});let m=i.find(g=>g.key===p);!m||m.key==="q"||!m.model&&m.key!=="r"?a({action:"quit"}):m.key==="r"?a({action:"retry"}):a({action:"switch",model:m.model,provider:t})};l.on("data",d)})}function Jv(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,s=new Set,n;for(;(n=e.exec(t))!==null;){let o=n[1].replace(/\/$/,"");o.length>1&&o.split("/").filter(i=>i.length>2).forEach(i=>s.add(i))}return Array.from(s)}function Zv(t){let e=[];return(t.includes("@click")||t.includes("x-data")||t.includes("v-if")||t.includes("v-model"))&&e.push("Snippet contains Vue/Alpine.js directives (e.g., @click, v-model). Do not restrict your search to just .js/.ts/.vue files; also search .html and .py (templates) if appropriate."),(t.includes("className=")||t.includes("useEffect"))&&e.push("Snippet appears to be React. Look in .jsx, .tsx, .js, .ts files."),e}var sn=null;async function Qv(t,e=null,s={}){let n=cv(Kt());gg=n.staleWarn,kc=n.staleAbort,sn=e;let o=t;if(Qo&&typeof t=="string"&&(o=`${Qo}
1329
+ `,Yc=t,tr}function cy(){tu.clear(),sy.clear(),Yi.clear(),lr.clear(),oy.clear(),Gi.clear(),cr.clear(),bn.clear(),Ln.clear(),ur.clear(),Dt.clear(),ws.clear(),na.clear(),zc.clear(),qt=0,sr=0,zi=0,At=!1,Xi=0,ms=-1,Xc=!1,Vi=0,Ji=!1,Bt=0,Ut=!1,Jt=0,Zt=0,ot=!1,bt="",or=0,Zi="",gs=0,Qi="",ys=0,Ft=!1,Vc=!1,Me="plan",sa=0,$e=!1,kn=null,Jc=null,Zc=null,$s=[],to=0,dr=0,no=0,In=0,so=null,fr.clear(),pr.clear(),Kc="",Ki=0}function HT(){P=[],rr=null,cy();try{let{resetCompactionFailures:t}=Ul();t()}catch{}try{let{cancelAllJobs:t}=Vs();t()}catch{}}function YT(){P.length>Hg&&P.splice(0,P.length-Hg)}function GT(){return P.length}function zT(){return P}function KT(t){P=t}async function XT(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(d,f)=>new Promise(p=>{t(d,f,{cwd:s,timeout:3e3},(m,g)=>{p(m?"":(g||"").trim())})}),[o]=await Promise.all([n("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
1330
+ `):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let c=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=Ye.join(s,"package.json");if(e.existsSync(u))try{let d=JSON.parse(e.readFileSync(u,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let p=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";c+=`
1331
+ \u{1F4E6} ${p}${m}`}}catch{}return c}function VT(t){if(process.platform==="darwin")try{let{execFileSync:e}=require("child_process");e("osascript",["-e",`display notification "${t.replace(/"/g,'\\"')}" with title "nex-code"`],{timeout:3e3,stdio:"ignore"})}catch{}}function Ne(t,e,s,n,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((c,u)=>c+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,l=0;if(o){let c=Date.now()-o;l=Math.round(c/1e3),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1332
+ ${h.dim} ${a}${h.reset}`),l>=30&&process.stdout.isTTY){let c=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;VT(c)}if(pr.size>0&&fr.size>0)for(let c of pr){let u=fr.get(c);u&&console.log(`${h.dim} \u2714 task #${c} auto-matched: ${u.slice(0,60)}${h.reset}`)}s.size>0?console.log(`${h.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${h.reset}`):!r&&n.size>=5&&s.size===0&&t>=3?console.log(`${h.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${h.reset}`):n.size>0&&t>=2&&console.log(`${h.dim} \u{1F4A1} /save \xB7 /clear${h.reset}`)}async function JT(){if(!process.stdout.isTTY)return{action:"quit"};let t=Qs(),e=Qt(),s=ta.fast?.[t],n=ta.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${h.dim}(${e})${h.reset}`}),o&&i.push({key:"f",label:`Switch to ${h.bold}${s}${h.reset} ${h.dim}\u2014 fast, low latency${h.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${h.bold}${n}${h.reset} ${h.dim}\u2014 reliable tool-calling, medium speed${h.reset}`,model:n}),i.push({key:"q",label:`${h.dim}Quit${h.reset}`}),console.log(),console.log(`${h.yellow} Stream stale \u2014 all retries exhausted.${h.reset} What would you like to do?`);for(let a of i)console.log(` ${h.cyan}[${a.key}]${h.reset} ${a.label}`);return process.stdout.write(` ${h.yellow}> ${h.reset}`),new Promise(a=>{let l=process.stdin,c=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,l.removeListener("data",d),l.setRawMode(c||!1),l.pause();let p=f.toLowerCase().trim();if(process.stdout.write(`${p}
1333
+ `),f==="")return a({action:"quit"});let m=i.find(g=>g.key===p);!m||m.key==="q"||!m.model&&m.key!=="r"?a({action:"quit"}):m.key==="r"?a({action:"retry"}):a({action:"switch",model:m.model,provider:t})};l.on("data",d)})}function ZT(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,s=new Set,n;for(;(n=e.exec(t))!==null;){let o=n[1].replace(/\/$/,"");o.length>1&&o.split("/").filter(i=>i.length>2).forEach(i=>s.add(i))}return Array.from(s)}function QT(t){let e=[];return(t.includes("@click")||t.includes("x-data")||t.includes("v-if")||t.includes("v-model"))&&e.push("Snippet contains Vue/Alpine.js directives (e.g., @click, v-model). Do not restrict your search to just .js/.ts/.vue files; also search .html and .py (templates) if appropriate."),(t.includes("className=")||t.includes("useEffect"))&&e.push("Snippet appears to be React. Look in .jsx, .tsx, .js, .ts files."),e}var un=null;async function eR(t,e=null,s={}){let n=aT(Qt());Wg=n.staleWarn,Ic=n.staleAbort,un=e;let o=t;if(rr&&typeof t=="string"&&(o=`${rr}
1297
1334
 
1298
- ${t}`,Qo=null),typeof o=="string"){let me=Jv(o),ge=Zv(o);(me.length>0||ge.length>0)&&(o+=`
1335
+ ${t}`,rr=null),typeof o=="string"){let ge=ZT(o),ye=QT(o);(ge.length>0||ye.length>0)&&(o+=`
1299
1336
 
1300
1337
  [System Note for Assistant: To resolve this task faster, consider these hints:
1301
- `,me.length>0&&(o+=`- The user mentioned URLs containing the paths/folders: ${me.join(", ")}. Prioritize searching these folder names using glob or grep first.
1302
- `),ge.length>0&&ge.forEach(xe=>{o+=`- ${xe}
1303
- `}),o+="Always prefer parallel search execution if unsure.]")}typeof o=="string"&&vg(o)&&(o+=`
1338
+ `,ge.length>0&&(o+=`- The user mentioned URLs containing the paths/folders: ${ge.join(", ")}. Prioritize searching these folder names using glob or grep first.
1339
+ `),ye.length>0&&ye.forEach(Se=>{o+=`- ${Se}
1340
+ `}),o+="Always prefer parallel search execution if unsure.]")}typeof o=="string"&&Qg(o)&&(o+=`
1304
1341
 
1305
- [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=Eg(o);r&&typeof r.then=="function"&&(r=await r),P.push({role:"user",content:r}),Hv();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:me,runOrchestrated:ge}=rg(),xe=me(typeof t=="string"?t:"");if(i&&xe.isComplex&&xe.estimatedGoals>=a){console.log(`${h.yellow}\u26A1 Auto-orchestrate: ${xe.estimatedGoals} goals \u2192 parallel agents${h.reset}`);let Ke=await ge(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});if(Ke&&Ke.synthesis){let lt=Ke.synthesis.summary||"",gn=Ke.synthesis.filesChanged?.length?`
1342
+ [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=Zg(o);r&&typeof r.then=="function"&&(r=await r),P.push({role:"user",content:r}),YT();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:ge,runOrchestrated:ye}=Ng(),Se=ge(typeof t=="string"?t:"");if(i&&Se.isComplex&&Se.estimatedGoals>=a){console.log(`${h.yellow}\u26A1 Auto-orchestrate: ${Se.estimatedGoals} goals \u2192 parallel agents${h.reset}`);let Ze=await ye(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});if(Ze&&Ze.synthesis){let dt=Ze.synthesis.summary||"",Sn=Ze.synthesis.filesChanged?.length?`
1306
1343
 
1307
- Files changed: ${Ke.synthesis.filesChanged.join(", ")}`:"",Ge=Ke.synthesis.conflicts?.length?`
1344
+ Files changed: ${Ze.synthesis.filesChanged.join(", ")}`:"",Xe=Ze.synthesis.conflicts?.length?`
1308
1345
 
1309
1346
  Conflicts:
1310
- ${Ke.synthesis.conflicts.map(Tt=>`- ${Tt}`).join(`
1311
- `)}`:"";P.push({role:"assistant",content:lt+gn+Ge}),Ce(P),Ai(P)}return Ke}xe.isComplex&&process.stdout.isTTY&&console.log(`${h.dim}Hint: ~${xe.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${h.reset}`)}catch{}let{setOnChange:l}=Cl(),c=null,u=0;l((me,ge)=>{me==="create"?(c&&c.stop(),c=new bE(ge.name,ge.tasks),c.setStats({tokens:u}),c.start()):me==="update"&&c?c.updateTask(ge.id,ge.status):me==="clear"&&c&&(c.stop(),c=null)});let d=await Fc(),f=d;try{let{getBrainContext:me}=Bl(),ge=await me(t);ge&&(f=d+`
1312
- `+ge+`
1313
- `)}catch(me){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",me.message)}let m=rv(typeof t=="string"?t:"");if(m.length>0){let me=m.map(ge=>`[Triggered: ${ge.name}]
1314
- ${ge.instructions}`).join(`
1347
+ ${Ze.synthesis.conflicts.map(Ot=>`- ${Ot}`).join(`
1348
+ `)}`:"";P.push({role:"assistant",content:dt+Sn+Xe}),Ae(P),qi(P)}return Ze}Se.isComplex&&process.stdout.isTTY&&console.log(`${h.dim}Hint: ~${Se.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${h.reset}`)}catch{}let{setOnChange:l}=Fl(),c=null,u=0;l((ge,ye)=>{ge==="create"?(c&&c.stop(),c=new $v(ye.name,ye.tasks),c.setStats({tokens:u}),c.start()):ge==="update"&&c?c.updateTask(ye.id,ye.status):ge==="clear"&&c&&(c.stop(),c=null)});let d=await eu(),f=d;try{let{getBrainContext:ge}=Zl(),ye=await ge(t);ye&&(f=d+`
1349
+ `+ye+`
1350
+ `)}catch(ge){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",ge.message)}let m=sT(typeof t=="string"?t:"");if(m.length>0){let ge=m.map(ye=>`[Triggered: ${ye.name}]
1351
+ ${ye.instructions}`).join(`
1315
1352
  `);f+=`
1316
- `+me+`
1317
- `}let g=[{role:"system",content:f},...P];ig(Kt());let _=new Xs(mc());_.start();let k=P.length===1,A=k?Kv().catch(()=>null):Promise.resolve(null),L=k?BE(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),E=it(),[{messages:v,compressed:N,compacted:te,tokensRemoved:V},re,le]=await Promise.all([RE(g,E),A,L]),ne=Yt(g,E);if(_.stop(),re&&console.log(`${h.dim}${re}${h.reset}`),te)console.log(`${h.dim} [context compacted \u2014 summary (~${V} tokens freed)]${h.reset}`);else if(N){let me=ne.limit>0?Math.round(V/ne.limit*100):0;j(`${h.dim} [context compressed \u2014 ~${V} tokens freed (${me}%)]${h.reset}`)}ne.percentage>85&&j(`${h.yellow} \u26A0 Context ${Math.round(ne.percentage)}% used (${Math.round(100-ne.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${h.reset}`);let S=v;if(le&&k&&(S=[S[0],{role:"user",content:`[Server probe at task start]
1318
- ${le}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...S.slice(1)]),k){let me=UE(typeof t=="string"?t:"");me&&(S=[S[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1319
- `+me.user},{role:"assistant",content:me.assistant+`
1320
- [END EXAMPLE \u2014 wait for the real user request below]`},...S.slice(1)])}if(Yt(S,it()).percentage>=65){let{messages:ge,tokensRemoved:xe}=tn(S,it());xe>0&&(S=ge,console.log(`${h.dim} [pre-flight compress \u2014 ${xe} tokens freed, now ${Math.round(Yt(S,it()).percentage)}% used]${h.reset}`))}let Ee=0,W=0,J=0,he=0,Re=0,Ue=9,be=0,$e=new Set,$=(()=>{let me=P.find(ge=>ge.role==="user");return typeof me?.content=="string"?me.content:""})(),I=/set_reminder|google.?auth|cron:|api\.log|swarm.{0,30}(agent|crash|gecrasht|abgestürzt|fail)|agent.{0,30}(gecrasht|abgestürzt|crashed|fail)|server.{0,30}(passiert|fehler|crash|problem)|am.server/i.test($),H=0;if(!et){let me=P.filter(xe=>xe.role==="user"||xe.role==="tool").map(xe=>typeof xe.content=="string"?xe.content:"").join(`
1321
- `),ge=Sc(me);ge&&(et=!0,wt=ge.slice(0,120),j(`${h.yellow} \u26A1 Root cause in briefing: ${wt} \u2014 fix phase active from start (read budget: 3)${h.reset}`))}!et&&!It&&/\b(create|build|generate|implement|write|make|develop|set\s*up|scaffold|add)\b.{0,80}\b(app|component|page|game|api|backend|frontend|server|service|module|class|function|feature|project|system|bot|script|tool)\b/i.test($)&&(It=!0,j(`${h.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${h.reset}`)),P.length<=1&&!s.skipPhaseRouting&&(we=DE(),we&&(Qs=IE($)?.id||"coding",Pe="plan",mn=Rc("plan",Qs),Ki=0,Zs=0,An=0,process.stdout.isTTY&&console.log(`${h.dim} \u21B3 Phase routing: plan(${mn||"default"}) \u2192 implement \u2192 verify${h.reset}`),j(`${h.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${mn||"default model"} (category: ${Qs})${h.reset}`)));let O=0,q=new Map,b=new Set,Y=new Set,ke=new Set,fe=0,at=0,no=0,ps=0,Ae=Date.now(),iy=new SE(dv),ay=or,We=s.skillLoop?10:1,ly=3*We,cy=5*We,Vc=Bc,uy=5*We,dy=8*We,fy=Ag,hy=(we?6:4)*We,py=(we?10:7)*We,ea=Ii,my=(we?5:3)*We,cr=(we?8:5)*We,gy=Og,yy=(we?4:3)*We,wy=(we?6:4)*We,_y=3*We,$y=4*We,ms=pn,by=(we?6:4)*We,ky=(we?10:8)*We,gs=(we?12:10)*We,xy=25,On=0,Sy=10*We,Ey=15*We,Nn=0,Jc=5*We,Mn=0,vy=2*We,Ty=3,ta=0,so=10,Ry=16,Zc=s.skillLoop?999:n.investigationCap,Qc=async()=>{let{hasPendingOrCompletedJobs:me,getPendingJobSummary:ge}=zs();if(me()){if(ge()){let xe=Date.now()+45e3;for(process.stderr.write(`${h.cyan} \u23F3 Waiting for background agents to finish\u2026${h.reset}
1322
- `);ge()&&Date.now()<xe;)await new Promise(Ke=>setTimeout(Ke,500).unref()),Mi(P,S)}Mi(P,S),P.length>0&&Ce(P)}},na=typeof t=="string"?t.trim():"",eu=na.length>0&&/^\s*(analyze|analyse|analysiere|explain|erkläre|describe|beschreib|review|audit|summari[sz]e|zusammenfass|list|liste|what is|what does|wie funktioniert|wie geht|how does|show me|zeig|show the|show all|tell me about|erzähl)/i.test(na)&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|edit|write|delete|remove|install|setup|deploy|run)\b/i.test(na),je,$t=s.maxIterations||(we?as(Pe):Ac);eu&&($t=Math.min($t,4),j(`${h.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${$t}${h.reset}`));let sa=0,tu=3,oa=!1,ur=0;e:for(;;){for(oa=!1,je=0;je<$t&&!Pi()?.aborted;je++){Mi(P,S);{let w=it(),y=Yt(S,w),z=O===0?65:78;if(y.percentage>=z){if(b.size>0||we&&Pe!=="plan"){let Q=AE(P,{filesModified:b,currentPhase:we?Pe:null});if(Q){let U=S.findIndex(C=>C._progressSnapshot);U!==-1&&S.splice(U,1);let ie=S.findIndex(C=>C.role==="system");S.splice(ie+1,0,Q)}}let{messages:T,tokensRemoved:M}=tn(S,w,O===0);if(M>0&&(S=T,M>50&&console.log(`${h.dim} [auto-compressed \u2014 ~${M} tokens freed, now ${Math.round(Yt(S,w).percentage)}%]${h.reset}`),It&&b.size>=3)){let Q=[...b].map(ie=>ie.split("/").pop()).slice(0,10).join(", "),U={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${b.size} files: ${Q}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};S.push(U)}}}if(vt&&!et&&Zo<2){Zo++;let w={role:"user",content:"[SYSTEM] SSH paused \u2014 you have made many consecutive SSH calls. Synthesize your findings so far: summarize what you learned and what the likely issue is. After your synthesis, SSH will be available again for targeted follow-up commands."};S.push(w),P.push(w),j(`${h.yellow} \u26A0 Pre-call SSH-blocked nudge #${Zo} injected \u2014 model told to synthesize${h.reset}`)}vt||(Zo=0);let ge=!0;O>0&&JE();let xe=null;if(c&&c.isActive())c._paused&&c.resume();else if(!c){let w,y=ZE();if(y&&y.total>1){let M=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;w=`Plan step ${y.current}/${y.total}: ${M}`}else w=O>0?`${mc()} (step ${O+1})`:mc();let{getPendingJobSummary:z}=zs(),T=z();T&&(w+=` [${T}]`),xe=new Xs(w),xe.start()}let Ke=!0,lt="",gn=!1,Ge=new QE,Tt,ra=Date.now(),dr=!1,ia=new AbortController,nu=setInterval(()=>{let w=Date.now()-ra;if(w>=kc)Ge._clearCursorLine(),j(`${h.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${h.reset}`),ia.abort();else if(w>=gg&&!dr){dr=!0,Ge._clearCursorLine();let y=Gi.fast?.[Vs()],z=J>0?` (retry ${J+1}/${Oi})`:"",T=Math.round((kc-w)/1e3);j(`${h.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${z}${h.reset}`),y&&y!==Kt()?console.log(`${h.dim} \u{1F4A1} Will auto-switch to ${y} in ~${T}s if no tokens arrive${h.reset}`):console.log(`${h.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${T}s${h.reset}`)}},5e3),Rt="",on=null;try{let w=Tg(it()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),z=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),T;tr()?T=w.filter(U=>bg.has(U.function.name)):we&&Pe==="plan"?T=w.filter(U=>y.has(U.function.name)):we&&Pe==="verify"?T=w.filter(U=>z.has(U.function.name)):T=w;let M=Pi(),Q=new AbortController;M&&M.addEventListener("abort",()=>Q.abort(),{once:!0}),ia.signal.addEventListener("abort",()=>Q.abort(),{once:!0}),Tt=await ag(S,T,{signal:Q.signal,...mn?{model:mn}:{},onThinkingToken:()=>{ra=Date.now(),dr=!1,sn?.onThinkingToken&&sn.onThinkingToken()},onToken:U=>{if(ra=Date.now(),dr=!1,sn?.onToken){sn.onToken(U),lt+=U;return}if(lt+=U,!gn&&lt.length>400&&lt.length%250<U.length+1){let ie=Cc(lt,3);ie.truncated&&(gn=!0,Ge._clearCursorLine?.(),j(`${h.yellow} \u26A0 LLM stream loop detected (${ie.repeatCount}\xD7 repeated) \u2014 suppressing display${h.reset}`))}gn||(Rt+=U,process.stdout.isTTY?on||(on=setTimeout(()=>{Rt&&Ge&&Ge.push(Rt),Rt="",on=null},50)):(Ge.push(Rt),Rt=""),Ke&&(c&&!c._paused?c.pause():xe&&xe.stop(),ge||(ge=!0),Ge.startCursor(),Ke=!1))}})}catch(w){if(clearInterval(nu),on&&(clearTimeout(on),on=null),Rt&&Ge&&(Ge.push(Rt),Rt=""),c&&!c._paused&&c.pause(),xe&&xe.stop(),Ge.stopCursor(),ia.signal.aborted&&!Pi()?.aborted){if(J++,J>Oi){if(he<1){he++,Ks("Stale retries exhausted \u2014 last-resort force-compress...",h.yellow);let ie=it(),{messages:C,tokensRemoved:D}=tn(S,ie);S=C,D>50&&j(`${h.dim} [force-compressed \u2014 ~${D} tokens freed]${h.reset}`),J=0,je--;continue}c&&(c.stop(),c=null);let U=await Vv();if(U.action==="quit"){l(null),Oe(O,q,b,Y,Ae),Ce(P);break}U.action==="switch"&&(gc(`${U.provider}:${U.model}`),console.log(`${h.green} \u2713 Switched to ${U.provider}:${U.model}${h.reset}`)),J=0,je--;continue}let M=J===1?3e3:5e3;if(J>=1&&be<1){be++,Ks(`Stale retry ${J}/${Oi} \u2014 force-compressing before retry...`,h.yellow);let U=it(),{messages:ie,tokensRemoved:C}=tn(S,U,!0);if(S=ie,C>0&&C>50&&j(`${h.dim} [force-compressed \u2014 ~${C} tokens freed]${h.reset}`),Av){let D=Gi.fast?.[Vs()];D&&D!==Kt()&&(gc(`${Vs()}:${D}`),console.log(`${h.cyan} \u26A1 Auto-switched to ${D} to avoid further stale timeouts${h.reset}`),console.log(`${h.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${h.reset}`))}}else j(`${h.yellow} \u26A0 Stale retry ${J}/${Oi} \u2014 retrying in ${M/1e3}s...${h.reset}`);let Q=new Xs(`Waiting ${M/1e3}s before retry...`);Q.start(),await new Promise(U=>setTimeout(U,M)),Q.stop(),je--;continue}if(w.name==="AbortError"||w.name==="CanceledError"||w.message?.includes("canceled")||w.message?.includes("aborted")){c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae),Ce(P);break}let y=w.message;if(w.code==="ECONNREFUSED"||w.message.includes("ECONNREFUSED"))y="Connection refused \u2014 please check your internet connection or API endpoint";else if(w.code==="ENOTFOUND"||w.message.includes("ENOTFOUND"))y="Network error \u2014 could not reach the API server. Please check your connection";else if(w.code==="ETIMEDOUT"||w.message.includes("timeout"))y="Request timed out \u2014 the API server took too long to respond. Please try again";else if(w.message.includes("401")||w.message.includes("Unauthorized"))y="Authentication failed \u2014 please check your API key in the .env file";else if(w.message.includes("403")||w.message.includes("Forbidden"))y="Access denied \u2014 your API key may not have permission for this model";else if(w.message.includes("404")){let M=Kt?Kt():"unknown",Q=C=>C.includes(":")&&C.split(":")[0].match(/^[a-z]+$/)&&!C.split(":")[1].includes(":")?C.split(":").slice(1).join(":"):C;$e.add(Q(M));let ie=(()=>{let C=[];process.env.NEX_FALLBACK_MODEL&&C.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:D}=Bo(),F=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let X of F){let K=D(X);K&&!C.includes(K)&&C.push(K)}}catch{}return C.filter(D=>!$e.has(Q(D)))})()[0];if(ie){console.log(`${h.yellow} \u26A0 Model ${M} unavailable (404) \u2014 switching to ${ie}${h.reset}`),gc(ie),ig(ie),je--;continue}y=`Model not found (404): ${M} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${h.red} \u2717 ${y}${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae),Ce(P);break}else if(w.message.includes("400")){if(he<3&&Re<Ue){he++,Re++;let M=O===0&&he===1,Q=M||he===3||be>0;if(M){he=3;let D=w.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);Ks(`Bad request (400) \u2014 ${D||"system prompt too large"}, compressing...`,h.yellow)}else Ks(Q?`Bad request (400) \u2014 nuclear compression (attempt ${he}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${he}/3)`,h.yellow);let U=it(),{messages:ie,tokensRemoved:C}=tn(S,U,Q);S=ie,C>50&&j(`${h.dim} [force-compressed \u2014 ~${C} tokens freed]${h.reset}`),je--;continue}{let M=S.find(F=>F.role==="system"),Q=S.find(F=>F.role==="user"&&!String(F.content).startsWith("[SYSTEM")&&!String(F.content).startsWith("BLOCKED:")),U=[M,Q].filter(Boolean),{getUsage:ie}=Qt(),C=Qt().estimateMessagesTokens(U),D=Qt().estimateMessagesTokens(S);if(C<D){let F=[],X=P.filter(ee=>ee.role==="assistant"&&typeof ee.content=="string"&&ee.content.trim().length>30).slice(-5).map(ee=>ee.content.trim().slice(0,300).replace(/\n+/g," "));X.length>0&&F.push(`Key findings:
1323
- `+X.map(ee=>`- ${ee}`).join(`
1324
- `));let K=P.filter(ee=>ee.role==="tool"&&typeof ee.content=="string"&&!ee.content.startsWith("BLOCKED:")&&ee.content.trim().length>10).slice(-5).map(ee=>ee.content.trim().split(`
1353
+ `+ge+`
1354
+ `}let g=[{role:"system",content:f},...P];Mg(Qt());let $=new Zs(Cc());$.start();let k=P.length===1,M=k?XT().catch(()=>null):Promise.resolve(null),D=k?qv(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),v=ut(),[{messages:E,compressed:A,compacted:ee,tokensRemoved:se},ue,ae]=await Promise.all([vv(g,v),M,D]),te=Vt(g,v);if($.stop(),ue&&console.log(`${h.dim}${ue}${h.reset}`),ee)console.log(`${h.dim} [context compacted \u2014 summary (~${se} tokens freed)]${h.reset}`);else if(A){let ge=te.limit>0?Math.round(se/te.limit*100):0;j(`${h.dim} [context compressed \u2014 ~${se} tokens freed (${ge}%)]${h.reset}`)}te.percentage>85&&j(`${h.yellow} \u26A0 Context ${Math.round(te.percentage)}% used (${Math.round(100-te.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${h.reset}`);let S=E;if(ae&&k&&(S=[S[0],{role:"user",content:`[Server probe at task start]
1355
+ ${ae}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...S.slice(1)]),k){let ge=Fv(typeof t=="string"?t:"");ge&&(S=[S[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1356
+ `+ge.user},{role:"assistant",content:ge.assistant+`
1357
+ [END EXAMPLE \u2014 wait for the real user request below]`},...S.slice(1)])}if(Vt(S,ut()).percentage>=65){let{messages:ye,tokensRemoved:Se}=an(S,ut());Se>0&&(S=ye,console.log(`${h.dim} [pre-flight compress \u2014 ${Se} tokens freed, now ${Math.round(Vt(S,ut()).percentage)}% used]${h.reset}`))}let ve=0,W=0,z=0,me=0,Ce=0,De=9,ke=0,be=new Set,b=(()=>{let ge=P.find(ye=>ye.role==="user");return typeof ge?.content=="string"?ge.content:""})(),I=/set_reminder|google.?auth|cron:|api\.log|swarm.{0,30}(agent|crash|gecrasht|abgestürzt|fail)|agent.{0,30}(gecrasht|abgestürzt|crashed|fail)|server.{0,30}(passiert|fehler|crash|problem)|am.server/i.test(b),H=0;if(!ot){let ge=P.filter(Se=>Se.role==="user"||Se.role==="tool").map(Se=>typeof Se.content=="string"?Se.content:"").join(`
1358
+ `),ye=Dc(ge);ye&&(ot=!0,bt=ye.slice(0,120),j(`${h.yellow} \u26A1 Root cause in briefing: ${bt} \u2014 fix phase active from start (read budget: 3)${h.reset}`))}!ot&&!Ft&&/\b(create|build|generate|implement|write|make|develop|set\s*up|scaffold|add)\b.{0,80}\b(app|component|page|game|api|backend|frontend|server|service|module|class|function|feature|project|system|bot|script|tool)\b/i.test(b)&&(Ft=!0,j(`${h.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${h.reset}`)),P.length<=1&&!s.skipPhaseRouting&&($e=Lv(),$e&&(so=Pv(b)?.id||"coding",Me="plan",kn=Uc("plan",so),sa=0,to=0,In=0,process.stdout.isTTY&&console.log(`${h.dim} \u21B3 Phase routing: plan(${kn||"default"}) \u2192 implement \u2192 verify${h.reset}`),j(`${h.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${kn||"default model"} (category: ${so})${h.reset}`)));let N=0,L=new Map,_=new Set,J=new Set,de=new Set,fe=0,Je=0,ro=0,xn=0,Oe=Date.now(),Iy=new kv(cT),jy=ur,ze=s.skillLoop?10:1,Dy=3*ze,qy=5*ze,du=tu,Fy=5*ze,By=8*ze,Uy=sy,Wy=($e?6:4)*ze,Hy=($e?10:7)*ze,ca=Yi,Yy=($e?5:3)*ze,gr=($e?8:5)*ze,Gy=oy,zy=($e?4:3)*ze,Ky=($e?6:4)*ze,Xy=3*ze,Vy=4*ze,_s=bn,Jy=($e?6:4)*ze,Zy=($e?10:8)*ze,bs=($e?12:10)*ze,Qy=25,jn=0,e0=10*ze,t0=15*ze,Dn=0,fu=5*ze,qn=0,n0=2*ze,s0=3,ua=0,io=10,o0=16,pu=s.skillLoop?999:n.investigationCap,hu=async()=>{let{hasPendingOrCompletedJobs:ge,getPendingJobSummary:ye}=Vs();if(ge()){if(ye()){let Se=Date.now()+45e3;for(process.stderr.write(`${h.cyan} \u23F3 Waiting for background agents to finish\u2026${h.reset}
1359
+ `);ye()&&Date.now()<Se;)await new Promise(Ze=>setTimeout(Ze,500).unref()),Ui(P,S)}Ui(P,S),P.length>0&&Ae(P)}},da=typeof t=="string"?t.trim():"",mu=da.length>0&&/^\s*(analyze|analyse|analysiere|explain|erkläre|describe|beschreib|review|audit|summari[sz]e|zusammenfass|list|liste|what is|what does|wie funktioniert|wie geht|how does|show me|zeig|show the|show all|tell me about|erzähl)/i.test(da)&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|edit|write|delete|remove|install|setup|deploy|run)\b/i.test(da),Ue,xt=s.maxIterations||($e?ps(Me):Hc);mu&&(xt=Math.min(xt,4),j(`${h.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${xt}${h.reset}`));let fa=0,gu=3,pa=!1,yr=0;e:for(;;){for(pa=!1,Ue=0;Ue<xt&&!Wi()?.aborted;Ue++){Ui(P,S);{let w=ut(),y=Vt(S,w),G=N===0?65:78;if(y.percentage>=G){if(_.size>0||$e&&Me!=="plan"){let Z=Rv(P,{filesModified:_,currentPhase:$e?Me:null});if(Z){let B=S.findIndex(R=>R._progressSnapshot);B!==-1&&S.splice(B,1);let oe=S.findIndex(R=>R.role==="system");S.splice(oe+1,0,Z)}}let{messages:T,tokensRemoved:O}=an(S,w,N===0);if(O>0&&(S=T,O>50&&console.log(`${h.dim} [auto-compressed \u2014 ~${O} tokens freed, now ${Math.round(Vt(S,w).percentage)}%]${h.reset}`),Ft&&_.size>=3)){let Z=[..._].map(oe=>oe.split("/").pop()).slice(0,10).join(", "),B={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${_.size} files: ${Z}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};S.push(B)}}}if(At&&!ot&&or<2){or++;let w={role:"user",content:"[SYSTEM] SSH paused \u2014 you have made many consecutive SSH calls. Synthesize your findings so far: summarize what you learned and what the likely issue is. After your synthesis, SSH will be available again for targeted follow-up commands."};S.push(w),P.push(w),j(`${h.yellow} \u26A0 Pre-call SSH-blocked nudge #${or} injected \u2014 model told to synthesize${h.reset}`)}At||(or=0);let ye=!0;N>0&&Xv();let Se=null;if(c&&c.isActive())c._paused&&c.resume();else if(!c){let w,y=Vv();if(y&&y.total>1){let O=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;w=`Plan step ${y.current}/${y.total}: ${O}`}else w=N>0?`${Cc()} (step ${N+1})`:Cc();let{getPendingJobSummary:G}=Vs(),T=G();T&&(w+=` [${T}]`),Se=new Zs(w),Se.start()}let Ze=!0,dt="",Sn=!1,Xe=new Jv,Ot,ha=Date.now(),wr=!1,ma=new AbortController,yu=setInterval(()=>{let w=Date.now()-ha;if(w>=Ic)Xe._clearCursorLine(),j(`${h.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${h.reset}`),ma.abort();else if(w>=Wg&&!wr){wr=!0,Xe._clearCursorLine();let y=ta.fast?.[Qs()],G=z>0?` (retry ${z+1}/${Fi})`:"",T=Math.round((Ic-w)/1e3);j(`${h.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${G}${h.reset}`),y&&y!==Qt()?console.log(`${h.dim} \u{1F4A1} Will auto-switch to ${y} in ~${T}s if no tokens arrive${h.reset}`):console.log(`${h.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${T}s${h.reset}`)}},5e3),Nt="",dn=null;try{let w=ey(ut()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),G=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),T;ar()?T=w.filter(B=>Kg.has(B.function.name)):$e&&Me==="plan"?T=w.filter(B=>y.has(B.function.name)):$e&&Me==="verify"?T=w.filter(B=>G.has(B.function.name)):T=w;let O=Wi(),Z=new AbortController;O&&O.addEventListener("abort",()=>Z.abort(),{once:!0}),ma.signal.addEventListener("abort",()=>Z.abort(),{once:!0}),Ot=await Pg(S,T,{signal:Z.signal,...kn?{model:kn}:{},onThinkingToken:()=>{ha=Date.now(),wr=!1,un?.onThinkingToken&&un.onThinkingToken()},onToken:B=>{if(ha=Date.now(),wr=!1,un?.onToken){un.onToken(B),dt+=B;return}if(dt+=B,!Sn&&dt.length>400&&dt.length%250<B.length+1){let oe=Wc(dt,3);oe.truncated&&(Sn=!0,Xe._clearCursorLine?.(),j(`${h.yellow} \u26A0 LLM stream loop detected (${oe.repeatCount}\xD7 repeated) \u2014 suppressing display${h.reset}`))}Sn||(Nt+=B,process.stdout.isTTY?dn||(dn=setTimeout(()=>{Nt&&Xe&&Xe.push(Nt),Nt="",dn=null},50)):(Xe.push(Nt),Nt=""),Ze&&(c&&!c._paused?c.pause():Se&&Se.stop(),ye||(ye=!0),Xe.startCursor(),Ze=!1))}})}catch(w){if(clearInterval(yu),dn&&(clearTimeout(dn),dn=null),Nt&&Xe&&(Xe.push(Nt),Nt=""),c&&!c._paused&&c.pause(),Se&&Se.stop(),Xe.stopCursor(),ma.signal.aborted&&!Wi()?.aborted){if(z++,z>Fi){if(me<1){me++,Js("Stale retries exhausted \u2014 last-resort force-compress...",h.yellow);let oe=ut(),{messages:R,tokensRemoved:q}=an(S,oe);S=R,q>50&&j(`${h.dim} [force-compressed \u2014 ~${q} tokens freed]${h.reset}`),z=0,Ue--;continue}c&&(c.stop(),c=null);let B=await JT();if(B.action==="quit"){l(null),Ne(N,L,_,J,Oe),Ae(P);break}B.action==="switch"&&(Ac(`${B.provider}:${B.model}`),console.log(`${h.green} \u2713 Switched to ${B.provider}:${B.model}${h.reset}`)),z=0,Ue--;continue}let O=z===1?3e3:5e3;if(z>=1&&ke<1){ke++,Js(`Stale retry ${z}/${Fi} \u2014 force-compressing before retry...`,h.yellow);let B=ut(),{messages:oe,tokensRemoved:R}=an(S,B,!0);if(S=oe,R>0&&R>50&&j(`${h.dim} [force-compressed \u2014 ~${R} tokens freed]${h.reset}`),RT){let q=ta.fast?.[Qs()];q&&q!==Qt()&&(Ac(`${Qs()}:${q}`),console.log(`${h.cyan} \u26A1 Auto-switched to ${q} to avoid further stale timeouts${h.reset}`),console.log(`${h.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${h.reset}`))}}else j(`${h.yellow} \u26A0 Stale retry ${z}/${Fi} \u2014 retrying in ${O/1e3}s...${h.reset}`);let Z=new Zs(`Waiting ${O/1e3}s before retry...`);Z.start(),await new Promise(B=>setTimeout(B,O)),Z.stop(),Ue--;continue}if(w.name==="AbortError"||w.name==="CanceledError"||w.message?.includes("canceled")||w.message?.includes("aborted")){c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe),Ae(P);break}let y=w.message;if(w.code==="ECONNREFUSED"||w.message.includes("ECONNREFUSED"))y="Connection refused \u2014 please check your internet connection or API endpoint";else if(w.code==="ENOTFOUND"||w.message.includes("ENOTFOUND"))y="Network error \u2014 could not reach the API server. Please check your connection";else if(w.code==="ETIMEDOUT"||w.message.includes("timeout"))y="Request timed out \u2014 the API server took too long to respond. Please try again";else if(w.message.includes("401")||w.message.includes("Unauthorized"))y="Authentication failed \u2014 please check your API key in the .env file";else if(w.message.includes("403")||w.message.includes("Forbidden"))y="Access denied \u2014 your API key may not have permission for this model";else if(w.message.includes("404")){let O=Qt?Qt():"unknown",Z=R=>R.includes(":")&&R.split(":")[0].match(/^[a-z]+$/)&&!R.split(":")[1].includes(":")?R.split(":").slice(1).join(":"):R;be.add(Z(O));let oe=(()=>{let R=[];process.env.NEX_FALLBACK_MODEL&&R.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:q}=zo(),F=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let X of F){let K=q(X);K&&!R.includes(K)&&R.push(K)}}catch{}return R.filter(q=>!be.has(Z(q)))})()[0];if(oe){console.log(`${h.yellow} \u26A0 Model ${O} unavailable (404) \u2014 switching to ${oe}${h.reset}`),Ac(oe),Mg(oe),Ue--;continue}y=`Model not found (404): ${O} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${h.red} \u2717 ${y}${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe),Ae(P);break}else if(w.message.includes("400")){if(me<3&&Ce<De){me++,Ce++;let O=N===0&&me===1,Z=O||me===3||ke>0;if(O){me=3;let q=w.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);Js(`Bad request (400) \u2014 ${q||"system prompt too large"}, compressing...`,h.yellow)}else Js(Z?`Bad request (400) \u2014 nuclear compression (attempt ${me}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${me}/3)`,h.yellow);let B=ut(),{messages:oe,tokensRemoved:R}=an(S,B,Z);S=oe,R>50&&j(`${h.dim} [force-compressed \u2014 ~${R} tokens freed]${h.reset}`),Ue--;continue}{let O=S.find(F=>F.role==="system"),Z=S.find(F=>F.role==="user"&&!String(F.content).startsWith("[SYSTEM")&&!String(F.content).startsWith("BLOCKED:")),B=[O,Z].filter(Boolean),{getUsage:oe}=on(),R=on().estimateMessagesTokens(B),q=on().estimateMessagesTokens(S);if(R<q){let F=[],X=P.filter(Q=>Q.role==="assistant"&&typeof Q.content=="string"&&Q.content.trim().length>30).slice(-5).map(Q=>Q.content.trim().slice(0,300).replace(/\n+/g," "));X.length>0&&F.push(`Key findings:
1360
+ `+X.map(Q=>`- ${Q}`).join(`
1361
+ `));let K=P.filter(Q=>Q.role==="tool"&&typeof Q.content=="string"&&!Q.content.startsWith("BLOCKED:")&&Q.content.trim().length>10).slice(-5).map(Q=>Q.content.trim().split(`
1325
1362
  `).slice(0,8).join(`
1326
1363
  `).slice(0,500));if(K.length>0&&F.push(`Tool results summary:
1327
- `+K.map(ee=>`- ${ee}`).join(`
1328
- `)),b.size>0){let ee=[...b].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");F.unshift(`Already modified: ${ee} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(Y.size>0){let ee=[...Y].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");F.push(`Files already investigated: ${ee}`)}let oe=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(oe,JSON.stringify({filesWritten:[...b].map(ee=>ee.split("/").slice(-2).join("/")),filesRead:[...Y].map(ee=>ee.split("/").slice(-2).join("/")),isCreationTask:It,wipeNumber:Jo+1,timestamp:Date.now()},null,2)),F.push(`Session checkpoint: ${oe} \u2014 read it for exact file list`)}catch{}let de=0;{let _e=((typeof Q?.content=="string"?Q.content:Array.isArray(Q?.content)?Q.content.filter(Ve=>Ve.type==="text").map(Ve=>Ve.text).join(" "):"").match(/(?:^|\s)([\w./\-]+\.(?:js|ts|jsx|tsx|py|json|yml|yaml|sh|css|scss|html|md|go|rs|java|rb|php))/gm)||[]).map(Ve=>Ve.trim()).filter(Boolean),ve=[...b],mt=_e.filter(Ve=>!ve.some(la=>la.endsWith(Ve)||Ve.endsWith(la.split("/").pop())));de=mt.length;let Xe=[...P].reverse().find(Ve=>Ve.role==="tool"&&typeof Ve.content=="string"&&!Ve.content.startsWith("BLOCKED:")&&Ve.content.length>5),At={completed:ve.map(Ve=>Ve.split("/").slice(-2).join("/")),pending:mt.length>0?mt:ve.length===0?["(task files not yet identified)"]:[],lastEdit:Xe?Xe.content.trim().slice(0,120):null};(At.completed.length>0||At.pending.length>0)&&F.unshift(`Work manifest:
1329
- ${JSON.stringify(At,null,2)}`)}if(F.length>0){let ee={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1364
+ `+K.map(Q=>`- ${Q}`).join(`
1365
+ `)),_.size>0){let Q=[..._].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");F.unshift(`Already modified: ${Q} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(J.size>0){let Q=[...J].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");F.push(`Files already investigated: ${Q}`)}let re=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(re,JSON.stringify({filesWritten:[..._].map(Q=>Q.split("/").slice(-2).join("/")),filesRead:[...J].map(Q=>Q.split("/").slice(-2).join("/")),isCreationTask:Ft,wipeNumber:sr+1,timestamp:Date.now()},null,2)),F.push(`Session checkpoint: ${re} \u2014 read it for exact file list`)}catch{}let he=0;{let _e=((typeof Z?.content=="string"?Z.content:Array.isArray(Z?.content)?Z.content.filter(et=>et.type==="text").map(et=>et.text).join(" "):"").match(/(?:^|\s)([\w./\-]+\.(?:js|ts|jsx|tsx|py|json|yml|yaml|sh|css|scss|html|md|go|rs|java|rb|php))/gm)||[]).map(et=>et.trim()).filter(Boolean),Te=[..._],wt=_e.filter(et=>!Te.some(ya=>ya.endsWith(et)||et.endsWith(ya.split("/").pop())));he=wt.length;let Qe=[...P].reverse().find(et=>et.role==="tool"&&typeof et.content=="string"&&!et.content.startsWith("BLOCKED:")&&et.content.length>5),Pt={completed:Te.map(et=>et.split("/").slice(-2).join("/")),pending:wt.length>0?wt:Te.length===0?["(task files not yet identified)"]:[],lastEdit:Qe?Qe.content.trim().slice(0,120):null};(Pt.completed.length>0||Pt.pending.length>0)&&F.unshift(`Work manifest:
1366
+ ${JSON.stringify(Pt,null,2)}`)}if(F.length>0){let Q={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1330
1367
  ${F.join(`
1331
1368
  `)}
1332
- Continue implementing the fixes based on these findings.`};U.push(ee)}if(Jo>=3){let ee=b.size>0?`
1333
- Files modified so far: ${[...b].map(_e=>_e.split("/").slice(-1)[0]).join(", ")}`:"";j(`${h.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${h.reset}`),console.log(`${h.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ee?h.dim+ee:""}${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae,{suppressHint:!0}),Ce(P);break}S=U,Jo++,cs=10+Math.min(de*3,7),Lc=!0,Bi=b.size,Ui=!1,Lt=0,H=0;for(let[ee,_e]of pn){let ve=_e?.count??_e??0;Ec(pn,ee,ve>=2?ve:1)}for(let[ee]of Rn)nn(pn,ee)<2&&Rn.delete(ee);Pt.clear(),fs.clear(),It&&zt>0&&(jt=!0,j(`${h.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${zt} edits already made)${h.reset}`));for(let[ee]of Ii)Ec(Ii,ee,cr-1);if(Ks(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${D-C} tokens freed)`,h.yellow),Jo>=1){let ee=[...pn.entries()].filter(([,Xe])=>Xe>=gs).map(([Xe])=>Xe.split("/").slice(-1)[0]),_e=ee.length>0?`
1369
+ Continue implementing the fixes based on these findings.`};B.push(Q)}if(sr>=3){let Q=_.size>0?`
1370
+ Files modified so far: ${[..._].map(_e=>_e.split("/").slice(-1)[0]).join(", ")}`:"";j(`${h.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${h.reset}`),console.log(`${h.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${Q?h.dim+Q:""}${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe,{suppressHint:!0}),Ae(P);break}S=B,sr++,ms=10+Math.min(he*3,7),Xc=!0,Vi=_.size,Ji=!1,qt=0,H=0;for(let[Q,_e]of bn){let Te=_e?.count??_e??0;qc(bn,Q,Te>=2?Te:1)}for(let[Q]of Ln)ln(bn,Q)<2&&Ln.delete(Q);Dt.clear(),ws.clear(),Ft&&Zt>0&&(Ut=!0,j(`${h.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Zt} edits already made)${h.reset}`));for(let[Q]of Yi)qc(Yi,Q,gr-1);if(Js(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${q-R} tokens freed)`,h.yellow),sr>=1){let Q=[...bn.entries()].filter(([,Qe])=>Qe>=bs).map(([Qe])=>Qe.split("/").slice(-1)[0]),_e=Q.length>0?`
1334
1371
 
1335
- Files already at read cap \u2014 use grep_search instead: ${ee.join(", ")}`:"",mt={role:"user",content:vt&&!et?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${_e}`};P.push(mt),S.push(mt)}he=0,je--;continue}}y="Context too large to compress \u2014 use /clear to start fresh"}else w.message.includes("500")||w.message.includes("502")||w.message.includes("503")||w.message.includes("504")?y="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(w.message.includes("fetch failed")||w.message.includes("fetch"))&&(y="Network request failed \u2014 please check your internet connection");if(console.log(`${h.red} \u2717 ${y}${h.reset}`),w.message.includes("429")){if(Ee++,Ee>$c){console.log(`${h.red} Rate limit: max retries (${$c}) exceeded. Try again later or use /budget to check your limits.${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae),Ce(P);break e}let M=Math.min(1e4*Math.pow(2,Ee-1),12e4),Q=new Xs(`Rate limit \u2014 waiting ${Math.round(M/1e3)}s (retry ${Ee}/${$c})`);Q.start(),await new Promise(U=>setTimeout(U,M)),Q.stop();continue}let z=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return ot().getActiveProviderName()==="ollama"}catch{return!1}})();if(w.message.includes("socket disconnected")||w.message.includes("TLS")||w.message.includes("ECONNRESET")||w.message.includes("ECONNABORTED")||w.message.includes("ETIMEDOUT")||z&&(w.message.includes("500")||w.message.includes("502")||w.message.includes("503")||w.message.includes("504")||w.message.includes("401")||w.message.includes("Unauthorized"))||w.code==="ECONNRESET"||w.code==="ECONNABORTED"){if(W++,W>bc){console.log(`${h.red} Network error: max retries (${bc}) exceeded. Check your connection and try again.
1336
- Use /undo to revert changes made during this session.${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae),Ce(P);break e}let M=Math.min(2e3*Math.pow(2,W-1),3e4),Q=new Xs(`API temporarily unavailable \u2014 retrying in ${Math.round(M/1e3)}s (${W}/${bc}). Your changes are safe.`);Q.start(),await new Promise(U=>setTimeout(U,M)),Q.stop(),je--;continue}c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae),Ce(P);break}if(clearInterval(nu),Ee=0,W=0,Ke&&(c&&!c._paused&&c.pause(),xe&&xe.stop()),on&&(clearTimeout(on),on=null),Rt&&Ge&&(Ge.push(Rt),Rt=""),lt&&Ge.flush(),W=0,J=0,Tt&&Tt.usage){let w=Tt.usage.prompt_tokens||0,y=Tt.usage.completion_tokens||0;cg(Vs(),Kt(),w,y),u+=w+y,c&&c.setStats({tokens:u})}else if(Tt&&!Tt.usage){let w=S.map(T=>typeof T.content=="string"?T.content:Array.isArray(T.content)?T.content.map(M=>typeof M=="string"?M:M.text||"").join(""):"").join(" "),y=dg(w),z=dg(Tt.content||lt||"");cg(Vs(),Kt(),y,z),u+=y+z,c&&c.setStats({tokens:u})}let{content:su,tool_calls:rn}=Tt,fr=Cc(su||""),ou=fr.truncated?fr.text:su;fr.truncated&&j(`${h.yellow} \u26A0 LLM output loop detected (${fr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${h.reset}`);let hr=yv(ou||""),Ct=hr.truncated?hr.text:ou;hr.truncated&&j(`${h.yellow} \u26A0 LLM output loop detected (${hr.repeatCount}\xD7 repeated window) \u2014 response truncated${h.reset}`);let oo={role:"assistant",content:Ct||""};if(rn&&rn.length>0&&(oo.tool_calls=rn),P.push(oo),S.push(oo),eu&&(Ct||"").trim().length>1500&&b.size===0&&ps===0){j(`${h.green} \u2713 Analysis-only early exit: ${(Ct||"").length} chars produced, no file changes${h.reset}`),oo.tool_calls&&delete oo.tool_calls,Oe(O,q,b,Y,Ae),Ce(P);break e}if(!et&&Ct&&rn&&rn.length>0){let w=Sc(Ct);if(w){et=!0,wt=w.slice(0,120),Dt=0,jt=!1,Gt=0,j(`${h.yellow} \u26A1 Root cause in model analysis: ${wt} \u2014 fix phase (read budget: 3)${h.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${wt}. Read only the file that needs fixing, then edit it. Do not read other files.`};P.push(y),S.push(y)}}if(!rn||rn.length===0){let w=(Ct||"").trim().length>0||lt.trim().length>0,y=!1;if(vt&&w&&(Ni>=2?j(`${h.yellow} \u26A0 SSH permanently blocked after ${Ni} storm warnings \u2014 no further SSH calls allowed${h.reset}`):(vt=!1,Lt=so-4,y=!0)),y&&w){let T=(Ct||"").trim();if(T.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(T.slice(-200))){let Q={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};S.push(Q),P.push(Q);continue}}if(!w&&O>0&&je<Ac-1){let T={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};S.push(T),P.push(T);continue}let z=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(w&&je<3&&z.test((Ct||"").slice(0,600)))if(Lc&&cs<=0||vt){j(`${h.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${h.reset}`);let M={role:"user",content:"[SYSTEM] Correct \u2014 remote access is currently limited. Summarize what you have found so far and tell the user exactly what specific information (logs, process list, error output) you need from the server to continue."};S.push(M),P.push(M);continue}else{j(`${h.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${h.reset}`);let M={role:"user",content:"[SYSTEM] You have full tool access. Use your tools to investigate and implement the fix directly \u2014 do not say you cannot use tools. If SSH is needed, use a single targeted command that captures the most relevant information rather than multiple sequential calls."};S.push(M),P.push(M);continue}if(s.skillLoop&&w&&O>3&&ur<5){let T=(Ct||lt||"").toLowerCase();if(/\b(i.ll stop|stop the|stopped|done with|complet|summar|conclud|no more|finish|end of|that.s all|final|wrapped up|no further|mindful of|reached.*limit|tool call limit|at this point|recommend keep)/.test(T.slice(-600))){ur=(ur||0)+1,j(`${h.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${ur}${h.reset}`);let Q={role:"user",content:"[SYSTEM] Do NOT stop. You are in an autonomous experiment loop. The user is away and expects you to keep running experiments indefinitely until they interrupt with Ctrl+C. Start the next experiment NOW: hypothesize a new change, checkpoint, edit, run, measure, keep or revert. Think harder \u2014 try a completely different optimization approach."};S.push(Q),P.push(Q);continue}}if(er()&&!s.skillLoop&&!we&&(b.size>0||ps>0)&&w&&O>=2){j(`${h.green} \u2713 Headless early exit: ${b.size} file(s) modified (+ ${ps} bash writes), text response received${h.reset}`),Oe(O,q,b,Y,Ae),Ce(P);break e}if(we&&Pe==="plan"&&An>=2){j(`${h.cyan} \u21B3 Plan phase: ${An} consecutive blocks \u2014 auto-advancing to implement${h.reset}`),An=0;let T=Ko("implement","[auto-advance: task only requires direct action]");if(T){P.push(T),S.push(T),je=0,$t=as("implement");continue}}if(we&&w){let T=(Ct||lt||"").trim();if(Pe==="plan"){let M=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files|keine (Ergebnisse|Treffer|Übereinstimmung|Funde|passenden)|nicht gefunden|nichts gefunden)\b/i,Q=Ng(T,pn).length===0,U=nr.size>0,ie=sr.size>0,C=T.length>1500;if(er()&&Q&&!U&&!ie&&!C&&M.test(T)){j(`${h.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${h.reset}
1337
- `),Oe(O,q,b,Y,Ae),Ce(P);break e}let D=Ko("implement",T);if(D){P.push(D),S.push(D),je=0,$t=as("implement");continue}}else if(Pe==="implement"&&(b.size>0||ps>0)){let M=P.find(ie=>ie.role==="user"),Q=typeof M?.content=="string"?M.content:"",U=Ko("verify",T,b,Q);if(U){P.push(U),S.push(U),je=0,$t=Math.min(as("verify")+Math.max(0,(b.size-2)*2),20);continue}}else if(Pe==="verify"){let Q=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(T.slice(0,500));if(Q&&Zs<3){Zs++;let U={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1372
+ Files already at read cap \u2014 use grep_search instead: ${Q.join(", ")}`:"",wt={role:"user",content:At&&!ot?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${_e}`};P.push(wt),S.push(wt)}me=0,Ue--;continue}}y="Context too large to compress \u2014 use /clear to start fresh"}else w.message.includes("500")||w.message.includes("502")||w.message.includes("503")||w.message.includes("504")?y="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(w.message.includes("fetch failed")||w.message.includes("fetch"))&&(y="Network request failed \u2014 please check your internet connection");if(console.log(`${h.red} \u2717 ${y}${h.reset}`),w.message.includes("429")){if(ve++,ve>Pc){console.log(`${h.red} Rate limit: max retries (${Pc}) exceeded. Try again later or use /budget to check your limits.${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe),Ae(P);break e}let O=Math.min(1e4*Math.pow(2,ve-1),12e4),Z=new Zs(`Rate limit \u2014 waiting ${Math.round(O/1e3)}s (retry ${ve}/${Pc})`);Z.start(),await new Promise(B=>setTimeout(B,O)),Z.stop();continue}let G=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return lt().getActiveProviderName()==="ollama"}catch{return!1}})();if(w.message.includes("socket disconnected")||w.message.includes("TLS")||w.message.includes("ECONNRESET")||w.message.includes("ECONNABORTED")||w.message.includes("ETIMEDOUT")||G&&(w.message.includes("500")||w.message.includes("502")||w.message.includes("503")||w.message.includes("504")||w.message.includes("401")||w.message.includes("Unauthorized"))||w.code==="ECONNRESET"||w.code==="ECONNABORTED"){if(W++,W>Lc){console.log(`${h.red} Network error: max retries (${Lc}) exceeded. Check your connection and try again.
1373
+ Use /undo to revert changes made during this session.${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe),Ae(P);break e}let O=Math.min(2e3*Math.pow(2,W-1),3e4),Z=new Zs(`API temporarily unavailable \u2014 retrying in ${Math.round(O/1e3)}s (${W}/${Lc}). Your changes are safe.`);Z.start(),await new Promise(B=>setTimeout(B,O)),Z.stop(),Ue--;continue}c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe),Ae(P);break}if(clearInterval(yu),ve=0,W=0,Ze&&(c&&!c._paused&&c.pause(),Se&&Se.stop()),dn&&(clearTimeout(dn),dn=null),Nt&&Xe&&(Xe.push(Nt),Nt=""),dt&&Xe.flush(),W=0,z=0,Ot&&Ot.usage){let w=Ot.usage.prompt_tokens||0,y=Ot.usage.completion_tokens||0;Ig(Qs(),Qt(),w,y),u+=w+y,c&&c.setStats({tokens:u})}else if(Ot&&!Ot.usage){let w=S.map(T=>typeof T.content=="string"?T.content:Array.isArray(T.content)?T.content.map(O=>typeof O=="string"?O:O.text||"").join(""):"").join(" "),y=Dg(w),G=Dg(Ot.content||dt||"");Ig(Qs(),Qt(),y,G),u+=y+G,c&&c.setStats({tokens:u})}let{content:wu,tool_calls:fn}=Ot,$r=Wc(wu||""),$u=$r.truncated?$r.text:wu;$r.truncated&&j(`${h.yellow} \u26A0 LLM output loop detected (${$r.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${h.reset}`);let _r=mT($u||""),Mt=_r.truncated?_r.text:$u;_r.truncated&&j(`${h.yellow} \u26A0 LLM output loop detected (${_r.repeatCount}\xD7 repeated window) \u2014 response truncated${h.reset}`);let ao={role:"assistant",content:Mt||""};if(fn&&fn.length>0&&(ao.tool_calls=fn),P.push(ao),S.push(ao),mu&&(Mt||"").trim().length>1500&&_.size===0&&xn===0){j(`${h.green} \u2713 Analysis-only early exit: ${(Mt||"").length} chars produced, no file changes${h.reset}`),ao.tool_calls&&delete ao.tool_calls,Ne(N,L,_,J,Oe),Ae(P);break e}if(!ot&&Mt&&fn&&fn.length>0){let w=Dc(Mt);if(w){ot=!0,bt=w.slice(0,120),Bt=0,Ut=!1,Jt=0,j(`${h.yellow} \u26A1 Root cause in model analysis: ${bt} \u2014 fix phase (read budget: 3)${h.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${bt}. Read only the file that needs fixing, then edit it. Do not read other files.`};P.push(y),S.push(y)}}if(!fn||fn.length===0){let w=(Mt||"").trim().length>0||dt.trim().length>0,y=!1;if(At&&w&&(Bi>=2?j(`${h.yellow} \u26A0 SSH permanently blocked after ${Bi} storm warnings \u2014 no further SSH calls allowed${h.reset}`):(At=!1,qt=io-4,y=!0)),y&&w){let T=(Mt||"").trim();if(T.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(T.slice(-200))){let Z={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};S.push(Z),P.push(Z);continue}}if(!w&&N>0&&Ue<Hc-1){let T={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};S.push(T),P.push(T);continue}let G=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(w&&Ue<3&&G.test((Mt||"").slice(0,600)))if(Xc&&ms<=0||At){j(`${h.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${h.reset}`);let O={role:"user",content:"[SYSTEM] Correct \u2014 remote access is currently limited. Summarize what you have found so far and tell the user exactly what specific information (logs, process list, error output) you need from the server to continue."};S.push(O),P.push(O);continue}else{j(`${h.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${h.reset}`);let O={role:"user",content:"[SYSTEM] You have full tool access. Use your tools to investigate and implement the fix directly \u2014 do not say you cannot use tools. If SSH is needed, use a single targeted command that captures the most relevant information rather than multiple sequential calls."};S.push(O),P.push(O);continue}if(s.skillLoop&&w&&N>3&&yr<5){let T=(Mt||dt||"").toLowerCase();if(/\b(i.ll stop|stop the|stopped|done with|complet|summar|conclud|no more|finish|end of|that.s all|final|wrapped up|no further|mindful of|reached.*limit|tool call limit|at this point|recommend keep)/.test(T.slice(-600))){yr=(yr||0)+1,j(`${h.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${yr}${h.reset}`);let Z={role:"user",content:"[SYSTEM] Do NOT stop. You are in an autonomous experiment loop. The user is away and expects you to keep running experiments indefinitely until they interrupt with Ctrl+C. Start the next experiment NOW: hypothesize a new change, checkpoint, edit, run, measure, keep or revert. Think harder \u2014 try a completely different optimization approach."};S.push(Z),P.push(Z);continue}}if(ir()&&!s.skillLoop&&!$e&&(_.size>0||xn>0)&&w&&N>=2){j(`${h.green} \u2713 Headless early exit: ${_.size} file(s) modified (+ ${xn} bash writes), text response received${h.reset}`),Ne(N,L,_,J,Oe),Ae(P);break e}if($e&&Me==="plan"&&In>=2){j(`${h.cyan} \u21B3 Plan phase: ${In} consecutive blocks \u2014 auto-advancing to implement${h.reset}`),In=0;let T=await er("implement","[auto-advance: task only requires direct action]");if(T){P.push(T),S.push(T),Ue=0,xt=ps("implement");continue}}if($e&&w){let T=(Mt||dt||"").trim();if(Me==="plan"){let O=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files|keine (Ergebnisse|Treffer|Übereinstimmung|Funde|passenden)|nicht gefunden|nichts gefunden)\b/i,Z=ry(T,bn).length===0,B=lr.size>0,oe=cr.size>0,R=T.length>1500;if(ir()&&Z&&!B&&!oe&&!R&&O.test(T)){j(`${h.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${h.reset}
1374
+ `),Ne(N,L,_,J,Oe),Ae(P);break e}let q=await er("implement",T);if(q){P.push(q),S.push(q),Ue=0,xt=ps("implement");continue}}else if(Me==="implement"&&(_.size>0||xn>0)){let O=P.find(oe=>oe.role==="user"),Z=typeof O?.content=="string"?O.content:"",B=await er("verify",T,_,Z);if(B){P.push(B),S.push(B),Ue=0,xt=Math.min(ps("verify")+Math.max(0,(_.size-2)*2),20);continue}}else if(Me==="verify"){let O=/\bPASS\b/i.test(T.slice(0,500)),B=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(T.slice(0,500));if(B&&to<3){to++;let oe={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1338
1375
  ${T.slice(0,400)}
1339
1376
 
1340
- Fix the identified issues. This is attempt ${Zs}/3.`};Pe="implement",mn=Rc("implement",Qs),P.push(U),S.push(U),je=0,$t=as("implement"),j(`${h.yellow} \u21B3 Verify \u2192 implement loop-back #${Zs} (issues found)${h.reset}`);continue}if(j(`${h.green} \u2713 Verification phase complete${Q?" (loop-back exhausted)":" (PASS)"}${h.reset}`),!Q){Oe(O,q,b,Y,Ae),Ce(P),Ai(P);break e}}}if(tr()&&w&&O===0)if(ji++,ji>2)j(`${h.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${h.reset}`);else{let T={role:"user",content:`[SYSTEM] You wrote a plan without reading any files. This plan may be based on incorrect assumptions (wrong database type, wrong file structure, etc.).
1377
+ Fix the identified issues. This is attempt ${to}/3.`};Me="implement",kn=Uc("implement",so),P.push(oe),S.push(oe),Ue=0,xt=ps("implement"),j(`${h.yellow} \u21B3 Verify \u2192 implement loop-back #${to} (issues found)${h.reset}`);continue}if(!B&&(!O||dr===0)){if(no<2){no++;let oe=[];dr===0&&oe.push("run at least one verification tool"),O||oe.push("end your report with PASS or FAIL");let R={role:"user",content:`[SYSTEM] Verification is incomplete: ${oe.join(" and ")}. Do not stop yet. Re-read the modified files and/or run tests or linters, then respond with PASS or FAIL.`};P.push(R),S.push(R),j(`${h.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${no}/2)${h.reset}`);continue}j(`${h.yellow} \u26A0 Verify phase completion accepted without full markers after ${no} nudges${h.reset}`)}if(j(`${h.green} \u2713 Verification phase complete${B?" (loop-back exhausted)":" (PASS)"}${h.reset}`),!B){Ne(N,L,_,J,Oe),Ae(P),qi(P);break e}}}if(ar()&&w&&N===0)if(zi++,zi>2)j(`${h.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${h.reset}`);else{let T={role:"user",content:`[SYSTEM] You wrote a plan without reading any files. This plan may be based on incorrect assumptions (wrong database type, wrong file structure, etc.).
1341
1378
 
1342
- MANDATORY: Use read_file, glob, or grep to investigate the actual codebase first. Read at least the relevant module file and route file before writing the plan.`};P.push(T),S.push(T),j(`${h.yellow} \u26A0 Plan rejected (${ji}/2): no files read \u2014 forcing investigation${h.reset}`);continue}if(tr()&&w){let T=(Ct||lt||"").trim();KE(T),Ov(T);let M=XE(T);if(M.length>0){let Q=P.find(D=>D.role==="user"),U=typeof Q?.content=="string"?Q.content.slice(0,120):"Task";VE(U,M);let ie=M.length===1?"step":"steps",C=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:D,startExecution:F,setPlanMode:X}=Ei();process.stdout.write(`
1343
- ${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${M.length} ${ie})${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.yellow}[E]${h.reset}${h.dim}dit${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let K=process.stdin.isRaw,oe=await new Promise(de=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ee=>{try{process.stdin.setRawMode(K||!1)}catch{}let _e=ee.toString().toLowerCase()[0]||"\r";de(_e)})});if(process.stdout.write(`
1344
- `),oe==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(oe==="e")console.log(`${h.yellow}Type /plan edit to open in editor, or give feedback.${h.reset}`);else if(D()){F(),X(!1),Nc(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing ${M.length} ${ie}...`);let de=`[PLAN APPROVED \u2014 EXECUTE NOW]
1379
+ MANDATORY: Use read_file, glob, or grep to investigate the actual codebase first. Read at least the relevant module file and route file before writing the plan.`};P.push(T),S.push(T),j(`${h.yellow} \u26A0 Plan rejected (${zi}/2): no files read \u2014 forcing investigation${h.reset}`);continue}if(ar()&&w){let T=(Mt||dt||"").trim();Gv(T),CT(T);let O=zv(T);if(O.length>0){let Z=P.find(q=>q.role==="user"),B=typeof Z?.content=="string"?Z.content.slice(0,120):"Task";Kv(B,O);let oe=O.length===1?"step":"steps",R=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:q,startExecution:F,setPlanMode:X}=Pi();process.stdout.write(`
1380
+ ${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${O.length} ${oe})${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.yellow}[E]${h.reset}${h.dim}dit${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let K=process.stdin.isRaw,re=await new Promise(he=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",Q=>{try{process.stdin.setRawMode(K||!1)}catch{}let _e=Q.toString().toLowerCase()[0]||"\r";he(_e)})});if(process.stdout.write(`
1381
+ `),re==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(re==="e")console.log(`${h.yellow}Type /plan edit to open in editor, or give feedback.${h.reset}`);else if(q()){F(),X(!1),Gc(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing ${O.length} ${oe}...`);let he=`[PLAN APPROVED \u2014 EXECUTE NOW]
1345
1382
 
1346
1383
  Implement the following plan step by step. All tools are now available.
1347
1384
 
1348
- ${T}`;P.push({role:"user",content:de}),S.push({role:"user",content:de}),C=!0}}else console.log(`
1349
- ${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${M.length} ${ie} extracted).${h.reset} Type ${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ${h.reset}${h.cyan}/plan edit${h.reset}${h.dim} to review.${h.reset}`);if(C){c&&(c.stop(),c=null),je--;continue}}else{let Q=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:U,startExecution:ie,setPlanMode:C}=Ei();process.stdout.write(`
1350
- ${h.cyan}${h.bold}Plan ready.${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let D=process.stdin.isRaw,F=await new Promise(X=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",K=>{try{process.stdin.setRawMode(D||!1)}catch{}X(K.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1351
- `),F==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(U()){ie(),C(!1),Nc(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing...`);let K=`[PLAN APPROVED \u2014 EXECUTE NOW]
1385
+ ${T}`;P.push({role:"user",content:he}),S.push({role:"user",content:he}),R=!0}}else console.log(`
1386
+ ${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${O.length} ${oe} extracted).${h.reset} Type ${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ${h.reset}${h.cyan}/plan edit${h.reset}${h.dim} to review.${h.reset}`);if(R){c&&(c.stop(),c=null),Ue--;continue}}else{let Z=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:B,startExecution:oe,setPlanMode:R}=Pi();process.stdout.write(`
1387
+ ${h.cyan}${h.bold}Plan ready.${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let q=process.stdin.isRaw,F=await new Promise(X=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",K=>{try{process.stdin.setRawMode(q||!1)}catch{}X(K.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1388
+ `),F==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(B()){oe(),R(!1),Gc(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing...`);let K=`[PLAN APPROVED \u2014 EXECUTE NOW]
1352
1389
 
1353
1390
  Implement the following plan step by step. All tools are now available.
1354
1391
 
1355
- ${getPlanContent()||Tt.content}`;P.push({role:"user",content:K}),S.push({role:"user",content:K}),Q=!0}}else console.log(`
1356
- ${h.cyan}${h.bold}Plan ready.${h.reset} ${h.dim}Type ${h.reset}${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ask follow-up questions to refine.${h.reset}`);if(Q){c&&(c.stop(),c=null),je--;continue}}}if(c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae),It&&b.size>=3){let T=[...b].map(C=>C.split("/").pop()).slice(0,8).join(", "),M=[...b].some(C=>C.endsWith("package.json")),Q=[...b].some(C=>C.endsWith("requirements.txt")),U=[...b].some(C=>C.endsWith("package-lock.json")||C.endsWith("yarn.lock")||C.endsWith("pnpm-lock.yaml")),ie=M&&!U?"npm install not yet run":Q?"pip install not yet run":null;Qo=`[Previous session created ${b.size} files: ${T}`+(ie?` \u2014 ${ie}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(It&&!Ic&&O>0){let T=[...b].some(K=>K.endsWith("package.json")),M=[...b].some(K=>K.endsWith("requirements.txt")||K.endsWith("Pipfile")||K.endsWith("pyproject.toml")),Q=[...b].some(K=>K.endsWith("package-lock.json")||K.endsWith("yarn.lock")||K.endsWith("pnpm-lock.yaml")),U=P.flatMap(K=>{let oe=Array.isArray(K.tool_calls)?K.tool_calls:[],de=Array.isArray(K.content)?K.content.filter(ee=>ee?.type==="tool_use"):[];return[...oe,...de]}).filter(K=>{let oe=K.function?.name||K.name||"";return oe==="bash"||oe==="Bash"}).map(K=>{try{let oe=K.function?.arguments??K.input??{};return(typeof oe=="string"?JSON.parse(oe):oe)?.command||""}catch{return""}}),ie=U.some(K=>/pip\s+install|python\s+-m\s+venv/.test(K)),C=U.some(K=>/npm\s+install/.test(K)),F=[...b].some(K=>/\/App\.(js|ts|jsx|tsx)$/.test(K))&&!T&&!C;if(M&&!ie||T&&!Q&&!C||F){Ic=!0;let K=[];M&&!ie&&K.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),F?K.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):T&&!Q&&!C&&K.push("npm install");let oe=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${K.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;j(`${h.dim} [post-creation] bootstrapping environment (${K.join(", ")})${h.reset}`),P.push({role:"user",content:oe}),S.push({role:"user",content:oe});continue}}if(O>0&&!s._isSummaryTurn&&jE(Ct))try{j(`${h.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${h.reset}`);let T=b.size>0?"Write a closing summary (3+ sentences): what files changed and why, what the result is, anything the user should know or do next.":"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",M=[...S,{role:"user",content:T}],U=((await ag(M,[],{}))?.content||"").trim();U&&(console.log(`
1357
- ${U}`),P.push({role:"user",content:T},{role:"assistant",content:U}))}catch{}Ce(P),Ai(P),await Qc();return}O++,Ki++,O>=1&&(ge=!1);for(let w of rn){let y=w.function.name;q.set(y,(q.get(y)||0)+1)}if(O>=30&&!_g){_g=!0,j(`${h.yellow} \u26A0 Tool budget warning: ${O} tool calls used \u2014 nudging model to wrap up${h.reset}`);let w={role:"user",content:"[SYSTEM] \u26A0 You have used "+O+" tool calls. This is approaching the quality threshold (40). Wrap up NOW: write your final summary and stop. Do NOT run additional verification commands (git status, git diff, git log) \u2014 your changes are already committed and verified. Further tool calls will hurt session quality."};P.push(w),S.push(w)}let ye=await Promise.all(rn.map(w=>Nv(w)));{let w=Yt(S,it()),y=w.percentage,z=ye.some(U=>U.canExecute&&U.fnName==="read_file"&&!U.args?.line_end),T=ye.filter(U=>U.canExecute&&U.fnName==="read_file"&&U.args?.path&&nn(ms,U.args.path)>=1&&!U.args?.line_start).map(U=>U.args.path.split("/").slice(-2).join("/")),M=T.length>0;if(y>=70&&z&&ta<70||y>=85&&ta<85||M){ta=y;let U=y>=85?"URGENT":"WARNING",ie;M?(U="WARNING",ie=`Full-file read of ${T.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):z?ie=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:ie="Use targeted reads (line_start/line_end) to save space.";let C={role:"user",content:`[SYSTEM ${U}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${ie}`};if(P.push(C),S.push(C),y>=85){let D=M?` (re-read of: ${T.join(", ")})`:"";j(`${h.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${D}${h.reset}`)}}}let aa=new Map;for(let w of ye){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let z=nn(ms,y),T=aa.get(y)||0,M=z+T,Q=w.args?.line_start!=null,U=Pt.get(y)||0,ie=U>0,C=2;if(M>=gs){let D=y.split("/").slice(-2).join("/"),F=(fs.get(y)||0)+1;if(fs.set(y,F),F===1)j(`${h.red} \u2716 Blocked: "${D}" read ${M}\xD7 \u2014 hard cap (${gs}) reached${h.reset}`);else if(F===2){j(`${h.red} \u2716 Escalated block: "${D}" \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${y}") and tried again anyway. This file has reached its read cap (${gs}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};P.push(X),S.push(X)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${M}\xD7 (hard cap: ${gs}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:w.callId}}else if(M>=1&&Q)if(ie&&U<=C){let D=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Targeted re-read: "${D}" (line_start=${w.args.line_start}) \u2014 edit recovery #${U}${h.reset}`),Pt.set(y,U-1)}else if(ie&&U>C){let D=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Edit recovery blocked: "${D}" \u2014 ${C} recovery reads already used. Use grep to find the exact line numbers, then retry.${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${C} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:w.callId}}else{let D=parseInt(w.args.line_start,10)||1,F=parseInt(w.args.line_end,10)||D+350,X=Rn.get(y)||[],K=!1;for(let[oe,de]of X){let ee=Math.max(D,oe),_e=Math.min(F,de);if(_e>ee){let ve=_e-ee,mt=F-D||1,Xe=de-oe||1,At=ve/Xe>=.7&&ve/mt<.7,Ve=F-D<=xy;if(ve>=mt||!Ve&&(ve/mt>=.7||ve/Xe>=.7)){let ca=y.split("/").slice(-2).join("/"),cu=`${y}:${D}-${F}`,ws=(zi.get(cu)||0)+1;if(zi.set(cu,ws),j(At?`${h.red} \u2716 Blocked superread: "${ca}" lines ${D}-${F} subsumes already-read ${oe}-${de} \u2014 use line_start=${de+1} to skip known content (block #${ws})${h.reset}`:`${h.red} \u2716 Blocked duplicate read: "${ca}" lines ${D}-${F} (\u226570% overlap with lines ${oe}-${de} already in context, block #${ws})${h.reset}`),ws>=2){j(`${h.red} \u2716 Escalated range-block: "${ca}" lines ${D}-${F} \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let uu={role:"user",content:At?`[SYSTEM] Read blocked ${ws}\xD7 for read_file("${y}", lines ${D}-${F}). Lines ${oe}-${de} were already read. Use line_start=${de+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${ws}\xD7 for read_file("${y}", lines ${D}-${F}). Lines ${oe}-${de} were already read and will NOT change. Use grep_search to find specific content instead.`};P.push(uu),S.push(uu)}w.canExecute=!1,w.errorResult={role:"tool",content:At?`BLOCKED: read_file("${y}", lines ${D}-${F}) re-reads lines ${oe}-${de} already in context. Use line_start=${de+1} to read only the new content beyond line ${de}.`:`BLOCKED: read_file("${y}", lines ${D}-${F}) is a duplicate \u2014 lines ${oe}-${de} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:w.callId},K=!0;break}}}if(!K){let oe=X.length,de=2;if(oe>=3){let _e=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked file-scroll: "${_e}" \u2014 ${oe} sections already read. Use grep to find specific content.${h.reset}`);let ve=nn(ea,y)>=cr;w.canExecute=!1,w.errorResult={role:"tool",content:ve?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${oe} different sections of this file (file-scroll pattern). Grep is also exhausted. The content you need is already in your context \u2014 work with what you have.`:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${oe} different sections of this file (file-scroll pattern). You have seen most of this file. Use grep_search to find the exact lines you need instead of continuing to scroll.`,tool_call_id:w.callId}}else oe>=de&&(w._scrollWarn={sectionCount:oe+1,path:y})}}else if(M>=1){let D=Pt.get(y)||0;if(D>0){let F=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Full re-read: "${F}" \u2014 test-failure recovery (${D} remaining)${h.reset}`);let X=D-1;X<=0?Pt.delete(y):Pt.set(y,X)}else{let F=y.split("/").slice(-2).join("/"),X=(fs.get(y)||0)+1;if(fs.set(y,X),X===1)j(`${h.red} \u2716 Blocked unbounded re-read: "${F}" \u2014 already in context. Use line_start/line_end for specific sections.${h.reset}`);else if(X===2){j(`${h.red} \u2716 Escalated block: "${F}" \u2014 model ignored unbounded re-read block, injecting system warning${h.reset}`);let K={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};P.push(K),S.push(K)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${M}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:w.callId}}}w.canExecute&&aa.set(y,(aa.get(y)||0)+1)}if(Tn>=3)for(let w of ye)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(j(`${h.red} \u2716 Blocked ${w.fnName} \u2014 ${Tn} consecutive file-not-found errors, must search first${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${Tn} consecutive "File not found" errors. You must call search_files or glob_files to locate the correct path before reading or editing. Do not guess file paths.`,tool_call_id:w.callId}));for(let w of ye){if(!w.canExecute||w.fnName!=="bash")continue;let y=(w.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){j(`${h.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:w.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(j(`${h.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:w.callId})}for(let w of ye)w.canExecute&&(w.fnName!=="ssh_exec"&&w.fnName!=="bash"||/\bsed\s+-n\b/.test(w.args?.command||"")&&(j(`${h.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:w.callId}));for(let w of ye){if(!w.canExecute||w.fnName!=="write_file")continue;let y=w.args?.path,z=w.args?.content||"";if(y)try{let T=require("fs"),M=require("path").resolve(process.cwd(),y);if(T.existsSync(M)){let Q=T.statSync(M).size,U=Buffer.byteLength(z,"utf8"),ie=Q>0?U/Q:1;if(ie<.6&&Q>200){let C=y.split("/").slice(-2).join("/");console.log(`${h.red} \u2716 write_file shrink guard: "${C}" would shrink to ${Math.round(ie*100)}% of original \u2014 likely context loss${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(ie*100)}% of current file size (${Q} \u2192 ${U} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:w.callId}}}}catch{}}let ru=new Map;for(let w of ye){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let z=ru.get(y)||0,T=nn(ea,y)+z,M=nn(ms,y)>=1,Q=M?Math.min(3,cr):cr;if(T>=Q){let U=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked grep: "${U}" grepped ${T}\xD7 with different patterns \u2014 flood threshold exceeded${h.reset}`);let ie=nn(ms,y),C=ie>=gs;if(C){let D={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${ie} sections and tried ${T} grep patterns. Do NOT attempt to read or grep this file again. The content you need is already in your conversation context \u2014 scroll back to find it, or proceed with what you know.`};P.push(D),S.push(D),j(`${h.red} \u2716 Deadlock detected: "${U}" \u2014 both read and grep blocked, injecting deadlock-break${h.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:C?`BLOCKED: grep("${y}") denied \u2014 ${T} patterns already tried AND reads are also exhausted. The content is already in your context. Do not attempt to read or grep this file again.`:M?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${T} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${T} patterns already tried. Work with the grep results already in your context.`,tool_call_id:w.callId}}w.canExecute&&ru.set(y,z+1)}let Cy=5,iu=new Map;for(let w of ye){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let z=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),T=iu.get(z)||0,M=nn(Vc,z)+T;M>=Cy&&(j(`${h.yellow} \u26A0 Blocked ssh_exec: same command run ${M}\xD7 \u2014 result already in context${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${M} times and the output is in your context. Use existing results, try a different command, or run it as a local bash call: bash("ssh user@host 'your command'").`,tool_call_id:w.callId}),w.canExecute&&iu.set(z,T+1)}if(vt){let w=ye.filter(T=>T.canExecute&&T.fnName==="ssh_exec"),y=ye.some(T=>T.canExecute&&T.fnName!=="ssh_exec"),z=I&&H<3;if(w.length>0&&!y&&z&&Fi<1)vt=!1,Fi++,Lt=Math.max(0,so-2),j(`${h.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Fi}/1)]${h.reset}`);else for(let T of w)T.canExecute=!1,T.errorResult={role:"tool",content:et?`BLOCKED: ssh_exec denied \u2014 SSH paused (${so}+ calls). Root cause is known (${wt}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${so}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary. For one-off lookups use bash("ssh user@host 'cmd'") instead.`,tool_call_id:T.callId}}if(I&&H<3&&!vt){for(let w of ye)if(w.canExecute&&["bash","read_file","find_files"].includes(w.fnName)){H++;{let y=it(),{messages:z}=tn(S,y);S=z}j(`${h.yellow} \u26A0 Server-local guard: blocking local ${w.fnName} \u2014 use ssh_exec on 94.130.37.43${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:w.callId};break}}if(!we&&jt&&It&&zt>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of ye)y.canExecute&&w.includes(y.fnName)&&(j(`${h.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(cs>=0){let w=ye.filter(y=>y.canExecute).length;if(w>0&&(cs-=w,cs<0))if(!Ui&&b.size>Bi){Ui=!0,cs=5,j(`${h.green} \u2713 Post-wipe progress detected (${b.size-Bi} files modified) \u2014 granting 5 bonus tool calls${h.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};P.push(y),S.push(y)}else{j(`${h.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${h.reset}`);for(let z of ye)z.canExecute&&(z.canExecute=!1,z.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:z.callId});let y={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};P.push(y),S.push(y)}}let Ay=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open","skill_ar_run_experiment","skill_ar_run_benchmark","skill_ar_checkpoint","skill_ar_revert","skill_ar_log_experiment","skill_ar_extract_metric"]);for(let w of ye){if(!w.canExecute||Ay.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),z=`${w.fnName}|${y}`,T=nn(Mc,z);T>=2?(j(`${h.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${T+1}\xD7 with identical args${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName}() with these exact arguments has already been called ${T}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:w.callId}):T===1&&j(`${h.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${h.reset}`),ls(Mc,z)}{let w=new Set;for(let y of ye){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let z=y.args?.path;z&&(ke.has(z)||w.has(z)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${z}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:y.callId},j(`${h.yellow} \u26A0 Map-first gate: blocked re-edit of "${z.split("/").slice(-1)[0]}" \u2014 re-read required${h.reset}`)):w.add(z))}}let ro=c?{skipSpinner:!0,skipSummaries:!0}:{},Oy=ye.some(w=>w.fnName==="ask_user"),au=!ro.skipSummaries&&!ge,pr=null,ys=null;au&&!Oy?(ge=!0,ro.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(ys=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Ci(ye,O,!1,"blink")),pr=!0):sn||process.stdout.write(Ci(ye,O,!1)+`
1358
- `)):au&&(ge=!0,ro.skipSpinner=!0),c&&c._paused&&c.resume();let mr=null;if(pr&&process.stdout.isTTY&&ye.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();mr=setInterval(()=>{let z=Math.round((Date.now()-y)/1e3);if(z>=3){let T=`${Ci(ye,O,!1,"blink")} ${h.dim}[${z}s]${h.reset}`;ys!==null?process.stdout.write(`\x1B[${ys};1H\x1B[2K${T}`):process.stdout.write(`\r\x1B[2K${T}`)}},1e3)}let{results:nt,summaries:Ny}=await Iv(ye,!0,{...ro,skipSummaries:!0});if(mr&&(clearInterval(mr),mr=null),pr){pr=null;let w=Ci(ye,O,!1);ys!==null?process.stdout.write(`\x1B[${ys};1H\x1B[2K${w}
1392
+ ${getPlanContent()||Ot.content}`;P.push({role:"user",content:K}),S.push({role:"user",content:K}),Z=!0}}else console.log(`
1393
+ ${h.cyan}${h.bold}Plan ready.${h.reset} ${h.dim}Type ${h.reset}${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ask follow-up questions to refine.${h.reset}`);if(Z){c&&(c.stop(),c=null),Ue--;continue}}}if(c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe),Ft&&_.size>=3){let T=[..._].map(R=>R.split("/").pop()).slice(0,8).join(", "),O=[..._].some(R=>R.endsWith("package.json")),Z=[..._].some(R=>R.endsWith("requirements.txt")),B=[..._].some(R=>R.endsWith("package-lock.json")||R.endsWith("yarn.lock")||R.endsWith("pnpm-lock.yaml")),oe=O&&!B?"npm install not yet run":Z?"pip install not yet run":null;rr=`[Previous session created ${_.size} files: ${T}`+(oe?` \u2014 ${oe}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Ft&&!Vc&&N>0){let T=[..._].some(K=>K.endsWith("package.json")),O=[..._].some(K=>K.endsWith("requirements.txt")||K.endsWith("Pipfile")||K.endsWith("pyproject.toml")),Z=[..._].some(K=>K.endsWith("package-lock.json")||K.endsWith("yarn.lock")||K.endsWith("pnpm-lock.yaml")),B=P.flatMap(K=>{let re=Array.isArray(K.tool_calls)?K.tool_calls:[],he=Array.isArray(K.content)?K.content.filter(Q=>Q?.type==="tool_use"):[];return[...re,...he]}).filter(K=>{let re=K.function?.name||K.name||"";return re==="bash"||re==="Bash"}).map(K=>{try{let re=K.function?.arguments??K.input??{};return(typeof re=="string"?JSON.parse(re):re)?.command||""}catch{return""}}),oe=B.some(K=>/pip\s+install|python\s+-m\s+venv/.test(K)),R=B.some(K=>/npm\s+install/.test(K)),F=[..._].some(K=>/\/App\.(js|ts|jsx|tsx)$/.test(K))&&!T&&!R;if(O&&!oe||T&&!Z&&!R||F){Vc=!0;let K=[];O&&!oe&&K.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),F?K.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):T&&!Z&&!R&&K.push("npm install");let re=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${K.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;j(`${h.dim} [post-creation] bootstrapping environment (${K.join(", ")})${h.reset}`),P.push({role:"user",content:re}),S.push({role:"user",content:re});continue}}if(N>0&&!s._isSummaryTurn&&Iv(Mt))try{j(`${h.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${h.reset}`);let T=_.size>0?"Write a closing summary (3+ sentences): what files changed and why, what the result is, anything the user should know or do next.":"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",O=[...S,{role:"user",content:T}],B=((await Pg(O,[],{}))?.content||"").trim();B&&(console.log(`
1394
+ ${B}`),P.push({role:"user",content:T},{role:"assistant",content:B}))}catch{}Ae(P),qi(P),await hu();return}N++,sa++,N>=1&&(ye=!1);for(let w of fn){let y=w.function.name;L.set(y,(L.get(y)||0)+1)}if(N>=30&&!Gg){Gg=!0,j(`${h.yellow} \u26A0 Tool budget warning: ${N} tool calls used \u2014 nudging model to wrap up${h.reset}`);let w={role:"user",content:"[SYSTEM] \u26A0 You have used "+N+" tool calls. This is approaching the quality threshold (40). Wrap up NOW: write your final summary and stop. Do NOT run additional verification commands (git status, git diff, git log) \u2014 your changes are already committed and verified. Further tool calls will hurt session quality."};P.push(w),S.push(w)}let we=await Promise.all(fn.map(w=>AT(w)));{let w=Vt(S,ut()),y=w.percentage,G=we.some(B=>B.canExecute&&B.fnName==="read_file"&&!B.args?.line_end),T=we.filter(B=>B.canExecute&&B.fnName==="read_file"&&B.args?.path&&ln(_s,B.args.path)>=1&&!B.args?.line_start).map(B=>B.args.path.split("/").slice(-2).join("/")),O=T.length>0;if(y>=70&&G&&ua<70||y>=85&&ua<85||O){ua=y;let B=y>=85?"URGENT":"WARNING",oe;O?(B="WARNING",oe=`Full-file read of ${T.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):G?oe=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:oe="Use targeted reads (line_start/line_end) to save space.";let R={role:"user",content:`[SYSTEM ${B}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${oe}`};if(P.push(R),S.push(R),y>=85){let q=O?` (re-read of: ${T.join(", ")})`:"";j(`${h.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${q}${h.reset}`)}}}let ga=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let G=ln(_s,y),T=ga.get(y)||0,O=G+T,Z=w.args?.line_start!=null,B=Dt.get(y)||0,oe=B>0,R=2;if(O>=bs){let q=y.split("/").slice(-2).join("/"),F=(ws.get(y)||0)+1;if(ws.set(y,F),F===1)j(`${h.red} \u2716 Blocked: "${q}" read ${O}\xD7 \u2014 hard cap (${bs}) reached${h.reset}`);else if(F===2){j(`${h.red} \u2716 Escalated block: "${q}" \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${y}") and tried again anyway. This file has reached its read cap (${bs}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};P.push(X),S.push(X)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${O}\xD7 (hard cap: ${bs}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:w.callId}}else if(O>=1&&Z)if(oe&&B<=R){let q=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Targeted re-read: "${q}" (line_start=${w.args.line_start}) \u2014 edit recovery #${B}${h.reset}`),Dt.set(y,B-1)}else if(oe&&B>R){let q=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Edit recovery blocked: "${q}" \u2014 ${R} recovery reads already used. Use grep to find the exact line numbers, then retry.${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${R} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:w.callId}}else{let q=parseInt(w.args.line_start,10)||1,F=parseInt(w.args.line_end,10)||q+350,X=Ln.get(y)||[],K=!1;for(let[re,he]of X){let Q=Math.max(q,re),_e=Math.min(F,he);if(_e>Q){let Te=_e-Q,wt=F-q||1,Qe=he-re||1,Pt=Te/Qe>=.7&&Te/wt<.7,et=F-q<=Qy;if(Te>=wt||!et&&(Te/wt>=.7||Te/Qe>=.7)){let wa=y.split("/").slice(-2).join("/"),Su=`${y}:${q}-${F}`,xs=(na.get(Su)||0)+1;if(na.set(Su,xs),j(Pt?`${h.red} \u2716 Blocked superread: "${wa}" lines ${q}-${F} subsumes already-read ${re}-${he} \u2014 use line_start=${he+1} to skip known content (block #${xs})${h.reset}`:`${h.red} \u2716 Blocked duplicate read: "${wa}" lines ${q}-${F} (\u226570% overlap with lines ${re}-${he} already in context, block #${xs})${h.reset}`),xs>=2){j(`${h.red} \u2716 Escalated range-block: "${wa}" lines ${q}-${F} \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let Eu={role:"user",content:Pt?`[SYSTEM] Read blocked ${xs}\xD7 for read_file("${y}", lines ${q}-${F}). Lines ${re}-${he} were already read. Use line_start=${he+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${xs}\xD7 for read_file("${y}", lines ${q}-${F}). Lines ${re}-${he} were already read and will NOT change. Use grep_search to find specific content instead.`};P.push(Eu),S.push(Eu)}w.canExecute=!1,w.errorResult={role:"tool",content:Pt?`BLOCKED: read_file("${y}", lines ${q}-${F}) re-reads lines ${re}-${he} already in context. Use line_start=${he+1} to read only the new content beyond line ${he}.`:`BLOCKED: read_file("${y}", lines ${q}-${F}) is a duplicate \u2014 lines ${re}-${he} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:w.callId},K=!0;break}}}if(!K){let re=X.length,he=2;if(re>=3){let _e=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked file-scroll: "${_e}" \u2014 ${re} sections already read. Use grep to find specific content.${h.reset}`);let Te=ln(ca,y)>=gr;w.canExecute=!1,w.errorResult={role:"tool",content:Te?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${re} different sections of this file (file-scroll pattern). Grep is also exhausted. The content you need is already in your context \u2014 work with what you have.`:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${re} different sections of this file (file-scroll pattern). You have seen most of this file. Use grep_search to find the exact lines you need instead of continuing to scroll.`,tool_call_id:w.callId}}else re>=he&&(w._scrollWarn={sectionCount:re+1,path:y})}}else if(O>=1){let q=Dt.get(y)||0;if(q>0){let F=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Full re-read: "${F}" \u2014 test-failure recovery (${q} remaining)${h.reset}`);let X=q-1;X<=0?Dt.delete(y):Dt.set(y,X)}else{let F=y.split("/").slice(-2).join("/"),X=(ws.get(y)||0)+1;if(ws.set(y,X),X===1)j(`${h.red} \u2716 Blocked unbounded re-read: "${F}" \u2014 already in context. Use line_start/line_end for specific sections.${h.reset}`);else if(X===2){j(`${h.red} \u2716 Escalated block: "${F}" \u2014 model ignored unbounded re-read block, injecting system warning${h.reset}`);let K={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};P.push(K),S.push(K)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${O}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:w.callId}}}w.canExecute&&ga.set(y,(ga.get(y)||0)+1)}if(Pn>=3)for(let w of we)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(j(`${h.red} \u2716 Blocked ${w.fnName} \u2014 ${Pn} consecutive file-not-found errors, must search first${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${Pn} consecutive "File not found" errors. You must call search_files or glob_files to locate the correct path before reading or editing. Do not guess file paths.`,tool_call_id:w.callId}));for(let w of we){if(!w.canExecute||w.fnName!=="bash")continue;let y=(w.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){j(`${h.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:w.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(j(`${h.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:w.callId})}for(let w of we)w.canExecute&&(w.fnName!=="ssh_exec"&&w.fnName!=="bash"||/\bsed\s+-n\b/.test(w.args?.command||"")&&(j(`${h.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:w.callId}));for(let w of we){if(!w.canExecute||w.fnName!=="write_file")continue;let y=w.args?.path,G=w.args?.content||"";if(y)try{let T=require("fs"),O=require("path").resolve(process.cwd(),y);if(T.existsSync(O)){let Z=T.statSync(O).size,B=Buffer.byteLength(G,"utf8"),oe=Z>0?B/Z:1;if(oe<.6&&Z>200){let R=y.split("/").slice(-2).join("/");console.log(`${h.red} \u2716 write_file shrink guard: "${R}" would shrink to ${Math.round(oe*100)}% of original \u2014 likely context loss${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(oe*100)}% of current file size (${Z} \u2192 ${B} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:w.callId}}}}catch{}}let _u=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let G=_u.get(y)||0,T=ln(ca,y)+G,O=ln(_s,y)>=1,Z=O?Math.min(3,gr):gr;if(T>=Z){let B=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked grep: "${B}" grepped ${T}\xD7 with different patterns \u2014 flood threshold exceeded${h.reset}`);let oe=ln(_s,y),R=oe>=bs;if(R){let q={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${oe} sections and tried ${T} grep patterns. Do NOT attempt to read or grep this file again. The content you need is already in your conversation context \u2014 scroll back to find it, or proceed with what you know.`};P.push(q),S.push(q),j(`${h.red} \u2716 Deadlock detected: "${B}" \u2014 both read and grep blocked, injecting deadlock-break${h.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:R?`BLOCKED: grep("${y}") denied \u2014 ${T} patterns already tried AND reads are also exhausted. The content is already in your context. Do not attempt to read or grep this file again.`:O?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${T} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${T} patterns already tried. Work with the grep results already in your context.`,tool_call_id:w.callId}}w.canExecute&&_u.set(y,G+1)}let r0=5,bu=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let G=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),T=bu.get(G)||0,O=ln(du,G)+T;O>=r0&&(j(`${h.yellow} \u26A0 Blocked ssh_exec: same command run ${O}\xD7 \u2014 result already in context${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${O} times and the output is in your context. Use existing results, try a different command, or run it as a local bash call: bash("ssh user@host 'your command'").`,tool_call_id:w.callId}),w.canExecute&&bu.set(G,T+1)}if(At){let w=we.filter(T=>T.canExecute&&T.fnName==="ssh_exec"),y=we.some(T=>T.canExecute&&T.fnName!=="ssh_exec"),G=I&&H<3;if(w.length>0&&!y&&G&&Xi<1)At=!1,Xi++,qt=Math.max(0,io-2),j(`${h.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Xi}/1)]${h.reset}`);else for(let T of w)T.canExecute=!1,T.errorResult={role:"tool",content:ot?`BLOCKED: ssh_exec denied \u2014 SSH paused (${io}+ calls). Root cause is known (${bt}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${io}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary. For one-off lookups use bash("ssh user@host 'cmd'") instead.`,tool_call_id:T.callId}}if(I&&H<3&&!At){for(let w of we)if(w.canExecute&&["bash","read_file","find_files"].includes(w.fnName)){H++;{let y=ut(),{messages:G}=an(S,y);S=G}j(`${h.yellow} \u26A0 Server-local guard: blocking local ${w.fnName} \u2014 use ssh_exec on 94.130.37.43${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:w.callId};break}}if(!$e&&Ut&&Ft&&Zt>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of we)y.canExecute&&w.includes(y.fnName)&&(j(`${h.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(ms>=0){let w=we.filter(y=>y.canExecute).length;if(w>0&&(ms-=w,ms<0))if(!Ji&&_.size>Vi){Ji=!0,ms=5,j(`${h.green} \u2713 Post-wipe progress detected (${_.size-Vi} files modified) \u2014 granting 5 bonus tool calls${h.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};P.push(y),S.push(y)}else{j(`${h.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${h.reset}`);for(let G of we)G.canExecute&&(G.canExecute=!1,G.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:G.callId});let y={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};P.push(y),S.push(y)}}let i0=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open","skill_ar_run_experiment","skill_ar_run_benchmark","skill_ar_checkpoint","skill_ar_revert","skill_ar_log_experiment","skill_ar_extract_metric"]);for(let w of we){if(!w.canExecute||i0.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),G=`${w.fnName}|${y}`,T=ln(zc,G);T>=2?(j(`${h.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${T+1}\xD7 with identical args${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName}() with these exact arguments has already been called ${T}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:w.callId}):T===1&&j(`${h.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${h.reset}`),hs(zc,G)}{let w=new Set;for(let y of we){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let G=y.args?.path;G&&(de.has(G)||w.has(G)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${G}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:y.callId},j(`${h.yellow} \u26A0 Map-first gate: blocked re-edit of "${G.split("/").slice(-1)[0]}" \u2014 re-read required${h.reset}`)):w.add(G))}}let lo=c?{skipSpinner:!0,skipSummaries:!0}:{},a0=we.some(w=>w.fnName==="ask_user"),ku=!lo.skipSummaries&&!ye,br=null,ks=null;ku&&!a0?(ye=!0,lo.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(ks=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Di(we,N,!1,"blink")),br=!0):un||process.stdout.write(Di(we,N,!1)+`
1395
+ `)):ku&&(ye=!0,lo.skipSpinner=!0),c&&c._paused&&c.resume();let kr=null;if(br&&process.stdout.isTTY&&we.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();kr=setInterval(()=>{let G=Math.round((Date.now()-y)/1e3);if(G>=3){let T=`${Di(we,N,!1,"blink")} ${h.dim}[${G}s]${h.reset}`;ks!==null?process.stdout.write(`\x1B[${ks};1H\x1B[2K${T}`):process.stdout.write(`\r\x1B[2K${T}`)}},1e3)}let{results:it,summaries:l0}=await PT(we,!0,{...lo,skipSummaries:!0});if(kr&&(clearInterval(kr),kr=null),br){br=null;let w=Di(we,N,!1);ks!==null?process.stdout.write(`\x1B[${ks};1H\x1B[2K${w}
1359
1396
  `):process.stdout.write(`\r\x1B[2K${w}
1360
- `),ys=null}if(!ro.skipSummaries){let w=Ny.filter((T,M)=>!(ye[M]&&ye[M].fnName==="ask_user"));for(let T of w)console.log(T);let y=ye.filter(T=>T&&T.fnName!=="ask_user").map(T=>T.fnName),z=iy.record(0,y,Y,b);z&&fv(z)}for(let w of ye){if(w.canExecute||!w.errorResult)continue;let y=typeof w.errorResult.content=="string"?w.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:")||y.startsWith("PLAN PHASE:"))&&(Nn++,Nn>=Jc)){j(`${h.red} \u2716 Loop abort: ${Nn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae,{suppressHint:!0}),Ce(P);return}}for(let w=0;w<ye.length;w++){let y=ye[w];if(!y.canExecute)continue;let z=nt[w].content,T=z.split(`
1361
- `)[0],M=!T.startsWith("ERROR")&&!T.startsWith("CANCELLED")&&!T.startsWith("Command failed")&&!T.startsWith("EXIT");if(!M&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&T.includes("old_text not found")){let C=Pt.get(y.args.path)||0;Pt.set(y.args.path,C+1)}if(!M&&y.fnName==="bash"&&or.size>0){let C=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(C))for(let[F]of or)Pt.has(F)||(Pt.set(F,1),j(`${h.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${F.split("/").pop()}"${h.reset}`))}if(!M&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(T)){if(Tn++,Tn>=2){j(`${h.yellow} \u26A0 File-not-found streak: ${Tn} consecutive misses \u2014 forcing search${h.reset}`);let C={role:"user",content:`[SYSTEM] ${Tn} consecutive "File not found" errors. STOP guessing paths. Use search_files or glob_files to locate the correct file first, then read/edit the path returned by the search.`};P.push(C),S.push(C)}}else M&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(Tn=0);if(M&&y.fnName==="write_file"&&y.args?.path){let C=y.args.path.split("/").pop(),D=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(C)&&!D){j(`${h.yellow} \u26A0 Temp file: "${C}" \u2014 delete with bash rm when done to keep the workspace clean${h.reset}`);let X={role:"user",content:`[HINT] "${y.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${y.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};P.push(X),S.push(X)}}if(M&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Pt.delete(y.args.path),b.add(y.args.path);for(let F of hs)!F.done&&y.args.path.endsWith(F.file.split("/").pop())&&(F.done=!0,j(`${h.green} \u2713 TODO done: ${F.file}${h.reset}`));let C=ls(ay,y.args.path),D=y.args.path.split("/").slice(-2).join("/");if(C===ly){j(`${h.yellow} \u26A0 Loop warning: "${D}" edited ${C}\xD7 \u2014 possible edit loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${C}\xD7. One more edit max, then move on.`};P.push(F),S.push(F)}else if(C>=cy){j(`${h.red} \u2716 Loop abort: "${D}" edited ${C}\xD7 \u2014 aborting to prevent runaway loop${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae,{suppressHint:!0}),Ce(P);return}}if(M&&y.canExecute&&we&&(An=0),M&&y.canExecute&&!(we&&Pe==="plan")){let C=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){Dt=0,jt=!1,Gt=0,zt++;let ee=y.args?.path||y.args?.file_path;ee&&(Ec(pn,ee,1),Rn.delete(ee),ke.add(ee))}else if(C.includes(y.fnName)&&(Dt++,jt&&Gt++,we&&Pe==="implement"&&y.fnName==="read_file"&&hs.length>0)){let ee=y.args?.path||y.args?.file_path||"",_e=hs.find(ve=>!ve.done&&ee.endsWith(ve.file.split("/").pop()));if(_e){let ve={role:"user",content:`[TODO OBSERVER] You already analyzed "${_e.file}" in the plan phase. Action: ${_e.action}
1362
- Do NOT re-read \u2014 apply the edit directly with edit_file.`};P.push(ve),S.push(ve),j(`${h.yellow} \u26A0 TODO nudge: ${_e.file} \u2014 already analyzed, edit directly${h.reset}`)}}let F=n.postEditCap,X=we&&Pe==="implement"?Math.min(Zc,10):Zc,K=et?8:It?zt>0?6:10:zt>0?F:X,oe=6,de=!we&&jt&&(et&&Gt>=oe||It&&zt>=3&&Gt>=oe||Gt>=oe);if(Go<2&&!jt&&Dt>=3&&b.size===0){let ee=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,_e=Date.now()-Ae,ve=Go===0?.4:.65;if(ee>0&&_e>ee*ve){Go++;let mt=Math.round(_e/6e4),Xe=Math.round(_e/ee*100);j(`${h.yellow} \u26A0 Time nudge #${Go}: ${mt}m elapsed (${Xe}%), ${Dt} reads, 0 edits${h.reset}`);let At={role:"user",content:Go===1?`[SYSTEM] ${Xe}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${Xe}% of time used, still no edits. You MUST write code NOW. Use edit_file or write_file immediately \u2014 any further reading will be blocked.`};P.push(At),S.push(At)}}if(de&&C.includes(y.fnName)){let ee=et?`root cause already identified (${wt})`:Gt>=oe?`${Dt} consecutive reads without an edit`:`${zt} file edit(s) already made`;j(`${h.red} \u2716 Blocked read-only tool: cap fired, ${ee}${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:et?`BLOCKED: root cause already identified (${wt}). Use edit_file to fix the issue \u2014 do not read more files.`:It?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Gt>=oe?`BLOCKED: You have read ${Dt} files without making any edits. Stop investigating and either implement a fix with edit_file/write_file, or write your diagnosis as text output. Do not read more files.`:`BLOCKED: ${zt} file edit(s) already made and post-edit investigation cap reached. The fix is in place. Do not read more files \u2014 proceed with the task.`,tool_call_id:y.callId}}else if(Dt>=K&&!jt){if(jt=!0,j(`${h.yellow} \u26A0 Investigation cap: ${Dt} read-only calls without an edit \u2014 forcing implementation${h.reset}`),we&&Pe==="plan"){let ve=[...S].reverse().find(At=>At.role==="assistant"),mt=typeof ve?.content=="string"?ve.content:"",Xe=Ko("implement",mt);Xe&&(P.push(Xe),S.push(Xe),je=0,$t=as("implement"))}let ee;et?ee=`[SYSTEM] Root cause was already identified (${wt}). Edit the file now \u2014 do not read more files.`:vt?ee="[SYSTEM] SSH temporarily paused. Summarize your findings and state the likely diagnosis. Do NOT ask the user to run commands \u2014 SSH re-enables after your summary.":ee="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let _e={role:"user",content:ee};P.push(_e),S.push(_e)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let C=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),D=ls(Vc,C);if(D===uy){j(`${h.yellow} \u26A0 Loop warning: same bash command run ${D}\xD7 \u2014 possible debug loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same bash command ${D}\xD7. Debug loop detected \u2014 try a different approach.`};P.push(F),S.push(F)}else if(D>=dy){j(`${h.red} \u2716 Loop abort: same bash command run ${D}\xD7 \u2014 aborting runaway debug loop${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae,{suppressHint:!0}),Ce(P);return}}if(y.fnName==="ssh_exec"){Lt++;{let F=(nt[w]?.content??"").split(`
1363
- `).map(X=>X.trim()).find(X=>X.length>0&&!X.startsWith("**")&&(X.startsWith("EXIT")||/^[\w./-]+:\s/.test(X)||X.startsWith("bash:")||X.startsWith("sh:")))??"";if(F){if(F===Wi?us++:(Wi=F,us=1),us===3&&!vt){j(`${h.yellow} \u26A0 SSH repeated-error: "${F.slice(0,60)}" returned ${us}\xD7 \u2014 nudging to change approach${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] The last ${us} SSH commands all failed with the same error: "${F}". Retrying variants of the same command will not help. Switch to a different approach to accomplish the task (e.g. use a different tool, read a local file, or change the command syntax entirely).`};P.push(X),S.push(X)}}else Wi="",us=0}if(Lt>=Ry){j(`${h.red} \u2716 SSH storm abort: ${Lt} consecutive ssh_exec calls \u2014 aborting${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae,{suppressHint:!0}),Ce(P);return}else if(Lt===so){{let F=it(),{messages:X}=tn(S,F);S=X}vt=!0,Ni++,j(`${h.yellow} \u26A0 SSH storm warning (#${Ni}): ${Lt} consecutive ssh_exec calls \u2014 blocking further SSH${h.reset}`);let D={role:"user",content:et?`[SYSTEM WARNING] ${Lt} consecutive SSH calls. Root cause identified (${wt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Lt} consecutive SSH calls \u2014 SSH temporarily paused for synthesis. Summarize what you found and state the likely diagnosis. Do NOT ask the user to run commands or provide logs. SSH will be re-enabled after your summary so you can continue.`};P.push(D),S.push(D)}}else y.canExecute&&(Lt=0);if(y.fnName==="bash"&&y.canExecute){let F=(nt[w]?.content??"").split(`
1364
- `).map(X=>X.trim()).find(X=>X.length>0&&(X.startsWith("EXIT")||/^[\w./-]+:\s/.test(X)||X.startsWith("bash:")||X.startsWith("sh:")))??"";if(F){if(F===Hi?ds++:(Hi=F,ds=1),ds===3){j(`${h.yellow} \u26A0 Bash repeated-error: "${F.slice(0,60)}" returned ${ds}\xD7 \u2014 nudging to change approach${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] The last ${ds} bash commands all failed with the same error: "${F}". Retrying variants of the same command will not help. Switch to a completely different approach (e.g. use a different tool, change the command syntax, or use ssh_exec to run the command on the remote server instead).`};P.push(X),S.push(X)}}else Hi="",ds=0}if(y.fnName==="bash"&&y.canExecute&&!vc&&y.args?.command){let C=nt[w]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!C.startsWith("EXIT")&&!C.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(C)||C.includes("files changed")||C.includes("file changed")||C.includes("insertions(+)")||C.includes("create mode"))){vc=!0,zo=0,j(`${h.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${h.reset}`);let X={role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. Your changes are committed. Do NOT run further git status / git diff / git log calls \u2014 the commit is done. Write your final summary and stop. Running extra verification commands wastes tool calls and hurts session quality."};P.push(X),S.push(X)}}if(vc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(zo++,zo>2)){j(`${h.yellow} \u26A0 Post-commit git verification blocked (call ${zo})${h.reset}`);let D={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(zo-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};P.push(D),S.push(D)}if(M&&y.fnName==="grep"&&z&&!z.startsWith("(no matches)")){let C=z.split(`
1365
- `);for(let D of C){let F=D.indexOf(":");if(F>0){let X=D.substring(0,F);X.startsWith("/")&&!X.includes(" ")&&nr.add(X)}else D.startsWith("/")&&!D.includes(" ")&&nr.add(D.trim())}}{let C=["grep","search_files","glob","glob_files"].includes(y.fnName);if(C&&M&&z&&(z.startsWith("(no matches)")||z.trim()===""||/^No matches found/.test(z.trim())||/^\(0 results\)/.test(z.trim()))){if(no++,no===3){j(`${h.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${h.reset}`);let F={role:"user",content:"[SYSTEM NOTE] 3 consecutive local searches returned no results. The target files may be on a remote server. If you have an SSH profile configured for this project's server, use ssh_exec to search there (e.g. ssh_exec with grep). Do not keep searching locally if the code does not exist on this machine."};P.push(F),S.push(F)}}else C&&M&&z&&z.trim().length>0&&(no=0)}if(M&&y.fnName==="grep"&&y.args&&y.args.pattern){let C=`${y.args.pattern}|${y.args.path||""}`,D=ls(fy,C);if(D===hy){j(`${h.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${D}\xD7 \u2014 possible search loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${D}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};P.push(F),S.push(F)}else if(D>=py){j(`${h.red} \u2716 Loop abort: grep pattern run ${D}\xD7 \u2014 aborting runaway search loop${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae,{suppressHint:!0}),Ce(P);return}if(y.args.path){let F=ls(ea,y.args.path),X=nn(ms,y.args.path)>=1;if(F===(X?1:my)){let oe=y.args.path.split("/").slice(-2).join("/");j(`${h.yellow} \u26A0 Loop warning: "${oe}" grepped ${F}\xD7 with different patterns \u2014 context flood risk${h.reset}`);let de={role:"user",content:X?`[SYSTEM NOTE] "${y.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${y.args.path}" grepped ${F}\xD7 \u2014 use the search results already in context instead of searching again.`};P.push(de),S.push(de)}}}if(M&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(z&&!z.startsWith("(no matches)")){let X=z.split(`
1366
- `);for(let K of X)(K.startsWith("/")&&!K.includes(" ")||!K.includes(":")&&!K.startsWith("["))&&sr.add(K.trim())}let C=y.args.pattern||y.args.query||y.args.path||"",D=ls(gy,C);if(D===yy){j(`${h.yellow} \u26A0 Loop warning: glob pattern "${C.slice(0,40)}" run ${D}\xD7 \u2014 possible search loop${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${D}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};P.push(X),S.push(X)}else if(D>=wy){j(`${h.red} \u2716 Loop abort: glob pattern run ${D}\xD7 \u2014 aborting runaway search loop${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae,{suppressHint:!0}),Ce(P);return}let F=C.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(X=>X.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(X));for(let X of F){let K=X.toLowerCase();Di.has(K)||Di.set(K,new Set);let oe=Di.get(K);if(oe.add(C),oe.size===$y){j(`${h.red} \u2716 Glob core-term block: ${oe.size} different patterns all searching for "${K}" \u2014 search loop${h.reset}`);let de={role:"user",content:`[SYSTEM WARNING] You have searched for "${K}" using ${oe.size} different glob patterns. This is a search loop \u2014 the file you are looking for likely does not exist. Stop searching and work with the files you have already found, or ask the user for clarification.`};P.push(de),S.push(de)}else if(oe.size===_y){j(`${h.yellow} \u26A0 Glob core-term warning: ${oe.size} different patterns searching for "${K}"${h.reset}`);let de={role:"user",content:`[SYSTEM WARNING] ${oe.size} different glob patterns all target "${K}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};P.push(de),S.push(de)}}}let Q=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),U=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(Q)||/\/(health|status|ping|ready|alive)\b/.test(Q);if(M&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&U&&z.includes('"valid":true')){{let D=it();if(Yt(S,D).percentage>=60){let{messages:X,tokensRemoved:K}=tn(S,D);K>0&&(S=X,console.log(`${h.dim} [pre-stop-compress \u2014 ~${K} tokens freed before STOP injection, now ${Math.round(Yt(S,D).percentage)}%]${h.reset}`))}}let C={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};P.push(C),S.push(C),console.log(`${h.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${h.reset}`)}if(M&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&Q&&/\bsed\s+-[ie]\b|\btee\b|\bcp\b|\bmv\b|\bpatch\b|\bdd\b|>\s*\S|\becho\b.*>|\bcat\b.*>|\bprintf\b.*>|\bpython[23]?\b.*open\b.*['"'w]|\bnpm\b.*run\b|\byarn\b.*run\b/.test(Q)&&(ps++,j(`${h.dim} [bash write detected: _bashModifiedFiles=${ps}]${h.reset}`)),z.startsWith("BLOCKED:")){if(Nn++,Nn>=Jc){j(`${h.red} \u2716 Loop abort: ${Nn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae,{suppressHint:!0}),Ce(P);return}}else Nn=0;if(M)On=0,oa=!0;else if(On++,On===Sy){j(`${h.yellow} \u26A0 Loop warning: ${On} consecutive tool errors \u2014 possible stuck loop${h.reset}`);let C={role:"user",content:`[SYSTEM WARNING] ${On} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};P.push(C),S.push(C)}else if(On>=Ey){j(`${h.red} \u2716 Loop abort: ${On} consecutive errors \u2014 aborting stuck loop${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae,{suppressHint:!0}),Ce(P);return}if(M&&y.fnName==="read_file"&&y.args&&y.args.path){Y.add(y.args.path),ke.delete(y.args.path);let C=ls(ms,y.args.path);{let K=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,oe=y.args.line_start!=null?parseInt(y.args.line_end,10)||K+350:350;Rn.has(y.args.path)||Rn.set(y.args.path,[]),Rn.get(y.args.path).push([K,oe])}if(y._scrollWarn){let{sectionCount:K,path:oe}=y._scrollWarn,de={role:"user",content:`[SYSTEM WARNING] "${oe}" \u2014 you have now read ${K} different sections of this file. This is a file-scroll pattern. Stop reading sections and use grep_search to find the specific lines you need instead.`};P.push(de),S.push(de),j(`${h.yellow} \u26A0 Scroll warning: "${oe.split("/").slice(-2).join("/")}" \u2014 ${K} sections read \u2014 use grep instead${h.reset}`)}let D=y.args.path.split("/").slice(-2).join("/"),F=!y.args?.line_start&&!y.args?.line_end,X=we&&Pe==="plan";if(!X&&F&&C===by){{let oe=it();if(Yt(S,oe).percentage>=60){let{messages:ee}=tn(S,oe);S=ee}}j(`${h.yellow} \u26A0 Loop warning: "${D}" read unbounded ${C}\xD7 \u2014 use line_start/line_end${h.reset}`);let K={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${C}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};P.push(K),S.push(K)}else if(!X&&F&&C>=ky){j(`${h.red} \u2716 Loop abort: "${D}" read unbounded ${C}\xD7 \u2014 aborting runaway read loop${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae,{suppressHint:!0}),Ce(P);return}}if(y.fnName==="spawn_agents"){let C=(z.match(/\bStatus: done\b/g)||[]).length;if((z.match(/\bStatus: truncated\b/g)||[]).length>0&&C===0){if(Mn++,Mn===vy){j(`${h.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Mn}\xD7 in a row${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Mn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};P.push(F),S.push(F)}else if(Mn>=Ty){console.log(`${h.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Mn}\xD7 \u2014 aborting stuck swarm${h.reset}`),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae,{suppressHint:!0}),Ce(P);return}}else C>0&&(Mn=0)}}{let y=nt.reduce((z,T)=>z+(typeof T.content=="string"?T.content.length:0),0);if(y>2e5){let z=nt.map((T,M)=>({i:M,len:typeof T.content=="string"?T.content.length:0})).sort((T,M)=>M.len-T.len);for(let{i:T,len:M}of z){if(y<=2e5)break;let Q=y-2e5,U=Math.max(M-Q,500);U<M&&typeof nt[T].content=="string"&&(nt[T]={...nt[T],content:nt[T].content.substring(0,U)+`
1367
- ...(truncated ${M-U} chars \u2014 per-message budget)`},y-=M-U)}}}for(let w of nt)P.push(w),S.push(w);if(Mi(P,S),!et)for(let w=0;w<nt.length;w++){if(!ye[w]||ye[w].fnName!=="ssh_exec")continue;let y=nt[w];if(!y||typeof y.content!="string")continue;let z=Sc(y.content);if(z){et=!0,wt=z.slice(0,120),Dt=0,jt=!1,Gt=0,j(`${h.yellow} \u26A1 Root cause detected: ${wt} \u2014 fix phase (read budget: 3)${h.reset}`);let T={role:"user",content:`[SYSTEM] Root cause identified: ${wt}. Read only the file that needs fixing, then edit it. Do not read other files.`};P.push(T),S.push(T);break}}for(let w=0;w<nt.length;w++){let y=ye[w];if(!y)continue;let z=typeof nt[w]?.content=="string"?nt[w].content:"";if(y.fnName==="create_task"){let T=z.match(/Task #(\d+) created/),M=typeof y.args?.subject=="string"?y.args.subject:"";T&&M&&rr.set(T[1],M)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!z.startsWith("BLOCKED:")&&z.trim().length>0){let M=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),Q=M.split(/[._\-/]/).filter(U=>U.length>2);for(let[U,ie]of rr){if(ir.has(U))continue;let C=ie.toLowerCase().split(/\W+/).filter(F=>F.length>3);Q.filter(F=>C.some(X=>X.includes(F)||F.includes(X))).length>=1&&(ir.add(U),j(`${h.green} \u2714 Auto-matched task #${U} to ${M}: ${ie.slice(0,60)}${h.reset}`))}}}{let w=it();if(Yt(S,w).percentage>=78){let{messages:z,tokensRemoved:T}=tn(S,w);T>0&&(S=z,console.log(`${h.dim} [auto-compressed \u2014 ~${T} tokens freed, now ${Math.round(Yt(S,w).percentage)}%]${h.reset}`))}}if(er()&&!s.skillLoop&&(ye.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?fe=0:(fe===0&&(at=b.size),fe++),fe>=9&&O>=4&&b.size===at)){j(`${h.green} \u2713 Stagnation exit: ${fe} read-only iterations, no new file changes${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Stagnation detected: ${fe} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${h.reset}
1368
- `),c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae),Ce(P);break e}let lu=jv();if(lu){let w={role:"user",content:`[User note mid-run]: ${lu}`};P.push(w),S.push(w),console.log(`${h.cyan} \u270E Context added${h.reset}`)}}if(je>=$t){if(c&&(c.stop(),c=null),l(null),Oe(O,q,b,Y,Ae),Ce(P),Ai(P),we&&Pe==="plan"){let Ke=[...P].reverse().find(Ge=>Ge.role==="assistant"),lt=typeof Ke?.content=="string"?Ke.content:"",gn=Ko("implement",lt);if(gn){P.push(gn),S=[{role:"system",content:await Fc()},...P],$t=as("implement"),j(`${h.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${h.reset}`);continue e}}else if(we&&Pe==="verify"){j(`${h.yellow} \u26A0 Verify budget exhausted \u2014 completing session${h.reset}`);break e}let{getActiveProviderName:me}=ot();if(me()==="ollama"&&sa<tu){if(b.size===0&&!oa){console.log(`${h.yellow} \u26A0 Max iterations reached with no progress. Stopping.${h.reset}`);break e}sa++,$t=20,console.log(`${h.dim} \u2500\u2500 auto-extending (+20 turns, ext ${sa}/${tu}) \u2500\u2500${h.reset}`);continue e}if(console.log(`
1369
- ${h.yellow}\u26A0 Max iterations reached.${h.reset}`),await $g(" Continue for 20 more turns?")){$t=20;continue e}console.log(`${h.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${h.reset}`)}break e}await Qc()}Pg.exports={processInput:Qv,clearConversation:Wv,getConversationLength:Yv,getConversationMessages:Gv,setConversationMessages:zv,setAbortSignalGetter:_v,setMaxIterations:wv,invalidateSystemPromptCache:Nc,clearToolFilterCache:Tv,getCachedFilteredTools:Tg,buildSystemPrompt:Fc,splitSystemPrompt:Uv,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:qc,getProjectContextHash:Rg,buildUserContent:Eg,_detectImageURLs:kg,_downloadImageURL:xg,_grabClipboardImage:Sg,detectFrustration:vg,detectAndTruncateLoop:Cc,injectMidRunNote:Dv,resetSessionTracking:Mg}});var ot=Z(($1,jg)=>{var{OllamaProvider:eT}=gu(),{OpenAIProvider:tT}=$u(),{AnthropicProvider:nT}=Su(),{GeminiProvider:sT}=Ru(),{LocalProvider:oT}=Ou(),{checkBudget:rT}=Tr(),Hc={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},Uc=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Ig={};for(let[t,e]of Object.entries(Hc))for(let s of Object.values(e))Ig[s]=t;function Wc(t,e){let s=Ig[t];return s&&Hc[s][e]||t}var tt={},_t=null,Be=null,ar=[];function qt(){if(Object.keys(tt).length>0)return;to("ollama",new eT),to("openai",new tT),to("anthropic",new nT),to("gemini",new sT),to("local",new oT);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;tt[t]?(_t=t,Be=e||tt[t].defaultModel):(_t="ollama",Be="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(ar=s.split(",").map(n=>n.trim()).filter(Boolean))}function to(t,e){tt[t]=e}function iT(t){return qt(),tt[t]||null}function Yc(){return qt(),tt[_t]||null}function aT(){return qt(),_t}function lT(){return qt(),Be}function cT(){qt();let t=Yc();if(!t)return{id:Be,name:Be,provider:_t};let e=t.getModel(Be);return e?{...e,provider:_t}:{id:Be,name:Be,provider:_t}}function Gc(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(tt[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function uT(t){qt();let{provider:e,model:s}=Gc(t);if(e){let o=tt[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(_t=e,Be=s,Xi(),!0):!1}let n=Yc();if(n&&n.getModel(s))return Be=s,Xi(),!0;for(let[o,r]of Object.entries(tt))if(r.getModel(s))return _t=o,Be=s,Xi(),!0;return!1}function Xi(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Vl();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Qt();t()}catch{}}function dT(){qt();let t=new Set;for(let e of Object.values(tt))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function fT(){return qt(),Object.entries(tt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===_t&&s.id===Be}))}))}function hT(){qt();let t=[];for(let[e,s]of Object.entries(tt)){let n=s.isConfigured();for(let o of Object.values(s.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:n})}return t}function pT(t){ar=Array.isArray(t)?t:[]}function mT(){return[...ar]}function Lg(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function Dg(t){let e=[_t,...ar.filter(r=>r!==_t)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=tt[i];if(!a||!a.isConfigured())continue;o++;let l=rT(i);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let c=r>0,u=c?Wc(Be,i):Be;return c&&u!==Be&&process.stderr.write(` [fallback: ${i}:${u}]
1370
- `),await t(a,i,u)}catch(c){if(s=c,!Lg(c)||r>=e.length-1)throw c;if(i==="ollama"&&Uc.length>0){let u=isFallback?Wc(Be,i):Be;for(let d of Uc)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
1371
- `),await t(a,i,d)}catch(f){if(s=f,!Lg(f))throw f}}continue}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function gT(t,e,s={}){qt();let n=s.model,o=n?(()=>{let{model:i}=Gc(n);return i||n})():void 0,r=o!==n?{...s,model:o}:s;return Dg((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function yT(t,e,s={}){if(qt(),s.provider){let n=tt[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||Be,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return Dg(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function wT(){qt();let t=[];for(let[e,s]of Object.entries(tt))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function _T(){for(let t of Object.keys(tt))delete tt[t];_t=null,Be=null,ar=[]}jg.exports={registerProvider:to,getProvider:iT,getActiveProvider:Yc,getActiveProviderName:aT,getActiveModelId:lT,getActiveModel:cT,setActiveModel:uT,getModelNames:dT,parseModelSpec:Gc,listProviders:fT,listAllModels:hT,callStream:gT,callChat:yT,getConfiguredProviders:wT,setFallbackChain:pT,getFallbackChain:mT,resolveModelForProvider:Wc,MODEL_EQUIVALENTS:Hc,OLLAMA_FALLBACK_MODELS:Uc,_reset:_T}});var gi=Z((k1,ry)=>{var{callStream:$T,getActiveProviderName:Ji,getActiveModelId:qg,getConfiguredProviders:bT,getProvider:Fg,getActiveProvider:Bg,parseModelSpec:Ug}=ot(),{parseToolArgs:Wg}=Mr(),{filterToolsForModel:kT,getModelTier:Vi}=_o(),{getModelBriefing:xT}=Ti(),{trackUsage:Hg,estimateTokens:Yg}=Tr(),{MultiProgress:ST,C:b1}=Je();function Gg(t){return!t||typeof t!="string"?0:typeof Yg=="function"?Yg(t):Math.ceil(t.length/4)}var Xg=15,ET=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),zg=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Vg=8,vT=2,Zi=new Map,Jg=600*1e3;function TT(t,e){let s=Zi.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Jg?!1:(Zi.set(t,{agentId:e,timestamp:Date.now()}),!0)}function lr(t){Zi.delete(t)}function zc(){Zi.clear()}function Kc(t){let e=(t.message||"").toLowerCase(),s=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":s==="ECONNRESET"||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function Zg(t){let e=Kc(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Qg(t,e,s){let n;for(let o=0;o<=zg;o++)try{return await $T(t,e,s)}catch(r){n=r;let i=Kc(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(o<zg&&Zg(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(c=>setTimeout(c,l).unref());continue}throw r}throw n}var Kg=new Set(["ask_user","task_list"]);function ey(t){return t>=2?new Set([...Kg,"spawn_agents"]):Kg}var RT=new Set(["write_file","edit_file","patch_file"]),ty={explore:{allowedTools:new Set(["bash","read_file","list_directory","glob","grep","search_files","web_fetch","web_search"]),systemSuffix:"You are an exploration agent. Read and search code only. Do NOT modify any files."},review:{allowedTools:new Set(["read_file","list_directory","glob","grep","search_files"]),systemSuffix:"You are a code review agent. Read code and report findings. Do NOT make changes."},implement:{allowedTools:null,systemSuffix:""}},CT=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,AT=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ny(t){return AT.test(t)?"full":CT.test(t)?"essential":t.length>300?"full":"standard"}function sy(t){let e=bT(),s=Ji(),n=[...e].sort((o,r)=>(o.name===s?-1:1)-(r.name===s?-1:1));for(let o of n)for(let r of o.models)if(Vi(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var OT={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Qi(t){if(t.model){let{provider:o,model:r}=Ug(t.model),i=o?Fg(o):Bg(),a=o||Ji();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=Vi(r,a);return{provider:a,model:r,tier:l}}}let e=ny(t.task),s=OT[e];if(s){let{provider:o,model:r}=Ug(s),i=o?Fg(o):Bg(),a=o||Ji();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=Vi(r,a);return{provider:a,model:r,tier:l}}}let n=sy(e);if(n){let o=Vi(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function oy(t,e={},s=0){let n=s===0?Xg:Vg,o=Math.min(t.max_iterations||10,n),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},l=new Set,c=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
1397
+ `),ks=null}if(!lo.skipSummaries){let w=l0.filter((T,O)=>!(we[O]&&we[O].fnName==="ask_user"));for(let T of w)console.log(T);let y=we.filter(T=>T&&T.fnName!=="ask_user").map(T=>T.fnName),G=Iy.record(0,y,J,_);G&&uT(G)}for(let w of we){if(w.canExecute||!w.errorResult)continue;let y=typeof w.errorResult.content=="string"?w.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:")||y.startsWith("PLAN PHASE:"))&&(Dn++,Dn>=fu)){j(`${h.red} \u2716 Loop abort: ${Dn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe,{suppressHint:!0}),Ae(P);return}}for(let w=0;w<we.length;w++){let y=we[w];if(!y.canExecute)continue;let G=it[w].content,T=G.split(`
1398
+ `)[0],O=!T.startsWith("ERROR")&&!T.startsWith("CANCELLED")&&!T.startsWith("Command failed")&&!T.startsWith("EXIT");if(!O&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&T.includes("old_text not found")){let R=Dt.get(y.args.path)||0;Dt.set(y.args.path,R+1)}if(!O&&y.fnName==="bash"&&ur.size>0){let R=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(R))for(let[F]of ur)Dt.has(F)||(Dt.set(F,1),j(`${h.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${F.split("/").pop()}"${h.reset}`))}if(!O&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(T)){if(Pn++,Pn>=2){j(`${h.yellow} \u26A0 File-not-found streak: ${Pn} consecutive misses \u2014 forcing search${h.reset}`);let R={role:"user",content:`[SYSTEM] ${Pn} consecutive "File not found" errors. STOP guessing paths. Use search_files or glob_files to locate the correct file first, then read/edit the path returned by the search.`};P.push(R),S.push(R)}}else O&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(Pn=0);if(O&&y.fnName==="write_file"&&y.args?.path){let R=y.args.path.split("/").pop(),q=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(R)&&!q){j(`${h.yellow} \u26A0 Temp file: "${R}" \u2014 delete with bash rm when done to keep the workspace clean${h.reset}`);let X={role:"user",content:`[HINT] "${y.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${y.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};P.push(X),S.push(X)}}if(O&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Dt.delete(y.args.path),_.add(y.args.path);for(let F of $s)!F.done&&y.args.path.endsWith(F.file.split("/").pop())&&(F.done=!0,j(`${h.green} \u2713 TODO done: ${F.file}${h.reset}`));let R=hs(jy,y.args.path),q=y.args.path.split("/").slice(-2).join("/");if(R===Dy){j(`${h.yellow} \u26A0 Loop warning: "${q}" edited ${R}\xD7 \u2014 possible edit loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${R}\xD7. One more edit max, then move on.`};P.push(F),S.push(F)}else if(R>=qy){j(`${h.red} \u2716 Loop abort: "${q}" edited ${R}\xD7 \u2014 aborting to prevent runaway loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe,{suppressHint:!0}),Ae(P);return}}if(O&&y.canExecute&&$e&&(In=0),O&&y.canExecute&&!($e&&Me==="plan")){let R=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){Bt=0,Ut=!1,Jt=0,Zt++;let Q=y.args?.path||y.args?.file_path;Q&&(qc(bn,Q,1),Ln.delete(Q),de.add(Q))}else if(R.includes(y.fnName)&&(Bt++,Ut&&Jt++,$e&&Me==="implement"&&y.fnName==="read_file"&&$s.length>0)){let Q=y.args?.path||y.args?.file_path||"",_e=$s.find(Te=>!Te.done&&Q.endsWith(Te.file.split("/").pop()));if(_e){let Te={role:"user",content:`[TODO OBSERVER] You already analyzed "${_e.file}" in the plan phase. Action: ${_e.action}
1399
+ Do NOT re-read \u2014 apply the edit directly with edit_file.`};P.push(Te),S.push(Te),j(`${h.yellow} \u26A0 TODO nudge: ${_e.file} \u2014 already analyzed, edit directly${h.reset}`)}}$e&&Me==="verify"&&dr++;let F=n.postEditCap,X=$e&&Me==="implement"?Math.min(pu,10):pu,K=ot?8:Ft?Zt>0?6:10:Zt>0?F:X,re=6,he=!$e&&Ut&&(ot&&Jt>=re||Ft&&Zt>=3&&Jt>=re||Jt>=re);if(Zo<2&&!Ut&&Bt>=3&&_.size===0){let Q=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,_e=Date.now()-Oe,Te=Zo===0?.4:.65;if(Q>0&&_e>Q*Te){Zo++;let wt=Math.round(_e/6e4),Qe=Math.round(_e/Q*100);j(`${h.yellow} \u26A0 Time nudge #${Zo}: ${wt}m elapsed (${Qe}%), ${Bt} reads, 0 edits${h.reset}`);let Pt={role:"user",content:Zo===1?`[SYSTEM] ${Qe}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${Qe}% of time used, still no edits. You MUST write code NOW. Use edit_file or write_file immediately \u2014 any further reading will be blocked.`};P.push(Pt),S.push(Pt)}}if(he&&R.includes(y.fnName)){let Q=ot?`root cause already identified (${bt})`:Jt>=re?`${Bt} consecutive reads without an edit`:`${Zt} file edit(s) already made`;j(`${h.red} \u2716 Blocked read-only tool: cap fired, ${Q}${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:ot?`BLOCKED: root cause already identified (${bt}). Use edit_file to fix the issue \u2014 do not read more files.`:Ft?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Jt>=re?`BLOCKED: You have read ${Bt} files without making any edits. Stop investigating and either implement a fix with edit_file/write_file, or write your diagnosis as text output. Do not read more files.`:`BLOCKED: ${Zt} file edit(s) already made and post-edit investigation cap reached. The fix is in place. Do not read more files \u2014 proceed with the task.`,tool_call_id:y.callId}}else if(Bt>=K&&!Ut){if(Ut=!0,j(`${h.yellow} \u26A0 Investigation cap: ${Bt} read-only calls without an edit \u2014 forcing implementation${h.reset}`),$e&&Me==="plan"){let Te=[...S].reverse().find(Pt=>Pt.role==="assistant"),wt=typeof Te?.content=="string"?Te.content:"",Qe=await er("implement",wt);Qe&&(P.push(Qe),S.push(Qe),Ue=0,xt=ps("implement"))}let Q;ot?Q=`[SYSTEM] Root cause was already identified (${bt}). Edit the file now \u2014 do not read more files.`:At?Q="[SYSTEM] SSH temporarily paused. Summarize your findings and state the likely diagnosis. Do NOT ask the user to run commands \u2014 SSH re-enables after your summary.":Q="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let _e={role:"user",content:Q};P.push(_e),S.push(_e)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let R=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),q=hs(du,R);if(q===Fy){j(`${h.yellow} \u26A0 Loop warning: same bash command run ${q}\xD7 \u2014 possible debug loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same bash command ${q}\xD7. Debug loop detected \u2014 try a different approach.`};P.push(F),S.push(F)}else if(q>=By){j(`${h.red} \u2716 Loop abort: same bash command run ${q}\xD7 \u2014 aborting runaway debug loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe,{suppressHint:!0}),Ae(P);return}}if(y.fnName==="ssh_exec"){qt++;{let F=(it[w]?.content??"").split(`
1400
+ `).map(X=>X.trim()).find(X=>X.length>0&&!X.startsWith("**")&&(X.startsWith("EXIT")||/^[\w./-]+:\s/.test(X)||X.startsWith("bash:")||X.startsWith("sh:")))??"";if(F){if(F===Zi?gs++:(Zi=F,gs=1),gs===3&&!At){j(`${h.yellow} \u26A0 SSH repeated-error: "${F.slice(0,60)}" returned ${gs}\xD7 \u2014 nudging to change approach${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] The last ${gs} SSH commands all failed with the same error: "${F}". Retrying variants of the same command will not help. Switch to a different approach to accomplish the task (e.g. use a different tool, read a local file, or change the command syntax entirely).`};P.push(X),S.push(X)}}else Zi="",gs=0}if(qt>=o0){j(`${h.red} \u2716 SSH storm abort: ${qt} consecutive ssh_exec calls \u2014 aborting${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe,{suppressHint:!0}),Ae(P);return}else if(qt===io){{let F=ut(),{messages:X}=an(S,F);S=X}At=!0,Bi++,j(`${h.yellow} \u26A0 SSH storm warning (#${Bi}): ${qt} consecutive ssh_exec calls \u2014 blocking further SSH${h.reset}`);let q={role:"user",content:ot?`[SYSTEM WARNING] ${qt} consecutive SSH calls. Root cause identified (${bt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${qt} consecutive SSH calls \u2014 SSH temporarily paused for synthesis. Summarize what you found and state the likely diagnosis. Do NOT ask the user to run commands or provide logs. SSH will be re-enabled after your summary so you can continue.`};P.push(q),S.push(q)}}else y.canExecute&&(qt=0);if(y.fnName==="bash"&&y.canExecute){let F=(it[w]?.content??"").split(`
1401
+ `).map(X=>X.trim()).find(X=>X.length>0&&(X.startsWith("EXIT")||/^[\w./-]+:\s/.test(X)||X.startsWith("bash:")||X.startsWith("sh:")))??"";if(F){if(F===Qi?ys++:(Qi=F,ys=1),ys===3){j(`${h.yellow} \u26A0 Bash repeated-error: "${F.slice(0,60)}" returned ${ys}\xD7 \u2014 nudging to change approach${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] The last ${ys} bash commands all failed with the same error: "${F}". Retrying variants of the same command will not help. Switch to a completely different approach (e.g. use a different tool, change the command syntax, or use ssh_exec to run the command on the remote server instead).`};P.push(X),S.push(X)}}else Qi="",ys=0}if(y.fnName==="bash"&&y.canExecute&&!Fc&&y.args?.command){let R=it[w]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!R.startsWith("EXIT")&&!R.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(R)||R.includes("files changed")||R.includes("file changed")||R.includes("insertions(+)")||R.includes("create mode"))){Fc=!0,Qo=0,j(`${h.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${h.reset}`);let X={role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. Your changes are committed. Do NOT run further git status / git diff / git log calls \u2014 the commit is done. Write your final summary and stop. Running extra verification commands wastes tool calls and hurts session quality."};P.push(X),S.push(X)}}if(Fc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(Qo++,Qo>2)){j(`${h.yellow} \u26A0 Post-commit git verification blocked (call ${Qo})${h.reset}`);let q={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(Qo-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};P.push(q),S.push(q)}if(O&&y.fnName==="grep"&&G&&!G.startsWith("(no matches)")){let R=G.split(`
1402
+ `);for(let q of R){let F=q.indexOf(":");if(F>0){let X=q.substring(0,F);X.startsWith("/")&&!X.includes(" ")&&lr.add(X)}else q.startsWith("/")&&!q.includes(" ")&&lr.add(q.trim())}}{let R=["grep","search_files","glob","glob_files"].includes(y.fnName);if(R&&O&&G&&(G.startsWith("(no matches)")||G.trim()===""||/^No matches found/.test(G.trim())||/^\(0 results\)/.test(G.trim()))){if(ro++,ro===3){j(`${h.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${h.reset}`);let F={role:"user",content:"[SYSTEM NOTE] 3 consecutive local searches returned no results. The target files may be on a remote server. If you have an SSH profile configured for this project's server, use ssh_exec to search there (e.g. ssh_exec with grep). Do not keep searching locally if the code does not exist on this machine."};P.push(F),S.push(F)}}else R&&O&&G&&G.trim().length>0&&(ro=0)}if(O&&y.fnName==="grep"&&y.args&&y.args.pattern){let R=`${y.args.pattern}|${y.args.path||""}`,q=hs(Uy,R);if(q===Wy){j(`${h.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};P.push(F),S.push(F)}else if(q>=Hy){j(`${h.red} \u2716 Loop abort: grep pattern run ${q}\xD7 \u2014 aborting runaway search loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe,{suppressHint:!0}),Ae(P);return}if(y.args.path){let F=hs(ca,y.args.path),X=ln(_s,y.args.path)>=1;if(F===(X?1:Yy)){let re=y.args.path.split("/").slice(-2).join("/");j(`${h.yellow} \u26A0 Loop warning: "${re}" grepped ${F}\xD7 with different patterns \u2014 context flood risk${h.reset}`);let he={role:"user",content:X?`[SYSTEM NOTE] "${y.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${y.args.path}" grepped ${F}\xD7 \u2014 use the search results already in context instead of searching again.`};P.push(he),S.push(he)}}}if(O&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(G&&!G.startsWith("(no matches)")){let X=G.split(`
1403
+ `);for(let K of X)(K.startsWith("/")&&!K.includes(" ")||!K.includes(":")&&!K.startsWith("["))&&cr.add(K.trim())}let R=y.args.pattern||y.args.query||y.args.path||"",q=hs(Gy,R);if(q===zy){j(`${h.yellow} \u26A0 Loop warning: glob pattern "${R.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};P.push(X),S.push(X)}else if(q>=Ky){j(`${h.red} \u2716 Loop abort: glob pattern run ${q}\xD7 \u2014 aborting runaway search loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe,{suppressHint:!0}),Ae(P);return}let F=R.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(X=>X.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(X));for(let X of F){let K=X.toLowerCase();Gi.has(K)||Gi.set(K,new Set);let re=Gi.get(K);if(re.add(R),re.size===Vy){j(`${h.red} \u2716 Glob core-term block: ${re.size} different patterns all searching for "${K}" \u2014 search loop${h.reset}`);let he={role:"user",content:`[SYSTEM WARNING] You have searched for "${K}" using ${re.size} different glob patterns. This is a search loop \u2014 the file you are looking for likely does not exist. Stop searching and work with the files you have already found, or ask the user for clarification.`};P.push(he),S.push(he)}else if(re.size===Xy){j(`${h.yellow} \u26A0 Glob core-term warning: ${re.size} different patterns searching for "${K}"${h.reset}`);let he={role:"user",content:`[SYSTEM WARNING] ${re.size} different glob patterns all target "${K}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};P.push(he),S.push(he)}}}let Z=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),B=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(Z)||/\/(health|status|ping|ready|alive)\b/.test(Z);if(O&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&B&&G.includes('"valid":true')){{let q=ut();if(Vt(S,q).percentage>=60){let{messages:X,tokensRemoved:K}=an(S,q);K>0&&(S=X,console.log(`${h.dim} [pre-stop-compress \u2014 ~${K} tokens freed before STOP injection, now ${Math.round(Vt(S,q).percentage)}%]${h.reset}`))}}let R={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};P.push(R),S.push(R),console.log(`${h.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${h.reset}`)}if(O&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&Z&&/\bsed\s+-[ie]\b|\btee\b|\bcp\b|\bmv\b|\bpatch\b|\bdd\b|>\s*\S|\becho\b.*>|\bcat\b.*>|\bprintf\b.*>|\bpython[23]?\b.*open\b.*['"'w]|\bnpm\b.*run\b|\byarn\b.*run\b/.test(Z)&&(xn++,j(`${h.dim} [bash write detected: _bashModifiedFiles=${xn}]${h.reset}`)),G.startsWith("BLOCKED:")){if(Dn++,Dn>=fu){j(`${h.red} \u2716 Loop abort: ${Dn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe,{suppressHint:!0}),Ae(P);return}}else Dn=0;if(O)jn=0,pa=!0;else if(jn++,jn===e0){j(`${h.yellow} \u26A0 Loop warning: ${jn} consecutive tool errors \u2014 possible stuck loop${h.reset}`);let R={role:"user",content:`[SYSTEM WARNING] ${jn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};P.push(R),S.push(R)}else if(jn>=t0){j(`${h.red} \u2716 Loop abort: ${jn} consecutive errors \u2014 aborting stuck loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe,{suppressHint:!0}),Ae(P);return}if(O&&y.fnName==="read_file"&&y.args&&y.args.path){J.add(y.args.path),de.delete(y.args.path);let R=hs(_s,y.args.path);{let K=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,re=y.args.line_start!=null?parseInt(y.args.line_end,10)||K+350:350;Ln.has(y.args.path)||Ln.set(y.args.path,[]),Ln.get(y.args.path).push([K,re])}if(y._scrollWarn){let{sectionCount:K,path:re}=y._scrollWarn,he={role:"user",content:`[SYSTEM WARNING] "${re}" \u2014 you have now read ${K} different sections of this file. This is a file-scroll pattern. Stop reading sections and use grep_search to find the specific lines you need instead.`};P.push(he),S.push(he),j(`${h.yellow} \u26A0 Scroll warning: "${re.split("/").slice(-2).join("/")}" \u2014 ${K} sections read \u2014 use grep instead${h.reset}`)}let q=y.args.path.split("/").slice(-2).join("/"),F=!y.args?.line_start&&!y.args?.line_end,X=$e&&Me==="plan";if(!X&&F&&R===Jy){{let re=ut();if(Vt(S,re).percentage>=60){let{messages:Q}=an(S,re);S=Q}}j(`${h.yellow} \u26A0 Loop warning: "${q}" read unbounded ${R}\xD7 \u2014 use line_start/line_end${h.reset}`);let K={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${R}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};P.push(K),S.push(K)}else if(!X&&F&&R>=Zy){j(`${h.red} \u2716 Loop abort: "${q}" read unbounded ${R}\xD7 \u2014 aborting runaway read loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe,{suppressHint:!0}),Ae(P);return}}if(y.fnName==="spawn_agents"){let R=(G.match(/\bStatus: done\b/g)||[]).length;if((G.match(/\bStatus: truncated\b/g)||[]).length>0&&R===0){if(qn++,qn===n0){j(`${h.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${qn}\xD7 in a row${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${qn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};P.push(F),S.push(F)}else if(qn>=s0){console.log(`${h.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${qn}\xD7 \u2014 aborting stuck swarm${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe,{suppressHint:!0}),Ae(P);return}}else R>0&&(qn=0)}}{let y=it.reduce((G,T)=>G+(typeof T.content=="string"?T.content.length:0),0);if(y>2e5){let G=it.map((T,O)=>({i:O,len:typeof T.content=="string"?T.content.length:0})).sort((T,O)=>O.len-T.len);for(let{i:T,len:O}of G){if(y<=2e5)break;let Z=y-2e5,B=Math.max(O-Z,500);B<O&&typeof it[T].content=="string"&&(it[T]={...it[T],content:it[T].content.substring(0,B)+`
1404
+ ...(truncated ${O-B} chars \u2014 per-message budget)`},y-=O-B)}}}for(let w of it)P.push(w),S.push(w);if(Ui(P,S),!ot)for(let w=0;w<it.length;w++){if(!we[w]||we[w].fnName!=="ssh_exec")continue;let y=it[w];if(!y||typeof y.content!="string")continue;let G=Dc(y.content);if(G){ot=!0,bt=G.slice(0,120),Bt=0,Ut=!1,Jt=0,j(`${h.yellow} \u26A1 Root cause detected: ${bt} \u2014 fix phase (read budget: 3)${h.reset}`);let T={role:"user",content:`[SYSTEM] Root cause identified: ${bt}. Read only the file that needs fixing, then edit it. Do not read other files.`};P.push(T),S.push(T);break}}for(let w=0;w<it.length;w++){let y=we[w];if(!y)continue;let G=typeof it[w]?.content=="string"?it[w].content:"";if(y.fnName==="create_task"){let T=G.match(/Task #(\d+) created/),O=typeof y.args?.subject=="string"?y.args.subject:"";T&&O&&fr.set(T[1],O)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!G.startsWith("BLOCKED:")&&G.trim().length>0){let O=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),Z=O.split(/[._\-/]/).filter(B=>B.length>2);for(let[B,oe]of fr){if(pr.has(B))continue;let R=oe.toLowerCase().split(/\W+/).filter(F=>F.length>3);Z.filter(F=>R.some(X=>X.includes(F)||F.includes(X))).length>=1&&(pr.add(B),j(`${h.green} \u2714 Auto-matched task #${B} to ${O}: ${oe.slice(0,60)}${h.reset}`))}}}{let w=ut();if(Vt(S,w).percentage>=78){let{messages:G,tokensRemoved:T}=an(S,w);T>0&&(S=G,console.log(`${h.dim} [auto-compressed \u2014 ~${T} tokens freed, now ${Math.round(Vt(S,w).percentage)}%]${h.reset}`))}}if(ir()&&!s.skillLoop&&(we.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?fe=0:(fe===0&&(Je=_.size),fe++),fe>=9&&N>=4&&_.size===Je)){j(`${h.green} \u2713 Stagnation exit: ${fe} read-only iterations, no new file changes${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Stagnation detected: ${fe} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${h.reset}
1405
+ `),c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe),Ae(P);break e}let xu=IT();if(xu){let w={role:"user",content:`[User note mid-run]: ${xu}`};P.push(w),S.push(w),console.log(`${h.cyan} \u270E Context added${h.reset}`)}}if(Ue>=xt){if(c&&(c.stop(),c=null),l(null),Ne(N,L,_,J,Oe),Ae(P),qi(P),$e&&Me==="plan"){let Ze=[...P].reverse().find(Xe=>Xe.role==="assistant"),dt=typeof Ze?.content=="string"?Ze.content:"",Sn=await er("implement",dt);if(Sn){P.push(Sn),S=[{role:"system",content:await eu()},...P],xt=ps("implement"),j(`${h.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${h.reset}`);continue e}}else if($e&&Me==="verify"){j(`${h.yellow} \u26A0 Verify budget exhausted \u2014 completing session${h.reset}`);break e}let{getActiveProviderName:ge}=lt();if(ge()==="ollama"&&fa<gu){if(_.size===0&&!pa){console.log(`${h.yellow} \u26A0 Max iterations reached with no progress. Stopping.${h.reset}`);break e}fa++,xt=20,console.log(`${h.dim} \u2500\u2500 auto-extending (+20 turns, ext ${fa}/${gu}) \u2500\u2500${h.reset}`);continue e}if(console.log(`
1406
+ ${h.yellow}\u26A0 Max iterations reached.${h.reset}`),await zg(" Continue for 20 more turns?")){xt=20;continue e}console.log(`${h.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${h.reset}`)}break e}await hu()}uy.exports={processInput:eR,clearConversation:HT,getConversationLength:GT,getConversationMessages:zT,setConversationMessages:KT,setAbortSignalGetter:yT,setMaxIterations:gT,invalidateSystemPromptCache:Gc,clearToolFilterCache:ET,getCachedFilteredTools:ey,buildSystemPrompt:eu,splitSystemPrompt:WT,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Qc,getProjectContextHash:ty,_inferVerificationCommands:ly,_inferRelevantTests:nu,_inferSymbolTargets:iy,_buildSymbolHintBlock:ay,buildUserContent:Zg,_detectImageURLs:Xg,_downloadImageURL:Vg,_grabClipboardImage:Jg,detectFrustration:Qg,detectAndTruncateLoop:Wc,injectMidRunNote:LT,resetSessionTracking:cy}});var lt=V((_C,hy)=>{var{OllamaProvider:tR}=Ou(),{OpenAIProvider:nR}=Lu(),{AnthropicProvider:sR}=qu(),{GeminiProvider:oR}=Wu(),{LocalProvider:rR}=Gu(),{checkBudget:iR}=Pr(),ru={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},su=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),fy={};for(let[t,e]of Object.entries(ru))for(let s of Object.values(e))fy[s]=t;function ou(t,e){let s=fy[t];return s&&ru[s][e]||t}var rt={},kt=null,Ge=null,hr=[];function Wt(){if(Object.keys(rt).length>0)return;oo("ollama",new tR),oo("openai",new nR),oo("anthropic",new sR),oo("gemini",new oR),oo("local",new rR);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;rt[t]?(kt=t,Ge=e||rt[t].defaultModel):(kt="ollama",Ge="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(hr=s.split(",").map(n=>n.trim()).filter(Boolean))}function oo(t,e){rt[t]=e}function aR(t){return Wt(),rt[t]||null}function iu(){return Wt(),rt[kt]||null}function lR(){return Wt(),kt}function cR(){return Wt(),Ge}function uR(){Wt();let t=iu();if(!t)return{id:Ge,name:Ge,provider:kt};let e=t.getModel(Ge);return e?{...e,provider:kt}:{id:Ge,name:Ge,provider:kt}}function au(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(rt[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function dR(t){Wt();let{provider:e,model:s}=au(t);if(e){let o=rt[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(kt=e,Ge=s,oa(),!0):!1}let n=iu();if(n&&n.getModel(s))return Ge=s,oa(),!0;for(let[o,r]of Object.entries(rt))if(r.getModel(s))return kt=o,Ge=s,oa(),!0;return!1}function oa(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=uc();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=on();t()}catch{}}function fR(){Wt();let t=new Set;for(let e of Object.values(rt))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function pR(){return Wt(),Object.entries(rt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===kt&&s.id===Ge}))}))}function hR(){Wt();let t=[];for(let[e,s]of Object.entries(rt)){let n=s.isConfigured();for(let o of Object.values(s.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:n})}return t}function mR(t){hr=Array.isArray(t)?t:[]}function gR(){return[...hr]}function dy(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function py(t){let e=[kt,...hr.filter(r=>r!==kt)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=rt[i];if(!a||!a.isConfigured())continue;o++;let l=iR(i);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let c=r>0,u=c?ou(Ge,i):Ge;return c&&u!==Ge&&process.stderr.write(` [fallback: ${i}:${u}]
1407
+ `),await t(a,i,u)}catch(c){if(s=c,!dy(c)||r>=e.length-1)throw c;if(i==="ollama"&&su.length>0){let u=isFallback?ou(Ge,i):Ge;for(let d of su)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
1408
+ `),await t(a,i,d)}catch(f){if(s=f,!dy(f))throw f}}continue}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function yR(t,e,s={}){Wt();let n=s.model,o=n?(()=>{let{model:i}=au(n);return i||n})():void 0,r=o!==n?{...s,model:o}:s;return py((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function wR(t,e,s={}){if(Wt(),s.provider){let n=rt[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||Ge,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return py(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function $R(){Wt();let t=[];for(let[e,s]of Object.entries(rt))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function _R(){for(let t of Object.keys(rt))delete rt[t];kt=null,Ge=null,hr=[]}hy.exports={registerProvider:oo,getProvider:aR,getActiveProvider:iu,getActiveProviderName:lR,getActiveModelId:cR,getActiveModel:uR,setActiveModel:dR,getModelNames:fR,parseModelSpec:au,listProviders:pR,listAllModels:hR,callStream:yR,callChat:wR,getConfiguredProviders:$R,setFallbackChain:mR,getFallbackChain:gR,resolveModelForProvider:ou,MODEL_EQUIVALENTS:ru,OLLAMA_FALLBACK_MODELS:su,_reset:_R}});var Si=V((kC,Ly)=>{var{callStream:bR,getActiveProviderName:ia,getActiveModelId:my,getConfiguredProviders:kR,getProvider:gy,getActiveProvider:yy,parseModelSpec:wy}=lt(),{parseToolArgs:$y}=Fr(),{filterToolsForModel:xR,getModelTier:ra}=xo(),{getModelBriefing:SR}=Ii(),{trackUsage:_y,estimateTokens:by}=Pr(),{MultiProgress:ER,C:bC}=tt();function ky(t){return!t||typeof t!="string"?0:typeof by=="function"?by(t):Math.ceil(t.length/4)}var Ey=15,vR=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),xy=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),vy=8,TR=2,aa=new Map,Ty=600*1e3;function RR(t,e){let s=aa.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Ty?!1:(aa.set(t,{agentId:e,timestamp:Date.now()}),!0)}function mr(t){aa.delete(t)}function lu(){aa.clear()}function cu(t){let e=(t.message||"").toLowerCase(),s=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":s==="ECONNRESET"||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function Ry(t){let e=cu(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Cy(t,e,s){let n;for(let o=0;o<=xy;o++)try{return await bR(t,e,s)}catch(r){n=r;let i=cu(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(o<xy&&Ry(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(c=>setTimeout(c,l).unref());continue}throw r}throw n}var Sy=new Set(["ask_user","task_list"]);function Ay(t){return t>=2?new Set([...Sy,"spawn_agents"]):Sy}var CR=new Set(["write_file","edit_file","patch_file"]),Oy={explore:{allowedTools:new Set(["bash","read_file","list_directory","glob","grep","search_files","web_fetch","web_search"]),systemSuffix:"You are an exploration agent. Read and search code only. Do NOT modify any files."},review:{allowedTools:new Set(["read_file","list_directory","glob","grep","search_files"]),systemSuffix:'You are a code review agent. Read code and report findings only. Do NOT make changes. Output findings first, ordered by severity, using this format: "Finding: <title> | Severity: <high|medium|low> | File: <path[:line]> | Why: <impact>". After findings, add one short "Residual risk:" line. If there are no findings, say "No material findings" and still mention the main residual risk/test gap.'},implement:{allowedTools:null,systemSuffix:""}},AR=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,OR=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Ny(t){return OR.test(t)?"full":AR.test(t)?"essential":t.length>300?"full":"standard"}function My(t){let e=kR(),s=ia(),n=[...e].sort((o,r)=>(o.name===s?-1:1)-(r.name===s?-1:1));for(let o of n)for(let r of o.models)if(ra(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var NR={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function la(t){if(t.model){let{provider:o,model:r}=wy(t.model),i=o?gy(o):yy(),a=o||ia();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=ra(r,a);return{provider:a,model:r,tier:l}}}let e=Ny(t.task),s=NR[e];if(s){let{provider:o,model:r}=wy(s),i=o?gy(o):yy(),a=o||ia();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=ra(r,a);return{provider:a,model:r,tier:l}}}let n=My(e);if(n){let o=ra(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function Py(t,e={},s=0){let n=s===0?Ey:vy,o=Math.min(t.max_iterations||10,n),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},l=new Set,c=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
1372
1409
 
1373
1410
  TASK: ${t.task}
1374
1411
  ${t.context?`
@@ -1381,28 +1418,32 @@ RULES:
1381
1418
  - When done, respond with a clear summary of what you did and the result.
1382
1419
  - Do not ask questions \u2014 make reasonable decisions.
1383
1420
  - Use relative paths when possible.
1421
+ - You are not alone in the codebase. Do NOT revert or overwrite work that may belong to another agent.
1422
+ - Treat any files mentioned in your context/scope as your ownership boundary. Stay inside it unless you are only reading for context.
1384
1423
 
1385
1424
  TOOL STRATEGY:
1386
1425
  - Use read_file to read files (not bash cat). Use edit_file/patch_file to modify (not bash sed).
1387
1426
  - Use glob to find files by name. Use grep to search contents. Only use bash for shell operations.
1388
1427
  - ALWAYS read a file with read_file before editing it. edit_file old_text must match exactly.
1428
+ - Prefer symbol-first retrieval: identify the owning file/function, then read the exact section you need.
1429
+ - After making a change, verify with the smallest relevant check before doing more exploration.
1389
1430
 
1390
1431
  ERROR RECOVERY:
1391
1432
  - If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
1392
1433
  - If bash fails: read the error, fix the root cause, then retry.
1393
- - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&ty[t.type],f=d&&d.systemSuffix?`
1434
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Oy[t.type],f=d&&d.systemSuffix?`
1394
1435
 
1395
- ${d.systemSuffix}`:"",p=Qi(t),m=p.provider,g=p.model,_=p.tier,k=xT(g||qg()),L=[{role:"system",content:(k?`## Model Briefing
1436
+ ${d.systemSuffix}`:"",p=la(t),m=p.provider,g=p.model,$=p.tier,k=SR(g||my()),D=[{role:"system",content:(k?`## Model Briefing
1396
1437
  ${k}
1397
1438
 
1398
1439
  ---
1399
1440
 
1400
- `:"")+u+f}];L.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:E,executeTool:v}=po(),N=ey(s),te=kT(E.filter(le=>!N.has(le.function.name)),_);if(d&&d.allowedTools&&(te=te.filter(le=>d.allowedTools.has(le.function.name))),g&&!t._skipLog){let le=_?` (${_})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${le}]
1401
- `)}let V={};m&&(V.provider=m),g&&(V.model=g);let re=new Set;try{for(let ne=0;ne<o;ne++){let S=await Qg(L,te,V);if(!S||typeof S!="object")throw new Error("Empty or invalid response from provider");{let be=m||Ji(),$e=g||qg();if(S.usage){let $=S.usage.prompt_tokens||0,I=S.usage.completion_tokens||0;a.input+=$,a.output+=I,Hg(be,$e,$,I)}else{let $=S.content||"",I=L.map(q=>typeof q.content=="string"?q.content:Array.isArray(q.content)?q.content.map(b=>typeof b=="string"?b:b.text||"").join(""):"").join(" "),H=Gg(I),O=Gg($);a.input+=H,a.output+=O,a._estimated=!0,Hg(be,$e,H,O)}}let Ee=S.content||"",W=S.tool_calls,J={role:"assistant",content:Ee||""};if(W&&W.length>0&&(J.tool_calls=W),L.push(J),!W||W.length===0){for(let be of l)lr(be);return{task:t.task,status:"done",result:Ee||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let he=new Set,Re=W.map(be=>{let $e=be.function.name,$=Wg(be.function.arguments),I=be.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!$)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${$e}`,tool_call_id:I});if(["edit_file","patch_file"].includes($e)&&$.path){if(re.has($.path)||he.has($.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${$.path}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:I});he.add($.path)}let H=null;if(RT.has($e)&&$.path){let q=require("path"),b=q.isAbsolute($.path)?$.path:q.resolve(process.cwd(),$.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let Y=q.relative(process.cwd(),b);if(t._readOnlyFiles.some(fe=>Y===fe||Y.startsWith(fe+"/")||b===fe||b.startsWith(fe+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${$.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:I})}if(l.has(b)||!TT(b,r))return Promise.resolve({role:"tool",content:`ERROR: File '${$.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:I});l.add(b),H=b}return i.push($e),e.onUpdate&&e.onUpdate({type:"tool_call",tool:$e,agentId:r}),($e==="spawn_agents"?Xc($,s+1):v($e,$,{autoConfirm:!0,silent:!0})).then(q=>{H&&(lr(H),l.delete(H));let b=String(q??"");return $&&$.path&&(["edit_file","patch_file","write_file"].includes($e)&&b.startsWith("Edited:")?re.add($.path):$e==="read_file"&&!b.startsWith("ERROR")&&re.delete($.path)),{role:"tool",content:b.length>2e4?b.substring(0,2e4)+`
1402
- ...(truncated)`:b,tool_call_id:I}}).catch(q=>(H&&(lr(H),l.delete(H)),{role:"tool",content:`ERROR: ${q.message}`,tool_call_id:I}))}),Ue=await Promise.all(Re);if(L.push(...Ue),ne>=7&&L.length>12)try{let{compressMessage:be}=Qt(),$e=L.length-6;for(let $=1;$<$e;$++)L[$]._subAgentCompressed||(L[$]={...be(L[$],"light"),_subAgentCompressed:!0})}catch{}for(let be=0;be<W.length;be++){let $e=W[be];if($e.function.name==="bash_exec"){let $=Wg($e.function.arguments);if((Ue[be]?.content||"").startsWith("ERROR")&&$&&$.command){let H=$.command.replace(/\s+/g," ").trim().slice(0,100);c.set(H,(c.get(H)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${ne+1}/${o}`)}for(let ne of l)lr(ne);let le=[...c.entries()].filter(([,ne])=>ne>=3).sort((ne,S)=>S[1]-ne[1]).slice(0,3).map(([ne,S])=>`"${ne}" (failed ${S}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:le,result:L[L.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(le){for(let ne of l)lr(ne);return{task:t.task,status:"failed",result:`Error: ${le.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function Xc(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let s=e===0?ET:vT,n=e===0?Xg:Vg,o=(t.agents||[]).slice(0,s);if(o.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=o.map(u=>Qi(u)),l=o.map((u,d)=>{let f=a[d],p=f.model?` [${f.model}]`:"",m=u.task.substring(0,i-p.length);return`${r}Agent ${d+1}${p}: ${m}${u.task.length>m.length?"...":""}`}),c=new ST(l);c.start();try{let u=o.map((g,_)=>{let k=a[_],A=Math.min(g.max_iterations||n,n),L=k.model?{...g,model:`${k.provider}:${k.model}`,_skipLog:!0,max_iterations:A}:{...g,_skipLog:!0,max_iterations:A};return oy(L,{onUpdate:()=>{}},e).then(E=>(c.update(_,E.status==="failed"?"error":"done"),E)).catch(E=>(c.update(_,"error"),{task:g.task,status:"failed",result:`Error: ${E.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),zc();let f=["Sub-agent results:",""],p=0,m=0;for(let g=0;g<d.length;g++){let _=d[g],k=_.status==="done"?"\u2713":_.status==="truncated"?"\u26A0":"\u2717",A=_.modelSpec?` [${_.modelSpec}]`:"";f.push(`${k} Agent ${g+1}${A}: ${_.task}`),f.push(` Status: ${_.status}`),f.push(` Tools used: ${_.toolsUsed.length>0?_.toolsUsed.join(", "):"none"}`),f.push(` Result: ${_.result}`),_.repeatedFailures&&_.repeatedFailures.length>0&&f.push(` Repeated failures: ${_.repeatedFailures.join("; ")}`),f.push(""),p+=_.tokensUsed.input,m+=_.tokensUsed.output}return f.push(`Total sub-agent tokens: ${p} input + ${m} output`),f.join(`
1403
- `)}catch(u){return c.stop(),zc(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function NT(t){let{createJob:e}=zs(),s=(t.agents||[]).filter(i=>i.background),n=(t.agents||[]).filter(i=>!i.background),o=s.map(i=>{let a=Qi(i),l=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(l)}),r=[];if(o.length>0&&r.push(`Background agents started: [${o.join(", ")}]
1441
+ `:"")+u+f}];D.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:v,executeTool:E}=yo(),A=Ay(s),ee=xR(v.filter(ae=>!A.has(ae.function.name)),$);if(d&&d.allowedTools&&(ee=ee.filter(ae=>d.allowedTools.has(ae.function.name))),g&&!t._skipLog){let ae=$?` (${$})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${ae}]
1442
+ `)}let se={};m&&(se.provider=m),g&&(se.model=g);let ue=new Set;try{for(let te=0;te<o;te++){let S=await Cy(D,ee,se);if(!S||typeof S!="object")throw new Error("Empty or invalid response from provider");{let ke=m||ia(),be=g||my();if(S.usage){let b=S.usage.prompt_tokens||0,I=S.usage.completion_tokens||0;a.input+=b,a.output+=I,_y(ke,be,b,I)}else{let b=S.content||"",I=D.map(L=>typeof L.content=="string"?L.content:Array.isArray(L.content)?L.content.map(_=>typeof _=="string"?_:_.text||"").join(""):"").join(" "),H=ky(I),N=ky(b);a.input+=H,a.output+=N,a._estimated=!0,_y(ke,be,H,N)}}let ve=S.content||"",W=S.tool_calls,z={role:"assistant",content:ve||""};if(W&&W.length>0&&(z.tool_calls=W),D.push(z),!W||W.length===0){for(let ke of l)mr(ke);return{task:t.task,status:"done",result:ve||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let me=new Set,Ce=W.map(ke=>{let be=ke.function.name,b=$y(ke.function.arguments),I=ke.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!b)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${be}`,tool_call_id:I});if(["edit_file","patch_file"].includes(be)&&b.path){if(ue.has(b.path)||me.has(b.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${b.path}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:I});me.add(b.path)}let H=null;if(CR.has(be)&&b.path){let L=require("path"),_=L.isAbsolute(b.path)?b.path:L.resolve(process.cwd(),b.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let J=L.relative(process.cwd(),_);if(t._readOnlyFiles.some(fe=>J===fe||J.startsWith(fe+"/")||_===fe||_.startsWith(fe+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${b.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:I})}if(l.has(_)||!RR(_,r))return Promise.resolve({role:"tool",content:`ERROR: File '${b.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:I});l.add(_),H=_}return i.push(be),e.onUpdate&&e.onUpdate({type:"tool_call",tool:be,agentId:r}),(be==="spawn_agents"?uu(b,s+1):E(be,b,{autoConfirm:!0,silent:!0})).then(L=>{H&&(mr(H),l.delete(H));let _=String(L??"");return b&&b.path&&(["edit_file","patch_file","write_file"].includes(be)&&_.startsWith("Edited:")?ue.add(b.path):be==="read_file"&&!_.startsWith("ERROR")&&ue.delete(b.path)),{role:"tool",content:_.length>2e4?_.substring(0,2e4)+`
1443
+ ...(truncated)`:_,tool_call_id:I}}).catch(L=>(H&&(mr(H),l.delete(H)),{role:"tool",content:`ERROR: ${L.message}`,tool_call_id:I}))}),De=await Promise.all(Ce);if(D.push(...De),te>=7&&D.length>12)try{let{compressMessage:ke}=on(),be=D.length-6;for(let b=1;b<be;b++)D[b]._subAgentCompressed||(D[b]={...ke(D[b],"light"),_subAgentCompressed:!0})}catch{}for(let ke=0;ke<W.length;ke++){let be=W[ke];if(be.function.name==="bash_exec"){let b=$y(be.function.arguments);if((De[ke]?.content||"").startsWith("ERROR")&&b&&b.command){let H=b.command.replace(/\s+/g," ").trim().slice(0,100);c.set(H,(c.get(H)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${te+1}/${o}`)}for(let te of l)mr(te);let ae=[...c.entries()].filter(([,te])=>te>=3).sort((te,S)=>S[1]-te[1]).slice(0,3).map(([te,S])=>`"${te}" (failed ${S}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ae,result:D[D.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(ae){for(let te of l)mr(te);return{task:t.task,status:"failed",result:`Error: ${ae.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function uu(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let s=e===0?vR:TR,n=e===0?Ey:vy,o=(t.agents||[]).slice(0,s);if(o.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=o.map(u=>la(u)),l=o.map((u,d)=>{let f=a[d],p=f.model?` [${f.model}]`:"",m=u.task.substring(0,i-p.length);return`${r}Agent ${d+1}${p}: ${m}${u.task.length>m.length?"...":""}`}),c=new ER(l);c.start();try{let u=o.map((g,$)=>{let k=a[$],M=Math.min(g.max_iterations||n,n),D=k.model?{...g,model:`${k.provider}:${k.model}`,_skipLog:!0,max_iterations:M}:{...g,_skipLog:!0,max_iterations:M};return Py(D,{onUpdate:()=>{}},e).then(v=>(c.update($,v.status==="failed"?"error":"done"),v)).catch(v=>(c.update($,"error"),{task:g.task,status:"failed",result:`Error: ${v.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),lu();let f=["Sub-agent results:",""],p=0,m=0;for(let g=0;g<d.length;g++){let $=d[g],k=$.status==="done"?"\u2713":$.status==="truncated"?"\u26A0":"\u2717",M=$.modelSpec?` [${$.modelSpec}]`:"";f.push(`${k} Agent ${g+1}${M}: ${$.task}`),f.push(` Status: ${$.status}`),f.push(` Tools used: ${$.toolsUsed.length>0?$.toolsUsed.join(", "):"none"}`),f.push(` Result: ${$.result}`),$.repeatedFailures&&$.repeatedFailures.length>0&&f.push(` Repeated failures: ${$.repeatedFailures.join("; ")}`),f.push(""),p+=$.tokensUsed.input,m+=$.tokensUsed.output}return f.push(`Total sub-agent tokens: ${p} input + ${m} output`),f.join(`
1444
+ `)}catch(u){return c.stop(),lu(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function MR(t){let{createJob:e}=Vs(),s=(t.agents||[]).filter(i=>i.background),n=(t.agents||[]).filter(i=>!i.background),o=s.map(i=>{let a=la(i),l=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(l)}),r=[];if(o.length>0&&r.push(`Background agents started: [${o.join(", ")}]
1404
1445
  `+s.map((i,a)=>` ${o[a]}: ${i.task}`).join(`
1405
1446
  `)+`
1406
- Results will be injected into the conversation when each agent completes.`),n.length>0){let i=await Xc({agents:n});r.push(i)}return r.join(`
1447
+ Results will be injected into the conversation when each agent completes.`),n.length>0){let i=await uu({agents:n});r.push(i)}return r.join(`
1407
1448
 
1408
- `)||"No agents specified."}ry.exports={runSubAgent:oy,executeSpawnAgents:Xc,executeSpawnAgentsBackground:NT,clearAllLocks:zc,classifyTask:ny,pickModelForTier:sy,resolveSubAgentModel:Qi,classifyError:Kc,isRetryableError:Zg,callWithRetry:Qg,getExcludedTools:ey,LOCK_TIMEOUT_MS:Jg,SUB_AGENT_TYPES:ty}});var{runSubAgent:MT}=gi();process.on("message",async({jobId:t,agentDef:e})=>{try{let s=await MT({...e,_skipLog:!0},{onUpdate:()=>{}},0);process.send({type:"result",jobId:t,payload:s})}catch(s){process.send({type:"error",jobId:t,error:s.message})}finally{process.exit(0)}});
1449
+ `)||"No agents specified."}Ly.exports={runSubAgent:Py,executeSpawnAgents:uu,executeSpawnAgentsBackground:MR,clearAllLocks:lu,classifyTask:Ny,pickModelForTier:My,resolveSubAgentModel:la,classifyError:cu,isRetryableError:Ry,callWithRetry:Cy,getExcludedTools:Ay,LOCK_TIMEOUT_MS:Ty,SUB_AGENT_TYPES:Oy}});var{runSubAgent:PR}=Si();process.on("message",async({jobId:t,agentDef:e})=>{try{let s=await PR({...e,_skipLog:!0},{onUpdate:()=>{}},0);process.send({type:"result",jobId:t,payload:s})}catch(s){process.send({type:"error",jobId:t,error:s.message})}finally{process.exit(0)}});