nex-code 0.5.13 → 0.5.14

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,147 +1,155 @@
1
- var Ia=Object.defineProperty;var j0=Object.getOwnPropertyDescriptor;var D0=Object.getOwnPropertyNames;var q0=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),B0=(t,e)=>{for(var s in e)Ia(t,s,{get:e[s],enumerable:!0})},U0=(t,e,s,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of D0(e))!q0.call(t,n)&&n!==s&&Ia(t,n,{get:()=>e[n],enumerable:!(o=j0(e,n))||o.enumerable});return t};var W0=t=>U0(Ia({},"__esModule",{value:!0}),t);var As=V((C1,Hu)=>{async function H0(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 o=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)}),n=JSON.parse(o);return e(n)||o||t.message}catch{return t.message}}var ja=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,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,o={}){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`)}};Hu.exports={BaseProvider:ja,readStreamErrorBody:H0}});var Ms=V((A1,Yu)=>{var Os=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")}},Ns=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 o of s){let n=this.parseLine(o);if(n?.done)return n}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")}},Pr=class extends Ns{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let o=s.slice(6);if(o==="[DONE]")return{done:!0,result:this.getResult()};let n;try{n=JSON.parse(o)}catch{return{done:!1}}let r=n.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}}))}}},Lr=class extends Os{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:s,tools:o,maxTokens:n,temperature:r,stream:i}){let a={model:e,messages:s,max_tokens:n,temperature:r};return i&&(a.stream=!0),o&&o.length>0&&(a.tools=o),a}normalizeResponse(e){let s=e.choices?.[0]?.message||{},o=(s.tool_calls||[]).map(n=>({id:n.id,function:{name:n.function.name,arguments:n.function.arguments}}));return{content:s.content||"",tool_calls:o}}createStreamParser(e,s={}){return new Pr(e,s)}},Ir=class extends Ns{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 o=s.slice(6),n;try{n=JSON.parse(o)}catch{return{done:!1}}switch(n.type){case"content_block_start":{let r=n.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=n.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}}})}}},Da="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",jr=class extends Os{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:o,maxTokens:n,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,max_tokens:n,temperature:r};if(i&&(l.stream=!0),a?.system){let u=a.system,c=u.indexOf(Da);if(c!==-1){let d=u.slice(0,c).trimEnd(),f=u.slice(c+Da.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=u}return o&&o.length>0&&(l.tools=o),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="",o=[];for(let n of e.content||[])n.type==="text"?s+=n.text:n.type==="tool_use"&&o.push({id:n.id,function:{name:n.name,arguments:n.input}});return{content:s,tool_calls:o}}createStreamParser(e,s={}){return new Ir(e,s)}};function Gu(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 Dr=class extends Ns{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:Gu(e.function?.arguments??e.arguments)}}))}}},qr=class extends Os{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:o,maxTokens:n,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,stream:i,options:{temperature:r,num_predict:n,repeat_penalty:a?.repeat_penalty??1.05}};return o&&o.length>0&&(l.tools=o),l}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:(s.tool_calls||[]).map((o,n)=>({id:o.id||`ollama-${Date.now()}-${n}`,function:{name:o.function?.name||o.name||"unknown",arguments:Gu(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,s={}){return new Dr(e,s)}},G0=new Lr,Y0=new jr,z0=new qr;Yu.exports={ANTHROPIC_CACHE_BOUNDARY:Da,WireProtocol:Os,StreamParser:Ns,OpenAICompatibleProtocol:Lr,AnthropicProtocol:jr,OllamaChatProtocol:qr,OpenAIStreamParser:Pr,AnthropicStreamParser:Ir,OllamaStreamParser:Dr,openaiProtocol:G0,anthropicProtocol:Y0,ollamaProtocol:z0}});var Xu=V((O1,Ku)=>{var Fr=require("axios"),K0=require("http"),X0=require("https"),{BaseProvider:V0,readStreamErrorBody:J0}=As(),{ollamaProtocol:Bn}=Ms(),Br=new K0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Ur=new X0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),zu={"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}},qa=class extends V0{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||zu,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){Fr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Br,httpsAgent:Ur}).then(e=>{let s=e.data?.models||[];for(let o of s){let n=(o.name||o.model||"").replace(/:latest$/,"");!n||this.models[n]||(this.models[n]={id:n,name:o.name||n,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Fr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Br,httpsAgent:Ur})).data?.models||[];for(let o of s){let n=(o.name||o.model||"").replace(/:latest$/,"");!n||this.models[n]||(this.models[n]={id:n,name:o.name||n,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 o=[],n=[];for(let i of s.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&n.push(i.data);let r={role:s.role,content:o.join(`
3
- `)};return n.length>0&&(r.images=n),s.tool_call_id&&(r.tool_call_id=s.tool_call_id),r}return s})}async chat(e,s,o={}){await this.discoverModels();let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,a=Bn.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),l;try{l=await Fr.post(`${this.baseUrl}${Bn.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Br,httpsAgent:Ur})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let c=u.response?.status?` [HTTP ${u.response.status}]`:"",d=u.response?.data?.error||u.message;throw new Error(`API Error${c}: ${d}`)}return Bn.normalizeResponse(l.data)}async stream(e,s,o={}){await this.discoverModels();let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),u=Bn.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),c;try{c=await Fr.post(`${this.baseUrl}${Bn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:Br,httpsAgent:Ur})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await J0(f,$=>$?.error),g=new Error(`API Error${h}: ${m}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=Bn.createStreamParser(a,{onThinkingToken:l});return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{c.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),c.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),c.data.on("error",m=>{if(o.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,h(g)}),c.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Bn.normalizeResponse(e)}};Ku.exports={OllamaProvider:qa,OLLAMA_MODELS:zu}});var Qu=V((N1,Zu)=>{var Vu=require("axios"),{BaseProvider:Z0,readStreamErrorBody:Q0}=As(),{openaiProtocol:Un}=Ms(),Ju={"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}},Fa=class extends Z0{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Ju,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 o of e){if(this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let n=this._getMessageCacheKey(o);if(this._messageStringCache.has(n)){let i=this._messageStringCache.get(n);this._messageFormatCache.set(o,i),s.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(n,r),this._messageFormatCache.set(o,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_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(n=>n.type==="text").map(n=>n.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 o of e.content)if(o.type==="text")s.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let n=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;s.push({type:"image_url",image_url:{url:n,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),l=Un.buildRequestBody({model:n,messages:a,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await Vu.post(`${this.baseUrl}${Un.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let d=c.response?.status?` [HTTP ${c.response.status}]`:"",f=c.response?.data?.error?.message||c.response?.data?.error||c.message;throw new Error(`API Error${d}: ${f}`)}return Un.normalizeResponse(u.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u=Un.buildRequestBody({model:n,messages:l,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),c;try{c=await Vu.post(`${this.baseUrl}${Un.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await Q0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=Un.createStreamParser(a);return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{c.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),c.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),c.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),c.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Un.normalizeResponse(e)}};Zu.exports={OpenAIProvider:Fa,OPENAI_MODELS:Ju}});var sd=V((M1,nd)=>{var ed=require("axios"),{BaseProvider:ew,readStreamErrorBody:tw}=As(),{anthropicProtocol:Tn}=Ms(),td={"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}},nw="2023-06-01",Ba=class extends ew{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||td,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||nw}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="",o=[];for(let n of e){if(n.role==="system"){s+=(s?`
5
-
6
- `:"")+n.content;continue}if(n.role!=="system"&&n.role!=="tool"&&this._messageFormatCache.has(n)){o.push(this._messageFormatCache.get(n));continue}let r=this._formatSingleMessage(n,o);if(r){if(n.role!=="system"&&n.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(n);this._messageStringCache.set(i,r),this._messageFormatCache.set(n,r)}o.push(r)}}for(let n=o.length-1;n>0;n--)o[n].role==="user"&&o[n-1].role==="user"&&o.splice(n,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let n of e.tool_calls)o.push({type:"tool_use",id:n.id||`toolu-${Date.now()}`,name:n.function.name,input:typeof n.function.arguments=="string"?JSON.parse(n.function.arguments||"{}"):n.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=s[s.length-1],n;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}});n=i}else n=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:n};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let o=[];for(let n of e.content)n.type==="text"?o.push({type:"text",text:n.text??""}):n.type==="image"&&n.data&&o.push({type:"image",source:{type:"base64",media_type:n.media_type||"image/png",data:n.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return Tn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this._resolveModelId(n),i=this.getModel(n),a=o.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),c=this.formatTools(s),d=Tn.buildRequestBody({model:r,messages:l,tools:c,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:u}}),f;try{f=await ed.post(`${this.baseUrl}${Tn.getEndpoint()}`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let m=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${m}: ${g}`)}return Tn.normalizeResponse(f.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this._resolveModelId(n),i=this.getModel(n),a=o.maxTokens||i?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:u,system:c}=this.formatMessages(e),d=this.formatTools(s),f=Tn.buildRequestBody({model:r,messages:u,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:c}}),h;try{h=await ed.post(`${this.baseUrl}${Tn.getEndpoint()}`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.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 tw(g,v=>v?.error?.message||v?.error);throw new Error(`API Error${$}: ${k}`)}let m=Tn.createStreamParser(l);return new Promise((g,$)=>{o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),$(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{let{done:v,result:A}=m.feed(k.toString());v&&g(A)}),h.data.on("error",k=>{o.signal?.aborted||$(new Error(`Stream error: ${k.message}`))}),h.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return Tn.normalizeResponse(e)}};nd.exports={AnthropicProvider:Ba,ANTHROPIC_MODELS:td}});var ad=V((P1,id)=>{var od=require("axios"),{BaseProvider:sw,readStreamErrorBody:ow}=As(),{openaiProtocol:Wn}=Ms(),rd={"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}},Ua=class extends sw{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||rd,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 o of e){if(this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let n=this._getMessageCacheKey(o);if(this._messageStringCache.has(n)){let i=this._messageStringCache.get(n);this._messageFormatCache.set(o,i),s.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(n,r),this._messageFormatCache.set(o,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_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 o of e.content)if(o.type==="text")s.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let n=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;s.push({type:"image_url",image_url:{url:n,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),l=Wn.buildRequestBody({model:n,messages:a,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await od.post(`${this.baseUrl}${Wn.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let d=c.response?.status?` [HTTP ${c.response.status}]`:"",f=c.response?.data?.error?.message||c.response?.data?.error||c.message;throw new Error(`API Error${d}: ${f}`)}return Wn.normalizeResponse(u.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||8192,a=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u=Wn.buildRequestBody({model:n,messages:l,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),c;try{c=await od.post(`${this.baseUrl}${Wn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await ow(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=Wn.createStreamParser(a);return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{c.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),c.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),c.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),c.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Wn.normalizeResponse(e)}};id.exports={GeminiProvider:Ua,GEMINI_MODELS:rd}});var ud=V((L1,cd)=>{var Wr=require("axios"),{BaseProvider:rw,readStreamErrorBody:iw}=As(),{ollamaProtocol:Hn}=Ms(),ld="http://localhost:11434",Wa=class extends rw{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||ld,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 Wr.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of s){let n=o.name||o.model;if(!n)continue;let r=n.replace(/:latest$/,""),i=32768;try{let a=await Wr.post(`${this.baseUrl}/api/show`,{name:n},{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:o.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 o=[],n=[];for(let i of s.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&n.push(i.data);let r={role:"user",content:o.join(`
7
- `)};return n.length>0&&(r.images=n),r}return s})}async chat(e,s,o={}){this._modelsLoaded||await this.loadModels();let n=o.model||this.defaultModel;if(!n)throw new Error("No local model available. Is Ollama running?");let r=Hn.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await Wr.post(`${this.baseUrl}${Hn.getEndpoint()}`,r,{timeout:o.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}]`:"",u=a.response?.data?.error||a.message;throw new Error(`API Error${l}: ${u}`)}return Hn.normalizeResponse(i.data)}async stream(e,s,o={}){this._modelsLoaded||await this.loadModels();let n=o.model||this.defaultModel;if(!n)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i=Hn.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await Wr.post(`${this.baseUrl}${Hn.getEndpoint()}`,i,{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let c=u.response?.status?` [HTTP ${u.response.status}]`:"",d=await iw(u,f=>f?.error);throw new Error(`API Error${c}: ${d}`)}let l=Hn.createStreamParser(r);return new Promise((u,c)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),c(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:h}=l.feed(d.toString());f&&u(h)}),a.data.on("error",d=>{o.signal?.aborted||c(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{u(l.flush())})})}normalizeResponse(e){return Hn.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}};cd.exports={LocalProvider:Wa,DEFAULT_LOCAL_URL:ld}});var Gt=V((I1,yd)=>{"use strict";var dd="\x1B[0m",fd="\x1B[1m",Ps="\x1B[2m";function Y(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function aw(){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
- `),n=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(n){let r=parseInt(n[1].slice(0,2),16),i=parseInt(n[2].slice(0,2),16),a=parseInt(n[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function hd(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function lw(t){try{let s=require("fs").readFileSync(hd(),"utf8"),o=JSON.parse(s);if(o&&typeof o[t]=="boolean")return o[t]}catch(e){console.error("readThemeCache failed:",e.message)}return null}function cw(t,e){try{let s=require("fs"),o=require("path"),n=hd(),r=o.dirname(n),i={};try{i=JSON.parse(s.readFileSync(n,"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(n,JSON.stringify(i),"utf8")}catch{}}function uw(){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",o=lw(s);if(o!==null)return o;let n=aw(),r=n!==null?n:!0;return cw(s,r),r}var pd=uw(),md={reset:dd,bold:fd,dim:Ps,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:Ps,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:Ps,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:Ps,banner_model:Ps,banner_yolo:Y(245,175,50),banner_gemini:Y(138,180,248),footer_sep:Ps,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)},gd={reset:dd,bold:fd,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)},dw=pd?md:gd;yd.exports={T:dw,isDark:pd,DARK:md,LIGHT:gd}});var Gn=V((j1,$d)=>{"use strict";var Et=require("fs"),wd=require("path");function fw(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function hw(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function pw(t,e){let s=wd.dirname(t),o=wd.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{Et.existsSync(s)||Et.mkdirSync(s,{recursive:!0,mode:448}),Et.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Et.renameSync(o,t)}catch(n){try{Et.unlinkSync(o)}catch{}throw n}}function mw(t,e,{timeout:s=5e3,retryMs:o=50}={}){let n=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=Et.openSync(n,"wx"),Et.writeSync(i,Buffer.from(String(process.pid))),Et.closeSync(i),i=-1;try{return e()}finally{try{Et.unlinkSync(n)}catch{}}}catch(a){if(i!==-1)try{Et.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=Et.readFileSync(n,"utf-8").trim(),u=parseInt(l,10);if(!fw(u)){try{Et.unlinkSync(n)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Et.unlinkSync(n)}catch{}return e()}hw(o)}}}$d.exports={atomicWrite:pw,withFileLockSync:mw}});var Gr=V((D1,Td)=>{var Ls=require("fs"),Ha=require("path"),{T:bd}=Gt(),{atomicWrite:gw,withFileLockSync:yw}=Gn(),_d={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:{}},Hr=[],Rn={};function ww(t,e,s,o,n=0){if(Hr.push({provider:t,model:e,input:s,output:o,cacheRead:n}),Rn[t]!==void 0){let r=vd(t);r.allowed||process.stderr.write(`${bd.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${bd.reset}
9
- `)}}function Ga(t,e){let s=_d[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function kd(t){let e=Ga(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function xd(){let t={};for(let i of Hr){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:kd(i)})),s=e.reduce((i,a)=>i+a.cost,0),o=e.reduce((i,a)=>i+a.input,0),n=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:s,totalInput:o,totalOutput:n,totalCacheRead:r,breakdown:e}}function $w(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:o}=xd();if(o.length===0)return"No token usage recorded this session.";let n=[];n.push("Session Token Usage:"),n.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";n.push(` ${r.provider}:${r.model}`),n.push(` Input: ${r.input.toLocaleString()} tokens`),n.push(` Output: ${r.output.toLocaleString()} tokens`),n.push(` Cost: ${i}`)}return n.push(""),n.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),n.join(`
10
- `)}function bw(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function _w(t,e,s,o){let n=Ga(t,e),r=(s*n.input+o*n.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function kw(){Hr=[]}function xw(t,e){Rn[t]=e}function Sw(t){delete Rn[t]}function vw(){return{...Rn}}function Sd(t){let e=0;for(let s of Hr)s.provider===t&&(e+=kd(s));return e}function vd(t){let e=Sd(t),s=Rn[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let o=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:o}}function Ed(){let t=Ha.join(process.cwd(),".nex","config.json");if(Ls.existsSync(t))try{let e=JSON.parse(Ls.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Rn={...e.costLimits})}catch{}}function Ew(){let t=Ha.join(process.cwd(),".nex"),e=Ha.join(t,"config.json");Ls.existsSync(t)||Ls.mkdirSync(t,{recursive:!0}),yw(e,()=>{let s={};if(Ls.existsSync(e))try{s=JSON.parse(Ls.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Rn,gw(e,JSON.stringify(s,null,2))})}function Tw(){Rn={}}Ed();Td.exports={PRICING:_d,trackUsage:ww,getSessionCosts:xd,formatCosts:$w,formatCostHint:_w,resetCosts:kw,getPricing:Ga,setCostLimit:xw,removeCostLimit:Sw,getCostLimits:vw,getProviderSpend:Sd,checkBudget:vd,loadCostLimits:Ed,saveCostLimits:Ew,resetCostLimits:Tw,estimateTokens:bw}});var Ya=V((q1,Rw)=>{Rw.exports={name:"nex-code",version:"0.5.13",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 Yn=V((F1,Ad)=>{var{T:J}=Gt(),Kr=5,Is=(()=>{let t=[];for(let e=0;e<Kr;e++)t.push(e);for(let e=Kr-2;e>=1;e--)t.push(e);return t})(),Rd=["\u273D","\u2726","\u2727","\u2726"];function Cd(t=""){let e=String(t).toLowerCase();return e.includes("search")||e.includes("read")||e.includes("list")||e.includes("inspect")?{glyph:"\u25CC",color:J.cyan,accent:"scan"}:e.includes("write")||e.includes("edit")||e.includes("patch")||e.includes("build")?{glyph:"\u2726",color:J.yellow,accent:"shape"}:e.includes("test")||e.includes("diff")||e.includes("check")||e.includes("verify")?{glyph:"\u25A3",color:J.green,accent:"verify"}:e.includes("wait")||e.includes("github")||e.includes("fetch")||e.includes("browser")?{glyph:"\u25CD",color:J.blue,accent:"wait"}:{glyph:"\u25CF",color:J.cyan,accent:"think"}}var za=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Is[this.frame%Is.length],s=Cd(this.text),o="";for(let r=0;r<Kr;r++)o+=r===e?`${s.color}${s.glyph}${J.reset}`:" ";let n="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);if(r>=60){let i=Math.floor(r/60),a=r%60;n=` ${J.dim}${i}m ${String(a).padStart(2,"0")}s${J.reset}`}else r>=1&&(n=` ${J.dim}${r}s${J.reset}`)}process.stderr.write(`\x1B[2K\r${s.color}${s.accent.toUpperCase()}${J.reset} ${o} ${J.dim}${this.text}${J.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),o=e%60;return s>0?`${s}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let e=Is[this.frame%Is.length],s=`${J.cyan}\u25CC${J.reset}`,o=this._formatElapsed(),n=o?` ${J.dim}${o}${J.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let l,u;switch(this.statuses[a]){case"done":l=`${J.green}\u2713${J.reset}`,u=J.dim;break;case"error":l=`${J.red}\u2717${J.reset}`,u=J.dim;break;case"retry":l=`${J.yellow}\u21BB${J.reset}`,u=J.yellow;break;default:l=a===e?s:`${J.dim}\xB7${J.reset}`,u=""}let c=a===this.labels.length-1?n:"",d=r-4-(c?o.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} ${u}${f}${J.reset}${c}
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
- `;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 o=0;o<this.lineCount;o++)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?` ${J.dim}${e}${J.reset}`:"",o=process.stderr.columns||80,n="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${J.green}\u2713${J.reset}`;break;case"error":i=`${J.red}\u2717${J.reset}`;break;case"retry":i=`${J.yellow}\u21BB${J.reset}`;break;default:i=`${J.yellow}\u25CB${J.reset}`}let a=r===this.labels.length-1?s:"",l=o-4-(a?e.length+1:0),u=this.labels[r].length>l?this.labels[r].substring(0,Math.max(10,l-3))+"...":this.labels[r];n+=`\x1B[2K ${i} ${J.dim}${u}${J.reset}${a}
14
- `}process.stderr.write(n)}},Yr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},zr={done:J.green,in_progress:J.cyan,pending:J.dim,failed:J.red},Cn=null,Xa=class{constructor(e,s){this.name=e,this.tasks=s.map(o=>({id:o.id,description:o.description,status:o.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),o=e%60;return s>0?`${s}m ${String(o).padStart(2,"0")}s`:`${o}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=Rd[this.frame%Rd.length],s=this._formatElapsed(),o=this._formatTokens(),n=[s,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=n?` ${J.dim}(${n})${J.reset}`:"",i=`\x1B[2K${J.cyan}${J.bold}${e}${J.reset} ${J.bold}${this.name}${J.reset}${J.dim}\u2026${J.reset}${r}
15
- `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],u=a===0?"\u23BF":"\u2502",c=Yr[l.status]||Yr.pending,d=zr[l.status]||zr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${J.dim}${u}${J.reset} ${d}${c}${J.reset} ${f}
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),Cn=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,Cn===this&&(Cn=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
- `;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 o=this.tasks.find(n=>n.id===e);o&&(o.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,o=this.tasks.filter(a=>a.status==="failed").length,n=this.tasks.length,r=o>0?`${s}/${n} done, ${o} failed`:`${s}/${n} done`,i=`\x1B[2K${J.green}${J.bold}\u2714${J.reset} ${J.bold}${this.name}${J.reset} ${J.dim}(${e} \xB7 ${r})${J.reset}
20
- `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],u=a===0?"\u23BF":"\u2502",c=Yr[l.status]||Yr.pending,d=zr[l.status]||zr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${J.dim}${u}${J.reset} ${d}${c}${J.reset} ${J.dim}${f}${J.reset}
21
- `}process.stderr.write(i)}},Va=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=Is[this.frame%Is.length],s=Cd(this.message),o="";for(let i=0;i<Kr;i++)o+=i===e?`${s.color}${s.glyph}${J.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${J.cyan}${this.count}${J.reset}`,this.total&&(n+=`/${this.total}`)),this.detail&&(n+=` ${J.dim}${this.detail}${J.reset}`);let r="";if(this.startTime){let i=Math.floor((Date.now()-this.startTime)/1e3);i>=1&&(r=` ${J.dim}${i}s${J.reset}`)}process.stderr.write(`\x1B[2K\r${s.color}${s.accent.toUpperCase()}${J.reset} ${o} ${J.dim}${n}${J.reset}${r}`),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 Cw(t){Cn=t}function Aw(){return Cn}function Ow(){Cn&&(Cn.stop(),Cn=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Ad.exports={C:J,Spinner:za,MultiProgress:Ka,TaskProgress:Xa,ToolProgress:Va,setActiveTaskProgress:Cw,getActiveTaskProgress:Aw,cleanupTerminal:Ow}});var bo=V((B1,Ld)=>{"use strict";var{T:zn}=Gt(),he={kw:zn.syn_keyword,str:zn.syn_string,cmt:zn.syn_comment,num:zn.syn_number,type:zn.cyan,punct:zn.magenta,reset:zn.reset},Od={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"])},Nw={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 Md(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return Nw[e]||null}var Nd=/\x1b\[[0-9;]*m/g;function mn(t,e,s){let o=t.split(Nd),n=t.match(Nd)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,s),i<n.length&&(r+=n[i]);return r}function Mw(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,s=>he.type+s+he.reset),e=mn(e,/"([^"\\]|\\.)*"/g,s=>he.str+s+he.reset),e=mn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,s=>he.num+s+he.reset),e=mn(e,/\b(true|false|null)\b/g,s=>he.kw+s+he.reset),e}function Pw(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,s=>he.cmt+s+he.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(s,o,n)=>o+he.type+n+he.reset),e=mn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(s,o)=>" "+he.kw+o+he.reset+"="),e=mn(e,/"([^"]*)"/g,s=>he.str+s+he.reset),e}function Lw(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,s=>he.cmt+s+he.reset),e=mn(e,/#[0-9a-fA-F]{3,8}\b/g,s=>he.num+s+he.reset),e=mn(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(s,o,n)=>he.num+o+he.reset+n),e=mn(e,/([a-z][a-z-]*)(\s*:)/g,(s,o,n)=>he.type+o+he.reset+n),e=mn(e,/"[^"]*"|'[^']*'/g,s=>he.str+s+he.reset),e}function Pd(t,e,s){if(e==="json")return Mw(t);if(e==="html"||e==="xml")return Pw(t);if(e==="css")return Lw(t);if(e==="md")return t;let o=Od[e]||Od.js,n="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return he.cmt+t+he.reset;if(n+=he.cmt+t.slice(0,i+2)+he.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return n}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return he.str+t+he.reset;if(n+=he.str+t.slice(0,i+1)+he.reset,s.inString=null,r=i+1,r>=t.length)return n}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 n+=he.cmt+t.slice(r)+he.reset,s.inBlockComment=!0,n;n+=he.cmt+t.slice(r,a+2)+he.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 n+=he.cmt+t.slice(r)+he.reset,n;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,n+=he.str+i,r++;continue}if(s.inString){if(i==="\\"&&r+1<t.length){n+=i+t[r+1],r+=2;continue}if(i===s.inString){n+=i+he.reset,s.inString=null,r++;continue}n+=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++];n+=he.num+a+he.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++];n+=he.punct+a+he.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];o.has(a)?n+=he.kw+a+he.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?n+=he.type+a+he.reset:n+=a;continue}n+=i,r++}return s.inString&&s.inString!=="`"&&(n+=he.reset,s.inString=null),n}function Iw(t,e){let s=Md(e);if(!s)return t.split(`
1
+ var Da=Object.defineProperty;var aw=Object.getOwnPropertyDescriptor;var lw=Object.getOwnPropertyNames;var cw=Object.prototype.hasOwnProperty;var uw=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),dw=(t,e)=>{for(var n in e)Da(t,n,{get:e[n],enumerable:!0})},fw=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lw(e))!cw.call(t,s)&&s!==n&&Da(t,s,{get:()=>e[s],enumerable:!(o=aw(e,s))||o.enumerable});return t};var hw=t=>fw(Da({},"__esModule",{value:!0}),t);var Ls=Z((gC,Zu)=>{async function pw(t,e){if(!t.response?.data)return t.message;let n=t.response.data;if(typeof n=="object"&&n!==null&&typeof n.pipe!="function")return e(n)||t.message;try{let o=await new Promise((r,i)=>{let a=[];n.on("data",l=>a.push(l)),n.on("end",()=>r(Buffer.concat(a).toString("utf8"))),n.on("error",i)}),s=JSON.parse(o);return e(s)||o||t.message}catch{return t.message}}var qa=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,n,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,o={}){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`)}};Zu.exports={BaseProvider:qa,readStreamErrorBody:pw}});var Ds=Z((yC,ed)=>{var Is=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,n={}){throw new Error("createStreamParser() not implemented")}},js=class{constructor(e,n={}){this.onToken=e,this.callbacks=n,this.content="",this.buffer=""}feed(e){this.buffer+=e;let n=this.buffer.split(`
2
+ `);this.buffer=n.pop()||"";for(let o of n){let s=this.parseLine(o);if(s?.done)return s}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")}},Ir=class extends js{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let o=n.slice(6);if(o==="[DONE]")return{done:!0,result:this.getResult()};let s;try{s=JSON.parse(o)}catch{return{done:!1}}let r=s.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}}))}}},jr=class extends Is{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i}){let a={model:e,messages:n,max_tokens:s,temperature:r};return i&&(a.stream=!0),o&&o.length>0&&(a.tools=o),a}normalizeResponse(e){let n=e.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}createStreamParser(e,n={}){return new Ir(e,n)}},Dr=class extends js{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let o=n.slice(6),s;try{s=JSON.parse(o)}catch{return{done:!1}}switch(s.type){case"content_block_start":{let r=s.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=s.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 n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},Fa="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",qr=class extends Is{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let l={model:e,messages:n,max_tokens:s,temperature:r};if(i&&(l.stream=!0),a?.system){let u=a.system,c=u.indexOf(Fa);if(c!==-1){let d=u.slice(0,c).trimEnd(),f=u.slice(c+Fa.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=u}return o&&o.length>0&&(l.tools=o),l}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let n="",o=[];for(let s of e.content||[])s.type==="text"?n+=s.text:s.type==="tool_use"&&o.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:n,tool_calls:o}}createStreamParser(e,n={}){return new Dr(e,n)}};function Qu(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 Fr=class extends js{constructor(e,n={}){super(e,n),this.toolCalls=[],this.onThinkingToken=n.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let n;try{n=JSON.parse(e)}catch{return{done:!1}}return n.message?.thinking&&this.onThinkingToken(n.message.thinking),n.message?.content&&(this.onToken(n.message.content),this.content+=n.message.content),n.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(n.message.tool_calls)),n.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,n)=>({id:e.id||`ollama-${Date.now()}-${n}`,function:{name:e.function?.name||e.name||"unknown",arguments:Qu(e.function?.arguments??e.arguments)}}))}}},Br=class extends Is{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let l={model:e,messages:n,stream:i,options:{temperature:r,num_predict:s,repeat_penalty:a?.repeat_penalty??1.05}};return o&&o.length>0&&(l.tools=o),l}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((o,s)=>({id:o.id||`ollama-${Date.now()}-${s}`,function:{name:o.function?.name||o.name||"unknown",arguments:Qu(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,n={}){return new Fr(e,n)}},mw=new jr,gw=new qr,yw=new Br;ed.exports={ANTHROPIC_CACHE_BOUNDARY:Fa,WireProtocol:Is,StreamParser:js,OpenAICompatibleProtocol:jr,AnthropicProtocol:qr,OllamaChatProtocol:Br,OpenAIStreamParser:Ir,AnthropicStreamParser:Dr,OllamaStreamParser:Fr,openaiProtocol:mw,anthropicProtocol:gw,ollamaProtocol:yw}});var sd=Z((wC,nd)=>{var Ur=require("axios"),ww=require("http"),$w=require("https"),{BaseProvider:bw,readStreamErrorBody:_w}=Ls(),{ollamaProtocol:Un}=Ds(),Wr=new ww.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Hr=new $w.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),td={"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}},Ba=class extends bw{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||td,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){Ur.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Wr,httpsAgent:Hr}).then(e=>{let n=e.data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await Ur.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Wr,httpsAgent:Hr})).data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,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(n=>{if(Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:n.role,content:o.join(`
3
+ `)};return s.length>0&&(r.images=s),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=Un.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),l;try{l=await Ur.post(`${this.baseUrl}${Un.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Wr,httpsAgent:Hr})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let c=u.response?.status?` [HTTP ${u.response.status}]`:"",d=u.response?.data?.error||u.message;throw new Error(`API Error${c}: ${d}`)}return Un.normalizeResponse(l.data)}async stream(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),u=Un.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),c;try{c=await Ur.post(`${this.baseUrl}${Un.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:Wr,httpsAgent:Hr})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await _w(f,$=>$?.error),g=new Error(`API Error${h}: ${m}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=Un.createStreamParser(a,{onThinkingToken:l});return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{c.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),c.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),c.data.on("error",m=>{if(o.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,h(g)}),c.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Un.normalizeResponse(e)}};nd.exports={OllamaProvider:Ba,OLLAMA_MODELS:td}});var ad=Z(($C,id)=>{var od=require("axios"),{BaseProvider:xw,readStreamErrorBody:kw}=Ls(),{openaiProtocol:Wn}=Ds(),rd={"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}},Ua=class extends xw{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||rd,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 n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool"){let n;return Array.isArray(e.content)?n=e.content.filter(s=>s.type==="text").map(s=>s.text).join(`
4
+ `)||JSON.stringify(e.content):n=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:n,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),l=Wn.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await od.post(`${this.baseUrl}${Wn.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let d=c.response?.status?` [HTTP ${c.response.status}]`:"",f=c.response?.data?.error?.message||c.response?.data?.error||c.message;throw new Error(`API Error${d}: ${f}`)}return Wn.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u=Wn.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),c;try{c=await od.post(`${this.baseUrl}${Wn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await kw(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=Wn.createStreamParser(a);return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{c.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),c.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),c.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),c.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Wn.normalizeResponse(e)}};id.exports={OpenAIProvider:Ua,OPENAI_MODELS:rd}});var dd=Z((bC,ud)=>{var ld=require("axios"),{BaseProvider:Sw,readStreamErrorBody:vw}=Ls(),{anthropicProtocol:Cn}=Ds(),cd={"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}},Ew="2023-06-01",Wa=class extends Sw{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||cd,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Ew}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 n="",o=[];for(let s of e){if(s.role==="system"){n+=(n?`
5
+
6
+ `:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=n[n.length-1],s;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}});s=i}else s=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:s};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let o=[];for(let s of e.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return Cn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),c=this.formatTools(n),d=Cn.buildRequestBody({model:r,messages:l,tools:c,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:u}}),f;try{f=await ld.post(`${this.baseUrl}${Cn.getEndpoint()}`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let m=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${m}: ${g}`)}return Cn.normalizeResponse(f.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:u,system:c}=this.formatMessages(e),d=this.formatTools(n),f=Cn.buildRequestBody({model:r,messages:u,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:c}}),h;try{h=await ld.post(`${this.baseUrl}${Cn.getEndpoint()}`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let $=g.response?.status?` [HTTP ${g.response.status}]`:"",x=await vw(g,E=>E?.error?.message||E?.error);throw new Error(`API Error${$}: ${x}`)}let m=Cn.createStreamParser(l);return new Promise((g,$)=>{o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),$(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",x=>{let{done:E,result:N}=m.feed(x.toString());E&&g(N)}),h.data.on("error",x=>{o.signal?.aborted||$(new Error(`Stream error: ${x.message}`))}),h.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return Cn.normalizeResponse(e)}};ud.exports={AnthropicProvider:Wa,ANTHROPIC_MODELS:cd}});var md=Z((_C,pd)=>{var fd=require("axios"),{BaseProvider:Tw,readStreamErrorBody:Rw}=Ls(),{openaiProtocol:Hn}=Ds(),hd={"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}},Ha=class extends Tw{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||hd,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 n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.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 n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),l=Hn.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await fd.post(`${this.baseUrl}${Hn.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let d=c.response?.status?` [HTTP ${c.response.status}]`:"",f=c.response?.data?.error?.message||c.response?.data?.error||c.message;throw new Error(`API Error${d}: ${f}`)}return Hn.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,a=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u=Hn.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),c;try{c=await fd.post(`${this.baseUrl}${Hn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await Rw(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=Hn.createStreamParser(a);return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{c.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),c.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),c.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),c.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Hn.normalizeResponse(e)}};pd.exports={GeminiProvider:Ha,GEMINI_MODELS:hd}});var wd=Z((xC,yd)=>{var Yr=require("axios"),{BaseProvider:Cw,readStreamErrorBody:Aw}=Ls(),{ollamaProtocol:Yn}=Ds(),gd="http://localhost:11434",Ya=class extends Cw{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||gd,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 n=(await Yr.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let a=await Yr.post(`${this.baseUrl}/api/show`,{name:s},{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:o.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(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
7
+ `)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=Yn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await Yr.post(`${this.baseUrl}${Yn.getEndpoint()}`,r,{timeout:o.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}]`:"",u=a.response?.data?.error||a.message;throw new Error(`API Error${l}: ${u}`)}return Yn.normalizeResponse(i.data)}async stream(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i=Yn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await Yr.post(`${this.baseUrl}${Yn.getEndpoint()}`,i,{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let c=u.response?.status?` [HTTP ${u.response.status}]`:"",d=await Aw(u,f=>f?.error);throw new Error(`API Error${c}: ${d}`)}let l=Yn.createStreamParser(r);return new Promise((u,c)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),c(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:h}=l.feed(d.toString());f&&u(h)}),a.data.on("error",d=>{o.signal?.aborted||c(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{u(l.flush())})})}normalizeResponse(e){return Yn.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}};yd.exports={LocalProvider:Ya,DEFAULT_LOCAL_URL:gd}});var zt=Z((kC,vd)=>{"use strict";var $d="\x1B[0m",bd="\x1B[1m",qs="\x1B[2m";function X(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function Ow(){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
+ `),s=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(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),a=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function _d(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Nw(t){try{let n=require("fs").readFileSync(_d(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch(e){console.error("readThemeCache failed:",e.message)}return null}function Pw(t,e){try{let n=require("fs"),o=require("path"),s=_d(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"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]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(s,JSON.stringify(i),"utf8")}catch{}}function Mw(){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 n=process.env.TERM_SESSION_ID||"default",o=Nw(n);if(o!==null)return o;let s=Ow(),r=s!==null?s:!0;return Pw(n,r),r}var xd=Mw(),kd={reset:$d,bold:bd,dim:qs,primary:X(80,190,255),secondary:X(60,170,190),success:X(80,210,120),warning:X(245,175,50),error:X(230,80,80),muted:qs,subtle:X(130,130,145),tool_read:X(80,190,255),tool_write:X(245,165,55),tool_exec:X(185,100,235),tool_search:X(70,185,190),tool_git:X(90,210,100),tool_web:X(100,215,250),tool_sysadmin:X(225,150,75),tool_default:X(100,205,115),syn_keyword:X(185,100,235),syn_string:X(90,210,120),syn_number:X(245,175,50),syn_comment:qs,syn_key:X(80,190,255),diff_add:X(80,210,120),diff_rem:X(230,80,80),banner_logo:X(80,200,255),banner_name:X(80,200,255),banner_version:qs,banner_model:qs,banner_yolo:X(245,175,50),banner_gemini:X(138,180,248),footer_sep:qs,footer_model:X(80,175,235),footer_branch:X(80,210,100),footer_project:X(130,130,145),footer_divider:X(80,80,95),footer_mode:X(210,150,50),white:X(210,210,220),red:X(220,85,85),green:X(80,200,110),yellow:X(230,185,60),blue:X(70,140,230),magenta:X(200,120,190),cyan:X(90,200,215),gray:X(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:X(110,215,230),brightMagenta:X(220,140,210),brightBlue:X(100,160,240)},Sd={reset:$d,bold:bd,dim:X(110,110,120),primary:X(0,110,190),secondary:X(0,125,148),success:X(0,148,62),warning:X(168,92,0),error:X(188,32,32),muted:X(110,110,120),subtle:X(155,155,165),tool_read:X(0,110,190),tool_write:X(168,92,0),tool_exec:X(128,42,188),tool_search:X(0,122,148),tool_git:X(0,138,62),tool_web:X(0,112,178),tool_sysadmin:X(168,82,0),tool_default:X(0,138,62),syn_keyword:X(128,42,188),syn_string:X(0,138,62),syn_number:X(168,92,0),syn_comment:X(135,135,148),syn_key:X(0,110,190),diff_add:X(0,148,62),diff_rem:X(188,32,32),banner_logo:X(0,122,205),banner_name:X(0,122,205),banner_version:X(100,100,118),banner_model:X(100,100,118),banner_yolo:X(168,62,0),banner_gemini:X(26,115,232),footer_sep:X(168,168,178),footer_model:X(0,102,175),footer_branch:X(0,138,62),footer_project:X(135,135,148),footer_divider:X(168,168,178),footer_mode:X(148,88,0),white:X(40,40,52),red:X(188,32,32),green:X(0,148,62),yellow:X(168,92,0),blue:X(0,110,190),magenta:X(128,42,188),cyan:X(0,125,148),gray:X(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:X(0,158,182),brightMagenta:X(158,52,208),brightBlue:X(0,112,208)},Lw=xd?kd:Sd;vd.exports={T:Lw,isDark:xd,DARK:kd,LIGHT:Sd}});var Gn=Z((SC,Td)=>{"use strict";var Tt=require("fs"),Ed=require("path");function Iw(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function jw(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function Dw(t,e){let n=Ed.dirname(t),o=Ed.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Tt.existsSync(n)||Tt.mkdirSync(n,{recursive:!0,mode:448}),Tt.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Tt.renameSync(o,t)}catch(s){try{Tt.unlinkSync(o)}catch{}throw s}}function qw(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Tt.openSync(s,"wx"),Tt.writeSync(i,Buffer.from(String(process.pid))),Tt.closeSync(i),i=-1;try{return e()}finally{try{Tt.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{Tt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=Tt.readFileSync(s,"utf-8").trim(),u=parseInt(l,10);if(!Iw(u)){try{Tt.unlinkSync(s)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Tt.unlinkSync(s)}catch{}return e()}jw(o)}}}Td.exports={atomicWrite:Dw,withFileLockSync:qw}});var zr=Z((vC,Ld)=>{var Fs=require("fs"),Ga=require("path"),{T:Rd}=zt(),{atomicWrite:Fw,withFileLockSync:Bw}=Gn(),Cd={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:{}},Gr=[],An={};function Uw(t,e,n,o,s=0){if(Gr.push({provider:t,model:e,input:n,output:o,cacheRead:s}),An[t]!==void 0){let r=Pd(t);r.allowed||process.stderr.write(`${Rd.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${Rd.reset}
9
+ `)}}function za(t,e){let n=Cd[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function Ad(t){let e=za(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Od(){let t={};for(let i of Gr){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:Ad(i)})),n=e.reduce((i,a)=>i+a.cost,0),o=e.reduce((i,a)=>i+a.input,0),s=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:n,totalInput:o,totalOutput:s,totalCacheRead:r,breakdown:e}}function Ww(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=Od();if(o.length===0)return"No token usage recorded this session.";let s=[];s.push("Session Token Usage:"),s.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";s.push(` ${r.provider}:${r.model}`),s.push(` Input: ${r.input.toLocaleString()} tokens`),s.push(` Output: ${r.output.toLocaleString()} tokens`),s.push(` Cost: ${i}`)}return s.push(""),s.push(` Total: ${e.toLocaleString()} in + ${n.toLocaleString()} out = $${t.toFixed(4)}`),s.join(`
10
+ `)}function Hw(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function Yw(t,e,n,o){let s=za(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Gw(){Gr=[]}function zw(t,e){An[t]=e}function Kw(t){delete An[t]}function Xw(){return{...An}}function Nd(t){let e=0;for(let n of Gr)n.provider===t&&(e+=Ad(n));return e}function Pd(t){let e=Nd(t),n=An[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let o=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:o}}function Md(){let t=Ga.join(process.cwd(),".nex","config.json");if(Fs.existsSync(t))try{let e=JSON.parse(Fs.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(An={...e.costLimits})}catch{}}function Vw(){let t=Ga.join(process.cwd(),".nex"),e=Ga.join(t,"config.json");Fs.existsSync(t)||Fs.mkdirSync(t,{recursive:!0}),Bw(e,()=>{let n={};if(Fs.existsSync(e))try{n=JSON.parse(Fs.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=An,Fw(e,JSON.stringify(n,null,2))})}function Jw(){An={}}Md();Ld.exports={PRICING:Cd,trackUsage:Uw,getSessionCosts:Od,formatCosts:Ww,formatCostHint:Yw,resetCosts:Gw,getPricing:za,setCostLimit:zw,removeCostLimit:Kw,getCostLimits:Xw,getProviderSpend:Nd,checkBudget:Pd,loadCostLimits:Md,saveCostLimits:Vw,resetCostLimits:Jw,estimateTokens:Hw}});var Ka=Z((EC,Zw)=>{Zw.exports={name:"nex-code",version:"0.5.14",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 .","scan:secrets":"node scripts/secret-scan.js --staged","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 zn=Z((TC,Bd)=>{var{T:V}=zt(),Xa=5,Bs=(()=>{let t=[];for(let e=0;e<Xa;e++)t.push(e);for(let e=Xa-2;e>=1;e--)t.push(e);return t})(),Id=["\u273D","\u2726","\u2727","\u2726"],jd=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function Dd(t=""){let e=String(t).toLowerCase();return e.includes("search")||e.includes("read")||e.includes("list")||e.includes("inspect")?{glyph:"\u25CC",color:V.cyan,accent:"scan"}:e.includes("write")||e.includes("edit")||e.includes("patch")||e.includes("build")?{glyph:"\u2726",color:V.yellow,accent:"shape"}:e.includes("test")||e.includes("diff")||e.includes("check")||e.includes("verify")?{glyph:"\u25A3",color:V.green,accent:"verify"}:e.includes("wait")||e.includes("github")||e.includes("fetch")||e.includes("browser")?{glyph:"\u25CD",color:V.blue,accent:"wait"}:{glyph:"\u25CF",color:V.cyan,accent:"think"}}function qd(t,e,n){let o="";for(let s=0;s<Xa;s++)s===t?o+=`${n}${e}${V.reset}`:s===t-1||s===t+1?o+=`${V.dim}\xB7${V.reset}`:o+=`${V.dim}\xB7${V.reset}`;return o}function Fd(t){return`${V.dim}${jd[t%jd.length]}${V.reset}`}var Va=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Bs[this.frame%Bs.length],n=Dd(this.text),o=qd(e,n.glyph,n.color),s=Fd(this.frame),r="";if(this.startTime){let i=Math.floor((Date.now()-this.startTime)/1e3);if(i>=60){let a=Math.floor(i/60),l=i%60;r=` ${V.dim}${a}m ${String(l).padStart(2,"0")}s${V.reset}`}else i>=1&&(r=` ${V.dim}${i}s${V.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${V.reset}${s} ${o} ${V.dim}${this.text}${V.reset}${r}`),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}},Ja=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 n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let e=Bs[this.frame%Bs.length],n=`${V.cyan}\u25CC${V.reset}`,o=this._formatElapsed(),s=o?` ${V.dim}${o}${V.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let l,u;switch(this.statuses[a]){case"done":l=`${V.green}\u2713${V.reset}`,u=V.dim;break;case"error":l=`${V.red}\u2717${V.reset}`,u=V.dim;break;case"retry":l=`${V.yellow}\u21BB${V.reset}`,u=V.yellow;break;default:l=a===e?n:`${V.dim}\xB7${V.reset}`,u=""}let c=a===this.labels.length-1?s:"",d=r-4-(c?o.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} ${u}${f}${V.reset}${c}
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 n=0;n<this.lineCount;n++)e+=`
12
+ `;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,n){e>=0&&e<this.statuses.length&&(this.statuses[e]=n)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let n="";for(let o=0;o<this.lineCount;o++)n+=`\x1B[2K
13
+ `;this.lineCount>0&&(n+=`\x1B[${this.lineCount}A`),process.stderr.write(n)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),n=e?` ${V.dim}${e}${V.reset}`:"",o=process.stderr.columns||80,s="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${V.green}\u2713${V.reset}`;break;case"error":i=`${V.red}\u2717${V.reset}`;break;case"retry":i=`${V.yellow}\u21BB${V.reset}`;break;default:i=`${V.yellow}\u25CB${V.reset}`}let a=r===this.labels.length-1?n:"",l=o-4-(a?e.length+1:0),u=this.labels[r].length>l?this.labels[r].substring(0,Math.max(10,l-3))+"...":this.labels[r];s+=`\x1B[2K ${i} ${V.dim}${u}${V.reset}${a}
14
+ `}process.stderr.write(s)}},Kr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Xr={done:V.green,in_progress:V.cyan,pending:V.dim,failed:V.red},On=null,Za=class{constructor(e,n){this.name=e,this.tasks=n.map(o=>({id:o.id,description:o.description,status:o.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 n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}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=Id[this.frame%Id.length],n=this._formatElapsed(),o=this._formatTokens(),s=[n,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=s?` ${V.dim}(${s})${V.reset}`:"",i=`\x1B[2K${V.cyan}${V.bold}${e}${V.reset} ${V.bold}${this.name}${V.reset}${V.dim}\u2026${V.reset}${r}
15
+ `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],u=a===0?"\u23BF":"\u2502",c=Kr[l.status]||Kr.pending,d=Xr[l.status]||Xr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${V.dim}${u}${V.reset} ${d}${c}${V.reset} ${f}
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 n=0;n<this.lineCount;n++)e+=`
17
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),On=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,On===this&&(On=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let n=0;n<this.lineCount;n++)e+=`\x1B[2K
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 n=0;n<this.lineCount;n++)e+=`
19
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,n){let o=this.tasks.find(s=>s.id===e);o&&(o.status=n)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),n=this.tasks.filter(a=>a.status==="done").length,o=this.tasks.filter(a=>a.status==="failed").length,s=this.tasks.length,r=o>0?`${n}/${s} done, ${o} failed`:`${n}/${s} done`,i=`\x1B[2K${V.green}${V.bold}\u2714${V.reset} ${V.bold}${this.name}${V.reset} ${V.dim}(${e} \xB7 ${r})${V.reset}
20
+ `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],u=a===0?"\u23BF":"\u2502",c=Kr[l.status]||Kr.pending,d=Xr[l.status]||Xr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${V.dim}${u}${V.reset} ${d}${c}${V.reset} ${V.dim}${f}${V.reset}
21
+ `}process.stderr.write(i)}},Qa=class{constructor(e,n){this.toolName=e,this.message=n||`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=Bs[this.frame%Bs.length],n=Dd(this.message),o=qd(e,n.glyph,n.color),s=Fd(this.frame),r=this.message;this.count>0&&(r+=` ${V.cyan}${this.count}${V.reset}`,this.total&&(r+=`/${this.total}`)),this.detail&&(r+=` ${V.dim}${this.detail}${V.reset}`);let i="";if(this.startTime){let a=Math.floor((Date.now()-this.startTime)/1e3);a>=1&&(i=` ${V.dim}${a}s${V.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${V.reset}${s} ${o} ${V.dim}${r}${V.reset}${i}`),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 Qw(t){On=t}function e$(){return On}function t$(){On&&(On.stop(),On=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Bd.exports={C:V,Spinner:Va,MultiProgress:Ja,TaskProgress:Za,ToolProgress:Qa,setActiveTaskProgress:Qw,getActiveTaskProgress:e$,cleanupTerminal:t$}});var Vr=Z((RC,Gd)=>{"use strict";var{T:Kn}=zt(),pe={kw:Kn.syn_keyword,str:Kn.syn_string,cmt:Kn.syn_comment,num:Kn.syn_number,type:Kn.cyan,punct:Kn.magenta,reset:Kn.reset},Ud={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"])},n$={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 n$[e]||null}var Wd=/\x1b\[[0-9;]*m/g;function $n(t,e,n){let o=t.split(Wd),s=t.match(Wd)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,n),i<s.length&&(r+=s[i]);return r}function s$(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,n=>pe.type+n+pe.reset),e=$n(e,/"([^"\\]|\\.)*"/g,n=>pe.str+n+pe.reset),e=$n(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,n=>pe.num+n+pe.reset),e=$n(e,/\b(true|false|null)\b/g,n=>pe.kw+n+pe.reset),e}function o$(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,n=>pe.cmt+n+pe.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(n,o,s)=>o+pe.type+s+pe.reset),e=$n(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(n,o)=>" "+pe.kw+o+pe.reset+"="),e=$n(e,/"([^"]*)"/g,n=>pe.str+n+pe.reset),e}function r$(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,n=>pe.cmt+n+pe.reset),e=$n(e,/#[0-9a-fA-F]{3,8}\b/g,n=>pe.num+n+pe.reset),e=$n(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(n,o,s)=>pe.num+o+pe.reset+s),e=$n(e,/([a-z][a-z-]*)(\s*:)/g,(n,o,s)=>pe.type+o+pe.reset+s),e=$n(e,/"[^"]*"|'[^']*'/g,n=>pe.str+n+pe.reset),e}function Yd(t,e,n){if(e==="json")return s$(t);if(e==="html"||e==="xml")return o$(t);if(e==="css")return r$(t);if(e==="md")return t;let o=Ud[e]||Ud.js,s="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return pe.cmt+t+pe.reset;if(s+=pe.cmt+t.slice(0,i+2)+pe.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return s}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return pe.str+t+pe.reset;if(s+=pe.str+t.slice(0,i+1)+pe.reset,n.inString=null,r=i+1,r>=t.length)return s}for(;r<t.length;){let i=t[r];if(!n.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return s+=pe.cmt+t.slice(r)+pe.reset,n.inBlockComment=!0,s;s+=pe.cmt+t.slice(r,a+2)+pe.reset,r=a+2;continue}if(!n.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return s+=pe.cmt+t.slice(r)+pe.reset,s;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,s+=pe.str+i,r++;continue}if(n.inString){if(i==="\\"&&r+1<t.length){s+=i+t[r+1],r+=2;continue}if(i===n.inString){s+=i+pe.reset,n.inString=null,r++;continue}s+=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++];s+=pe.num+a+pe.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++];s+=pe.punct+a+pe.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];o.has(a)?s+=pe.kw+a+pe.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?s+=pe.type+a+pe.reset:s+=a;continue}s+=i,r++}return n.inString&&n.inString!=="`"&&(s+=pe.reset,n.inString=null),s}function i$(t,e){let n=Hd(e);if(!n)return t.split(`
22
22
  `);let o=t.split(`
23
- `),n={inString:null,inBlockComment:!1};return o.map(r=>Pd(r,s,n))}function jw(t,e){return e?Pd(t,e,{inString:null,inBlockComment:!1}):t}Ld.exports={detectLang:Md,highlightLine:jw,highlightLines:Iw}});var Ud=V((U1,Bd)=>{var{T:b}=Gt(),Pe=b,Xr=require("path");function Id(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var Dw={read_file:b.tool_read,list_directory:b.tool_read,write_file:b.tool_write,edit_file:b.tool_write,patch_file:b.tool_write,bash:b.tool_exec,grep:b.tool_search,search_files:b.tool_search,glob:b.tool_search,git_commit:b.tool_git,git_push:b.tool_git,git_pull:b.tool_git,git_status:b.tool_git,git_diff:b.tool_git,git_log:b.tool_git,git_branch:b.tool_git,git_stash:b.tool_git,web_fetch:b.tool_web,web_search:b.tool_web,sysadmin:b.tool_sysadmin,ssh_exec:b.tool_sysadmin,ssh_upload:b.tool_sysadmin,ssh_download:b.tool_sysadmin,deploy:b.tool_sysadmin},Fd={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"},qw={read_file:{label:"Inspect",accent:b.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:b.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:b.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:b.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:b.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:b.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:b.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:b.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:b.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:b.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:b.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:b.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:b.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:b.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:b.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:b.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:b.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:b.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:b.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:b.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:b.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:b.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:b.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:b.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:b.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:b.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:b.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:b.tool_git,icon:"\u2713"}};function Ja(t){return qw[t]||{label:"Run",accent:b.tool_default,icon:"\u2022"}}function jd(t){let e=Ja(t);return`${e.accent}${Pe.bold}${e.icon} ${e.label.toUpperCase()}${b.reset}`}function Fw(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Dd(t,e={}){return e.path?Id(e.path):e.file?Id(e.file):e.query?String(e.query).substring(0,44):e.pattern?String(e.pattern).substring(0,44):e.url?String(e.url).substring(0,44):e.command?String(e.command).substring(0,44):Fd[t]||Fw(t)}function Bw(t){return String(t||"").split(`
24
- `).map(e=>{let s=e.match(/^(\d+):\s?(.*)$/s);return s?{lineNumber:s[1],content:s[2]||""}:null}).filter(Boolean)}function Uw(t,e,s={}){let{maxLines:o=4,indent:n=" ",maxContent:r=110,includeOverflow:i=!0}=s;if(!Array.isArray(e)||e.length===0)return"";let{highlightLine:a,detectLang:l}=bo(),u=l(t||null),c=e.slice(0,o),d=c.map(({lineNumber:f,content:h})=>{let m=h.length>r?h.substring(0,r-1)+"\u2026":h;return`${n}${b.subtle}${f}:${b.reset} ${a(m,u)}${b.reset}`});return i&&e.length>c.length&&d.push(`${n}${b.subtle}\u2026 +${e.length-c.length} more line${e.length-c.length!==1?"s":""}${b.reset}`),d.join(`
25
- `)}function Ww(t){let e=new Set,s=[];for(let o of t){let n=Ja(o.fnName).label;e.has(n)||(e.add(n),s.push(n))}return s.length===0?"":s.length<=3?s.join(`${Pe.dim} \u2192 ${Pe.reset}`):`${s.slice(0,3).join(`${Pe.dim} \u2192 ${Pe.reset}`)}${Pe.dim} \u2192 +${s.length-3}${Pe.reset}`}function Vr(t,e=!1,s=null){if(e)return`${b.error}\u23FA${b.reset}`;let o=Dw[t]||b.tool_default;return s==="blink"?`${o}\x1B[5m\u23FA\x1B[25m${b.reset}`:`${o}${s!==null?s:"\u23FA"}${b.reset}`}function Hw(t,e,s=!1,o=null){let n=(t||[]).filter(u=>u&&u.canExecute!==!1);if(n.length===0)return`${Vr("",s,o)} Step ${e}`;if(n.length===1){let u=n[0],c=u.args||{},d=Dd(u.fnName,{...c,path:c._originalPath||c.path});return`${Vr(u.fnName,s,o)} ${jd(u.fnName)} ${Pe.bold}${d}${Pe.reset}`}let r=n[0].fnName,i=Ww(n)||`${n.length} tools`,a=n.slice(0,2).map(u=>Dd(u.fnName,u.args||{})).filter(Boolean).join(`${Pe.dim} \xB7 ${Pe.reset}`),l=a?` ${b.subtle}\xB7${b.reset} ${Pe.dim}${a}${Pe.reset}`:"";return`${Vr(r,s,o)} ${jd(r)} ${Pe.bold}${i}${Pe.reset}${l}`}function Gw(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 o=Fd[t]||t.replace(/_/g," "),n=s?`(${Pe.dim}${s}${Pe.reset})`:"";return`${Vr(t)} ${Pe.bold}${o}${Pe.reset}${n}`}function Yw(t,e=8){let s=t.split(`
26
- `),o=s.slice(0,e),n=s.length-e,r=`${b.muted} \u23BF ${b.reset}`,i=" ",a=o.map((l,u)=>`${u===0?r:i}${b.success}${l}${b.reset}`).join(`
27
- `);return n>0&&(a+=`
28
- ${b.subtle} \u2026 +${n} lines${b.reset}`),a}var Jr=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],qd=Math.floor(Math.random()*Jr.length),zw=null;function Kw(t){zw=t}function Xw(){let t=Jr[qd%Jr.length];return qd++,t}function Vw(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"Analyzing repository 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 Jw(t,e,s,o){let n=String(s||""),r=Ja(t),i=` ${b.subtle}\u2502${b.reset} ${r.accent}${Pe.bold}${r.label}${b.reset} ${b.subtle}\xB7${b.reset} `;if(o){let u=n.split(`
29
- `)[0];if(u.startsWith("BLOCKED:")){let h=u.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${b.muted}blocked: ${h}${b.reset}`}let c=u.replace(/^ERROR:\s*/i,"").substring(0,80),d=n.match(/\nHINT: (.+)/),f=d?`
30
- ${b.muted}${d[1].substring(0,100)}${b.reset}`:"";return`${i}${b.error}${c}${b.reset}${f}`}let a;switch(t){case"read_file":{let u=Bw(n),c=u.length,d=u[u.length-1],f=d?parseInt(d.lineNumber||"0"):0,h=e.line_start||e.line_end,m=e.path?Xr.basename(e.path):null,g=m?` ${b.muted}from ${m}${b.reset}`:"";h&&f>c?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${c} line${c!==1?"s":""}${g}`;let $=Uw(e.path,u,{maxLines:4,maxContent:120});$&&(a+=`
23
+ `),s={inString:null,inBlockComment:!1};return o.map(r=>Yd(r,n,s))}function a$(t,e){return e?Yd(t,e,{inString:null,inBlockComment:!1}):t}Gd.exports={detectLang:Hd,highlightLine:a$,highlightLines:i$}});var nf=Z((CC,tf)=>{var{T:b}=zt(),Le=b,zd=require("path"),Kd=["\u23FA","\u25C9","\u25CE","\u25C9"];function Zr(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var l$={read_file:b.tool_read,list_directory:b.tool_read,write_file:b.tool_write,edit_file:b.tool_write,patch_file:b.tool_write,bash:b.tool_exec,grep:b.tool_search,search_files:b.tool_search,glob:b.tool_search,git_commit:b.tool_git,git_push:b.tool_git,git_pull:b.tool_git,git_status:b.tool_git,git_diff:b.tool_git,git_log:b.tool_git,git_branch:b.tool_git,git_stash:b.tool_git,web_fetch:b.tool_web,web_search:b.tool_web,sysadmin:b.tool_sysadmin,ssh_exec:b.tool_sysadmin,ssh_upload:b.tool_sysadmin,ssh_download:b.tool_sysadmin,deploy:b.tool_sysadmin},Zd={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"},c$={read_file:{label:"Inspect",accent:b.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:b.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:b.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:b.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:b.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:b.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:b.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:b.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:b.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:b.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:b.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:b.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:b.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:b.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:b.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:b.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:b.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:b.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:b.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:b.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:b.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:b.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:b.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:b.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:b.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:b.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:b.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:b.tool_git,icon:"\u2713"}};function tl(t){return c$[t]||{label:"Run",accent:b.tool_default,icon:"\u2022"}}function Xd(t){let e=tl(t);return`${e.accent}${Le.bold}${e.icon} ${e.label.toUpperCase()}${b.reset}`}function u$(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Vd(t,e={}){return e.path?Zr(e.path):e.file?Zr(e.file):e.query?String(e.query).substring(0,44):e.pattern?String(e.pattern).substring(0,44):e.url?String(e.url).substring(0,44):e.command?String(e.command).substring(0,44):Zd[t]||u$(t)}function d$(t){return String(t||"").split(`
24
+ `).map(e=>{let n=e.match(/^(\d+):\s?(.*)$/s);return n?{lineNumber:n[1],content:n[2]||""}:null}).filter(Boolean)}function f$(t,e,n={}){let{maxLines:o=4,indent:s=" ",maxContent:r=110,includeOverflow:i=!0}=n;if(!Array.isArray(e)||e.length===0)return"";let{highlightLine:a,detectLang:l}=Vr(),u=l(t||null),c=e.slice(0,o),d=c.map(({lineNumber:f,content:h})=>{let m=h.length>r?h.substring(0,r-1)+"\u2026":h;return`${s}${b.subtle}${f}:${b.reset} ${a(m,u)}${b.reset}`});return i&&e.length>c.length&&d.push(`${s}${b.subtle}\u2026 +${e.length-c.length} more line${e.length-c.length!==1?"s":""}${b.reset}`),d.join(`
25
+ `)}function h$(t,e=96){let n=String(t||"").replace(/\t/g," ").trimEnd();return n.length>e?n.substring(0,Math.max(1,e-1))+"\u2026":n}function el(t,e={}){let{maxLines:n=3,maxContent:o=96}=e,r=String(t||"").split(`
26
+ `).filter((a,l,u)=>a.trim()||u.length===1||l===0),i=r.slice(0,n).map(a=>h$(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function Qd(t,e={}){let{indent:n=" ",maxLines:o=2,maxContent:s=100}=e;if(!t)return"";let{shown:r,more:i}=el(t,{maxLines:o,maxContent:s});if(r.length===0)return"";let a=r.map((l,u)=>`${n}${b.subtle}${u===0?"$":">"}${b.reset} ${b.muted}${l}${b.reset}`);return i>0&&a.push(`${n}${b.subtle}\u2026 +${i} more command line${i!==1?"s":""}${b.reset}`),a.join(`
27
+ `)}function nl(t,e,n,o={}){let{indent:s=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=o,{highlightLine:l,detectLang:u}=Vr(),c=u(t||null),{shown:d,more:f}=el(e,{maxLines:r,maxContent:i}),{shown:h,more:m}=el(n,{maxLines:r,maxContent:i}),g=[];return d.length>0&&a&&g.push(`${s}${b.subtle}before${b.reset}`),d.forEach($=>{g.push(`${s}${b.diff_rem}- ${b.reset}${l($,c)}${b.reset}`)}),f>0&&g.push(`${s}${b.subtle}\u2026 ${f} more removed line${f!==1?"s":""}${b.reset}`),h.length>0&&a&&g.push(`${s}${b.subtle}after${b.reset}`),h.forEach($=>{g.push(`${s}${b.diff_add}+ ${b.reset}${l($,c)}${b.reset}`)}),m>0&&g.push(`${s}${b.subtle}\u2026 ${m} more added line${m!==1?"s":""}${b.reset}`),g.join(`
28
+ `)}function ef(t,e,n={}){let{indent:o=" ",maxPatches:s=2,maxLinesPerSide:r=2,maxContent:i=92}=n;if(!Array.isArray(e)||e.length===0)return"";let a=[];return e.slice(0,s).forEach((l,u)=>{a.push(`${o}${b.subtle}patch ${u+1}${b.reset}`);let c=nl(t,l.old_text,l.new_text,{indent:o+" ",maxLines:r,maxContent:i,includeLabels:!1});c&&a.push(c)}),e.length>s&&a.push(`${o}${b.subtle}\u2026 +${e.length-s} more patches${b.reset}`),a.join(`
29
+ `)}function p$(t){let e=new Set,n=[];for(let o of t){let s=tl(o.fnName).label;e.has(s)||(e.add(s),n.push(s))}return n.length===0?"":n.length<=3?n.join(`${Le.dim} \u2192 ${Le.reset}`):`${n.slice(0,3).join(`${Le.dim} \u2192 ${Le.reset}`)}${Le.dim} \u2192 +${n.length-3}${Le.reset}`}function Jr(t,e=!1,n=null){if(e)return`${b.error}\u23FA${b.reset}`;let o=l$[t]||b.tool_default;if(n==="blink")return`${o}\x1B[5m\u23FA\x1B[25m${b.reset}`;let s=typeof n=="number"?Kd[n%Kd.length]:n!==null?n:"\u23FA";return`${o}${s}${b.reset}`}function m$(t,e,n=!1,o=null){let s=(t||[]).filter(u=>u&&u.canExecute!==!1);if(s.length===0)return`${Jr("",n,o)} Step ${e}`;if(s.length===1){let u=s[0],c=u.args||{},d=Vd(u.fnName,{...c,path:c._originalPath||c.path});return`${Jr(u.fnName,n,o)} ${Xd(u.fnName)} ${Le.bold}${d}${Le.reset}`}let r=s[0].fnName,i=p$(s)||`${s.length} tools`,a=s.slice(0,2).map(u=>Vd(u.fnName,u.args||{})).filter(Boolean).join(`${Le.dim} \xB7 ${Le.reset}`),l=a?` ${b.subtle}\xB7${b.reset} ${Le.dim}${a}${Le.reset}`:"";return`${Jr(r,n,o)} ${Xd(r)} ${Le.bold}${i}${Le.reset}${l}`}function g$(t,e){let n;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":n=e.path||"";break;case"bash":case"ssh_exec":n=(e.command||"").substring(0,44);break;case"grep":case"search_files":n=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":n=e.pattern||"";break;case"web_fetch":n=(e.url||"").substring(0,60);break;case"web_search":n=(e.query||"").substring(0,50);break;default:n=JSON.stringify(e).substring(0,80)}let o=Zd[t]||t.replace(/_/g," "),s=n?`(${Le.dim}${n}${Le.reset})`:"",r=`${Jr(t)} ${Le.bold}${o}${Le.reset}${s}`;if(t==="bash"||t==="ssh_exec"){let i=Qd(e.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
30
+ ${i}`:r}if(t==="edit_file"){let i=nl(e.path,e.old_text,e.new_text,{indent:" ",maxLines:2,maxContent:92});return i?`${r}
31
+ ${i}`:r}if(t==="patch_file"){let i=ef(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
32
+ ${i}`:r}return r}function y$(t,e=8){let n=t.split(`
33
+ `),o=n.slice(0,e),s=n.length-e,r=`${b.muted} \u23BF ${b.reset}`,i=" ",a=o.map((l,u)=>`${u===0?r:i}${b.success}${l}${b.reset}`).join(`
34
+ `);return s>0&&(a+=`
35
+ ${b.subtle} \u2026 +${s} lines${b.reset}`),a}var Qr=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Jd=Math.floor(Math.random()*Qr.length),w$=null;function $$(t){w$=t}function b$(){let t=Qr[Jd%Qr.length];return Jd++,t}function _$(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"Analyzing repository 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 n=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${n}: full audit...`;case"disk_usage":return`Sysadmin${n}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${n}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${n}: network status...`;case"ssl_check":return`Sysadmin${n}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${n}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${n}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${n}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${n}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${n}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${n}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${n}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${n}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${n}: cron ${e.cron_action||""}...`;default:return`Sysadmin${n}: ${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 x$(t,e,n,o){let s=String(n||""),r=tl(t),i=` ${b.subtle}\u2502${b.reset} ${r.accent}${Le.bold}${r.label}${b.reset} ${b.subtle}\xB7${b.reset} `;if(o){let u=s.split(`
36
+ `)[0];if(u.startsWith("BLOCKED:")){let h=u.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${b.muted}blocked: ${h}${b.reset}`}let c=u.replace(/^ERROR:\s*/i,"").substring(0,80),d=s.match(/\nHINT: (.+)/),f=d?`
37
+ ${b.muted}${d[1].substring(0,100)}${b.reset}`:"";return`${i}${b.error}${c}${b.reset}${f}`}let a;switch(t){case"read_file":{let u=d$(s),c=u.length,d=u[u.length-1],f=d?parseInt(d.lineNumber||"0"):0,h=e.line_start||e.line_end,m=e.path?zd.basename(e.path):null,g=m?` ${b.muted}from ${m}${b.reset}`:"";h&&f>c?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${c} line${c!==1?"s":""}${g}`;let $=f$(e.path,u,{maxLines:4,maxContent:120});$&&(a+=`
31
38
  ${$}`);break}case"write_file":{let c=(e.content||"").split(`
32
- `).length,d=e.path?Xr.basename(e.path):null,f=d?`Wrote ${d} \xB7 ${c} line${c!==1?"s":""}`:`Wrote ${c} line${c!==1?"s":""}`,{highlightLines:h}=bo(),m=h(e.content||"",e.path||null),g=40,$=8;if(c<=g){let k=m.map(v=>` ${v}`).join(`
39
+ `).length,d=e.path?zd.basename(e.path):null,f=d?`Wrote ${d} \xB7 ${c} line${c!==1?"s":""}`:`Wrote ${c} line${c!==1?"s":""}`,{highlightLines:h}=Vr(),m=h(e.content||"",e.path||null),g=40,$=8;if(c<=g){let x=m.map(E=>` ${E}`).join(`
33
40
  `);a=`${f}
34
- ${k}`}else{let k=m.slice(0,$).map(v=>` ${v}`).join(`
41
+ ${x}`}else{let x=m.slice(0,$).map(E=>` ${E}`).join(`
35
42
  `);a=`${f}
36
- ${k}
43
+ ${x}
37
44
  ${b.subtle}\u2026 +${c-$} lines${b.reset}`}break}case"edit_file":{let u=(e.old_text||"").split(`
38
45
  `),c=(e.new_text||"").split(`
39
- `),d=u.length,f=c.length,h=e.path?Xr.basename(e.path):null,m=h?` ${b.muted}${h}${b.reset}`:"",{highlightLine:g,detectLang:$}=bo(),k=$(e.path||null),v=[],A=u.filter((S,N,ee)=>S.trim()||ee.length===1||N===0).slice(0,3),E=c.filter((S,N,ee)=>S.trim()||ee.length===1||N===0).slice(0,3);A.forEach(S=>{v.push(` ${b.diff_rem}- ${b.reset}${g(S.trimEnd().substring(0,96),k)}${b.reset}`)}),u.length>A.length&&v.push(` ${b.subtle}\u2026 ${u.length-A.length} more removed line${u.length-A.length!==1?"s":""}${b.reset}`),E.forEach(S=>{v.push(` ${b.diff_add}+ ${b.reset}${g(S.trimEnd().substring(0,96),k)}${b.reset}`)}),c.length>E.length&&v.push(` ${b.subtle}\u2026 ${c.length-E.length} more added line${c.length-E.length!==1?"s":""}${b.reset}`),a=`${b.diff_rem}\u2212${d}${b.reset} ${b.diff_add}+${f}${b.reset}${m}`+(v.length>0?`
40
- `+v.join(`
41
- `):"");break}case"patch_file":{let u=e.patches||[],c=u.reduce((v,A)=>v+(A.old_text||"").split(`
42
- `).length,0),d=u.reduce((v,A)=>v+(A.new_text||"").split(`
43
- `).length,0),f=e.path?Xr.basename(e.path):null,h=f?` ${b.muted}${f}${b.reset}`:"";a=`${u.length} patch${u.length!==1?"es":""} ${b.diff_rem}\u2212${c}${b.reset} ${b.diff_add}+${d}${b.reset}${h}`;let m=[],{highlightLine:g,detectLang:$}=bo(),k=$(e.path||null);u.slice(0,2).forEach((v,A)=>{let E=String(v.old_text||"").split(`
44
- `).find(Boolean),S=String(v.new_text||"").split(`
45
- `).find(Boolean);m.push(` ${b.subtle}patch ${A+1}${b.reset}`),E&&m.push(` ${b.diff_rem}- ${b.reset}${g(E.trimEnd().substring(0,92),k)}${b.reset}`),S&&m.push(` ${b.diff_add}+ ${b.reset}${g(S.trimEnd().substring(0,92),k)}${b.reset}`)}),u.length>2&&m.push(` ${b.subtle}\u2026 +${u.length-2} more patches${b.reset}`),m.length>0&&(a+=`
46
- ${m.join(`
47
- `)}`);break}case"bash":{let c=n.match(/^EXIT (\d+)/),d=n.split(`
48
- `).filter(m=>m&&!m.startsWith("EXIT ")&&!m.startsWith("HINT:")&&m.trim()),f=c?c[1]==="0"?`${b.success}\u2713${b.reset}`:`${b.error}\u2717 Exit ${c[1]}${b.reset}`:`${b.success}\u2713${b.reset}`,h=n.match(/\nHINT: (.+)/);if(h)a=`${f} ${b.muted}\u2014 ${h[1].substring(0,100)}${b.reset}`;else if(d.length===0)a=f;else{let m=c&&c[1]!=="0",g=m?d.slice(-3):d.slice(0,3),$=d.length-3,k=g.map((v,A)=>A===0?`${f} ${b.muted}${v.substring(0,120)}${b.reset}`:` ${b.muted}${v.substring(0,120)}${b.reset}`);if($>0){let v=m?` ${b.subtle}${$} lines above\u2026${b.reset}`:` ${b.subtle}\u2026 +${$} lines${b.reset}`;m?k.unshift(v):k.push(v)}a=k.join(`
49
- `)}break}case"grep":case"search_files":{if(n.includes("(no matches)")||n==="no matches")a=`No matches${e.pattern?` ${b.muted}"${String(e.pattern).substring(0,40)}"${b.reset}`:""}`;else{let $=function(E){let S=E.indexOf(":");if(S===-1)return`${b.muted}${E.substring(0,90)}${b.reset}`;let N=E.substring(0,S),ee=E.substring(S+1),re=ee.match(/^(\d+)[:-](.*)/s),le=re?`:${re[1]}`:"",ue=(re?re[2]:ee).trim(),oe=`${b.subtle}${u.basename(N)}${le}${b.reset}`,ae=`${b.muted}${ue.substring(0,80)}${ue.length>80?"\u2026":""}${b.reset}`;return`${oe} ${ae}`};var l=$;let u=require("path"),c=n.split(`
50
- `).filter(Boolean),d=c.length,h=new Set(c.map(E=>E.split(":")[0]).filter(Boolean)).size,m=e.pattern?` ${b.muted}"${String(e.pattern).substring(0,40)}"${b.reset}`:"",g=h>1?`${d} match${d!==1?"es":""} in ${h} files${m}`:`${d} match${d!==1?"es":""}${m}`,k=e.path?`
51
- ${b.subtle}path:${b.reset} ${b.muted}${String(e.path).substring(0,70)}${b.reset}`:"",v=c.slice(0,5).map((E,S)=>S===0?`${g}${k}
52
- ${$(E)}`:` ${$(E)}`),A=c.length-5;A>0&&v.push(` ${b.subtle}\u2026 +${A} more matches${b.reset}`),a=v.join(`
53
- `)}break}case"glob":{let u=e.pattern?` ${b.muted}${String(e.pattern).substring(0,50)}${b.reset}`:"";if(n==="(no matches)")a=`No files found${u}`;else{let c=require("path"),d=n.split(`
54
- `).filter(Boolean),f=d.length,h=d.slice(0,8),m=f-h.length,g=h.map(k=>` ${b.muted}${k}${b.reset}`);m>0&&g.push(` ${b.subtle}\u2026 +${m} more files${b.reset}`);let $=e.path?`
46
+ `),d=u.length,f=c.length,h=e.path?Zr(e.path):null,m=h?` ${b.muted}${h}${b.reset}`:"",g=nl(e.path,e.old_text,e.new_text,{indent:" ",maxLines:4,maxContent:96});a=`${b.diff_rem}\u2212${d}${b.reset} ${b.diff_add}+${f}${b.reset}${m}`+(g?`
47
+ `+g:"");break}case"patch_file":{let u=e.patches||[],c=u.reduce((g,$)=>g+($.old_text||"").split(`
48
+ `).length,0),d=u.reduce((g,$)=>g+($.new_text||"").split(`
49
+ `).length,0),f=e.path?Zr(e.path):null,h=f?` ${b.muted}${f}${b.reset}`:"";a=`${u.length} patch${u.length!==1?"es":""} ${b.diff_rem}\u2212${c}${b.reset} ${b.diff_add}+${d}${b.reset}${h}`;let m=ef(e.path,u,{indent:" ",maxPatches:3,maxLinesPerSide:2,maxContent:92});m&&(a+=`
50
+ ${m}`);break}case"bash":{let c=s.match(/^EXIT (\d+)/),d=s.split(`
51
+ `).filter(g=>g&&!g.startsWith("EXIT ")&&!g.startsWith("HINT:")&&g.trim()),f=c?c[1]==="0"?`${b.success}\u2713${b.reset}`:`${b.error}\u2717 Exit ${c[1]}${b.reset}`:`${b.success}\u2713${b.reset}`,h=s.match(/\nHINT: (.+)/);if(h)a=`${f} ${b.muted}\u2014 ${h[1].substring(0,100)}${b.reset}`;else if(d.length===0)a=f;else{let g=c&&c[1]!=="0",$=g?d.slice(-3):d.slice(0,3),x=d.length-3,E=$.map((N,v)=>v===0?`${f} ${b.muted}${N.substring(0,120)}${b.reset}`:` ${b.muted}${N.substring(0,120)}${b.reset}`);if(x>0){let N=g?` ${b.subtle}${x} lines above\u2026${b.reset}`:` ${b.subtle}\u2026 +${x} lines${b.reset}`;g?E.unshift(N):E.push(N)}a=E.join(`
52
+ `)}let m=Qd(e.command,{indent:" ",maxLines:2,maxContent:108});m&&(a=`${m}
53
+ ${a}`);break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")a=`No matches${e.pattern?` ${b.muted}"${String(e.pattern).substring(0,40)}"${b.reset}`:""}`;else{let $=function(v){let S=v.indexOf(":");if(S===-1)return`${b.muted}${v.substring(0,90)}${b.reset}`;let P=v.substring(0,S),ne=v.substring(S+1),re=ne.match(/^(\d+)[:-](.*)/s),ce=re?`:${re[1]}`:"",de=(re?re[2]:ne).trim(),oe=`${b.subtle}${u.basename(P)}${ce}${b.reset}`,le=`${b.muted}${de.substring(0,80)}${de.length>80?"\u2026":""}${b.reset}`;return`${oe} ${le}`};var l=$;let u=require("path"),c=s.split(`
54
+ `).filter(Boolean),d=c.length,h=new Set(c.map(v=>v.split(":")[0]).filter(Boolean)).size,m=e.pattern?` ${b.muted}"${String(e.pattern).substring(0,40)}"${b.reset}`:"",g=h>1?`${d} match${d!==1?"es":""} in ${h} files${m}`:`${d} match${d!==1?"es":""}${m}`,x=e.path?`
55
+ ${b.subtle}path:${b.reset} ${b.muted}${String(e.path).substring(0,70)}${b.reset}`:"",E=c.slice(0,5).map((v,S)=>S===0?`${g}${x}
56
+ ${$(v)}`:` ${$(v)}`),N=c.length-5;N>0&&E.push(` ${b.subtle}\u2026 +${N} more matches${b.reset}`),a=E.join(`
57
+ `)}break}case"glob":{let u=e.pattern?` ${b.muted}${String(e.pattern).substring(0,50)}${b.reset}`:"";if(s==="(no matches)")a=`No files found${u}`;else{let c=require("path"),d=s.split(`
58
+ `).filter(Boolean),f=d.length,h=d.slice(0,8),m=f-h.length,g=h.map(x=>` ${b.muted}${x}${b.reset}`);m>0&&g.push(` ${b.subtle}\u2026 +${m} more files${b.reset}`);let $=e.path?`
55
59
  ${b.subtle}path:${b.reset} ${b.muted}${String(e.path).substring(0,70)}${b.reset}`:"";a=`${f} file${f!==1?"s":""}${u}${$}`+(g.length>0?`
56
60
  ${g.join(`
57
- `)}`:"")}break}case"list_directory":{if(n==="(empty)")a="0 entries";else{let u=n.split(`
58
- `).filter(Boolean),c=u.length,d=u.slice(0,6).join(", "),f=c-6;a=f>0?`${c} entries \u2014 ${b.muted}${d}, +${f} more${b.reset}`:`${c} entr${c!==1?"ies":"y"} \u2014 ${b.muted}${d}${b.reset}`}break}case"git_status":{let u=n.match(/Branch:\s*(\S+)/),c=n.split(`
59
- `).filter(d=>/^\s*[MADRCU?!]/.test(d)).length;a=u?`${u[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let u=(n.match(/^\+[^+]/gm)||[]).length,c=(n.match(/^-[^-]/gm)||[]).length;a=u||c?`+${u} \u2212${c} lines`:"No diff";break}case"git_log":{let u=n.split(`
60
- `).filter(h=>/^commit\s+[0-9a-f]{7}/.test(h)),c=u.length,d=u[0]?u[0].replace(/^commit\s+/,"").substring(0,7):null,f=(()=>{let h=n.indexOf(u[0]||"\0");return h===-1?null:n.substring(h).split(`
61
- `).find((g,$)=>$>0&&g.trim()&&!g.startsWith("Author:")&&!g.startsWith("Date:")&&!g.startsWith("Merge:"))})();if(c===0)a="Log retrieved";else if(d&&f){let h=c>1?` ${b.muted}+${c-1} more${b.reset}`:"";a=`${d} ${b.muted}${f.trim().substring(0,60)}${b.reset}${h}`}else a=`${c} commit${c!==1?"s":""}`;break}case"git_commit":{let u=n.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=n.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);a=u?`${u[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let u=n.match(/(?:->|→)\s*(\S+)/);a=u?`\u2192 ${u[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(n))a="Already up to date";else{let u=(n.match(/^\+/gm)||[]).length;a=u>0?`Pulled \xB7 +${u} lines`:"Pulled"}break}case"web_fetch":{let u=n.match(/<title[^>]*>([^<]{1,80})<\/title>/i),c=n.match(/^#\s+(.{1,80})/m),d=e.url||"",f="";try{f=new URL(d).hostname}catch{f=d.substring(0,60)}let h=u?u[1].trim():c?c[1].trim():null;a=h?`${f} \u2014 ${b.muted}${h.substring(0,70)}${b.reset}`:`Fetched ${f}`;break}case"web_search":{let u=n.split(`
61
+ `)}`:"")}break}case"list_directory":{if(s==="(empty)")a="0 entries";else{let u=s.split(`
62
+ `).filter(Boolean),c=u.length,d=u.slice(0,6).join(", "),f=c-6;a=f>0?`${c} entries \u2014 ${b.muted}${d}, +${f} more${b.reset}`:`${c} entr${c!==1?"ies":"y"} \u2014 ${b.muted}${d}${b.reset}`}break}case"git_status":{let u=s.match(/Branch:\s*(\S+)/),c=s.split(`
63
+ `).filter(d=>/^\s*[MADRCU?!]/.test(d)).length;a=u?`${u[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let u=(s.match(/^\+[^+]/gm)||[]).length,c=(s.match(/^-[^-]/gm)||[]).length;a=u||c?`+${u} \u2212${c} lines`:"No diff";break}case"git_log":{let u=s.split(`
64
+ `).filter(h=>/^commit\s+[0-9a-f]{7}/.test(h)),c=u.length,d=u[0]?u[0].replace(/^commit\s+/,"").substring(0,7):null,f=(()=>{let h=s.indexOf(u[0]||"\0");return h===-1?null:s.substring(h).split(`
65
+ `).find((g,$)=>$>0&&g.trim()&&!g.startsWith("Author:")&&!g.startsWith("Date:")&&!g.startsWith("Merge:"))})();if(c===0)a="Log retrieved";else if(d&&f){let h=c>1?` ${b.muted}+${c-1} more${b.reset}`:"";a=`${d} ${b.muted}${f.trim().substring(0,60)}${b.reset}${h}`}else a=`${c} commit${c!==1?"s":""}`;break}case"git_commit":{let u=s.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=s.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);a=u?`${u[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let u=s.match(/(?:->|→)\s*(\S+)/);a=u?`\u2192 ${u[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(s))a="Already up to date";else{let u=(s.match(/^\+/gm)||[]).length;a=u>0?`Pulled \xB7 +${u} lines`:"Pulled"}break}case"web_fetch":{let u=s.match(/<title[^>]*>([^<]{1,80})<\/title>/i),c=s.match(/^#\s+(.{1,80})/m),d=e.url||"",f="";try{f=new URL(d).hostname}catch{f=d.substring(0,60)}let h=u?u[1].trim():c?c[1].trim():null;a=h?`${f} \u2014 ${b.muted}${h.substring(0,70)}${b.reset}`:`Fetched ${f}`;break}case"web_search":{let u=s.split(`
62
66
 
63
67
  `).filter(Boolean),c=u.length,d=u[0]?u[0].split(`
64
- `)[0].replace(/^\d+\.\s*/,"").trim():null,f=d?` ${b.muted}\u2014 ${d.substring(0,70)}${b.reset}`:"";a=`${c} result${c!==1?"s":""}${f}`;break}case"task_list":a="Done";break;case"spawn_agents":{if(n.includes("Background agents started")){let d=n.match(/\bbg-[\w-]+/g),f=d?d.length:0;a=`${f} bg agent${f!==1?"s":""} started`;break}let u=(n.match(/✓ Agent/g)||[]).length,c=(n.match(/✗ Agent/g)||[]).length;a=c>0?`${u} done, ${c} failed`:`${u} agent${u!==1?"s":""} done`;break}case"switch_model":{let u=n.match(/Switched to (.+)/);a=u?`\u2192 ${u[1]}`:"Done";break}case"ssh_exec":{let c=n.startsWith("EXIT ")||n.startsWith("Command failed"),d=n.split(`
65
- `).filter(h=>h.trim()&&!h.startsWith("EXIT ")),f=c?`${b.error}\u2717${b.reset}`:`${b.success}\u2713${b.reset}`;if(d.length===0)a=f;else{if(d.length>2&&d.every(k=>/^\[/.test(k.trim()))){a=`${f} ${d.length} log lines`;break}let m=c?d.slice(-3):d.slice(0,3),g=d.length-3,$=m.map((k,v)=>v===0?`${f} ${b.muted}${k.substring(0,120)}${b.reset}`:` ${b.muted}${k.substring(0,120)}${b.reset}`);if(g>0){let k=c?` ${b.subtle}${g} lines above\u2026${b.reset}`:` ${b.subtle}\u2026 +${g} lines${b.reset}`;c?$.unshift(k):$.push(k)}a=$.join(`
66
- `)}break}default:{let u=n.split(`
67
- `).filter(c=>c.trim()&&!c.startsWith("EXIT ")&&!c.startsWith("HINT:"));if(u.length>0){let c=u[0].trim().substring(0,90),d=u.length>1?` ${b.subtle}\u2026 +${u.length-1} lines${b.reset}`:"";a=`${b.muted}${c}${b.reset}${d}`}else a=`${r.label} complete`}}return`${i}${a}${b.reset}`}function Zw(t,e,s,o,n,r){let i=Math.round(o/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,l=`
68
- ${b.success}\u25C6${Pe.reset} ${Pe.bold}${t}${Pe.reset}`;return l+=` ${b.subtle}\u2501\u2501${b.reset} ${Pe.dim}${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),n.size>0&&(l+=` \xB7 ${n.size} scanned`),l+=Pe.reset,l}Bd.exports={C:Pe,formatToolCall:Gw,formatResult:Yw,getToolSpinnerText:Vw,formatToolSummary:Jw,formatSectionHeader:Hw,formatMilestone:Zw,getThinkingVerb:Xw,setActiveModelForSpinner:Kw,THINKING_VERBS:Jr}});var ot=V((W1,Hd)=>{var{T:tn}=Gt(),Za=tn,Qw=require("path"),Wd=["01100110","01111110","01111110","01011010","01111110","00111100"];function e$(t,e){let s=[];for(let o=0;o<t.length;o+=2){let n="";for(let r=0;r<t[0].length;r++){let i=t[o][r]==="1",a=o+1<t.length&&t[o+1][r]==="1";i&&a?n+=`${e}\u2588\x1B[0m`:i&&!a?n+=`${e}\u2580\x1B[0m`:!i&&a?n+=`${e}\u2584\x1B[0m`:n+=" "}s.push(n)}return s}function t$(t,e,s={}){let o=Za.bold,n=Za.reset,r=e$(Wd,tn.banner_logo),i=s.yolo?` ${o}${tn.banner_yolo}\u26A1 YOLO${n}`:"",a=s.gemini?` ${o}${tn.banner_gemini}\u2726 GEMINI${n}`:"",l=Ya().version,u=e?Qw.basename(e):null,c=`${tn.banner_model}[${t||"model"}]${n}`,d=`${tn.banner_version}[${u||"workspace"}]${n}`,f=[` ${tn.banner_name}${o}nex-code${n} ${tn.banner_version}v${l}${n}`,` ${c} ${d}`,` ${tn.banner_logo}${o}terminal workbench${n} ${tn.muted}\xB7 /help${n}${a}${i}`,""],h=Math.max(r.length,f.length),m=Math.floor((h-r.length)/2),g=Math.floor((h-f.length)/2),$=Wd[0].length,k=[];for(let v=0;v<h;v++){let A=r[v-m]??" ".repeat($),E=f[v-g]??"";k.push(A+E)}console.log(`
69
- `+k.join(`
68
+ `)[0].replace(/^\d+\.\s*/,"").trim():null,f=d?` ${b.muted}\u2014 ${d.substring(0,70)}${b.reset}`:"";a=`${c} result${c!==1?"s":""}${f}`;break}case"task_list":a="Done";break;case"spawn_agents":{if(s.includes("Background agents started")){let d=s.match(/\bbg-[\w-]+/g),f=d?d.length:0;a=`${f} bg agent${f!==1?"s":""} started`;break}let u=(s.match(/✓ Agent/g)||[]).length,c=(s.match(/✗ Agent/g)||[]).length;a=c>0?`${u} done, ${c} failed`:`${u} agent${u!==1?"s":""} done`;break}case"switch_model":{let u=s.match(/Switched to (.+)/);a=u?`\u2192 ${u[1]}`:"Done";break}case"ssh_exec":{let c=s.startsWith("EXIT ")||s.startsWith("Command failed"),d=s.split(`
69
+ `).filter(h=>h.trim()&&!h.startsWith("EXIT ")),f=c?`${b.error}\u2717${b.reset}`:`${b.success}\u2713${b.reset}`;if(d.length===0)a=f;else{if(d.length>2&&d.every(x=>/^\[/.test(x.trim()))){a=`${f} ${d.length} log lines`;break}let m=c?d.slice(-3):d.slice(0,3),g=d.length-3,$=m.map((x,E)=>E===0?`${f} ${b.muted}${x.substring(0,120)}${b.reset}`:` ${b.muted}${x.substring(0,120)}${b.reset}`);if(g>0){let x=c?` ${b.subtle}${g} lines above\u2026${b.reset}`:` ${b.subtle}\u2026 +${g} lines${b.reset}`;c?$.unshift(x):$.push(x)}a=$.join(`
70
+ `)}break}default:{let u=s.split(`
71
+ `).filter(c=>c.trim()&&!c.startsWith("EXIT ")&&!c.startsWith("HINT:"));if(u.length>0){let c=u[0].trim().substring(0,90),d=u.length>1?` ${b.subtle}\u2026 +${u.length-1} lines${b.reset}`:"";a=`${b.muted}${c}${b.reset}${d}`}else a=`${r.label} complete`}}return`${i}${a}${b.reset}`}function k$(t,e,n,o,s,r){let i=Math.round(o/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,l=`
72
+ ${b.success}\u25C6${Le.reset} ${Le.bold}${t}${Le.reset}`;return l+=` ${b.subtle}\u2501\u2501${b.reset} ${Le.dim}${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),s.size>0&&(l+=` \xB7 ${s.size} scanned`),l+=Le.reset,l}tf.exports={C:Le,formatToolCall:g$,formatResult:y$,getToolSpinnerText:_$,formatToolSummary:x$,formatSectionHeader:m$,formatMilestone:k$,getThinkingVerb:b$,setActiveModelForSpinner:$$,THINKING_VERBS:Qr}});var it=Z((AC,of)=>{var{T:on}=zt(),sl=on,S$=require("path"),sf=["01100110","01111110","01111110","01011010","01111110","00111100"];function v$(t,e){let n=[];for(let o=0;o<t.length;o+=2){let s="";for(let r=0;r<t[0].length;r++){let i=t[o][r]==="1",a=o+1<t.length&&t[o+1][r]==="1";i&&a?s+=`${e}\u2588\x1B[0m`:i&&!a?s+=`${e}\u2580\x1B[0m`:!i&&a?s+=`${e}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function E$(t,e,n={}){let o=sl.bold,s=sl.reset,r=v$(sf,on.banner_logo),i=n.yolo?` ${o}${on.banner_yolo}\u26A1 YOLO${s}`:"",a=n.gemini?` ${o}${on.banner_gemini}\u2726 GEMINI${s}`:"",l=Ka().version,u=e?S$.basename(e):null,c=`${on.banner_model}[${t||"model"}]${s}`,d=`${on.banner_version}[${u||"workspace"}]${s}`,f=[` ${on.banner_name}${o}nex-code${s} ${on.banner_version}v${l}${s}`,` ${c} ${d}`,` ${on.banner_logo}${o}terminal workbench${s} ${on.muted}\xB7 /help${s}${a}${i}`,""],h=Math.max(r.length,f.length),m=Math.floor((h-r.length)/2),g=Math.floor((h-f.length)/2),$=sf[0].length,x=[];for(let E=0;E<h;E++){let N=r[E-m]??" ".repeat($),v=f[E-g]??"";x.push(N+v)}console.log(`
73
+ `+x.join(`
70
74
  `)+`
71
- `)}var{Spinner:n$,MultiProgress:s$,TaskProgress:o$,ToolProgress:r$,setActiveTaskProgress:i$,getActiveTaskProgress:a$,cleanupTerminal:l$}=Yn(),{formatToolCall:c$,formatResult:u$,getToolSpinnerText:d$,formatToolSummary:f$,formatSectionHeader:h$,formatMilestone:p$,getThinkingVerb:m$,setActiveModelForSpinner:g$}=Ud();Hd.exports={C:Za,banner:t$,Spinner:n$,MultiProgress:s$,TaskProgress:o$,ToolProgress:r$,setActiveTaskProgress:i$,getActiveTaskProgress:a$,cleanupTerminal:l$,formatToolCall:c$,formatResult:u$,getToolSpinnerText:d$,formatToolSummary:f$,formatSectionHeader:h$,formatMilestone:p$,getThinkingVerb:m$,setActiveModelForSpinner:g$}});var el=V((H1,Gd)=>{function Qa(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var y$=Qa();function w$(...t){Qa()&&console.log(...t)}function $$(...t){Qa()&&console.warn(...t)}Gd.exports={DEBUG:y$,debugLog:w$,warnLog:$$}});var Kd=V((G1,zd)=>{"use strict";var b$=new Set(["read_file","grep","glob","search_files","list_directory"]),_$=new Set(["write_file","edit_file","patch_file"]),k$=new Set(["bash"]),x$=new Set(["web_search","web_fetch","perplexity_search"]);function Yd(t,e){let s=0,o=0,n=0,r=0,i=0;for(let[a,l]of t)i+=l,b$.has(a)&&(s+=l),_$.has(a)&&(o+=l),k$.has(a)&&(n+=l),x$.has(a)&&(r+=l);return i===0?`Phase ${e}`:r/i>.5?"Research":s/i>.5?"Exploration":o/i>.3?"Implementation":n/i>.3&&o/i<.15?"Verification":`Phase ${e}`}var tl=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,o,n){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:Yd(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(o),filesModified:new Set(n)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};zd.exports={MilestoneTracker:tl,_phaseName:Yd}});var Zr=V((Y1,Xd)=>{var _o=ut(),S$={"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 v$(){return _o.getActiveModel()}function E$(t){return _o.setActiveModel(t)}function T$(){return _o.getModelNames()}function R$(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let o=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(o)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let o=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(o)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function C$(t,e){let{C:s}=ot(),{Spinner:o}=ot(),n=new o("Thinking...");n.start();let r=!0,i="";try{let a=await _o.callStream(t,e,{onToken:l=>{r&&(n.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?n.stop():process.stdout.write(`${s.reset}
72
- `),a}catch(a){throw n.stop(),a}}async function A$(t,e){return _o.callChat(t,e)}Xd.exports={MODELS:S$,getActiveModel:v$,setActiveModel:E$,getModelNames:T$,callOllamaStream:C$,callOllama:A$,parseToolArgs:R$}});var xo=V((z1,tf)=>{var O$=require("readline"),{C:nn}=ot(),N$=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,M$=/^=([\w-]+)/;function ko(t){return typeof t!="string"?t:t.replace(N$,"").replace(M$,"$1")}var ol=[/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/],Vd=[...ol,/\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 P$(t){for(let e of Vd)if(e.test(t))return e;return null}var Jd=[/\.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)/],L$=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,nl=[/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 Zd(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let o=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(o.length===0)return!1;let n=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(u=>u.trim()).filter(Boolean).every(u=>n(u)):nl.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:nl.some(a=>a.test(i))};return o.every(n)}var rl=[/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/],Qd=[/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/],ef=[...rl,...Qd],il=!1,Kn=null,sl=null;function I$(t){il=t}function j$(t){sl=t}function D$(){return il}function q$(t){Kn=t}function F$(t){let e=ko(t);for(let s of ol)if(s.test(e))return s;return null}function B$(t){let e=ko(t);if(/ssh\s/.test(e)&&Zd(e))return!1;for(let s of ef)if(s.test(e))return!0;return!1}function U$(t){let e=ko(t);for(let s of rl)if(s.test(e))return!0;return!1}function W$(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=ko(t);if(!L$.test(e))return null;for(let s of Jd)if(s.test(e))return s;return null}function H$(t,e={}){if(il)return Promise.resolve(!0);if(sl)return sl(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return G$(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let n=0;Kn&&Kn.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${nn.yellow}${t}${nn.reset}`;for(let h=0;h<s.length;h++){let m=h===n,g=m?`${nn.yellow}\u276F${nn.reset}`:" ",$=m?`${nn.yellow}${s[h]}${nn.reset}`:s[h];f+=`\x1B[${d+1+h};1H\x1B[2K ${g} ${$}`}r(f)},l=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",c);let f=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),m="";for(let g=0;g<s.length+1;g++)m+=`\x1B[${h+g};1H\x1B[2K`;f(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Kn&&Kn.resume(),o(d)},u=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&Qr(e.toolName),l(!0)},c=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
73
- `){u(n);return}if(f==="\x1B[A"){n=(n-1+s.length)%s.length,a();return}if(f==="\x1B[B"){n=(n+1)%s.length,a();return}let h=f.toLowerCase().trim();if(h==="y"){l(!0);return}if(h==="n"){l(!1);return}if(h==="a"&&e.toolName){Qr(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",c)})}function G$(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let n=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Qr(e.toolName),o(!0)):o(i!=="n")};if(Kn)Kn.question(`${nn.yellow}${t} ${s}${nn.reset}`,n);else{let r=O$.createInterface({input:process.stdin,output:process.stdout});r.question(`${nn.yellow}${t} ${s}${nn.reset}`,i=>{r.close(),n(i)})}})}var Qr=()=>{};function Y$(t){Qr=t}tf.exports={sanitizeBashCommand:ko,FORBIDDEN_PATTERNS:ol,SSH_FORBIDDEN_PATTERNS:Vd,BASH_PROTECTED_PATHS:Jd,SSH_SAFE_PATTERNS:nl,isSSHReadOnly:Zd,DANGEROUS_BASH:ef,CRITICAL_BASH:rl,NOTABLE_BASH:Qd,isForbidden:F$,isSSHForbidden:P$,isDangerous:B$,isCritical:U$,isBashPathForbidden:W$,confirm:H$,setAutoConfirm:I$,getAutoConfirm:D$,setConfirmHook:j$,setReadlineInterface:q$,setAllowAlwaysHandler:Y$}});var of=V((X1,sf)=>{var ei=require("path"),{C:F}=ot(),{T:al,isDark:K1}=Gt(),{confirm:z$,getAutoConfirm:K$}=xo(),nf=2e3;function So(t,e){let s=t.split(`
75
+ `)}var{Spinner:T$,MultiProgress:R$,TaskProgress:C$,ToolProgress:A$,setActiveTaskProgress:O$,getActiveTaskProgress:N$,cleanupTerminal:P$}=zn(),{formatToolCall:M$,formatResult:L$,getToolSpinnerText:I$,formatToolSummary:j$,formatSectionHeader:D$,formatMilestone:q$,getThinkingVerb:F$,setActiveModelForSpinner:B$}=nf();of.exports={C:sl,banner:E$,Spinner:T$,MultiProgress:R$,TaskProgress:C$,ToolProgress:A$,setActiveTaskProgress:O$,getActiveTaskProgress:N$,cleanupTerminal:P$,formatToolCall:M$,formatResult:L$,getToolSpinnerText:I$,formatToolSummary:j$,formatSectionHeader:D$,formatMilestone:q$,getThinkingVerb:F$,setActiveModelForSpinner:B$}});var rl=Z((OC,rf)=>{function ol(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var U$=ol();function W$(...t){ol()&&console.log(...t)}function H$(...t){ol()&&console.warn(...t)}rf.exports={DEBUG:U$,debugLog:W$,warnLog:H$}});var cf=Z((NC,lf)=>{"use strict";var Y$=new Set(["read_file","grep","glob","search_files","list_directory"]),G$=new Set(["write_file","edit_file","patch_file"]),z$=new Set(["bash"]),K$=new Set(["web_search","web_fetch","perplexity_search"]);function af(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[a,l]of t)i+=l,Y$.has(a)&&(n+=l),G$.has(a)&&(o+=l),z$.has(a)&&(s+=l),K$.has(a)&&(r+=l);return i===0?`Phase ${e}`:r/i>.5?"Research":n/i>.5?"Exploration":o/i>.3?"Implementation":s/i>.3&&o/i<.15?"Verification":`Phase ${e}`}var il=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,n,o,s){if(this._disabled)return null;this._stepsThisPhase++;for(let i of n)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:af(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(o),filesModified:new Set(s)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};lf.exports={MilestoneTracker:il,_phaseName:af}});var ei=Z((PC,uf)=>{var ko=dt(),X$={"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 V$(){return ko.getActiveModel()}function J$(t){return ko.setActiveModel(t)}function Z$(){return ko.getModelNames()}function Q$(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let o=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(o)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let o=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(o)}catch{}let n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function eb(t,e){let{C:n}=it(),{Spinner:o}=it(),s=new o("Thinking...");s.start();let r=!0,i="";try{let a=await ko.callStream(t,e,{onToken:l=>{r&&(s.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?s.stop():process.stdout.write(`${n.reset}
76
+ `),a}catch(a){throw s.stop(),a}}async function tb(t,e){return ko.callChat(t,e)}uf.exports={MODELS:X$,getActiveModel:V$,setActiveModel:J$,getModelNames:Z$,callOllamaStream:eb,callOllama:tb,parseToolArgs:Q$}});var vo=Z((MC,gf)=>{var nb=require("readline"),{C:rn}=it(),sb=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,ob=/^=([\w-]+)/;function So(t){return typeof t!="string"?t:t.replace(sb,"").replace(ob,"$1")}var cl=[/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/],df=[...cl,/\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 rb(t){for(let e of df)if(e.test(t))return e;return null}var ff=[/\.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)/],ib=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,al=[/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 hf(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let o=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(o.length===0)return!1;let s=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(u=>u.trim()).filter(Boolean).every(u=>s(u)):al.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:al.some(a=>a.test(i))};return o.every(s)}var ul=[/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/],pf=[/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/],mf=[...ul,...pf],dl=!1,Xn=null,ll=null;function ab(t){dl=t}function lb(t){ll=t}function cb(){return dl}function ub(t){Xn=t}function db(t){let e=So(t);for(let n of cl)if(n.test(e))return n;return null}function fb(t){let e=So(t);if(/ssh\s/.test(e)&&hf(e))return!1;for(let n of mf)if(n.test(e))return!0;return!1}function hb(t){let e=So(t);for(let n of ul)if(n.test(e))return!0;return!1}function pb(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=So(t);if(!ib.test(e))return null;for(let n of ff)if(n.test(e))return n;return null}function mb(t,e={}){if(dl)return Promise.resolve(!0);if(ll)return ll(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return gb(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Xn&&Xn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-n.length-2)},a=()=>{let d=i();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${rn.yellow}${t}${rn.reset}`;for(let h=0;h<n.length;h++){let m=h===s,g=m?`${rn.yellow}\u276F${rn.reset}`:" ",$=m?`${rn.yellow}${n[h]}${rn.reset}`:n[h];f+=`\x1B[${d+1+h};1H\x1B[2K ${g} ${$}`}r(f)},l=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",c);let f=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),m="";for(let g=0;g<n.length+1;g++)m+=`\x1B[${h+g};1H\x1B[2K`;f(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Xn&&Xn.resume(),o(d)},u=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&ti(e.toolName),l(!0)},c=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
77
+ `){u(s);return}if(f==="\x1B[A"){s=(s-1+n.length)%n.length,a();return}if(f==="\x1B[B"){s=(s+1)%n.length,a();return}let h=f.toLowerCase().trim();if(h==="y"){l(!0);return}if(h==="n"){l(!1);return}if(h==="a"&&e.toolName){ti(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",c)})}function gb(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let s=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(ti(e.toolName),o(!0)):o(i!=="n")};if(Xn)Xn.question(`${rn.yellow}${t} ${n}${rn.reset}`,s);else{let r=nb.createInterface({input:process.stdin,output:process.stdout});r.question(`${rn.yellow}${t} ${n}${rn.reset}`,i=>{r.close(),s(i)})}})}var ti=()=>{};function yb(t){ti=t}gf.exports={sanitizeBashCommand:So,FORBIDDEN_PATTERNS:cl,SSH_FORBIDDEN_PATTERNS:df,BASH_PROTECTED_PATHS:ff,SSH_SAFE_PATTERNS:al,isSSHReadOnly:hf,DANGEROUS_BASH:mf,CRITICAL_BASH:ul,NOTABLE_BASH:pf,isForbidden:db,isSSHForbidden:rb,isDangerous:fb,isCritical:hb,isBashPathForbidden:pb,confirm:mb,setAutoConfirm:ab,getAutoConfirm:cb,setConfirmHook:lb,setReadlineInterface:ub,setAllowAlwaysHandler:yb}});var $f=Z((IC,wf)=>{var ni=require("path"),{C:D}=it(),{T:fl,isDark:LC}=zt(),{confirm:wb,getAutoConfirm:$b}=vo(),yf=2e3;function Eo(t,e){let n=t.split(`
74
78
  `),o=e.split(`
75
- `),n=[],r=s.length,i=o.length;if(r>nf||i>nf){for(let d of s)n.push({type:"remove",line:d});for(let d of o)n.push({type:"add",line:d});return n}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]===o[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,u=i,c=[];for(;l>0||u>0;)l>0&&u>0&&s[l-1]===o[u-1]?(c.unshift({type:"same",line:s[l-1]}),l--,u--):u>0&&(l===0||a[l][u-1]>=a[l-1][u])?(c.unshift({type:"add",line:o[u-1]}),u--):(c.unshift({type:"remove",line:s[l-1]}),l--);return c}function X$(t,e,s,o=3){console.log(`
76
- ${F.bold}${F.cyan} Diff: ${t}${F.reset}`);let n=So(e,s),r=[];if(n.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${F.gray} (no changes)${F.reset}`);return}let i=Math.max(0,r[0]-o),a=Math.min(n.length,r[r.length-1]+o+1);i>0&&console.log(`${F.gray} ...${F.reset}`);for(let l=i;l<a;l++){let u=n[l];switch(u.type){case"remove":console.log(`${F.red} - ${u.line}${F.reset}`);break;case"add":console.log(`${F.green} + ${u.line}${F.reset}`);break;default:console.log(`${F.gray} ${u.line}${F.reset}`)}}a<n.length&&console.log(`${F.gray} ...${F.reset}`),console.log()}function V$(t,e,s){console.log(`
77
- ${F.bold}${F.cyan} File exists \u2014 showing changes: ${t}${F.reset}`);let o=So(e,s),n=0;for(let i of o)i.type!=="same"&&n++;if(n===0){console.log(`${F.gray} (identical content)${F.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${F.gray} ...(${n-r} more changes)${F.reset}`);break}switch(i.type){case"remove":console.log(`${F.red} - ${i.line}${F.reset}`),r++;break;case"add":console.log(`${F.green} + ${i.line}${F.reset}`),r++;break;default:r>0&&console.log(`${F.gray} ${i.line}${F.reset}`)}}console.log()}function J$(t,e){console.log(`
78
- ${F.bold}${F.cyan} New file: ${t}${F.reset}`);let s=e.split(`
79
- `),o=s.slice(0,20);for(let n of o)console.log(`${F.green} + ${n}${F.reset}`);s.length>20&&console.log(`${F.gray} ...+${s.length-20} more lines${F.reset}`),console.log()}async function Z$(t){return K$()?!0:z$(` ${t}?`)}function Q$(t,e,s,o){let n=o||process.stdout.columns||80,r=Math.floor((n-3)/2);console.log(`
80
- ${F.bold}${F.cyan} Side-by-side: ${t}${F.reset}`),console.log(` ${F.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${F.reset}`);let i=So(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 h=[];for(;l<i.length&&i[l].type==="remove";)h.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(h.length,m.length);for(let $=0;$<g;$++)a.push({left:$<h.length?h[$]:"",right:$<m.length?m[$]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let u=a.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${F.gray}(no changes)${F.reset}`);return}let c=Math.max(0,u[0]-2),d=Math.min(a.length,u[u.length-1]+3),f=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};c>0&&console.log(` ${F.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${F.reset}`);for(let h=c;h<d;h++){let m=a[h];if(m.type==="same")console.log(` ${F.gray}${f(m.left,r)}${F.reset}\u2502${F.gray}${f(m.right,r)}${F.reset}`);else{let g=m.left?`${F.red}${f(m.left,r)}${F.reset}`:`${f("",r)}`,$=m.right?`${F.green}${f(m.right,r)}${F.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${$}`)}}d<a.length&&console.log(` ${F.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${F.reset}`),console.log(` ${F.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${F.reset}
81
- `)}function eb(t,e,s,o={}){let n=o.label||"Update",r=o.context||3,i=o.annotations||[],a=ei.isAbsolute(t)?ei.relative(process.cwd(),t):t,l=So(e,s),u=1,c=1;for(let N of l)N.type==="same"?(N.oldLine=u++,N.newLine=c++):N.type==="remove"?(N.oldLine=u++,N.newLine=null):(N.oldLine=null,N.newLine=c++);let d=0,f=0;for(let N of l)N.type==="add"?d++:N.type==="remove"&&f++;if(console.log(`
82
- ${F.green}\u23FA${F.reset} ${F.bold}${n}(${a})${F.reset}`),d===0&&f===0){console.log(` ${F.dim}\u23BF (no changes)${F.reset}
83
- `);return}let h=[];if(d>0&&h.push(`Added ${d} line${d!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let N=i.filter(ue=>ue.severity==="error").length,ee=i.filter(ue=>ue.severity==="warn").length,re=i.filter(ue=>ue.severity==="info").length,le=[];N>0&&le.push(`${F.red}${N} error${N!==1?"s":""}${F.dim}`),ee>0&&le.push(`${F.yellow}${ee} warning${ee!==1?"s":""}${F.dim}`),re>0&&le.push(`${F.cyan}${re} info${re!==1?"s":""}${F.dim}`),h.push(`found ${le.join(", ")}`)}console.log(` ${F.dim}\u23BF ${h.join(", ")}${F.reset}`);let g=[];l.forEach((N,ee)=>{N.type!=="same"&&g.push(ee)});let $=[],k=null,v=null;for(let N of g){let ee=Math.max(0,N-r),re=Math.min(l.length-1,N+r);k===null?(k=ee,v=re):(ee<=v+1||($.push([k,v]),k=ee),v=re)}k!==null&&$.push([k,v]);let A=" ",E=process.stdout.columns||120;function S(N,ee,re){let le=re.replace(/\x1b\[[0-9;]*m/g,""),ue=re+" ".repeat(Math.max(0,E-le.length));return`${N}${ee}${ue}${F.reset}`}for(let N=0;N<$.length;N++){N>0&&console.log(`${A}${F.dim}\xB7\xB7\xB7${F.reset}`);let[ee,re]=$[N];for(let le=ee;le<=re;le++){let ue=l[le],oe=ue.newLine!=null?ue.newLine:ue.oldLine,ae=String(oe).padStart(4),T=ue.type!=="remove"?i.filter(U=>U.line===ue.newLine):[];ue.type==="remove"?console.log(S(al.diff_rem_bg,F.red,`${A}${ae} - ${ue.line}`)):ue.type==="add"?console.log(S(al.diff_add_bg,F.green,`${A}${ae} + ${ue.line}`)):console.log(`${A}${F.dim}${ae} ${F.reset}${ue.line}`);for(let U of T){let Z=F.cyan,ye="\u2139";U.severity==="error"?(Z=F.red,ye="\u2716"):U.severity==="warn"&&(Z=F.yellow,ye="\u26A0"),console.log(`${A} ${Z}${ye} ${U.message}${F.reset}`)}}}console.log()}function tb(t,e,s={}){let o=ei.isAbsolute(t)?ei.relative(process.cwd(),t):t,n=e.split(`
84
- `),r=s.annotations||[];console.log(`
85
- ${F.green}\u23FA${F.reset} ${F.bold}Create(${o})${F.reset}`);let i=[`${n.length} line${n.length!==1?"s":""}`];if(r.length>0){let d=r.filter(g=>g.severity==="error").length,f=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,m=[];d>0&&m.push(`${F.red}${d} error${d!==1?"s":""}${F.dim}`),f>0&&m.push(`${F.yellow}${f} warning${f!==1?"s":""}${F.dim}`),h>0&&m.push(`${F.cyan}${h} info${h!==1?"s":""}${F.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${F.dim}\u23BF ${i.join(", ")}${F.reset}`);let l=" ",u=process.stdout.columns||120,c=Math.min(n.length,20);for(let d=0;d<c;d++){let f=String(d+1).padStart(4),h=d+1,m=r.filter(v=>v.line===h),g=`${l}${f} + ${n[d]}`,$=g.replace(/\x1b\[[0-9;]*m/g,""),k=g+" ".repeat(Math.max(0,u-$.length));console.log(`${al.diff_add_bg}${F.green}${k}${F.reset}`);for(let v of m){let A=F.cyan,E="\u2139";v.severity==="error"?(A=F.red,E="\u2716"):v.severity==="warn"&&(A=F.yellow,E="\u26A0"),console.log(`${l} ${A}${E} ${v.message}${F.reset}`)}}n.length>20&&console.log(`${l}${F.dim} ...+${n.length-20} more lines${F.reset}`),console.log()}sf.exports={diffLines:So,showEditDiff:X$,showWriteDiff:V$,showNewFilePreview:J$,confirmFileChange:Z$,showSideBySideDiff:Q$,showDiff:eb,showNewFile:tb}});var si=V((V1,lf)=>{var rf=require("util").promisify(require("child_process").exec),nb=require("util").promisify(require("child_process").execFile),{C:Be}=ot();async function ll(t){try{let{stdout:e}=await rf(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function ti(...t){try{let{stdout:e}=await nb("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function sb(){return await ll("git rev-parse --is-inside-work-tree")==="true"}async function ob(){return await ll("git branch --show-current")}async function cl(){try{let{stdout:t}=await rf("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
86
- `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),o=e.substring(3);return{status:s,file:o}})}catch{return[]}}async function ni(t=!1){return await ll(`git diff ${t?"--cached":""}`)||""}async function ul(){return(await cl()).map(e=>e.file)}async function af(){let t=await ul();if(t.length===0)return null;let e=await ni(),o=await ni(!0)||e,n=0,r=0;if(o){let c=o.split(`
87
- `);for(let d of c)d.startsWith("+")&&!d.startsWith("+++")&&n++,d.startsWith("-")&&!d.startsWith("---")&&r++}else n=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":n>r*2?i="feat":r>n?i="refactor":i="fix";let l=t.slice(0,3).map(c=>c.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:n,deletions:r}}}async function rb(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await ti("checkout","-b",s)!==null?s:null}async function ib(t){return await ti("add","-A"),await ti("commit","-m",t)?await ti("rev-parse","--short","HEAD"):null}async function ab(){let t=await af();if(!t)return`${Be.dim}No changes${Be.reset}`;let e=[];e.push(`
88
- ${Be.bold}${Be.cyan}Git Diff Summary:${Be.reset}`),e.push(` ${Be.green}+${t.stats.additions}${Be.reset} ${Be.red}-${t.stats.deletions}${Be.reset} in ${t.files.length} file(s)`),e.push(`
89
- ${Be.bold}${Be.cyan}Files:${Be.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Be.dim}${s}${Be.reset}`);return t.files.length>20&&e.push(` ${Be.dim}...+${t.files.length-20} more${Be.reset}`),e.push(`
90
- ${Be.bold}${Be.cyan}Suggested message:${Be.reset}`),e.push(` ${Be.cyan}${t.summary}${Be.reset}
79
+ `),s=[],r=n.length,i=o.length;if(r>yf||i>yf){for(let d of n)s.push({type:"remove",line:d});for(let d of o)s.push({type:"add",line:d});return s}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++)n[d-1]===o[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,u=i,c=[];for(;l>0||u>0;)l>0&&u>0&&n[l-1]===o[u-1]?(c.unshift({type:"same",line:n[l-1]}),l--,u--):u>0&&(l===0||a[l][u-1]>=a[l-1][u])?(c.unshift({type:"add",line:o[u-1]}),u--):(c.unshift({type:"remove",line:n[l-1]}),l--);return c}function bb(t,e,n,o=3){console.log(`
80
+ ${D.bold}${D.cyan} Diff: ${t}${D.reset}`);let s=Eo(e,n),r=[];if(s.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${D.gray} (no changes)${D.reset}`);return}let i=Math.max(0,r[0]-o),a=Math.min(s.length,r[r.length-1]+o+1);i>0&&console.log(`${D.gray} ...${D.reset}`);for(let l=i;l<a;l++){let u=s[l];switch(u.type){case"remove":console.log(`${D.red} - ${u.line}${D.reset}`);break;case"add":console.log(`${D.green} + ${u.line}${D.reset}`);break;default:console.log(`${D.gray} ${u.line}${D.reset}`)}}a<s.length&&console.log(`${D.gray} ...${D.reset}`),console.log()}function _b(t,e,n){console.log(`
81
+ ${D.bold}${D.cyan} File exists \u2014 showing changes: ${t}${D.reset}`);let o=Eo(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${D.gray} (identical content)${D.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${D.gray} ...(${s-r} more changes)${D.reset}`);break}switch(i.type){case"remove":console.log(`${D.red} - ${i.line}${D.reset}`),r++;break;case"add":console.log(`${D.green} + ${i.line}${D.reset}`),r++;break;default:r>0&&console.log(`${D.gray} ${i.line}${D.reset}`)}}console.log()}function xb(t,e){console.log(`
82
+ ${D.bold}${D.cyan} New file: ${t}${D.reset}`);let n=e.split(`
83
+ `),o=n.slice(0,20);for(let s of o)console.log(`${D.green} + ${s}${D.reset}`);n.length>20&&console.log(`${D.gray} ...+${n.length-20} more lines${D.reset}`),console.log()}async function kb(t){return $b()?!0:wb(` ${t}?`)}function Sb(t,e,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
84
+ ${D.bold}${D.cyan} Side-by-side: ${t}${D.reset}`),console.log(` ${D.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${D.reset}`);let i=Eo(e,n),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 h=[];for(;l<i.length&&i[l].type==="remove";)h.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(h.length,m.length);for(let $=0;$<g;$++)a.push({left:$<h.length?h[$]:"",right:$<m.length?m[$]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let u=a.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${D.gray}(no changes)${D.reset}`);return}let c=Math.max(0,u[0]-2),d=Math.min(a.length,u[u.length-1]+3),f=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};c>0&&console.log(` ${D.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${D.reset}`);for(let h=c;h<d;h++){let m=a[h];if(m.type==="same")console.log(` ${D.gray}${f(m.left,r)}${D.reset}\u2502${D.gray}${f(m.right,r)}${D.reset}`);else{let g=m.left?`${D.red}${f(m.left,r)}${D.reset}`:`${f("",r)}`,$=m.right?`${D.green}${f(m.right,r)}${D.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${$}`)}}d<a.length&&console.log(` ${D.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${D.reset}`),console.log(` ${D.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${D.reset}
85
+ `)}function vb(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],a=ni.isAbsolute(t)?ni.relative(process.cwd(),t):t,l=Eo(e,n),u=1,c=1;for(let P of l)P.type==="same"?(P.oldLine=u++,P.newLine=c++):P.type==="remove"?(P.oldLine=u++,P.newLine=null):(P.oldLine=null,P.newLine=c++);let d=0,f=0;for(let P of l)P.type==="add"?d++:P.type==="remove"&&f++;if(console.log(`
86
+ ${D.green}\u23FA${D.reset} ${D.bold}${s}(${a})${D.reset}`),d===0&&f===0){console.log(` ${D.dim}\u23BF (no changes)${D.reset}
87
+ `);return}let h=[];if(d>0&&h.push(`Added ${d} line${d!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let P=i.filter(de=>de.severity==="error").length,ne=i.filter(de=>de.severity==="warn").length,re=i.filter(de=>de.severity==="info").length,ce=[];P>0&&ce.push(`${D.red}${P} error${P!==1?"s":""}${D.dim}`),ne>0&&ce.push(`${D.yellow}${ne} warning${ne!==1?"s":""}${D.dim}`),re>0&&ce.push(`${D.cyan}${re} info${re!==1?"s":""}${D.dim}`),h.push(`found ${ce.join(", ")}`)}console.log(` ${D.dim}\u23BF ${h.join(", ")}${D.reset}`);let g=[];l.forEach((P,ne)=>{P.type!=="same"&&g.push(ne)});let $=[],x=null,E=null;for(let P of g){let ne=Math.max(0,P-r),re=Math.min(l.length-1,P+r);x===null?(x=ne,E=re):(ne<=E+1||($.push([x,E]),x=ne),E=re)}x!==null&&$.push([x,E]);let N=" ",v=process.stdout.columns||120;function S(P,ne,re){let ce=re.replace(/\x1b\[[0-9;]*m/g,""),de=re+" ".repeat(Math.max(0,v-ce.length));return`${P}${ne}${de}${D.reset}`}for(let P=0;P<$.length;P++){P>0&&console.log(`${N}${D.dim}\xB7\xB7\xB7${D.reset}`);let[ne,re]=$[P];for(let ce=ne;ce<=re;ce++){let de=l[ce],oe=de.newLine!=null?de.newLine:de.oldLine,le=String(oe).padStart(4),T=de.type!=="remove"?i.filter(q=>q.line===de.newLine):[];de.type==="remove"?console.log(S(fl.diff_rem_bg,D.red,`${N}${le} - ${de.line}`)):de.type==="add"?console.log(S(fl.diff_add_bg,D.green,`${N}${le} + ${de.line}`)):console.log(`${N}${D.dim}${le} ${D.reset}${de.line}`);for(let q of T){let Q=D.cyan,we="\u2139";q.severity==="error"?(Q=D.red,we="\u2716"):q.severity==="warn"&&(Q=D.yellow,we="\u26A0"),console.log(`${N} ${Q}${we} ${q.message}${D.reset}`)}}}console.log()}function Eb(t,e,n={}){let o=ni.isAbsolute(t)?ni.relative(process.cwd(),t):t,s=e.split(`
88
+ `),r=n.annotations||[];console.log(`
89
+ ${D.green}\u23FA${D.reset} ${D.bold}Create(${o})${D.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let d=r.filter(g=>g.severity==="error").length,f=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,m=[];d>0&&m.push(`${D.red}${d} error${d!==1?"s":""}${D.dim}`),f>0&&m.push(`${D.yellow}${f} warning${f!==1?"s":""}${D.dim}`),h>0&&m.push(`${D.cyan}${h} info${h!==1?"s":""}${D.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${D.dim}\u23BF ${i.join(", ")}${D.reset}`);let l=" ",u=process.stdout.columns||120,c=Math.min(s.length,20);for(let d=0;d<c;d++){let f=String(d+1).padStart(4),h=d+1,m=r.filter(E=>E.line===h),g=`${l}${f} + ${s[d]}`,$=g.replace(/\x1b\[[0-9;]*m/g,""),x=g+" ".repeat(Math.max(0,u-$.length));console.log(`${fl.diff_add_bg}${D.green}${x}${D.reset}`);for(let E of m){let N=D.cyan,v="\u2139";E.severity==="error"?(N=D.red,v="\u2716"):E.severity==="warn"&&(N=D.yellow,v="\u26A0"),console.log(`${l} ${N}${v} ${E.message}${D.reset}`)}}s.length>20&&console.log(`${l}${D.dim} ...+${s.length-20} more lines${D.reset}`),console.log()}wf.exports={diffLines:Eo,showEditDiff:bb,showWriteDiff:_b,showNewFilePreview:xb,confirmFileChange:kb,showSideBySideDiff:Sb,showDiff:vb,showNewFile:Eb}});var ri=Z((jC,xf)=>{var bf=require("util").promisify(require("child_process").exec),Tb=require("util").promisify(require("child_process").execFile),{C:We}=it();async function hl(t){try{let{stdout:e}=await bf(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function si(...t){try{let{stdout:e}=await Tb("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Rb(){return await hl("git rev-parse --is-inside-work-tree")==="true"}async function Cb(){return await hl("git branch --show-current")}async function pl(){try{let{stdout:t}=await bf("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
90
+ `).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function oi(t=!1){return await hl(`git diff ${t?"--cached":""}`)||""}async function ml(){return(await pl()).map(e=>e.file)}async function _f(){let t=await ml();if(t.length===0)return null;let e=await oi(),o=await oi(!0)||e,s=0,r=0;if(o){let c=o.split(`
91
+ `);for(let d of c)d.startsWith("+")&&!d.startsWith("+++")&&s++,d.startsWith("-")&&!d.startsWith("---")&&r++}else s=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":s>r*2?i="feat":r>s?i="refactor":i="fix";let l=t.slice(0,3).map(c=>c.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:s,deletions:r}}}async function Ab(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await si("checkout","-b",n)!==null?n:null}async function Ob(t){return await si("add","-A"),await si("commit","-m",t)?await si("rev-parse","--short","HEAD"):null}async function Nb(){let t=await _f();if(!t)return`${We.dim}No changes${We.reset}`;let e=[];e.push(`
92
+ ${We.bold}${We.cyan}Git Diff Summary:${We.reset}`),e.push(` ${We.green}+${t.stats.additions}${We.reset} ${We.red}-${t.stats.deletions}${We.reset} in ${t.files.length} file(s)`),e.push(`
93
+ ${We.bold}${We.cyan}Files:${We.reset}`);for(let n of t.files.slice(0,20))e.push(` ${We.dim}${n}${We.reset}`);return t.files.length>20&&e.push(` ${We.dim}...+${t.files.length-20} more${We.reset}`),e.push(`
94
+ ${We.bold}${We.cyan}Suggested message:${We.reset}`),e.push(` ${We.cyan}${t.summary}${We.reset}
91
95
  `),e.join(`
92
- `)}async function lb(){return(await cl()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function cb(){let t=await ul();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let o of t.slice(0,10))e.push(` ${o}`);let s=await ni();if(s){let o=s.length>5e3?s.substring(0,5e3)+`
93
- ...(truncated)`:s;e.push(`
96
+ `)}async function Pb(){return(await pl()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Mb(){let t=await ml();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let o of t.slice(0,10))e.push(` ${o}`);let n=await oi();if(n){let o=n.length>5e3?n.substring(0,5e3)+`
97
+ ...(truncated)`:n;e.push(`
94
98
  DIFF:
95
99
  ${o}`)}return e.join(`
96
- `)}lf.exports={isGitRepo:sb,getCurrentBranch:ob,getStatus:cl,getDiff:ni,getChangedFiles:ul,analyzeDiff:af,createBranch:rb,commit:ib,formatDiffSummary:ab,getDiffContext:cb,getMergeConflicts:lb}});var gf=V((Z1,mf)=>{var rt=require("fs").promises,J1=require("fs"),Lt=require("path"),ub=require("crypto"),{execSync:dl,execFileSync:df}=require("child_process"),db=100*1024,ff=50,$t=[],js=[];function fb(t,e,s,o){for($t.push({tool:t,filePath:e,oldContent:s,newContent:o,timestamp:Date.now()});$t.length>ff;)$t.shift();js.length=0,hf($t[$t.length-1]).catch(()=>{})}async function hb(){if($t.length===0)return null;let t=$t.pop();if(t.oldContent===null)try{await rt.unlink(t.filePath)}catch{}else await rt.writeFile(t.filePath,t.oldContent,"utf-8");return js.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function pb(){if(js.length===0)return null;let t=js.pop();return await rt.writeFile(t.filePath,t.newContent,"utf-8"),$t.push(t),{tool:t.tool,filePath:t.filePath}}function mb(t=10){return $t.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function gb(){return $t.length}function yb(){return js.length}function wb({diskToo:t=!0}={}){if($t.length=0,js.length=0,t){let e=ri();rt.readdir(e).then(s=>{for(let o of s)o.endsWith(".json")&&rt.unlink(Lt.join(e,o)).catch(()=>{})}).catch(()=>{})}}function ri(){return Lt.join(process.cwd(),".nex","history")}async function cf(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=db)return{inline:!0,content:t};let s=ub.createHash("sha256").update(t,"utf-8").digest("hex"),o=Lt.join(e,"blobs");return await rt.mkdir(o,{recursive:!0}),await rt.writeFile(Lt.join(o,s),t,"utf-8"),{inline:!1,hash:s}}async function hf(t){let e=ri();await rt.mkdir(e,{recursive:!0});let s=Lt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${s}.json`,n=await cf(t.oldContent,e),r=await cf(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:n.inline?{inline:!0,content:n.content}:{inline:!1,hash:n.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await rt.writeFile(Lt.join(e,o),JSON.stringify(i),"utf-8")}async function uf(t,e){if(!t)return null;if(t.inline)return t.content;let s=Lt.join(e,"blobs",t.hash);return rt.readFile(s,"utf-8")}async function $b(){let t=ri(),e;try{e=await rt.readdir(t)}catch{return 0}let s=e.filter(n=>n.endsWith(".json")).sort(),o=0;for(let n of s)try{let r=await rt.readFile(Lt.join(t,n),"utf-8"),i=JSON.parse(r),a=await uf(i.oldContent,t),l=await uf(i.newContent,t);$t.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),o++}catch{}for(;$t.length>ff;)$t.shift();return o}async function bb(t=7){let e=ri(),s;try{s=await rt.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,n=s.filter(u=>u.endsWith(".json")),r=0,i=new Set,a=[];for(let u of n)try{let c=await rt.readFile(Lt.join(e,u),"utf-8"),d=JSON.parse(c);d.timestamp<o?(a.push(u),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 u of a)try{await rt.unlink(Lt.join(e,u))}catch{}let l=Lt.join(e,"blobs");try{let u=await rt.readdir(l);for(let c of u)if(!i.has(c))try{await rt.unlink(Lt.join(l,c))}catch{}}catch{}return r}var oi="nex-snapshot";function _b(t,e=process.cwd()){let s=t?`${oi}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${oi}-${Date.now()}`;try{return dl("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(df("git",["stash","push","-u","-m",s],{cwd:e,timeout:15e3}),dl("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(o){return{name:s,label:s,ok:!1,error:o.message}}}function pf(t=process.cwd()){try{let e=dl("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
97
- `).map(s=>{let o=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let n=o[2].trim();return n.startsWith(oi)?{index:parseInt(o[1],10),label:n,shortName:n.replace(`${oi}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function kb(t,e=process.cwd()){try{let s=pf(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let o;return t===void 0||t==="last"?o=s[0]:typeof t=="number"?o=s.find(n=>n.index===t):o=s.find(n=>n.label===t||n.shortName===t||n.shortName.includes(String(t))),o?(df("git",["stash","apply",`stash@{${o.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:o.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}mf.exports={recordChange:fb,undo:hb,redo:pb,getHistory:mb,getUndoCount:gb,getRedoCount:yb,clearHistory:wb,persistEntry:hf,loadPersistedHistory:$b,pruneHistory:bb,createSnapshot:_b,listSnapshots:pf,restoreSnapshot:kb}});var gl=V((Q1,kf)=>{var Ie=require("fs"),bt=require("path"),{atomicWrite:xb,withFileLockSync:Sb}=Gn(),ht=[];function vo(){return bt.join(process.cwd(),".nex","skills")}function yf(){return bt.join(process.cwd(),".nex","config.json")}function wf(){let t=vo();return Ie.existsSync(t)||Ie.mkdirSync(t,{recursive:!0}),t}function pl(){let t=yf();if(!Ie.existsSync(t))return[];try{let e=JSON.parse(Ie.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function $f(t){let e=yf(),s=bt.dirname(e);Ie.existsSync(s)||Ie.mkdirSync(s,{recursive:!0}),Sb(e,()=>{let o={};if(Ie.existsSync(e))try{o=JSON.parse(Ie.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,xb(e,JSON.stringify(o,null,2))})}function bf(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 o=0;o<t.commands.length;o++){let n=t.commands[o];(!n.cmd||typeof n.cmd!="string")&&s.push(`commands[${o}].cmd must be a non-empty string`),n.handler!==void 0&&typeof n.handler!="function"&&s.push(`commands[${o}].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 o=0;o<t.tools.length;o++){let n=t.tools[o];(!n.function||!n.function.name||typeof n.function.name!="string")&&s.push(`tools[${o}].function.name must be a non-empty string`),n.execute!==void 0&&typeof n.execute!="function"&&s.push(`tools[${o}].execute must be a function`)}return{valid:s.length===0,errors:s}}function _f(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],o=e[2].trim(),n=[],r=!1;for(let i of s.split(`
98
- `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?n.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:n,body:o}}function fl(t){try{let e=Ie.readFileSync(t,"utf-8").trim();if(!e)return null;let s=bt.basename(t,".md"),{triggers:o,body:n}=_f(e);return{name:s,type:"prompt",filePath:t,instructions:n||e,triggers:o,commands:[],tools:[]}}catch{return null}}function hl(t){try{let e=require(t),{valid:s,errors:o}=bf(e,t);return s?{name:e.name||bt.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}
100
+ `)}xf.exports={isGitRepo:Rb,getCurrentBranch:Cb,getStatus:pl,getDiff:oi,getChangedFiles:ml,analyzeDiff:_f,createBranch:Ab,commit:Ob,formatDiffSummary:Nb,getDiffContext:Mb,getMergeConflicts:Pb}});var Af=Z((qC,Cf)=>{var at=require("fs").promises,DC=require("fs"),It=require("path"),Lb=require("crypto"),{execSync:gl,execFileSync:vf}=require("child_process"),Ib=100*1024,Ef=50,bt=[],Us=[];function jb(t,e,n,o){for(bt.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});bt.length>Ef;)bt.shift();Us.length=0,Tf(bt[bt.length-1]).catch(()=>{})}async function Db(){if(bt.length===0)return null;let t=bt.pop();if(t.oldContent===null)try{await at.unlink(t.filePath)}catch{}else await at.writeFile(t.filePath,t.oldContent,"utf-8");return Us.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function qb(){if(Us.length===0)return null;let t=Us.pop();return await at.writeFile(t.filePath,t.newContent,"utf-8"),bt.push(t),{tool:t.tool,filePath:t.filePath}}function Fb(t=10){return bt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Bb(){return bt.length}function Ub(){return Us.length}function Wb({diskToo:t=!0}={}){if(bt.length=0,Us.length=0,t){let e=ai();at.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&at.unlink(It.join(e,o)).catch(()=>{})}).catch(()=>{})}}function ai(){return It.join(process.cwd(),".nex","history")}async function kf(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Ib)return{inline:!0,content:t};let n=Lb.createHash("sha256").update(t,"utf-8").digest("hex"),o=It.join(e,"blobs");return await at.mkdir(o,{recursive:!0}),await at.writeFile(It.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function Tf(t){let e=ai();await at.mkdir(e,{recursive:!0});let n=It.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await kf(t.oldContent,e),r=await kf(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:s.inline?{inline:!0,content:s.content}:{inline:!1,hash:s.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await at.writeFile(It.join(e,o),JSON.stringify(i),"utf-8")}async function Sf(t,e){if(!t)return null;if(t.inline)return t.content;let n=It.join(e,"blobs",t.hash);return at.readFile(n,"utf-8")}async function Hb(){let t=ai(),e;try{e=await at.readdir(t)}catch{return 0}let n=e.filter(s=>s.endsWith(".json")).sort(),o=0;for(let s of n)try{let r=await at.readFile(It.join(t,s),"utf-8"),i=JSON.parse(r),a=await Sf(i.oldContent,t),l=await Sf(i.newContent,t);bt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),o++}catch{}for(;bt.length>Ef;)bt.shift();return o}async function Yb(t=7){let e=ai(),n;try{n=await at.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,s=n.filter(u=>u.endsWith(".json")),r=0,i=new Set,a=[];for(let u of s)try{let c=await at.readFile(It.join(e,u),"utf-8"),d=JSON.parse(c);d.timestamp<o?(a.push(u),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 u of a)try{await at.unlink(It.join(e,u))}catch{}let l=It.join(e,"blobs");try{let u=await at.readdir(l);for(let c of u)if(!i.has(c))try{await at.unlink(It.join(l,c))}catch{}}catch{}return r}var ii="nex-snapshot";function Gb(t,e=process.cwd()){let n=t?`${ii}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${ii}-${Date.now()}`;try{return gl("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(vf("git",["stash","push","-u","-m",n],{cwd:e,timeout:15e3}),gl("git stash pop",{cwd:e,timeout:1e4}),{name:n,label:n,ok:!0}):{name:n,label:n,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(o){return{name:n,label:n,ok:!1,error:o.message}}}function Rf(t=process.cwd()){try{let e=gl("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
101
+ `).map(n=>{let o=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let s=o[2].trim();return s.startsWith(ii)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${ii}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function zb(t,e=process.cwd()){try{let n=Rf(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let o;return t===void 0||t==="last"?o=n[0]:typeof t=="number"?o=n.find(s=>s.index===t):o=n.find(s=>s.label===t||s.shortName===t||s.shortName.includes(String(t))),o?(vf("git",["stash","apply",`stash@{${o.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:o.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}Cf.exports={recordChange:jb,undo:Db,redo:qb,getHistory:Fb,getUndoCount:Bb,getRedoCount:Ub,clearHistory:Wb,persistEntry:Tf,loadPersistedHistory:Hb,pruneHistory:Yb,createSnapshot:Gb,listSnapshots:Rf,restoreSnapshot:zb}});var _l=Z((FC,If)=>{var je=require("fs"),_t=require("path"),{atomicWrite:Kb,withFileLockSync:Xb}=Gn(),pt=[];function To(){return _t.join(process.cwd(),".nex","skills")}function Of(){return _t.join(process.cwd(),".nex","config.json")}function Nf(){let t=To();return je.existsSync(t)||je.mkdirSync(t,{recursive:!0}),t}function $l(){let t=Of();if(!je.existsSync(t))return[];try{let e=JSON.parse(je.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Pf(t){let e=Of(),n=_t.dirname(e);je.existsSync(n)||je.mkdirSync(n,{recursive:!0}),Xb(e,()=>{let o={};if(je.existsSync(e))try{o=JSON.parse(je.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,Kb(e,JSON.stringify(o,null,2))})}function Mf(t,e){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&n.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&n.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&n.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))n.push("commands must be an array");else for(let o=0;o<t.commands.length;o++){let s=t.commands[o];(!s.cmd||typeof s.cmd!="string")&&n.push(`commands[${o}].cmd must be a non-empty string`),s.handler!==void 0&&typeof s.handler!="function"&&n.push(`commands[${o}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))n.push("tools must be an array");else for(let o=0;o<t.tools.length;o++){let s=t.tools[o];(!s.function||!s.function.name||typeof s.function.name!="string")&&n.push(`tools[${o}].function.name must be a non-empty string`),s.execute!==void 0&&typeof s.execute!="function"&&n.push(`tools[${o}].execute must be a function`)}return{valid:n.length===0,errors:n}}function Lf(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let n=e[1],o=e[2].trim(),s=[],r=!1;for(let i of n.split(`
102
+ `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?s.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:s,body:o}}function yl(t){try{let e=je.readFileSync(t,"utf-8").trim();if(!e)return null;let n=_t.basename(t,".md"),{triggers:o,body:s}=Lf(e);return{name:n,type:"prompt",filePath:t,instructions:s||e,triggers:o,commands:[],tools:[]}}catch{return null}}function wl(t){try{let e=require(t),{valid:n,errors:o}=Mf(e,t);return n?{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}
99
103
  ${o.join(`
100
- `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function ml(){ht=[];let t=pl(),e=vo(),s=[];if(Ie.existsSync(e))try{s=Ie.readdirSync(e)}catch{s=[]}for(let n of s){let r=bt.join(e,n),i;try{i=Ie.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;n.endsWith(".md")?a=fl(r):n.endsWith(".js")&&(a=hl(r)),a&&(a.enabled=!t.includes(a.name),ht.push(a))}let o=bt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ie.existsSync(o)){let n;try{n=Ie.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{n=[]}for(let r of n){let i=bt.join(o,r),a=bt.basename(r,bt.extname(r));if(ht.some(c=>c.name===a))continue;let l;try{l=Ie.statSync(i)}catch{continue}if(!l.isFile())continue;let u=r.endsWith(".md")?fl(i):hl(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),ht.push(u))}}return ht}function vb(){let t=[];for(let e of ht)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
104
+ `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function bl(){pt=[];let t=$l(),e=To(),n=[];if(je.existsSync(e))try{n=je.readdirSync(e)}catch{n=[]}for(let s of n){let r=_t.join(e,s),i;try{i=je.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;s.endsWith(".md")?a=yl(r):s.endsWith(".js")&&(a=wl(r)),a&&(a.enabled=!t.includes(a.name),pt.push(a))}let o=_t.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&je.existsSync(o)){let s;try{s=je.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{s=[]}for(let r of s){let i=_t.join(o,r),a=_t.basename(r,_t.extname(r));if(pt.some(c=>c.name===a))continue;let l;try{l=je.statSync(i)}catch{continue}if(!l.isFile())continue;let u=r.endsWith(".md")?yl(i):wl(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),pt.push(u))}}return pt}function Vb(){let t=[];for(let e of pt)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
101
105
  ${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
102
106
  ${t.join(`
103
107
 
104
- `)}`}function Eb(){let t=[];for(let e of ht)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function Tb(){let t=[];for(let e of ht)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 Rb(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let o of ht)if(o.enabled){for(let n of o.tools)if(n.function.name===s&&n.execute)try{let r=await n.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 Cb(t){let[e,...s]=t.split(/\s+/),o=s.join(" ").trim();for(let n of ht)if(n.enabled){for(let r of n.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(o);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 Ab(){return ht.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 Ob(t){let e=ht.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let s=pl().filter(o=>o!==t);return $f(s),!0}function Nb(t){let e=ht.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let s=pl();return s.includes(t)||(s.push(t),$f(s)),!0}function Mb(){return ht}async function Pb(t,e={}){let{execFileSync:s}=require("child_process"),o=wf(),n=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(n=`https://github.com/${t}.git`);let r=e.name||bt.basename(n,".git").replace(/^nex-skill-/,""),i=bt.join(o,r);if(Ie.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(n))throw new Error(`Invalid git URL: ${n}`);s("git",["clone","--depth","1",n,i],{timeout:3e4,stdio:"pipe"})}catch(c){return{ok:!1,name:r,error:`Git clone failed: ${c.stderr?.toString().trim()||c.message}`}}let a=bt.join(i,"skill.json"),l=Ie.existsSync(a),u=Ie.readdirSync(i).some(c=>(c.endsWith(".md")||c.endsWith(".js"))&&!c.startsWith("."));if(!l&&!u){try{Ie.rmSync(i,{recursive:!0,force:!0})}catch(c){console.error("skills.js line 562 failed:",c.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let c=JSON.parse(Ie.readFileSync(a,"utf-8"));c.name||(c.name=r)}catch{try{Ie.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return ml(),{ok:!0,name:r}}async function Lb(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(n=>({name:n.name.replace(/^nex-skill-/,""),description:n.description||"(no description)",url:n.clone_url,stars:n.stargazers_count,owner:n.owner.login}))}catch(s){return[{name:"error",description:`Search failed: ${s.message}`,url:"",stars:0,owner:""}]}}function Ib(t){let e=bt.join(vo(),t);if(!Ie.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${vo()}`};try{return Ie.rmSync(e,{recursive:!0,force:!0}),ml(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function jb(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let o of ht){if(!o.enabled||!o.triggers||o.triggers.length===0)continue;if(o.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(o.instructions||"").split(`
108
+ `)}`}function Jb(){let t=[];for(let e of pt)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function Zb(){let t=[];for(let e of pt)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function Qb(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let o of pt)if(o.enabled){for(let s of o.tools)if(s.function.name===n&&s.execute)try{let r=await s.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function e_(t){let[e,...n]=t.split(/\s+/),o=n.join(" ").trim();for(let s of pt)if(s.enabled){for(let r of s.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(o);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 t_(){return pt.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 n_(t){let e=pt.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=$l().filter(o=>o!==t);return Pf(n),!0}function s_(t){let e=pt.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=$l();return n.includes(t)||(n.push(t),Pf(n)),!0}function o_(){return pt}async function r_(t,e={}){let{execFileSync:n}=require("child_process"),o=Nf(),s=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(s=`https://github.com/${t}.git`);let r=e.name||_t.basename(s,".git").replace(/^nex-skill-/,""),i=_t.join(o,r);if(je.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(s))throw new Error(`Invalid git URL: ${s}`);n("git",["clone","--depth","1",s,i],{timeout:3e4,stdio:"pipe"})}catch(c){return{ok:!1,name:r,error:`Git clone failed: ${c.stderr?.toString().trim()||c.message}`}}let a=_t.join(i,"skill.json"),l=je.existsSync(a),u=je.readdirSync(i).some(c=>(c.endsWith(".md")||c.endsWith(".js"))&&!c.startsWith("."));if(!l&&!u){try{je.rmSync(i,{recursive:!0,force:!0})}catch(c){console.error("skills.js line 562 failed:",c.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let c=JSON.parse(je.readFileSync(a,"utf-8"));c.name||(c.name=r)}catch{try{je.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return bl(),{ok:!0,name:r}}async function i_(t){let e=require("axios");try{let n=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(s=>({name:s.name.replace(/^nex-skill-/,""),description:s.description||"(no description)",url:s.clone_url,stars:s.stargazers_count,owner:s.owner.login}))}catch(n){return[{name:"error",description:`Search failed: ${n.message}`,url:"",stars:0,owner:""}]}}function a_(t){let e=_t.join(To(),t);if(!je.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${To()}`};try{return je.rmSync(e,{recursive:!0,force:!0}),bl(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function l_(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let o of pt){if(!o.enabled||!o.triggers||o.triggers.length===0)continue;if(o.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(o.instructions||"").split(`
105
109
  `).slice(0,3).join(`
106
- `);s.push({name:o.name,instructions:r})}}return s}kf.exports={initSkillsDir:wf,loadAllSkills:ml,getSkillInstructions:vb,getSkillCommands:Eb,getSkillToolDefinitions:Tb,routeSkillCall:Rb,handleSkillCommand:Cb,listSkills:Ab,enableSkill:Ob,disableSkill:Nb,getLoadedSkills:Mb,installSkill:Pb,searchSkills:Lb,removeSkill:Ib,matchSkillTriggers:jb,_getSkillsDir:vo,_validateScriptSkill:bf,_loadMarkdownSkill:fl,_loadScriptSkill:hl,_parseFrontmatter:_f}});var wl=V((eC,Rf)=>{var{spawn:Db}=require("child_process"),qb=require("path"),xf=require("fs"),gn=new Map;function Fb(){return qb.join(process.cwd(),".nex","config.json")}function yl(){let t=Fb();if(!xf.existsSync(t))return{};try{return JSON.parse(xf.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function ii(t,e,s={},o=1e4){return new Promise((n,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
110
+ `);n.push({name:o.name,instructions:r})}}return n}If.exports={initSkillsDir:Nf,loadAllSkills:bl,getSkillInstructions:Vb,getSkillCommands:Jb,getSkillToolDefinitions:Zb,routeSkillCall:Qb,handleSkillCommand:e_,listSkills:t_,enableSkill:n_,disableSkill:s_,getLoadedSkills:o_,installSkill:r_,searchSkills:i_,removeSkill:a_,matchSkillTriggers:l_,_getSkillsDir:To,_validateScriptSkill:Mf,_loadMarkdownSkill:yl,_loadScriptSkill:wl,_parseFrontmatter:Lf}});var kl=Z((BC,Uf)=>{var{spawn:c_}=require("child_process"),u_=require("path"),jf=require("fs"),bn=new Map;function d_(){return u_.join(process.cwd(),".nex","config.json")}function xl(){let t=d_();if(!jf.existsSync(t))return{};try{return JSON.parse(jf.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function li(t,e,n={},o=1e4){return new Promise((s,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
107
111
  `,l="",u=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},o);function c(f){l+=f.toString();let h=l.split(`
108
- `);for(let m of h)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)}`)):n(g.result);return}}catch{}l=h[h.length-1]||""}function d(){clearTimeout(u),t.stdout.removeListener("data",c)}t.stdout.on("data",c);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function Sf(t,e){if(gn.has(t))return gn.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of s)process.env[i]&&(o[i]=process.env[i]);let n=Db(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:n,tools:[],config:e};try{await ii(n,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await ii(n,"tools/list",{});return r.tools=i&&i.tools||[],gn.set(t,r),r}catch(i){throw n.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function vf(t){let e=gn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return gn.delete(t),!0}function Bb(){for(let[t]of gn)vf(t)}async function Ef(t,e,s={}){let o=gn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let n=await ii(o.proc,"tools/call",{name:e,arguments:s});return n&&Array.isArray(n.content)?n.content.filter(r=>r.type==="text").map(r=>r.text).join(`
109
- `):JSON.stringify(n)}function Tf(){let t=[];for(let[e,s]of gn)for(let o of s.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function Ub(){return Tf().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Wb(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let o=s[0],n=s.slice(1).join("_");return Ef(o,n,e)}function Hb(){let t=yl();return Object.entries(t).map(([e,s])=>{let o=gn.get(e);return{name:e,command:s.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function Gb(){let t=yl(),e=[];for(let[s,o]of Object.entries(t))try{let n=await Sf(s,o);e.push({name:s,tools:n.tools.length})}catch(n){e.push({name:s,tools:0,error:n.message})}return e}Rf.exports={loadMCPConfig:yl,sendRequest:ii,connectServer:Sf,disconnectServer:vf,disconnectAll:Bb,callTool:Ef,getAllTools:Tf,getMCPToolDefinitions:Ub,routeMCPCall:Wb,listServers:Hb,connectAll:Gb}});var li=V((tC,Nf)=>{var Cf=require("fs"),$l=require("path"),ai=[],Eo=[],Xn={},To=["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 Eo.some(o=>o.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(Eo.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Of(t,e){return To.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Xn[t]||(Xn[t]=[]),Xn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${To.join(", ")}`}}async function bl(t,e){let s=Xn[t]||[],o=e;for(let n of s)try{let r=await n(o);r!==void 0&&(o=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return o}function Yb(){let t=$l.join(process.cwd(),".nex","plugins"),e=[];if(!Cf.existsSync(t))return{loaded:0,errors:[]};let s=Cf.readdirSync(t).filter(n=>n.endsWith(".js")),o={registerTool:Af,registerHook:Of,EVENTS:To};for(let n of s){let r=$l.join(t,n);try{let i=require(r);if(typeof i=="function")i(o);else if(typeof i.setup=="function")i.setup(o);else{e.push(`${n}: Plugin must export a function or { setup: function }`);continue}ai.push({name:i.name||$l.basename(n,".js"),filePath:r})}catch(i){e.push(`${n}: ${i.message}`)}}return{loaded:ai.length,errors:e}}function zb(){return Eo.map(t=>t.definition)}async function Kb(t,e,s={}){let o=Eo.find(a=>a.definition.function.name===t);if(!o)return null;let n=await bl("beforeToolExec",{name:t,args:e,options:s}),r=await o.handler(n.args||e,s);return(await bl("afterToolExec",{name:t,args:e,result:r})).result||r}function Xb(){return[...ai]}function Vb(){let t={};for(let e of To)t[e]=(Xn[e]||[]).length;return t}function Jb(){ai.length=0,Eo.length=0;for(let t of Object.keys(Xn))delete Xn[t]}Nf.exports={registerTool:Af,registerHook:Of,emit:bl,loadPlugins:Yb,getPluginToolDefinitions:zb,executePluginTool:Kb,getLoadedPlugins:Xb,getHookCounts:Vb,clearPlugins:Jb,EVENTS:To}});var _l=V((nC,If)=>{var{getSkillToolDefinitions:Zb}=gl(),{getMCPToolDefinitions:Qb}=wl(),{getPluginToolDefinitions:e_}=li(),ci=new Map;function Mf(){let{TOOL_DEFINITIONS:t}=Ro();return[...t,...Zb(),...Qb(),...e_()]}function Pf(t){if(ci.has(t))return ci.get(t);let s=Mf().find(n=>n.function.name===t);if(!s)return null;let o=s.function.parameters;return ci.set(t,o),o}function t_(){ci.clear()}function ui(t,e){if(!t||e.length===0)return null;let s=null,o=1/0;for(let n of e){let r=Lf(t.toLowerCase(),n.toLowerCase());r<o&&(o=r,s=n)}return o<=Math.ceil(t.length/2)?s:null}function Lf(t,e){let s=t.length,o=e.length,n=Array.from({length:s+1},()=>Array(o+1).fill(0));for(let r=0;r<=s;r++)n[r][0]=r;for(let r=0;r<=o;r++)n[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=o;i++)n[r][i]=t[r-1]===e[i-1]?n[r-1][i-1]:1+Math.min(n[r-1][i],n[r][i-1],n[r-1][i-1]);return n[s][o]}function n_(t,e){let s=Pf(t);if(s===null){let d=Mf().map(h=>h.function.name),f=ui(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
110
- Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let o=s.required||[],n=Object.keys(s.properties),r=Object.keys(e),i=[],a={...e},l=!1;for(let c of o)if(!(c in e)||e[c]===void 0||e[c]===null){let d=ui(c,r);d&&!n.includes(d)?(a[c]=e[d],delete a[d],l=!0):i.push(`Missing required parameter "${c}" (${s.properties[c]?.description||s.properties[c]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!n.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 c of Object.keys(a))if(!n.includes(c)){let d=ui(c,n);if(d&&!(d in a))a[d]=a[c],delete a[c],l=!0;else if(!l){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${c}".${f}`)}}for(let c of Object.keys(a)){if(!s.properties[c])continue;let d=s.properties[c].type,f=typeof a[c];d==="string"&&f==="number"?(a[c]=String(a[c]),l=!0):d==="number"&&f==="string"&&!isNaN(a[c])?(a[c]=Number(a[c]),l=!0):d==="boolean"&&f==="string"&&(a[c]=a[c]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
112
+ `);for(let m of h)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)}`)):s(g.result);return}}catch{}l=h[h.length-1]||""}function d(){clearTimeout(u),t.stdout.removeListener("data",c)}t.stdout.on("data",c);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function Df(t,e){if(bn.has(t))return bn.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of n)process.env[i]&&(o[i]=process.env[i]);let s=c_(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await li(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await li(s,"tools/list",{});return r.tools=i&&i.tools||[],bn.set(t,r),r}catch(i){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function qf(t){let e=bn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return bn.delete(t),!0}function f_(){for(let[t]of bn)qf(t)}async function Ff(t,e,n={}){let o=bn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await li(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
113
+ `):JSON.stringify(s)}function Bf(){let t=[];for(let[e,n]of bn)for(let o of n.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function h_(){return Bf().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function p_(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let o=n[0],s=n.slice(1).join("_");return Ff(o,s,e)}function m_(){let t=xl();return Object.entries(t).map(([e,n])=>{let o=bn.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function g_(){let t=xl(),e=[];for(let[n,o]of Object.entries(t))try{let s=await Df(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}Uf.exports={loadMCPConfig:xl,sendRequest:li,connectServer:Df,disconnectServer:qf,disconnectAll:f_,callTool:Ff,getAllTools:Bf,getMCPToolDefinitions:h_,routeMCPCall:p_,listServers:m_,connectAll:g_}});var ui=Z((UC,Gf)=>{var Wf=require("fs"),Sl=require("path"),ci=[],Ro=[],Vn={},Co=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Hf(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 n=t.function.name;return Ro.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(Ro.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Yf(t,e){return Co.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Vn[t]||(Vn[t]=[]),Vn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Co.join(", ")}`}}async function vl(t,e){let n=Vn[t]||[],o=e;for(let s of n)try{let r=await s(o);r!==void 0&&(o=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return o}function y_(){let t=Sl.join(process.cwd(),".nex","plugins"),e=[];if(!Wf.existsSync(t))return{loaded:0,errors:[]};let n=Wf.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:Hf,registerHook:Yf,EVENTS:Co};for(let s of n){let r=Sl.join(t,s);try{let i=require(r);if(typeof i=="function")i(o);else if(typeof i.setup=="function")i.setup(o);else{e.push(`${s}: Plugin must export a function or { setup: function }`);continue}ci.push({name:i.name||Sl.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:ci.length,errors:e}}function w_(){return Ro.map(t=>t.definition)}async function $_(t,e,n={}){let o=Ro.find(a=>a.definition.function.name===t);if(!o)return null;let s=await vl("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await vl("afterToolExec",{name:t,args:e,result:r})).result||r}function b_(){return[...ci]}function __(){let t={};for(let e of Co)t[e]=(Vn[e]||[]).length;return t}function x_(){ci.length=0,Ro.length=0;for(let t of Object.keys(Vn))delete Vn[t]}Gf.exports={registerTool:Hf,registerHook:Yf,emit:vl,loadPlugins:y_,getPluginToolDefinitions:w_,executePluginTool:$_,getLoadedPlugins:b_,getHookCounts:__,clearPlugins:x_,EVENTS:Co}});var El=Z((WC,Vf)=>{var{getSkillToolDefinitions:k_}=_l(),{getMCPToolDefinitions:S_}=kl(),{getPluginToolDefinitions:v_}=ui(),di=new Map;function zf(){let{TOOL_DEFINITIONS:t}=Ao();return[...t,...k_(),...S_(),...v_()]}function Kf(t){if(di.has(t))return di.get(t);let n=zf().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return di.set(t,o),o}function E_(){di.clear()}function fi(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=Xf(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function Xf(t,e){let n=t.length,o=e.length,s=Array.from({length:n+1},()=>Array(o+1).fill(0));for(let r=0;r<=n;r++)s[r][0]=r;for(let r=0;r<=o;r++)s[0][r]=r;for(let r=1;r<=n;r++)for(let i=1;i<=o;i++)s[r][i]=t[r-1]===e[i-1]?s[r-1][i-1]:1+Math.min(s[r-1][i],s[r][i-1],s[r-1][i-1]);return s[n][o]}function T_(t,e){let n=Kf(t);if(n===null){let d=zf().map(h=>h.function.name),f=fi(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
114
+ Available tools: ${d.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let o=n.required||[],s=Object.keys(n.properties),r=Object.keys(e),i=[],a={...e},l=!1;for(let c of o)if(!(c in e)||e[c]===void 0||e[c]===null){let d=fi(c,r);d&&!s.includes(d)?(a[c]=e[d],delete a[d],l=!0):i.push(`Missing required parameter "${c}" (${n.properties[c]?.description||n.properties[c]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!s.includes("-n")&&(delete a["-n"],delete a.n,l=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(n.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 c of Object.keys(a))if(!s.includes(c)){let d=fi(c,s);if(d&&!(d in a))a[d]=a[c],delete a[c],l=!0;else if(!l){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${c}".${f}`)}}for(let c of Object.keys(a)){if(!n.properties[c])continue;let d=n.properties[c].type,f=typeof a[c];d==="string"&&f==="number"?(a[c]=String(a[c]),l=!0):d==="number"&&f==="string"&&!isNaN(a[c])?(a[c]=Number(a[c]),l=!0):d==="boolean"&&f==="string"&&(a[c]=a[c]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
111
115
  `+i.map(c=>` - ${c}`).join(`
112
116
  `)+`
113
117
 
114
- Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function s_(t,e){let s=[],o={...t};if(!o.function&&!o.name)return s.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:s};if(!o.function&&o.name&&(o.function={name:o.name,arguments:o.arguments||o.args||{}},delete o.name,delete o.args),o.function&&o.function.args!==void 0&&o.function.arguments===void 0&&(o.function.arguments=o.function.args,delete o.function.args),o.function&&(o.function.arguments===void 0||o.function.arguments===null)&&(o.function.arguments={}),o.function&&typeof o.function.arguments=="string"){let n=o.function.arguments;if(n.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(n)}catch(r){return s.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:s}}}return o.function&&typeof o.function.arguments!="object"?(s.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:s}):!o.function.name||typeof o.function.name!="string"?(s.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:s}):{valid:s.length===0,normalized:o,errors:s}}If.exports={validateToolArgs:n_,validateToolCallFormat:s_,closestMatch:ui,levenshtein:Lf,getCachedSchema:Pf,clearSchemaCache:t_}});var Ff=V((sC,qf)=>{var{levenshtein:di}=_l(),o_=200,r_=.3,i_=2;function kl(t){return t.replace(/\r\n/g,`
118
+ Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function R_(t,e){let n=[],o={...t};if(!o.function&&!o.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:n};if(!o.function&&o.name&&(o.function={name:o.name,arguments:o.arguments||o.args||{}},delete o.name,delete o.args),o.function&&o.function.args!==void 0&&o.function.arguments===void 0&&(o.function.arguments=o.function.args,delete o.function.args),o.function&&(o.function.arguments===void 0||o.function.arguments===null)&&(o.function.arguments={}),o.function&&typeof o.function.arguments=="string"){let s=o.function.arguments;if(s.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(s)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:n}}}return o.function&&typeof o.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:n}):!o.function.name||typeof o.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:n}):{valid:n.length===0,normalized:o,errors:n}}Vf.exports={validateToolArgs:T_,validateToolCallFormat:R_,closestMatch:fi,levenshtein:Xf,getCachedSchema:Kf,clearSchemaCache:E_}});var eh=Z((HC,Qf)=>{var{levenshtein:hi}=El(),C_=200,A_=.3,O_=2;function Tl(t){return t.replace(/\r\n/g,`
115
119
  `).replace(/\r/g,`
116
- `).replace(/\t/g," ".repeat(i_)).split(`
117
- `).map(e=>{let s=e.replace(/\s+$/,""),o=s.match(/^(\s*)(.*)/);if(!o)return s;let[,n,r]=o;return n+r.replace(/ {2,}/g," ")}).join(`
118
- `)}function a_(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=kl(t),o=kl(e);if(!s.includes(o))return null;let n=t.split(`
119
- `),r=s.split(`
120
+ `).replace(/\t/g," ".repeat(O_)).split(`
121
+ `).map(e=>{let n=e.replace(/\s+$/,""),o=n.match(/^(\s*)(.*)/);if(!o)return n;let[,s,r]=o;return s+r.replace(/ {2,}/g," ")}).join(`
122
+ `)}function N_(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=Tl(t),o=Tl(e);if(!n.includes(o))return null;let s=t.split(`
123
+ `),r=n.split(`
120
124
  `),i=o.split(`
121
- `),a=i[0],l=i[i.length-1];for(let u=0;u<=r.length-i.length;u++){let c=!0;for(let d=0;d<i.length;d++)if(r[u+d]!==i[d]){c=!1;break}if(c)return n.slice(u,u+i.length).join(`
122
- `)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return n[u]}return null}function l_(t,e){if(!t||!e)return null;let s=t.split(`
123
- `),n=e.split(`
124
- `).length;return s.length===0||n===0?null:n===1?c_(s,e):d_(s,e,n)}function jf(t){return Math.max(1,Math.floor(t/o_))}function Df(t,e){return t<=Math.ceil(e*r_)}function c_(t,e){let s=e.trim(),o=jf(t.length),n=null,r=1/0;for(let i=0;i<t.length;i+=o){let a=t[i];if(!a.trim())continue;let l=di(a.trim(),s);l<r&&(r=l,n={text:a,distance:l,line:i+1})}return n&&o>1&&(n=u_(t,s,n,o)||n,r=n.distance),Df(r,e.length)?n:null}function u_(t,e,s,o){let n=s.line-1,r=Math.max(0,n-o),i=Math.min(t.length-1,n+o),a=s.distance,l=null;for(let u=r;u<=i;u++){let c=t[u];if(!c.trim())continue;let d=di(c.trim(),e);d<a&&(a=d,l={text:c,distance:d,line:u+1})}return l}function d_(t,e,s){let o=t.length-s+1;if(o<=0)return null;let n=jf(o),r=null,i=1/0;for(let a=0;a<o;a+=n){let l=t.slice(a,a+s).join(`
125
- `),u=di(l,e);u<i&&(i=u,r={text:l,distance:u,line:a+1})}return r&&n>1&&(r=f_(t,e,r,n,s,o)||r,i=r.distance),Df(i,e.length)?r:null}function f_(t,e,s,o,n,r){let i=s.line-1,a=Math.max(0,i-o),l=Math.min(r-1,i+o),u=s.distance,c=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+n).join(`
126
- `),h=di(f,e);h<u&&(u=h,c={text:f,distance:h,line:d+1})}return c}qf.exports={normalizeWhitespace:kl,fuzzyFindText:a_,findMostSimilar:l_}});var Uf=V((rC,Bf)=>{var{C:oC}=ot(),h_=[{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}],p_=[{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 m_(t,e){let s=e.split(`
127
- `),o=[],n=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let l of h_)l.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of p_)l.ext&&!l.ext.includes(n)||l.regex.test(i)&&o.push({line:a,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&o.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),o}function g_(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Bf.exports={runDiagnostics:m_,getMemoryUsage:g_}});var sn=V((iC,eh)=>{var Vn=require("fs").promises,_t=require("path"),{exec:y_}=require("util").promisify(require("child_process").exec),An=[],vl=null,fi=!1,Sl=0,w_=6e4;function El(t){return!(An.length===0||vl!==t||Date.now()-Sl>w_)}async function zf(t){if(!fi&&!El(t)){fi=!0,vl=t;try{try{let{stdout:o}=await y_("rg --files",{cwd:t,timeout:5e3});An=o.split(`
128
- `).filter(Boolean),Sl=Date.now(),fi=!1;return}catch{}let e=[],s=async(o,n)=>{let r;try{r=await Vn.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=n?`${n}/${i.name}`:i.name;i.isDirectory()?await s(_t.join(o,i.name),a):e.push(a)}};await s(t,""),An=e,Sl=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{fi=!1}}}function Co(){return An}function $_(){return vl}function b_(t){return An.filter(e=>_t.basename(e)===t)}function __(t){let e=t.toLowerCase();return An.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}function Kf(t,e){let s=t.length,o=e.length;if(s===0)return o;if(o===0)return s;let n=Array.from({length:o+1},(r,i)=>i);for(let r=1;r<=s;r++){let i=r-1;n[0]=r;for(let a=1;a<=o;a++){let l=t[r-1]===e[a-1]?i:1+Math.min(n[a],n[a-1],i);i=n[a],n[a]=l}}return n[o]}function Xf(t,e){let s=t.toLowerCase(),o=e.toLowerCase();if(s===o)return 1e3;let n=s.split("/").filter(Boolean),r=o.split("/").filter(Boolean),i=0;for(let c=1;c<=Math.min(n.length,r.length)&&n[n.length-c]===r[r.length-c];c++)i=c;if(i>0&&i===r.length)return 500+i*100;let a=_t.basename(t).toLowerCase(),l=_t.basename(e).toLowerCase(),u=0;if(a===l)u+=80;else{let c=Math.max(a.length,l.length);if(c>0&&c<100){let f=1-Kf(a,l)/c;f>=.6&&(u+=Math.round(f*50))}}if((s.includes(o)||o.includes(s))&&(u+=20),r.length>1){let c=new Set(n),d=0;for(let f of r)c.has(f)&&d++;u+=d*10}return i>0&&(u+=i*30),u}function k_(t,{limit:e=10,minScore:s=15}={}){if(!t||An.length===0)return[];let o=[];for(let n of An){let r=Xf(n,t);r>=s&&o.push({file:n,score:r})}return o.sort((n,r)=>r.score-n.score),o.slice(0,e)}var xl=null,Wf=0,Hf=null,Vf=12e4,hi=null,Gf=0,Yf=null,Jf=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Zf(t,e){let s=[],o=t.split(`
129
- `);for(let n=0;n<o.length;n++){let r=o[n],i=n+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 u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&s.push({type:"function",name:u[1],line:i});let c=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(c){let f=c[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of f)/^\w+$/.test(h)&&s.push({type:"export",name:h,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 u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&s.push({type:"import",name:u[1]||u[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 pi(t){t=t||process.cwd();let e=_t.join(t,".nex","index","content-index.json"),s={};if(xl&&Hf===t&&Date.now()-Wf<Vf)return xl;try{let i=await Vn.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}let o=Co();(!El(t)||o.length===0)&&(await zf(t),o=Co());let n={files:{}},r=!1;for(let i of Co()){let a=_t.extname(i);if(!Jf.has(a))continue;let l=_t.join(t,i);try{let c=(await Vn.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===c){n.files[i]=s.files[i];continue}let d=await Vn.readFile(l,"utf-8"),f=Zf(d,a);n.files[i]={defs:f,mtime:c},r=!0}catch{}}if(r){let i=_t.join(t,".nex","index");await Vn.mkdir(i,{recursive:!0}),await Vn.writeFile(e,JSON.stringify(n),"utf-8")}return xl=n,Wf=Date.now(),Hf=t,n}async function x_(t,e,s){let o=await pi(s),n=[],r=t.toLowerCase();for(let[i,a]of Object.entries(o.files))for(let l of a.defs)e&&l.type!==e||l.name.toLowerCase().includes(r)&&n.push({file:i,type:l.type,name:l.name,line:l.line});return n.sort((i,a)=>{let l=i.name.toLowerCase()===r?0:1,u=a.name.toLowerCase()===r?0:1;if(l!==u)return l-u;let c=i.name.toLowerCase().startsWith(r)?0:1,d=a.name.toLowerCase().startsWith(r)?0:1;return c-d}),n.slice(0,50)}function S_(t,e,s){if(!e||!e.startsWith("."))return null;let o=_t.posix.dirname(t.replace(/\\/g,"/")),n=_t.posix.normalize(_t.posix.join(o==="."?"":o,e)),r=[];if(_t.posix.extname(n))r.push(n);else for(let a of Jf)r.push(`${n}${a}`),r.push(_t.posix.join(n,`index${a}`));for(let a of r)if(s.has(a))return a;return null}async function Tl(t){if(t=t||process.cwd(),hi&&Yf===t&&Date.now()-Gf<Vf)return hi;let e=await pi(t),s=Co(),o=new Set(s.map(i=>i.replace(/\\/g,"/"))),n={},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:[],u=[],c=new Set;for(let d of l){if(d.type!=="import")continue;let f=S_(a,d.name,o);!f||f===a||c.has(f)||(c.add(f),u.push(f),r[f]||(r[f]=[]),r[f].push(a))}n[a]=u}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return hi={importsByFile:n,importedByFile:r},Gf=Date.now(),Yf=t,hi}async function v_(t,e,s=6){if(!t)return[];let o=await Tl(e),n=String(t).replace(/\\/g,"/"),r=[...o.importsByFile[n]||[],...o.importedByFile[n]||[]];return[...new Set(r)].filter(i=>i!==n).slice(0,s)}async function E_(t,e=4){let s=await Tl(t),o=new Map;for(let[n,r]of Object.entries(s.importsByFile||{}))o.set(n,(o.get(n)||0)+r.length);for(let[n,r]of Object.entries(s.importedByFile||{}))o.set(n,(o.get(n)||0)+r.length);return[...o.entries()].filter(([,n])=>n>0).sort((n,r)=>r[1]-n[1]||n[0].localeCompare(r[0])).slice(0,e).map(([n,r])=>`${n} (${r} links)`)}function Qf(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function T_(t,e){let s=Qf(e);return[new RegExp(`\\bfunction\\s+${s}\\b`),new RegExp(`\\bclass\\s+${s}\\b`),new RegExp(`\\b(?:const|let|var)\\s+${s}\\b\\s*=`),new RegExp(`\\bdef\\s+${s}\\b`),new RegExp(`\\btype\\s+${s}\\b\\s+struct\\b`),new RegExp(`\\bmodule\\.exports\\b[^\\n]*\\b${s}\\b`),new RegExp(`\\bexport\\b[^\\n]*\\b${s}\\b`)].some(n=>n.test(t))}async function R_(t,e,s={}){e=e||process.cwd();let{excludeFile:o=null,excludeLine:n=null,limit:r=6}=s;if(!t||typeof t!="string")return[];let i=await pi(e),a=Qf(t),l=new RegExp(`\\b${a}\\s*\\(`),u=new RegExp(`\\b${a}\\b`),c=[];for(let d of Object.keys(i.files||{})){let f=d.replace(/\\/g,"/");try{let h=_t.join(e,f),g=(await Vn.readFile(h,"utf-8")).split(`
130
- `);for(let $=0;$<g.length;$++){let k=g[$],v=$+1;if(!u.test(k)||o&&f===o&&n===v||T_(k,t))continue;let A=(f===o?0:4)+(l.test(k)?3:1);c.push({file:f,line:v,context:k.trim(),score:A})}}catch{}}return c.sort((d,f)=>f.score!==d.score?f.score-d.score:d.file.localeCompare(f.file)||d.line-f.line),c.slice(0,r)}eh.exports={refreshIndex:zf,getFileIndex:Co,getIndexedCwd:$_,findFileInIndex:b_,searchIndex:__,isIndexValid:El,buildContentIndex:pi,searchContentIndex:x_,extractDefinitions:Zf,buildImportGraph:Tl,getRelatedFiles:v_,summarizeModuleHubs:E_,findSymbolReferences:R_,smartSearch:k_,scorePathMatch:Xf,pathLevenshtein:Kf}});var Ds=V((aC,ih)=>{var mi=require("fs"),$i=require("path"),bi=require("os"),{execFile:C_}=require("child_process"),{promisify:A_}=require("util"),Rl=A_(C_),O_=$i.join(bi.homedir(),".nex","servers.json"),gi=$i.join(bi.tmpdir(),"nex-ssh-sockets");function N_(){return $i.join(process.cwd(),".nex","servers.json")}function th(){let t=o=>{if(!mi.existsSync(o))return{};try{return JSON.parse(mi.readFileSync(o,"utf-8"))}catch{return{}}},e=t(O_),s=t(N_());return{...e,...s}}function M_(t){let e=th();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[n,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:n}}let s=Object.keys(e),o=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}". ${o}`)}function P_(){mi.existsSync(gi)||mi.mkdirSync(gi,{recursive:!0})}function nh(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,bi.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),P_();let s=t.user?`${t.user}@${t.host}`:t.host,o=$i.join(gi,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function sh(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,bi.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function yi(t,e,{timeout:s=3e4,sudo:o=!1}={}){let{args:n}=nh(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await Rl("ssh",[...n,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:_i(l,t)}}}async function L_(t,e,s,{timeout:o=12e4}={}){let n=sh(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await Rl("scp",n,{timeout:o,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(_i(a,t)||a)}}async function I_(t,e,s,{timeout:o=12e4}={}){let n=sh(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await Rl("scp",n,{timeout:o,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(_i(a,t)||a)}}function _i(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
131
- 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}
132
- 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}
125
+ `),a=i[0],l=i[i.length-1];for(let u=0;u<=r.length-i.length;u++){let c=!0;for(let d=0;d<i.length;d++)if(r[u+d]!==i[d]){c=!1;break}if(c)return s.slice(u,u+i.length).join(`
126
+ `)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return s[u]}return null}function P_(t,e){if(!t||!e)return null;let n=t.split(`
127
+ `),s=e.split(`
128
+ `).length;return n.length===0||s===0?null:s===1?M_(n,e):I_(n,e,s)}function Jf(t){return Math.max(1,Math.floor(t/C_))}function Zf(t,e){return t<=Math.ceil(e*A_)}function M_(t,e){let n=e.trim(),o=Jf(t.length),s=null,r=1/0;for(let i=0;i<t.length;i+=o){let a=t[i];if(!a.trim())continue;let l=hi(a.trim(),n);l<r&&(r=l,s={text:a,distance:l,line:i+1})}return s&&o>1&&(s=L_(t,n,s,o)||s,r=s.distance),Zf(r,e.length)?s:null}function L_(t,e,n,o){let s=n.line-1,r=Math.max(0,s-o),i=Math.min(t.length-1,s+o),a=n.distance,l=null;for(let u=r;u<=i;u++){let c=t[u];if(!c.trim())continue;let d=hi(c.trim(),e);d<a&&(a=d,l={text:c,distance:d,line:u+1})}return l}function I_(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=Jf(o),r=null,i=1/0;for(let a=0;a<o;a+=s){let l=t.slice(a,a+n).join(`
129
+ `),u=hi(l,e);u<i&&(i=u,r={text:l,distance:u,line:a+1})}return r&&s>1&&(r=j_(t,e,r,s,n,o)||r,i=r.distance),Zf(i,e.length)?r:null}function j_(t,e,n,o,s,r){let i=n.line-1,a=Math.max(0,i-o),l=Math.min(r-1,i+o),u=n.distance,c=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+s).join(`
130
+ `),h=hi(f,e);h<u&&(u=h,c={text:f,distance:h,line:d+1})}return c}Qf.exports={normalizeWhitespace:Tl,fuzzyFindText:N_,findMostSimilar:P_}});var ch=Z((YC,Cl)=>{var th=require("fs"),D_=require("path"),{execFileSync:q_}=require("child_process"),nh=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],F_=/(^|\/)(tests\/.*\.test\.(js|ts|jsx|tsx)|__tests__\/.*\.(js|ts|jsx|tsx))$/i,sh=[{category:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{category:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{category:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{category:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{category:"GitHub Token (ghp_)",regex:/ghp_[a-zA-Z0-9]{36}/i},{category:"GitHub OAuth (gho_)",regex:/gho_[a-zA-Z0-9]{36}/i},{category:"GitHub App Token (ghs_)",regex:/ghs_[a-zA-Z0-9]{36}/i},{category:"GitHub Fine-Grained Token",regex:/github_pat_[a-zA-Z0-9_]{20,}/i},{category:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{category:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{category:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{category:"Credential URL",regex:/\b[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@[^/\s]+/i},{category:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"][^'"]{8,}/i},{category:"SSH + IP",regex:/\bssh\s+.*@[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"SSH Config HostName",regex:/\bHostName\s+[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"Server IP Assignment",regex:/\b(host|hostname|server|server_ip|public_ip|private_ip|vps_ip|ssh_host|remote_host|db_host)\b\s*[:=]\s*['"]?[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+['"]?/i},{category:".env Secret Assignment",regex:/\b(API_KEY|SECRET_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY|ACCESS_KEY|AUTH_TOKEN|DB_PASSWORD|DATABASE_URL)\s*=/i}],B_=/(^|\/)\.env(?:\.[^/]+)?\.(example|sample|template)$/i,oh=[{category:"Sensitive Env File",regex:/(^|\/)\.env(?:\.[^/]+)?$/i},{category:"Private Key File",regex:/(^|\/)(id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|.*\.key)$/i},{category:"Certificate Bundle",regex:/(^|\/).*\.(p12|pfx|mobileprovision)$/i},{category:"Terraform Secrets",regex:/(^|\/).*\.(tfvars|tfstate)(\..+)?$/i},{category:"Credential File",regex:/(^|\/)(\.npmrc|\.netrc)$/i},{category:"Cloud Credentials",regex:/(^|\/)\.(aws\/credentials|kube\/config)$/i}];function pi(t,e=process.cwd()){return q_("git",t,{cwd:e,encoding:"utf8"})}function U_(t=process.cwd()){return pi(["rev-parse","--show-toplevel"],t).trim()}function W_(t){let e=D_.join(t,".nex","push-allowlist");return th.existsSync(e)?th.readFileSync(e,"utf8").split(`
131
+ `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function Rl(t,e){return e.some(n=>t.includes(n))}function rh(t){return B_.test(t)}function ih(t,e){let n=[];for(let o of t)if(!rh(o))for(let s of oh)s.regex.test(o)&&(Rl(o,e)||n.push({category:s.category,location:o,preview:o}));return n}function H_(t){let e=t.split(`
132
+ `),n=[],o="";for(let s=0;s<e.length;s++){let r=e[s];if(r.startsWith("+++ b/")){o=r.slice(6);continue}!r.startsWith("+")||r.startsWith("+++")||n.push({filePath:o,lineNumber:s+1,text:r.slice(1),raw:r})}return n}function ah(t,e){let n=[];for(let o of H_(t))if(!F_.test(o.filePath||""))for(let s of sh)s.regex.test(o.text)&&(Rl(o.raw,e)||Rl(o.text,e)||n.push({category:s.category,location:`${o.lineNumber}:${o.raw}`,preview:o.raw}));return n}function Y_(t){return pi(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function G_(t,e){return pi(["diff",e,...nh],t)}function z_(t){return pi(["diff","--cached",...nh],t)}function lh({repoRoot:t,mode:e,range:n}){let o=W_(t),s=e==="staged"?Y_(t):[],r=ih(s,o),i=e==="range"?G_(t,n):z_(t),a=ah(i,o);return[...r,...a]}function K_(t){return t.map(e=>` [${e.category}]
133
+ ${e.location}`).join(`
134
+ `)}function X_(t){let e={mode:"staged",range:""};for(let n=0;n<t.length;n++)t[n]==="--staged"&&(e.mode="staged"),t[n]==="--range"&&(e.mode="range",e.range=t[n+1]||"",n++);return e}function V_(){let t=X_(process.argv.slice(2)),e=U_(),n=lh({repoRoot:e,mode:t.mode,range:t.range});if(n.length===0)return;let o=t.mode==="range"?"pushed commits":"staged changes";console.log(""),console.log("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log("\u2551 SECRET DETECTED \u2014 operation blocked \u2551"),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(`\u2551 Found ${n.length} potential secret(s) in ${o}:`),console.log(K_(n)),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log("\u2551 Remove secrets or move them to local-only config. \u2551"),console.log("\u2551 To allowlist: add a specific pattern to .nex/push-allowlist"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(""),process.exit(1)}require.main===Cl&&V_();Cl.exports={SECRET_PATTERNS:sh,SENSITIVE_FILE_RULES:oh,scanDiffText:ah,scanFileNames:ih,scanRepo:lh,isSafeExampleFile:rh}});var dh=Z((zC,uh)=>{var{C:GC}=it(),{SECRET_PATTERNS:J_}=ch(),Z_=[{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 Q_(t,e){let n=e.split(`
135
+ `),o=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let l of J_)l.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${l.category}`,severity:"error"});for(let l of Z_)l.ext&&!l.ext.includes(s)||l.regex.test(i)&&o.push({line:a,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return n.length>500&&o.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),o}function ex(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}uh.exports={runDiagnostics:Q_,getMemoryUsage:ex}});var an=Z((KC,kh)=>{var Jn=require("fs").promises,xt=require("path"),{exec:tx}=require("util").promisify(require("child_process").exec),Nn=[],Nl=null,mi=!1,Ol=0,nx=6e4;function Pl(t){return!(Nn.length===0||Nl!==t||Date.now()-Ol>nx)}async function gh(t){if(!mi&&!Pl(t)){mi=!0,Nl=t;try{try{let{stdout:o}=await tx("rg --files",{cwd:t,timeout:5e3});Nn=o.split(`
136
+ `).filter(Boolean),Ol=Date.now(),mi=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await Jn.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=s?`${s}/${i.name}`:i.name;i.isDirectory()?await n(xt.join(o,i.name),a):e.push(a)}};await n(t,""),Nn=e,Ol=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{mi=!1}}}function Oo(){return Nn}function sx(){return Nl}function ox(t){return Nn.filter(e=>xt.basename(e)===t)}function rx(t){let e=t.toLowerCase();return Nn.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}function yh(t,e){let n=t.length,o=e.length;if(n===0)return o;if(o===0)return n;let s=Array.from({length:o+1},(r,i)=>i);for(let r=1;r<=n;r++){let i=r-1;s[0]=r;for(let a=1;a<=o;a++){let l=t[r-1]===e[a-1]?i:1+Math.min(s[a],s[a-1],i);i=s[a],s[a]=l}}return s[o]}function wh(t,e){let n=t.toLowerCase(),o=e.toLowerCase();if(n===o)return 1e3;let s=n.split("/").filter(Boolean),r=o.split("/").filter(Boolean),i=0;for(let c=1;c<=Math.min(s.length,r.length)&&s[s.length-c]===r[r.length-c];c++)i=c;if(i>0&&i===r.length)return 500+i*100;let a=xt.basename(t).toLowerCase(),l=xt.basename(e).toLowerCase(),u=0;if(a===l)u+=80;else{let c=Math.max(a.length,l.length);if(c>0&&c<100){let f=1-yh(a,l)/c;f>=.6&&(u+=Math.round(f*50))}}if((n.includes(o)||o.includes(n))&&(u+=20),r.length>1){let c=new Set(s),d=0;for(let f of r)c.has(f)&&d++;u+=d*10}return i>0&&(u+=i*30),u}function ix(t,{limit:e=10,minScore:n=15}={}){if(!t||Nn.length===0)return[];let o=[];for(let s of Nn){let r=wh(s,t);r>=n&&o.push({file:s,score:r})}return o.sort((s,r)=>r.score-s.score),o.slice(0,e)}var Al=null,fh=0,hh=null,$h=12e4,gi=null,ph=0,mh=null,bh=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function _h(t,e){let n=[],o=t.split(`
137
+ `);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&n.push({type:"function",name:u[1],line:i});let c=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(c){let f=c[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of f)/^\w+$/.test(h)&&n.push({type:"export",name:h,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];n.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&n.push({type:"import",name:u[1]||u[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&n.push({type:"class",name:l[1],line:i})}}return n}async function yi(t){t=t||process.cwd();let e=xt.join(t,".nex","index","content-index.json"),n={};if(Al&&hh===t&&Date.now()-fh<$h)return Al;try{let i=await Jn.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}let o=Oo();(!Pl(t)||o.length===0)&&(await gh(t),o=Oo());let s={files:{}},r=!1;for(let i of Oo()){let a=xt.extname(i);if(!bh.has(a))continue;let l=xt.join(t,i);try{let c=(await Jn.stat(l)).mtimeMs;if(n.files[i]&&n.files[i].mtime===c){s.files[i]=n.files[i];continue}let d=await Jn.readFile(l,"utf-8"),f=_h(d,a);s.files[i]={defs:f,mtime:c},r=!0}catch{}}if(r){let i=xt.join(t,".nex","index");await Jn.mkdir(i,{recursive:!0}),await Jn.writeFile(e,JSON.stringify(s),"utf-8")}return Al=s,fh=Date.now(),hh=t,s}async function ax(t,e,n){let o=await yi(n),s=[],r=t.toLowerCase();for(let[i,a]of Object.entries(o.files))for(let l of a.defs)e&&l.type!==e||l.name.toLowerCase().includes(r)&&s.push({file:i,type:l.type,name:l.name,line:l.line});return s.sort((i,a)=>{let l=i.name.toLowerCase()===r?0:1,u=a.name.toLowerCase()===r?0:1;if(l!==u)return l-u;let c=i.name.toLowerCase().startsWith(r)?0:1,d=a.name.toLowerCase().startsWith(r)?0:1;return c-d}),s.slice(0,50)}function lx(t,e,n){if(!e||!e.startsWith("."))return null;let o=xt.posix.dirname(t.replace(/\\/g,"/")),s=xt.posix.normalize(xt.posix.join(o==="."?"":o,e)),r=[];if(xt.posix.extname(s))r.push(s);else for(let a of bh)r.push(`${s}${a}`),r.push(xt.posix.join(s,`index${a}`));for(let a of r)if(n.has(a))return a;return null}async function Ml(t){if(t=t||process.cwd(),gi&&mh===t&&Date.now()-ph<$h)return gi;let e=await yi(t),n=Oo(),o=new Set(n.map(i=>i.replace(/\\/g,"/"))),s={},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:[],u=[],c=new Set;for(let d of l){if(d.type!=="import")continue;let f=lx(a,d.name,o);!f||f===a||c.has(f)||(c.add(f),u.push(f),r[f]||(r[f]=[]),r[f].push(a))}s[a]=u}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return gi={importsByFile:s,importedByFile:r},ph=Date.now(),mh=t,gi}async function cx(t,e,n=6){if(!t)return[];let o=await Ml(e),s=String(t).replace(/\\/g,"/"),r=[...o.importsByFile[s]||[],...o.importedByFile[s]||[]];return[...new Set(r)].filter(i=>i!==s).slice(0,n)}async function ux(t,e=4){let n=await Ml(t),o=new Map;for(let[s,r]of Object.entries(n.importsByFile||{}))o.set(s,(o.get(s)||0)+r.length);for(let[s,r]of Object.entries(n.importedByFile||{}))o.set(s,(o.get(s)||0)+r.length);return[...o.entries()].filter(([,s])=>s>0).sort((s,r)=>r[1]-s[1]||s[0].localeCompare(r[0])).slice(0,e).map(([s,r])=>`${s} (${r} links)`)}function xh(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dx(t,e){let n=xh(e);return[new RegExp(`\\bfunction\\s+${n}\\b`),new RegExp(`\\bclass\\s+${n}\\b`),new RegExp(`\\b(?:const|let|var)\\s+${n}\\b\\s*=`),new RegExp(`\\bdef\\s+${n}\\b`),new RegExp(`\\btype\\s+${n}\\b\\s+struct\\b`),new RegExp(`\\bmodule\\.exports\\b[^\\n]*\\b${n}\\b`),new RegExp(`\\bexport\\b[^\\n]*\\b${n}\\b`)].some(s=>s.test(t))}async function fx(t,e,n={}){e=e||process.cwd();let{excludeFile:o=null,excludeLine:s=null,limit:r=6}=n;if(!t||typeof t!="string")return[];let i=await yi(e),a=xh(t),l=new RegExp(`\\b${a}\\s*\\(`),u=new RegExp(`\\b${a}\\b`),c=[];for(let d of Object.keys(i.files||{})){let f=d.replace(/\\/g,"/");try{let h=xt.join(e,f),g=(await Jn.readFile(h,"utf-8")).split(`
138
+ `);for(let $=0;$<g.length;$++){let x=g[$],E=$+1;if(!u.test(x)||o&&f===o&&s===E||dx(x,t))continue;let N=(f===o?0:4)+(l.test(x)?3:1);c.push({file:f,line:E,context:x.trim(),score:N})}}catch{}}return c.sort((d,f)=>f.score!==d.score?f.score-d.score:d.file.localeCompare(f.file)||d.line-f.line),c.slice(0,r)}kh.exports={refreshIndex:gh,getFileIndex:Oo,getIndexedCwd:sx,findFileInIndex:ox,searchIndex:rx,isIndexValid:Pl,buildContentIndex:yi,searchContentIndex:ax,extractDefinitions:_h,buildImportGraph:Ml,getRelatedFiles:cx,summarizeModuleHubs:ux,findSymbolReferences:fx,smartSearch:ix,scorePathMatch:wh,pathLevenshtein:yh}});var Ws=Z((XC,Ch)=>{var wi=require("fs"),xi=require("path"),ki=require("os"),{execFile:hx}=require("child_process"),{promisify:px}=require("util"),Ll=px(hx),mx=xi.join(ki.homedir(),".nex","servers.json"),$i=xi.join(ki.tmpdir(),"nex-ssh-sockets");function gx(){return xi.join(process.cwd(),".nex","servers.json")}function Sh(){let t=o=>{if(!wi.existsSync(o))return{};try{return JSON.parse(wi.readFileSync(o,"utf-8"))}catch{return{}}},e=t(mx),n=t(gx());return{...e,...n}}function yx(t){let e=Sh();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[s,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:s}}let n=Object.keys(e),o=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${o}`)}function wx(){wi.existsSync($i)||wi.mkdirSync($i,{recursive:!0})}function vh(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,ki.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),wx();let n=t.user?`${t.user}@${t.host}`:t.host,o=xi.join($i,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function Eh(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,ki.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function bi(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=vh(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await Ll("ssh",[...s,r],{timeout:n,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:Si(l,t)}}}async function $x(t,e,n,{timeout:o=12e4}={}){let s=Eh(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:a}=await Ll("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Si(a,t)||a)}}async function bx(t,e,n,{timeout:o=12e4}={}){let s=Eh(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:a}=await Ll("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Si(a,t)||a)}}function Si(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
139
+ HINT: Connection refused on ${e.host}:${n}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${n} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let n=e.key?`key: ${e.key}`:"SSH agent";return`${t}
140
+ HINT: Auth failed using ${n} 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}
133
141
  HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
134
142
  HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
135
143
  HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
136
- HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function j_(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",n=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${o}${n}${r}${i}`}var wi=new Map,D_=12e4;async function oh(t,e,{force:s=!1}={}){let n=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=wi.get(n);if(!s&&r&&Date.now()-r.time<D_)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 yi(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let u=e.endsWith("/")?e:e+"/",c=a.split(`
137
- `).filter(Boolean).map(d=>d.startsWith(u)?d.slice(u.length):d);return wi.set(n,{files:c,time:Date.now()}),c}async function rh(t,e,s,{limit:o=5,minScore:n=15}={}){let r=await oh(t,e);if(r.length===0)return[];let{scorePathMatch:i}=sn(),a=[];for(let l of r){let u=i(l,s);u>=n&&a.push({file:l,score:u})}return a.sort((l,u)=>u.score-l.score),a.slice(0,o)}async function q_(t,e,s){if(!s)return{fixedPath:null,message:""};let o=s.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await yi(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await yi(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let n=await rh(t,e,s,{limit:5,minScore:15});if(n.length>0){let i=(e.endsWith("/")?e:e+"/")+n[0].file;if(n[0].score>=200||n.length===1&&n[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${n[0].file})`};if(n.length>=2&&n[0].score>=80&&n[0].score>=n[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${n[0].file})`};if(n.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
138
- ${n.map(a=>` - ${a.file}`).join(`
139
- `)}`}}return{fixedPath:null,message:""}}function F_(t){t?wi.delete(t):wi.clear()}ih.exports={loadServerProfiles:th,resolveProfile:M_,buildSSHArgs:nh,sshExec:yi,scpUpload:L_,scpDownload:I_,enrichSSHError:_i,formatProfile:j_,SSH_SOCKET_DIR:gi,getRemoteIndex:oh,remoteSmartSearch:rh,remoteAutoFixPath:q_,clearRemoteIndex:F_}});var ch=V((lC,lh)=>{var Ao=require("fs"),Cl=require("path"),B_=Cl.join(".nex","deploy.json");function Al(){return Cl.join(process.cwd(),B_)}function ah(){let t=Al();if(!Ao.existsSync(t))return{};try{return JSON.parse(Ao.readFileSync(t,"utf-8"))}catch{return{}}}function U_(t){let e=ah();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),o=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${o}`)}function W_(t){let e=Cl.join(process.cwd(),".nex");Ao.existsSync(e)||Ao.mkdirSync(e,{recursive:!0}),Ao.writeFileSync(Al(),JSON.stringify(t,null,2)+`
140
- `,"utf-8")}lh.exports={loadDeployConfigs:ah,resolveDeployConfig:U_,saveDeployConfigs:W_,getDeployConfigPath:Al}});var Po=V((cC,fh)=>{var{getActiveModel:H_,getActiveProviderName:G_}=ut(),Oo={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},No={"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"},Mo={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},on={};function dh(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(on=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{on={}}}dh();function Ol(){let e=H_()?.id,s=G_();return e&&on[e]?on[e]:s&&on[`${s}:*`]?on[`${s}:*`]:e&&No[e]?No[e]:s&&Mo[s]?Mo[s]:"full"}var Y_=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"]),uh={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function z_(t,e){return t&&(Y_.has(t)||t.startsWith("claude-"))?"strict":e&&uh[e]?uh[e]:"fuzzy"}function K_(t,e){return t&&on[t]?on[t]:e&&on[`${e}:*`]?on[`${e}:*`]:t&&No[t]?No[t]:e&&Mo[e]?Mo[e]:"full"}function X_(t,e){let s=e||Ol();if(s==="full"||!Oo[s])return t;let o=new Set(Oo[s]);return t.filter(n=>o.has(n.function.name))}function V_(){let t=Ol(),e=Oo[t]?Oo[t].length:"all";return{tier:t,toolCount:e}}fh.exports={filterToolsForModel:X_,getActiveTier:Ol,getModelTier:K_,getEditMode:z_,getTierInfo:V_,TIERS:Oo,MODEL_TIERS:No,PROVIDER_DEFAULT_TIER:Mo,loadConfigOverrides:dh}});var wn=V((uC,mh)=>{var Nl=null,yn=null,Lo=null,hh=`Playwright is not installed. Install with:
144
+ 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 n=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",s=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${o}${s}${r}${i}`}var _i=new Map,xx=12e4;async function Th(t,e,{force:n=!1}={}){let s=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=_i.get(s);if(!n&&r&&Date.now()-r.time<xx)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 bi(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let u=e.endsWith("/")?e:e+"/",c=a.split(`
145
+ `).filter(Boolean).map(d=>d.startsWith(u)?d.slice(u.length):d);return _i.set(s,{files:c,time:Date.now()}),c}async function Rh(t,e,n,{limit:o=5,minScore:s=15}={}){let r=await Th(t,e);if(r.length===0)return[];let{scorePathMatch:i}=an(),a=[];for(let l of r){let u=i(l,n);u>=s&&a.push({file:l,score:u})}return a.sort((l,u)=>u.score-l.score),a.slice(0,o)}async function kx(t,e,n){if(!n)return{fixedPath:null,message:""};let o=n.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await bi(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await bi(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let s=await Rh(t,e,n,{limit:5,minScore:15});if(s.length>0){let i=(e.endsWith("/")?e:e+"/")+s[0].file;if(s[0].score>=200||s.length===1&&s[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${s[0].file})`};if(s.length>=2&&s[0].score>=80&&s[0].score>=s[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${s[0].file})`};if(s.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
146
+ ${s.map(a=>` - ${a.file}`).join(`
147
+ `)}`}}return{fixedPath:null,message:""}}function Sx(t){t?_i.delete(t):_i.clear()}Ch.exports={loadServerProfiles:Sh,resolveProfile:yx,buildSSHArgs:vh,sshExec:bi,scpUpload:$x,scpDownload:bx,enrichSSHError:Si,formatProfile:_x,SSH_SOCKET_DIR:$i,getRemoteIndex:Th,remoteSmartSearch:Rh,remoteAutoFixPath:kx,clearRemoteIndex:Sx}});var Nh=Z((VC,Oh)=>{var No=require("fs"),Il=require("path"),vx=Il.join(".nex","deploy.json");function jl(){return Il.join(process.cwd(),vx)}function Ah(){let t=jl();if(!No.existsSync(t))return{};try{return JSON.parse(No.readFileSync(t,"utf-8"))}catch{return{}}}function Ex(t){let e=Ah();if(e[t])return{...e[t],_name:t};let n=Object.keys(e),o=n.length?`Available: ${n.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${o}`)}function Tx(t){let e=Il.join(process.cwd(),".nex");No.existsSync(e)||No.mkdirSync(e,{recursive:!0}),No.writeFileSync(jl(),JSON.stringify(t,null,2)+`
148
+ `,"utf-8")}Oh.exports={loadDeployConfigs:Ah,resolveDeployConfig:Ex,saveDeployConfigs:Tx,getDeployConfigPath:jl}});var Io=Z((JC,Lh)=>{var{getActiveModel:Rx,getActiveProviderName:Cx}=dt(),Po={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},Mo={"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"},Lo={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},ln={};function Mh(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(ln=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{ln={}}}Mh();function Dl(){let e=Rx()?.id,n=Cx();return e&&ln[e]?ln[e]:n&&ln[`${n}:*`]?ln[`${n}:*`]:e&&Mo[e]?Mo[e]:n&&Lo[n]?Lo[n]:"full"}var Ax=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"]),Ph={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function Ox(t,e){return t&&(Ax.has(t)||t.startsWith("claude-"))?"strict":e&&Ph[e]?Ph[e]:"fuzzy"}function Nx(t,e){return t&&ln[t]?ln[t]:e&&ln[`${e}:*`]?ln[`${e}:*`]:t&&Mo[t]?Mo[t]:e&&Lo[e]?Lo[e]:"full"}function Px(t,e){let n=e||Dl();if(n==="full"||!Po[n])return t;let o=new Set(Po[n]);return t.filter(s=>o.has(s.function.name))}function Mx(){let t=Dl(),e=Po[t]?Po[t].length:"all";return{tier:t,toolCount:e}}Lh.exports={filterToolsForModel:Px,getActiveTier:Dl,getModelTier:Nx,getEditMode:Ox,getTierInfo:Mx,TIERS:Po,MODEL_TIERS:Mo,PROVIDER_DEFAULT_TIER:Lo,loadConfigOverrides:Mh}});var xn=Z((ZC,Dh)=>{var ql=null,_n=null,jo=null,Ih=`Playwright is not installed. Install with:
141
149
  npm install playwright && npx playwright install chromium
142
- Then restart nex-code.`;function ph(){if(Lo!==null)return Lo;try{require("playwright"),Lo=!0}catch{Lo=!1}return Lo}async function ki(){if(!ph())throw new Error(hh);return Nl||(Nl=require("playwright")),(!yn||!yn.isConnected())&&(yn=await Nl.chromium.launch({headless:!0})),yn}async function J_(){if(yn){try{await yn.close()}catch(t){console.error("closeBrowser failed:",t.message)}yn=null}}process.on("exit",()=>{if(yn)try{yn.close()}catch(t){console.error("Error closing browser on exit:",t.message)}});async function Z_(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let n=await(await ki()).newPage();try{await n.goto(t,{waitUntil:s,timeout:e});let r=await n.title(),i=await n.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),a=await n.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:n.url(),text:i.substring(0,8e3)+(i.length>8e3?`
143
- ...(truncated)`:""),links:a.slice(0,20)}}finally{await n.close()}}async function Q_(t,{width:e=1280,height:s=800,fullPage:o=!1,timeout:n=3e4}={}){let i=await(await ki()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:n});let a=await i.screenshot({type:"png",fullPage:o}),l=require("os"),u=require("path"),c=require("fs"),d=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return c.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 ek(t,{selector:e,text:s,timeout:o=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await ki()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),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 tk(t,{selector:e,value:s,submit:o=!1,timeout:n=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await ki()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:n}),await i.fill(e,String(s)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}mh.exports={isPlaywrightAvailable:ph,browserNavigate:Z_,browserScreenshot:Q_,browserClick:ek,browserFill:tk,closeBrowser:J_,INSTALL_MSG:hh}});var Ml=V((dC,yh)=>{"use strict";var nk=require("util"),gh=require("stream"),Yt=yh.exports=function(){gh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};nk.inherits(Yt,gh);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,o=Buffer.alloc(t.length);for(;e<t.length;){let n=this._buffers[s++],r=Math.min(n.length,t.length-e);n.copy(o,e,0,r),e+=r,r!==n.length&&(this._buffers[--s]=n.slice(r))}s>0&&this._buffers.splice(0,s),this._buffered-=t.length,t.func.call(this,o)};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 Ll=V(Pl=>{"use strict";var On=[{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]}];Pl.getImagePasses=function(t,e){let s=[],o=t%8,n=e%8,r=(t-o)/8,i=(e-n)/8;for(let a=0;a<On.length;a++){let l=On[a],u=r*l.x.length,c=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<o;d++)u++;for(let d=0;d<l.y.length&&l.y[d]<n;d++)c++;u>0&&c>0&&s.push({width:u,height:c,index:a})}return s};Pl.getInterlaceIterator=function(t){return function(e,s,o){let n=e%On[o].x.length,r=(e-n)/On[o].x.length*8+On[o].x[n],i=s%On[o].y.length,a=(s-i)/On[o].y.length*8+On[o].y[i];return r*4+a*t*4}}});var Il=V((hC,wh)=>{"use strict";wh.exports=function(e,s,o){let n=e+s-o,r=Math.abs(n-e),i=Math.abs(n-s),a=Math.abs(n-o);return r<=i&&r<=a?e:i<=a?s:o}});var jl=V((pC,bh)=>{"use strict";var sk=Ll(),ok=Il();function $h(t,e,s){let o=t*e;return s!==8&&(o=Math.ceil(o/(8/s))),o}var qs=bh.exports=function(t,e){let s=t.width,o=t.height,n=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=[],n){let a=sk.getImagePasses(s,o);for(let l=0;l<a.length;l++)this._images.push({byteWidth:$h(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:$h(s,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};qs.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};qs.prototype._unFilterType1=function(t,e,s){let o=this._xComparison,n=o-1;for(let r=0;r<s;r++){let i=t[1+r],a=r>n?e[r-o]:0;e[r]=i+a}};qs.prototype._unFilterType2=function(t,e,s){let o=this._lastLine;for(let n=0;n<s;n++){let r=t[1+n],i=o?o[n]:0;e[n]=r+i}};qs.prototype._unFilterType3=function(t,e,s){let o=this._xComparison,n=o-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,u=i>n?e[i-o]:0,c=Math.floor((u+l)/2);e[i]=a+c}};qs.prototype._unFilterType4=function(t,e,s){let o=this._xComparison,n=o-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,u=i>n?e[i-o]:0,c=i>n&&r?r[i-o]:0,d=ok(u,l,c);e[i]=a+d}};qs.prototype._reverseFilterLine=function(t){let e=t[0],s,o=this._images[this._imageIndex],n=o.byteWidth;if(e===0)s=t.slice(1,n+1);else switch(s=Buffer.alloc(n),e){case 1:this._unFilterType1(t,s,n);break;case 2:this._unFilterType2(t,s,n);break;case 3:this._unFilterType3(t,s,n);break;case 4:this._unFilterType4(t,s,n);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(s),o.lineIndex++,o.lineIndex>=o.height?(this._lastLine=null,this._imageIndex++,o=this._images[this._imageIndex]):this._lastLine=s,o?this.read(o.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var xh=V((mC,kh)=>{"use strict";var rk=require("util"),_h=Ml(),ik=jl(),ak=kh.exports=function(t){_h.call(this);let e=[],s=this;this._filter=new ik(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};rk.inherits(ak,_h)});var Fs=V((gC,Sh)=>{"use strict";Sh.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 Fl=V((yC,vh)=>{"use strict";var Dl=[];(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;Dl[t]=e}})();var ql=vh.exports=function(){this._crc=-1};ql.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Dl[(this._crc^t[e])&255]^this._crc>>>8;return!0};ql.prototype.crc32=function(){return this._crc^-1};ql.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=Dl[(e^t[s])&255]^e>>>8;return e^-1}});var Bl=V((wC,Eh)=>{"use strict";var Je=Fs(),lk=Fl(),et=Eh.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[Je.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Je.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Je.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Je.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Je.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Je.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(){}};et.prototype.start=function(){this.read(Je.PNG_SIGNATURE.length,this._parseSignature.bind(this))};et.prototype._parseSignature=function(t){let e=Je.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))};et.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),s=t.readUInt32BE(4),o="";for(let r=4;r<8;r++)o+=String.fromCharCode(t[r]);let n=!!(t[4]&32);if(!this._hasIHDR&&s!==Je.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new lk,this._crc.write(Buffer.from(o)),this._chunks[s])return this._chunks[s](e);if(!n){this.error(new Error("Unsupported critical chunk type "+o));return}this.read(e+4,this._skipChunk.bind(this))};et.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};et.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};et.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))};et.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};et.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),s=t.readUInt32BE(4),o=t[8],n=t[9],r=t[10],i=t[11],a=t[12];if(o!==8&&o!==4&&o!==2&&o!==1&&o!==16){this.error(new Error("Unsupported bit depth "+o));return}if(!(n in Je.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=n;let l=Je.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:s,depth:o,interlace:!!a,palette:!!(n&Je.COLORTYPE_PALETTE),color:!!(n&Je.COLORTYPE_COLOR),alpha:!!(n&Je.COLORTYPE_ALPHA),bpp:l,colorType:n}),this._handleChunkEnd()};et.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};et.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()};et.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};et.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Je.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===Je.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===Je.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};et.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};et.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Je.GAMMA_DIVISION),this._handleChunkEnd()};et.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};et.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Je.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()};et.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};et.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Ul=V(Rh=>{"use strict";var Th=Ll(),ck=[function(){},function(t,e,s,o){if(o===e.length)throw new Error("Ran out of data");let n=e[o];t[s]=n,t[s+1]=n,t[s+2]=n,t[s+3]=255},function(t,e,s,o){if(o+1>=e.length)throw new Error("Ran out of data");let n=e[o];t[s]=n,t[s+1]=n,t[s+2]=n,t[s+3]=e[o+1]},function(t,e,s,o){if(o+2>=e.length)throw new Error("Ran out of data");t[s]=e[o],t[s+1]=e[o+1],t[s+2]=e[o+2],t[s+3]=255},function(t,e,s,o){if(o+3>=e.length)throw new Error("Ran out of data");t[s]=e[o],t[s+1]=e[o+1],t[s+2]=e[o+2],t[s+3]=e[o+3]}],uk=[function(){},function(t,e,s,o){let n=e[0];t[s]=n,t[s+1]=n,t[s+2]=n,t[s+3]=o},function(t,e,s){let o=e[0];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=e[1]},function(t,e,s,o){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=o},function(t,e,s){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=e[3]}];function dk(t,e){let s=[],o=0;function n(){if(o===t.length)throw new Error("Ran out of data");let r=t[o];o++;let i,a,l,u,c,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[o],o++,s.push((r<<8)+f);break;case 4:f=r&15,h=r>>4,s.push(h,f);break;case 2:c=r&3,d=r>>2&3,f=r>>4&3,h=r>>6&3,s.push(h,f,d,c);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,u=r>>3&1,c=r>>4&1,d=r>>5&1,f=r>>6&1,h=r>>7&1,s.push(h,f,d,c,u,l,a,i);break}}return{get:function(r){for(;s.length<r;)n();let i=s.slice(0,r);return s=s.slice(r),i},resetAfterLine:function(){s.length=0},end:function(){if(o!==t.length)throw new Error("extra data found")}}}function fk(t,e,s,o,n,r){let i=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++)for(let c=0;c<i;c++){let d=s(c,u,l);ck[o](e,n,d,r),r+=o}return r}function hk(t,e,s,o,n,r){let i=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++){for(let c=0;c<i;c++){let d=n.get(o),f=s(c,u,l);uk[o](e,d,f,r)}n.resetAfterLine()}}Rh.dataToBitMap=function(t,e){let s=e.width,o=e.height,n=e.depth,r=e.bpp,i=e.interlace,a;n!==8&&(a=dk(t,n));let l;n<=8?l=Buffer.alloc(s*o*4):l=new Uint16Array(s*o*4);let u=Math.pow(2,n)-1,c=0,d,f;if(i)d=Th.getImagePasses(s,o),f=Th.getInterlaceIterator(s,o);else{let h=0;f=function(){let m=h;return h+=4,m},d=[{width:s,height:o}]}for(let h=0;h<d.length;h++)n===8?c=fk(d[h],l,f,r,t,c):hk(d[h],l,f,r,a,u);if(n===8){if(c!==t.length)throw new Error("extra data found")}else a.end();return l}});var Wl=V((bC,Ch)=>{"use strict";function pk(t,e,s,o,n){let r=0;for(let i=0;i<o;i++)for(let a=0;a<s;a++){let l=n[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let u=0;u<4;u++)e[r+u]=l[u];r+=4}}function mk(t,e,s,o,n){let r=0;for(let i=0;i<o;i++)for(let a=0;a<s;a++){let l=!1;if(n.length===1?n[0]===t[r]&&(l=!0):n[0]===t[r]&&n[1]===t[r+1]&&n[2]===t[r+2]&&(l=!0),l)for(let u=0;u<4;u++)e[r+u]=0;r+=4}}function gk(t,e,s,o,n){let r=255,i=Math.pow(2,n)-1,a=0;for(let l=0;l<o;l++)for(let u=0;u<s;u++){for(let c=0;c<4;c++)e[a+c]=Math.floor(t[a+c]*r/i+.5);a+=4}}Ch.exports=function(t,e,s=!1){let o=e.depth,n=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,u=t;return i===3?pk(t,u,n,r,l):(a&&mk(t,u,n,r,a),o!==8&&!s&&(o===16&&(u=Buffer.alloc(n*r*4)),gk(t,u,n,r,o))),u}});var Nh=V((_C,Oh)=>{"use strict";var yk=require("util"),Hl=require("zlib"),Ah=Ml(),wk=xh(),$k=Bl(),bk=Ul(),_k=Wl(),rn=Oh.exports=function(t){Ah.call(this),this._parser=new $k(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()};yk.inherits(rn,Ah);rn.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};rn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Hl.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,o=Math.max(s,Hl.Z_MIN_CHUNK);this._inflate=Hl.createInflate({chunkSize:o});let n=s,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){n&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){n&&(a.length>n&&(a=a.slice(0,n)),n-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};rn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new wk(this._bitmapInfo)};rn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};rn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};rn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};rn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};rn.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};rn.prototype._complete=function(t){if(this.errord)return;let e;try{let s=bk.dataToBitMap(t,this._bitmapInfo);e=_k(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var Ph=V((kC,Mh)=>{"use strict";var It=Fs();Mh.exports=function(t,e,s,o){let n=[It.COLORTYPE_COLOR_ALPHA,It.COLORTYPE_ALPHA].indexOf(o.colorType)!==-1;if(o.colorType===o.inputColorType){let m=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(o.bitDepth===8||o.bitDepth===16&&m)return t}let r=o.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=It.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let l=It.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,l*=2);let u=Buffer.alloc(e*s*l),c=0,d=0,f=o.bgColor||{};f.red===void 0&&(f.red=i),f.green===void 0&&(f.green=i),f.blue===void 0&&(f.blue=i);function h(){let m,g,$,k=i;switch(o.inputColorType){case It.COLORTYPE_COLOR_ALPHA:k=r[c+3],m=r[c],g=r[c+1],$=r[c+2];break;case It.COLORTYPE_COLOR:m=r[c],g=r[c+1],$=r[c+2];break;case It.COLORTYPE_ALPHA:k=r[c+1],m=r[c],g=m,$=m;break;case It.COLORTYPE_GRAYSCALE:m=r[c],g=m,$=m;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}return o.inputHasAlpha&&(n||(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 $=h(r,c);switch(o.colorType){case It.COLORTYPE_COLOR_ALPHA:case It.COLORTYPE_COLOR:o.bitDepth===8?(u[d]=$.red,u[d+1]=$.green,u[d+2]=$.blue,n&&(u[d+3]=$.alpha)):(u.writeUInt16BE($.red,d),u.writeUInt16BE($.green,d+2),u.writeUInt16BE($.blue,d+4),n&&u.writeUInt16BE($.alpha,d+6));break;case It.COLORTYPE_ALPHA:case It.COLORTYPE_GRAYSCALE:{let k=($.red+$.green+$.blue)/3;o.bitDepth===8?(u[d]=k,n&&(u[d+1]=$.alpha)):(u.writeUInt16BE(k,d),n&&u.writeUInt16BE($.alpha,d+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}c+=a,d+=l}return u}});var jh=V((xC,Ih)=>{"use strict";var Lh=Il();function kk(t,e,s,o,n){for(let r=0;r<s;r++)o[n+r]=t[e+r]}function xk(t,e,s){let o=0,n=e+s;for(let r=e;r<n;r++)o+=Math.abs(t[r]);return o}function Sk(t,e,s,o,n,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;o[n+i]=l}}function vk(t,e,s,o){let n=0;for(let r=0;r<s;r++){let i=r>=o?t[e+r-o]:0,a=t[e+r]-i;n+=Math.abs(a)}return n}function Ek(t,e,s,o,n){for(let r=0;r<s;r++){let i=e>0?t[e+r-s]:0,a=t[e+r]-i;o[n+r]=a}}function Tk(t,e,s){let o=0,n=e+s;for(let r=e;r<n;r++){let i=e>0?t[r-s]:0,a=t[r]-i;o+=Math.abs(a)}return o}function Rk(t,e,s,o,n,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,u=t[e+i]-(a+l>>1);o[n+i]=u}}function Ck(t,e,s,o){let n=0;for(let r=0;r<s;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-s]:0,l=t[e+r]-(i+a>>1);n+=Math.abs(l)}return n}function Ak(t,e,s,o,n,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,u=e>0&&i>=r?t[e+i-(s+r)]:0,c=t[e+i]-Lh(a,l,u);o[n+i]=c}}function Ok(t,e,s,o){let n=0;for(let r=0;r<s;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-s]:0,l=e>0&&r>=o?t[e+r-(s+o)]:0,u=t[e+r]-Lh(i,a,l);n+=Math.abs(u)}return n}var Nk={0:kk,1:Sk,2:Ek,3:Rk,4:Ak},Mk={0:xk,1:vk,2:Tk,3:Ck,4:Ok};Ih.exports=function(t,e,s,o,n){let r;if(!("filterType"in o)||o.filterType===-1)r=[0,1,2,3,4];else if(typeof o.filterType=="number")r=[o.filterType];else throw new Error("unrecognised filter types");o.bitDepth===16&&(n*=2);let i=e*n,a=0,l=0,u=Buffer.alloc((i+1)*s),c=r[0];for(let d=0;d<s;d++){if(r.length>1){let f=1/0;for(let h=0;h<r.length;h++){let m=Mk[r[h]](t,l,i,n);m<f&&(c=r[h],f=m)}}u[a]=c,a++,Nk[c](t,l,i,u,a,n),a+=i,l+=i}return u}});var Gl=V((SC,Dh)=>{"use strict";var dt=Fs(),Pk=Fl(),Lk=Ph(),Ik=jh(),jk=require("zlib"),Nn=Dh.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||jk.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:dt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:dt.COLORTYPE_COLOR_ALPHA,[dt.COLORTYPE_GRAYSCALE,dt.COLORTYPE_COLOR,dt.COLORTYPE_COLOR_ALPHA,dt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([dt.COLORTYPE_GRAYSCALE,dt.COLORTYPE_COLOR,dt.COLORTYPE_COLOR_ALPHA,dt.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")};Nn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Nn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Nn.prototype.filterData=function(t,e,s){let o=Lk(t,e,s,this._options),n=dt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Ik(o,e,s,this._options,n)};Nn.prototype._packChunk=function(t,e){let s=e?e.length:0,o=Buffer.alloc(s+12);return o.writeUInt32BE(s,0),o.writeUInt32BE(t,4),e&&e.copy(o,8),o.writeInt32BE(Pk.crc32(o.slice(4,o.length-4)),o.length-4),o};Nn.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*dt.GAMMA_DIVISION),0),this._packChunk(dt.TYPE_gAMA,e)};Nn.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(dt.TYPE_IHDR,s)};Nn.prototype.packIDAT=function(t){return this._packChunk(dt.TYPE_IDAT,t)};Nn.prototype.packIEND=function(){return this._packChunk(dt.TYPE_IEND,null)}});var Uh=V((vC,Bh)=>{"use strict";var Dk=require("util"),qh=require("stream"),qk=Fs(),Fk=Gl(),Fh=Bh.exports=function(t){qh.call(this);let e=t||{};this._packer=new Fk(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Dk.inherits(Fh,qh);Fh.prototype.pack=function(t,e,s,o){this.emit("data",Buffer.from(qk.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,s)),o&&this.emit("data",this._packer.packGAMA(o));let n=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(n)}});var Kh=V((Io,zh)=>{"use strict";var Wh=require("assert").ok,Bs=require("zlib"),Bk=require("util"),Hh=require("buffer").kMaxLength;function Jn(t){if(!(this instanceof Jn))return new Jn(t);t&&t.chunkSize<Bs.Z_MIN_CHUNK&&(t.chunkSize=Bs.Z_MIN_CHUNK),Bs.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 Uk(t){return new Jn(t)}function Gh(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Jn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return Bs.Inflate._processChunk.call(this,t,e,s);let o=this,n=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],u=0,c;this.on("error",function(m){c=m});function d(m,g){if(o._hadError)return;let $=r-g;if(Wh($>=0,"have should not go down"),$>0){let k=o._buffer.slice(o._offset,o._offset+$);if(o._offset+=$,k.length>i&&(k=k.slice(0,i)),l.push(k),u+=k.length,i-=k.length,i===0)return!1}return(g===0||o._offset>=o._chunkSize)&&(r=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),g===0?(a+=n-m,n=m,!0):!1}Wh(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,n,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw c;if(u>=Hh)throw Gh(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Hh.toString(16)+" bytes");let h=Buffer.concat(l,u);return Gh(this),h};Bk.inherits(Jn,Bs.Inflate);function Wk(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=Bs.Z_FINISH),t._processChunk(e,s)}function Yh(t,e){return Wk(new Jn(e),t)}zh.exports=Io=Yh;Io.Inflate=Jn;Io.createInflate=Uk;Io.inflateSync=Yh});var Yl=V((EC,Vh)=>{"use strict";var Xh=Vh.exports=function(t){this._buffer=t,this._reads=[]};Xh.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Xh.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 Zh=V(Jh=>{"use strict";var Hk=Yl(),Gk=jl();Jh.process=function(t,e){let s=[],o=new Hk(t);return new Gk(e,{read:o.read.bind(o),write:function(r){s.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(s)}});var np=V((RC,tp)=>{"use strict";var Qh=!0,ep=require("zlib"),Yk=Kh();ep.deflateSync||(Qh=!1);var zk=Yl(),Kk=Zh(),Xk=Bl(),Vk=Ul(),Jk=Wl();tp.exports=function(t,e){if(!Qh)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 o(E){s=E}let n;function r(E){n=E}function i(E){n.transColor=E}function a(E){n.palette=E}function l(){n.alpha=!0}let u;function c(E){u=E}let d=[];function f(E){d.push(E)}let h=new zk(t);if(new Xk(e,{read:h.read.bind(h),error:o,metadata:r,gamma:c,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),h.process(),s)throw s;let g=Buffer.concat(d);d.length=0;let $;if(n.interlace)$=ep.inflateSync(g);else{let S=((n.width*n.bpp*n.depth+7>>3)+1)*n.height;$=Yk(g,{chunkSize:S,maxLength:S})}if(g=null,!$||!$.length)throw new Error("bad png - invalid inflate data response");let k=Kk.process($,n);g=null;let v=Vk.dataToBitMap(k,n);k=null;let A=Jk(v,n,e.skipRescale);return n.data=A,n.gamma=u||0,n}});var ip=V((CC,rp)=>{"use strict";var sp=!0,op=require("zlib");op.deflateSync||(sp=!1);var Zk=Fs(),Qk=Gl();rp.exports=function(t,e){if(!sp)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||{},o=new Qk(s),n=[];n.push(Buffer.from(Zk.PNG_SIGNATURE)),n.push(o.packIHDR(t.width,t.height)),t.gamma&&n.push(o.packGAMA(t.gamma));let r=o.filterData(t.data,t.width,t.height),i=op.deflateSync(r,o.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return n.push(o.packIDAT(i)),n.push(o.packIEND()),Buffer.concat(n)}});var ap=V(zl=>{"use strict";var ex=np(),tx=ip();zl.read=function(t,e){return ex(t,e||{})};zl.write=function(t,e){return tx(t,e)}});var up=V(cp=>{"use strict";var nx=require("util"),lp=require("stream"),sx=Nh(),ox=Uh(),rx=ap(),pt=cp.PNG=function(t){lp.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 sx(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 ox(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"))};nx.inherits(pt,lp);pt.sync=rx;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,o;s=function(n){this.removeListener("error",o),this.data=n,e(null,this)}.bind(this),o=function(n){this.removeListener("parsed",s),e(n,null)}.bind(this),this.once("parsed",s),this.once("error",o)}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,o,n,r,i,a){if(s|=0,o|=0,n|=0,r|=0,i|=0,a|=0,s>t.width||o>t.height||s+n>t.width||o+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+n>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,(o+l)*t.width+s<<2,(o+l)*t.width+s+n<<2)};pt.prototype.bitblt=function(t,e,s,o,n,r,i){return pt.bitblt(this,t,e,s,o,n,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 o=t.width*e+s<<2;for(let n=0;n<3;n++){let r=t.data[o+n]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[o+n]=Math.round(r*255)}}t.gamma=0}};pt.prototype.adjustGamma=function(){pt.adjustGamma(this)}});var mp={};B0(mp,{default:()=>hp});function hp(t,e,s,o,n,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:u=[255,0,0],includeAA:c,diffColorAlt:d,diffMask:f}=r;if(!Kl(t)||!Kl(e)||s&&!Kl(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!==o*n*4)throw new Error("Image data size does not match width/height.");let h=o*n,m=new Uint32Array(t.buffer,t.byteOffset,h),g=new Uint32Array(e.buffer,e.byteOffset,h),$=!0;for(let ae=0;ae<h;ae++)if(m[ae]!==g[ae]){$=!1;break}if($){if(s&&!f)for(let ae=0;ae<h;ae++)fp(t,4*ae,a,s);return 0}let k=35215*i*i,[v,A,E]=l,[S,N,ee]=u,[re,le,ue]=d||u,oe=0;for(let ae=0;ae<n;ae++)for(let T=0;T<o;T++){let U=ae*o+T,Z=U*4,ye=m[U]===g[U]?0:pp(t,e,Z,Z,!1);if(Math.abs(ye)>k){let ke=dp(t,T,ae,o,n,m,g)||dp(e,T,ae,o,n,g,m);!c&&ke?s&&!f&&Si(s,Z,v,A,E):(s&&(ye<0?Si(s,Z,re,le,ue):Si(s,Z,S,N,ee)),oe++)}else s&&!f&&fp(t,Z,a,s)}return oe}function Kl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function dp(t,e,s,o,n,r,i){let a=Math.max(e-1,0),l=Math.max(s-1,0),u=Math.min(e+1,o-1),c=Math.min(s+1,n-1),d=s*o+e,f=e===a||e===u||s===l||s===c?1:0,h=0,m=0,g=0,$=0,k=0,v=0;for(let A=a;A<=u;A++)for(let E=l;E<=c;E++){if(A===e&&E===s)continue;let S=pp(t,t,d*4,(E*o+A)*4,!0);if(S===0){if(f++,f>2)return!1}else S<h?(h=S,g=A,$=E):S>m&&(m=S,k=A,v=E)}return h===0||m===0?!1:xi(r,g,$,o,n)&&xi(i,g,$,o,n)||xi(r,k,v,o,n)&&xi(i,k,v,o,n)}function xi(t,e,s,o,n){let r=Math.max(e-1,0),i=Math.max(s-1,0),a=Math.min(e+1,o-1),l=Math.min(s+1,n-1),u=t[s*o+e],c=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)&&(c+=+(u===t[f*o+d]),c>2))return!0;return!1}function pp(t,e,s,o,n){let r=t[s],i=t[s+1],a=t[s+2],l=t[s+3],u=e[o],c=e[o+1],d=e[o+2],f=e[o+3],h=r-u,m=i-c,g=a-d,$=l-f;if(!h&&!m&&!g&&!$)return 0;if(l<255||f<255){let S=48+159*(s%2),N=48+159*((s/1.618033988749895|0)%2),ee=48+159*((s/2.618033988749895|0)%2);h=(r*l-u*f-S*$)/255,m=(i*l-c*f-N*$)/255,g=(a*l-d*f-ee*$)/255}let k=h*.29889531+m*.58662247+g*.11448223;if(n)return k;let v=h*.59597799-m*.2741761-g*.32180189,A=h*.21147017-m*.52261711+g*.31114694,E=.5053*k*k+.299*v*v+.1957*A*A;return k>0?-E:E}function Si(t,e,s,o,n){t[e+0]=s,t[e+1]=o,t[e+2]=n,t[e+3]=255}function fp(t,e,s,o){let n=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;Si(o,e,n,n,n)}var gp=F0(()=>{});var Zn=V((NC,_p)=>{var $n=require("fs"),ix=require("path"),ax=require("os"),lx="nex-visual-";function wp(t){return ix.join(ax.tmpdir(),`${lx}${Date.now()}-${t}`)}var Xl=null;function vi(){return Xl||(Xl=up().PNG),Xl}var Vl=null;function cx(){if(!Vl){let t=(gp(),W0(mp));Vl=t.default||t}return Vl}function Ql(t,e,{threshold:s=.1}={}){let o=vi(),n=cx(),r=o.sync.read($n.readFileSync(t)),i=o.sync.read($n.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),u=yp(r,a,l),c=yp(i,a,l),d=new o({width:a,height:l}),f=n(u,c,d.data,a,l,{threshold:s,includeAA:!1}),h=a*l,m=(f/h*100).toFixed(1),g=ux(d.data,a,l,3,3),$=wp("diff.png");return $n.writeFileSync($,o.sync.write(d),{mode:384}),{diffPath:$,diffPercent:parseFloat(m),totalPixels:h,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function yp(t,e,s){if(t.width===e&&t.height===s)return t.data;let o=Buffer.alloc(e*s*4,0);for(let n=0;n<t.height;n++){let r=n*t.width*4,i=n*e*4;t.data.copy(o,i,r,r+t.width*4)}return o}function ux(t,e,s,o,n){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/o),a=Math.ceil(s/n),l=[];for(let u=0;u<n;u++)for(let c=0;c<o;c++){let d=0,f=0,h=c*i,m=u*a,g=Math.min(h+i,e),$=Math.min(m+a,s);for(let k=m;k<$;k++)for(let v=h;v<g;v++){f++;let A=(k*e+v)*4;(t[A]>0||t[A+1]>0)&&d++}if(d>0){let k=(d/f*100).toFixed(1),v=r[u]&&r[u][c]?r[u][c]:`row${u}-col${c}`;l.push({name:v,changedPercent:parseFloat(k),changed:d,total:f})}}return l.sort((u,c)=>c.changedPercent-u.changedPercent),l}var $p=[{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 dx(t,{viewports:e=$p,height:s=800,fullPage:o=!1,timeout:n=3e4}={}){let{browserScreenshot:r}=wn(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:s,fullPage:o,timeout:n});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function bp(t,e=[]){let s=vi(),o=s.sync.read($n.readFileSync(t));for(let i of e){let a=fx(i.color||"#FF0000");i.type==="box"?(hx(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Zl(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(px(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Zl(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(mx(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Zl(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let n=wp("annotated.png");$n.writeFileSync(n,s.sync.write(o),{mode:384});let r=$n.readFileSync(n).toString("base64");return{path:n,base64:r,media_type:"image/png"}}function fx(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 an(t,e,s,o){if(e<0||s<0||e>=t.width||s>=t.height)return;let n=(s*t.width+e)*4;t.data[n]=o.r,t.data[n+1]=o.g,t.data[n+2]=o.b,t.data[n+3]=o.a}function hx(t,e,s,o,n,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<o;l++)an(t,e+l,s+a,r),an(t,e+l,s+n-1-a,r);for(let l=0;l<n;l++)an(t,e+a,s+l,r),an(t,e+o-1-a,s+l,r)}}function Jl(t,e,s,o,n,r,i=3){let a=Math.abs(o-e),l=Math.abs(n-s),u=e<o?1:-1,c=s<n?1:-1,d=a-l,f=e,h=s;for(;;){let m=Math.floor(i/2);for(let $=-m;$<=m;$++)for(let k=-m;k<=m;k++)an(t,f+$,h+k,r);if(f===o&&h===n)break;let g=2*d;g>-l&&(d-=l,f+=u),g<a&&(d+=a,h+=c)}}function px(t,e,s,o,n,r,i=3){Jl(t,e,s,o,n,r,i);let a=Math.atan2(n-s,o-e),l=15,u=a+Math.PI*.8,c=a-Math.PI*.8;Jl(t,o,n,Math.round(o+l*Math.cos(u)),Math.round(n+l*Math.sin(u)),r,i),Jl(t,o,n,Math.round(o+l*Math.cos(c)),Math.round(n+l*Math.sin(c)),r,i)}function mx(t,e,s,o,n,r=3){for(let i=0;i<r;i++){let a=o-i;for(let l=0;l<360;l+=.5){let u=l*Math.PI/180,c=Math.round(e+a*Math.cos(u)),d=Math.round(s+a*Math.sin(u));an(t,c,d,n)}}}function Zl(t,e,s,o,n){let i=o.length*6+4,a=12;for(let l=0;l<a;l++)for(let u=0;u<i;u++)an(t,e+u,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)an(t,e+l,s+a-1,n),an(t,e+l,s+a-2,n);for(let l=0;l<o.length;l++){let u=e+2+l*6;for(let c=2;c<9;c++)for(let d=0;d<4;d++)an(t,u+d,s+c,n)}}async function*gx(t,e,{maxIterations:s=20,hmrDelay:o=1500,width:n=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=wn(),l=yx("chokidar"),u=await a(t,{width:n,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:u.path,base64:u.base64,media_type:u.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let c=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;c<s;){await $x(()=>d,3e5),d=!1,c++,await wx(o);let h=await a(t,{width:n,height:r,timeout:i}),m=null;try{m=Ql(u.path,h.path)}catch{}u=h,yield{iteration:c,type:"change",path:h.path,base64:h.base64,media_type:h.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function yx(t){try{return require(t)}catch{return null}}function wx(t){return new Promise(e=>setTimeout(e,t))}function $x(t,e=6e4){return new Promise((s,o)=>{let n=setInterval(()=>{t()&&(clearInterval(n),clearTimeout(r),s())},200),r=setTimeout(()=>{clearInterval(n),o(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function bx(t,{sampleRate:e=4}={}){let o=vi().sync.read($n.readFileSync(t)),n=new Map;for(let u=0;u<o.height;u+=e)for(let c=0;c<o.width;c+=e){let d=(u*o.width+c)*4,f=o.data[d],h=o.data[d+1],m=o.data[d+2];if(o.data[d+3]<128)continue;let $=Math.round(f/8)*8,k=Math.round(h/8)*8,v=Math.round(m/8)*8,A=`${$},${k},${v}`;n.set(A,(n.get(A)||0)+1)}let r=[...n.entries()].sort((u,c)=>c[1]-u[1]).slice(0,20),i=r.reduce((u,c)=>u+c[1],0),a=r.map(([u,c])=>{let[d,f,h]=u.split(",").map(Number);return{hex:_x(d,f,h),rgb:`rgb(${d}, ${f}, ${h})`,frequency:parseFloat((c/i*100).toFixed(1)),category:kx(d,f,h)}}),l=xx(o);return{colors:a,spacing:l,dimensions:{width:o.width,height:o.height},imagePath:t}}function _x(t,e,s){return"#"+[t,e,s].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function kx(t,e,s){let o=(t*299+e*587+s*114)/1e3;return o>240?"white/background":o<30?"black/text":o<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":o>200?"light/subtle":"midtone"}function xx(t){let e=[],s=!1,o=0,n=Sx(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let u=(i*t.width+l)*4;if(Math.abs(t.data[u]-n.r)>20||Math.abs(t.data[u+1]-n.g)>20||Math.abs(t.data[u+2]-n.b)>20){a=!1;break}}if(a&&s)s=!1,o=i;else if(!a&&!s&&(s=!0,o>0)){let l=i-o;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 Sx(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],s=0,o=0,n=0;for(let[r,i]of e){let a=(i*t.width+r)*4;s+=t.data[a],o+=t.data[a+1],n+=t.data[a+2]}return{r:Math.round(s/4),g:Math.round(o/4),b:Math.round(n/4)}}async function vx(t,e,{width:s,height:o=800,fullPage:n=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=wn(),u=vi().sync.read($n.readFileSync(e)),c=s||u.width,d=o||u.height,f=await a(t,{width:c,height:d,fullPage:n,timeout:i}),h=Ql(e,f.path,{threshold:r}),m=bp(f.path,h.regionSummary.filter(g=>g.changedPercent>1).map((g,$)=>{let A=Math.ceil(h.width/3),E=Math.ceil(h.height/3),S=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],N=0,ee=0;for(let re=0;re<3;re++)for(let le=0;le<3;le++)S[re][le]===g.name&&(N=le,ee=re);return{type:"box",x:N*A+2,y:ee*E+2,width:A-4,height:E-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:h.diffPath,annotatedPath:m.path,diffPercent:h.diffPercent,changedPixels:h.changedPixels,totalPixels:h.totalPixels,regions:h.regionSummary,liveBase64:f.base64,diffBase64:$n.readFileSync(h.diffPath).toString("base64"),annotatedBase64:m.base64}}_p.exports={pixelDiff:Ql,responsiveSweep:dx,annotateImage:bp,visualWatch:gx,extractDesignTokens:bx,designCompare:vx,DEFAULT_VIEWPORTS:$p}});var ec=V((MC,kp)=>{var{C:je}=ot(),Do="",mt=[],jo=0,Qn=null;function Ex(t){Qn=t}function Tx(t,e){Do=t,mt=[],jo=0;for(let o of e){jo++;let n=`t${jo}`;mt.push({id:n,description:o.description||o.title||o.name||o.task||`Task ${jo}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let s=mt.map(o=>({...o}));return Qn&&Qn("create",{name:t,tasks:s}),s}function Rx(t,e,s){let o=mt.find(n=>n.id===t);return o?(o.status=e,s!==void 0&&(o.result=s),Qn&&Qn("update",{id:t,status:e,result:s}),{...o}):null}function Cx(){return{name:Do,tasks:mt.map(t=>({...t}))}}function Ax(){Do="",mt=[],jo=0,Qn&&Qn("clear",{})}function Ox(){return mt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=mt.find(o=>o.id===e);return s&&s.status==="done"}))}function Nx(){if(mt.length===0)return`${je.dim}No active tasks${je.reset}`;let t=[];Do&&(t.push(` ${je.bold}${je.cyan}Tasks: ${Do}${je.reset}`),t.push(` ${je.dim}${"\u2500".repeat(40)}${je.reset}`));for(let n of mt){let r,i;switch(n.status){case"done":r="\u2713",i=je.green;break;case"in_progress":r="\u2192",i=je.cyan;break;case"failed":r="\u2717",i=je.red;break;default:r="\xB7",i=je.dim}let a=n.dependsOn.length>0?` ${je.dim}(after: ${n.dependsOn.join(", ")})${je.reset}`:"",l=`[${n.status}]`,u=n.description.length>50?n.description.substring(0,47)+"...":n.description;if(t.push(` ${i}${r}${je.reset} ${je.bold}${n.id}${je.reset} ${u.padEnd(40)} ${i}${l}${je.reset}${a}`),n.result&&n.status==="done"){let c=n.result.length>60?n.result.substring(0,57)+"...":n.result;t.push(` ${je.dim}\u2192 ${c}${je.reset}`)}}let e=mt.filter(n=>n.status==="done").length,s=mt.filter(n=>n.status==="failed").length,o=mt.length;return t.push(` ${je.dim}${"\u2500".repeat(40)}${je.reset}`),t.push(` ${je.dim}${e}/${o} done${s>0?`, ${s} failed`:""}${je.reset}`),t.join(`
144
- `)}function Mx(){return mt.length>0&&mt.some(t=>t.status==="pending"||t.status==="in_progress")}kp.exports={createTasks:Tx,updateTask:Rx,getTaskList:Cx,clearTasks:Ax,getReadyTasks:Ox,renderTaskList:Nx,setOnChange:Ex,hasActiveTasks:Mx}});var nc=V((PC,Rp)=>{var{callChat:Px}=ut(),{estimateTokens:tc}=ln(),xp=process.env.NEX_COMPACTION!=="false",Sp=6,vp=2e3,Ep=3,Lx=`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.
150
+ Then restart nex-code.`;function jh(){if(jo!==null)return jo;try{require("playwright"),jo=!0}catch{jo=!1}return jo}async function vi(){if(!jh())throw new Error(Ih);return ql||(ql=require("playwright")),(!_n||!_n.isConnected())&&(_n=await ql.chromium.launch({headless:!0})),_n}async function Lx(){if(_n){try{await _n.close()}catch(t){console.error("closeBrowser failed:",t.message)}_n=null}}process.on("exit",()=>{if(_n)try{_n.close()}catch(t){console.error("Error closing browser on exit:",t.message)}});async function Ix(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await vi()).newPage();try{await s.goto(t,{waitUntil:n,timeout:e});let r=await s.title(),i=await s.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),a=await s.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:s.url(),text:i.substring(0,8e3)+(i.length>8e3?`
151
+ ...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function jx(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await vi()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:s});let a=await i.screenshot({type:"png",fullPage:o}),l=require("os"),u=require("path"),c=require("fs"),d=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return c.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 Dx(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await vi()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),n?await r.getByText(n,{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 qx(t,{selector:e,value:n,submit:o=!1,timeout:s=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await vi()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:s}),await i.fill(e,String(n)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}Dh.exports={isPlaywrightAvailable:jh,browserNavigate:Ix,browserScreenshot:jx,browserClick:Dx,browserFill:qx,closeBrowser:Lx,INSTALL_MSG:Ih}});var Fl=Z((QC,Fh)=>{"use strict";var Fx=require("util"),qh=require("stream"),Kt=Fh.exports=function(){qh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Fx.inherits(Kt,qh);Kt.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))};Kt.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Kt.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()))};Kt.prototype.destroySoon=Kt.prototype.end;Kt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Kt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Kt.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))};Kt.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,o=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],r=Math.min(s.length,t.length-e);s.copy(o,e,0,r),e+=r,r!==s.length&&(this._buffers[--n]=s.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,o)};Kt.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(Bl=>{"use strict";var Pn=[{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]}];Bl.getImagePasses=function(t,e){let n=[],o=t%8,s=e%8,r=(t-o)/8,i=(e-s)/8;for(let a=0;a<Pn.length;a++){let l=Pn[a],u=r*l.x.length,c=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<o;d++)u++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)c++;u>0&&c>0&&n.push({width:u,height:c,index:a})}return n};Bl.getInterlaceIterator=function(t){return function(e,n,o){let s=e%Pn[o].x.length,r=(e-s)/Pn[o].x.length*8+Pn[o].x[s],i=n%Pn[o].y.length,a=(n-i)/Pn[o].y.length*8+Pn[o].y[i];return r*4+a*t*4}}});var Wl=Z((tA,Bh)=>{"use strict";Bh.exports=function(e,n,o){let s=e+n-o,r=Math.abs(s-e),i=Math.abs(s-n),a=Math.abs(s-o);return r<=i&&r<=a?e:i<=a?n:o}});var Hl=Z((nA,Wh)=>{"use strict";var Bx=Ul(),Ux=Wl();function Uh(t,e,n){let o=t*e;return n!==8&&(o=Math.ceil(o/(8/n))),o}var Hs=Wh.exports=function(t,e){let n=t.width,o=t.height,s=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=[],s){let a=Bx.getImagePasses(n,o);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Uh(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Uh(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Hs.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Hs.prototype._unFilterType1=function(t,e,n){let o=this._xComparison,s=o-1;for(let r=0;r<n;r++){let i=t[1+r],a=r>s?e[r-o]:0;e[r]=i+a}};Hs.prototype._unFilterType2=function(t,e,n){let o=this._lastLine;for(let s=0;s<n;s++){let r=t[1+s],i=o?o[s]:0;e[s]=r+i}};Hs.prototype._unFilterType3=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],l=r?r[i]:0,u=i>s?e[i-o]:0,c=Math.floor((u+l)/2);e[i]=a+c}};Hs.prototype._unFilterType4=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],l=r?r[i]:0,u=i>s?e[i-o]:0,c=i>s&&r?r[i-o]:0,d=Ux(u,l,c);e[i]=a+d}};Hs.prototype._reverseFilterLine=function(t){let e=t[0],n,o=this._images[this._imageIndex],s=o.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),o.lineIndex++,o.lineIndex>=o.height?(this._lastLine=null,this._imageIndex++,o=this._images[this._imageIndex]):this._lastLine=n,o?this.read(o.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Gh=Z((sA,Yh)=>{"use strict";var Wx=require("util"),Hh=Fl(),Hx=Hl(),Yx=Yh.exports=function(t){Hh.call(this);let e=[],n=this;this._filter=new Hx(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Wx.inherits(Yx,Hh)});var Ys=Z((oA,zh)=>{"use strict";zh.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 zl=Z((rA,Kh)=>{"use strict";var Yl=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;Yl[t]=e}})();var Gl=Kh.exports=function(){this._crc=-1};Gl.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Yl[(this._crc^t[e])&255]^this._crc>>>8;return!0};Gl.prototype.crc32=function(){return this._crc^-1};Gl.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Yl[(e^t[n])&255]^e>>>8;return e^-1}});var Kl=Z((iA,Xh)=>{"use strict";var nt=Ys(),Gx=zl(),ot=Xh.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[nt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[nt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[nt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[nt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[nt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[nt.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(){}};ot.prototype.start=function(){this.read(nt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};ot.prototype._parseSignature=function(t){let e=nt.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};ot.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o="";for(let r=4;r<8;r++)o+=String.fromCharCode(t[r]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==nt.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Gx,this._crc.write(Buffer.from(o)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+o));return}this.read(e+4,this._skipChunk.bind(this))};ot.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};ot.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};ot.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};ot.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};ot.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o=t[8],s=t[9],r=t[10],i=t[11],a=t[12];if(o!==8&&o!==4&&o!==2&&o!==1&&o!==16){this.error(new Error("Unsupported bit depth "+o));return}if(!(s in nt.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=s;let l=nt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:o,interlace:!!a,palette:!!(s&nt.COLORTYPE_PALETTE),color:!!(s&nt.COLORTYPE_COLOR),alpha:!!(s&nt.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};ot.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};ot.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};ot.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};ot.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===nt.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===nt.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===nt.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};ot.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};ot.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/nt.GAMMA_DIVISION),this._handleChunkEnd()};ot.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};ot.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===nt.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};ot.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};ot.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Xl=Z(Jh=>{"use strict";var Vh=Ul(),zx=[function(){},function(t,e,n,o){if(o===e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,o){if(o+1>=e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[o+1]},function(t,e,n,o){if(o+2>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=255},function(t,e,n,o){if(o+3>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=e[o+3]}],Kx=[function(){},function(t,e,n,o){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=o},function(t,e,n){let o=e[0];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=e[1]},function(t,e,n,o){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=o},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function Xx(t,e){let n=[],o=0;function s(){if(o===t.length)throw new Error("Ran out of data");let r=t[o];o++;let i,a,l,u,c,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[o],o++,n.push((r<<8)+f);break;case 4:f=r&15,h=r>>4,n.push(h,f);break;case 2:c=r&3,d=r>>2&3,f=r>>4&3,h=r>>6&3,n.push(h,f,d,c);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,u=r>>3&1,c=r>>4&1,d=r>>5&1,f=r>>6&1,h=r>>7&1,n.push(h,f,d,c,u,l,a,i);break}}return{get:function(r){for(;n.length<r;)s();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(o!==t.length)throw new Error("extra data found")}}}function Vx(t,e,n,o,s,r){let i=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++)for(let c=0;c<i;c++){let d=n(c,u,l);zx[o](e,s,d,r),r+=o}return r}function Jx(t,e,n,o,s,r){let i=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++){for(let c=0;c<i;c++){let d=s.get(o),f=n(c,u,l);Kx[o](e,d,f,r)}s.resetAfterLine()}}Jh.dataToBitMap=function(t,e){let n=e.width,o=e.height,s=e.depth,r=e.bpp,i=e.interlace,a;s!==8&&(a=Xx(t,s));let l;s<=8?l=Buffer.alloc(n*o*4):l=new Uint16Array(n*o*4);let u=Math.pow(2,s)-1,c=0,d,f;if(i)d=Vh.getImagePasses(n,o),f=Vh.getInterlaceIterator(n,o);else{let h=0;f=function(){let m=h;return h+=4,m},d=[{width:n,height:o}]}for(let h=0;h<d.length;h++)s===8?c=Vx(d[h],l,f,r,t,c):Jx(d[h],l,f,r,a,u);if(s===8){if(c!==t.length)throw new Error("extra data found")}else a.end();return l}});var Vl=Z((lA,Zh)=>{"use strict";function Zx(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let l=s[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let u=0;u<4;u++)e[r+u]=l[u];r+=4}}function Qx(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[r]&&(l=!0):s[0]===t[r]&&s[1]===t[r+1]&&s[2]===t[r+2]&&(l=!0),l)for(let u=0;u<4;u++)e[r+u]=0;r+=4}}function ek(t,e,n,o,s){let r=255,i=Math.pow(2,s)-1,a=0;for(let l=0;l<o;l++)for(let u=0;u<n;u++){for(let c=0;c<4;c++)e[a+c]=Math.floor(t[a+c]*r/i+.5);a+=4}}Zh.exports=function(t,e,n=!1){let o=e.depth,s=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,u=t;return i===3?Zx(t,u,s,r,l):(a&&Qx(t,u,s,r,a),o!==8&&!n&&(o===16&&(u=Buffer.alloc(s*r*4)),ek(t,u,s,r,o))),u}});var tp=Z((cA,ep)=>{"use strict";var tk=require("util"),Jl=require("zlib"),Qh=Fl(),nk=Gh(),sk=Kl(),ok=Xl(),rk=Vl(),cn=ep.exports=function(t){Qh.call(this),this._parser=new sk(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()};tk.inherits(cn,Qh);cn.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};cn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Jl.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 n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,o=Math.max(n,Jl.Z_MIN_CHUNK);this._inflate=Jl.createInflate({chunkSize:o});let s=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};cn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new nk(this._bitmapInfo)};cn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};cn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};cn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};cn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};cn.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};cn.prototype._complete=function(t){if(this.errord)return;let e;try{let n=ok.dataToBitMap(t,this._bitmapInfo);e=rk(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var sp=Z((uA,np)=>{"use strict";var jt=Ys();np.exports=function(t,e,n,o){let s=[jt.COLORTYPE_COLOR_ALPHA,jt.COLORTYPE_ALPHA].indexOf(o.colorType)!==-1;if(o.colorType===o.inputColorType){let m=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(o.bitDepth===8||o.bitDepth===16&&m)return t}let r=o.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=jt.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let l=jt.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,l*=2);let u=Buffer.alloc(e*n*l),c=0,d=0,f=o.bgColor||{};f.red===void 0&&(f.red=i),f.green===void 0&&(f.green=i),f.blue===void 0&&(f.blue=i);function h(){let m,g,$,x=i;switch(o.inputColorType){case jt.COLORTYPE_COLOR_ALPHA:x=r[c+3],m=r[c],g=r[c+1],$=r[c+2];break;case jt.COLORTYPE_COLOR:m=r[c],g=r[c+1],$=r[c+2];break;case jt.COLORTYPE_ALPHA:x=r[c+1],m=r[c],g=m,$=m;break;case jt.COLORTYPE_GRAYSCALE:m=r[c],g=m,$=m;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}return o.inputHasAlpha&&(s||(x/=i,m=Math.min(Math.max(Math.round((1-x)*f.red+x*m),0),i),g=Math.min(Math.max(Math.round((1-x)*f.green+x*g),0),i),$=Math.min(Math.max(Math.round((1-x)*f.blue+x*$),0),i))),{red:m,green:g,blue:$,alpha:x}}for(let m=0;m<n;m++)for(let g=0;g<e;g++){let $=h(r,c);switch(o.colorType){case jt.COLORTYPE_COLOR_ALPHA:case jt.COLORTYPE_COLOR:o.bitDepth===8?(u[d]=$.red,u[d+1]=$.green,u[d+2]=$.blue,s&&(u[d+3]=$.alpha)):(u.writeUInt16BE($.red,d),u.writeUInt16BE($.green,d+2),u.writeUInt16BE($.blue,d+4),s&&u.writeUInt16BE($.alpha,d+6));break;case jt.COLORTYPE_ALPHA:case jt.COLORTYPE_GRAYSCALE:{let x=($.red+$.green+$.blue)/3;o.bitDepth===8?(u[d]=x,s&&(u[d+1]=$.alpha)):(u.writeUInt16BE(x,d),s&&u.writeUInt16BE($.alpha,d+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}c+=a,d+=l}return u}});var ip=Z((dA,rp)=>{"use strict";var op=Wl();function ik(t,e,n,o,s){for(let r=0;r<n;r++)o[s+r]=t[e+r]}function ak(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++)o+=Math.abs(t[r]);return o}function lk(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;o[s+i]=l}}function ck(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=t[e+r]-i;s+=Math.abs(a)}return s}function uk(t,e,n,o,s){for(let r=0;r<n;r++){let i=e>0?t[e+r-n]:0,a=t[e+r]-i;o[s+r]=a}}function dk(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++){let i=e>0?t[r-n]:0,a=t[r]-i;o+=Math.abs(a)}return o}function fk(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-n]:0,u=t[e+i]-(a+l>>1);o[s+i]=u}}function hk(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,l=t[e+r]-(i+a>>1);s+=Math.abs(l)}return s}function pk(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-n]:0,u=e>0&&i>=r?t[e+i-(n+r)]:0,c=t[e+i]-op(a,l,u);o[s+i]=c}}function mk(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,l=e>0&&r>=o?t[e+r-(n+o)]:0,u=t[e+r]-op(i,a,l);s+=Math.abs(u)}return s}var gk={0:ik,1:lk,2:uk,3:fk,4:pk},yk={0:ak,1:ck,2:dk,3:hk,4:mk};rp.exports=function(t,e,n,o,s){let r;if(!("filterType"in o)||o.filterType===-1)r=[0,1,2,3,4];else if(typeof o.filterType=="number")r=[o.filterType];else throw new Error("unrecognised filter types");o.bitDepth===16&&(s*=2);let i=e*s,a=0,l=0,u=Buffer.alloc((i+1)*n),c=r[0];for(let d=0;d<n;d++){if(r.length>1){let f=1/0;for(let h=0;h<r.length;h++){let m=yk[r[h]](t,l,i,s);m<f&&(c=r[h],f=m)}}u[a]=c,a++,gk[c](t,l,i,u,a,s),a+=i,l+=i}return u}});var Zl=Z((fA,ap)=>{"use strict";var ft=Ys(),wk=zl(),$k=sp(),bk=ip(),_k=require("zlib"),Mn=ap.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||_k.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:ft.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:ft.COLORTYPE_COLOR_ALPHA,[ft.COLORTYPE_GRAYSCALE,ft.COLORTYPE_COLOR,ft.COLORTYPE_COLOR_ALPHA,ft.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([ft.COLORTYPE_GRAYSCALE,ft.COLORTYPE_COLOR,ft.COLORTYPE_COLOR_ALPHA,ft.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")};Mn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Mn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Mn.prototype.filterData=function(t,e,n){let o=$k(t,e,n,this._options),s=ft.COLORTYPE_TO_BPP_MAP[this._options.colorType];return bk(o,e,n,this._options,s)};Mn.prototype._packChunk=function(t,e){let n=e?e.length:0,o=Buffer.alloc(n+12);return o.writeUInt32BE(n,0),o.writeUInt32BE(t,4),e&&e.copy(o,8),o.writeInt32BE(wk.crc32(o.slice(4,o.length-4)),o.length-4),o};Mn.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*ft.GAMMA_DIVISION),0),this._packChunk(ft.TYPE_gAMA,e)};Mn.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(ft.TYPE_IHDR,n)};Mn.prototype.packIDAT=function(t){return this._packChunk(ft.TYPE_IDAT,t)};Mn.prototype.packIEND=function(){return this._packChunk(ft.TYPE_IEND,null)}});var dp=Z((hA,up)=>{"use strict";var xk=require("util"),lp=require("stream"),kk=Ys(),Sk=Zl(),cp=up.exports=function(t){lp.call(this);let e=t||{};this._packer=new Sk(e),this._deflate=this._packer.createDeflate(),this.readable=!0};xk.inherits(cp,lp);cp.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(kk.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),o&&this.emit("data",this._packer.packGAMA(o));let s=this._packer.filterData(t,e,n);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(s)}});var yp=Z((Do,gp)=>{"use strict";var fp=require("assert").ok,Gs=require("zlib"),vk=require("util"),hp=require("buffer").kMaxLength;function Zn(t){if(!(this instanceof Zn))return new Zn(t);t&&t.chunkSize<Gs.Z_MIN_CHUNK&&(t.chunkSize=Gs.Z_MIN_CHUNK),Gs.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 Ek(t){return new Zn(t)}function pp(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Zn.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Gs.Inflate._processChunk.call(this,t,e,n);let o=this,s=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],u=0,c;this.on("error",function(m){c=m});function d(m,g){if(o._hadError)return;let $=r-g;if(fp($>=0,"have should not go down"),$>0){let x=o._buffer.slice(o._offset,o._offset+$);if(o._offset+=$,x.length>i&&(x=x.slice(0,i)),l.push(x),u+=x.length,i-=x.length,i===0)return!1}return(g===0||o._offset>=o._chunkSize)&&(r=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),g===0?(a+=s-m,s=m,!0):!1}fp(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw c;if(u>=hp)throw pp(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+hp.toString(16)+" bytes");let h=Buffer.concat(l,u);return pp(this),h};vk.inherits(Zn,Gs.Inflate);function Tk(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=Gs.Z_FINISH),t._processChunk(e,n)}function mp(t,e){return Tk(new Zn(e),t)}gp.exports=Do=mp;Do.Inflate=Zn;Do.createInflate=Ek;Do.inflateSync=mp});var Ql=Z((pA,$p)=>{"use strict";var wp=$p.exports=function(t){this._buffer=t,this._reads=[]};wp.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};wp.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 _p=Z(bp=>{"use strict";var Rk=Ql(),Ck=Hl();bp.process=function(t,e){let n=[],o=new Rk(t);return new Ck(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var vp=Z((gA,Sp)=>{"use strict";var xp=!0,kp=require("zlib"),Ak=yp();kp.deflateSync||(xp=!1);var Ok=Ql(),Nk=_p(),Pk=Kl(),Mk=Xl(),Lk=Vl();Sp.exports=function(t,e){if(!xp)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function o(v){n=v}let s;function r(v){s=v}function i(v){s.transColor=v}function a(v){s.palette=v}function l(){s.alpha=!0}let u;function c(v){u=v}let d=[];function f(v){d.push(v)}let h=new Ok(t);if(new Pk(e,{read:h.read.bind(h),error:o,metadata:r,gamma:c,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let g=Buffer.concat(d);d.length=0;let $;if(s.interlace)$=kp.inflateSync(g);else{let S=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;$=Ak(g,{chunkSize:S,maxLength:S})}if(g=null,!$||!$.length)throw new Error("bad png - invalid inflate data response");let x=Nk.process($,s);g=null;let E=Mk.dataToBitMap(x,s);x=null;let N=Lk(E,s,e.skipRescale);return s.data=N,s.gamma=u||0,s}});var Cp=Z((yA,Rp)=>{"use strict";var Ep=!0,Tp=require("zlib");Tp.deflateSync||(Ep=!1);var Ik=Ys(),jk=Zl();Rp.exports=function(t,e){if(!Ep)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},o=new jk(n),s=[];s.push(Buffer.from(Ik.PNG_SIGNATURE)),s.push(o.packIHDR(t.width,t.height)),t.gamma&&s.push(o.packGAMA(t.gamma));let r=o.filterData(t.data,t.width,t.height),i=Tp.deflateSync(r,o.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return s.push(o.packIDAT(i)),s.push(o.packIEND()),Buffer.concat(s)}});var Ap=Z(ec=>{"use strict";var Dk=vp(),qk=Cp();ec.read=function(t,e){return Dk(t,e||{})};ec.write=function(t,e){return qk(t,e)}});var Pp=Z(Np=>{"use strict";var Fk=require("util"),Op=require("stream"),Bk=tp(),Uk=dp(),Wk=Ap(),mt=Np.PNG=function(t){Op.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 Bk(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 Uk(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"))};Fk.inherits(mt,Op);mt.sync=Wk;mt.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)};mt.prototype.parse=function(t,e){if(e){let n,o;n=function(s){this.removeListener("error",o),this.data=s,e(null,this)}.bind(this),o=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",o)}return this.end(t),this};mt.prototype.write=function(t){return this._parser.write(t),!0};mt.prototype.end=function(t){this._parser.end(t)};mt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};mt.prototype._gamma=function(t){this.gamma=t};mt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};mt.bitblt=function(t,e,n,o,s,r,i,a){if(n|=0,o|=0,s|=0,r|=0,i|=0,a|=0,n>t.width||o>t.height||n+s>t.width||o+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+s>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,(o+l)*t.width+n<<2,(o+l)*t.width+n+s<<2)};mt.prototype.bitblt=function(t,e,n,o,s,r,i){return mt.bitblt(this,t,e,n,o,s,r,i),this};mt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let o=t.width*e+n<<2;for(let s=0;s<3;s++){let r=t.data[o+s]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[o+s]=Math.round(r*255)}}t.gamma=0}};mt.prototype.adjustGamma=function(){mt.adjustGamma(this)}});var Dp={};dw(Dp,{default:()=>Ip});function Ip(t,e,n,o,s,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:u=[255,0,0],includeAA:c,diffColorAlt:d,diffMask:f}=r;if(!tc(t)||!tc(e)||n&&!tc(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||n&&n.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==o*s*4)throw new Error("Image data size does not match width/height.");let h=o*s,m=new Uint32Array(t.buffer,t.byteOffset,h),g=new Uint32Array(e.buffer,e.byteOffset,h),$=!0;for(let le=0;le<h;le++)if(m[le]!==g[le]){$=!1;break}if($){if(n&&!f)for(let le=0;le<h;le++)Lp(t,4*le,a,n);return 0}let x=35215*i*i,[E,N,v]=l,[S,P,ne]=u,[re,ce,de]=d||u,oe=0;for(let le=0;le<s;le++)for(let T=0;T<o;T++){let q=le*o+T,Q=q*4,we=m[q]===g[q]?0:jp(t,e,Q,Q,!1);if(Math.abs(we)>x){let ke=Mp(t,T,le,o,s,m,g)||Mp(e,T,le,o,s,g,m);!c&&ke?n&&!f&&Ti(n,Q,E,N,v):(n&&(we<0?Ti(n,Q,re,ce,de):Ti(n,Q,S,P,ne)),oe++)}else n&&!f&&Lp(t,Q,a,n)}return oe}function tc(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Mp(t,e,n,o,s,r,i){let a=Math.max(e-1,0),l=Math.max(n-1,0),u=Math.min(e+1,o-1),c=Math.min(n+1,s-1),d=n*o+e,f=e===a||e===u||n===l||n===c?1:0,h=0,m=0,g=0,$=0,x=0,E=0;for(let N=a;N<=u;N++)for(let v=l;v<=c;v++){if(N===e&&v===n)continue;let S=jp(t,t,d*4,(v*o+N)*4,!0);if(S===0){if(f++,f>2)return!1}else S<h?(h=S,g=N,$=v):S>m&&(m=S,x=N,E=v)}return h===0||m===0?!1:Ei(r,g,$,o,s)&&Ei(i,g,$,o,s)||Ei(r,x,E,o,s)&&Ei(i,x,E,o,s)}function Ei(t,e,n,o,s){let r=Math.max(e-1,0),i=Math.max(n-1,0),a=Math.min(e+1,o-1),l=Math.min(n+1,s-1),u=t[n*o+e],c=e===r||e===a||n===i||n===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===n)&&(c+=+(u===t[f*o+d]),c>2))return!0;return!1}function jp(t,e,n,o,s){let r=t[n],i=t[n+1],a=t[n+2],l=t[n+3],u=e[o],c=e[o+1],d=e[o+2],f=e[o+3],h=r-u,m=i-c,g=a-d,$=l-f;if(!h&&!m&&!g&&!$)return 0;if(l<255||f<255){let S=48+159*(n%2),P=48+159*((n/1.618033988749895|0)%2),ne=48+159*((n/2.618033988749895|0)%2);h=(r*l-u*f-S*$)/255,m=(i*l-c*f-P*$)/255,g=(a*l-d*f-ne*$)/255}let x=h*.29889531+m*.58662247+g*.11448223;if(s)return x;let E=h*.59597799-m*.2741761-g*.32180189,N=h*.21147017-m*.52261711+g*.31114694,v=.5053*x*x+.299*E*E+.1957*N*N;return x>0?-v:v}function Ti(t,e,n,o,s){t[e+0]=n,t[e+1]=o,t[e+2]=s,t[e+3]=255}function Lp(t,e,n,o){let s=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;Ti(o,e,s,s,s)}var qp=uw(()=>{});var Qn=Z((bA,Hp)=>{var kn=require("fs"),Hk=require("path"),Yk=require("os"),Gk="nex-visual-";function Bp(t){return Hk.join(Yk.tmpdir(),`${Gk}${Date.now()}-${t}`)}var nc=null;function Ri(){return nc||(nc=Pp().PNG),nc}var sc=null;function zk(){if(!sc){let t=(qp(),hw(Dp));sc=t.default||t}return sc}function ic(t,e,{threshold:n=.1}={}){let o=Ri(),s=zk(),r=o.sync.read(kn.readFileSync(t)),i=o.sync.read(kn.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),u=Fp(r,a,l),c=Fp(i,a,l),d=new o({width:a,height:l}),f=s(u,c,d.data,a,l,{threshold:n,includeAA:!1}),h=a*l,m=(f/h*100).toFixed(1),g=Kk(d.data,a,l,3,3),$=Bp("diff.png");return kn.writeFileSync($,o.sync.write(d),{mode:384}),{diffPath:$,diffPercent:parseFloat(m),totalPixels:h,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function Fp(t,e,n){if(t.width===e&&t.height===n)return t.data;let o=Buffer.alloc(e*n*4,0);for(let s=0;s<t.height;s++){let r=s*t.width*4,i=s*e*4;t.data.copy(o,i,r,r+t.width*4)}return o}function Kk(t,e,n,o,s){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/o),a=Math.ceil(n/s),l=[];for(let u=0;u<s;u++)for(let c=0;c<o;c++){let d=0,f=0,h=c*i,m=u*a,g=Math.min(h+i,e),$=Math.min(m+a,n);for(let x=m;x<$;x++)for(let E=h;E<g;E++){f++;let N=(x*e+E)*4;(t[N]>0||t[N+1]>0)&&d++}if(d>0){let x=(d/f*100).toFixed(1),E=r[u]&&r[u][c]?r[u][c]:`row${u}-col${c}`;l.push({name:E,changedPercent:parseFloat(x),changed:d,total:f})}}return l.sort((u,c)=>c.changedPercent-u.changedPercent),l}var Up=[{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 Xk(t,{viewports:e=Up,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=xn(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:n,fullPage:o,timeout:s});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function Wp(t,e=[]){let n=Ri(),o=n.sync.read(kn.readFileSync(t));for(let i of e){let a=Vk(i.color||"#FF0000");i.type==="box"?(Jk(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&rc(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(Zk(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&rc(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(Qk(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&rc(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=Bp("annotated.png");kn.writeFileSync(s,n.sync.write(o),{mode:384});let r=kn.readFileSync(s).toString("base64");return{path:s,base64:r,media_type:"image/png"}}function Vk(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 un(t,e,n,o){if(e<0||n<0||e>=t.width||n>=t.height)return;let s=(n*t.width+e)*4;t.data[s]=o.r,t.data[s+1]=o.g,t.data[s+2]=o.b,t.data[s+3]=o.a}function Jk(t,e,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<o;l++)un(t,e+l,n+a,r),un(t,e+l,n+s-1-a,r);for(let l=0;l<s;l++)un(t,e+a,n+l,r),un(t,e+o-1-a,n+l,r)}}function oc(t,e,n,o,s,r,i=3){let a=Math.abs(o-e),l=Math.abs(s-n),u=e<o?1:-1,c=n<s?1:-1,d=a-l,f=e,h=n;for(;;){let m=Math.floor(i/2);for(let $=-m;$<=m;$++)for(let x=-m;x<=m;x++)un(t,f+$,h+x,r);if(f===o&&h===s)break;let g=2*d;g>-l&&(d-=l,f+=u),g<a&&(d+=a,h+=c)}}function Zk(t,e,n,o,s,r,i=3){oc(t,e,n,o,s,r,i);let a=Math.atan2(s-n,o-e),l=15,u=a+Math.PI*.8,c=a-Math.PI*.8;oc(t,o,s,Math.round(o+l*Math.cos(u)),Math.round(s+l*Math.sin(u)),r,i),oc(t,o,s,Math.round(o+l*Math.cos(c)),Math.round(s+l*Math.sin(c)),r,i)}function Qk(t,e,n,o,s,r=3){for(let i=0;i<r;i++){let a=o-i;for(let l=0;l<360;l+=.5){let u=l*Math.PI/180,c=Math.round(e+a*Math.cos(u)),d=Math.round(n+a*Math.sin(u));un(t,c,d,s)}}}function rc(t,e,n,o,s){let i=o.length*6+4,a=12;for(let l=0;l<a;l++)for(let u=0;u<i;u++)un(t,e+u,n+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)un(t,e+l,n+a-1,s),un(t,e+l,n+a-2,s);for(let l=0;l<o.length;l++){let u=e+2+l*6;for(let c=2;c<9;c++)for(let d=0;d<4;d++)un(t,u+d,n+c,s)}}async function*eS(t,e,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=xn(),l=tS("chokidar"),u=await a(t,{width:s,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:u.path,base64:u.base64,media_type:u.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let c=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;c<n;){await sS(()=>d,3e5),d=!1,c++,await nS(o);let h=await a(t,{width:s,height:r,timeout:i}),m=null;try{m=ic(u.path,h.path)}catch{}u=h,yield{iteration:c,type:"change",path:h.path,base64:h.base64,media_type:h.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function tS(t){try{return require(t)}catch{return null}}function nS(t){return new Promise(e=>setTimeout(e,t))}function sS(t,e=6e4){return new Promise((n,o)=>{let s=setInterval(()=>{t()&&(clearInterval(s),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(s),o(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function oS(t,{sampleRate:e=4}={}){let o=Ri().sync.read(kn.readFileSync(t)),s=new Map;for(let u=0;u<o.height;u+=e)for(let c=0;c<o.width;c+=e){let d=(u*o.width+c)*4,f=o.data[d],h=o.data[d+1],m=o.data[d+2];if(o.data[d+3]<128)continue;let $=Math.round(f/8)*8,x=Math.round(h/8)*8,E=Math.round(m/8)*8,N=`${$},${x},${E}`;s.set(N,(s.get(N)||0)+1)}let r=[...s.entries()].sort((u,c)=>c[1]-u[1]).slice(0,20),i=r.reduce((u,c)=>u+c[1],0),a=r.map(([u,c])=>{let[d,f,h]=u.split(",").map(Number);return{hex:rS(d,f,h),rgb:`rgb(${d}, ${f}, ${h})`,frequency:parseFloat((c/i*100).toFixed(1)),category:iS(d,f,h)}}),l=aS(o);return{colors:a,spacing:l,dimensions:{width:o.width,height:o.height},imagePath:t}}function rS(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function iS(t,e,n){let o=(t*299+e*587+n*114)/1e3;return o>240?"white/background":o<30?"black/text":o<80?"dark":t>200&&e<100&&n<100?"red/danger":t<100&&e>150&&n<100?"green/success":t<100&&e<100&&n>200?"blue/primary":t>200&&e>200&&n<100?"yellow/warning":t>200&&e>100&&n<50?"orange/accent":o>200?"light/subtle":"midtone"}function aS(t){let e=[],n=!1,o=0,s=lS(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let u=(i*t.width+l)*4;if(Math.abs(t.data[u]-s.r)>20||Math.abs(t.data[u+1]-s.g)>20||Math.abs(t.data[u+2]-s.b)>20){a=!1;break}}if(a&&n)n=!1,o=i;else if(!a&&!n&&(n=!0,o>0)){let l=i-o;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 lS(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],n=0,o=0,s=0;for(let[r,i]of e){let a=(i*t.width+r)*4;n+=t.data[a],o+=t.data[a+1],s+=t.data[a+2]}return{r:Math.round(n/4),g:Math.round(o/4),b:Math.round(s/4)}}async function cS(t,e,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=xn(),u=Ri().sync.read(kn.readFileSync(e)),c=n||u.width,d=o||u.height,f=await a(t,{width:c,height:d,fullPage:s,timeout:i}),h=ic(e,f.path,{threshold:r}),m=Wp(f.path,h.regionSummary.filter(g=>g.changedPercent>1).map((g,$)=>{let N=Math.ceil(h.width/3),v=Math.ceil(h.height/3),S=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],P=0,ne=0;for(let re=0;re<3;re++)for(let ce=0;ce<3;ce++)S[re][ce]===g.name&&(P=ce,ne=re);return{type:"box",x:P*N+2,y:ne*v+2,width:N-4,height:v-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:h.diffPath,annotatedPath:m.path,diffPercent:h.diffPercent,changedPixels:h.changedPixels,totalPixels:h.totalPixels,regions:h.regionSummary,liveBase64:f.base64,diffBase64:kn.readFileSync(h.diffPath).toString("base64"),annotatedBase64:m.base64}}Hp.exports={pixelDiff:ic,responsiveSweep:Xk,annotateImage:Wp,visualWatch:eS,extractDesignTokens:oS,designCompare:cS,DEFAULT_VIEWPORTS:Up}});var ac=Z((_A,Yp)=>{var{C:De}=it(),Fo="",gt=[],qo=0,es=null;function uS(t){es=t}function dS(t,e){Fo=t,gt=[],qo=0;for(let o of e){qo++;let s=`t${qo}`;gt.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${qo}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=gt.map(o=>({...o}));return es&&es("create",{name:t,tasks:n}),n}function fS(t,e,n){let o=gt.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),es&&es("update",{id:t,status:e,result:n}),{...o}):null}function hS(){return{name:Fo,tasks:gt.map(t=>({...t}))}}function pS(){Fo="",gt=[],qo=0,es&&es("clear",{})}function mS(){return gt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=gt.find(o=>o.id===e);return n&&n.status==="done"}))}function gS(){if(gt.length===0)return`${De.dim}No active tasks${De.reset}`;let t=[];Fo&&(t.push(` ${De.bold}${De.cyan}Tasks: ${Fo}${De.reset}`),t.push(` ${De.dim}${"\u2500".repeat(40)}${De.reset}`));for(let s of gt){let r,i;switch(s.status){case"done":r="\u2713",i=De.green;break;case"in_progress":r="\u2192",i=De.cyan;break;case"failed":r="\u2717",i=De.red;break;default:r="\xB7",i=De.dim}let a=s.dependsOn.length>0?` ${De.dim}(after: ${s.dependsOn.join(", ")})${De.reset}`:"",l=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${De.reset} ${De.bold}${s.id}${De.reset} ${u.padEnd(40)} ${i}${l}${De.reset}${a}`),s.result&&s.status==="done"){let c=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${De.dim}\u2192 ${c}${De.reset}`)}}let e=gt.filter(s=>s.status==="done").length,n=gt.filter(s=>s.status==="failed").length,o=gt.length;return t.push(` ${De.dim}${"\u2500".repeat(40)}${De.reset}`),t.push(` ${De.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${De.reset}`),t.join(`
152
+ `)}function yS(){return gt.length>0&&gt.some(t=>t.status==="pending"||t.status==="in_progress")}Yp.exports={createTasks:dS,updateTask:fS,getTaskList:hS,clearTasks:pS,getReadyTasks:mS,renderTaskList:gS,setOnChange:uS,hasActiveTasks:yS}});var cc=Z((xA,Jp)=>{var{callChat:wS}=dt(),{estimateTokens:lc}=dn(),Gp=process.env.NEX_COMPACTION!=="false",zp=6,Kp=2e3,Xp=3,$S=`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.
145
153
  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.
146
154
 
147
155
  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:
@@ -173,38 +181,38 @@ Format your output as:
173
181
 
174
182
  <summary>
175
183
  [Sections 1-9 above]
176
- </summary>`,es=0;async function Ix(t){if(!xp||t.length<Sp||es>=Ep)return null;let e=[{role:"system",content:Lx},{role:"user",content:Tp(t)}];try{let o=((await Px(e,[],{temperature:0,maxTokens:vp})).content||"").trim();if(!o)return es++,null;let n=o.match(/<summary>([\s\S]*?)<\/summary>/);if(n?o=n[1].trim():o=o.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!o)return es++,null;let r=t.reduce((a,l)=>a+tc(l.content||"")+(l.tool_calls?tc(JSON.stringify(l.tool_calls)):0),0),i=tc(o);return i>=r*.8?(es++,null):(es=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
177
- ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return es++,null}}function jx(){es=0}function Tp(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let n=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${o}
178
- tools: ${n}`}return`[${s}] ${o}`}).join(`
184
+ </summary>`,ts=0;async function bS(t){if(!Gp||t.length<zp||ts>=Xp)return null;let e=[{role:"system",content:$S},{role:"user",content:Vp(t)}];try{let o=((await wS(e,[],{temperature:0,maxTokens:Kp})).content||"").trim();if(!o)return ts++,null;let s=o.match(/<summary>([\s\S]*?)<\/summary>/);if(s?o=s[1].trim():o=o.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!o)return ts++,null;let r=t.reduce((a,l)=>a+lc(l.content||"")+(l.tool_calls?lc(JSON.stringify(l.tool_calls)):0),0),i=lc(o);return i>=r*.8?(ts++,null):(ts=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
185
+ ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return ts++,null}}function _S(){ts=0}function Vp(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let s=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${o}
186
+ tools: ${s}`}return`[${n}] ${o}`}).join(`
179
187
 
180
- `)}Rp.exports={compactMessages:Ix,formatMessagesForSummary:Tp,resetCompactionFailures:jx,COMPACTION_ENABLED:xp,COMPACTION_MIN_MESSAGES:Sp,COMPACTION_SUMMARY_BUDGET:vp,MAX_CONSECUTIVE_FAILURES:Ep}});var ln=V((LC,Dp)=>{var Dx=require("path");function Ap(){return ut().getActiveModel()}var qx={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Fx={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},ts=new Map,Cp=1e3,sc=new WeakMap,ns=null;function Bx(){if(ns!==null)return ns;try{let t=Ap(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[o,n]of Object.entries(Fx))if(s.startsWith(o))return ns=n,ns;return ns=qx[e]||4,ns}catch{return 4}}function Ux(){ns=null}function ss(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=ts.get(e);if(s!==void 0)return ts.delete(e),ts.set(e,s),s;let o=Math.ceil(t.length/Bx());if(ts.size>=Cp){let n=Cp>>1,r=ts.keys();for(let i=0;i<n;i++)ts.delete(r.next().value)}return ts.set(e,o),o}function Wx(t){if(sc.has(t))return sc.get(t);let e=JSON.stringify(t);return sc.set(t,e),e}function os(t){let s=4;if(t.content&&(s+=ss(t.content)),t.tool_calls)for(let o of t.tool_calls){s+=4,s+=ss(o.function?.name||"");let n=o.function?.arguments;typeof n=="string"?s+=ss(n):n&&(s+=ss(JSON.stringify(n)))}return s}function zt(t){let e=0;for(let s of t)e+=os(s);return e}function Hx(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,o=e.length,n=0;for(let r=s;r<o;r++)n+=os(e[r]);return n}var oc=new WeakMap;function Ei(t){if(!t||t.length===0)return 0;if(oc.has(t))return oc.get(t);let e=ss(JSON.stringify(t));return oc.set(t,e),e}function Ti(){return Ap()?.contextWindow||32768}var gt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function Gx(t,e){let s=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(gt.result&&t.length===gt.msgCount&&s===gt.lastMsgRef&&o===gt.toolCount)return gt.result;let n,r,i,a;if(gt.messagesRef===t&&t.length>gt.msgCount&&gt.msgCount>=0){n=gt.messageTokens,r=gt.systemTokens,i=gt.conversationTokens,a=gt.toolResultTokens;for(let h=gt.msgCount;h<t.length;h++){let m=os(t[h]);n+=m,t[h].role==="system"?r+=m:t[h].role==="tool"?a+=m:i+=m}}else{n=0,r=0,i=0,a=0;for(let h of t){let m=os(h);n+=m,h.role==="system"?r+=m:h.role==="tool"?a+=m:i+=m}}let l=Ei(e),u=n+l,c=Ti(),d=c>0?u/c*100:0,f={used:u,limit:c,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return gt={msgCount:t.length,lastMsgRef:s,toolCount:o,result:f,messagesRef:t,messageTokens:n,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var qo=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Op=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Np=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Mp={essential:.6,standard:.65,full:Math.min(qo,.75)};function Pp(){if(process.env.NEX_COMPRESSION_THRESHOLD)return qo;try{let{getActiveTier:t}=Po(),e=t();return Mp[e]??qo}catch{return qo}}var Yx=200,zx=1e3;function Lp(t,e){if(!t||t.length<=e)return t;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=o)return t;let n=t.split(`
181
- `);if(n.length<=10){let m=Math.floor(o*.6),g=Math.floor(o*.4),$=t.substring(0,m),k=t.substring(t.length-g);return $+`
188
+ `)}Jp.exports={compactMessages:bS,formatMessagesForSummary:Vp,resetCompactionFailures:_S,COMPACTION_ENABLED:Gp,COMPACTION_MIN_MESSAGES:zp,COMPACTION_SUMMARY_BUDGET:Kp,MAX_CONSECUTIVE_FAILURES:Xp}});var dn=Z((kA,am)=>{var xS=require("path");function Qp(){return dt().getActiveModel()}var kS={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},SS={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},ns=new Map,Zp=1e3,uc=new WeakMap,ss=null;function vS(){if(ss!==null)return ss;try{let t=Qp(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(SS))if(n.startsWith(o))return ss=s,ss;return ss=kS[e]||4,ss}catch{return 4}}function ES(){ss=null}function os(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)}`,n=ns.get(e);if(n!==void 0)return ns.delete(e),ns.set(e,n),n;let o=Math.ceil(t.length/vS());if(ns.size>=Zp){let s=Zp>>1,r=ns.keys();for(let i=0;i<s;i++)ns.delete(r.next().value)}return ns.set(e,o),o}function TS(t){if(uc.has(t))return uc.get(t);let e=JSON.stringify(t);return uc.set(t,e),e}function rs(t){let n=4;if(t.content&&(n+=os(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=os(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=os(s):s&&(n+=os(JSON.stringify(s)))}return n}function Xt(t){let e=0;for(let n of t)e+=rs(n);return e}function RS(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 n=t?t.length:0,o=e.length,s=0;for(let r=n;r<o;r++)s+=rs(e[r]);return s}var dc=new WeakMap;function Ci(t){if(!t||t.length===0)return 0;if(dc.has(t))return dc.get(t);let e=os(JSON.stringify(t));return dc.set(t,e),e}function Ai(){return Qp()?.contextWindow||32768}var yt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function CS(t,e){let n=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(yt.result&&t.length===yt.msgCount&&n===yt.lastMsgRef&&o===yt.toolCount)return yt.result;let s,r,i,a;if(yt.messagesRef===t&&t.length>yt.msgCount&&yt.msgCount>=0){s=yt.messageTokens,r=yt.systemTokens,i=yt.conversationTokens,a=yt.toolResultTokens;for(let h=yt.msgCount;h<t.length;h++){let m=rs(t[h]);s+=m,t[h].role==="system"?r+=m:t[h].role==="tool"?a+=m:i+=m}}else{s=0,r=0,i=0,a=0;for(let h of t){let m=rs(h);s+=m,h.role==="system"?r+=m:h.role==="tool"?a+=m:i+=m}}let l=Ci(e),u=s+l,c=Ai(),d=c>0?u/c*100:0,f={used:u,limit:c,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return yt={msgCount:t.length,lastMsgRef:n,toolCount:o,result:f,messagesRef:t,messageTokens:s,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Bo=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,em=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,tm=parseInt(process.env.NEX_KEEP_RECENT,10)||10,nm={essential:.6,standard:.65,full:Math.min(Bo,.75)};function sm(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Bo;try{let{getActiveTier:t}=Io(),e=t();return nm[e]??Bo}catch{return Bo}}var AS=200,OS=1e3;function om(t,e){if(!t||t.length<=e)return t;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=o)return t;let s=t.split(`
189
+ `);if(s.length<=10){let m=Math.floor(o*.6),g=Math.floor(o*.4),$=t.substring(0,m),x=t.substring(t.length-g);return $+`
182
190
  ...(${t.length} chars total)...
183
- `+k}let r=Math.floor(n.length*.4),i=Math.floor(n.length*.4),a=[],l=0,u=Math.floor(o*.4);for(let m=0;m<r&&l<u;m++)if(l+n[m].length+1>u&&n[m].trim().startsWith("```")){a.push(n[m]),l+=n[m].length+1;let g=m+1;for(;g<n.length&&l<u*1.5&&!n[g].trim().startsWith("```");)a.push(n[g]),l+=n[g].length+1,g++;g<n.length&&n[g].trim().startsWith("```")&&(a.push(n[g]),l+=n[g].length+1),m=g}else a.push(n[m]),l+=n[m].length+1;let c=[],d=0,f=Math.floor(o*.4);for(let m=n.length-1;m>=n.length-i&&d<f;m--)if(d+n[m].length+1>f&&n[m].trim().startsWith("```")){c.push(n[m]),d+=n[m].length+1;let g=m-1;for(;g>=0&&d<f*1.5&&!n[g].trim().startsWith("```");)c.push(n[g]),d+=n[g].length+1,g--;g>=0&&n[g].trim().startsWith("```")&&(c.push(n[g]),d+=n[g].length+1),m=g}else c.push(n[m]),d+=n[m].length+1;c.reverse();let h=n.length-a.length-c.length;return a.join(`
191
+ `+x}let r=Math.floor(s.length*.4),i=Math.floor(s.length*.4),a=[],l=0,u=Math.floor(o*.4);for(let m=0;m<r&&l<u;m++)if(l+s[m].length+1>u&&s[m].trim().startsWith("```")){a.push(s[m]),l+=s[m].length+1;let g=m+1;for(;g<s.length&&l<u*1.5&&!s[g].trim().startsWith("```");)a.push(s[g]),l+=s[g].length+1,g++;g<s.length&&s[g].trim().startsWith("```")&&(a.push(s[g]),l+=s[g].length+1),m=g}else a.push(s[m]),l+=s[m].length+1;let c=[],d=0,f=Math.floor(o*.4);for(let m=s.length-1;m>=s.length-i&&d<f;m--)if(d+s[m].length+1>f&&s[m].trim().startsWith("```")){c.push(s[m]),d+=s[m].length+1;let g=m-1;for(;g>=0&&d<f*1.5&&!s[g].trim().startsWith("```");)c.push(s[g]),d+=s[g].length+1,g--;g>=0&&s[g].trim().startsWith("```")&&(c.push(s[g]),d+=s[g].length+1),m=g}else c.push(s[m]),d+=s[m].length+1;c.reverse();let h=s.length-a.length-c.length;return a.join(`
184
192
  `)+`
185
- ...(${h} lines omitted, ${n.length} total)...
193
+ ...(${h} lines omitted, ${s.length} total)...
186
194
  `+c.join(`
187
- `)}function Ws(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:zx,o=e==="aggressive"?50:e==="medium"?100:Yx;if(t.role==="tool"){let n=typeof t.content=="string"?t.content:JSON.stringify(t.content);return n.length>o?{...t,content:Lp(n,o)}:t}if(t.role==="assistant"){let n={...t};return n.content&&n.content.length>s&&(n.content=n.content.substring(0,s)+`
188
- ...(truncated)`),n.tool_calls&&e==="aggressive"&&(n.tool_calls=n.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}}))),n}return t}function Ip(t,e,s,o){let n=0;if(t.role==="system")return 100;if(t.role==="user")n+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?n+=30:n+=15}else t.role==="assistant"&&(n+=t.tool_calls?20:10);let r=s>1?e/(s-1):1;if(n+=Math.round(r*30),o&&o.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let l of o)(i.includes(l)||i.includes(Dx.basename(l)))&&a++;n+=Math.min(30,a*10)}return Math.min(100,n)}function jp(t,e=10){let s=new Set,o=t.slice(-e),n=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(n);a&&a.forEach(l=>s.add(l))}return s}function Kx(t,{filesModified:e=new Set,currentPhase:s=null}={}){let o=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");o.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}s&&o.push(`Current phase: ${s}`);let n=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 n.length>0&&o.push(`Recent progress:
189
- `+n.map(r=>`- ${r}`).join(`
195
+ `)}function Ks(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:OS,o=e==="aggressive"?50:e==="medium"?100:AS;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:om(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
196
+ ...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.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}}))),s}return t}function rm(t,e,n,o){let s=0;if(t.role==="system")return 100;if(t.role==="user")s+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?s+=30:s+=15}else t.role==="assistant"&&(s+=t.tool_calls?20:10);let r=n>1?e/(n-1):1;if(s+=Math.round(r*30),o&&o.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let l of o)(i.includes(l)||i.includes(xS.basename(l)))&&a++;s+=Math.min(30,a*10)}return Math.min(100,s)}function im(t,e=10){let n=new Set,o=t.slice(-e),s=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(s);a&&a.forEach(l=>n.add(l))}return n}function NS(t,{filesModified:e=new Set,currentPhase:n=null}={}){let o=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");o.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}n&&o.push(`Current phase: ${n}`);let s=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 s.length>0&&o.push(`Recent progress:
197
+ `+s.map(r=>`- ${r}`).join(`
190
198
  `)),o.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
191
199
  ${o.join(`
192
- `)}`,_pinned:!0,_progressSnapshot:!0}}var Us={msgCount:-1,lastMsgRef:null,result:null};function Xx(){Us={msgCount:-1,lastMsgRef:null,result:null},gt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function Vx(t,e,s={}){let o=t.length>0?t[t.length-1]:null;if(!s.force&&Us.result&&t.length===Us.msgCount&&o===Us.lastMsgRef)return Us.result;let n=s.threshold??Pp(),r=s.safetyMargin??Op,i=s.keepRecent??Np,a=Ti(),l=Ei(e),u=Math.floor(a*(n-r)),c=u-l,d=zt(t);if(d+l<=u){let oe={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Us={msgCount:t.length,lastMsgRef:o,result:oe},oe}let h=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,$),v=t.slice($),A=k.map(oe=>Ws(oe,"light")),E=Mn(m,A,v),S=zt(E);if(S+l<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S};if(A=k.map(oe=>Ws(oe,"medium")),E=Mn(m,A,v),S=zt(E),S+l<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S};if(A=k.map(oe=>Ws(oe,"aggressive")),E=Mn(m,A,v),S=zt(E),S+l<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S};let N=process.env.NEX_SKIP_COMPACTOR==="1",ee=k.filter(oe=>oe._pinned),re=k.filter(oe=>!oe._compacted&&!oe._pinned);if(!N&&re.length>=6)try{let{compactMessages:oe}=nc(),ae=await oe(re);if(ae){let T=k.filter(ke=>ke._compacted&&!ke._pinned),U=[...ee,...T,ae.message],Z=Mn(m,U,v),ye=zt(Z);if(ye+l<=u)return{messages:Z,compressed:!0,compacted:!0,tokensRemoved:h-ye};k=U}}catch(oe){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",oe.message)}let le=jp([...A,...v]),ue=A.map((oe,ae)=>({msg:oe,score:oe._pinned?1/0:Ip(oe,ae,A.length,le),tokens:os(oe)}));for(;ue.length>0&&S>c;){let oe=-1;for(let ae=0;ae<ue.length;ae++)ue[ae].score!==1/0&&(oe===-1||ue[ae].score<ue[oe].score)&&(oe=ae);if(oe===-1)break;S-=ue[oe].tokens,ue.splice(oe,1)}return A=ue.map(oe=>oe.msg),E=Mn(m,A,v),S=zt(E),{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S}}function Mn(t,e,s){let o=[];return t&&o.push(t),o.push(...e,...s),o}function Jx(t,e){if(!t)return"";if(ss(t)<=e)return t;let o=e*4,n=t.split(`
193
- `),r=Math.floor(o*.6),i=Math.floor(o*.4),a="",l=0;for(let h of n){if(a.length+h.length+1>r)break;a+=(a?`
194
- `:"")+h,l++}let u="",c=0;for(let h=n.length-1;h>=l;h--){let m=n[h]+(u?`
200
+ `)}`,_pinned:!0,_progressSnapshot:!0}}var zs={msgCount:-1,lastMsgRef:null,result:null};function PS(){zs={msgCount:-1,lastMsgRef:null,result:null},yt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function MS(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&zs.result&&t.length===zs.msgCount&&o===zs.lastMsgRef)return zs.result;let s=n.threshold??sm(),r=n.safetyMargin??em,i=n.keepRecent??tm,a=Ai(),l=Ci(e),u=Math.floor(a*(s-r)),c=u-l,d=Xt(t);if(d+l<=u){let oe={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return zs={msgCount:t.length,lastMsgRef:o,result:oe},oe}let h=d,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let $=Math.max(g,t.length-i),x=t.slice(g,$),E=t.slice($),N=x.map(oe=>Ks(oe,"light")),v=Ln(m,N,E),S=Xt(v);if(S+l<=u)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:h-S};if(N=x.map(oe=>Ks(oe,"medium")),v=Ln(m,N,E),S=Xt(v),S+l<=u)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:h-S};if(N=x.map(oe=>Ks(oe,"aggressive")),v=Ln(m,N,E),S=Xt(v),S+l<=u)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:h-S};let P=process.env.NEX_SKIP_COMPACTOR==="1",ne=x.filter(oe=>oe._pinned),re=x.filter(oe=>!oe._compacted&&!oe._pinned);if(!P&&re.length>=6)try{let{compactMessages:oe}=cc(),le=await oe(re);if(le){let T=x.filter(ke=>ke._compacted&&!ke._pinned),q=[...ne,...T,le.message],Q=Ln(m,q,E),we=Xt(Q);if(we+l<=u)return{messages:Q,compressed:!0,compacted:!0,tokensRemoved:h-we};x=q}}catch(oe){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",oe.message)}let ce=im([...N,...E]),de=N.map((oe,le)=>({msg:oe,score:oe._pinned?1/0:rm(oe,le,N.length,ce),tokens:rs(oe)}));for(;de.length>0&&S>c;){let oe=-1;for(let le=0;le<de.length;le++)de[le].score!==1/0&&(oe===-1||de[le].score<de[oe].score)&&(oe=le);if(oe===-1)break;S-=de[oe].tokens,de.splice(oe,1)}return N=de.map(oe=>oe.msg),v=Ln(m,N,E),S=Xt(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:h-S}}function Ln(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function LS(t,e){if(!t)return"";if(os(t)<=e)return t;let o=e*4,s=t.split(`
201
+ `),r=Math.floor(o*.6),i=Math.floor(o*.4),a="",l=0;for(let h of s){if(a.length+h.length+1>r)break;a+=(a?`
202
+ `:"")+h,l++}let u="",c=0;for(let h=s.length-1;h>=l;h--){let m=s[h]+(u?`
195
203
  `:"")+u;if(m.length>i)break;u=m,c++}let f=`
196
204
 
197
- ... (${n.length-l-c} lines omitted, ${n.length} total) ...
205
+ ... (${s.length-l-c} lines omitted, ${s.length} total) ...
198
206
 
199
- `;return a+f+u}var Zx=6;function Qx(t,e,s=!1){let o=Ti(),n=Ei(e),r=Math.floor(o*(s?.35:.5))-n,i=zt(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let l=null,u=0;t.length>0&&t[0].role==="system"&&(l=t[0],u=1);let c=s?2:Zx,d=Math.max(u,t.length-c),f=t.slice(u,d),h=t.slice(d),m=f.map(S=>Ws(S,"aggressive"));s&&(h=h.map(S=>Ws(S,"aggressive")));let g=Mn(l,m,h),$=zt(g);for(;m.length>0&&$>r;){let S=m.shift();$-=os(S)}s&&$>r&&(h=h.filter(N=>N.role==="user").slice(-1),g=Mn(l,[],h),$=zt(g)),g=Mn(l,m,h);let k=t.filter(S=>S.role==="user"),v=S=>{let N=typeof S.content=="string"?S.content:"";return N.startsWith("[SYSTEM WARNING]")||N.startsWith("[SYSTEM:")||N.startsWith("BLOCKED:")},A=k.find(S=>!v(S)),E=[...k].reverse().find(S=>!v(S));if(A&&!g.find(S=>S===A)){let S=g.findIndex(ee=>ee.role==="system"),N=S>=0?S+1:0;g.splice(N,0,A)}return E&&E!==A&&!g.find(S=>S===E)&&g.push(E),{messages:g,tokensRemoved:i-zt(g)}}Dp.exports={estimateTokens:ss,estimateMessageTokens:os,estimateMessagesTokens:zt,estimateDeltaTokens:Hx,estimateToolsTokens:Ei,serializeMessage:Wx,getContextWindow:Ti,getUsage:Gx,compressMessage:Ws,compressToolResult:Lp,scoreMessageRelevance:Ip,extractActiveFiles:jp,buildProgressSnapshot:Kx,fitToContext:Vx,forceCompress:Qx,truncateFileContent:Jx,invalidateTokenRatioCache:Ux,invalidateFitToContextCache:Xx,getEffectiveCompressionThreshold:Pp,COMPRESSION_THRESHOLD:qo,TIER_COMPRESSION_THRESHOLDS:Mp,SAFETY_MARGIN:Op,KEEP_RECENT:Np}});var fc=V((IC,Zp)=>{var Ye=require("fs"),bn=require("path"),{atomicWrite:qp,withFileLockSync:Fp}=Gn(),eS=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 Gs(){let t=bn.join(process.cwd(),".nex","brain");return Ye.existsSync(t)||Ye.mkdirSync(t,{recursive:!0}),t}function Ci(){return bn.join(Gs(),".brain-index.json")}function ac(){return bn.join(Gs(),".embeddings.json")}function Fo(){let t=bn.join(process.cwd(),".nex","brain");if(!Ye.existsSync(t))return[];try{return Ye.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=bn.join(t,e),o=Ye.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:o.size,modified:new Date(o.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function Bo(t){let e={},s=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let n=o[1].split(`
200
- `);for(let r of n){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(u=>u.trim()).filter(Boolean):e[a]=l}s=o[2]}return{frontmatter:e,body:s}}function Bp(t){let e=bn.join(Gs(),`${t}.md`);if(!Ye.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Ye.readFileSync(e,"utf-8"),{frontmatter:o,body:n}=Bo(s);return{name:t,content:s,body:n,frontmatter:o}}function tS(t,e){let s=bn.join(Gs(),`${t}.md`);qp(s,e),oS(t,e),nS()}function nS(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=ac();Ye.existsSync(t)&&setImmediate(async()=>{try{await Kp()}catch{}})}function sS(t){let e=bn.join(Gs(),`${t}.md`);return Ye.existsSync(e)?(Ye.unlinkSync(e),rS(t),!0):!1}function Ri(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!eS.has(e))}function lc(t){let e={},{frontmatter:s,body:o}=Bo(t),n=Array.isArray(s.tags)?s.tags:[];for(let i of n){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(o||t).split(`
201
- `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of Ri(a))e[l]=(e[l]||0)+3}for(let i of Ri(o||t))e[i]=(e[i]||0)+1;return e}function cc(){let t=Ci();if(!Ye.existsSync(t))return{documents:{}};try{return JSON.parse(Ye.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function uc(t){qp(Ci(),JSON.stringify(t,null,2))}function oS(t,e){Fp(Ci(),()=>{let s=cc(),{frontmatter:o}=Bo(e),n=Array.isArray(o.tags)?o.tags:[];s.documents[t]={keywords:lc(e),tags:n,modified:new Date().toISOString()},uc(s)})}function rS(t){Fp(Ci(),()=>{let e=cc();delete e.documents[t],uc(e)})}function ic(){let t=Fo(),e={documents:{}};for(let s of t){let o=Ye.readFileSync(s.path,"utf-8"),{frontmatter:n}=Bo(o),r=Array.isArray(n.tags)?n.tags:[];e.documents[s.name]={keywords:lc(o),tags:r,modified:s.modified.toISOString()}}return uc(e),e}function Up(){let t=cc(),e=Fo();for(let s of e){let o=t.documents[s.name];if(!o||new Date(o.modified)<s.modified)return ic()}for(let s of Object.keys(t.documents))if(!e.some(o=>o.name===s))return ic();return t}function Wp(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=Ri(t);if(n.length===0)return[];let r=Up(),i=[];for(let[a,l]of Object.entries(r.documents)){let u=0;for(let c of n){l.keywords[c]&&(u+=l.keywords[c]);for(let[d,f]of Object.entries(l.keywords))d!==c&&d.length>3&&c.length>3&&(d.includes(c)||c.includes(d))&&(u+=f*.3)}u>=o&&i.push({name:a,score:u})}return i.sort((a,l)=>l.score-a.score),i.slice(0,s)}var Hp=process.env.NEX_EMBED_MODEL||"nomic-embed-text",rc=400,iS=50;async function Gp(){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"),o=new URL(`${t}/api/tags`),n=o.protocol==="https:"?s:e;return((await new Promise((a,l)=>{let u=n.get(o.toString(),{timeout:2e3},c=>{let d="";c.on("data",f=>d+=f),c.on("end",()=>{try{a(JSON.parse(d))}catch{l(new Error("bad json"))}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(Hp.split(":")[0]))}catch{return!1}}async function dc(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),o=require("https"),n=new URL(`${e}/api/embeddings`),r=n.protocol==="https:"?o:s,i=JSON.stringify({model:Hp,prompt:t});return new Promise((a,l)=>{let u=r.request(n,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},c=>{let d="";c.on("data",f=>d+=f),c.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){l(f)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(i),u.end()})}function Yp(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,o=0,n=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],o+=t[i]*t[i],n+=e[i]*e[i];let r=Math.sqrt(o)*Math.sqrt(n);return r===0?0:s/r}function zp(t){let e=t.split(/\s+/),s=[],o=0;for(;o<e.length;){let n=e.slice(o,o+rc).join(" ");if(s.push({text:n,offset:o}),o+rc>=e.length)break;o+=rc-iS}return s}async function Kp(){let t=Fo(),e={documents:{}},s=ac();if(Ye.existsSync(s))try{e=JSON.parse(Ye.readFileSync(s,"utf-8"))}catch{}for(let o of t){let n=e.documents[o.name];if(n&&new Date(n.modified)>=o.modified)continue;let r=Ye.readFileSync(o.path,"utf-8"),i=zp(r),a=[];for(let l of i){let u=await dc(l.text);a.push({text:l.text,embedding:u,offset:l.offset})}e.documents[o.name]={chunks:a,modified:o.modified.toISOString()}}for(let o of Object.keys(e.documents))t.some(n=>n.name===o)||delete e.documents[o];return Ye.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Xp(t,e={}){let{topK:s=3,minSimilarity:o=.3}=e,n=ac();if(!Ye.existsSync(n))return[];let r;try{r=JSON.parse(Ye.readFileSync(n,"utf-8"))}catch{return[]}let i=await dc(t),a=[];for(let[l,u]of Object.entries(r.documents||{})){let c=0,d="";for(let f of u.chunks||[]){let h=Yp(i,f.embedding);h>c&&(c=h,d=f.text)}c>=o&&a.push({name:l,score:c,bestChunk:d})}return a.sort((l,u)=>u.score-l.score),a.slice(0,s)}function Vp(t,e,s={}){let{k:o=60,topK:n=3}=s,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,n)}async function Jp(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=Wp(t,{topK:s,minScore:o}),r=n;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Gp()){let a=await Xp(t,{topK:s});r=Vp(n,a,{topK:s})}}catch{}return r.map(i=>{let a=Bp(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 Hs={queryKey:null,result:null,ts:0},aS=3e5;async function lS(t){if(!t||!t.trim())return"";let e=bn.join(process.cwd(),".nex","brain");if(!Ye.existsSync(e)||Fo().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(Hs.result!==null&&Hs.queryKey===o&&Date.now()-Hs.ts<aS)return Hs.result;let n;try{n=await Jp(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let r;try{r=ln().estimateTokens}catch{r=c=>Math.ceil(c.length/4)}let i=25e3,a=[],l=0;for(let c of n){let d=c.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))+`
207
+ `;return a+f+u}var IS=6;function jS(t,e,n=!1){let o=Ai(),s=Ci(e),r=Math.floor(o*(n?.35:.5))-s,i=Xt(t),a=Math.floor(i*(n?.5:.8));r>a&&(r=a);let l=null,u=0;t.length>0&&t[0].role==="system"&&(l=t[0],u=1);let c=n?2:IS,d=Math.max(u,t.length-c),f=t.slice(u,d),h=t.slice(d),m=f.map(S=>Ks(S,"aggressive"));n&&(h=h.map(S=>Ks(S,"aggressive")));let g=Ln(l,m,h),$=Xt(g);for(;m.length>0&&$>r;){let S=m.shift();$-=rs(S)}n&&$>r&&(h=h.filter(P=>P.role==="user").slice(-1),g=Ln(l,[],h),$=Xt(g)),g=Ln(l,m,h);let x=t.filter(S=>S.role==="user"),E=S=>{let P=typeof S.content=="string"?S.content:"";return P.startsWith("[SYSTEM WARNING]")||P.startsWith("[SYSTEM:")||P.startsWith("BLOCKED:")},N=x.find(S=>!E(S)),v=[...x].reverse().find(S=>!E(S));if(N&&!g.find(S=>S===N)){let S=g.findIndex(ne=>ne.role==="system"),P=S>=0?S+1:0;g.splice(P,0,N)}return v&&v!==N&&!g.find(S=>S===v)&&g.push(v),{messages:g,tokensRemoved:i-Xt(g)}}am.exports={estimateTokens:os,estimateMessageTokens:rs,estimateMessagesTokens:Xt,estimateDeltaTokens:RS,estimateToolsTokens:Ci,serializeMessage:TS,getContextWindow:Ai,getUsage:CS,compressMessage:Ks,compressToolResult:om,scoreMessageRelevance:rm,extractActiveFiles:im,buildProgressSnapshot:NS,fitToContext:MS,forceCompress:jS,truncateFileContent:LS,invalidateTokenRatioCache:ES,invalidateFitToContextCache:PS,getEffectiveCompressionThreshold:sm,COMPRESSION_THRESHOLD:Bo,TIER_COMPRESSION_THRESHOLDS:nm,SAFETY_MARGIN:em,KEEP_RECENT:tm}});var $c=Z((SA,_m)=>{var Ve=require("fs"),Sn=require("path"),{atomicWrite:lm,withFileLockSync:cm}=Gn(),DS=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 Vs(){let t=Sn.join(process.cwd(),".nex","brain");return Ve.existsSync(t)||Ve.mkdirSync(t,{recursive:!0}),t}function Ni(){return Sn.join(Vs(),".brain-index.json")}function pc(){return Sn.join(Vs(),".embeddings.json")}function Uo(){let t=Sn.join(process.cwd(),".nex","brain");if(!Ve.existsSync(t))return[];try{return Ve.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=Sn.join(t,e),o=Ve.statSync(n);return{name:e.replace(/\.md$/,""),path:n,size:o.size,modified:new Date(o.mtimeMs)}}).sort((e,n)=>n.modified-e.modified)}catch{return[]}}function Wo(t){let e={},n=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let s=o[1].split(`
208
+ `);for(let r of s){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(u=>u.trim()).filter(Boolean):e[a]=l}n=o[2]}return{frontmatter:e,body:n}}function um(t){let e=Sn.join(Vs(),`${t}.md`);if(!Ve.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=Ve.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=Wo(n);return{name:t,content:n,body:s,frontmatter:o}}function qS(t,e){let n=Sn.join(Vs(),`${t}.md`);lm(n,e),US(t,e),FS()}function FS(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=pc();Ve.existsSync(t)&&setImmediate(async()=>{try{await ym()}catch{}})}function BS(t){let e=Sn.join(Vs(),`${t}.md`);return Ve.existsSync(e)?(Ve.unlinkSync(e),WS(t),!0):!1}function Oi(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!DS.has(e))}function mc(t){let e={},{frontmatter:n,body:o}=Wo(t),s=Array.isArray(n.tags)?n.tags:[];for(let i of s){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(o||t).split(`
209
+ `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of Oi(a))e[l]=(e[l]||0)+3}for(let i of Oi(o||t))e[i]=(e[i]||0)+1;return e}function gc(){let t=Ni();if(!Ve.existsSync(t))return{documents:{}};try{return JSON.parse(Ve.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function yc(t){lm(Ni(),JSON.stringify(t,null,2))}function US(t,e){cm(Ni(),()=>{let n=gc(),{frontmatter:o}=Wo(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:mc(e),tags:s,modified:new Date().toISOString()},yc(n)})}function WS(t){cm(Ni(),()=>{let e=gc();delete e.documents[t],yc(e)})}function hc(){let t=Uo(),e={documents:{}};for(let n of t){let o=Ve.readFileSync(n.path,"utf-8"),{frontmatter:s}=Wo(o),r=Array.isArray(s.tags)?s.tags:[];e.documents[n.name]={keywords:mc(o),tags:r,modified:n.modified.toISOString()}}return yc(e),e}function dm(){let t=gc(),e=Uo();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return hc()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return hc();return t}function fm(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=Oi(t);if(s.length===0)return[];let r=dm(),i=[];for(let[a,l]of Object.entries(r.documents)){let u=0;for(let c of s){l.keywords[c]&&(u+=l.keywords[c]);for(let[d,f]of Object.entries(l.keywords))d!==c&&d.length>3&&c.length>3&&(d.includes(c)||c.includes(d))&&(u+=f*.3)}u>=o&&i.push({name:a,score:u})}return i.sort((a,l)=>l.score-a.score),i.slice(0,n)}var hm=process.env.NEX_EMBED_MODEL||"nomic-embed-text",fc=400,HS=50;async function pm(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),n=require("https"),o=new URL(`${t}/api/tags`),s=o.protocol==="https:"?n:e;return((await new Promise((a,l)=>{let u=s.get(o.toString(),{timeout:2e3},c=>{let d="";c.on("data",f=>d+=f),c.on("end",()=>{try{a(JSON.parse(d))}catch{l(new Error("bad json"))}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(hm.split(":")[0]))}catch{return!1}}async function wc(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",n=require("http"),o=require("https"),s=new URL(`${e}/api/embeddings`),r=s.protocol==="https:"?o:n,i=JSON.stringify({model:hm,prompt:t});return new Promise((a,l)=>{let u=r.request(s,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},c=>{let d="";c.on("data",f=>d+=f),c.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){l(f)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(i),u.end()})}function mm(t,e){if(!t||!e||t.length!==e.length)return 0;let n=0,o=0,s=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],o+=t[i]*t[i],s+=e[i]*e[i];let r=Math.sqrt(o)*Math.sqrt(s);return r===0?0:n/r}function gm(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+fc).join(" ");if(n.push({text:s,offset:o}),o+fc>=e.length)break;o+=fc-HS}return n}async function ym(){let t=Uo(),e={documents:{}},n=pc();if(Ve.existsSync(n))try{e=JSON.parse(Ve.readFileSync(n,"utf-8"))}catch{}for(let o of t){let s=e.documents[o.name];if(s&&new Date(s.modified)>=o.modified)continue;let r=Ve.readFileSync(o.path,"utf-8"),i=gm(r),a=[];for(let l of i){let u=await wc(l.text);a.push({text:l.text,embedding:u,offset:l.offset})}e.documents[o.name]={chunks:a,modified:o.modified.toISOString()}}for(let o of Object.keys(e.documents))t.some(s=>s.name===o)||delete e.documents[o];return Ve.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function wm(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=pc();if(!Ve.existsSync(s))return[];let r;try{r=JSON.parse(Ve.readFileSync(s,"utf-8"))}catch{return[]}let i=await wc(t),a=[];for(let[l,u]of Object.entries(r.documents||{})){let c=0,d="";for(let f of u.chunks||[]){let h=mm(i,f.embedding);h>c&&(c=h,d=f.text)}c>=o&&a.push({name:l,score:c,bestChunk:d})}return a.sort((l,u)=>u.score-l.score),a.slice(0,n)}function $m(t,e,n={}){let{k:o=60,topK:s=3}=n,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,s)}async function bm(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=fm(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await pm()){let a=await wm(t,{topK:n});r=$m(s,a,{topK:n})}}catch{}return r.map(i=>{let a=um(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 Xs={queryKey:null,result:null,ts:0},YS=3e5;async function GS(t){if(!t||!t.trim())return"";let e=Sn.join(process.cwd(),".nex","brain");if(!Ve.existsSync(e)||Uo().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(Xs.result!==null&&Xs.queryKey===o&&Date.now()-Xs.ts<YS)return Xs.result;let s;try{s=await bm(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=dn().estimateTokens}catch{r=c=>Math.ceil(c.length/4)}let i=25e3,a=[],l=0;for(let c of s){let d=c.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))+`
202
210
  ...(truncated)`}let h=typeof c.score=="number"?c.score.toFixed(2):String(c.score);if(a.push(`--- ${c.name} (relevance: ${h}) ---
203
- ${d}`),l+=r(d),l>=i)break}if(a.length===0)return Hs={queryKey:o,result:"",ts:Date.now()},"";let u=`KNOWLEDGE BASE (auto-selected):
211
+ ${d}`),l+=r(d),l>=i)break}if(a.length===0)return Xs={queryKey:o,result:"",ts:Date.now()},"";let u=`KNOWLEDGE BASE (auto-selected):
204
212
 
205
213
  ${a.join(`
206
214
 
207
- `)}`;return Hs={queryKey:o,result:u,ts:Date.now()},u}Zp.exports={getBrainDir:Gs,listDocuments:Fo,readDocument:Bp,writeDocument:tS,removeDocument:sS,buildIndex:ic,getIndex:Up,query:Jp,getBrainContext:lS,isEmbeddingAvailable:Gp,generateEmbedding:dc,buildEmbeddingIndex:Kp,semanticQuery:Xp,cosineSimilarity:Yp,_keywordQuery:Wp,_extractKeywords:lc,_chunkText:zp,parseFrontmatter:Bo,tokenize:Ri,_fuseResults:Vp}});var Ho=V((jC,um)=>{var qe=require("fs"),Tt=require("path"),cS=require("os"),{atomicWrite:Ai,withFileLockSync:Qp}=Gn(),Uo=["user","feedback","project","reference"],uS=50;function rs(){return Tt.join(process.cwd(),".nex","memory")}function Ys(){return Tt.join(rs(),"memory.json")}function em(){return Tt.join(rs(),"MEMORY.md")}function dS(){return Tt.join(process.cwd(),"NEX.md")}function tm(){return Tt.join(cS.homedir(),".nex","NEX.md")}function Oi(){let t=rs();qe.existsSync(t)||qe.mkdirSync(t,{recursive:!0})}function nm(t){let e=Tt.join(rs(),t);return qe.existsSync(e)||qe.mkdirSync(e,{recursive:!0}),e}function Wo(){let t=Ys();if(!qe.existsSync(t))return{};try{return JSON.parse(qe.readFileSync(t,"utf-8"))}catch{return{}}}function sm(t){Oi(),Ai(Ys(),JSON.stringify(t,null,2))}function om(){let t=Ys();if(!qe.existsSync(t))return;let e=Wo(),s=Object.keys(e);if(s.length===0){try{qe.renameSync(t,t+".bak")}catch{}return}for(let o of s){let n=e[o],r=n.value||String(n),i=o.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=nm("project"),l=Tt.join(a,`${i}.md`),u=r.split(`
215
+ `)}`;return Xs={queryKey:o,result:u,ts:Date.now()},u}_m.exports={getBrainDir:Vs,listDocuments:Uo,readDocument:um,writeDocument:qS,removeDocument:BS,buildIndex:hc,getIndex:dm,query:bm,getBrainContext:GS,isEmbeddingAvailable:pm,generateEmbedding:wc,buildEmbeddingIndex:ym,semanticQuery:wm,cosineSimilarity:mm,_keywordQuery:fm,_extractKeywords:mc,_chunkText:gm,parseFrontmatter:Wo,tokenize:Oi,_fuseResults:$m}});var Go=Z((vA,Pm)=>{var Fe=require("fs"),Rt=require("path"),zS=require("os"),{atomicWrite:Pi,withFileLockSync:xm}=Gn(),Ho=["user","feedback","project","reference"],KS=50;function is(){return Rt.join(process.cwd(),".nex","memory")}function Js(){return Rt.join(is(),"memory.json")}function km(){return Rt.join(is(),"MEMORY.md")}function XS(){return Rt.join(process.cwd(),"NEX.md")}function Sm(){return Rt.join(zS.homedir(),".nex","NEX.md")}function Mi(){let t=is();Fe.existsSync(t)||Fe.mkdirSync(t,{recursive:!0})}function vm(t){let e=Rt.join(is(),t);return Fe.existsSync(e)||Fe.mkdirSync(e,{recursive:!0}),e}function Yo(){let t=Js();if(!Fe.existsSync(t))return{};try{return JSON.parse(Fe.readFileSync(t,"utf-8"))}catch{return{}}}function Em(t){Mi(),Pi(Js(),JSON.stringify(t,null,2))}function Tm(){let t=Js();if(!Fe.existsSync(t))return;let e=Yo(),n=Object.keys(e);if(n.length===0){try{Fe.renameSync(t,t+".bak")}catch{}return}for(let o of n){let s=e[o],r=s.value||String(s),i=o.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=vm("project"),l=Rt.join(a,`${i}.md`),u=r.split(`
208
216
  `)[0].slice(0,100),c=`---
209
217
  name: ${o}
210
218
  description: ${u}
@@ -212,19 +220,19 @@ type: project
212
220
  ---
213
221
 
214
222
  ${r}
215
- `;Ai(l,c)}Ni();try{qe.renameSync(t,t+".bak")}catch{}}function fS(t,e,s,o){if(!Uo.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Uo.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 n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!n)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=nm(t),i=Tt.join(r,`${n}.md`);if(qe.existsSync(i))try{if(hc(qe.readFileSync(i,"utf-8")).body.slice(0,200)===s.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=o||s.split(`
223
+ `;Pi(l,c)}Li();try{Fe.renameSync(t,t+".bak")}catch{}}function VS(t,e,n,o){if(!Ho.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Ho.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!n||typeof n!="string"||n.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!s)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=vm(t),i=Rt.join(r,`${s}.md`);if(Fe.existsSync(i))try{if(bc(Fe.readFileSync(i,"utf-8")).body.slice(0,200)===n.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=o||n.split(`
216
224
  `)[0].slice(0,100),l=`---
217
225
  name: ${e}
218
226
  description: ${a}
219
227
  type: ${t}
220
228
  ---
221
229
 
222
- ${s}
223
- `;return Ai(i,l),Ni(),{ok:!0,path:i,updated:!0}}function hS(t,e){if(!Uo.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=Tt.join(rs(),t,`${s}.md`);if(!qe.existsSync(o))return!1;try{return qe.unlinkSync(o),Ni(),!0}catch{return!1}}function hc(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],o=(e[2]||"").trim(),n=r=>{let i=s.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:n("name"),description:n("description"),type:n("type"),body:o}}function rm(){let t=[],e=rs();for(let s of Uo){let o=Tt.join(e,s);if(!qe.existsSync(o))continue;let n;try{n=qe.readdirSync(o).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of n){let i=Tt.join(o,r);try{let a=qe.readFileSync(i,"utf-8"),l=hc(a);t.push({type:s,name:l.name||Tt.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function Ni(){let t=rm(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=uS+2)break;let o=`${s.type}/${Tt.basename(s.filePath)}`;e.push(`- [${s.name}](${o}) \u2014 ${s.description||"(no description)"}`)}Oi(),Ai(em(),e.join(`
230
+ ${n}
231
+ `;return Pi(i,l),Li(),{ok:!0,path:i,updated:!0}}function JS(t,e){if(!Ho.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=Rt.join(is(),t,`${n}.md`);if(!Fe.existsSync(o))return!1;try{return Fe.unlinkSync(o),Li(),!0}catch{return!1}}function bc(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 n=e[1],o=(e[2]||"").trim(),s=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:s("name"),description:s("description"),type:s("type"),body:o}}function Rm(){let t=[],e=is();for(let n of Ho){let o=Rt.join(e,n);if(!Fe.existsSync(o))continue;let s;try{s=Fe.readdirSync(o).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of s){let i=Rt.join(o,r);try{let a=Fe.readFileSync(i,"utf-8"),l=bc(a);t.push({type:n,name:l.name||Rt.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function Li(){let t=Rm(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=KS+2)break;let o=`${n.type}/${Rt.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Mi(),Pi(km(),e.join(`
224
232
  `)+`
225
- `)}function im(){let t=em();if(!qe.existsSync(t))return"";try{return qe.readFileSync(t,"utf-8").trim()}catch{return""}}function pS(t,e){Oi(),Qp(Ys(),()=>{let s=Wo();s[t]={value:e,updatedAt:new Date().toISOString()},sm(s)})}function mS(t){let e=Wo();return e[t]?e[t].value:null}function gS(t){return Oi(),Qp(Ys(),()=>{let e=Wo();return t in e?(delete e[t],sm(e),!0):!1})}function am(){let t=Wo();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function lm(){let t=tm();if(!qe.existsSync(t))return"";try{return qe.readFileSync(t,"utf-8").trim()}catch{return""}}function cm(){let t=dS();if(!qe.existsSync(t))return"";try{return qe.readFileSync(t,"utf-8").trim()}catch{return""}}function yS(){om();let t=[],e=lm();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
226
- ${e}`);let s=cm();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
227
- ${s}`);let o="",n=im();if(n)o=n;else{let d=am();d.length>0&&(o=`PROJECT MEMORY:
233
+ `)}function Cm(){let t=km();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function ZS(t,e){Mi(),xm(Js(),()=>{let n=Yo();n[t]={value:e,updatedAt:new Date().toISOString()},Em(n)})}function QS(t){let e=Yo();return e[t]?e[t].value:null}function ev(t){return Mi(),xm(Js(),()=>{let e=Yo();return t in e?(delete e[t],Em(e),!0):!1})}function Am(){let t=Yo();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function Om(){let t=Sm();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function Nm(){let t=XS();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function tv(){Tm();let t=[],e=Om();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
234
+ ${e}`);let n=Nm();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
235
+ ${n}`);let o="",s=Cm();if(s)o=s;else{let d=Am();d.length>0&&(o=`PROJECT MEMORY:
228
236
  ${d.map(h=>` ${h.key}: ${h.value}`).join(`
229
237
  `)}`)}let r=t.join(`
230
238
 
@@ -233,87 +241,87 @@ ${d.map(h=>` ${h.key}: ${h.value}`).join(`
233
241
  `}o=f.trimEnd()+`
234
242
  [Memory index truncated \u2014 use delete_memory to prune old entries]`}else o.length>u&&(o="");let c=[...t];return o&&c.push(o),c.length>0&&c.push(i),c.join(`
235
243
 
236
- `)}um.exports={saveMemory:fS,deleteMemory:hS,scanMemories:rm,rebuildIndex:Ni,loadMemoryIndex:im,remember:pS,recall:mS,forget:gS,listMemories:am,loadGlobalInstructions:lm,loadProjectInstructions:cm,getMemoryContext:yS,_getMemoryDir:rs,_getMemoryFile:Ys,_getGlobalNexMdPath:tm,_parseMemoryFile:hc,_migrateIfNeeded:om,VALID_TYPES:Uo}});var gm=V((DC,mm)=>{var Go=require("fs"),pc=require("path"),mc=process.env.NEX_AUDIT!=="false",is=null;function dm(){return is||(is=pc.join(process.cwd(),".nex","audit"),Go.existsSync(is)||Go.mkdirSync(is,{recursive:!0}),is)}function fm(){let t=new Date().toISOString().split("T")[0];return pc.join(dm(),`${t}.jsonl`)}function wS(t){if(mc)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:hm(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)+`
237
- `;Go.appendFileSync(fm(),s,"utf-8")}catch{}}function hm(t){if(!t||typeof t!="object")return{};let e={};for(let[s,o]of Object.entries(t))/key|token|password|secret|credential/i.test(s)?e[s]="***":typeof o=="string"&&o.length>500?e[s]=o.substring(0,500)+`... (${o.length} chars)`:e[s]=o;return e}function pm(t={}){let e=dm(),s=t.days||1,o=[];for(let n=0;n<s;n++){let r=t.date||new Date(Date.now()-n*864e5).toISOString().split("T")[0],i=pc.join(e,`${r}.jsonl`);if(!Go.existsSync(i))continue;let a=Go.readFileSync(i,"utf-8").split(`
238
- `).filter(l=>l.trim());for(let l of a)try{let u=JSON.parse(l);if(t.tool&&u.tool!==t.tool)continue;o.push(u)}catch{}if(t.date)break}return o}function $S(t=1){let e=pm({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let s={},o=0,n=0;for(let r of e)s[r.tool]=(s[r.tool]||0)+1,o+=r.duration||0,r.success&&n++;return{totalCalls:e.length,byTool:s,avgDuration:Math.round(o/e.length),successRate:n/e.length}}function bS(t){mc=t}function _S(){return mc}function kS(){is=null}mm.exports={logToolExecution:wS,sanitizeArgs:hm,readAuditLog:pm,getAuditSummary:$S,setAuditEnabled:bS,isAuditEnabled:_S,getAuditLogPath:fm,_reset:kS}});var Lm=V((FC,Pm)=>{var ze=require("fs").promises,Xt=require("fs"),ie=require("path"),Ue=require("util").promisify(require("child_process").exec),as=require("util").promisify(require("child_process").execFile),{spawnSync:xS}=require("child_process"),gc=require("axios"),{isForbidden:SS,isSSHForbidden:vS,isDangerous:ES,isCritical:ym,isBashPathForbidden:TS,confirm:Kt}=xo(),{showDiff:Mi,showNewFile:RS,showEditDiff:qC,confirmFileChange:Yo}=of(),{C:de,Spinner:CS,getToolSpinnerText:AS}=ot(),{ToolProgress:Pi}=Yn(),{isGitRepo:yc,getCurrentBranch:wm,getStatus:OS,getDiff:NS}=si(),{recordChange:Li}=gf(),{fuzzyFindText:$m,findMostSimilar:Jo}=Ff(),{runDiagnostics:zo}=Uf(),{findFileInIndex:MS,getFileIndex:bm,searchContentIndex:PS,scorePathMatch:_m,refreshIndex:LS,isIndexValid:IS}=sn(),{resolveProfile:jt,sshExec:yt,scpUpload:jS,scpDownload:km}=Ds(),{resolveDeployConfig:DS,loadDeployConfigs:qS}=ch(),{getEditMode:xm}=Po(),FS=/^(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/,BS=/^ssh\s/,US=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Rt(t){return ze.access(t).then(()=>!0).catch(()=>!1)}var Ii=null,Sm=0,WS=12e4;function HS(){let t=Date.now();if(Ii&&t-Sm<WS)return Ii;let e=ie.dirname(process.cwd());try{let s=Xt.readdirSync(e,{withFileTypes:!0}),o=ie.basename(process.cwd()),n=s.filter(r=>r.isDirectory()&&r.name!==o&&!r.name.startsWith(".")).map(r=>r.name).sort();return Ii=n.length>0?n:null,Sm=t,Ii}catch{return null}}function wc(t){if(t&&ie.resolve(t)!==process.cwd())return"";let e=HS();if(!e)return"";let s=ie.dirname(process.cwd());return`
239
- Hint: no matches in current project. Sibling directories in ${s}/:
244
+ `)}Pm.exports={saveMemory:VS,deleteMemory:JS,scanMemories:Rm,rebuildIndex:Li,loadMemoryIndex:Cm,remember:ZS,recall:QS,forget:ev,listMemories:Am,loadGlobalInstructions:Om,loadProjectInstructions:Nm,getMemoryContext:tv,_getMemoryDir:is,_getMemoryFile:Js,_getGlobalNexMdPath:Sm,_parseMemoryFile:bc,_migrateIfNeeded:Tm,VALID_TYPES:Ho}});var qm=Z((EA,Dm)=>{var zo=require("fs"),_c=require("path"),xc=process.env.NEX_AUDIT!=="false",as=null;function Mm(){return as||(as=_c.join(process.cwd(),".nex","audit"),zo.existsSync(as)||zo.mkdirSync(as,{recursive:!0}),as)}function Lm(){let t=new Date().toISOString().split("T")[0];return _c.join(Mm(),`${t}.jsonl`)}function nv(t){if(xc)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Im(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},n=JSON.stringify(e)+`
245
+ `;zo.appendFileSync(Lm(),n,"utf-8")}catch{}}function Im(t){if(!t||typeof t!="object")return{};let e={};for(let[n,o]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof o=="string"&&o.length>500?e[n]=o.substring(0,500)+`... (${o.length} chars)`:e[n]=o;return e}function jm(t={}){let e=Mm(),n=t.days||1,o=[];for(let s=0;s<n;s++){let r=t.date||new Date(Date.now()-s*864e5).toISOString().split("T")[0],i=_c.join(e,`${r}.jsonl`);if(!zo.existsSync(i))continue;let a=zo.readFileSync(i,"utf-8").split(`
246
+ `).filter(l=>l.trim());for(let l of a)try{let u=JSON.parse(l);if(t.tool&&u.tool!==t.tool)continue;o.push(u)}catch{}if(t.date)break}return o}function sv(t=1){let e=jm({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},o=0,s=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,o+=r.duration||0,r.success&&s++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(o/e.length),successRate:s/e.length}}function ov(t){xc=t}function rv(){return xc}function iv(){as=null}Dm.exports={logToolExecution:nv,sanitizeArgs:Im,readAuditLog:jm,getAuditSummary:sv,setAuditEnabled:ov,isAuditEnabled:rv,getAuditLogPath:Lm,_reset:iv}});var og=Z((RA,sg)=>{var Je=require("fs").promises,Jt=require("fs"),ie=require("path"),He=require("util").promisify(require("child_process").exec),ls=require("util").promisify(require("child_process").execFile),{spawnSync:av}=require("child_process"),kc=require("axios"),{isForbidden:lv,isSSHForbidden:cv,isDangerous:uv,isCritical:Fm,isBashPathForbidden:dv,confirm:Vt}=vo(),{showDiff:Ii,showNewFile:fv,showEditDiff:TA,confirmFileChange:Ko}=$f(),{C:fe,Spinner:hv,getToolSpinnerText:pv}=it(),{ToolProgress:ji}=zn(),{isGitRepo:Sc,getCurrentBranch:Bm,getStatus:mv,getDiff:gv}=ri(),{recordChange:Di}=Af(),{fuzzyFindText:Um,findMostSimilar:Qo}=eh(),{runDiagnostics:Xo}=dh(),{findFileInIndex:yv,getFileIndex:Wm,searchContentIndex:wv,scorePathMatch:Hm,refreshIndex:$v,isIndexValid:bv}=an(),{resolveProfile:Dt,sshExec:wt,scpUpload:_v,scpDownload:Ym}=Ws(),{resolveDeployConfig:xv,loadDeployConfigs:kv}=Nh(),{getEditMode:Gm}=Io(),Sv=/^(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/,vv=/^ssh\s/,Ev=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Ct(t){return Je.access(t).then(()=>!0).catch(()=>!1)}var qi=null,zm=0,Tv=12e4;function Rv(){let t=Date.now();if(qi&&t-zm<Tv)return qi;let e=ie.dirname(process.cwd());try{let n=Jt.readdirSync(e,{withFileTypes:!0}),o=ie.basename(process.cwd()),s=n.filter(r=>r.isDirectory()&&r.name!==o&&!r.name.startsWith(".")).map(r=>r.name).sort();return qi=s.length>0?s:null,zm=t,qi}catch{return null}}function vc(t){if(t&&ie.resolve(t)!==process.cwd())return"";let e=Rv();if(!e)return"";let n=ie.dirname(process.cwd());return`
247
+ Hint: no matches in current project. Sibling directories in ${n}/:
240
248
  ${e.join(", ")}
241
- You can search there with: grep pattern --path ${s}/<dir>`}async function ji(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=it(e);if(s&&await Rt(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],n=ie.extname(t);if(!n)for(let i of o){let a=it(t+i);if(a&&await Rt(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(n){let i=t.replace(/\.[^.]+$/,"");for(let a of o){if(a===n)continue;let l=it(i+a);if(l&&await Rt(l))return{fixedPath:l,message:`(auto-fixed: ${n} \u2192 ${a})`}}}let r=ie.basename(t);if(r&&r.length>2)try{let i=MS(r).map(a=>it(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${ie.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
249
+ You can search there with: grep pattern --path ${n}/<dir>`}async function Fi(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=lt(e);if(n&&await Ct(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=ie.extname(t);if(!s)for(let i of o){let a=lt(t+i);if(a&&await Ct(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(s){let i=t.replace(/\.[^.]+$/,"");for(let a of o){if(a===s)continue;let l=lt(i+a);if(l&&await Ct(l))return{fixedPath:l,message:`(auto-fixed: ${s} \u2192 ${a})`}}}let r=ie.basename(t);if(r&&r.length>2)try{let i=yv(r).map(a=>lt(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${ie.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
242
250
  ${i.map(l=>ie.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
243
- `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=sn(),l=a().filter(u=>ie.basename(u).toLowerCase()===i).map(u=>it(u));if(l.length===1)return{fixedPath:l[0],message:`(auto-fixed: case-insensitive match \u2192 ${ie.relative(process.cwd(),l[0])})`};if(l.length>1&&l.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
251
+ `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=an(),l=a().filter(u=>ie.basename(u).toLowerCase()===i).map(u=>lt(u));if(l.length===1)return{fixedPath:l[0],message:`(auto-fixed: case-insensitive match \u2192 ${ie.relative(process.cwd(),l[0])})`};if(l.length>1&&l.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
244
252
  ${l.map(c=>ie.relative(process.cwd(),c)).map(c=>` - ${c}`).join(`
245
- `)}`}}catch{}try{let{smartSearch:i}=sn(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=it(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 ${ie.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 ${ie.relative(process.cwd(),l)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
246
- ${a.map(c=>ie.relative(process.cwd(),it(c.file))).map(c=>` - ${c}`).join(`
247
- `)}`}}}catch{}return{fixedPath:null,message:""}}function GS(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 Rm(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 o=s.split(/[\/\s,]+/).map(n=>n.trim()).filter(Boolean).filter(n=>n!=="."&&n!=="..").filter(n=>!/^\.[a-z0-9]+$/i.test(n)).filter(n=>n.length>=3);return o.length===0?null:(o.sort((n,r)=>r.length-n.length),o[0])}async function Cm(t,e){let s=Rm(t);if(!s)return new Map;try{let o=await PS(s,void 0,e||process.cwd()),n=new Map;for(let r of o){let a=r.name.toLowerCase()===s.toLowerCase()?140:90;n.set(r.file,(n.get(r.file)||0)+a)}return n}catch{return new Map}}function vm(t,e){if(!t)return"";let s=e||process.cwd(),o=ie.isAbsolute(t)?t:ie.resolve(s,t),n=ie.relative(s,o);return n&&!n.startsWith("..")&&!ie.isAbsolute(n)?n:ie.relative(process.cwd(),o)}function Ko(t,e){let s=(t||"").trim();return s?e==="files_with_matches"||e==="count"?s.split(`
248
- `).filter(o=>o.trim()):s.split(`
249
- `).filter(o=>o.trim()):[]}function Am(t,{query:e,basePath:s,definitionScores:o=new Map,mtimeByPath:n=new Map}={}){let r=Rm(e);return[...t].sort((i,a)=>{let l=vm(i,s),u=vm(a,s),c=0,d=0;if(r&&(c+=_m(l,r),d+=_m(u,r)),c+=o.get(l)||0,d+=o.get(u)||0,c!==d)return d-c;let f=n.get(i)||0,h=n.get(a)||0;return f!==h?h-f:l.localeCompare(u)})}async function $c(t,{query:e,basePath:s,outputMode:o}={}){if(!Array.isArray(t)||t.length<=1)return t;let n=new Map,r=[];for(let u of t){if(!u)continue;let c=u;(o==="count"||o!=="files_with_matches")&&(c=u.split(":")[0]),n.has(c)||(n.set(c,[]),r.push(c)),n.get(c).push(u)}let i=await Cm(e,s),a=Am(r,{query:e,basePath:s,definitionScores:i}),l=[];for(let u of a)l.push(...n.get(u)||[]);return l}function Om(t,e){let s=[];if(/command not found|: not found|not recognized/i.test(t)){let o=e.match(/^(\S+)/),n=o?o[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(n)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(n)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${n}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let o=t.match(/Cannot find module '([^']+)'/),n=o?o[1]:"";n&&!n.startsWith(".")&&!n.startsWith("/")?s.push(`HINT: Missing npm package "${n}". Run: npm install ${n}`):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 o=t.match(/port (\d+)|:(\d+)/),n=o?o[1]||o[2]:"";s.push(`HINT: Port ${n||""} 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 o=t.match(/curl:\s*\((\d+)\)/),n=o?parseInt(o[1],10):null;n===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):n===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."):n===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):n===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(n===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 o=t.match(/port (\d+)/),n=o?o[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${n}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${n}" 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+`
250
-
251
- `+s.join(`
252
- `)}function Nm(t,e,s){let o=Jo(t,e);if(!o)return null;let n=Math.max(2,Math.ceil(e.length*.03));return o.distance>n?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(s),distance:o.distance,line:o.line}}var Em=!1,ls=null;function YS(){ls&&(ls(),ls=null)}var xc=null;function zS(t){xc=t}async function bc(){if(!Em){Em=!0;try{let{stdout:t}=await Ue("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Ue('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Ue("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Ue("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var KS=[/\.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 XS(){let t=process.cwd();try{return Xt.realpathSync(t)}catch{return ie.resolve(t)}}function VS(t,e){let s=ie.relative(e,t);return s===""||!s.startsWith("..")&&!ie.isAbsolute(s)}function JS(t){if(Xt.existsSync(t))return Xt.realpathSync(t);let e=ie.dirname(t);for(;e&&e!==ie.dirname(e);){if(Xt.existsSync(e)){let s=Xt.realpathSync(e),o=ie.relative(e,t);return ie.resolve(s,o)}e=ie.dirname(e)}return t}function it(t){let e=ie.isAbsolute(t)?ie.resolve(t):ie.resolve(process.cwd(),t);for(let o of KS)if(o.test(e))return null;let s=JS(e);return VS(s,XS())?s:null}function Ee(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function Mm(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function ZS(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function QS(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function _c(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function ev(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Xo(t,e="user"){return Mm(t)?null:`ERROR: ${e} contains unsafe characters`}function kc(t,e="service"){return ZS(t)?null:`ERROR: ${e} contains unsafe characters`}var tv=[{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 Vo(t,{server:e,context:s}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,n=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(n&&(r+=` --context ${n}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function Tm(t,e,s={}){switch(t){case"bash":{let o=e.command,n=SS(o);if(n){let d=GS(o);return`BLOCKED: Command matches forbidden pattern: ${n}${d?`
253
- HINT: ${d}`:""}`}let r=TS(o);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
254
- 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?ym(o):ES(o)){let d=ym(o)?"\u26D4":"\u26A0";if(!await Kt(` ${d} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Xt.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${de.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${de.reset}`)}let l=BS.test(o.trim())&&!US.test(o.trim());if(FS.test(o.trim())||l){s.silent||console.log(`${de.dim} \u25B6 interactive: ${o}${de.reset}`);let d=xS("sh",["-c",o],{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:u}=Yn(),c=s.silent?null:new u("bash",o.substring(0,40));c&&c.start();try{let{stdout:d,stderr:f}=await Ue(o,{cwd:a,timeout:9e4,maxBuffer:5242880});return c&&c.stop(),d||f||"(no output)"}catch(d){c&&c.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),h=Om(f,o);return`EXIT ${d.code||1}
255
- ${h}`}}case"read_file":{let o=new Pi("read_file","Reading file...");o.start();try{let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Rt(n)){let le=await ji(e.path);if(le.fixedPath)n=le.fixedPath,console.log(`${de.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),n)}${de.reset}`),o.update({message:"Resolved path",detail:ie.relative(process.cwd(),n)});else return`ERROR: File not found: ${e.path}${le.message?`
256
- `+le.message:""}`}let i=ie.relative(process.cwd(),n);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),l=await Xt.promises.open(n,"r"),{bytesRead:u}=await l.read(a,0,8192,0);await l.close();for(let le=0;le<u;le++)if(a[le]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let c=await ze.readFile(n,"utf-8");if(!c&&(await ze.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let d=c.split(`
257
- `),f=await ze.stat(n),h=d.length,m=350,g=!e.line_start&&!e.line_end,$=g&&h>m,k=(e.line_start||1)-1,v=$?m:e.line_end||d.length,A=k+1,E=v;o.update({count:Math.max(0,v-k),total:h,detail:`${i} lines ${A}-${E}`,message:$?"Reading excerpt":"Reading"});let S=$?`showing lines 1-${m} of ${h}`:e.line_start||e.line_end?`lines ${k+1}-${v} of ${h}`:`${h} lines`,N=`File: ${i} (${S}, ${f.size} bytes)`,ee=d.slice(k,v).map((le,ue)=>`${k+ue+1}: ${le}`).join(`
253
+ `)}`}}catch{}try{let{smartSearch:i}=an(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=lt(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 ${ie.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 ${ie.relative(process.cwd(),l)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
254
+ ${a.map(c=>ie.relative(process.cwd(),lt(c.file))).map(c=>` - ${c}`).join(`
255
+ `)}`}}}catch{}return{fixedPath:null,message:""}}function Cv(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 Jm(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e||/[()[\]{}|^$\\]/.test(e))return null;let n=e.replace(/\*\*/g," ").replace(/[*?]/g," ").replace(/[:=><!]+/g," ").replace(/\s+/g," ").trim();if(!n)return null;let o=n.split(/[\/\s,]+/).map(s=>s.trim()).filter(Boolean).filter(s=>s!=="."&&s!=="..").filter(s=>!/^\.[a-z0-9]+$/i.test(s)).filter(s=>s.length>=3);return o.length===0?null:(o.sort((s,r)=>r.length-s.length),o[0])}async function Zm(t,e){let n=Jm(t);if(!n)return new Map;try{let o=await wv(n,void 0,e||process.cwd()),s=new Map;for(let r of o){let a=r.name.toLowerCase()===n.toLowerCase()?140:90;s.set(r.file,(s.get(r.file)||0)+a)}return s}catch{return new Map}}function Km(t,e){if(!t)return"";let n=e||process.cwd(),o=ie.isAbsolute(t)?t:ie.resolve(n,t),s=ie.relative(n,o);return s&&!s.startsWith("..")&&!ie.isAbsolute(s)?s:ie.relative(process.cwd(),o)}function Vo(t,e){let n=(t||"").trim();return n?e==="files_with_matches"||e==="count"?n.split(`
256
+ `).filter(o=>o.trim()):n.split(`
257
+ `).filter(o=>o.trim()):[]}function Qm(t,{query:e,basePath:n,definitionScores:o=new Map,mtimeByPath:s=new Map}={}){let r=Jm(e);return[...t].sort((i,a)=>{let l=Km(i,n),u=Km(a,n),c=0,d=0;if(r&&(c+=Hm(l,r),d+=Hm(u,r)),c+=o.get(l)||0,d+=o.get(u)||0,c!==d)return d-c;let f=s.get(i)||0,h=s.get(a)||0;return f!==h?h-f:l.localeCompare(u)})}async function Ec(t,{query:e,basePath:n,outputMode:o}={}){if(!Array.isArray(t)||t.length<=1)return t;let s=new Map,r=[];for(let u of t){if(!u)continue;let c=u;(o==="count"||o!=="files_with_matches")&&(c=u.split(":")[0]),s.has(c)||(s.set(c,[]),r.push(c)),s.get(c).push(u)}let i=await Zm(e,n),a=Qm(r,{query:e,basePath:n,definitionScores:i}),l=[];for(let u of a)l.push(...s.get(u)||[]);return l}function eg(t,e){let n=[];if(/command not found|: not found|not recognized/i.test(t)){let o=e.match(/^(\S+)/),s=o?o[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(s)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(s)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${s}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let o=t.match(/Cannot find module '([^']+)'/),s=o?o[1]:"";s&&!s.startsWith(".")&&!s.startsWith("/")?n.push(`HINT: Missing npm package "${s}". Run: npm install ${s}`):n.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&n.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let o=t.match(/port (\d+)|:(\d+)/),s=o?o[1]||o[2]:"";n.push(`HINT: Port ${s||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&n.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&n.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&n.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&n.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let o=t.match(/curl:\s*\((\d+)\)/),s=o?parseInt(o[1],10):null;s===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):s===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):s===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):s===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(s===35||/SSL.*error/i.test(t))&&n.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let o=t.match(/port (\d+)/),s=o?o[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${s}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${s}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&n.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)&&n.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)&&n.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)&&n.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.'),n.length===0?t:t+`
258
+
259
+ `+n.join(`
260
+ `)}function tg(t,e,n){let o=Qo(t,e);if(!o)return null;let s=Math.max(2,Math.ceil(e.length*.03));return o.distance>s?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(n),distance:o.distance,line:o.line}}var Xm=!1,cs=null;function Av(){cs&&(cs(),cs=null)}var Ac=null;function Ov(t){Ac=t}async function Tc(){if(!Xm){Xm=!0;try{let{stdout:t}=await He("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await He('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await He("git stash pop",{cwd:process.cwd(),timeout:1e4}),await He("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Nv=[/\.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 Pv(){let t=process.cwd();try{return Jt.realpathSync(t)}catch{return ie.resolve(t)}}function Mv(t,e){let n=ie.relative(e,t);return n===""||!n.startsWith("..")&&!ie.isAbsolute(n)}function Lv(t){if(Jt.existsSync(t))return Jt.realpathSync(t);let e=ie.dirname(t);for(;e&&e!==ie.dirname(e);){if(Jt.existsSync(e)){let n=Jt.realpathSync(e),o=ie.relative(e,t);return ie.resolve(n,o)}e=ie.dirname(e)}return t}function lt(t){let e=ie.isAbsolute(t)?ie.resolve(t):ie.resolve(process.cwd(),t);for(let o of Nv)if(o.test(e))return null;let n=Lv(e);return Mv(n,Pv())?n:null}function Ce(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function ng(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function Iv(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function jv(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function Rc(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function Dv(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Jo(t,e="user"){return ng(t)?null:`ERROR: ${e} contains unsafe characters`}function Cc(t,e="service"){return Iv(t)?null:`ERROR: ${e} contains unsafe characters`}var qv=[{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 Zo(t,{server:e,context:n}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function Vm(t,e,n={}){switch(t){case"bash":{let o=e.command,s=lv(o);if(s){let d=Cv(o);return`BLOCKED: Command matches forbidden pattern: ${s}${d?`
261
+ HINT: ${d}`:""}`}let r=dv(o);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
262
+ HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(n.autoConfirm?Fm(o):uv(o)){let d=Fm(o)?"\u26D4":"\u26A0";if(!await Vt(` ${d} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Jt.accessSync(a)}catch{a=require("os").homedir(),n.silent||console.log(`${fe.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${fe.reset}`)}let l=vv.test(o.trim())&&!Ev.test(o.trim());if(Sv.test(o.trim())||l){n.silent||console.log(`${fe.dim} \u25B6 interactive: ${o}${fe.reset}`);let d=av("sh",["-c",o],{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:u}=zn(),c=n.silent?null:new u("bash",`$ ${o.substring(0,72)}`);c&&c.start();try{let{stdout:d,stderr:f}=await He(o,{cwd:a,timeout:9e4,maxBuffer:5242880});return c&&c.stop(),d||f||"(no output)"}catch(d){c&&c.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),h=eg(f,o);return`EXIT ${d.code||1}
263
+ ${h}`}}case"read_file":{let o=new ji("read_file","Reading file...");o.start();try{let s=lt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ct(s)){let ce=await Fi(e.path);if(ce.fixedPath)s=ce.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),s)}${fe.reset}`),o.update({message:"Resolved path",detail:ie.relative(process.cwd(),s)});else return`ERROR: File not found: ${e.path}${ce.message?`
264
+ `+ce.message:""}`}let i=ie.relative(process.cwd(),s);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),l=await Jt.promises.open(s,"r"),{bytesRead:u}=await l.read(a,0,8192,0);await l.close();for(let ce=0;ce<u;ce++)if(a[ce]===0)return`ERROR: ${s} is a binary file (not readable as text)`;let c=await Je.readFile(s,"utf-8");if(!c&&(await Je.stat(s)).size>0)return`WARNING: ${s} is empty or unreadable`;let d=c.split(`
265
+ `),f=await Je.stat(s),h=d.length,m=350,g=!e.line_start&&!e.line_end,$=g&&h>m,x=(e.line_start||1)-1,E=$?m:e.line_end||d.length,N=x+1,v=E;o.update({count:Math.max(0,E-x),total:h,detail:`${i} lines ${N}-${v}`,message:$?"Reading excerpt":"Reading"});let S=$?`showing lines 1-${m} of ${h}`:e.line_start||e.line_end?`lines ${x+1}-${E} of ${h}`:`${h} lines`,P=`File: ${i} (${S}, ${f.size} bytes)`,ne=d.slice(x,E).map((ce,de)=>`${x+de+1}: ${ce}`).join(`
258
266
  `),re=$?`
259
267
 
260
- [\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${m} of ${h} 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=${m+1}), or use grep_search to find specific keywords.]`:!g&&h>v?`
268
+ [\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${m} of ${h} 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=${m+1}), or use grep_search to find specific keywords.]`:!g&&h>E?`
261
269
 
262
- [\u{1F6A8} FILE CONTINUES: This is only lines ${k+1} to ${v} of ${h} total. The rest is HIDDEN. Use line_start=${v+1} to read the next section, or grep_search for keywords.]`:"";return`${N}
263
- ${ee}${re}`}finally{o.stop()}}case"write_file":{let o=new Pi("write_file","Preparing write...");o.start();try{await bc();let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await Rt(n),i=null,a=String(e.content||"").split(`
264
- `).length;if(o.update({count:a,detail:`${ie.relative(process.cwd(),n)} ${a} lines`,message:r?"Overwriting":"Creating"}),s.autoConfirm)r&&(i=await ze.readFile(n,"utf-8"));else if(r){i=await ze.readFile(n,"utf-8");let f=await zo(n,e.content);if(Mi(n,i,e.content,{annotations:f}),!await Yo("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let f=await zo(n,e.content);if(RS(n,e.content,{annotations:f}),!await Yo("Create"))return"CANCELLED: User declined to create file."}let l=ie.dirname(n);await Rt(l)||await ze.mkdir(l,{recursive:!0}),o.update({message:"Writing",detail:`${ie.relative(process.cwd(),n)} ${a} lines`}),await ze.writeFile(n,e.content,"utf-8");let c=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");c&&(o.update({message:"Chmod",detail:ie.relative(process.cwd(),n)}),await ze.chmod(n,493)),Li("write_file",n,i,e.content);let d=c?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${d}`}finally{o.stop()}}case"edit_file":{let o=new Pi("edit_file","Preparing edit...");o.start();try{await bc();let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Rt(n)){let d=await ji(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${de.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),n)}${de.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
265
- `+d.message:""}`}o.update({message:"Loading",detail:ie.relative(process.cwd(),n)});let i=await ze.readFile(n,"utf-8"),a=e.old_text,l=!1,u=!1;if(!i.includes(e.old_text)){o.update({message:"Matching target",detail:`${ie.relative(process.cwd(),n)} ${String(e.old_text||"").trim().split(`
266
- `)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=ut();if(xm(d(),f())==="strict"){let g=Jo(i,e.old_text);return g?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
270
+ [\u{1F6A8} FILE CONTINUES: This is only lines ${x+1} to ${E} of ${h} total. The rest is HIDDEN. Use line_start=${E+1} to read the next section, or grep_search for keywords.]`:"";return`${P}
271
+ ${ne}${re}`}finally{o.stop()}}case"write_file":{let o=new ji("write_file","Preparing write...");o.start();try{await Tc();let s=lt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await Ct(s),i=null,a=String(e.content||"").split(`
272
+ `).length;if(o.update({count:a,detail:`${ie.relative(process.cwd(),s)} ${a} lines`,message:r?"Overwriting":"Creating"}),n.autoConfirm)r&&(i=await Je.readFile(s,"utf-8"));else if(r){i=await Je.readFile(s,"utf-8");let f=await Xo(s,e.content);if(Ii(s,i,e.content,{annotations:f}),!await Ko("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let f=await Xo(s,e.content);if(fv(s,e.content,{annotations:f}),!await Ko("Create"))return"CANCELLED: User declined to create file."}let l=ie.dirname(s);await Ct(l)||await Je.mkdir(l,{recursive:!0}),o.update({message:"Writing",detail:`${ie.relative(process.cwd(),s)} ${a} lines`}),await Je.writeFile(s,e.content,"utf-8");let c=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||e.content.startsWith("#!");c&&(o.update({message:"Chmod",detail:ie.relative(process.cwd(),s)}),await Je.chmod(s,493)),Di("write_file",s,i,e.content);let d=c?" [chmod +x applied]":"";return`Written: ${s} (${e.content.length} chars)${d}`}finally{o.stop()}}case"edit_file":{let o=new ji("edit_file","Preparing edit...");o.start();try{await Tc();let s=lt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ct(s)){let d=await Fi(e.path);if(d.fixedPath)s=d.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),s)}${fe.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
273
+ `+d.message:""}`}o.update({message:"Loading",detail:ie.relative(process.cwd(),s)});let i=await Je.readFile(s,"utf-8"),a=e.old_text,l=!1,u=!1;if(!i.includes(e.old_text)){o.update({message:"Matching target",detail:`${ie.relative(process.cwd(),s)} ${String(e.old_text||"").trim().split(`
274
+ `)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=dt();if(Gm(d(),f())==="strict"){let g=Qo(i,e.old_text);return g?`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)
267
275
  Most similar text (line ${g.line}, distance ${g.distance}):
268
- ${g.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let m=$m(i,e.old_text);if(m)a=m,l=!0,o.update({message:"Matched target",detail:`${ie.relative(process.cwd(),n)} whitespace-normalized`}),console.log(`${de.dim} \u2713 fuzzy whitespace match applied${de.reset}`);else{let g=Nm(i,e.old_text,e.new_text);if(g){if(!s.autoConfirm){let E=await zo(n,g.content);if(Mi(n,i,g.content,{annotations:E}),!await Yo(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await ze.writeFile(n,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||g.content.startsWith("#!"))&&await ze.chmod(n,493),Li("edit_file",n,i,g.content);let A=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${de.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${de.reset}`),`Edited: ${n} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${A}")`}let $=Jo(i,e.old_text);if($){let A=i.split(`
269
- `),E=Math.max(0,$.line-6),S=Math.min(A.length,$.line+10),N=A.slice(E,S).map((re,le)=>`${E+le+1}: ${re}`).join(`
270
- `),ee=`line_start=${Math.max(1,$.line-5)} line_end=${Math.min(A.length,$.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${$.line}, distance ${$.distance})
276
+ ${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let m=Um(i,e.old_text);if(m)a=m,l=!0,o.update({message:"Matched target",detail:`${ie.relative(process.cwd(),s)} whitespace-normalized`}),console.log(`${fe.dim} \u2713 fuzzy whitespace match applied${fe.reset}`);else{let g=tg(i,e.old_text,e.new_text);if(g){if(!n.autoConfirm){let v=await Xo(s,g.content);if(Ii(s,i,g.content,{annotations:v}),!await Ko(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await Je.writeFile(s,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||g.content.startsWith("#!"))&&await Je.chmod(s,493),Di("edit_file",s,i,g.content);let N=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${fe.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${fe.reset}`),`Edited: ${s} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${N}")`}let $=Qo(i,e.old_text);if($){let N=i.split(`
277
+ `),v=Math.max(0,$.line-6),S=Math.min(N.length,$.line+10),P=N.slice(v,S).map((re,ce)=>`${v+ce+1}: ${re}`).join(`
278
+ `),ne=`line_start=${Math.max(1,$.line-5)} line_end=${Math.min(N.length,$.line+15)}`;return`ERROR: old_text not found in ${s} (most similar at line ${$.line}, distance ${$.distance})
271
279
 
272
280
  Actual file content around line ${$.line} \u2014 use this to correct old_text:
273
- ${N}
274
-
275
- Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${ee}`}let k=(e.old_text||"").trim().split(`
276
- `)[0].slice(0,60),v=k?`
277
- Recovery: grep -n "${k.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
278
- 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}${v}`}}if(!s.autoConfirm){o.update({message:"Previewing edit",detail:`${ie.relative(process.cwd(),n)} ${String(e.new_text||"").trim().split(`
279
- `)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await zo(n,d);if(Mi(n,i,d,{annotations:f}),!await Yo(l?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let c=i.split(a).join(e.new_text);return o.update({message:"Applying edit",detail:`${ie.relative(process.cwd(),n)} ${String(e.new_text||"").trim().split(`
280
- `)[0].slice(0,40)}`}),await ze.writeFile(n,c,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||c.startsWith("#!"))&&(o.update({message:"Chmod",detail:ie.relative(process.cwd(),n)}),await ze.chmod(n,493)),Li("edit_file",n,i,c),l?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}finally{o.stop()}}case"list_directory":{let o=it(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Rt(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),c=it(u),d=await Rt(c);if(c&&d)o=c;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],l=async(u,c,d)=>{if(c>r)return;let f;try{f=await ze.readdir(u,{withFileTypes:!0})}catch{return}f=f.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of f){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let m=h.isDirectory()?"/":"";a.push(`${d}${h.name}${m}`),h.isDirectory()&&await l(ie.join(u,h.name),c+1,d+" ")}};return await l(o,1,""),a.join(`
281
- `)||"(empty)"}case"search_files":{let o=it(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let n=["-rn","-H"];e.file_pattern&&n.push(`--include=${e.file_pattern}`),n.push(e.pattern,o);try{let{stdout:r}=await as("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=Ko(r).slice(0,50);return(await $c(i,{query:e.pattern,basePath:o})).join(`
282
- `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let n=process.cwd(),r=e.path?it(e.path):n,i=e.pattern,a=S=>{let N=S.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${N}$`)},l=a(i),u=i.split("/").pop(),c=a(u),{ToolProgress:d}=Yn(),f=new d("glob","Finding files...");f.start();let h=bm();IS(r)||(await LS(r),h=bm());let m=h.filter(S=>l.test(S)||c.test(ie.basename(S))).map(S=>ie.join(r,S));if(m.length===0)return f.stop(),"(no matches)"+wc(e.path);let g=await Promise.all(m.slice(0,210).map(async S=>{try{let N=await ze.stat(S);return{path:S,mtime:N.mtimeMs}}catch{return{path:S,mtime:0}}})),$=new Map(g.map(S=>[S.path,S.mtime])),k=await Cm(i,r),v=Am(g.map(S=>S.path),{query:i,basePath:r,definitionScores:k,mtimeByPath:$}),A=m.length>200,E=v.slice(0,200).join(`
283
- `);return f.update({count:m.length,detail:e.pattern}),f.stop(),A?`${E}
284
-
285
- \u26A0 Results truncated at 200. Use a more specific pattern.`:E}case"grep":{let o=e.path?it(e.path):process.cwd();if(e.staged){let{getDiff:l}=si(),u=await l(!0);if(!u.trim())return"(no staged changes)";let c=new Set,d=u.split(`
286
- `);for(let $ of d)if($.startsWith("diff --git")){let k=$.match(/diff --git a\/(.+) b\/(.+)/);k&&c.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:h}=Yn(),m=new h("grep","Searching staged content...");m.start();let g=[];for(let $ of c)try{let k=ie.join(process.cwd(),$);if(await Rt(k)){let v=[...f];v.push(e.pattern,k);let{stdout:A}=await as("grep",v,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let E=Ko(A,e.output_mode);g=g.concat(E)}else g=g.concat(Ko(A))}}catch{}return g=await $c(g,{query:e.pattern,basePath:process.cwd(),outputMode:e.output_mode}),m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
287
- `).trim()||"(no matches in staged files)"}let n=["-rn","-E","-H"];e.ignore_case&&n.push("-i"),e.include&&n.push(`--include=${e.include}`),e.type&&n.push(`--include=*.${e.type}`);let r=20;e.context?n.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&n.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&n.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?n.push("-l"):e.output_mode==="count"&&n.push("-c"),n.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),n.push(e.pattern,o);let{ToolProgress:i}=Yn(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await as("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),u;e.output_mode==="files_with_matches"||e.output_mode==="count"?u=Ko(l,e.output_mode):u=Ko(l);let c=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return u=await $c(u,{query:e.pattern,basePath:o,outputMode:e.output_mode}),u=u.slice(c,c+d),a.update({count:u.length,detail:`in ${o}`}),a.stop(),u.join(`
288
- `).trim()||"(no matches)"+wc(e.path)}catch(l){if(a.stop(),l.code===2){let u=(l.stderr||l.message||"").toString().trim();return u.includes("No such file or directory")?`ERROR: Directory not found: ${o}`:u.includes("Invalid")||u.includes("Unmatched")||u.includes("unterminated")||u.includes("unclosed")||u.includes("parse error")||u.includes("brackets")||u.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${u.slice(0,200)||"exit code 2"}`}return"(no matches)"+wc(e.path)}}case"patch_file":{let o=new Pi("patch_file","Preparing patches...");o.start();try{await bc();let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Rt(n)){let v=await ji(e.path);if(v.fixedPath)n=v.fixedPath,console.log(`${de.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),n)}${de.reset}`);else return`ERROR: File not found: ${e.path}${v.message?`
289
- `+v.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";o.update({count:0,total:i.length,detail:`${ie.relative(process.cwd(),n)} ${i.length} patches`,message:"Validating patches"});let a=await ze.readFile(n,"utf-8"),{getActiveModelId:l,getActiveProviderName:u}=ut(),c=xm(l(),u()),d=[],f=!1,h=!1;for(let v=0;v<i.length;v++){o.update({count:v+1,total:i.length,detail:`${ie.relative(process.cwd(),n)} patch ${v+1}/${i.length}`,message:"Matching patches"});let{old_text:A,new_text:E}=i[v];if(a.includes(A))d.push({old_text:A,new_text:E});else if(c==="strict"){let S=Jo(a,A);return S?`ERROR: Patch ${v+1} old_text not found in ${n} (strict mode \u2014 exact match required)
281
+ ${P}
282
+
283
+ Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${ne}`}let x=(e.old_text||"").trim().split(`
284
+ `)[0].slice(0,60),E=x?`
285
+ Recovery: grep -n "${x.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
286
+ 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 ${s}${E}`}}if(!n.autoConfirm){o.update({message:"Previewing edit",detail:`${ie.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
287
+ `)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await Xo(s,d);if(Ii(s,i,d,{annotations:f}),!await Ko(l?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let c=i.split(a).join(e.new_text);return o.update({message:"Applying edit",detail:`${ie.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
288
+ `)[0].slice(0,40)}`}),await Je.writeFile(s,c,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||c.startsWith("#!"))&&(o.update({message:"Chmod",detail:ie.relative(process.cwd(),s)}),await Je.chmod(s,493)),Di("edit_file",s,i,c),l?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}finally{o.stop()}}case"list_directory":{let o=lt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ct(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),c=lt(u),d=await Ct(c);if(c&&d)o=c;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],l=async(u,c,d)=>{if(c>r)return;let f;try{f=await Je.readdir(u,{withFileTypes:!0})}catch{return}f=f.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of f){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let m=h.isDirectory()?"/":"";a.push(`${d}${h.name}${m}`),h.isDirectory()&&await l(ie.join(u,h.name),c+1,d+" ")}};return await l(o,1,""),a.join(`
289
+ `)||"(empty)"}case"search_files":{let o=lt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=["-rn","-H"];e.file_pattern&&s.push(`--include=${e.file_pattern}`),s.push(e.pattern,o);try{let{stdout:r}=await ls("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=Vo(r).slice(0,50);return(await Ec(i,{query:e.pattern,basePath:o})).join(`
290
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?lt(e.path):s,i=e.pattern,a=S=>{let P=S.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${P}$`)},l=a(i),u=i.split("/").pop(),c=a(u),{ToolProgress:d}=zn(),f=new d("glob","Finding files...");f.start();let h=Wm();bv(r)||(await $v(r),h=Wm());let m=h.filter(S=>l.test(S)||c.test(ie.basename(S))).map(S=>ie.join(r,S));if(m.length===0)return f.stop(),"(no matches)"+vc(e.path);let g=await Promise.all(m.slice(0,210).map(async S=>{try{let P=await Je.stat(S);return{path:S,mtime:P.mtimeMs}}catch{return{path:S,mtime:0}}})),$=new Map(g.map(S=>[S.path,S.mtime])),x=await Zm(i,r),E=Qm(g.map(S=>S.path),{query:i,basePath:r,definitionScores:x,mtimeByPath:$}),N=m.length>200,v=E.slice(0,200).join(`
291
+ `);return f.update({count:m.length,detail:e.pattern}),f.stop(),N?`${v}
292
+
293
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:v}case"grep":{let o=e.path?lt(e.path):process.cwd();if(e.staged){let{getDiff:l}=ri(),u=await l(!0);if(!u.trim())return"(no staged changes)";let c=new Set,d=u.split(`
294
+ `);for(let $ of d)if($.startsWith("diff --git")){let x=$.match(/diff --git a\/(.+) b\/(.+)/);x&&c.add(x[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:h}=zn(),m=new h("grep","Searching staged content...");m.start();let g=[];for(let $ of c)try{let x=ie.join(process.cwd(),$);if(await Ct(x)){let E=[...f];E.push(e.pattern,x);let{stdout:N}=await ls("grep",E,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let v=Vo(N,e.output_mode);g=g.concat(v)}else g=g.concat(Vo(N))}}catch{}return g=await Ec(g,{query:e.pattern,basePath:process.cwd(),outputMode:e.output_mode}),m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
295
+ `).trim()||"(no matches in staged files)"}let s=["-rn","-E","-H"];e.ignore_case&&s.push("-i"),e.include&&s.push(`--include=${e.include}`),e.type&&s.push(`--include=*.${e.type}`);let r=20;e.context?s.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&s.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&s.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?s.push("-l"):e.output_mode==="count"&&s.push("-c"),s.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),s.push(e.pattern,o);let{ToolProgress:i}=zn(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await ls("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),u;e.output_mode==="files_with_matches"||e.output_mode==="count"?u=Vo(l,e.output_mode):u=Vo(l);let c=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return u=await Ec(u,{query:e.pattern,basePath:o,outputMode:e.output_mode}),u=u.slice(c,c+d),a.update({count:u.length,detail:`in ${o}`}),a.stop(),u.join(`
296
+ `).trim()||"(no matches)"+vc(e.path)}catch(l){if(a.stop(),l.code===2){let u=(l.stderr||l.message||"").toString().trim();return u.includes("No such file or directory")?`ERROR: Directory not found: ${o}`:u.includes("Invalid")||u.includes("Unmatched")||u.includes("unterminated")||u.includes("unclosed")||u.includes("parse error")||u.includes("brackets")||u.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${u.slice(0,200)||"exit code 2"}`}return"(no matches)"+vc(e.path)}}case"patch_file":{let o=new ji("patch_file","Preparing patches...");o.start();try{await Tc();let s=lt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ct(s)){let E=await Fi(e.path);if(E.fixedPath)s=E.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),s)}${fe.reset}`);else return`ERROR: File not found: ${e.path}${E.message?`
297
+ `+E.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";o.update({count:0,total:i.length,detail:`${ie.relative(process.cwd(),s)} ${i.length} patches`,message:"Validating patches"});let a=await Je.readFile(s,"utf-8"),{getActiveModelId:l,getActiveProviderName:u}=dt(),c=Gm(l(),u()),d=[],f=!1,h=!1;for(let E=0;E<i.length;E++){o.update({count:E+1,total:i.length,detail:`${ie.relative(process.cwd(),s)} patch ${E+1}/${i.length}`,message:"Matching patches"});let{old_text:N,new_text:v}=i[E];if(a.includes(N))d.push({old_text:N,new_text:v});else if(c==="strict"){let S=Qo(a,N);return S?`ERROR: Patch ${E+1} old_text not found in ${s} (strict mode \u2014 exact match required)
290
298
  Most similar text (line ${S.line}, distance ${S.distance}):
291
- ${S.text}`:`ERROR: Patch ${v+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let S=$m(a,A);if(S)d.push({old_text:S,new_text:E}),f=!0;else{let N=Jo(a,A);if(N){let ee=Math.max(3,Math.ceil(A.length*.05));if(N.distance<=ee)d.push({old_text:N.text,new_text:E}),h=!0;else return`ERROR: Patch ${v+1} old_text not found in ${n}
292
- Most similar text (line ${N.line}, distance ${N.distance}):
293
- ${N.text}`}else return`ERROR: Patch ${v+1} old_text not found in ${n}`}}}let m=a;for(let{old_text:v,new_text:A}of d)m=m.split(v).join(A);if(!s.autoConfirm){o.update({message:"Previewing patch set",count:d.length,total:i.length,detail:`${ie.relative(process.cwd(),n)} ${d.length} matched`});let v=await zo(n,m);if(Mi(n,a,m,{annotations:v}),!await Yo(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}o.update({message:"Applying patches",count:d.length,total:i.length,detail:`${ie.relative(process.cwd(),n)} ${d.length} matched`}),await ze.writeFile(n,m,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||m.startsWith("#!");g&&(o.update({message:"Chmod",detail:ie.relative(process.cwd(),n)}),await ze.chmod(n,493)),Li("patch_file",n,a,m);let $=h?" (auto-fixed)":f?" (fuzzy match)":"",k=g?" [chmod +x applied]":"";return`Patched: ${n} (${i.length} replacements)${$}${k}`}finally{o.stop()}}case"web_fetch":{let o=e.url,n=e.max_length||1e4;try{let i=new URL(o).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 gc.get(o,{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,n)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${o}: ${r.message}`}}case"web_search":{let o=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let n=await gc.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=n.data?.choices?.[0]?.message?.content||"",i=n.data?.citations||[],a=`[Perplexity grounded search]
299
+ ${S.text}`:`ERROR: Patch ${E+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let S=Um(a,N);if(S)d.push({old_text:S,new_text:v}),f=!0;else{let P=Qo(a,N);if(P){let ne=Math.max(3,Math.ceil(N.length*.05));if(P.distance<=ne)d.push({old_text:P.text,new_text:v}),h=!0;else return`ERROR: Patch ${E+1} old_text not found in ${s}
300
+ Most similar text (line ${P.line}, distance ${P.distance}):
301
+ ${P.text}`}else return`ERROR: Patch ${E+1} old_text not found in ${s}`}}}let m=a;for(let{old_text:E,new_text:N}of d)m=m.split(E).join(N);if(!n.autoConfirm){o.update({message:"Previewing patch set",count:d.length,total:i.length,detail:`${ie.relative(process.cwd(),s)} ${d.length} matched`});let E=await Xo(s,m);if(Ii(s,a,m,{annotations:E}),!await Ko(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}o.update({message:"Applying patches",count:d.length,total:i.length,detail:`${ie.relative(process.cwd(),s)} ${d.length} matched`}),await Je.writeFile(s,m,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||m.startsWith("#!");g&&(o.update({message:"Chmod",detail:ie.relative(process.cwd(),s)}),await Je.chmod(s,493)),Di("patch_file",s,a,m);let $=h?" (auto-fixed)":f?" (fuzzy match)":"",x=g?" [chmod +x applied]":"";return`Patched: ${s} (${i.length} replacements)${$}${x}`}finally{o.stop()}}case"web_fetch":{let o=e.url,s=e.max_length||1e4;try{let i=new URL(o).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 kc.get(o,{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,s)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${o}: ${r.message}`}}case"web_search":{let o=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let s=await kc.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=s.data?.choices?.[0]?.message?.content||"",i=s.data?.citations||[],a=`[Perplexity grounded search]
294
302
 
295
303
  ${r}`;return i.length>0&&(a+=`
296
304
 
297
305
  Sources:
298
306
  `+i.slice(0,o).map((l,u)=>`${u+1}. ${l}`).join(`
299
- `)),a}catch(n){console.error(`${de.dim} Perplexity search failed (${n.message}), falling back to DuckDuckGo${de.reset}`)}try{let r=(await gc.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<o;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],c=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:c,url:decodeURIComponent(u)})}catch{i.push({title:c,url:u})}}return i.length===0?"(no results)":i.map((u,c)=>`${c+1}. ${u.title}
307
+ `)),a}catch(s){console.error(`${fe.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${fe.reset}`)}try{let r=(await kc.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<o;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],c=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:c,url:decodeURIComponent(u)})}catch{i.push({title:c,url:u})}}return i.length===0?"(no results)":i.map((u,c)=>`${c+1}. ${u.title}
300
308
  ${u.url}`).join(`
301
309
 
302
- `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=wn();try{let n=await o(e.url,{waitFor:e.wait_for}),r=n.links.length>0?`
310
+ `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=xn();try{let s=await o(e.url,{waitFor:e.wait_for}),r=s.links.length>0?`
303
311
 
304
312
  Links:
305
- `+n.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
306
- `):"";return`Title: ${n.title}
307
- URL: ${n.url}
308
-
309
- ${n.text}${r}`}catch(n){return`ERROR: ${n.message}`}}case"browser_screenshot":{let{browserScreenshot:o}=wn();try{let n=await o(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${n.path}
310
- Title: ${n.title}
311
- URL: ${n.url}
312
-
313
- To analyze visually, paste the path into your next message: ${n.path}`}catch(n){return`ERROR: ${n.message}`}}case"visual_review":{let{browserScreenshot:o}=wn();try{let n=await o(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
314
- URL: ${n.url}
315
- Title: ${n.title}
316
- Screenshot: ${n.path}
313
+ `+s.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
314
+ `):"";return`Title: ${s.title}
315
+ URL: ${s.url}
316
+
317
+ ${s.text}${r}`}catch(s){return`ERROR: ${s.message}`}}case"browser_screenshot":{let{browserScreenshot:o}=xn();try{let s=await o(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${s.path}
318
+ Title: ${s.title}
319
+ URL: ${s.url}
320
+
321
+ To analyze visually, paste the path into your next message: ${s.path}`}catch(s){return`ERROR: ${s.message}`}}case"visual_review":{let{browserScreenshot:o}=xn();try{let s=await o(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
322
+ URL: ${s.url}
323
+ Title: ${s.title}
324
+ Screenshot: ${s.path}
317
325
  Viewport: ${e.width||1280}\xD7${e.height||800}${e.full_page?" (full page)":""}
318
326
 
319
327
  Focus area: ${r}
@@ -325,46 +333,46 @@ Analyze the screenshot above and provide structured feedback:
325
333
  2. Visual hierarchy (typography, contrast, colors)
326
334
  3. Consistency (margins, padding patterns)
327
335
  4. Responsiveness concerns at this viewport
328
- 5. Specific issues related to: ${r}`;return e.compare_with&&Xt.existsSync(e.compare_with)&&(i+=`
336
+ 5. Specific issues related to: ${r}`;return e.compare_with&&Jt.existsSync(e.compare_with)&&(i+=`
329
337
 
330
- COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:n.path,base64:n.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(n){return`ERROR: ${n.message}`}}case"clipboard_image":try{let{_grabClipboardImage:o}=Sc(),n=o();return n?{text:`Clipboard image captured: ${n.path}
331
- Size: ${Math.round(Buffer.from(n.data,"base64").length/1024)} KB
338
+ COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:s.path,base64:s.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(s){return`ERROR: ${s.message}`}}case"clipboard_image":try{let{_grabClipboardImage:o}=Oc(),s=o();return s?{text:`Clipboard image captured: ${s.path}
339
+ Size: ${Math.round(Buffer.from(s.data,"base64").length/1024)} KB
332
340
 
333
- [Clipboard image is attached for visual analysis]`,images:[{path:n.path,base64:n.data,media_type:n.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(o){return`ERROR: ${o.message}`}case"browser_click":{let{browserClick:o}=wn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(n){return`ERROR: ${n.message}`}}case"browser_fill":{let{browserFill:o}=wn();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(n){return`ERROR: ${n.message}`}}case"visual_diff":try{let{pixelDiff:o}=Zn(),n=o(e.before,e.after,{threshold:e.threshold}),r=n.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
334
- `):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${n.diffPercent}% of pixels changed
335
- Changed: ${n.changedPixels.toLocaleString()} / ${n.totalPixels.toLocaleString()} pixels
336
- Canvas: ${n.width}\xD7${n.height}
337
- Diff image: ${n.diffPath}
341
+ [Clipboard image is attached for visual analysis]`,images:[{path:s.path,base64:s.data,media_type:s.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(o){return`ERROR: ${o.message}`}case"browser_click":{let{browserClick:o}=xn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:o}=xn();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(s){return`ERROR: ${s.message}`}}case"visual_diff":try{let{pixelDiff:o}=Qn(),s=o(e.before,e.after,{threshold:e.threshold}),r=s.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
342
+ `):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${s.diffPercent}% of pixels changed
343
+ Changed: ${s.changedPixels.toLocaleString()} / ${s.totalPixels.toLocaleString()} pixels
344
+ Canvas: ${s.width}\xD7${s.height}
345
+ Diff image: ${s.diffPath}
338
346
 
339
347
  Regional breakdown:
340
348
  ${i}
341
349
 
342
- [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:n.diffPath,base64:Xt.readFileSync(n.diffPath).toString("base64"),media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"responsive_sweep":try{let{responsiveSweep:o}=Zn(),n=await o(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=n.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
343
- `);return{text:`RESPONSIVE SWEEP \u2014 ${n.length} viewports captured
350
+ [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:s.diffPath,base64:Jt.readFileSync(s.diffPath).toString("base64"),media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"responsive_sweep":try{let{responsiveSweep:o}=Qn(),s=await o(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=s.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
351
+ `);return{text:`RESPONSIVE SWEEP \u2014 ${s.length} viewports captured
344
352
  URL: ${e.url}
345
353
 
346
354
  Screenshots:
347
355
  ${r}
348
356
 
349
- [All ${n.length} screenshots attached for breakpoint analysis]
357
+ [All ${s.length} screenshots attached for breakpoint analysis]
350
358
 
351
359
  Analyze these screenshots for:
352
360
  1. Layout breakpoint issues (overflow, collapse, stacking)
353
361
  2. Typography scaling (text too small on mobile, too large on desktop)
354
362
  3. Navigation pattern changes across viewports
355
363
  4. Image/media sizing and aspect ratio issues
356
- 5. Touch target sizes on mobile viewports`,images:n.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(o){return`ERROR: ${o.message}`}case"visual_annotate":try{let{annotateImage:o}=Zn(),n=o(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})
364
+ 5. Touch target sizes on mobile viewports`,images:s.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(o){return`ERROR: ${o.message}`}case"visual_annotate":try{let{annotateImage:o}=Qn(),s=o(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})
357
365
  Source: ${e.image}
358
- Output: ${n.path}
366
+ Output: ${s.path}
359
367
 
360
- [Annotated image attached with visual markers]`,images:[{path:n.path,base64:n.base64,media_type:n.media_type}]}}catch(o){return`ERROR: ${o.message}`}case"visual_watch":try{let{visualWatch:o}=Zn(),n=o(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await n.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 n.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(c=>`${c.name}:${c.changedPercent}%`).join(", ")}`);let u=[{path:l.path,base64:l.base64,media_type:l.media_type}];return l.diff?.diffPath&&u.push({path:l.diff.diffPath,base64:Xt.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
368
+ [Annotated image attached with visual markers]`,images:[{path:s.path,base64:s.base64,media_type:s.media_type}]}}catch(o){return`ERROR: ${o.message}`}case"visual_watch":try{let{visualWatch:o}=Qn(),s=o(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await s.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 s.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(c=>`${c.name}:${c.changedPercent}%`).join(", ")}`);let u=[{path:l.path,base64:l.base64,media_type:l.media_type}];return l.diff?.diffPath&&u.push({path:l.diff.diffPath,base64:Jt.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
361
369
  `),images:u}}return{text:i.join(`
362
370
  `)+`
363
371
 
364
- No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(o){return`ERROR: ${o.message}`}case"design_tokens":try{let{extractDesignTokens:o}=Zn(),n=o(e.image,{sampleRate:e.sample_rate}),r=n.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
365
- `),i=n.spacing.length?n.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
366
- `):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${n.dimensions.width}\xD7${n.dimensions.height} image
367
- Source: ${n.imagePath}
372
+ No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(o){return`ERROR: ${o.message}`}case"design_tokens":try{let{extractDesignTokens:o}=Qn(),s=o(e.image,{sampleRate:e.sample_rate}),r=s.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
373
+ `),i=s.spacing.length?s.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
374
+ `):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${s.dimensions.width}\xD7${s.dimensions.height} image
375
+ Source: ${s.imagePath}
368
376
 
369
377
  Dominant Colors:
370
378
  ${r}
@@ -375,101 +383,101 @@ ${i}
375
383
  Use these values to:
376
384
  - Compare against CSS variables / design system tokens
377
385
  - Identify inconsistent colors or spacing
378
- - Generate a color palette from the rendered output`}catch(o){return`ERROR: ${o.message}`}case"design_compare":try{let{designCompare:o}=Zn(),n=await o(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=n.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
379
- `)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${n.diffPercent}% deviation from reference
380
- Reference: ${n.referencePath}
381
- Live: ${n.livePath}
382
- Diff: ${n.diffPath}
383
- Annotated: ${n.annotatedPath}
386
+ - Generate a color palette from the rendered output`}catch(o){return`ERROR: ${o.message}`}case"design_compare":try{let{designCompare:o}=Qn(),s=await o(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=s.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
387
+ `)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${s.diffPercent}% deviation from reference
388
+ Reference: ${s.referencePath}
389
+ Live: ${s.livePath}
390
+ Diff: ${s.diffPath}
391
+ Annotated: ${s.annotatedPath}
384
392
 
385
- Pixel deviation: ${n.changedPixels.toLocaleString()} / ${n.totalPixels.toLocaleString()}
393
+ Pixel deviation: ${s.changedPixels.toLocaleString()} / ${s.totalPixels.toLocaleString()}
386
394
 
387
395
  Regional breakdown:
388
396
  ${r}
389
397
 
390
- [Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:n.livePath,base64:n.liveBase64,media_type:"image/png"},{path:n.diffPath,base64:n.diffBase64,media_type:"image/png"},{path:n.annotatedPath,base64:n.annotatedBase64,media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"ask_user":{let{question:o,options:n=[]}=e;return xc?new Promise(r=>{ls=()=>r("CANCELLED"),xc(o,n).then(i=>{ls=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});ls=()=>{i.close(),r("CANCELLED")};let a=n.length>0?`
391
- ${n.map((l,u)=>` ${u+1}. ${l}`).join(`
398
+ [Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:s.livePath,base64:s.liveBase64,media_type:"image/png"},{path:s.diffPath,base64:s.diffBase64,media_type:"image/png"},{path:s.annotatedPath,base64:s.annotatedBase64,media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"ask_user":{let{question:o,options:s=[]}=e;return Ac?new Promise(r=>{cs=()=>r("CANCELLED"),Ac(o,s).then(i=>{cs=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});cs=()=>{i.close(),r("CANCELLED")};let a=s.length>0?`
399
+ ${s.map((l,u)=>` ${u+1}. ${l}`).join(`
392
400
  `)}
393
401
  `:"";console.log(`
394
- ${de.cyan}${de.bold} ? ${o}${de.reset}${a}`),i.question(`${de.cyan} > ${de.reset}`,l=>{ls=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await yc())return"ERROR: Not a git repository";let o=await wm()||"(detached)",n=await OS();if(n.length===0)return`Branch: ${o}
395
- Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${n.length}):`];for(let i of n){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(`
396
- `)}case"git_diff":{if(!await yc())return"ERROR: Not a git repository";let o;if(e.file){let n=["diff"];e.staged&&n.push("--cached"),n.push("--",e.file);try{o=execFileSync("git",n,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await NS(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await yc())return"ERROR: Not a git repository";let n=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&n.push("--",e.file);try{return execFileSync("git",n,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:o,updateTask:n,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=ec(),{getActiveTaskProgress:l}=ot(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let c=o(e.name,e.tasks);return u||console.log(`
402
+ ${fe.cyan}${fe.bold} ? ${o}${fe.reset}${a}`),i.question(`${fe.cyan} > ${fe.reset}`,l=>{cs=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Sc())return"ERROR: Not a git repository";let o=await Bm()||"(detached)",s=await mv();if(s.length===0)return`Branch: ${o}
403
+ Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${s.length}):`];for(let i of s){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(`
404
+ `)}case"git_diff":{if(!await Sc())return"ERROR: Not a git repository";let o;if(e.file){let s=["diff"];e.staged&&s.push("--cached"),s.push("--",e.file);try{o=execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await gv(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await Sc())return"ERROR: Not a git repository";let s=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&s.push("--",e.file);try{return execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:o,updateTask:s,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=ac(),{getActiveTaskProgress:l}=it(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let c=o(e.name,e.tasks);return u||console.log(`
397
405
  `+i()),`Created task list "${e.name}" with ${c.length} tasks:
398
406
  `+c.map(d=>` ${d.id}: ${d.description}`).join(`
399
- `)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":n(e.task_id,e.status,e.result)?(u||console.log(`
407
+ `)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":s(e.task_id,e.status,e.result)?(u||console.log(`
400
408
  `+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let c=r();return c.tasks.length===0?"No active tasks":(u||console.log(`
401
- `+i()),JSON.stringify(c,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o,executeSpawnAgentsBackground:n}=Di();return e.agents?.some(r=>r.background)?n(e):o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:n,getActiveModelId:r}=ut();return o(e.model)?`Switched to ${n()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let o=Math.min(e.limit||10,30),n=["run","list","--limit",String(o),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&n.push("--workflow",e.workflow),e.branch&&n.push("--branch",e.branch),e.status&&n.push("--status",e.status);try{let{stdout:r}=await as("gh",n,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let u=l.conclusion||l.status||"unknown",c=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",d=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${c} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${d}`}).join(`
409
+ `+i()),JSON.stringify(c,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o,executeSpawnAgentsBackground:s}=Bi();return e.agents?.some(r=>r.background)?s(e):o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:s,getActiveModelId:r}=dt();return o(e.model)?`Switched to ${s()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let o=Math.min(e.limit||10,30),s=["run","list","--limit",String(o),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&s.push("--workflow",e.workflow),e.branch&&s.push("--branch",e.branch),e.status&&s.push("--status",e.status);try{let{stdout:r}=await ls("gh",s,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let u=l.conclusion||l.status||"unknown",c=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",d=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${c} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${d}`}).join(`
402
410
  `)}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(`
403
- `)[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 as("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
404
- ...(truncated)`:"")}let{stdout:o}=await as("gh",["run","view",String(e.run_id),"--json","status,conclusion,name,headBranch,createdAt,updatedAt,jobs"],{cwd:process.cwd(),timeout:3e4}),n=JSON.parse(o),r=[`Run: ${n.name} [${e.run_id}]`,`Branch: ${n.headBranch} Status: ${n.conclusion||n.status}`,`Started: ${n.createdAt} Finished: ${n.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of n.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 u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
411
+ `)[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 ls("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
412
+ ...(truncated)`:"")}let{stdout:o}=await ls("gh",["run","view",String(e.run_id),"--json","status,conclusion,name,headBranch,createdAt,updatedAt,jobs"],{cwd:process.cwd(),timeout:3e4}),s=JSON.parse(o),r=[`Run: ${s.name} [${e.run_id}]`,`Branch: ${s.headBranch} Status: ${s.conclusion||s.status}`,`Started: ${s.createdAt} Finished: ${s.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of s.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 u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
405
413
  `)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
406
- `)[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:o}=xo(),n=e.branch||await wm()||"main";if(!/^[\w./-]+$/.test(n))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",n];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(`
407
- ${de.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${n}${de.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await as("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${n}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
408
- `)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",n=e.label?`-l ${e.label}`:"",r=Vo(`get pods ${o} ${n} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await Ue(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
409
- `)[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 o=e.namespace||"default",n=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${n}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Vo(r,e);try{let{stdout:a,stderr:l}=await Ue(i,{timeout:6e4,maxBuffer:5242880}),u=(a||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
414
+ `)[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:o}=vo(),s=e.branch||await Bm()||"main";if(!/^[\w./-]+$/.test(s))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",s];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(`
415
+ ${fe.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${fe.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ls("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${s}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
416
+ `)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=Zo(`get pods ${o} ${s} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await He(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
417
+ `)[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 o=e.namespace||"default",s=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${s}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Zo(r,e);try{let{stdout:a,stderr:l}=await He(i,{timeout:6e4,maxBuffer:5242880}),u=(a||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
410
418
  ...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
411
419
  `)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let o=e.namespace||"default";if(console.log(`
412
- ${de.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${de.reset}`),console.log(`${de.dim} Command: ${e.command}${de.reset}`),!await Kt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${o}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Vo(r,e);try{let{stdout:a,stderr:l}=await Ue(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
420
+ ${fe.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${fe.reset}`),console.log(`${fe.dim} Command: ${e.command}${fe.reset}`),!await Vt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${o}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Zo(r,e);try{let{stdout:a,stderr:l}=await He(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
413
421
  `)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let o=!!e.dry_run;if(!o){let i=e.file;if(console.log(`
414
- ${de.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${de.reset}`),!await Kt(" Apply to cluster?"))return"CANCELLED: User declined."}let n=`apply -f ${e.file}`;e.namespace&&(n+=` -n ${e.namespace}`),o&&(n+=" --dry-run=client");let r=Vo(n,e);try{let{stdout:i,stderr:a}=await Ue(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
422
+ ${fe.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${fe.reset}`),!await Vt(" Apply to cluster?"))return"CANCELLED: User declined."}let s=`apply -f ${e.file}`;e.namespace&&(s+=` -n ${e.namespace}`),o&&(s+=" --dry-run=client");let r=Zo(s,e);try{let{stdout:i,stderr:a}=await He(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
415
423
  `)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let o=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let a=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
416
- ${de.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${de.reset}`),!await Kt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=Vo(r,e);try{let{stdout:a,stderr:l}=await Ue(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
417
- `)[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:o,readDocument:n}=fc(),{name:r,content:i,mode:a}=e;if(a==="create"&&n(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let l=n(r),u=l.content?l.content+`
424
+ ${fe.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${fe.reset}`),!await Vt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=Zo(r,e);try{let{stdout:a,stderr:l}=await He(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
425
+ `)[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:o,readDocument:s}=$c(),{name:r,content:i,mode:a}=e;if(a==="create"&&s(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let l=s(r),u=l.content?l.content+`
418
426
 
419
- `+i:i;return o(r,u),`Appended to brain document: ${r}.md`}return o(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 o;try{o=jt(e.server)}catch(N){return`ERROR: ${N.message}`}let n=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=vS(n);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(n)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
427
+ `+i:i;return o(r,u),`Appended to brain document: ${r}.md`}return o(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 o;try{o=Dt(e.server)}catch(P){return`ERROR: ${P.message}`}let s=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=cv(s);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(s)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
420
428
  grep -n "pattern" /path/to/file -A 50
421
429
  or to read the whole file:
422
430
  cat /path/to/file
423
431
  NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
424
- 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(n=n.replace(/(-[BAC])\s*(\d+)/g,(N,ee,re)=>{let le=Math.min(Number(re),20);return`${ee} ${le}`}),n=n.replace(/(--(?:before|after|context)=)(\d+)/g,(N,ee,re)=>ee+Math.min(Number(re),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(n)){let N=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
425
- ${de.yellow} \u26A0 Remote command on ${N}: ${n}${de.reset}`),!await Kt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:u,stderr:c,exitCode:d,error:f}=await yt(o,n,{timeout:i,sudo:r}),h=[u,c].filter(Boolean).join(`
426
- `).trim();if(d!==0){if(/no such file or directory/i.test(h)){let ee=h.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),re=n.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),le=ee&&ee[1]||re&&re[1];if(le)try{let{remoteAutoFixPath:ue}=Ds(),oe=le.startsWith("/")?le.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(o.user||"root"),ae=await ue(o,oe,le);if(ae.fixedPath){let T=n.replace(le,ae.fixedPath);console.log(`${de.dim} \u2713 remote auto-fix: ${le} \u2192 ${ae.fixedPath}${de.reset}`);let U=await yt(o,T,{timeout:i,sudo:r}),Z=[U.stdout,U.stderr].filter(Boolean).join(`
427
- `).trim();if(U.exitCode===0)return`${ae.message}
428
- ${Z}`||"(command completed, no output)"}else if(ae.message)return`EXIT ${d}
432
+ 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(s=s.replace(/(-[BAC])\s*(\d+)/g,(P,ne,re)=>{let ce=Math.min(Number(re),20);return`${ne} ${ce}`}),s=s.replace(/(--(?:before|after|context)=)(\d+)/g,(P,ne,re)=>ne+Math.min(Number(re),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(s)){let P=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
433
+ ${fe.yellow} \u26A0 Remote command on ${P}: ${s}${fe.reset}`),!await Vt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:u,stderr:c,exitCode:d,error:f}=await wt(o,s,{timeout:i,sudo:r}),h=[u,c].filter(Boolean).join(`
434
+ `).trim();if(d!==0){if(/no such file or directory/i.test(h)){let ne=h.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),re=s.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),ce=ne&&ne[1]||re&&re[1];if(ce)try{let{remoteAutoFixPath:de}=Ws(),oe=ce.startsWith("/")?ce.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(o.user||"root"),le=await de(o,oe,ce);if(le.fixedPath){let T=s.replace(ce,le.fixedPath);console.log(`${fe.dim} \u2713 remote auto-fix: ${ce} \u2192 ${le.fixedPath}${fe.reset}`);let q=await wt(o,T,{timeout:i,sudo:r}),Q=[q.stdout,q.stderr].filter(Boolean).join(`
435
+ `).trim();if(q.exitCode===0)return`${le.message}
436
+ ${Q}`||"(command completed, no output)"}else if(le.message)return`EXIT ${d}
429
437
  ${f||h}
430
438
 
431
- ${ae.message}`}catch{}}return`EXIT ${d}
432
- ${f||h||"(no output)"}`}let m=/\bgrep\b/.test(n),g=h;m&&(g=g.split(`
433
- `).filter(N=>N!=="--").join(`
434
- `));let $=m?60:100,k=g.split(`
435
- `);k.length>$&&(g=`(${k.length-$} earlier lines omitted \u2014 showing last ${$})
436
- `+k.slice(-$).join(`
437
- `));let v=4,A=g.split(`
438
- `),E=[],S=0;for(;S<A.length;){let N=S+1;for(;N<A.length&&A[N]===A[S];)N++;let ee=N-S;if(E.push(A[S]),ee>v)E.push(`... (${ee-1} identical lines omitted)`);else for(let re=1;re<ee;re++)E.push(A[S]);S=N}return E.join(`
439
- `)||"(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 o;try{o=jt(e.server)}catch(i){return`ERROR: ${i.message}`}let n=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
440
- ${de.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${n}:${e.remote_path}${de.reset}`),!await Kt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await jS(o,e.local_path,e.remote_path);try{Ds().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 o;try{o=jt(e.server)}catch(n){return`ERROR: ${n.message}`}try{return await km(o,e.remote_path,e.local_path)}catch(n){if(/no such file|not found/i.test(n.message))try{let{remoteAutoFixPath:r}=Ds(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(o,i,e.remote_path);if(a.fixedPath){console.log(`${de.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${de.reset}`);let l=await km(o,a.fixedPath,e.local_path);return`${a.message}
441
- ${l}`}if(a.message)return`ERROR: ${n.message}
442
-
443
- ${a.message}`}catch{}return`ERROR: ${n.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),n=null;try{n=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=n?`${n.user||"root"}@${n.host}`:e.server,i=n?.key?["-i",n.key]:[],a=(e.project_path||n?.home||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),l=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),c=['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 '${c}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let h=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
444
- ${h.slice(-2e3)}`:h.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 o=kc(e.service);if(o)return o;let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.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(c){return`ERROR: ${c.message}`}if(!i){let c=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
445
- ${de.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${c}${de.reset}`),!await Kt(" Execute?"))return"CANCELLED: User declined service action."}let l=e.service.includes(".")?e.service:`${e.service}.service`,u=`systemctl ${e.action} ${Ee(l)}`;if(r){let d=e.action!=="status"?`sudo ${u}`:u;try{let{stdout:f,stderr:h}=await Ue(d,{timeout:15e3});return(f||h||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(f){let h=(f.stderr||f.message||"").toString().trim();return/not found|loaded.*not-found/i.test(h)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${f.code||1}
446
- ${h}`}}else{let{stdout:c,stderr:d,exitCode:f,error:h}=await yt(a,u,{timeout:15e3,sudo:!0}),m=[c,d].filter(Boolean).join(`
439
+ ${le.message}`}catch{}}return`EXIT ${d}
440
+ ${f||h||"(no output)"}`}let m=/\bgrep\b/.test(s),g=h;m&&(g=g.split(`
441
+ `).filter(P=>P!=="--").join(`
442
+ `));let $=m?60:100,x=g.split(`
443
+ `);x.length>$&&(g=`(${x.length-$} earlier lines omitted \u2014 showing last ${$})
444
+ `+x.slice(-$).join(`
445
+ `));let E=4,N=g.split(`
446
+ `),v=[],S=0;for(;S<N.length;){let P=S+1;for(;P<N.length&&N[P]===N[S];)P++;let ne=P-S;if(v.push(N[S]),ne>E)v.push(`... (${ne-1} identical lines omitted)`);else for(let re=1;re<ne;re++)v.push(N[S]);S=P}return v.join(`
447
+ `)||"(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 o;try{o=Dt(e.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
448
+ ${fe.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${fe.reset}`),!await Vt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await _v(o,e.local_path,e.remote_path);try{Ws().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 o;try{o=Dt(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await Ym(o,e.remote_path,e.local_path)}catch(s){if(/no such file|not found/i.test(s.message))try{let{remoteAutoFixPath:r}=Ws(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(o,i,e.remote_path);if(a.fixedPath){console.log(`${fe.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${fe.reset}`);let l=await Ym(o,a.fixedPath,e.local_path);return`${a.message}
449
+ ${l}`}if(a.message)return`ERROR: ${s.message}
450
+
451
+ ${a.message}`}catch{}return`ERROR: ${s.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),s=null;try{s=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=s?`${s.user||"root"}@${s.host}`:e.server,i=s?.key?["-i",s.key]:[],a=(e.project_path||s?.home||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),l=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),c=['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 '${c}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let h=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
452
+ ${h.slice(-2e3)}`:h.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 o=Cc(e.service);if(o)return o;let s=["status","start","stop","restart","reload","enable","disable"];if(!s.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${s.join(", ")}`;let r=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",a=null;if(!r)try{a=Dt(e.server)}catch(c){return`ERROR: ${c.message}`}if(!i){let c=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
453
+ ${fe.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${c}${fe.reset}`),!await Vt(" Execute?"))return"CANCELLED: User declined service action."}let l=e.service.includes(".")?e.service:`${e.service}.service`,u=`systemctl ${e.action} ${Ce(l)}`;if(r){let d=e.action!=="status"?`sudo ${u}`:u;try{let{stdout:f,stderr:h}=await He(d,{timeout:15e3});return(f||h||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(f){let h=(f.stderr||f.message||"").toString().trim();return/not found|loaded.*not-found/i.test(h)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${f.code||1}
454
+ ${h}`}}else{let{stdout:c,stderr:d,exitCode:f,error:h}=await wt(a,u,{timeout:15e3,sudo:!0}),m=[c,d].filter(Boolean).join(`
447
455
  `).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}
448
- ${h||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=kc(e.service);if(o)return o;let n=!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 ${Ee(e.since)}`:"",l=e.follow?"-f":"",u=`journalctl -u ${Ee(i)} -n ${r} ${a} ${l} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:$,stderr:k}=await Ue(u,{timeout:15e3});return($||k||"(no log output)").trim()}catch($){return`EXIT ${$.code||1}
449
- ${($.stderr||$.message||"").toString().trim()}`}let c;try{c=jt(e.server)}catch($){return`ERROR: ${$.message}`}let{stdout:d,stderr:f,exitCode:h,error:m}=await yt(c,u,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
456
+ ${h||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=Cc(e.service);if(o)return o;let s=!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 ${Ce(e.since)}`:"",l=e.follow?"-f":"",u=`journalctl -u ${Ce(i)} -n ${r} ${a} ${l} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:$,stderr:x}=await He(u,{timeout:15e3});return($||x||"(no log output)").trim()}catch($){return`EXIT ${$.code||1}
457
+ ${($.stderr||$.message||"").toString().trim()}`}let c;try{c=Dt(e.server)}catch($){return`ERROR: ${$.message}`}let{stdout:d,stderr:f,exitCode:h,error:m}=await wt(c,u,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
450
458
  `).trim();return h!==0?`EXIT ${h}
451
- ${m||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let o=!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(o)try{let{stdout:f,stderr:h}=await Ue(r,{timeout:1e4});return(f||h||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
452
- ${(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:u,error:c}=await yt(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
459
+ ${m||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let o=!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(o)try{let{stdout:f,stderr:h}=await He(r,{timeout:1e4});return(f||h||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
460
+ ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=Dt(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:u,error:c}=await wt(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
453
461
  `).trim();return u!==0?`EXIT ${u}
454
- ${c||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${n} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(o)try{let{stdout:h,stderr:m}=await Ue(i,{timeout:15e3});return(h||m||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
455
- ${(h.stderr||h.message||"").toString().trim()}`}let a;try{a=jt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:c,error:d}=await yt(a,i,{timeout:2e4}),f=[l,u].filter(Boolean).join(`
462
+ ${c||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let o=!e.server||e.server==="local"||e.server==="localhost",s=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${s} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(o)try{let{stdout:h,stderr:m}=await He(i,{timeout:15e3});return(h||m||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
463
+ ${(h.stderr||h.message||"").toString().trim()}`}let a;try{a=Dt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:c,error:d}=await wt(a,i,{timeout:2e4}),f=[l,u].filter(Boolean).join(`
456
464
  `).trim();return c!==0?`EXIT ${c}
457
- ${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 o=!e.server||e.server==="local"||e.server==="localhost",n=/^(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&&!n.test(e.command.trim())){let m=o?"local":e.server;if(console.log(`
458
- ${de.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${de.reset}`),!await Kt(" 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(o)try{let{stdout:m,stderr:g}=await Ue(a,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
459
- ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=jt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:c,exitCode:d,error:f}=await yt(l,a,{timeout:35e3}),h=[u,c].filter(Boolean).join(`
465
+ ${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 o=!e.server||e.server==="local"||e.server==="localhost",s=/^(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(!n.autoConfirm&&!s.test(e.command.trim())){let m=o?"local":e.server;if(console.log(`
466
+ ${fe.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${fe.reset}`),!await Vt(" 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(o)try{let{stdout:m,stderr:g}=await He(a,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
467
+ ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Dt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:c,exitCode:d,error:f}=await wt(l,a,{timeout:35e3}),h=[u,c].filter(Boolean).join(`
460
468
  `).trim();return d!==0?`EXIT ${d}
461
- ${f||h}`:h||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let o=["start","stop","restart","remove","inspect"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let n=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let m=n?"local":e.server;if(console.log(`
462
- ${de.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${de.reset}`),!await Kt(" 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(n)try{let{stdout:m,stderr:g}=await Ue(a,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
463
- ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=jt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:c,exitCode:d,error:f}=await yt(l,a,{timeout:35e3}),h=[u,c].filter(Boolean).join(`
469
+ ${f||h}`:h||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let o=["start","stop","restart","remove","inspect"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let s=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!n.autoConfirm){let m=s?"local":e.server;if(console.log(`
470
+ ${fe.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${fe.reset}`),!await Vt(" 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(s)try{let{stdout:m,stderr:g}=await He(a,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
471
+ ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Dt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:c,exitCode:d,error:f}=await wt(l,a,{timeout:35e3}),h=[u,c].filter(Boolean).join(`
464
472
  `).trim();return d!==0?`EXIT ${d}
465
- ${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...DS(e.config),...e},delete e.config,delete e._name}catch(c){return`ERROR: ${c.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let o=e.method||"rsync";if(o==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let n;try{n=jt(e.server)}catch(c){return`ERROR: ${c.message}`}let r=n.user?`${n.user}@${n.host}`:n.host;if(!e.dry_run&&!s.autoConfirm){if(o==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
466
- ${de.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${de.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
467
- ${de.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${de.reset}`)}if(e.deploy_script&&console.log(`${de.yellow} Then run: ${e.deploy_script}${de.reset}`),e.health_check&&console.log(`${de.yellow} Health check: ${e.health_check}${de.reset}`),!await Kt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(o==="git"){let c=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&c!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=c?`cd '${d}' && git fetch origin && git checkout '${c}' && git pull origin '${c}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
473
+ ${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...xv(e.config),...e},delete e.config,delete e._name}catch(c){return`ERROR: ${c.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let o=e.method||"rsync";if(o==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let s;try{s=Dt(e.server)}catch(c){return`ERROR: ${c.message}`}let r=s.user?`${s.user}@${s.host}`:s.host;if(!e.dry_run&&!n.autoConfirm){if(o==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
474
+ ${fe.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${fe.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
475
+ ${fe.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${fe.reset}`)}if(e.deploy_script&&console.log(`${fe.yellow} Then run: ${e.deploy_script}${fe.reset}`),e.health_check&&console.log(`${fe.yellow} Health check: ${e.health_check}${fe.reset}`),!await Vt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(o==="git"){let c=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&c!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=c?`cd '${d}' && git fetch origin && git checkout '${c}' && git pull origin '${c}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
468
476
  ${f}${e.deploy_script?`
469
- ${e.deploy_script}`:""}`;let{stdout:h,stderr:m,exitCode:g,error:$}=await yt(n,f,{timeout:12e4});if(i=[h,m].filter(Boolean).join(`
477
+ ${e.deploy_script}`:""}`;let{stdout:h,stderr:m,exitCode:g,error:$}=await wt(s,f,{timeout:12e4});if(i=[h,m].filter(Boolean).join(`
470
478
  `).trim(),g!==0)return`ERROR (git pull, exit ${g}):
471
- ${$||i}`}else{let c=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}${n.port&&Number(n.port)!==22?` -p ${n.port}`:""}"`:n.port&&Number(n.port)!==22?`-e "ssh -p ${n.port}"`:"",d=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),f=e.dry_run?"--dry-run":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,m=`rsync -avz --delete ${f} ${d} ${c} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:$}=await Ue(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]:
472
- ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:c,stderr:d,exitCode:f,error:h}=await yt(n,e.deploy_script,{timeout:12e4}),m=[c,d].filter(Boolean).join(`
479
+ ${$||i}`}else{let c=s.key?`-e "ssh -i ${s.key.replace(/^~/,require("os").homedir())}${s.port&&Number(s.port)!==22?` -p ${s.port}`:""}"`:s.port&&Number(s.port)!==22?`-e "ssh -p ${s.port}"`:"",d=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),f=e.dry_run?"--dry-run":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,m=`rsync -avz --delete ${f} ${d} ${c} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:$}=await He(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]:
480
+ ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:c,stderr:d,exitCode:f,error:h}=await wt(s,e.deploy_script,{timeout:12e4}),m=[c,d].filter(Boolean).join(`
473
481
  `).trim();if(f!==0)return`${o==="git"?"git pull":"rsync"} OK
474
482
 
475
483
  ERROR (deploy_script, exit ${f}):
@@ -482,69 +490,69 @@ Health check: \u2713 ${c} \u2192 ${h.status}`;else return l=`
482
490
 
483
491
  Health check FAILED: ${c} \u2192 HTTP ${h.status}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l}catch(f){return l=`
484
492
 
485
- Health check FAILED: ${c} \u2192 ${f.message}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l}else{let{stdout:f,stderr:h,exitCode:m}=await yt(n,c,{timeout:15e3}),g=[f,h].filter(Boolean).join(`
493
+ Health check FAILED: ${c} \u2192 ${f.message}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l}else{let{stdout:f,stderr:h,exitCode:m}=await wt(s,c,{timeout:15e3}),g=[f,h].filter(Boolean).join(`
486
494
  `).trim();if(m!==0)return l=`
487
495
 
488
496
  Health check FAILED (exit ${m}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
489
497
 
490
498
  Health check: \u2713 ${g||"(exit 0)"}`}}let u=o==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${o}] ${u}
491
- ${i}${a}${l}`.trim()}case"deployment_status":{let o=qS(),n=e.config?[e.config]:Object.keys(o);if(n.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of n){let a=o[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let l=jt(a.server||i),c=(await yt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(c&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{d=(await yt(l,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let h=a.health_check.trim();if(/^https?:\/\//.test(h))try{let m=require("node-fetch"),g=await Promise.race([m(h),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 yt(l,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${c?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
499
+ ${i}${a}${l}`.trim()}case"deployment_status":{let o=kv(),s=e.config?[e.config]:Object.keys(o);if(s.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of s){let a=o[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let l=Dt(a.server||i),c=(await wt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(c&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{d=(await wt(l,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let h=a.health_check.trim();if(/^https?:\/\//.test(h))try{let m=require("node-fetch"),g=await Promise.race([m(h),new Promise(($,x)=>setTimeout(()=>x(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(m){f=`unhealthy: ${m.message.substring(0,50)}`}else try{f=(await wt(l,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${c?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
492
500
  ${r.join(`
493
- `)}`}case"frontend_recon":{let o=process.cwd(),n=(e.type||"").toLowerCase(),r=[],i=async(E,S=120)=>{try{let N=ie.isAbsolute(E)?E:ie.join(o,E),re=(await ze.readFile(N,"utf8")).split(`
494
- `),le=re.slice(0,S).join(`
495
- `);return re.length>S?le+`
496
- ... (${re.length-S} more lines \u2014 use read_file for full content)`:le}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(E=>`-not -path "*/${E}/*"`).join(" "),u=async E=>{try{let{stdout:S}=await Ue(`find "${o}" -type f -name "${E}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return S.trim().split(`
497
- `).filter(Boolean)}catch{return[]}},c=async(E,S)=>{try{let{stdout:N}=await Ue(`grep -rl "${E}" "${o}" --include="${S}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return N.trim().split(`
501
+ `)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(v,S=120)=>{try{let P=ie.isAbsolute(v)?v:ie.join(o,v),re=(await Je.readFile(P,"utf8")).split(`
502
+ `),ce=re.slice(0,S).join(`
503
+ `);return re.length>S?ce+`
504
+ ... (${re.length-S} more lines \u2014 use read_file for full content)`:ce}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(v=>`-not -path "*/${v}/*"`).join(" "),u=async v=>{try{let{stdout:S}=await He(`find "${o}" -type f -name "${v}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return S.trim().split(`
505
+ `).filter(Boolean)}catch{return[]}},c=async(v,S)=>{try{let{stdout:P}=await He(`grep -rl "${v}" "${o}" --include="${S}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return P.trim().split(`
498
506
  `).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
499
- `);let d=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(d.length>0){let E=await i(d[0],80);E&&r.push(`### Tailwind config (${ie.relative(o,d[0])})
507
+ `);let d=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(d.length>0){let v=await i(d[0],80);v&&r.push(`### Tailwind config (${ie.relative(o,d[0])})
500
508
  \`\`\`js
501
- ${E}
502
- \`\`\``)}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"],h=!1;for(let E of f){let S=await u(E);for(let N of S){let ee=await i(N,100);if(ee&&ee.includes(":root")){r.push(`### CSS Variables (${ie.relative(o,N)})
509
+ ${v}
510
+ \`\`\``)}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"],h=!1;for(let v of f){let S=await u(v);for(let P of S){let ne=await i(P,100);if(ne&&ne.includes(":root")){r.push(`### CSS Variables (${ie.relative(o,P)})
503
511
  \`\`\`css
504
- ${ee}
505
- \`\`\``),h=!0;break}}if(h)break}if(!h){let E=await c(":root","*.css");if(E.length>0){let S=await i(E[0],100);S&&r.push(`### CSS Variables (${ie.relative(o,E[0])})
512
+ ${ne}
513
+ \`\`\``),h=!0;break}}if(h)break}if(!h){let v=await c(":root","*.css");if(v.length>0){let S=await i(v[0],100);S&&r.push(`### CSS Variables (${ie.relative(o,v[0])})
506
514
  \`\`\`css
507
515
  ${S}
508
516
  \`\`\``),h=!0}}h||r.push("(no CSS custom properties / :root found)"),r.push(`
509
517
  ## STEP 2: Main Layout / Index Page
510
- `);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 S=await u(E);if(S.length>0){let N=await i(S[0],150);if(N){r.push(`### Main layout: ${ie.relative(o,S[0])}
518
+ `);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 S=await u(v);if(S.length>0){let P=await i(S[0],150);if(P){r.push(`### Main layout: ${ie.relative(o,S[0])}
511
519
  \`\`\`html
512
- ${N}
520
+ ${P}
513
521
  \`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
514
522
  ## STEP 3: Reference Component (same type)
515
- `);let $=[];if(n){for(let E of["*.html","*.vue","*.jsx","*.tsx"])if($=await c(n,E),$.length>0)break}if($.length===0)try{let{stdout:E}=await Ue(`find "${o}" -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(`
516
- `).filter(Boolean)}catch{$=[]}if($.length>0){let E=$[0],S=await i(E,150);S?r.push(`### Reference: ${ie.relative(o,E)}
523
+ `);let $=[];if(s){for(let v of["*.html","*.vue","*.jsx","*.tsx"])if($=await c(s,v),$.length>0)break}if($.length===0)try{let{stdout:v}=await He(`find "${o}" -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(`
524
+ `).filter(Boolean)}catch{$=[]}if($.length>0){let v=$[0],S=await i(v,150);S?r.push(`### Reference: ${ie.relative(o,v)}
517
525
  \`\`\`html
518
526
  ${S}
519
527
  \`\`\``):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(`
520
528
  ## STEP 4: Framework Stack
521
- `);let k=[],v=await i(ie.join(o,"package.json"),999);if(v){if((v.includes('"react"')||v.includes("'react'"))&&k.push("React"),v.includes('"vue"')||v.includes("'vue'")){let S=v.match(/"vue":\s*"[\^~]?(\d+)/);k.push(S?`Vue.js v${S[1]}`:"Vue.js")}let E=v.match(/"alpinejs":\s*"[\^~]?(\d+)/);E&&k.push(`Alpine.js v${E[1]} (\u26A0 v2 vs v3 API differs!)`),(v.includes('"htmx')||v.includes("'htmx"))&&k.push("HTMX"),v.includes('"tailwindcss"')&&k.push("Tailwind CSS"),v.includes('"bootstrap"')&&k.push("Bootstrap")}if((await Rt(ie.join(o,"manage.py"))||(await i(ie.join(o,"requirements.txt"),50)||"").includes("Django"))&&k.push("Django (server-rendered templates)"),!k.some(E=>E.includes("Alpine"))){let E=await c("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 c("htmx","*.html")).length>0&&k.push("HTMX (via CDN)"),k.length>0?(r.push(k.map(E=>`- ${E}`).join(`
529
+ `);let x=[],E=await i(ie.join(o,"package.json"),999);if(E){if((E.includes('"react"')||E.includes("'react'"))&&x.push("React"),E.includes('"vue"')||E.includes("'vue'")){let S=E.match(/"vue":\s*"[\^~]?(\d+)/);x.push(S?`Vue.js v${S[1]}`:"Vue.js")}let v=E.match(/"alpinejs":\s*"[\^~]?(\d+)/);v&&x.push(`Alpine.js v${v[1]} (\u26A0 v2 vs v3 API differs!)`),(E.includes('"htmx')||E.includes("'htmx"))&&x.push("HTMX"),E.includes('"tailwindcss"')&&x.push("Tailwind CSS"),E.includes('"bootstrap"')&&x.push("Bootstrap")}if((await Ct(ie.join(o,"manage.py"))||(await i(ie.join(o,"requirements.txt"),50)||"").includes("Django"))&&x.push("Django (server-rendered templates)"),!x.some(v=>v.includes("Alpine"))){let v=await c("alpinejs","*.html");if(v.length>0){let P=(await i(v[0],30)||"").match(/alpinejs[@/]v?(\d)/);x.push(P?`Alpine.js v${P[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return x.some(v=>v.includes("HTMX"))||(await c("htmx","*.html")).length>0&&x.push("HTMX (via CDN)"),x.length>0?(r.push(x.map(v=>`- ${v}`).join(`
522
530
  `)),r.push(`
523
531
  \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(`
524
532
  ---
525
533
  \u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
526
- `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",n;if(!o)try{n=jt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,u=3e4)=>{if(o)try{let{stdout:c,stderr:d}=await Ue(l,{timeout:u});return{out:(c||d||"").trim(),exitCode:0}}catch(c){return{out:(c.stderr||c.message||"").toString().trim(),exitCode:c.code||1}}else{let{stdout:c,stderr:d,exitCode:f,error:h}=await yt(n,l,{timeout:u}),m=[c,d].filter(Boolean).join(`
534
+ `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",s;if(!o)try{s=Dt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,u=3e4)=>{if(o)try{let{stdout:c,stderr:d}=await He(l,{timeout:u});return{out:(c||d||"").trim(),exitCode:0}}catch(c){return{out:(c.stderr||c.message||"").toString().trim(),exitCode:c.code||1}}else{let{stdout:c,stderr:d,exitCode:f,error:h}=await wt(s,l,{timeout:u}),m=[c,d].filter(Boolean).join(`
527
535
  `).trim();return{out:h&&f!==0&&!c.trim()?(h+`
528
- `+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=o?"local":e.server;if(!await Kt(`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:u,exitCode:c}=await r(l,45e3);return u||`EXIT ${c}
529
- (no output)`}case"disk_usage":{let l=e.path||"/",u=Ee(l),c=`df -h ${u}; echo '--- Top subdirs ---'; du -d1 -x -h ${u} 2>/dev/null | sort -rh | head -20`,{out:d,exitCode:f}=await r(c,3e4);return f!==0?`EXIT ${f}
536
+ `+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))&&!n.autoConfirm){let l=o?"local":e.server;if(!await Vt(`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:u,exitCode:c}=await r(l,45e3);return u||`EXIT ${c}
537
+ (no output)`}case"disk_usage":{let l=e.path||"/",u=Ce(l),c=`df -h ${u}; echo '--- Top subdirs ---'; du -d1 -x -h ${u} 2>/dev/null | sort -rh | head -20`,{out:d,exitCode:f}=await r(c,3e4);return f!==0?`EXIT ${f}
530
538
  ${d}`:d}case"process_list":{let l=e.sort_by==="mem"?"4":"3",u=(e.limit||20)+1,c=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${u} || ps aux | awk 'NR==1{print; next} {print | "sort -k${l} -rn"}' | head -${u}`,{out:d,exitCode:f}=await r(c,15e3);return f!==0?`EXIT ${f}
531
539
  ${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:u,exitCode:c}=await r(l,15e3);return c!==0?`EXIT ${c}
532
- ${u}`:u}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),u=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!u)return"ERROR: No supported package manager found (dnf/apt)";let c=e.packages||[];if(!c.every(QS))return"ERROR: package names contain unsafe characters";let d=c.map(Ee).join(" "),f;switch(e.package_action){case"list":f=u==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=u==="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=u==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=u==="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=u==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=u==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:h,exitCode:m}=await r(f,12e4);return m!==0?`EXIT ${m}
540
+ ${u}`:u}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),u=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!u)return"ERROR: No supported package manager found (dnf/apt)";let c=e.packages||[];if(!c.every(jv))return"ERROR: package names contain unsafe characters";let d=c.map(Ce).join(" "),f;switch(e.package_action){case"list":f=u==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=u==="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=u==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=u==="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=u==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=u==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:h,exitCode:m}=await r(f,12e4);return m!==0?`EXIT ${m}
533
541
  ${h}`:h||`${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:u,exitCode:c}=await r(l,1e4);return c!==0?`EXIT ${c}
534
- ${u}`:u||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=Xo(e.user);if(l)return l;let u=Ee(e.user),c=`id ${u} && echo '--- Groups ---' && groups ${u} && echo '--- Last login ---' && lastlog -u ${u} 2>/dev/null`,{out:d,exitCode:f}=await r(c,1e4);return f!==0?`EXIT ${f}
535
- ${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=Xo(e.user);if(l)return l;if(!(e.groups||[]).every(Mm))return"ERROR: groups contain unsafe characters";let u=(e.groups||[]).map(m=>`-G ${Ee(m)}`).join(" "),c=Ee(e.user),d=`useradd -m ${u} ${c} && echo "User ${e.user} created"`,{out:f,exitCode:h}=await r(d,15e3);return h!==0?`EXIT ${h}
536
- ${f}`:f}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=Xo(e.user);if(l)return l;let c=`userdel -r ${Ee(e.user)} && echo "User ${e.user} deleted"`,{out:d,exitCode:f}=await r(c,15e3);return f!==0?`EXIT ${f}
537
- ${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=Xo(e.user);if(l)return l;let c=`${`/home/${e.user}`}/.ssh`,d=`${c}/authorized_keys`,f=Ee(e.user),h=`mkdir -p ${Ee(c)} && chmod 700 ${Ee(c)} && printf '%s
538
- ' ${Ee(e.ssh_key)} >> ${Ee(d)} && chmod 600 ${Ee(d)} && chown -R ${Ee(`${e.user}:${e.user}`)} ${Ee(c)} && echo "SSH key added for ${e.user}"`,{out:m,exitCode:g}=await r(h,15e3);return g!==0?`EXIT ${g}
539
- ${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),u=l.includes("firewalld")?"firewalld":l.includes("ufw")?"ufw":"iptables",c;switch(e.firewall_action){case"status":c=u==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":u==="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(!_c(e.port))return"ERROR: port contains unsafe characters";c=u==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw allow ${Ee(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(!_c(e.port))return"ERROR: port contains unsafe characters";c=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw deny ${Ee(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(!_c(e.port))return"ERROR: port contains unsafe characters";c=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw delete allow ${Ee(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":c=u==="firewalld"?"firewall-cmd --reload":u==="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(c,3e4);return f!==0?`EXIT ${f}
540
- ${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 u=Xo(e.user);if(u)return u}let l=e.user?`-u ${Ee(e.user)}`:"";switch(e.cron_action){case"list":{let u=`crontab ${l} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:c}=await r(u,1e4);return c||"(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 u=`${e.schedule} ${e.command}`,c=`(crontab ${l} -l 2>/dev/null; printf '%s
541
- ' ${Ee(u)}) | crontab ${l} - && echo "Cron entry added: ${u}"`,{out:d,exitCode:f}=await r(c,15e3);return f!==0?`EXIT ${f}
542
+ ${u}`:u||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=Jo(e.user);if(l)return l;let u=Ce(e.user),c=`id ${u} && echo '--- Groups ---' && groups ${u} && echo '--- Last login ---' && lastlog -u ${u} 2>/dev/null`,{out:d,exitCode:f}=await r(c,1e4);return f!==0?`EXIT ${f}
543
+ ${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=Jo(e.user);if(l)return l;if(!(e.groups||[]).every(ng))return"ERROR: groups contain unsafe characters";let u=(e.groups||[]).map(m=>`-G ${Ce(m)}`).join(" "),c=Ce(e.user),d=`useradd -m ${u} ${c} && echo "User ${e.user} created"`,{out:f,exitCode:h}=await r(d,15e3);return h!==0?`EXIT ${h}
544
+ ${f}`:f}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=Jo(e.user);if(l)return l;let c=`userdel -r ${Ce(e.user)} && echo "User ${e.user} deleted"`,{out:d,exitCode:f}=await r(c,15e3);return f!==0?`EXIT ${f}
545
+ ${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=Jo(e.user);if(l)return l;let c=`${`/home/${e.user}`}/.ssh`,d=`${c}/authorized_keys`,f=Ce(e.user),h=`mkdir -p ${Ce(c)} && chmod 700 ${Ce(c)} && printf '%s
546
+ ' ${Ce(e.ssh_key)} >> ${Ce(d)} && chmod 600 ${Ce(d)} && chown -R ${Ce(`${e.user}:${e.user}`)} ${Ce(c)} && echo "SSH key added for ${e.user}"`,{out:m,exitCode:g}=await r(h,15e3);return g!==0?`EXIT ${g}
547
+ ${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),u=l.includes("firewalld")?"firewalld":l.includes("ufw")?"ufw":"iptables",c;switch(e.firewall_action){case"status":c=u==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":u==="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(!Rc(e.port))return"ERROR: port contains unsafe characters";c=u==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw allow ${Ce(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(!Rc(e.port))return"ERROR: port contains unsafe characters";c=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw deny ${Ce(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(!Rc(e.port))return"ERROR: port contains unsafe characters";c=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw delete allow ${Ce(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":c=u==="firewalld"?"firewall-cmd --reload":u==="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(c,3e4);return f!==0?`EXIT ${f}
548
+ ${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 u=Jo(e.user);if(u)return u}let l=e.user?`-u ${Ce(e.user)}`:"";switch(e.cron_action){case"list":{let u=`crontab ${l} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:c}=await r(u,1e4);return c||"(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 u=`${e.schedule} ${e.command}`,c=`(crontab ${l} -l 2>/dev/null; printf '%s
549
+ ' ${Ce(u)}) | crontab ${l} - && echo "Cron entry added: ${u}"`,{out:d,exitCode:f}=await r(c,15e3);return f!==0?`EXIT ${f}
542
550
  ${d}`:d}case"remove":{if(!e.command)return"ERROR: command (substring to match) is required for cron remove";let u=e.command.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=`crontab ${l} -l 2>/dev/null | grep -v "${u}" | crontab ${l} - && echo "Matching cron entries removed"`,{out:d,exitCode:f}=await r(c,15e3);return f!==0?`EXIT ${f}
543
551
  ${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=`
544
- CERT=${Ee(e.cert_path)}
552
+ CERT=${Ce(e.cert_path)}
545
553
  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"
546
554
  `.trim():l=`
547
- DOMAIN=${Ee(e.domain)}
555
+ DOMAIN=${Ce(e.domain)}
548
556
  LECP="/etc/letsencrypt/live/$DOMAIN/cert.pem"
549
557
  if [ -f "$LECP" ]; then
550
558
  echo "Source: Let's Encrypt $LECP"
@@ -564,14 +572,14 @@ if [ -n "$EXPIRY" ]; then
564
572
  [ "$DAYS" -lt 0 ] && echo "CRITICAL: Certificate has EXPIRED!"
565
573
  fi
566
574
  `.trim();let{out:u,exitCode:c}=await r(l,25e3),d=/notAfter=|Days until expiry:/i.test(u);return c!==0&&!d?`EXIT ${c}
567
- ${u}`:u||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let u=`tail -n ${e.lines||100} ${Ee(e.path)} 2>&1`,{out:c,exitCode:d}=await r(u,15e3);return d!==0?`EXIT ${d}
568
- ${c}`:c||"(empty log)"}case"find_large":{let l=e.path||"/",u=e.limit||20,c=e.min_size||"100M",d=`find ${Ee(l)} -xdev -type f -size +${Ee(c)} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${u}`,{out:f,exitCode:h}=await r(d,6e4);return h!==0?`EXIT ${h}
569
- ${f}`:f||`(no files larger than ${c} 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 h=kc(e.service_name,"service_name");if(h)return h}let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",u;switch(e.service_action){case"status":u=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":u="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":u=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":u=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":u=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":u=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":u=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":u=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:c,exitCode:d}=await r(u,3e4);return d===0||e.service_action==="status"&&d===3?c||`service ${e.service_action} OK`:`EXIT ${d}
570
- ${c}`}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(!ev(l))return"ERROR: signal contains unsafe characters";let u;if(e.pid){if(!/^\d+$/.test(String(e.pid)))return"ERROR: pid must be numeric";u=`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 u=`pgrep -a ${Ee(e.process_name)} 2>/dev/null | head -5 && pkill -${l} ${Ee(e.process_name)} && echo "Sent ${l} to all '${e.process_name}' processes"`;let{out:c,exitCode:d}=await r(u,15e3);return d!==0?`EXIT ${d}
575
+ ${u}`:u||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let u=`tail -n ${e.lines||100} ${Ce(e.path)} 2>&1`,{out:c,exitCode:d}=await r(u,15e3);return d!==0?`EXIT ${d}
576
+ ${c}`:c||"(empty log)"}case"find_large":{let l=e.path||"/",u=e.limit||20,c=e.min_size||"100M",d=`find ${Ce(l)} -xdev -type f -size +${Ce(c)} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${u}`,{out:f,exitCode:h}=await r(d,6e4);return h!==0?`EXIT ${h}
577
+ ${f}`:f||`(no files larger than ${c} 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 h=Cc(e.service_name,"service_name");if(h)return h}let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",u;switch(e.service_action){case"status":u=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":u="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":u=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":u=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":u=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":u=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":u=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":u=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:c,exitCode:d}=await r(u,3e4);return d===0||e.service_action==="status"&&d===3?c||`service ${e.service_action} OK`:`EXIT ${d}
578
+ ${c}`}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(!Dv(l))return"ERROR: signal contains unsafe characters";let u;if(e.pid){if(!/^\d+$/.test(String(e.pid)))return"ERROR: pid must be numeric";u=`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 u=`pgrep -a ${Ce(e.process_name)} 2>/dev/null | head -5 && pkill -${l} ${Ce(e.process_name)} && echo "Sent ${l} to all '${e.process_name}' processes"`;let{out:c,exitCode:d}=await r(u,15e3);return d!==0?`EXIT ${d}
571
579
  ${c}`:c}case"journalctl":{let l=e.lines||100,u=["journalctl","--no-pager","-n",String(l)];e.unit&&u.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&u.push("-p",e.priority),e.since&&u.push(`--since="${e.since}"`),u.push('2>/dev/null || echo "(journalctl not available)"');let{out:c,exitCode:d}=await r(u.join(" "),2e4);return d!==0?`EXIT ${d}
572
- ${c}`:c||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=Ho(),n=o(e.type,e.name,e.content,e.description);return n.ok?n.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${n.path}`:`ERROR: ${n.error}`}case"delete_memory":{let{deleteMemory:o}=Ho();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=li(),n=await o(t,e,s);return n!==null?n:`ERROR: Unknown tool: ${t}`}}}async function nv(t,e,s={}){let{emit:o}=li(),{logToolExecution:n}=gm(),r=Date.now(),i=s.silent?null:AS(t,e);if(!i){let l=await Tm(t,e,s);return n({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}let a=new CS(i);a.start();try{let l=await Tm(t,e,s);return a.stop(),n({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw a.stop(),n({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}Pm.exports={TOOL_DEFINITIONS:tv,executeTool:nv,resolvePath:it,autoFixPath:ji,autoFixEdit:Nm,enrichBashError:Om,cancelPendingAskUser:YS,setAskUserHandler:zS,fileExists:Rt}});var Ro=V((BC,Im)=>{Im.exports=Lm()});var Ec=V((WC,Dm)=>{var{loadServerProfiles:zs,resolveProfile:UC,sshExec:sv}=Ds(),ov=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,rv=/\b(bug|issue|problem|broken|failing|fails|error|wrong|regression|debug|investigate|why|slow|fix|delete|deleted|deleting|removed|reappears?|returns?|comes?\s+back|webui|production|prod|server|fehler|kaputt|lösche|loesch|gelösch|geloesch|zurück|zurueck|taucht?\s+wieder\s+auf)\b/i,iv=/https?:\/\/[^\s)]+/gi;function av(t){if(typeof t!="string")return[];let e=new Set,s=[];for(let o of t.match(iv)||[]){let n=o.replace(/[.,;!?]+$/g,"");e.has(n)||(e.add(n),s.push(n))}return s}function lv(t,e){let s;try{s=new URL(t).hostname.toLowerCase()}catch{return null}let o=s.split(".");for(let[n,r]of Object.entries(e))if(o.includes(n.toLowerCase()))return{matchedName:n,matchedProfile:r,hostname:s};for(let[n,r]of Object.entries(e))if(String(r.host||"").toLowerCase()===s)return{matchedName:n,matchedProfile:r,hostname:s};return{matchedName:null,matchedProfile:null,hostname:s}}function jm(t,e=zs()){if(typeof t!="string"||!rv.test(t))return null;let s=av(t).filter(o=>!ov.test(o));if(s.length===0)return null;for(let o of s){let n=lv(o,e);if(n)return{url:o,hostname:n.hostname,matchedName:n.matchedName,matchedProfile:n.matchedProfile,shouldPreferBrowser:!0,shouldPreferSsh:!!(n.matchedName&&n.matchedProfile)}}return null}var vc={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 cv(){let t=zs();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[n,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}`:"",u=r.sudo?", sudo available":"";s.push(`- **${n}**: ${i}${a}${l}${u}`)}let o=new Set;for(let n of Object.values(t))n.os&&vc[n.os]&&o.add(n.os);if(o.size>0){s.push("");for(let n of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[n]||n;s.push(`### ${r} Notes`);for(let i of vc[n])s.push(`- ${i}`)}}return s.join(`
573
- `)}function uv(t){let e=zs();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function dv(){return Object.keys(zs())}function fv(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(s,"utf-8")}catch{}let n=zs(),r=Object.keys(n);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=o.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let u=r.map(f=>{let h=n[f],m=h.user?`${h.user}@${h.host}`:h.host,g=h.port&&Number(h.port)!==22?`:${h.port}`:"";return` - **${f}**: ${m}${g}${h.os?` (${h.os})`:""}`}).join(`
574
- `),c=r.map(f=>n[f].log_path).filter(Boolean),d=c.length>0?`
580
+ ${c}`:c||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=Go(),s=o(e.type,e.name,e.content,e.description);return s.ok?s.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${s.path}`:`ERROR: ${s.error}`}case"delete_memory":{let{deleteMemory:o}=Go();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=ui(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function Fv(t,e,n={}){let{emit:o}=ui(),{logToolExecution:s}=qm(),r=Date.now(),i=n.silent?null:pv(t,e);if(!i){let l=await Vm(t,e,n);return s({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}let a=new hv(i);a.start();try{let l=await Vm(t,e,n);return a.stop(),s({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw a.stop(),s({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}sg.exports={TOOL_DEFINITIONS:qv,executeTool:Fv,resolvePath:lt,autoFixPath:Fi,autoFixEdit:tg,enrichBashError:eg,cancelPendingAskUser:Av,setAskUserHandler:Ov,fileExists:Ct}});var Ao=Z((CA,rg)=>{rg.exports=og()});var Pc=Z((OA,ag)=>{var{loadServerProfiles:Zs,resolveProfile:AA,sshExec:Bv}=Ws(),Uv=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,Wv=/\b(bug|issue|problem|broken|failing|fails|error|wrong|regression|debug|investigate|why|slow|fix|delete|deleted|deleting|removed|reappears?|returns?|comes?\s+back|webui|production|prod|server|fehler|kaputt|lösche|loesch|gelösch|geloesch|zurück|zurueck|taucht?\s+wieder\s+auf)\b/i,Hv=/https?:\/\/[^\s)]+/gi;function Yv(t){if(typeof t!="string")return[];let e=new Set,n=[];for(let o of t.match(Hv)||[]){let s=o.replace(/[.,;!?]+$/g,"");e.has(s)||(e.add(s),n.push(s))}return n}function Gv(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return null}let o=n.split(".");for(let[s,r]of Object.entries(e))if(o.includes(s.toLowerCase()))return{matchedName:s,matchedProfile:r,hostname:n};for(let[s,r]of Object.entries(e))if(String(r.host||"").toLowerCase()===n)return{matchedName:s,matchedProfile:r,hostname:n};return{matchedName:null,matchedProfile:null,hostname:n}}function ig(t,e=Zs()){if(typeof t!="string"||!Wv.test(t))return null;let n=Yv(t).filter(o=>!Uv.test(o));if(n.length===0)return null;for(let o of n){let s=Gv(o,e);if(s)return{url:o,hostname:s.hostname,matchedName:s.matchedName,matchedProfile:s.matchedProfile,shouldPreferBrowser:!0,shouldPreferSsh:!!(s.matchedName&&s.matchedProfile)}}return null}var Nc={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 zv(){let t=Zs();if(Object.keys(t).length===0)return null;let n=["## Remote Servers (.nex/servers.json)"];n.push(""),n.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[s,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}`:"",u=r.sudo?", sudo available":"";n.push(`- **${s}**: ${i}${a}${l}${u}`)}let o=new Set;for(let s of Object.values(t))s.os&&Nc[s.os]&&o.add(s.os);if(o.size>0){n.push("");for(let s of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[s]||s;n.push(`### ${r} Notes`);for(let i of Nc[s])n.push(`- ${i}`)}}return n.join(`
581
+ `)}function Kv(t){let e=Zs();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function Xv(){return Object.keys(Zs())}function Vv(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(n,"utf-8")}catch{}let s=Zs(),r=Object.keys(s);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=o.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let u=r.map(f=>{let h=s[f],m=h.user?`${h.user}@${h.host}`:h.host,g=h.port&&Number(h.port)!==22?`:${h.port}`:"";return` - **${f}**: ${m}${g}${h.os?` (${h.os})`:""}`}).join(`
582
+ `),c=r.map(f=>s[f].log_path).filter(Boolean),d=c.length>0?`
575
583
  - Server log paths: ${c.join(", ")}`:"";return`# Deployment Context (Auto-detected)
576
584
 
577
585
  This project is deployed on a **remote server**. The application runs as a service there \u2014 NOT locally.
@@ -589,7 +597,7 @@ ${u}
589
597
  - \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
590
598
  - \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
591
599
 
592
- **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${hv(n)}`}function hv(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
600
+ **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${Jv(s)}`}function Jv(t){return Object.values(t).some(n=>n.host==="94.130.37.43")?`
593
601
 
594
602
  ## Server Debugging Rules
595
603
 
@@ -600,36 +608,36 @@ ${u}
600
608
  - 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.
601
609
  - 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.
602
610
  - 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.
603
- - 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 pv(t){let e=zs(),s=jm(t,e);if(!s?.matchedProfile||!s?.matchedName)return null;let{matchedProfile:o,matchedName:n}=s,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 sv(o,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=o.user?`${o.user}@${o.host}`:o.host;return`[Server context for "${n}" (${a}) \u2014 probed at task start]
604
- `+i.trim()}catch{return null}}Dm.exports={getServerContext:cv,getDeploymentContextBlock:fv,hasServerOS:uv,getProfileNames:dv,probeUrlServer:pv,detectRuntimeDebugTarget:jm,OS_HINTS:vc}});var Um=V((HC,Bm)=>{var wt=require("fs").promises,Fi=require("fs"),We=require("path"),qi=require("util").promisify(require("child_process").exec),{C:Ks}=ot(),{getMergeConflicts:Fm}=si(),{getServerContext:mv}=Ec(),{refreshIndex:gv,getFileIndex:yv,buildContentIndex:wv,summarizeModuleHubs:$v}=sn(),bv=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),_v=[{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 kv(t,e=6){let s=new Map;for(let o of t){let n=o.includes("/")?o.split("/")[0]:"(root)";!n||n.startsWith(".")||s.set(n,(s.get(n)||0)+1)}return[...s.entries()].sort((o,n)=>n[1]-o[1]||o[0].localeCompare(n[0])).slice(0,e).map(([o,n])=>`${o} (${n})`)}function xv(t){let e=new Set(t),s=new Set;for(let o of _v)(e.has(o.file)||[...e].some(n=>n.startsWith(`${o.file}/`)))&&s.add(o.label);return e.has("package.json")&&s.add("Node.js"),[...e].some(o=>/^tests?\//.test(o)||/\.test\./.test(o)||/\.spec\./.test(o))&&s.add("Tests"),[...e].some(o=>o.startsWith("vscode/"))&&s.add("VS Code Extension"),[...s]}function Sv(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 o of e)if(t.includes(o)&&s.push(o),s.length>=5)break;return s}function vv(t,e=6){let s=t.filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(s.length===0)return[];let o=t.filter(r=>!/^tests?\//.test(r)&&!/\.test\./.test(r)&&!/\.spec\./.test(r)&&/\.(js|jsx|ts|tsx|py|go|rs|java)$/.test(r)),n=[];for(let r of o){let i=We.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=s.filter(l=>l.includes(i));if(a.length>0&&n.push(`${r} -> ${a.slice(0,2).join(", ")}`),n.length>=e)break}return n}function Ev(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function Tv(t){try{await gv(t);let e=yv();if(!e||e.length===0)return"";let s=xv(e),o=kv(e),n=Sv(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=vv(e),a=[];try{let d=We.join(t,"package.json");if(Fi.existsSync(d)){let f=JSON.parse(Fi.readFileSync(d,"utf-8"));a=Ev(f)}}catch{}let l="",u="";try{let d=await wv(t),f=Object.entries(d.files||{}).map(([h,m])=>({file:h,defs:Array.isArray(m.defs)?m.defs.length:0})).filter(h=>h.defs>0).sort((h,m)=>m.defs-h.defs||h.file.localeCompare(m.file)).slice(0,4).map(h=>`${h.file} (${h.defs} defs)`);f.length>0&&(l=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await $v(t,4);d.length>0&&(u=`MODULE HUBS: ${d.join(", ")}`)}catch{}let c=[`REPO MAP: ${e.length} indexed files${s.length?` | stack: ${s.join(", ")}`:""}`];return o.length>0&&c.push(`WORK AREAS: ${o.join(", ")}`),n.length>0&&c.push(`LIKELY ENTRY POINTS: ${n.join(", ")}`),a.length>0&&c.push(`WORKSPACES: ${a.join(", ")}`),r>0&&c.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&c.push(`TEST MAP: ${i.join(" | ")}`),l&&c.push(l),u&&c.push(u),c.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."),c.join(`
605
- `)}catch{return""}}function Rv(t){try{return Fi.readFileSync(t,"utf-8").split(`
606
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function Cv(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 Av(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:o=[]}={}){let n=We.join(t,".gitignore"),r=[...o,...Rv(n)],i=0,a=[We.basename(t)+"/"];function l(u,c,d){if(d>e||i>=s)return;let f;try{f=Fi.readdirSync(u,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=f.filter(m=>!(bv.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||Cv(m.name,r)));for(let m=0;m<h.length;m++){if(i>=s){a.push(`${c}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],$=m===h.length-1,k=$?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",v=c+($?" ":"\u2502 "),A=g.isDirectory()?g.name+"/":g.name;a.push(`${c}${k}${A}`),i++,g.isDirectory()&&l(We.join(u,g.name),v,d+1)}}return l(t,"",1),a.join(`
607
- `)}var Tc=new Map,Vs=new Map,Bi=null,qm=3e4,Xs={result:null,expiry:0,cwd:null};async function cn(t){try{return await t()}catch{return null}}async function Ov(){if(!Bi||Date.now()>Bi)return!1;let t=[We.join(process.cwd(),"package.json"),We.join(process.cwd(),"README.md"),We.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await wt.stat(e),o=Vs.get(e);if(!o||s.mtimeMs!==o)return!1}catch{if(Vs.has(e))return!1}try{let e=We.join(process.cwd(),".git","HEAD"),s=await wt.stat(e),o=Vs.get(e);if(!o||s.mtimeMs!==o)return!1}catch{}return!0}async function Nv(){let t=[We.join(process.cwd(),"package.json"),We.join(process.cwd(),"README.md"),We.join(process.cwd(),".gitignore"),We.join(process.cwd(),".git","HEAD"),We.join(process.cwd(),"CLAUDE.md"),We.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let s=await wt.stat(e);Vs.set(e,s.mtimeMs)}catch{Vs.delete(e)}}async function Mv(t){let e="fileContext",s=Tc.get(e),o=!1;if(s&&await Ov()&&(o=!0),!o){let u=[],c=We.join(t,"package.json");if(await cn(()=>wt.access(c).then(()=>!0).catch(()=>!1)))try{let S=await wt.readFile(c,"utf-8"),N=JSON.parse(S),ee={name:N.name,version:N.version};N.scripts&&(ee.scripts=Object.keys(N.scripts).slice(0,15)),N.dependencies&&(ee.deps=Object.keys(N.dependencies).length),N.devDependencies&&(ee.devDeps=Object.keys(N.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(ee)}`)}catch{}let f=We.join(t,"README.md");if(await cn(()=>wt.access(f).then(()=>!0).catch(()=>!1))){let N=(await wt.readFile(f,"utf-8")).split(`
611
+ - 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 Zv(t){let e=Zs(),n=ig(t,e);if(!n?.matchedProfile||!n?.matchedName)return null;let{matchedProfile:o,matchedName:s}=n,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 Bv(o,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=o.user?`${o.user}@${o.host}`:o.host;return`[Server context for "${s}" (${a}) \u2014 probed at task start]
612
+ `+i.trim()}catch{return null}}ag.exports={getServerContext:zv,getDeploymentContextBlock:Vv,hasServerOS:Kv,getProfileNames:Xv,probeUrlServer:Zv,detectRuntimeDebugTarget:ig,OS_HINTS:Nc}});var dg=Z((NA,ug)=>{var $t=require("fs").promises,Wi=require("fs"),Ye=require("path"),Ui=require("util").promisify(require("child_process").exec),{C:Qs}=it(),{getMergeConflicts:cg}=ri(),{getServerContext:Qv}=Pc(),{refreshIndex:eE,getFileIndex:tE,buildContentIndex:nE,summarizeModuleHubs:sE}=an(),oE=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),rE=[{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 iE(t,e=6){let n=new Map;for(let o of t){let s=o.includes("/")?o.split("/")[0]:"(root)";!s||s.startsWith(".")||n.set(s,(n.get(s)||0)+1)}return[...n.entries()].sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])).slice(0,e).map(([o,s])=>`${o} (${s})`)}function aE(t){let e=new Set(t),n=new Set;for(let o of rE)(e.has(o.file)||[...e].some(s=>s.startsWith(`${o.file}/`)))&&n.add(o.label);return e.has("package.json")&&n.add("Node.js"),[...e].some(o=>/^tests?\//.test(o)||/\.test\./.test(o)||/\.spec\./.test(o))&&n.add("Tests"),[...e].some(o=>o.startsWith("vscode/"))&&n.add("VS Code Extension"),[...n]}function lE(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"],n=[];for(let o of e)if(t.includes(o)&&n.push(o),n.length>=5)break;return n}function cE(t,e=6){let n=t.filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(n.length===0)return[];let o=t.filter(r=>!/^tests?\//.test(r)&&!/\.test\./.test(r)&&!/\.spec\./.test(r)&&/\.(js|jsx|ts|tsx|py|go|rs|java)$/.test(r)),s=[];for(let r of o){let i=Ye.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=n.filter(l=>l.includes(i));if(a.length>0&&s.push(`${r} -> ${a.slice(0,2).join(", ")}`),s.length>=e)break}return s}function uE(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function dE(t){try{await eE(t);let e=tE();if(!e||e.length===0)return"";let n=aE(e),o=iE(e),s=lE(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=cE(e),a=[];try{let d=Ye.join(t,"package.json");if(Wi.existsSync(d)){let f=JSON.parse(Wi.readFileSync(d,"utf-8"));a=uE(f)}}catch{}let l="",u="";try{let d=await nE(t),f=Object.entries(d.files||{}).map(([h,m])=>({file:h,defs:Array.isArray(m.defs)?m.defs.length:0})).filter(h=>h.defs>0).sort((h,m)=>m.defs-h.defs||h.file.localeCompare(m.file)).slice(0,4).map(h=>`${h.file} (${h.defs} defs)`);f.length>0&&(l=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await sE(t,4);d.length>0&&(u=`MODULE HUBS: ${d.join(", ")}`)}catch{}let c=[`REPO MAP: ${e.length} indexed files${n.length?` | stack: ${n.join(", ")}`:""}`];return o.length>0&&c.push(`WORK AREAS: ${o.join(", ")}`),s.length>0&&c.push(`LIKELY ENTRY POINTS: ${s.join(", ")}`),a.length>0&&c.push(`WORKSPACES: ${a.join(", ")}`),r>0&&c.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&c.push(`TEST MAP: ${i.join(" | ")}`),l&&c.push(l),u&&c.push(u),c.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."),c.join(`
613
+ `)}catch{return""}}function fE(t){try{return Wi.readFileSync(t,"utf-8").split(`
614
+ `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function hE(t,e){for(let n of e)if(n===t||n.includes("*")&&new RegExp("^"+n.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function pE(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=Ye.join(t,".gitignore"),r=[...o,...fE(s)],i=0,a=[Ye.basename(t)+"/"];function l(u,c,d){if(d>e||i>=n)return;let f;try{f=Wi.readdirSync(u,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=f.filter(m=>!(oE.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||hE(m.name,r)));for(let m=0;m<h.length;m++){if(i>=n){a.push(`${c}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],$=m===h.length-1,x=$?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",E=c+($?" ":"\u2502 "),N=g.isDirectory()?g.name+"/":g.name;a.push(`${c}${x}${N}`),i++,g.isDirectory()&&l(Ye.join(u,g.name),E,d+1)}}return l(t,"",1),a.join(`
615
+ `)}var Mc=new Map,to=new Map,Hi=null,lg=3e4,eo={result:null,expiry:0,cwd:null};async function fn(t){try{return await t()}catch{return null}}async function mE(){if(!Hi||Date.now()>Hi)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 n=await $t.stat(e),o=to.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(to.has(e))return!1}try{let e=Ye.join(process.cwd(),".git","HEAD"),n=await $t.stat(e),o=to.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function gE(){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 n=await $t.stat(e);to.set(e,n.mtimeMs)}catch{to.delete(e)}}async function yE(t){let e="fileContext",n=Mc.get(e),o=!1;if(n&&await mE()&&(o=!0),!o){let u=[],c=Ye.join(t,"package.json");if(await fn(()=>$t.access(c).then(()=>!0).catch(()=>!1)))try{let S=await $t.readFile(c,"utf-8"),P=JSON.parse(S),ne={name:P.name,version:P.version};P.scripts&&(ne.scripts=Object.keys(P.scripts).slice(0,15)),P.dependencies&&(ne.deps=Object.keys(P.dependencies).length),P.devDependencies&&(ne.devDeps=Object.keys(P.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(ne)}`)}catch{}let f=Ye.join(t,"README.md");if(await fn(()=>$t.access(f).then(()=>!0).catch(()=>!1))){let P=(await $t.readFile(f,"utf-8")).split(`
608
616
  `).slice(0,50);u.push(`README (first 50 lines):
609
- ${N.join(`
610
- `)}`)}let m=We.join(t,".gitignore");if(await cn(()=>wt.access(m).then(()=>!0).catch(()=>!1))){let S=await wt.readFile(m,"utf-8");u.push(`GITIGNORE:
611
- ${S.trim()}`)}let $=We.join(t,"CLAUDE.md");if(await cn(()=>wt.access($).then(()=>!0).catch(()=>!1))){let S=await wt.readFile($,"utf-8");S.trim()&&u.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
612
- ${S.trim()}`)}let v=We.join(t,".nex","CLAUDE.md");if(await cn(()=>wt.access(v).then(()=>!0).catch(()=>!1))){let S=await wt.readFile(v,"utf-8");S.trim()&&u.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
613
- ${S.trim()}`)}let E=await Tv(t);E&&u.push(E),s=u.join(`
614
-
615
- `),Tc.set(e,s),Bi=Date.now()+qm,await Nv()}let n=[s],r,i,a,l;if(Xs.result&&Date.now()<Xs.expiry&&Xs.cwd===t?{branch:r,status:i,log:a,conflicts:l}=Xs.result:([r,i,a,l]=await Promise.all([cn(async()=>{let{stdout:u}=await qi("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),cn(async()=>{let{stdout:u}=await qi("git status --short",{cwd:t,timeout:5e3});return u.trim()}),cn(async()=>{let{stdout:u}=await qi("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Fm()]),Xs={result:{branch:r,status:i,log:a,conflicts:l},expiry:Date.now()+qm,cwd:t}),r&&n.push(`GIT BRANCH: ${r}`),i&&n.push(`GIT STATUS:
616
- ${i}`),a&&n.push(`RECENT COMMITS:
617
+ ${P.join(`
618
+ `)}`)}let m=Ye.join(t,".gitignore");if(await fn(()=>$t.access(m).then(()=>!0).catch(()=>!1))){let S=await $t.readFile(m,"utf-8");u.push(`GITIGNORE:
619
+ ${S.trim()}`)}let $=Ye.join(t,"CLAUDE.md");if(await fn(()=>$t.access($).then(()=>!0).catch(()=>!1))){let S=await $t.readFile($,"utf-8");S.trim()&&u.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
620
+ ${S.trim()}`)}let E=Ye.join(t,".nex","CLAUDE.md");if(await fn(()=>$t.access(E).then(()=>!0).catch(()=>!1))){let S=await $t.readFile(E,"utf-8");S.trim()&&u.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
621
+ ${S.trim()}`)}let v=await dE(t);v&&u.push(v),n=u.join(`
622
+
623
+ `),Mc.set(e,n),Hi=Date.now()+lg,await gE()}let s=[n],r,i,a,l;if(eo.result&&Date.now()<eo.expiry&&eo.cwd===t?{branch:r,status:i,log:a,conflicts:l}=eo.result:([r,i,a,l]=await Promise.all([fn(async()=>{let{stdout:u}=await Ui("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),fn(async()=>{let{stdout:u}=await Ui("git status --short",{cwd:t,timeout:5e3});return u.trim()}),fn(async()=>{let{stdout:u}=await Ui("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),cg()]),eo={result:{branch:r,status:i,log:a,conflicts:l},expiry:Date.now()+lg,cwd:t}),r&&s.push(`GIT BRANCH: ${r}`),i&&s.push(`GIT STATUS:
624
+ ${i}`),a&&s.push(`RECENT COMMITS:
617
625
  ${a}`),l&&l.length>0){let u=l.map(c=>` ${c.file}`).join(`
618
- `);n.push(`MERGE CONFLICTS (resolve before editing these files):
619
- ${u}`)}try{let u=mv();u&&n.push(u)}catch{}return n.join(`
620
-
621
- `)}async function Pv(t){let e=We.join(t,"package.json"),s="";if(await cn(()=>wt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await wt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[n,r]=await Promise.all([cn(async()=>{let{stdout:i}=await qi("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Fm()]);if(r&&r.length>0){console.log(`${Ks.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ks.reset}`);for(let i of r)console.log(`${Ks.red} ${i.file}${Ks.reset}`);console.log(`${Ks.yellow} \u2192 Resolve conflicts before starting tasks${Ks.reset}`)}console.log()}Bm.exports={gatherProjectContext:Mv,printContext:Pv,generateFileTree:Av,_clearContextCache:()=>{Tc.clear(),Vs.clear(),Bi=null,Xs={result:null,expiry:0,cwd:null}}}});var Wi=V((GC,Gm)=>{var Vt=require("fs"),Ui=require("path"),{atomicWrite:Lv}=Gn();function Qo(){return Ui.join(process.cwd(),".nex","sessions")}function Rc(){let t=Qo();Vt.existsSync(t)||Vt.mkdirSync(t,{recursive:!0,mode:448})}function Cc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ui.join(Qo(),`${e}.json`)}function Ac(t,e,s={}){Rc();let o=Cc(t),n={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 Lv(o,JSON.stringify(n,null,2)),{path:o,name:t}}function Wm(t){let e=Cc(t);if(!Vt.existsSync(e))return null;try{return JSON.parse(Vt.readFileSync(e,"utf-8"))}catch{return null}}function Hm(){Rc();let t=Qo(),e=Vt.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(Vt.readFileSync(Ui.join(t,o),"utf-8"));s.push({name:n.name||o.replace(".json",""),createdAt:n.createdAt,updatedAt:n.updatedAt,messageCount:n.messageCount||0,model:n.model,provider:n.provider,score:n.score!=null?n.score:null,scoreGrade:n.scoreGrade||null})}catch{}return s.sort((o,n)=>(n.updatedAt||"").localeCompare(o.updatedAt||""))}function Iv(t){let e=Cc(t);return Vt.existsSync(e)?(Vt.unlinkSync(e),!0):!1}function jv(){let t=Hm();return t.length===0?null:Wm(t[0].name)}var cs=null,_n=null,Zo=null;function Dv(t,e={}){t.length!==0&&(cs&&clearTimeout(cs),_n=t,Zo=e||{},cs=setTimeout(()=>{_n&&_n.length>0&&Ac("_autosave",_n,Zo),cs=null,_n=null,Zo=null},5e3))}function qv(){cs&&(clearTimeout(cs),cs=null),_n&&_n.length>0&&(Ac("_autosave",_n,Zo),_n=null,Zo=null)}function Fv(){Rc();let t=Qo(),e=Vt.readdirSync(t).filter(r=>r.endsWith(".json")),s=new Date,o=new Date(s.getTime()-720*60*60*1e3),n=0;for(let r of e){let i=Ui.join(t,r);try{let a=Vt.statSync(i);new Date(a.mtime)<o&&(Vt.unlinkSync(i),n++)}catch{}}return n}Gm.exports={saveSession:Ac,loadSession:Wm,listSessions:Hm,deleteSession:Iv,getLastSession:jv,autoSave:Dv,flushAutoSave:qv,clearOldSessions:Fv,_getSessionsDir:Qo}});var eg=V((YC,Qm)=>{"use strict";var er=require("fs"),Ym=require("path");function zm(t){let e=[];return t.forEach((s,o)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_use"&&e.push({name:n.name||"",input:n.input||{},index:o,id:n.id||null})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(n=>{let r=n.function?.name||n.name||"",i={};try{i=typeof n.function?.arguments=="string"?JSON.parse(n.function.arguments):n.function?.arguments||n.input||{}}catch{}e.push({name:r,input:i,index:o,id:n.id||null})}))}),e}function Bv(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(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function Km(t){let e=[];return t.forEach((s,o)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{if(n&&n.type==="tool_result"){let r=typeof n.content=="string"?n.content:Array.isArray(n.content)?n.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(n.content||"");e.push({content:r,index:o})}}),s.role==="tool"){let n=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:n,index:o})}}),e}function Xm(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 o=s.content.filter(n=>n&&(n.type==="text"||typeof n=="string")).map(n=>typeof n=="string"?n:n.text||"").join("").trim();if(o)return o}}}return""}function Vm(t,e){let s=[];for(let o=t.length-1;o>=0&&s.length<e;o--){let n=t[o];if(n.role!=="assistant")continue;let r="";typeof n.content=="string"?r=n.content.trim():Array.isArray(n.content)&&(r=n.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 Jm(t){let e=new Map;for(let s of t){let o;try{o=JSON.stringify(s.input)}catch{o=String(s.input)}let n=`${s.name}|${o}`;e.set(n,(e.get(n)||0)+1)}return e}function Zm(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=[],o=zm(t),n=Km(t),r=o.length,i=Bv(t),a=o.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 u=o.find(_=>{let L=_.input?.command||_.input?.cmd||"";return/\bsed\s+-n\b/.test(L)});if(u){let _=(u.input?.command||u.input?.cmd||"").slice(0,80);n.some(W=>W.content.includes("BLOCKED: sed -n is forbidden")||W.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: ${_}`))}o.find(_=>{if(_.name!=="grep"&&_.name!=="bash"&&_.name!=="ssh_exec")return!1;let L=_.input?.command||_.input?.cmd||"",W=_.input?.pattern||"",te=`${L} ${W}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(te)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(te)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(_=>_.role==="assistant"),f=Xm(t),m=Vm(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 L=typeof _.content=="string"?_.content:Array.isArray(_.content)?_.content.map(W=>typeof W=="string"?W:W.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(L)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let k=Jm(a),v=0,A="";for(let[_,L]of k)L>v&&(v=L,A=_);if(v>=3){let[_]=A.split("|");e-=1,s.push(`Same tool call repeated ${v}\xD7 (tool: ${_})`)}let E=!1,S=t.findIndex(_=>_.role==="user"&&typeof _.content=="string"&&_.content.includes("[SYSTEM STOP]")&&_.content.includes('"valid":true'));S>=0&&o.filter(L=>L.index>S).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=o.filter(_=>_.name==="ssh_exec");if(N.length>=8){let _=0,L=1;for(let W=1;W<N.length;W++)N[W].index<=N[W-1].index+2?L++:(_=Math.max(_,L),L=1);_=Math.max(_,L),_>=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 ee=new Map;for(let _ of a)if(_.name==="read_file"&&_.input?.path){let L=_.input.path;ee.has(L)||ee.set(L,{count:0,ranges:[]});let W=ee.get(L);if(W.count++,_.input.line_start!=null){let te=_.input.line_start||1,z=_.input.line_end||te+350;W.ranges.push([te,z])}}function re(_,L,W){for(let[te,z]of W){let R=Math.max(_,te),H=Math.min(L,z);if(H>R){let se=H-R,D=L-_||1;if(se/D>=.7)return!0}}return!1}let le=0,ue="";for(let[_,L]of ee){if(L.count<3)continue;if(L.ranges.length===L.count){let z=!1,R=[];for(let[H,se]of L.ranges){if(R.length>0&&re(H,se,R)){z=!0;break}R.push([H,se])}if(!z)continue}if(L.count-L.ranges.length<=2&&L.ranges.length>=1){let z=!1,R=[];for(let[H,se]of L.ranges){if(R.length>0&&re(H,se,R)){z=!0;break}R.push([H,se])}if(!z)continue}L.count>le&&(le=L.count,ue=_)}if(le>=3){e-=1;let _=ue.split("/").slice(-2).join("/");s.push(`read_file loop: "${_}" read ${le}\xD7 (file already in context)`)}let oe=0,ae="";for(let[_,L]of ee){if(L.ranges.length<4)continue;let W=[],te=!1;for(let[z,R]of L.ranges){if(W.length>0&&re(z,R,W)){te=!0;break}W.push([z,R])}!te&&L.ranges.length>oe&&(oe=L.ranges.length,ae=_)}if(oe>=4){e-=.5;let _=ae.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${_}" read in ${oe} sequential sections \u2014 use grep instead`)}let T=new Map;for(let _ of a)if(_.name==="grep"&&_.input?.path&&_.input?.pattern){let L=_.input.path;T.has(L)||T.set(L,new Set),T.get(L).add(_.input.pattern)}let U=0,Z="";for(let[_,L]of T)_.split("/").pop().includes(".")&&L.size>U&&(U=L.size,Z=_);if(U>=3){e-=.75;let _=Z.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${_}" searched ${U}\xD7 with different patterns (file already in context)`)}{let _=new Set,L=new Set,W=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let z of o){if(z.name==="write_file"&&z.input?.path){let R=z.input.path.split("/").pop(),H=z.input.path.includes("/tests/");W.test(R)&&!H&&_.add(z.input.path)}if((z.name==="bash"||z.name==="ssh_exec")&&z.input?.command){let R=z.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(R)for(let H of R){let se=H.split(/\s+/),D=se[se.length-1];for(let me of _)(me.endsWith(D)||D.endsWith(me.split("/").pop()))&&L.add(me)}}}let te=L.size;if(te>=1){let z=Math.min(te*.25,.5);e-=z;let R=[...L].map(H=>H.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${R} \u2014 write inline logic or use tests/ instead`)}}let ye=n.filter(_=>_.content.startsWith("EXIT")).length;ye>=10?(e-=1,s.push(`Bash exit-error storm: ${ye} tool results started with EXIT (repeated failing commands)`)):ye>=5&&(e-=.5,s.push(`Repeated bash errors: ${ye} tool results with non-zero exit code`));for(let _ of t){if(_.role!=="assistant")continue;let L="";if(typeof _.content=="string"?L=_.content:Array.isArray(_.content)&&(L=_.content.filter(D=>D&&(D.type==="text"||typeof D=="string")).map(D=>typeof D=="string"?D:D.text||"").join("")),L.length<=5e3)continue;let W=L.split(/(?<=\. )/).filter(D=>D.trim().length>0);if(W.length<6)continue;let te=new Map;for(let D=0;D<=W.length-3;D++){let me=W.slice(D,D+3).join("").trim();me.length>30&&te.set(me,(te.get(me)||0)+1)}let z=0,R="";for(let[D,me]of te)me>z&&(z=me,R=D);if(z<3)continue;let se=R.length*z/L.length;if(se>=.4||z>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${z}\xD7 same paragraph, ${Math.round(se*100)}% repeated)`);break}}{let _=new Set(["read_file","list_directory","search_files","glob","grep"]),L=t.some(te=>Array.isArray(te.tool_calls)?te.tool_calls.some(z=>_.has(z.function?.name)):Array.isArray(te.content)?te.content.some(z=>z.type==="tool_use"&&_.has(z.name)):!1);t.some(te=>te.role==="assistant"&&typeof te.content=="string"&&(te.content.includes("## Steps")||te.content.includes("/plan approve")))&&!L&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let ke=n.filter(_=>_.content.startsWith("BLOCKED:")&&!_.content.includes("BLOCKED: sed -n")&&!_.content.includes("SSH paused")&&!_.content.includes("SSH temporarily paused"));if(ke.length>0){let _=Math.min(ke.length*.5,1.5);e-=_,s.push(`${ke.length} tool call${ke.length===1?"":"s"} blocked (agent attempted denied actions)`)}let De=t.filter(_=>{let L=typeof _.content=="string"?_.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(L)}).length;if(De>0){let _=Math.min(De*1,2);e-=_,s.push(`Super-nuclear context wipe fired ${De}\xD7 (context collapse \u2014 task too large or read loops)`)}{let _=!1,L=!1,W=!1;for(let z of o){if(z.name!=="bash")continue;let R=(z.input?.command||z.input?.cmd||"").trim();!(/cat\s*>/.test(R)||/<</.test(R))&&/\bcat\s+\S/.test(R)&&(_=!0),/^\s*ls(\s|$)/.test(R)&&!/npm|yarn|pnpm|make|git\b/.test(R)&&(L=!0),/\bfind\s+\S/.test(R)&&!/git\b|npm\b|-exec\b/.test(R)&&(W=!0)}let te=[_,L,W].filter(Boolean).length;if(te>0){let z=Math.min(te*.25,.75);e-=z;let R=[];_&&R.push("cat (use read_file)"),L&&R.push("ls (use list_directory)"),W&&R.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${R.join(", ")}`)}}{let _=o.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&(R.input.path.endsWith("requirements.txt")||R.input.path.endsWith("Pipfile")||R.input.path.endsWith("pyproject.toml"))),L=o.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&R.input.path.endsWith("package.json")),W=o.filter(R=>(R.name==="bash"||R.name==="Bash")&&R.input?.command).map(R=>R.input.command),te=W.some(R=>/pip\s+install|python\s+-m\s+venv/.test(R)),z=W.some(R=>/npm\s+install/.test(R));_&&!te?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):L&&!z&&o.some(H=>(H.name==="write_file"||H.name==="Write")&&H.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(H.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(R=>R.role==="assistant"),L="";_&&(typeof _.content=="string"?L=_.content:Array.isArray(_.content)&&(L=_.content.filter(R=>R&&(R.type==="text"||typeof R=="string")).map(R=>typeof R=="string"?R:R.text||"").join("")));let W=L.slice(0,400),te=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,z=W.split(`
622
- `).find(R=>{let H=R.trim();return H.length>0&&H.length<=30&&/^\d/.test(H)&&/=/.test(H)&&!/[a-zA-Z]/.test(H)});if(te.test(W)||z){e-=1.5;let R=(z||W.split(`
623
- `)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${R}"`)}}if(d&&r>0){let _=t.findIndex(W=>W.role==="assistant"),L=t.findIndex(W=>!!(Array.isArray(W.tool_calls)&&W.tool_calls.length>0||Array.isArray(W.content)&&W.content.some(te=>te&&te.type==="tool_use")));if(_!==-1&&L!==-1&&_<L){let W=t[_],te="";typeof W.content=="string"?te=W.content:Array.isArray(W.content)&&(te=W.content.filter(H=>H&&(H.type==="text"||typeof H=="string")).map(H=>typeof H=="string"?H:H.text||"").join(""));let z=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(te),R=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(te);(z||R)&&(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 W=(_.match(/^```/gm)||[]).length%2!==0,te=/"\s*:\s*$/.test(_.trimEnd()),z=/[,\[{]\s*$/.test(_.trimEnd());(W||te||z)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let _=[];t.forEach((W,te)=>{let z=[];Array.isArray(W.tool_calls)&&W.tool_calls.forEach(R=>{if((R.function?.name||R.name||"")==="read_file"){let se={};try{se=typeof R.function?.arguments=="string"?JSON.parse(R.function.arguments):R.function?.arguments||{}}catch{}(se.path||"").endsWith(".json")&&z.push({id:R.id,path:se.path})}}),Array.isArray(W.content)&&W.content.forEach(R=>{R&&R.type==="tool_use"&&R.name==="read_file"&&(R.input?.path||"").endsWith(".json")&&z.push({id:R.id,path:R.input.path})}),z.forEach(R=>_.push({...R,msgIdx:te}))});let L=0;for(let W of _){let te=null;for(let R of t){if(R.role==="tool"&&R.tool_call_id===W.id&&typeof R.content=="string"){te=R.content;break}if(R.role==="user"&&Array.isArray(R.content)){let H=R.content.find(se=>se&&se.type==="tool_result"&&se.tool_use_id===W.id);if(H){te=typeof H.content=="string"?H.content:"";break}}}if(!te)continue;te.split(`
624
- `).filter(R=>R.trim()).length<5&&/^\s*\[/.test(te)&&!/\]\s*$/.test(te.trimEnd())&&L++}L>=1&&(e-=.75,s.push(`Shallow JSON read: ${L} .json file${L>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let _=n.filter(L=>/argument errors?/i.test(L.content)||/missing required (argument|parameter)/i.test(L.content)||/invalid argument/i.test(L.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,L=0,W=0;for(let te of a){if((te.name==="bash"||te.name==="Bash")&&te.input?.command&&/git\s+commit\b/.test(te.input.command)){_&&(W=Math.max(W,L)),_=!0,L=0;continue}_&&(te.name==="bash"||te.name==="Bash")&&te.input?.command&&/git\s+(status|diff|log|show)\b/.test(te.input.command)&&L++}W=Math.max(W,L),W>=3&&(e-=.75,s.push(`Post-commit verification waste: ${W} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Oe=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Se=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:Oe,issues:s,summary:Se}}function Uv(t){try{let{loadSession:e}=Wi(),s=e(t);return s?Zm(s.messages||[]):null}catch{return null}}function Wv(t,e=null){let{score:s,issues:o}=t,n=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(s>=8||o.length===0)return"";let a=o.map(c=>c.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(s>=6){let c=a.slice(0,3),d=a.length-c.length,f=c.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
625
- ${n}${f}${r}`}let l="";for(let c of a.slice(0,4))l+=`
626
- ${i}\u26A0${r} ${n}${c}${r}`;let u=a.length-4;return u>0&&(l+=`
627
- ${n}(+${u} more)${r}`),l}function Hv(t,e={}){try{let s=Ym.join(process.cwd(),".nex");er.existsSync(s)||er.mkdirSync(s,{recursive:!0});let o=Ym.join(s,"benchmark-history.json"),n=[];if(er.existsSync(o))try{n=JSON.parse(er.readFileSync(o,"utf-8"))}catch{n=[]}Array.isArray(n)||(n=[]);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:[]};n.push(i),n.length>100&&(n=n.slice(n.length-100)),er.writeFileSync(o,JSON.stringify(n,null,2))}catch{}}Qm.exports={scoreMessages:Zm,scoreSession:Uv,formatScore:Wv,appendScoreHistory:Hv,_extractToolCalls:zm,_extractToolResults:Km,_getLastAssistantText:Xm,_getLastNAssistantTexts:Vm,_countDuplicateToolCalls:Jm}});var sr=V((zC,rg)=>{"use strict";var Gv=require("os"),Oc=require("path"),Pn=require("fs"),tr=Oc.join(Gv.homedir(),".nex-code","model-routing.json"),Hi={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}},tg=["agentic","frontend","sysadmin","data","coding"];function Yv(t){if(!t||t.length<8)return null;for(let e of tg){let s=Hi[e];if(!s.pattern||s.pattern.test(t))return s}return Hi.coding}function nr(){try{if(Pn.existsSync(tr))return JSON.parse(Pn.readFileSync(tr,"utf-8"))}catch{}return{}}function ng(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=Hi[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:nr()[t]||null}var sg={explore:10,plan:10,implement:35,verify:8},Nc={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function og(){let t=nr();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=ut();if(e()==="ollama")return Nc}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Nc:null}function zv(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let s=og();return s?.[t]?s[t]:e?ng(e):null}function Kv(t){return nr().phaseBudgets?.[t]||sg[t]||20}function Xv(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:og()!==null}function Vv(t){let e=Oc.dirname(tr);Pn.existsSync(e)||Pn.mkdirSync(e,{recursive:!0});let s=nr(),o={...s,...t};!t.phases&&s.phases&&(o.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(o.phaseBudgets=s.phaseBudgets),Pn.writeFileSync(tr,JSON.stringify(o,null,2));try{let n=Oc.join(e,".env"),r="";Pn.existsSync(n)&&(r=Pn.readFileSync(n,"utf-8"));let i=r.split(/\r?\n/),a=(l,u)=>{let c=i.findIndex(d=>d.startsWith(l+"="));c>=0?i[c]=`${l}=${u}`:i.push(`${l}=${u}`)};o.coding&&a("NEX_ROUTE_CODING",o.coding),o.frontend&&a("NEX_ROUTE_FRONTEND",o.frontend),o.sysadmin&&a("NEX_ROUTE_SYSADMIN",o.sysadmin),o.data&&a("NEX_ROUTE_DATA",o.data),o.agentic&&a("NEX_ROUTE_AGENTIC",o.agentic),o.phases&&(o.phases.plan&&a("NEX_PHASE_PLAN_MODEL",o.phases.plan),o.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",o.phases.implement),o.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",o.phases.verify)),Pn.writeFileSync(n,i.filter(l=>l.trim()!=="").join(`
626
+ `);s.push(`MERGE CONFLICTS (resolve before editing these files):
627
+ ${u}`)}try{let u=Qv();u&&s.push(u)}catch{}return s.join(`
628
+
629
+ `)}async function wE(t){let e=Ye.join(t,"package.json"),n="";if(await fn(()=>$t.access(e).then(()=>!0).catch(()=>!1)))try{let i=await $t.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([fn(async()=>{let{stdout:i}=await Ui("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),cg()]);if(r&&r.length>0){console.log(`${Qs.red} \u26A0 ${r.length} unresolved merge conflict(s):${Qs.reset}`);for(let i of r)console.log(`${Qs.red} ${i.file}${Qs.reset}`);console.log(`${Qs.yellow} \u2192 Resolve conflicts before starting tasks${Qs.reset}`)}console.log()}ug.exports={gatherProjectContext:yE,printContext:wE,generateFileTree:pE,_clearContextCache:()=>{Mc.clear(),to.clear(),Hi=null,eo={result:null,expiry:0,cwd:null}}}});var Gi=Z((PA,pg)=>{var Zt=require("fs"),Yi=require("path"),{atomicWrite:$E}=Gn();function tr(){return Yi.join(process.cwd(),".nex","sessions")}function Lc(){let t=tr();Zt.existsSync(t)||Zt.mkdirSync(t,{recursive:!0,mode:448})}function Ic(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Yi.join(tr(),`${e}.json`)}function jc(t,e,n={}){Lc();let o=Ic(t),s={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return $E(o,JSON.stringify(s,null,2)),{path:o,name:t}}function fg(t){let e=Ic(t);if(!Zt.existsSync(e))return null;try{return JSON.parse(Zt.readFileSync(e,"utf-8"))}catch{return null}}function hg(){Lc();let t=tr(),e=Zt.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(Zt.readFileSync(Yi.join(t,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function bE(t){let e=Ic(t);return Zt.existsSync(e)?(Zt.unlinkSync(e),!0):!1}function _E(){let t=hg();return t.length===0?null:fg(t[0].name)}var us=null,vn=null,er=null;function xE(t,e={}){t.length!==0&&(us&&clearTimeout(us),vn=t,er=e||{},us=setTimeout(()=>{vn&&vn.length>0&&jc("_autosave",vn,er),us=null,vn=null,er=null},5e3))}function kE(){us&&(clearTimeout(us),us=null),vn&&vn.length>0&&(jc("_autosave",vn,er),vn=null,er=null)}function SE(){Lc();let t=tr(),e=Zt.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of e){let i=Yi.join(t,r);try{let a=Zt.statSync(i);new Date(a.mtime)<o&&(Zt.unlinkSync(i),s++)}catch{}}return s}pg.exports={saveSession:jc,loadSession:fg,listSessions:hg,deleteSession:bE,getLastSession:_E,autoSave:xE,flushAutoSave:kE,clearOldSessions:SE,_getSessionsDir:tr}});var kg=Z((MA,xg)=>{"use strict";var nr=require("fs"),mg=require("path");function gg(t){let e=[];return t.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&e.push({name:s.name||"",input:s.input||{},index:o,id:s.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}e.push({name:r,input:i,index:o,id:s.id||null})}))}),e}function vE(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function yg(t){let e=[];return t.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");e.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:s,index:o})}}),e}function wg(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function $g(t,e){let n=[];for(let o=t.length-1;o>=0&&n.length<e;o--){let s=t[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function bg(t){let e=new Map;for(let n of t){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;e.set(s,(e.get(s)||0)+1)}return e}function _g(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,n=[],o=gg(t),s=yg(t),r=o.length,i=vE(t),a=o.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,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=o.find(_=>{let M=_.input?.command||_.input?.cmd||"";return/\bsed\s+-n\b/.test(M)});if(u){let _=(u.input?.command||u.input?.cmd||"").slice(0,80);s.some(F=>F.content.includes("BLOCKED: sed -n is forbidden")||F.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${_}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${_}`))}o.find(_=>{if(_.name!=="grep"&&_.name!=="bash"&&_.name!=="ssh_exec")return!1;let M=_.input?.command||_.input?.cmd||"",F=_.input?.pattern||"",ee=`${M} ${F}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(ee)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(ee)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let d=t.some(_=>_.role==="assistant"),f=wg(t),m=$g(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)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${_}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(_=>{let M=typeof _.content=="string"?_.content:Array.isArray(_.content)?_.content.map(F=>typeof F=="string"?F:F.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(M)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let x=bg(a),E=0,N="";for(let[_,M]of x)M>E&&(E=M,N=_);if(E>=3){let[_]=N.split("|");e-=1,n.push(`Same tool call repeated ${E}\xD7 (tool: ${_})`)}let v=!1,S=t.findIndex(_=>_.role==="user"&&typeof _.content=="string"&&_.content.includes("[SYSTEM STOP]")&&_.content.includes('"valid":true'));S>=0&&o.filter(M=>M.index>S).length>0&&(v=!0),v&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let P=o.filter(_=>_.name==="ssh_exec");if(P.length>=8){let _=0,M=1;for(let F=1;F<P.length;F++)P[F].index<=P[F-1].index+2?M++:(_=Math.max(_,M),M=1);_=Math.max(_,M),_>=8&&(e-=.5,n.push(`SSH reconnect storm: ${_} consecutive SSH calls`))}d&&P.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,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let ne=new Map;for(let _ of a)if(_.name==="read_file"&&_.input?.path){let M=_.input.path;ne.has(M)||ne.set(M,{count:0,ranges:[]});let F=ne.get(M);if(F.count++,_.input.line_start!=null){let ee=_.input.line_start||1,K=_.input.line_end||ee+350;F.ranges.push([ee,K])}}function re(_,M,F){for(let[ee,K]of F){let C=Math.max(_,ee),he=Math.min(M,K);if(he>C){let H=he-C,se=M-_||1;if(H/se>=.7)return!0}}return!1}let ce=0,de="";for(let[_,M]of ne){if(M.count<3)continue;if(M.ranges.length===M.count){let K=!1,C=[];for(let[he,H]of M.ranges){if(C.length>0&&re(he,H,C)){K=!0;break}C.push([he,H])}if(!K)continue}if(M.count-M.ranges.length<=2&&M.ranges.length>=1){let K=!1,C=[];for(let[he,H]of M.ranges){if(C.length>0&&re(he,H,C)){K=!0;break}C.push([he,H])}if(!K)continue}M.count>ce&&(ce=M.count,de=_)}if(ce>=3){e-=1;let _=de.split("/").slice(-2).join("/");n.push(`read_file loop: "${_}" read ${ce}\xD7 (file already in context)`)}let oe=0,le="";for(let[_,M]of ne){if(M.ranges.length<4)continue;let F=[],ee=!1;for(let[K,C]of M.ranges){if(F.length>0&&re(K,C,F)){ee=!0;break}F.push([K,C])}!ee&&M.ranges.length>oe&&(oe=M.ranges.length,le=_)}if(oe>=4){e-=.5;let _=le.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${_}" read in ${oe} sequential sections \u2014 use grep instead`)}let T=new Map;for(let _ of a)if(_.name==="grep"&&_.input?.path&&_.input?.pattern){let M=_.input.path;T.has(M)||T.set(M,new Set),T.get(M).add(_.input.pattern)}let q=0,Q="";for(let[_,M]of T)_.split("/").pop().includes(".")&&M.size>q&&(q=M.size,Q=_);if(q>=3){e-=.75;let _=Q.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${_}" searched ${q}\xD7 with different patterns (file already in context)`)}{let _=new Set,M=new Set,F=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let K of o){if(K.name==="write_file"&&K.input?.path){let C=K.input.path.split("/").pop(),he=K.input.path.includes("/tests/");F.test(C)&&!he&&_.add(K.input.path)}if((K.name==="bash"||K.name==="ssh_exec")&&K.input?.command){let C=K.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(C)for(let he of C){let H=he.split(/\s+/),se=H[H.length-1];for(let J of _)(J.endsWith(se)||se.endsWith(J.split("/").pop()))&&M.add(J)}}}let ee=M.size;if(ee>=1){let K=Math.min(ee*.25,.5);e-=K;let C=[...M].map(he=>he.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${C} \u2014 write inline logic or use tests/ instead`)}}let we=s.filter(_=>_.content.startsWith("EXIT")).length;we>=10?(e-=1,n.push(`Bash exit-error storm: ${we} tool results started with EXIT (repeated failing commands)`)):we>=5&&(e-=.5,n.push(`Repeated bash errors: ${we} tool results with non-zero exit code`));for(let _ of t){if(_.role!=="assistant")continue;let M="";if(typeof _.content=="string"?M=_.content:Array.isArray(_.content)&&(M=_.content.filter(se=>se&&(se.type==="text"||typeof se=="string")).map(se=>typeof se=="string"?se:se.text||"").join("")),M.length<=5e3)continue;let F=M.split(/(?<=\. )/).filter(se=>se.trim().length>0);if(F.length<6)continue;let ee=new Map;for(let se=0;se<=F.length-3;se++){let J=F.slice(se,se+3).join("").trim();J.length>30&&ee.set(J,(ee.get(J)||0)+1)}let K=0,C="";for(let[se,J]of ee)J>K&&(K=J,C=se);if(K<3)continue;let H=C.length*K/M.length;if(H>=.4||K>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${K}\xD7 same paragraph, ${Math.round(H*100)}% repeated)`);break}}{let _=new Set(["read_file","list_directory","search_files","glob","grep"]),M=t.some(ee=>Array.isArray(ee.tool_calls)?ee.tool_calls.some(K=>_.has(K.function?.name)):Array.isArray(ee.content)?ee.content.some(K=>K.type==="tool_use"&&_.has(K.name)):!1);t.some(ee=>ee.role==="assistant"&&typeof ee.content=="string"&&(ee.content.includes("## Steps")||ee.content.includes("/plan approve")))&&!M&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let ke=s.filter(_=>_.content.startsWith("BLOCKED:")&&!_.content.includes("BLOCKED: sed -n")&&!_.content.includes("SSH paused")&&!_.content.includes("SSH temporarily paused"));if(ke.length>0){let _=Math.min(ke.length*.5,1.5);e-=_,n.push(`${ke.length} tool call${ke.length===1?"":"s"} blocked (agent attempted denied actions)`)}let qe=t.filter(_=>{let M=typeof _.content=="string"?_.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(M)}).length;if(qe>0){let _=Math.min(qe*1,2);e-=_,n.push(`Super-nuclear context wipe fired ${qe}\xD7 (context collapse \u2014 task too large or read loops)`)}{let _=!1,M=!1,F=!1;for(let K of o){if(K.name!=="bash")continue;let C=(K.input?.command||K.input?.cmd||"").trim();!(/cat\s*>/.test(C)||/<</.test(C))&&/\bcat\s+\S/.test(C)&&(_=!0),/^\s*ls(\s|$)/.test(C)&&!/npm|yarn|pnpm|make|git\b/.test(C)&&(M=!0),/\bfind\s+\S/.test(C)&&!/git\b|npm\b|-exec\b/.test(C)&&(F=!0)}let ee=[_,M,F].filter(Boolean).length;if(ee>0){let K=Math.min(ee*.25,.75);e-=K;let C=[];_&&C.push("cat (use read_file)"),M&&C.push("ls (use list_directory)"),F&&C.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${C.join(", ")}`)}}{let _=o.some(C=>(C.name==="write_file"||C.name==="Write")&&C.input?.path&&(C.input.path.endsWith("requirements.txt")||C.input.path.endsWith("Pipfile")||C.input.path.endsWith("pyproject.toml"))),M=o.some(C=>(C.name==="write_file"||C.name==="Write")&&C.input?.path&&C.input.path.endsWith("package.json")),F=o.filter(C=>(C.name==="bash"||C.name==="Bash")&&C.input?.command).map(C=>C.input.command),ee=F.some(C=>/pip\s+install|python\s+-m\s+venv/.test(C)),K=F.some(C=>/npm\s+install/.test(C));_&&!ee?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):M&&!K&&o.some(he=>(he.name==="write_file"||he.name==="Write")&&he.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(he.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let _=t.find(C=>C.role==="assistant"),M="";_&&(typeof _.content=="string"?M=_.content:Array.isArray(_.content)&&(M=_.content.filter(C=>C&&(C.type==="text"||typeof C=="string")).map(C=>typeof C=="string"?C:C.text||"").join("")));let F=M.slice(0,400),ee=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,K=F.split(`
630
+ `).find(C=>{let he=C.trim();return he.length>0&&he.length<=30&&/^\d/.test(he)&&/=/.test(he)&&!/[a-zA-Z]/.test(he)});if(ee.test(F)||K){e-=1.5;let C=(K||F.split(`
631
+ `)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${C}"`)}}if(d&&r>0){let _=t.findIndex(F=>F.role==="assistant"),M=t.findIndex(F=>!!(Array.isArray(F.tool_calls)&&F.tool_calls.length>0||Array.isArray(F.content)&&F.content.some(ee=>ee&&ee.type==="tool_use")));if(_!==-1&&M!==-1&&_<M){let F=t[_],ee="";typeof F.content=="string"?ee=F.content:Array.isArray(F.content)&&(ee=F.content.filter(he=>he&&(he.type==="text"||typeof he=="string")).map(he=>typeof he=="string"?he:he.text||"").join(""));let K=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(ee),C=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(ee);(K||C)&&(e-=1,n.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 F=(_.match(/^```/gm)||[]).length%2!==0,ee=/"\s*:\s*$/.test(_.trimEnd()),K=/[,\[{]\s*$/.test(_.trimEnd());(F||ee||K)&&(e-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let _=[];t.forEach((F,ee)=>{let K=[];Array.isArray(F.tool_calls)&&F.tool_calls.forEach(C=>{if((C.function?.name||C.name||"")==="read_file"){let H={};try{H=typeof C.function?.arguments=="string"?JSON.parse(C.function.arguments):C.function?.arguments||{}}catch{}(H.path||"").endsWith(".json")&&K.push({id:C.id,path:H.path})}}),Array.isArray(F.content)&&F.content.forEach(C=>{C&&C.type==="tool_use"&&C.name==="read_file"&&(C.input?.path||"").endsWith(".json")&&K.push({id:C.id,path:C.input.path})}),K.forEach(C=>_.push({...C,msgIdx:ee}))});let M=0;for(let F of _){let ee=null;for(let C of t){if(C.role==="tool"&&C.tool_call_id===F.id&&typeof C.content=="string"){ee=C.content;break}if(C.role==="user"&&Array.isArray(C.content)){let he=C.content.find(H=>H&&H.type==="tool_result"&&H.tool_use_id===F.id);if(he){ee=typeof he.content=="string"?he.content:"";break}}}if(!ee)continue;ee.split(`
632
+ `).filter(C=>C.trim()).length<5&&/^\s*\[/.test(ee)&&!/\]\s*$/.test(ee.trimEnd())&&M++}M>=1&&(e-=.75,n.push(`Shallow JSON read: ${M} .json file${M>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let _=s.filter(M=>/argument errors?/i.test(M.content)||/missing required (argument|parameter)/i.test(M.content)||/invalid argument/i.test(M.content));_.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${_.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):_.length>=2&&(e-=.25,n.push(`Tool argument errors: ${_.length} tool calls returned argument errors`))}{let _=!1,M=0,F=0;for(let ee of a){if((ee.name==="bash"||ee.name==="Bash")&&ee.input?.command&&/git\s+commit\b/.test(ee.input.command)){_&&(F=Math.max(F,M)),_=!0,M=0;continue}_&&(ee.name==="bash"||ee.name==="Bash")&&ee.input?.command&&/git\s+(status|diff|log|show)\b/.test(ee.input.command)&&M++}F=Math.max(F,M),F>=3&&(e-=.75,n.push(`Post-commit verification waste: ${F} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Ne=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",ve=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:Ne,issues:n,summary:ve}}function EE(t){try{let{loadSession:e}=Gi(),n=e(t);return n?_g(n.messages||[]):null}catch{return null}}function TE(t,e=null){let{score:n,issues:o}=t,s=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(n>=8||o.length===0)return"";let a=o.map(c=>c.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(n>=6){let c=a.slice(0,3),d=a.length-c.length,f=c.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
633
+ ${s}${f}${r}`}let l="";for(let c of a.slice(0,4))l+=`
634
+ ${i}\u26A0${r} ${s}${c}${r}`;let u=a.length-4;return u>0&&(l+=`
635
+ ${s}(+${u} more)${r}`),l}function RE(t,e={}){try{let n=mg.join(process.cwd(),".nex");nr.existsSync(n)||nr.mkdirSync(n,{recursive:!0});let o=mg.join(n,"benchmark-history.json"),s=[];if(nr.existsSync(o))try{s=JSON.parse(nr.readFileSync(o,"utf-8"))}catch{s=[]}Array.isArray(s)||(s=[]);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:[]};s.push(i),s.length>100&&(s=s.slice(s.length-100)),nr.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}xg.exports={scoreMessages:_g,scoreSession:EE,formatScore:TE,appendScoreHistory:RE,_extractToolCalls:gg,_extractToolResults:yg,_getLastAssistantText:wg,_getLastNAssistantTexts:$g,_countDuplicateToolCalls:bg}});var rr=Z((LA,Rg)=>{"use strict";var CE=require("os"),Dc=require("path"),In=require("fs"),sr=Dc.join(CE.homedir(),".nex-code","model-routing.json"),zi={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}},Sg=["agentic","frontend","sysadmin","data","coding"];function AE(t){if(!t||t.length<8)return null;for(let e of Sg){let n=zi[e];if(!n.pattern||n.pattern.test(t))return n}return zi.coding}function or(){try{if(In.existsSync(sr))return JSON.parse(In.readFileSync(sr,"utf-8"))}catch{}return{}}function vg(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=zi[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:or()[t]||null}var Eg={explore:10,plan:10,implement:35,verify:8},qc={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Tg(){let t=or();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=dt();if(e()==="ollama")return qc}catch{}return process.env.NEX_PHASE_ROUTING==="1"?qc:null}function OE(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let n=Tg();return n?.[t]?n[t]:e?vg(e):null}function NE(t){return or().phaseBudgets?.[t]||Eg[t]||20}function PE(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:Tg()!==null}function ME(t){let e=Dc.dirname(sr);In.existsSync(e)||In.mkdirSync(e,{recursive:!0});let n=or(),o={...n,...t};!t.phases&&n.phases&&(o.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(o.phaseBudgets=n.phaseBudgets),In.writeFileSync(sr,JSON.stringify(o,null,2));try{let s=Dc.join(e,".env"),r="";In.existsSync(s)&&(r=In.readFileSync(s,"utf-8"));let i=r.split(/\r?\n/),a=(l,u)=>{let c=i.findIndex(d=>d.startsWith(l+"="));c>=0?i[c]=`${l}=${u}`:i.push(`${l}=${u}`)};o.coding&&a("NEX_ROUTE_CODING",o.coding),o.frontend&&a("NEX_ROUTE_FRONTEND",o.frontend),o.sysadmin&&a("NEX_ROUTE_SYSADMIN",o.sysadmin),o.data&&a("NEX_ROUTE_DATA",o.data),o.agentic&&a("NEX_ROUTE_AGENTIC",o.agentic),o.phases&&(o.phases.plan&&a("NEX_PHASE_PLAN_MODEL",o.phases.plan),o.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",o.phases.implement),o.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",o.phases.verify)),In.writeFileSync(s,i.filter(l=>l.trim()!=="").join(`
628
636
  `)+`
629
- `)}catch{}}rg.exports={CATEGORIES:Hi,DETECTION_ORDER:tg,detectCategory:Yv,getModelForCategory:ng,getModelForPhase:zv,getPhaseBudget:Kv,isPhaseRoutingEnabled:Xv,DEFAULT_PHASE_BUDGETS:sg,BUILTIN_PHASE_DEFAULTS:Nc,saveRoutingConfig:Vv,loadRoutingConfig:nr,ROUTING_CONFIG_PATH:tr}});var cg=V((KC,lg)=>{"use strict";var us=require("fs"),or=require("path"),Jv=require("os"),{detectCategory:Zv}=sr(),Js=or.join(Jv.homedir(),".nex-code","examples"),Mc=or.join(__dirname,"..","examples");function ig(t){try{let s=us.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),o=s.match(/^user:\s*(.+)$/m);if(!o)return null;let n=o[1].trim(),r=s.indexOf(`
630
- A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],l=0;for(let c of i.split(`
637
+ `)}catch{}}Rg.exports={CATEGORIES:zi,DETECTION_ORDER:Sg,detectCategory:AE,getModelForCategory:vg,getModelForPhase:OE,getPhaseBudget:NE,isPhaseRoutingEnabled:PE,DEFAULT_PHASE_BUDGETS:Eg,BUILTIN_PHASE_DEFAULTS:qc,saveRoutingConfig:ME,loadRoutingConfig:or,ROUTING_CONFIG_PATH:sr}});var Ng=Z((IA,Og)=>{"use strict";var ds=require("fs"),ir=require("path"),LE=require("os"),{detectCategory:IE}=rr(),no=ir.join(LE.homedir(),".nex-code","examples"),Fc=ir.join(__dirname,"..","examples");function Cg(t){try{let n=ds.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),o=n.match(/^user:\s*(.+)$/m);if(!o)return null;let s=o[1].trim(),r=n.indexOf(`
638
+ A: |`);if(r===-1)return null;let i=n.slice(r+5),a=[],l=0;for(let c of i.split(`
631
639
  `))if(c.startsWith(" ")){for(;l>0;)a.push(""),l--;a.push(c.slice(2))}else if(c.trim()==="")a.length>0&&l++;else break;if(a.length===0)return null;let u=a.join(`
632
- `).trim();return{user:n,assistant:u}}catch{return null}}function ag(t){let e=`${t}.md`,s=or.join(Js,e);if(us.existsSync(s)){let n=ig(s);if(n)return n}let o=or.join(Mc,e);return us.existsSync(o)?ig(o):null}function Qv(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=Zv(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:ag(e.id)}function eE(){let t=new Set;for(let e of[Js,Mc])try{for(let s of us.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function tE(t,e){us.existsSync(Js)||us.mkdirSync(Js,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
640
+ `).trim();return{user:s,assistant:u}}catch{return null}}function Ag(t){let e=`${t}.md`,n=ir.join(no,e);if(ds.existsSync(n)){let s=Cg(n);if(s)return s}let o=ir.join(Fc,e);return ds.existsSync(o)?Cg(o):null}function jE(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=IE(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:Ag(e.id)}function DE(){let t=new Set;for(let e of[no,Fc])try{for(let n of ds.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function qE(t,e){ds.existsSync(no)||ds.mkdirSync(no,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
633
641
 
634
642
  user: ${e.user}
635
643
 
@@ -637,14 +645,14 @@ A: |
637
645
  ${e.assistant.split(`
638
646
  `).map(o=>` ${o}`).join(`
639
647
  `)}
640
- `;us.writeFileSync(or.join(Js,`${t}.md`),s,"utf-8")}lg.exports={getFewShotForInput:Qv,loadExampleForCategory:ag,listAvailableExamples:eE,savePrivateExample:tE,PRIVATE_EXAMPLES_DIR:Js,BUNDLED_EXAMPLES_DIR:Mc}});var mg=V((VC,pg)=>{var Ct=require("fs"),Zs=require("path"),{C:XC}=ot(),{atomicWrite:nE,withFileLockSync:sE}=Gn(),Gi={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"},Qs={...Gi};function ug(){let t=Zs.join(process.cwd(),".nex","config.json");if(Ct.existsSync(t))try{let e=JSON.parse(Ct.readFileSync(t,"utf-8"));e.permissions&&(Qs={...Gi,...e.permissions})}catch{}}function oE(){let t=Zs.join(process.cwd(),".nex"),e=Zs.join(t,"config.json");Ct.existsSync(t)||Ct.mkdirSync(t,{recursive:!0}),sE(e,()=>{let s={};if(Ct.existsSync(e))try{s=JSON.parse(Ct.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Qs,nE(e,JSON.stringify(s,null,2))})}function dg(t){return Qs[t]||"ask"}function rE(t,e){return["allow","ask","deny"].includes(e)?(Qs[t]=e,!0):!1}function iE(t){return dg(t)}function aE(){return Object.entries(Qs).map(([t,e])=>({tool:t,mode:e}))}function lE(){Qs={...Gi}}var rr={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 fg(){let t=Zs.join(process.cwd(),".nex","config.json");try{return Ct.existsSync(t)&&JSON.parse(Ct.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function cE(t){let e=Zs.join(process.cwd(),".nex"),s=Zs.join(e,"config.json");Ct.existsSync(e)||Ct.mkdirSync(e,{recursive:!0});let o={};try{Ct.existsSync(s)&&(o=JSON.parse(Ct.readFileSync(s,"utf-8")))}catch{o={}}o.teamPermissions=t,Ct.writeFileSync(s,JSON.stringify(o,null,2),"utf-8")}function hg(){let t=fg();if(!t)return rr.admin;let e=t.role||"admin",s=rr[e]||rr.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function uE(t){let e=hg();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 dE(){return Object.entries(rr).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}ug();pg.exports={getPermission:dg,setPermission:rE,checkPermission:iE,listPermissions:aE,loadPermissions:ug,savePermissions:oE,resetPermissions:lE,DEFAULT_PERMISSIONS:Gi,PERMISSION_PRESETS:rr,loadPresetConfig:fg,savePresetConfig:cE,getEffectivePreset:hg,isToolAllowed:uE,listPresets:dE}});var Ki=V((ZC,bg)=>{var fs=require("fs"),Yi=require("path"),JC=require("readline"),{C:Me}=ot(),Re=null,Lc=!1,Ic=null,gg=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function zi(){return Yi.join(process.cwd(),".nex","plans")}function yg(){let t=zi();fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0})}function fE(t,e=[]){return Re={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()},Re}function hE(){return Re}function pE(t){Lc=t}function mE(){return Lc}function gE(){return!Re||Re.status!=="draft"?!1:(Re.status="approved",Re.updatedAt=new Date().toISOString(),!0)}function yE(){return!Re||Re.status!=="approved"?!1:(Re.status="executing",!0)}function Pc(t,e){return!Re||t<0||t>=Re.steps.length?!1:(Re.steps[t].status=e,Re.updatedAt=new Date().toISOString(),Re.steps.every(s=>s.status==="done"||s.status==="skipped")&&(Re.status="completed"),!0)}function wE(t){if(!t)return`${Me.dim}No active plan${Me.reset}`;let e={draft:`${Me.yellow}DRAFT${Me.reset}`,approved:`${Me.green}APPROVED${Me.reset}`,executing:`${Me.blue}EXECUTING${Me.reset}`,completed:`${Me.green}COMPLETED${Me.reset}`},s=[];s.push(`
641
- ${Me.bold}${Me.cyan}Plan: ${t.task}${Me.reset}`),s.push(`${Me.dim}Status: ${e[t.status]||t.status}${Me.reset}
642
- `);for(let o=0;o<t.steps.length;o++){let n=t.steps[o],r;switch(n.status){case"done":r=`${Me.green}\u2713${Me.reset}`;break;case"in_progress":r=`${Me.blue}\u2192${Me.reset}`;break;case"skipped":r=`${Me.dim}\u25CB${Me.reset}`;break;default:r=`${Me.dim} ${Me.reset}`}s.push(` ${r} ${Me.bold}Step ${o+1}:${Me.reset} ${n.description}`),n.files.length>0&&s.push(` ${Me.dim}Files: ${n.files.join(", ")}${Me.reset}`)}return s.push(""),s.join(`
643
- `)}function $E(t){if(t||(t=Re),!t)return null;yg();let e=Yi.join(zi(),`${t.name}.json`);return fs.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function bE(t){let e=Yi.join(zi(),`${t}.json`);if(!fs.existsSync(e))return null;try{let s=JSON.parse(fs.readFileSync(e,"utf-8"));return Re=s,s}catch{return null}}function _E(){yg();let t=zi(),e=fs.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(fs.readFileSync(Yi.join(t,o),"utf-8"));s.push({name:n.name,task:n.task,status:n.status,steps:n.steps?n.steps.length:0,createdAt:n.createdAt})}catch{}return s.sort((o,n)=>(n.createdAt||"").localeCompare(o.createdAt||""))}function kE(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=s?s[1]:t,n=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=n.exec(o))!==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 u=a[l][1];e[l].files=u.split(/[,\s]+/).filter(c=>/[./]/.test(c)).slice(0,5)}}return e}function xE(t){Ic=t}function SE(){return Ic}function vE(){Re=null,Lc=!1,Ic=null,CE()}function EE(){return`
648
+ `;ds.writeFileSync(ir.join(no,`${t}.md`),n,"utf-8")}Og.exports={getFewShotForInput:jE,loadExampleForCategory:Ag,listAvailableExamples:DE,savePrivateExample:qE,PRIVATE_EXAMPLES_DIR:no,BUNDLED_EXAMPLES_DIR:Fc}});var Dg=Z((DA,jg)=>{var At=require("fs"),so=require("path"),{C:jA}=it(),{atomicWrite:FE,withFileLockSync:BE}=Gn(),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"},oo={...Ki};function Pg(){let t=so.join(process.cwd(),".nex","config.json");if(At.existsSync(t))try{let e=JSON.parse(At.readFileSync(t,"utf-8"));e.permissions&&(oo={...Ki,...e.permissions})}catch{}}function UE(){let t=so.join(process.cwd(),".nex"),e=so.join(t,"config.json");At.existsSync(t)||At.mkdirSync(t,{recursive:!0}),BE(e,()=>{let n={};if(At.existsSync(e))try{n=JSON.parse(At.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=oo,FE(e,JSON.stringify(n,null,2))})}function Mg(t){return oo[t]||"ask"}function WE(t,e){return["allow","ask","deny"].includes(e)?(oo[t]=e,!0):!1}function HE(t){return Mg(t)}function YE(){return Object.entries(oo).map(([t,e])=>({tool:t,mode:e}))}function GE(){oo={...Ki}}var ar={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 Lg(){let t=so.join(process.cwd(),".nex","config.json");try{return At.existsSync(t)&&JSON.parse(At.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function zE(t){let e=so.join(process.cwd(),".nex"),n=so.join(e,"config.json");At.existsSync(e)||At.mkdirSync(e,{recursive:!0});let o={};try{At.existsSync(n)&&(o=JSON.parse(At.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,At.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function Ig(){let t=Lg();if(!t)return ar.admin;let e=t.role||"admin",n=ar[e]||ar.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function KE(t){let e=Ig();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(ar).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}Pg();jg.exports={getPermission:Mg,setPermission:WE,checkPermission:HE,listPermissions:YE,loadPermissions:Pg,savePermissions:UE,resetPermissions:GE,DEFAULT_PERMISSIONS:Ki,PERMISSION_PRESETS:ar,loadPresetConfig:Lg,savePresetConfig:zE,getEffectivePreset:Ig,isToolAllowed:KE,listPresets:XE}});var Ji=Z((FA,Wg)=>{var hs=require("fs"),Xi=require("path"),qA=require("readline"),{C:Me}=it(),Ae=null,Uc=!1,Wc=null,qg=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Vi(){return Xi.join(process.cwd(),".nex","plans")}function Fg(){let t=Vi();hs.existsSync(t)||hs.mkdirSync(t,{recursive:!0})}function VE(t,e=[]){return Ae={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(n=>({description:n.description||n,files:n.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Ae}function JE(){return Ae}function ZE(t){Uc=t}function QE(){return Uc}function eT(){return!Ae||Ae.status!=="draft"?!1:(Ae.status="approved",Ae.updatedAt=new Date().toISOString(),!0)}function tT(){return!Ae||Ae.status!=="approved"?!1:(Ae.status="executing",!0)}function Bc(t,e){return!Ae||t<0||t>=Ae.steps.length?!1:(Ae.steps[t].status=e,Ae.updatedAt=new Date().toISOString(),Ae.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Ae.status="completed"),!0)}function nT(t){if(!t)return`${Me.dim}No active plan${Me.reset}`;let e={draft:`${Me.yellow}DRAFT${Me.reset}`,approved:`${Me.green}APPROVED${Me.reset}`,executing:`${Me.blue}EXECUTING${Me.reset}`,completed:`${Me.green}COMPLETED${Me.reset}`},n=[];n.push(`
649
+ ${Me.bold}${Me.cyan}Plan: ${t.task}${Me.reset}`),n.push(`${Me.dim}Status: ${e[t.status]||t.status}${Me.reset}
650
+ `);for(let o=0;o<t.steps.length;o++){let s=t.steps[o],r;switch(s.status){case"done":r=`${Me.green}\u2713${Me.reset}`;break;case"in_progress":r=`${Me.blue}\u2192${Me.reset}`;break;case"skipped":r=`${Me.dim}\u25CB${Me.reset}`;break;default:r=`${Me.dim} ${Me.reset}`}n.push(` ${r} ${Me.bold}Step ${o+1}:${Me.reset} ${s.description}`),s.files.length>0&&n.push(` ${Me.dim}Files: ${s.files.join(", ")}${Me.reset}`)}return n.push(""),n.join(`
651
+ `)}function sT(t){if(t||(t=Ae),!t)return null;Fg();let e=Xi.join(Vi(),`${t.name}.json`);return hs.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function oT(t){let e=Xi.join(Vi(),`${t}.json`);if(!hs.existsSync(e))return null;try{let n=JSON.parse(hs.readFileSync(e,"utf-8"));return Ae=n,n}catch{return null}}function rT(){Fg();let t=Vi(),e=hs.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(hs.readFileSync(Xi.join(t,o),"utf-8"));n.push({name:s.name,task:s.task,status:s.status,steps:s.steps?s.steps.length:0,createdAt:s.createdAt})}catch{}return n.sort((o,s)=>(s.createdAt||"").localeCompare(o.createdAt||""))}function iT(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=n?n[1]:t,s=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=s.exec(o))!==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 u=a[l][1];e[l].files=u.split(/[,\s]+/).filter(c=>/[./]/.test(c)).slice(0,5)}}return e}function aT(t){Wc=t}function lT(){return Wc}function cT(){Ae=null,Uc=!1,Wc=null,hT()}function uT(){return`
644
652
  PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
645
653
 
646
654
  # Allowed Tools (read-only)
647
- You may ONLY use these tools: ${[...gg].join(", ")}
655
+ You may ONLY use these tools: ${[...qg].join(", ")}
648
656
  Any other tool call will be blocked and returned with an error.
649
657
 
650
658
  # MANDATORY: Read Before You Plan
@@ -696,26 +704,26 @@ Bullet list of potential issues and mitigations.
696
704
  - Order steps by dependency (later steps may depend on earlier ones).
697
705
  - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
698
706
  - Do NOT make any file changes \u2014 your role is analysis and planning only.
699
- - 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 ds=0;function TE(){!Re||Re.status!=="executing"||(ds>0&&Pc(ds-1,"done"),ds<Re.steps.length&&(Pc(ds,"in_progress"),ds++))}function RE(){if(!Re||Re.status!=="executing"||Re.steps.length===0)return null;let t=Math.min(ds,Re.steps.length),e=Re.steps.length,s=Math.max(0,t-1),o=Re.steps[s]?.description||"";return{current:t,total:e,description:o}}function CE(){ds=0}var wg=["interactive","semi-auto","autonomous"],$g="interactive";function AE(t){return wg.includes(t)?($g=t,!0):!1}function OE(){return $g}bg.exports={createPlan:fE,getActivePlan:hE,setPlanMode:pE,isPlanMode:mE,approvePlan:gE,startExecution:yE,updateStep:Pc,formatPlan:wE,savePlan:$E,loadPlan:bE,listPlans:_E,clearPlan:vE,getPlanModePrompt:EE,setPlanContent:xE,getPlanContent:SE,extractStepsFromText:kE,advancePlanStep:TE,getPlanStepInfo:RE,PLAN_MODE_ALLOWED_TOOLS:gg,setAutonomyLevel:AE,getAutonomyLevel:OE,AUTONOMY_LEVELS:wg}});var Og=V((QC,Ag)=>{var{C:x}=ot();function _g(){return Math.max(10,(process.stdout.columns||80)-2)}function NE(t){if(!t)return"";let e=t.split(`
700
- `),s=[],o=!1,n="";for(let r of e){let i=_g();if(r.trim().startsWith("```")){if(o)s.push(`${x.dim}${"\u2500".repeat(40)}${x.reset}`),o=!1,n="";else{o=!0,n=r.trim().substring(3).trim();let a=n?` ${n} `:"";s.push(`${x.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${x.reset}`)}continue}if(o){s.push(` ${Dc(r,n)}`);continue}if(r.startsWith("###### ")){s.push(`${x.bold}${x.cyan} ${At(r.substring(7))}${x.reset}`);continue}if(r.startsWith("##### ")){s.push(`${x.bold}${x.cyan} ${At(r.substring(6))}${x.reset}`);continue}if(r.startsWith("#### ")){s.push(`${x.bold}${x.cyan} ${At(r.substring(5))}${x.reset}`);continue}if(r.startsWith("### ")){s.push(`${x.bold}${x.cyan} ${At(r.substring(4))}${x.reset}`);continue}if(r.startsWith("## ")){s.push(`${x.bold}${x.cyan} ${At(r.substring(3))}${x.reset}`);continue}if(r.startsWith("# ")){s.push(`${x.bold}${x.cyan}${At(r.substring(2))}${x.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),u=`${a}${x.cyan}\u2022${x.reset} ${hs(l)}`;s.push(ps(u,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let l=a[1],u=a[2],c=a[3],d=`${l}${x.cyan}${u}.${x.reset} ${hs(c)}`,f=l+" ".repeat(u.length+2);s.push(ps(d,i,f));continue}}s.push(ps(hs(r),i))}return s.join(`
701
- `)}function At(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function hs(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 Dc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?kg(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?xg(t):e==="json"||e==="jsonc"?Sg(t):e==="python"||e==="py"?vg(t):e==="go"||e==="golang"?Eg(t):e==="rust"||e==="rs"?Tg(t):e==="css"||e==="scss"||e==="less"?Rg(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Cg(t):t:""}function kg(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,o=/(\/\/.*$)/,n=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(n,`${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(o,`${x.dim}$1${x.reset}`),r}function xg(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(#.*$)/,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(o,`${x.yellow}$&${x.reset}`),r=r.replace(n,`${x.dim}$1${x.reset}`),r}function Sg(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,o=/:\s*(\d+\.?\d*)/g,n=/:\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(o,`: ${x.yellow}$1${x.reset}`),r=r.replace(n,`: ${x.magenta}$1${x.reset}`),r}function vg(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,o=/(#.*$)/,n=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(n,`${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(o,`${x.dim}$1${x.reset}`),i}function Eg(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,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,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(o,`${x.green}$&${x.reset}`),i=i.replace(n,`${x.dim}$1${x.reset}`),i}function Tg(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,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,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(o,`${x.green}$&${x.reset}`),a=a.replace(n,`${x.dim}$1${x.reset}`),a}function Rg(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,n=/\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(n,`${x.yellow}$1${x.reset}`),a=a.replace(e,`$1${x.cyan}$2${x.reset}:`),a=a.replace(o,`$1${x.magenta}$&${x.reset}`),a=a.replace(r,`${x.dim}$1${x.reset}`),a}function Cg(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(n,`${x.dim}$1${x.reset}`),i=i.replace(o,`${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 ps(t,e,s=""){if(!e||e<10)return t;let o="",n=0,r=-1,i=0,a=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let u=i+1;if(u<l&&t[u]==="["){for(u++;u<l&&!/[a-zA-Z]/.test(t[u]);)u++;u<l&&u++}i=u;continue}if(t[i]===" "&&(r=i),n++,n>e&&r!==-1){o+=t.slice(a,r)+`
702
- `+s,a=r+1,i=a,n=s.length,r=-1;continue}n>e&&r===-1&&(o+=t.slice(a,i)+`
703
- `+s,a=i,n=s.length+1),i++}return o+=t.slice(a),o}function ME(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let l=e.reduce((u,c)=>Math.max(u,(c[a]||"").length),0);return Math.max(i.length,l)}),o=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),n=t.map((i,a)=>` ${x.bold}${i.padEnd(s[a])}${x.reset} `).join("\u2502"),r=[];r.push(`${x.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${x.reset}`),r.push(`${x.dim}\u2502${x.reset}${n}${x.dim}\u2502${x.reset}`),r.push(`${x.dim}\u251C${o}\u2524${x.reset}`);for(let i of e){let a=t.map((l,u)=>` ${(i[u]||"").padEnd(s[u])} `).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${o.replace(/┼/g,"\u2534")}\u2518${x.reset}`),r.join(`
704
- `)}function PE(t,e,s,o=30){let n=s>0?Math.round(e/s*100):0,r=Math.round(n/100*o),i=o-r,a=n>=100?x.green:n>50?x.yellow:x.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${x.dim}${"\u2591".repeat(i)}${x.reset} ${n}% (${e}/${s})`}var jc=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],o=s[this._cursorFrame%s.length],n="";for(let r=0;r<5;r++)n+=r===o?`${Gt().T.cyan}\u25CF${Gt().T.reset}`:" ";this._cursorWrite(`\x1B[2K\r${n}`),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(`
705
- `))!==-1;){let o=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(o)}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}
706
- `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=_g();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${x.dim}${"\u2500".repeat(40)}${x.reset}
707
- `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let n=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${x.dim}${"\u2500".repeat(3)}${n}${"\u2500".repeat(Math.max(0,37-n.length))}${x.reset}
708
- `)}return}if(this.inCodeBlock){this._safeWrite(` ${Dc(e,this.codeBlockLang)}
709
- `);return}if(e.startsWith("###### ")){this._safeWrite(`${x.bold}${x.cyan} ${At(e.substring(7))}${x.reset}
710
- `);return}if(e.startsWith("##### ")){this._safeWrite(`${x.bold}${x.cyan} ${At(e.substring(6))}${x.reset}
711
- `);return}if(e.startsWith("#### ")){this._safeWrite(`${x.bold}${x.cyan} ${At(e.substring(5))}${x.reset}
712
- `);return}if(e.startsWith("### ")){this._safeWrite(`${x.bold}${x.cyan} ${At(e.substring(4))}${x.reset}
713
- `);return}if(e.startsWith("## ")){this._safeWrite(`${x.bold}${x.cyan} ${At(e.substring(3))}${x.reset}
714
- `);return}if(e.startsWith("# ")){this._safeWrite(`${x.bold}${x.cyan}${At(e.substring(2))}${x.reset}
715
- `);return}if(/^\s*[-*]\s/.test(e)){let n=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${n}${x.cyan}\u2022${x.reset} ${hs(r)}`,a=ps(i,s,n+" ");this._safeWrite(`${a}
716
- `);return}if(/^\s*\d+\.\s/.test(e)){let n=e.match(/^(\s*)(\d+)\.\s(.*)/);if(n){let r=n[1],i=n[2],a=n[3],l=`${r}${x.cyan}${i}.${x.reset} ${hs(a)}`,u=r+" ".repeat(i.length+2),c=ps(l,s,u);this._safeWrite(`${c}
717
- `);return}}let o=ps(hs(e),s);this._safeWrite(`${o}
718
- `)}};Ag.exports={renderMarkdown:NE,renderInline:hs,stripHeadingMarkers:At,highlightCode:Dc,highlightJS:kg,highlightBash:xg,highlightJSON:Sg,highlightPython:vg,highlightGo:Eg,highlightRust:Tg,highlightCSS:Rg,highlightHTML:Cg,renderTable:ME,renderProgress:PE,wrapAnsi:ps,StreamRenderer:jc}});var Ig=V((eA,Lg)=>{var{execSync:LE}=require("child_process"),qc=require("path"),ir=require("fs"),Fc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Ng(){return qc.join(process.cwd(),".nex","hooks")}function IE(){return qc.join(process.cwd(),".nex","config.json")}function Mg(){let t=IE();if(!ir.existsSync(t))return{};try{return JSON.parse(ir.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Xi(t){if(!Fc.includes(t))return[];let e=[],s=Ng(),o=qc.join(s,t);ir.existsSync(o)&&e.push(o);let n=Mg();if(n[t]){let r=Array.isArray(n[t])?n[t]:[n[t]];e.push(...r)}return e}function Pg(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:LE(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(o){let n=typeof o.status=="number"?o.status:1;return{success:!1,exitCode:n,blocked:n===2,output:o.stdout?o.stdout.trim():"",error:o.stderr?o.stderr.trim():o.message}}}function jE(t,e={}){let s=Xi(t);if(s.length===0)return{results:[],blocked:!1};let o={};for(let[r,i]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(i);let n=[];for(let r of s){let i=Pg(r,o);if(n.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:n,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:n,blocked:!1}}function DE(t){return Xi(t).length>0}function qE(){let t=[];for(let e of Fc){let s=Xi(e);s.length>0&&t.push({event:e,commands:s})}return t}function FE(){let t=Ng();return ir.existsSync(t)||ir.mkdirSync(t,{recursive:!0}),t}Lg.exports={HOOK_EVENTS:Fc,loadHookConfig:Mg,getHooksForEvent:Xi,executeHook:Pg,runHooks:jE,hasHooks:DE,listHooks:qE,initHooksDir:FE}});var Vi=V((tA,Dg)=>{var ar={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
707
+ - 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 fs=0;function dT(){!Ae||Ae.status!=="executing"||(fs>0&&Bc(fs-1,"done"),fs<Ae.steps.length&&(Bc(fs,"in_progress"),fs++))}function fT(){if(!Ae||Ae.status!=="executing"||Ae.steps.length===0)return null;let t=Math.min(fs,Ae.steps.length),e=Ae.steps.length,n=Math.max(0,t-1),o=Ae.steps[n]?.description||"";return{current:t,total:e,description:o}}function hT(){fs=0}var Bg=["interactive","semi-auto","autonomous"],Ug="interactive";function pT(t){return Bg.includes(t)?(Ug=t,!0):!1}function mT(){return Ug}Wg.exports={createPlan:VE,getActivePlan:JE,setPlanMode:ZE,isPlanMode:QE,approvePlan:eT,startExecution:tT,updateStep:Bc,formatPlan:nT,savePlan:sT,loadPlan:oT,listPlans:rT,clearPlan:cT,getPlanModePrompt:uT,setPlanContent:aT,getPlanContent:lT,extractStepsFromText:iT,advancePlanStep:dT,getPlanStepInfo:fT,PLAN_MODE_ALLOWED_TOOLS:qg,setAutonomyLevel:pT,getAutonomyLevel:mT,AUTONOMY_LEVELS:Bg}});var ey=Z((BA,Qg)=>{var{C:k}=it();function Hg(){return Math.max(10,(process.stdout.columns||80)-2)}function gT(t){if(!t)return"";let e=t.split(`
708
+ `),n=[],o=!1,s="";for(let r of e){let i=Hg();if(r.trim().startsWith("```")){if(o)n.push(`${k.dim}${"\u2500".repeat(40)}${k.reset}`),o=!1,s="";else{o=!0,s=r.trim().substring(3).trim();let a=s?` ${s} `:"";n.push(`${k.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${k.reset}`)}continue}if(o){n.push(` ${Yc(r,s)}`);continue}if(r.startsWith("###### ")){n.push(`${k.bold}${k.cyan} ${Ot(r.substring(7))}${k.reset}`);continue}if(r.startsWith("##### ")){n.push(`${k.bold}${k.cyan} ${Ot(r.substring(6))}${k.reset}`);continue}if(r.startsWith("#### ")){n.push(`${k.bold}${k.cyan} ${Ot(r.substring(5))}${k.reset}`);continue}if(r.startsWith("### ")){n.push(`${k.bold}${k.cyan} ${Ot(r.substring(4))}${k.reset}`);continue}if(r.startsWith("## ")){n.push(`${k.bold}${k.cyan} ${Ot(r.substring(3))}${k.reset}`);continue}if(r.startsWith("# ")){n.push(`${k.bold}${k.cyan}${Ot(r.substring(2))}${k.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),u=`${a}${k.cyan}\u2022${k.reset} ${ps(l)}`;n.push(ms(u,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let l=a[1],u=a[2],c=a[3],d=`${l}${k.cyan}${u}.${k.reset} ${ps(c)}`,f=l+" ".repeat(u.length+2);n.push(ms(d,i,f));continue}}n.push(ms(ps(r),i))}return n.join(`
709
+ `)}function Ot(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function ps(t){return t?t.replace(/`([^`]+)`/g,`${k.cyan}$1${k.reset}`).replace(/\*\*([^*]+)\*\*/g,`${k.bold}$1${k.reset}`).replace(/\*([^*]+)\*/g,`${k.dim}$1${k.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${k.cyan}$1${k.reset} ${k.dim}($2)${k.reset}`):""}function Yc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Yg(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Gg(t):e==="json"||e==="jsonc"?zg(t):e==="python"||e==="py"?Kg(t):e==="go"||e==="golang"?Xg(t):e==="rust"||e==="rs"?Vg(t):e==="css"||e==="scss"||e==="less"?Jg(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Zg(t):t:""}function Yg(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,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,s=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(s,`${k.yellow}$1${k.reset}`),r=r.replace(e,`${k.magenta}$1${k.reset}`),r=r.replace(n,`${k.green}$&${k.reset}`),r=r.replace(o,`${k.dim}$1${k.reset}`),r}function Gg(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,r=t;return r=r.replace(n,`${k.cyan}$1${k.reset}`),r=r.replace(e,`$1${k.green}$2${k.reset}`),r=r.replace(o,`${k.yellow}$&${k.reset}`),r=r.replace(s,`${k.dim}$1${k.reset}`),r}function zg(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,o=/:\s*(\d+\.?\d*)/g,s=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${k.cyan}$1${k.reset}:`),r=r.replace(n,`: ${k.green}$1${k.reset}`),r=r.replace(o,`: ${k.yellow}$1${k.reset}`),r=r.replace(s,`: ${k.magenta}$1${k.reset}`),r}function Kg(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,n=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,o=/(#.*$)/,s=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(s,`${k.yellow}$1${k.reset}`),i=i.replace(e,`${k.magenta}$1${k.reset}`),i=i.replace(r,`${k.cyan}$1${k.reset}`),i=i.replace(n,`${k.green}$&${k.reset}`),i=i.replace(o,`${k.dim}$1${k.reset}`),i}function Xg(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,n=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${k.yellow}$1${k.reset}`),i=i.replace(n,`${k.cyan}$1${k.reset}`),i=i.replace(e,`${k.magenta}$1${k.reset}`),i=i.replace(o,`${k.green}$&${k.reset}`),i=i.replace(s,`${k.dim}$1${k.reset}`),i}function Vg(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,n=/\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,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${k.yellow}$1${k.reset}`),a=a.replace(n,`${k.cyan}$1${k.reset}`),a=a.replace(e,`${k.magenta}$1${k.reset}`),a=a.replace(i,`${k.yellow}$1${k.reset}`),a=a.replace(o,`${k.green}$&${k.reset}`),a=a.replace(s,`${k.dim}$1${k.reset}`),a}function Jg(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,s=/\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,`${k.yellow}$1${k.reset}`),a=a.replace(s,`${k.yellow}$1${k.reset}`),a=a.replace(e,`$1${k.cyan}$2${k.reset}:`),a=a.replace(o,`$1${k.magenta}$&${k.reset}`),a=a.replace(r,`${k.dim}$1${k.reset}`),a}function Zg(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(s,`${k.dim}$1${k.reset}`),i=i.replace(o,`${k.green}$&${k.reset}`),i=i.replace(e,`<${k.magenta}$1${k.reset}`),i=i.replace(n,` ${k.cyan}$1${k.reset}=`),i=i.replace(r,`${k.yellow}$1${k.reset}`),i}function ms(t,e,n=""){if(!e||e<10)return t;let o="",s=0,r=-1,i=0,a=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let u=i+1;if(u<l&&t[u]==="["){for(u++;u<l&&!/[a-zA-Z]/.test(t[u]);)u++;u<l&&u++}i=u;continue}if(t[i]===" "&&(r=i),s++,s>e&&r!==-1){o+=t.slice(a,r)+`
710
+ `+n,a=r+1,i=a,s=n.length,r=-1;continue}s>e&&r===-1&&(o+=t.slice(a,i)+`
711
+ `+n,a=i,s=n.length+1),i++}return o+=t.slice(a),o}function yT(t,e){if(!t||t.length===0)return"";let n=t.map((i,a)=>{let l=e.reduce((u,c)=>Math.max(u,(c[a]||"").length),0);return Math.max(i.length,l)}),o=n.map(i=>"\u2500".repeat(i+2)).join("\u253C"),s=t.map((i,a)=>` ${k.bold}${i.padEnd(n[a])}${k.reset} `).join("\u2502"),r=[];r.push(`${k.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${k.reset}`),r.push(`${k.dim}\u2502${k.reset}${s}${k.dim}\u2502${k.reset}`),r.push(`${k.dim}\u251C${o}\u2524${k.reset}`);for(let i of e){let a=t.map((l,u)=>` ${(i[u]||"").padEnd(n[u])} `).join(`${k.dim}\u2502${k.reset}`);r.push(`${k.dim}\u2502${k.reset}${a}${k.dim}\u2502${k.reset}`)}return r.push(`${k.dim}\u2514${o.replace(/┼/g,"\u2534")}\u2518${k.reset}`),r.join(`
712
+ `)}function wT(t,e,n,o=30){let s=n>0?Math.round(e/n*100):0,r=Math.round(s/100*o),i=o-r,a=s>=100?k.green:s>50?k.yellow:k.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${k.dim}${"\u2591".repeat(i)}${k.reset} ${s}% (${e}/${n})`}var Hc=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(n){if(n.code!=="EPIPE")throw n}}_cursorWrite(e){try{process.stderr.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let n=[0,1,2,3,4,3,2,1],o=n[this._cursorFrame%n.length],s="";for(let r=0;r<5;r++)s+=r===o?`${zt().T.cyan}\u25CF${zt().T.reset}`:" ";this._cursorWrite(`\x1B[2K\r${s}`),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 n;for(;(n=this.buffer.indexOf(`
713
+ `))!==-1;){let o=this.buffer.substring(0,n);this.buffer=this.buffer.substring(n+1),this._renderLine(o)}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(`${k.dim}${"\u2500".repeat(40)}${k.reset}
714
+ `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=Hg();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${k.dim}${"\u2500".repeat(40)}${k.reset}
715
+ `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${k.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${k.reset}
716
+ `)}return}if(this.inCodeBlock){this._safeWrite(` ${Yc(e,this.codeBlockLang)}
717
+ `);return}if(e.startsWith("###### ")){this._safeWrite(`${k.bold}${k.cyan} ${Ot(e.substring(7))}${k.reset}
718
+ `);return}if(e.startsWith("##### ")){this._safeWrite(`${k.bold}${k.cyan} ${Ot(e.substring(6))}${k.reset}
719
+ `);return}if(e.startsWith("#### ")){this._safeWrite(`${k.bold}${k.cyan} ${Ot(e.substring(5))}${k.reset}
720
+ `);return}if(e.startsWith("### ")){this._safeWrite(`${k.bold}${k.cyan} ${Ot(e.substring(4))}${k.reset}
721
+ `);return}if(e.startsWith("## ")){this._safeWrite(`${k.bold}${k.cyan} ${Ot(e.substring(3))}${k.reset}
722
+ `);return}if(e.startsWith("# ")){this._safeWrite(`${k.bold}${k.cyan}${Ot(e.substring(2))}${k.reset}
723
+ `);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${k.cyan}\u2022${k.reset} ${ps(r)}`,a=ms(i,n,s+" ");this._safeWrite(`${a}
724
+ `);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){let r=s[1],i=s[2],a=s[3],l=`${r}${k.cyan}${i}.${k.reset} ${ps(a)}`,u=r+" ".repeat(i.length+2),c=ms(l,n,u);this._safeWrite(`${c}
725
+ `);return}}let o=ms(ps(e),n);this._safeWrite(`${o}
726
+ `)}};Qg.exports={renderMarkdown:gT,renderInline:ps,stripHeadingMarkers:Ot,highlightCode:Yc,highlightJS:Yg,highlightBash:Gg,highlightJSON:zg,highlightPython:Kg,highlightGo:Xg,highlightRust:Vg,highlightCSS:Jg,highlightHTML:Zg,renderTable:yT,renderProgress:wT,wrapAnsi:ms,StreamRenderer:Hc}});var ry=Z((UA,oy)=>{var{execSync:$T}=require("child_process"),Gc=require("path"),lr=require("fs"),zc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function ty(){return Gc.join(process.cwd(),".nex","hooks")}function bT(){return Gc.join(process.cwd(),".nex","config.json")}function ny(){let t=bT();if(!lr.existsSync(t))return{};try{return JSON.parse(lr.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Zi(t){if(!zc.includes(t))return[];let e=[],n=ty(),o=Gc.join(n,t);lr.existsSync(o)&&e.push(o);let s=ny();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function sy(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:$T(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(o){let s=typeof o.status=="number"?o.status:1;return{success:!1,exitCode:s,blocked:s===2,output:o.stdout?o.stdout.trim():"",error:o.stderr?o.stderr.trim():o.message}}}function _T(t,e={}){let n=Zi(t);if(n.length===0)return{results:[],blocked:!1};let o={};for(let[r,i]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(i);let s=[];for(let r of n){let i=sy(r,o);if(s.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:s,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:s,blocked:!1}}function xT(t){return Zi(t).length>0}function kT(){let t=[];for(let e of zc){let n=Zi(e);n.length>0&&t.push({event:e,commands:n})}return t}function ST(){let t=ty();return lr.existsSync(t)||lr.mkdirSync(t,{recursive:!0}),t}oy.exports={HOOK_EVENTS:zc,loadHookConfig:ny,getHooksForEvent:Zi,executeHook:sy,runHooks:_T,hasHooks:xT,listHooks:kT,initHooksDir:ST}});var Qi=Z((WA,ay)=>{var cr={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
719
727
  Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
720
728
  You excel at sysadmin, frontend, and multi-step coding tasks.
721
729
  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.
@@ -728,7 +736,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
728
736
  Prioritize decisive, targeted edits. Read only what you need, then fix.
729
737
  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.
730
738
  Trust your reasoning. Use tools thoroughly when the task demands it.
731
- You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},jg={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function BE(t){let e=(t||"").toLowerCase(),s=null,o=0;for(let r of Object.keys(ar))e.startsWith(r)&&r.length>o&&(s=r,o=r.length);let n=s?{...ar[s]}:{...jg};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&&(n[i]=a)}return n}function UE(t){let e=(t||"").toLowerCase(),s=null,o=0;for(let n of Object.keys(ar))e.startsWith(n)&&n.length>o&&(s=n,o=n.length);return s&&ar[s].briefing||""}Dg.exports={getModelProfile:BE,getModelBriefing:UE,PROFILES:ar,DEFAULTS:jg}});var to=V((nA,qg)=>{var{fork:WE}=require("child_process"),HE=require("path"),GE=HE.join(__dirname,"background-worker.js"),ms=new Map,eo=new Map;function YE(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function zE(t){let e=YE(),s=WE(GE,[],{silent:!0,env:process.env,cwd:process.cwd()});return s.send({jobId:e,agentDef:t}),s.on("message",o=>{o.type==="result"?Bc(e,t,o.payload):o.type==="error"&&Bc(e,t,{task:t.task,status:"failed",result:`Background agent error: ${o.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),s.on("exit",(o,n)=>{if(ms.has(e)){let r=n?`killed (${n})`:`exit code ${o}`;Bc(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),ms.set(e,{process:s,agentDef:t,startedAt:Date.now()}),e}function Bc(t,e,s){ms.delete(t),eo.set(t,{jobId:t,agentDef:e,result:s,finishedAt:Date.now()})}function KE(){if(eo.size===0)return[];let t=[...eo.values()];return eo.clear(),t}function XE(){return ms.size>0||eo.size>0}function VE(){let t=ms.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function JE(){for(let[t,e]of ms){try{e.process.kill("SIGTERM")}catch{}ms.delete(t)}eo.clear()}qg.exports={createJob:zE,getCompletedJobs:KE,getPendingJobSummary:VE,hasPendingOrCompletedJobs:XE,cancelAllJobs:JE}});var sy=V((iA,ny)=>{"use strict";var{callWithRetry:Ug,runSubAgent:Fg,clearAllLocks:ZE}=Di(),{parseModelSpec:Wg,getActiveProviderName:sA,getActiveModelId:oA}=ut(),{detectCategory:QE,getModelForCategory:Bg}=sr(),{MultiProgress:eT,C:ge}=ot(),{getModelBriefing:rA}=Vi(),Hg=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Ji=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Gg="devstral-2:123b",Yg="kimi-k2.5",zg=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
739
+ You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},iy={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function vT(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let r of Object.keys(cr))e.startsWith(r)&&r.length>o&&(n=r,o=r.length);let s=n?{...cr[n]}:{...iy};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&&(s[i]=a)}return s}function ET(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let s of Object.keys(cr))e.startsWith(s)&&s.length>o&&(n=s,o=s.length);return n&&cr[n].briefing||""}ay.exports={getModelProfile:vT,getModelBriefing:ET,PROFILES:cr,DEFAULTS:iy}});var io=Z((HA,ly)=>{var{fork:TT}=require("child_process"),RT=require("path"),CT=RT.join(__dirname,"background-worker.js"),gs=new Map,ro=new Map;function AT(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function OT(t){let e=AT(),n=TT(CT,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:e,agentDef:t}),n.on("message",o=>{o.type==="result"?Kc(e,t,o.payload):o.type==="error"&&Kc(e,t,{task:t.task,status:"failed",result:`Background agent error: ${o.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),n.on("exit",(o,s)=>{if(gs.has(e)){let r=s?`killed (${s})`:`exit code ${o}`;Kc(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),gs.set(e,{process:n,agentDef:t,startedAt:Date.now()}),e}function Kc(t,e,n){gs.delete(t),ro.set(t,{jobId:t,agentDef:e,result:n,finishedAt:Date.now()})}function NT(){if(ro.size===0)return[];let t=[...ro.values()];return ro.clear(),t}function PT(){return gs.size>0||ro.size>0}function MT(){let t=gs.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function LT(){for(let[t,e]of gs){try{e.process.kill("SIGTERM")}catch{}gs.delete(t)}ro.clear()}ly.exports={createJob:OT,getCompletedJobs:NT,getPendingJobSummary:MT,hasPendingOrCompletedJobs:PT,cancelAllJobs:LT}});var Ey=Z((KA,vy)=>{"use strict";var{callWithRetry:dy,runSubAgent:cy,clearAllLocks:IT}=Bi(),{parseModelSpec:fy,getActiveProviderName:YA,getActiveModelId:GA}=dt(),{detectCategory:jT,getModelForCategory:uy}=rr(),{MultiProgress:DT,C:me}=it(),{getModelBriefing:zA}=Qi(),hy=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),ea=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),py="devstral-2:123b",my="kimi-k2.5",gy=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
732
740
 
733
741
  RULES:
734
742
  - Output ONLY a JSON array, no markdown fences, no explanation.
@@ -743,7 +751,7 @@ RULES:
743
751
  - If the request is simple (single goal), return an array with exactly 1 item.
744
752
 
745
753
  USER REQUEST:
746
- {prompt}`,Kg=`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.
754
+ {prompt}`,yy=`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.
747
755
 
748
756
  RULES:
749
757
  - Output ONLY a JSON object with these fields:
@@ -757,16 +765,16 @@ ORIGINAL REQUEST:
757
765
  {prompt}
758
766
 
759
767
  SUB-AGENT RESULTS:
760
- {results}`;async function Xg(t,e=1,s=2e3){for(let o=0;o<=e;o++)try{return await t()}catch(n){if(o===e)throw n;await new Promise(r=>setTimeout(r,s))}}function Vg(t){let e=0,s=[];return function(){return new Promise(n=>{let r=()=>{e<t?(e++,n(()=>{e--,s.length>0&&s.shift()()})):s.push(r)};r()})}}function tT(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,s=[],o=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);o&&o.length>=2&&(e=Math.max(e,o.length),s.push(`${o.length} numbered items`));let n=t.match(/(?:^|\n)\s*[-*]\s+\S/g);n&&n.length>=3&&(e=Math.max(e,n.length),s.push(`${n.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.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 Uc(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 o=e.search(/[[\{]/);if(o>=0){let n=e.slice(o);try{return JSON.parse(n)}catch{}}throw new Error(`Could not extract valid JSON from response:
761
- ${e.slice(0,200)}`)}async function Jg(t,e,s={}){let o=s.maxSubTasks||Ji,r=[{role:"system",content:zg.replace("{maxSubTasks}",String(o)).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 Ug(r,[],i)).content||"",u=Uc(l);if(!Array.isArray(u))throw new Error(`Decompose returned non-array: ${typeof u}`);let c=10,f=u.slice(0,o).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,c):8,priority:typeof g.priority=="number"?g.priority:$+1})).filter(g=>g.task.length>0),h=f.reduce((g,$)=>g+$.estimatedCalls,0),m=Ji*c;if(h>m){let{debugLog:g}=el();g(`${Gt().T.yellow} \u26A0 Orchestrator: total estimated calls ${h} > ${m} \u2014 consider raising maxSubTasks${Gt().T.reset}`)}return f}async function Zg(t,e,s){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((c,d)=>{let f=c.status==="done"?"SUCCESS":c.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
768
+ {results}`;async function wy(t,e=1,n=2e3){for(let o=0;o<=e;o++)try{return await t()}catch(s){if(o===e)throw s;await new Promise(r=>setTimeout(r,n))}}function $y(t){let e=0,n=[];return function(){return new Promise(s=>{let r=()=>{e<t?(e++,s(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function qT(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],o=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);o&&o.length>=2&&(e=Math.max(e,o.length),n.push(`${o.length} numbered items`));let s=t.match(/(?:^|\n)\s*[-*]\s+\S/g);s&&s.length>=3&&(e=Math.max(e,s.length),n.push(`${s.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),n.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),n.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function Xc(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 n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(n)try{return JSON.parse(n[1].trim())}catch{}let o=e.search(/[[\{]/);if(o>=0){let s=e.slice(o);try{return JSON.parse(s)}catch{}}throw new Error(`Could not extract valid JSON from response:
769
+ ${e.slice(0,200)}`)}async function by(t,e,n={}){let o=n.maxSubTasks||ea,r=[{role:"system",content:gy.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=fy(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await dy(r,[],i)).content||"",u=Xc(l);if(!Array.isArray(u))throw new Error(`Decompose returned non-array: ${typeof u}`);let c=10,f=u.slice(0,o).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,c):8,priority:typeof g.priority=="number"?g.priority:$+1})).filter(g=>g.task.length>0),h=f.reduce((g,$)=>g+$.estimatedCalls,0),m=ea*c;if(h>m){let{debugLog:g}=rl();g(`${zt().T.yellow} \u26A0 Orchestrator: total estimated calls ${h} > ${m} \u2014 consider raising maxSubTasks${zt().T.reset}`)}return f}async function _y(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((c,d)=>{let f=c.status==="done"?"SUCCESS":c.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
762
770
  Task: ${c.task}
763
771
  Result: ${c.result}
764
772
  Tools: ${(c.toolsUsed||[]).join(", ")||"none"}`}).join(`
765
773
 
766
- `),r=[{role:"system",content:Kg.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let c=Wg(s);c.provider&&(i.provider=c.provider),c.model&&(i.model=c.model)}let l=(await Ug(r,[],i)).content||"",u=Uc(l);return{summary:String(u.summary||""),conflicts:Array.isArray(u.conflicts)?u.conflicts:[],commitMessage:String(u.commitMessage||""),filesChanged:Array.isArray(u.filesChanged)?u.filesChanged:[]}}async function nT(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Yg,o=e.workerModel||Gg,n=e.maxParallel||Hg,r=e.maxSubTasks||Ji,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
767
- ${ge.bold}Orchestrator${ge.reset} ${ge.dim}model: ${s} | workers: ${o} | max parallel: ${n}${ge.reset}
768
- `),i("decomposing"),console.log(`${ge.dim}Phase 1: Decomposing prompt into sub-tasks...${ge.reset}`);let l;try{l=await Jg(t,s,{maxSubTasks:r})}catch(U){return console.log(`${ge.red}Decompose failed: ${U.message}${ge.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${U.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${ge.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ge.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${ge.green}Decomposed into ${l.length} sub-tasks:${ge.reset}`);for(let U of l){console.log(` ${ge.dim}${U.id}:${ge.reset} ${U.task}`);let Z=U.scope.filter(Boolean);Z.length>0&&console.log(` ${ge.dim}scope: ${Z.join(", ")}${ge.reset}`)}console.log("");let u=new Map;for(let U=0;U<l.length;U++)for(let Z of l[U].scope)Z&&!u.has(Z)&&u.set(Z,U);i("executing"),console.log(`${ge.dim}Phase 2: Running ${l.length} sub-agents (max ${n} parallel)...${ge.reset}
769
- `);let c=Date.now(),d=Vg(n),f={findings:[],_lock:!1},h=l.map(U=>{let Z=QE(U.task);return(Z?Bg(Z.id):null)||o}),m=l.map((U,Z)=>{let ye=`Agent ${Z+1} [${h[Z]}]: `,ke=Math.max(20,60-ye.length),De=U.task.substring(0,ke)+(U.task.length>ke?"...":"");return ye+De}),g=new eT(m);g.start();let $=`
774
+ `),r=[{role:"system",content:yy.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let c=fy(n);c.provider&&(i.provider=c.provider),c.model&&(i.model=c.model)}let l=(await dy(r,[],i)).content||"",u=Xc(l);return{summary:String(u.summary||""),conflicts:Array.isArray(u.conflicts)?u.conflicts:[],commitMessage:String(u.commitMessage||""),filesChanged:Array.isArray(u.filesChanged)?u.filesChanged:[]}}async function FT(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||my,o=e.workerModel||py,s=e.maxParallel||hy,r=e.maxSubTasks||ea,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
775
+ ${me.bold}Orchestrator${me.reset} ${me.dim}model: ${n} | workers: ${o} | max parallel: ${s}${me.reset}
776
+ `),i("decomposing"),console.log(`${me.dim}Phase 1: Decomposing prompt into sub-tasks...${me.reset}`);let l;try{l=await by(t,n,{maxSubTasks:r})}catch(q){return console.log(`${me.red}Decompose failed: ${q.message}${me.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${q.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${me.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${me.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${me.green}Decomposed into ${l.length} sub-tasks:${me.reset}`);for(let q of l){console.log(` ${me.dim}${q.id}:${me.reset} ${q.task}`);let Q=q.scope.filter(Boolean);Q.length>0&&console.log(` ${me.dim}scope: ${Q.join(", ")}${me.reset}`)}console.log("");let u=new Map;for(let q=0;q<l.length;q++)for(let Q of l[q].scope)Q&&!u.has(Q)&&u.set(Q,q);i("executing"),console.log(`${me.dim}Phase 2: Running ${l.length} sub-agents (max ${s} parallel)...${me.reset}
777
+ `);let c=Date.now(),d=$y(s),f={findings:[],_lock:!1},h=l.map(q=>{let Q=jT(q.task);return(Q?uy(Q.id):null)||o}),m=l.map((q,Q)=>{let we=`Agent ${Q+1} [${h[Q]}]: `,ke=Math.max(20,60-we.length),qe=q.task.substring(0,ke)+(q.task.length>ke?"...":"");return we+qe}),g=new DT(m);g.start();let $=`
770
778
  You are a focused coding agent executing ONE specific sub-task.
771
779
  Your scope is limited to the files listed in your task definition.
772
780
 
@@ -791,78 +799,78 @@ RULES:
791
799
  - Start with symbol-aware reads inside your scope: locate the target function/class/module, then read the exact section instead of scanning broadly.
792
800
  - Before finishing, run the smallest relevant verification for your scope and report any residual risk explicitly.
793
801
  - 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.
794
- `,k=new Map;for(let U=0;U<l.length;U++){let Z=l[U].priority||1;k.has(Z)||k.set(Z,[]),k.get(Z).push({st:l[U],idx:U})}let v=[...k.keys()].sort((U,Z)=>U-Z),A=new Array(l.length);for(let U of v){let ye=k.get(U).map(async({st:ke,idx:De})=>{let Oe=await d();try{let Se=await E(ke,De,{acquire:d,subTaskModels:h,labels:m,progress:g,sharedContext:f,_fileOwnership:u,workerModel:o,WORKER_SYSTEM_PROMPT:$});return A[De]=Se,Se}finally{Oe()}});await Promise.all(ye)}async function E(U,Z,ye){try{let ke=f.findings.filter(se=>se.agentId!==U.id).map(se=>`Agent ${se.agentId} found: ${se.summary}`).join(`
795
- `),De=[...u.entries()].filter(([,se])=>se===Z).map(([se])=>se),Oe=[...u.entries()].filter(([,se])=>se!==Z).map(([se])=>se),Se=[ke?`Prior agent findings:
802
+ `,x=new Map;for(let q=0;q<l.length;q++){let Q=l[q].priority||1;x.has(Q)||x.set(Q,[]),x.get(Q).push({st:l[q],idx:q})}let E=[...x.keys()].sort((q,Q)=>q-Q),N=new Array(l.length);for(let q of E){let we=x.get(q).map(async({st:ke,idx:qe})=>{let Ne=await d();try{let ve=await v(ke,qe,{acquire:d,subTaskModels:h,labels:m,progress:g,sharedContext:f,_fileOwnership:u,workerModel:o,WORKER_SYSTEM_PROMPT:$});return N[qe]=ve,ve}finally{Ne()}});await Promise.all(we)}async function v(q,Q,we){try{let ke=f.findings.filter(H=>H.agentId!==q.id).map(H=>`Agent ${H.agentId} found: ${H.summary}`).join(`
803
+ `),qe=[...u.entries()].filter(([,H])=>H===Q).map(([H])=>H),Ne=[...u.entries()].filter(([,H])=>H!==Q).map(([H])=>H),ve=[ke?`Prior agent findings:
796
804
  ${ke}
797
- `:"",U.scope.length>0?`Focus on files: ${U.scope.join(", ")}`:"",De.length>0?`You OWN these files (may read+write): ${De.join(", ")}`:"",Oe.length>0?`READ ONLY (owned by other agents, do NOT write): ${Oe.join(", ")}`:""].filter(Boolean),_=ty(U.task),L=h[Z],W=process.env.NEX_FALLBACK_MODEL||Bg("agentic")||o,te=0,z=await Xg(async()=>{let se=te>0;se&&(g.update(Z,"retry"),process.stderr.write(` ${ge.dim}[Agent ${Z+1}] retrying after error...${ge.reset}
798
- `)),te++;let D=se&&L!==W?W:L;return Fg({task:U.task,type:_,context:Se.length>0?Se.join(`
799
- `):void 0,max_iterations:Math.min(U.estimatedCalls||10,15),model:D,_skipLog:!0,_systemPrompt:$,_readOnlyFiles:Oe},{onUpdate:me=>{if(me&&me.type==="tool_call"&&process.stderr.isTTY){let go=`Agent ${Z+1} [${D}]`,Sn=me.tool||"...";g.labels[Z]=`${go}: ${Sn}`}}})},1,2e3),R="";if(ey(_,z,U,De)){let se=[...new Set([...De,...Array.isArray(z.filesModified)?z.filesModified:[],...Array.isArray(U.scope)?U.scope:[]])].filter(Boolean);try{g.labels[Z]=`Agent ${Z+1} [${L}] review`,g.update(Z,"retry");let D=await Fg({task:`Review the completed changes for: ${U.task}`,type:"review",context:iT(U,z,se),max_iterations:4,model:L,_skipLog:!0,_systemPrompt:$},{onUpdate:()=>{}},1);Qg(D.result)?(R=`
805
+ `:"",q.scope.length>0?`Focus on files: ${q.scope.join(", ")}`:"",qe.length>0?`You OWN these files (may read+write): ${qe.join(", ")}`:"",Ne.length>0?`READ ONLY (owned by other agents, do NOT write): ${Ne.join(", ")}`:""].filter(Boolean),_=Sy(q.task),M=h[Q],F=process.env.NEX_FALLBACK_MODEL||uy("agentic")||o,ee=0,K=await wy(async()=>{let H=ee>0;H&&(g.update(Q,"retry"),process.stderr.write(` ${me.dim}[Agent ${Q+1}] retrying after error...${me.reset}
806
+ `)),ee++;let se=H&&M!==F?F:M;return cy({task:q.task,type:_,context:ve.length>0?ve.join(`
807
+ `):void 0,max_iterations:Math.min(q.estimatedCalls||10,15),model:se,_skipLog:!0,_systemPrompt:$,_readOnlyFiles:Ne},{onUpdate:J=>{if(J&&J.type==="tool_call"&&process.stderr.isTTY){let Se=`Agent ${Q+1} [${se}]`,Ts=J.tool||"...";g.labels[Q]=`${Se}: ${Ts}`}}})},1,2e3),C="";if(ky(_,K,q,qe)){let H=[...new Set([...qe,...Array.isArray(K.filesModified)?K.filesModified:[],...Array.isArray(q.scope)?q.scope:[]])].filter(Boolean);try{g.labels[Q]=`Agent ${Q+1} [${M}] review`,g.update(Q,"retry");let se=await cy({task:`Review the completed changes for: ${q.task}`,type:"review",context:HT(q,K,H),max_iterations:4,model:M,_skipLog:!0,_systemPrompt:$},{onUpdate:()=>{}},1);xy(se.result)?(C=`
800
808
 
801
809
  Reviewer findings:
802
- ${D.result}`,f.findings.push({agentId:`${U.id}-review`,summary:String(D.result||"").slice(0,200),files:se})):D.result&&(R=`
810
+ ${se.result}`,f.findings.push({agentId:`${q.id}-review`,summary:String(se.result||"").slice(0,200),files:H})):se.result&&(C=`
803
811
 
804
- Reviewer: ${D.result}`)}catch(D){R=`
812
+ Reviewer: ${se.result}`)}catch(se){C=`
805
813
 
806
- Reviewer note: review pass failed (${D.message})`}}let H=typeof z.result=="string"?`${z.result}${R}`.slice(0,200):`${String(z.result||"")}${R}`.slice(0,200);return f.findings.push({agentId:U.id,summary:H,files:Array.isArray(U.scope)?U.scope:[]}),g.labels[Z]=m[Z],g.update(Z,z.status==="failed"?"error":"done"),a.input+=z.tokensUsed?.input||0,a.output+=z.tokensUsed?.output||0,z.tokensUsed?._estimated&&(a._estimated=!0),{...z,result:`${String(z.result||"")}${R}`,_scope:U.scope,_idx:Z}}catch(ke){return g.labels[Z]=m[Z],g.update(Z,"error"),{task:U.task,status:"failed",result:`Error: ${ke.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let S;try{S=A}finally{g.stop({silent:!0}),ZE()}console.log("");let N=Math.round((Date.now()-c)/1e3),ee=N>=60?`${Math.floor(N/60)}m ${N%60}s`:`${N}s`;for(let U=0;U<S.length;U++){let Z=S[U],ke=Z.status==="done"||Z.status==="truncated"&&Z.result&&!Z.result.startsWith("Error")?`${ge.green}\u2713${ge.reset}`:`${ge.red}\u2717${ge.reset}`,De=Z._scope&&Z._scope.length>0?Z._scope.map(_=>_.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],Oe=De.length>0?De.join(", "):Z.task.substring(0,35)+(Z.task.length>35?"...":""),Se=U===S.length-1;console.log(` ${ke} Agent ${U+1} ${ge.dim}${Oe}${ge.reset}${Se?` ${ge.dim}${ee}${ge.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ge.dim}Phase 3: Synthesizing results...${ge.reset}`);let re;try{re=await Zg(S,t,s)}catch(U){console.log(`${ge.yellow}Synthesize failed: ${U.message} \u2014 using raw results.${ge.reset}`),re={summary:S.map(Z=>Z.result).join(`
807
- `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let le=f.findings.flatMap(U=>U.files),ue=new Map;for(let U of le)ue.set(U,(ue.get(U)||0)+1);let oe=[...ue.values()].some(U=>U>1),ae=f.findings.length>1&&oe?` ${ge.dim}(agents shared context)${ge.reset}`:"";if(console.log(`
808
- ${ge.bold}Summary:${ge.reset} ${re.summary}${ae}`),re.conflicts.length>0){console.log(`${ge.yellow}Conflicts:${ge.reset}`);for(let U of re.conflicts)console.log(` - ${U}`)}re.commitMessage&&console.log(`${ge.dim}Suggested commit: ${re.commitMessage}${ge.reset}`);let T=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(`${ge.dim}Tokens: ${T}${ge.reset}
809
- `),{results:S,synthesis:re,totalTokens:a}}var sT=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,oT=/\b(review|audit|verify|validate|inspect|critique)\b/i,rT=/\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 iT(t,e,s){let o=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}`,o,`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(`
810
- `)}function Qg(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function ey(t,e,s,o){if(t!=="implement"||!e||e.status==="failed")return!1;let n=Array.isArray(s?.scope)?s.scope.length:0,r=Array.isArray(e.filesModified)?e.filesModified.length:0,i=Array.isArray(o)?o.length:0;return n+r+i>0}function ty(t){if(!t)return"implement";let e=sT.test(t),s=oT.test(t);return rT.test(t)?"implement":s?"review":e?"explore":"implement"}ny.exports={runOrchestrated:nT,decompose:Jg,synthesize:Zg,detectComplexPrompt:tT,extractJSON:Uc,createSemaphore:Vg,DECOMPOSE_PROMPT:zg,SYNTHESIZE_PROMPT:Kg,DEFAULT_ORCHESTRATOR_MODEL:Yg,DEFAULT_WORKER_MODEL:Gg,DEFAULT_MAX_PARALLEL:Hg,DEFAULT_MAX_SUBTASKS:Ji,withRetry:Xg,_classifyWorkerType:ty,_hasMaterialReviewFindings:Qg,_shouldRunFollowUpReview:ey}});var Sc=V((fA,Iy)=>{var{C:p,Spinner:so,TaskProgress:aT,formatToolCall:lT,formatToolSummary:nu,formatSectionHeader:lr,formatMilestone:cT,setActiveTaskProgress:aA,getThinkingVerb:Wc,setActiveModelForSpinner:oy}=ot(),{debugLog:I,warnLog:lA}=el(),{MilestoneTracker:uT}=Kd(),{callStream:ry}=ut(),{parseToolArgs:dT}=Zr(),{executeTool:fT}=Ro(),{gatherProjectContext:hT}=Um(),{fitToContext:pT,forceCompress:un,getUsage:Jt,estimateTokens:mT,buildProgressSnapshot:gT}=ln(),{autoSave:yT,flushAutoSave:wT}=Wi(),{scoreMessages:$T,formatScore:bT,appendScoreHistory:_T}=eg(),{detectCategory:kT,getModelForPhase:su,getPhaseBudget:gs,isPhaseRoutingEnabled:xT}=sr();function Ce(t){yT(t),wT()}function Zi(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 ST(t){return!t||typeof t!="string"?!1:/\.(?:md|mdx|txt|rst|adoc)$/i.test(t)}function cr(t){try{if(!t.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(n=>n&&n.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let s=$T(t);if(!s)return;console.log(bT(s,p));try{let{_getSessionsDir:o}=Wi(),n=require("fs"),r=require("path").join(o(),"_autosave.json");if(n.existsSync(r)){let i=JSON.parse(n.readFileSync(r,"utf-8"));i.score=s.score,i.scoreGrade=s.grade,i.scoreIssues=s.issues,n.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=Zr(),n=Ya();_T(s.score,{version:n.version,model:o?o():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:vT}=Ho(),{getDeploymentContextBlock:ET,probeUrlServer:TT,detectRuntimeDebugTarget:iy}=Ec(),{getFewShotForInput:RT}=cg(),{checkPermission:CT,setPermission:AT,savePermissions:OT}=mg(),{confirm:$y,setAllowAlwaysHandler:NT,getAutoConfirm:_s}=xo(),{isPlanMode:wr,getPlanModePrompt:MT,PLAN_MODE_ALLOWED_TOOLS:by,setPlanContent:PT,extractStepsFromText:LT,createPlan:IT,getActivePlan:cA,startExecution:uA,advancePlanStep:jT,getPlanStepInfo:DT}=Ki(),{StreamRenderer:qT}=Og(),{runHooks:ay}=Ig(),{routeMCPCall:FT,getMCPToolDefinitions:BT}=wl(),{getSkillInstructions:UT,getSkillToolDefinitions:WT,routeSkillCall:HT,matchSkillTriggers:GT}=gl(),{trackUsage:ly,estimateTokens:cy}=Gr();function uy(t){return!t||typeof t!="string"?0:typeof cy=="function"?cy(t):Math.ceil(t.length/4)}var{validateToolArgs:YT}=_l(),{filterToolsForModel:dy,getModelTier:zT,PROVIDER_DEFAULT_TIER:dA}=Po(),{getConfiguredProviders:KT,getActiveProviderName:oo,getActiveModelId:Qt,setActiveModel:Hc,MODEL_EQUIVALENTS:pa}=ut(),{getModelProfile:XT,getModelBriefing:VT}=Vi(),Fe=require("fs"),He=require("path"),JT=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function ZT(t){let e=cT(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
811
- `)}var fy=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,hy=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,QT=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function eR(t){let e=[],s;for(fy.lastIndex=0;(s=fy.exec(t))!==null;){let o=s[1].trim(),n=o.startsWith("~")?o.replace("~",process.env.HOME||""):He.resolve(o);Fe.existsSync(n)&&e.push({raw:o,abs:n})}return e}function _y(t){let e=[],s;for(hy.lastIndex=0;(s=hy.exec(t))!==null;)e.push(s[1].trim());return e}async function ky(t){try{let s=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),o=s.headers["content-type"]||"",n=o.startsWith("image/")?o.split(";")[0]:tR(t);return{data:Buffer.from(s.data).toString("base64"),media_type:n}}catch{return null}}function tR(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 xy(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=He.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&Fe.existsSync(e)){let n=Fe.readFileSync(e);if(n.length>100)return{data:n.toString("base64"),media_type:"image/png",path:e};try{Fe.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let o=t("osascript",["-e",`try
814
+ Reviewer note: review pass failed (${se.message})`}}let he=typeof K.result=="string"?`${K.result}${C}`.slice(0,200):`${String(K.result||"")}${C}`.slice(0,200);return f.findings.push({agentId:q.id,summary:he,files:Array.isArray(q.scope)?q.scope:[]}),g.labels[Q]=m[Q],g.update(Q,K.status==="failed"?"error":"done"),a.input+=K.tokensUsed?.input||0,a.output+=K.tokensUsed?.output||0,K.tokensUsed?._estimated&&(a._estimated=!0),{...K,result:`${String(K.result||"")}${C}`,_scope:q.scope,_idx:Q}}catch(ke){return g.labels[Q]=m[Q],g.update(Q,"error"),{task:q.task,status:"failed",result:`Error: ${ke.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let S;try{S=N}finally{g.stop({silent:!0}),IT()}console.log("");let P=Math.round((Date.now()-c)/1e3),ne=P>=60?`${Math.floor(P/60)}m ${P%60}s`:`${P}s`;for(let q=0;q<S.length;q++){let Q=S[q],ke=Q.status==="done"||Q.status==="truncated"&&Q.result&&!Q.result.startsWith("Error")?`${me.green}\u2713${me.reset}`:`${me.red}\u2717${me.reset}`,qe=Q._scope&&Q._scope.length>0?Q._scope.map(_=>_.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],Ne=qe.length>0?qe.join(", "):Q.task.substring(0,35)+(Q.task.length>35?"...":""),ve=q===S.length-1;console.log(` ${ke} Agent ${q+1} ${me.dim}${Ne}${me.reset}${ve?` ${me.dim}${ne}${me.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${me.dim}Phase 3: Synthesizing results...${me.reset}`);let re;try{re=await _y(S,t,n)}catch(q){console.log(`${me.yellow}Synthesize failed: ${q.message} \u2014 using raw results.${me.reset}`),re={summary:S.map(Q=>Q.result).join(`
815
+ `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ce=f.findings.flatMap(q=>q.files),de=new Map;for(let q of ce)de.set(q,(de.get(q)||0)+1);let oe=[...de.values()].some(q=>q>1),le=f.findings.length>1&&oe?` ${me.dim}(agents shared context)${me.reset}`:"";if(console.log(`
816
+ ${me.bold}Summary:${me.reset} ${re.summary}${le}`),re.conflicts.length>0){console.log(`${me.yellow}Conflicts:${me.reset}`);for(let q of re.conflicts)console.log(` - ${q}`)}re.commitMessage&&console.log(`${me.dim}Suggested commit: ${re.commitMessage}${me.reset}`);let T=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(`${me.dim}Tokens: ${T}${me.reset}
817
+ `),{results:S,synthesis:re,totalTokens:a}}var BT=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,UT=/\b(review|audit|verify|validate|inspect|critique)\b/i,WT=/\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 HT(t,e,n){let o=Array.isArray(n)&&n.length>0?`Files to review: ${n.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}`,o,`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(`
818
+ `)}function xy(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function ky(t,e,n,o){if(t!=="implement"||!e||e.status==="failed")return!1;let s=Array.isArray(n?.scope)?n.scope.length:0,r=Array.isArray(e.filesModified)?e.filesModified.length:0,i=Array.isArray(o)?o.length:0;return s+r+i>0}function Sy(t){if(!t)return"implement";let e=BT.test(t),n=UT.test(t);return WT.test(t)?"implement":n?"review":e?"explore":"implement"}vy.exports={runOrchestrated:FT,decompose:by,synthesize:_y,detectComplexPrompt:qT,extractJSON:Xc,createSemaphore:$y,DECOMPOSE_PROMPT:gy,SYNTHESIZE_PROMPT:yy,DEFAULT_ORCHESTRATOR_MODEL:my,DEFAULT_WORKER_MODEL:py,DEFAULT_MAX_PARALLEL:hy,DEFAULT_MAX_SUBTASKS:ea,withRetry:wy,_classifyWorkerType:Sy,_hasMaterialReviewFindings:xy,_shouldRunFollowUpReview:ky}});var Oc=Z((eO,i0)=>{var{C:p,Spinner:lo,TaskProgress:YT,formatToolCall:GT,formatToolSummary:cu,formatSectionHeader:ur,formatMilestone:zT,setActiveTaskProgress:XA,getThinkingVerb:Vc,setActiveModelForSpinner:Ty}=it(),{debugLog:L,warnLog:VA}=rl(),{MilestoneTracker:KT}=cf(),{callStream:Ry}=dt(),{parseToolArgs:XT}=ei(),{executeTool:VT}=Ao(),{gatherProjectContext:JT}=dg(),{fitToContext:ZT,forceCompress:hn,getUsage:Qt,estimateTokens:QT,buildProgressSnapshot:eR}=dn(),{autoSave:tR,flushAutoSave:nR}=Gi(),{scoreMessages:sR,formatScore:oR,appendScoreHistory:rR}=kg(),{detectCategory:iR,getModelForPhase:uu,getPhaseBudget:ys,isPhaseRoutingEnabled:aR}=rr();function Oe(t){tR(t),nR()}function ta(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 lR(t){return!t||typeof t!="string"?!1:/\.(?:md|mdx|txt|rst|adoc)$/i.test(t)}function dr(t){try{if(!t.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(s=>s&&s.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let n=sR(t);if(!n)return;console.log(oR(n,p));try{let{_getSessionsDir:o}=Gi(),s=require("fs"),r=require("path").join(o(),"_autosave.json");if(s.existsSync(r)){let i=JSON.parse(s.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,s.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=ei(),s=Ka();rR(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:cR}=Go(),{getDeploymentContextBlock:uR,probeUrlServer:dR,detectRuntimeDebugTarget:Cy}=Pc(),{getFewShotForInput:fR}=Ng(),{checkPermission:hR,setPermission:pR,savePermissions:mR}=Dg(),{confirm:Wy,setAllowAlwaysHandler:gR,getAutoConfirm:ks}=vo(),{isPlanMode:_r,getPlanModePrompt:yR,PLAN_MODE_ALLOWED_TOOLS:Hy,setPlanContent:wR,extractStepsFromText:$R,createPlan:bR,getActivePlan:JA,startExecution:ZA,advancePlanStep:_R,getPlanStepInfo:xR}=Ji(),{StreamRenderer:kR}=ey(),{runHooks:Ay}=ry(),{routeMCPCall:SR,getMCPToolDefinitions:vR}=kl(),{getSkillInstructions:ER,getSkillToolDefinitions:TR,routeSkillCall:RR,matchSkillTriggers:CR}=_l(),{trackUsage:Oy,estimateTokens:Ny}=zr();function Py(t){return!t||typeof t!="string"?0:typeof Ny=="function"?Ny(t):Math.ceil(t.length/4)}var{validateToolArgs:AR}=El(),{filterToolsForModel:My,getModelTier:OR,PROVIDER_DEFAULT_TIER:QA}=Io(),{getConfiguredProviders:NR,getActiveProviderName:co,getActiveModelId:tn,setActiveModel:Jc,MODEL_EQUIVALENTS:ya}=dt(),{getModelProfile:PR,getModelBriefing:MR}=Qi(),Be=require("fs"),Ge=require("path"),LR=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function IR(t){let e=zT(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
819
+ `)}var Ly=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,Iy=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,jR=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function DR(t){let e=[],n;for(Ly.lastIndex=0;(n=Ly.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):Ge.resolve(o);Be.existsSync(s)&&e.push({raw:o,abs:s})}return e}function Yy(t){let e=[],n;for(Iy.lastIndex=0;(n=Iy.exec(t))!==null;)e.push(n[1].trim());return e}async function Gy(t){try{let n=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),o=n.headers["content-type"]||"",s=o.startsWith("image/")?o.split(";")[0]:qR(t);return{data:Buffer.from(n.data).toString("base64"),media_type:s}}catch{return null}}function qR(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 zy(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=Ge.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&Be.existsSync(e)){let s=Be.readFileSync(e);if(s.length>100)return{data:s.toString("base64"),media_type:"image/png",path:e};try{Be.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let o=t("osascript",["-e",`try
812
820
  set imgData to the clipboard as \xABclass PNGf\xBB
813
821
  return "has_image"
814
822
  on error
815
823
  return "no_image"
816
- end try`],{timeout:3e3});if(o.stdout&&o.stdout.toString().trim()==="has_image"){let n=`
824
+ end try`],{timeout:3e3});if(o.stdout&&o.stdout.toString().trim()==="has_image"){let s=`
817
825
  set imgData to the clipboard as \xABclass PNGf\xBB
818
826
  set filePath to POSIX file "${e}"
819
827
  set fRef to open for access filePath with write permission
820
828
  write imgData to fRef
821
829
  close access fRef
822
- `;if(t("osascript",["-e",n],{timeout:5e3}).status===0&&Fe.existsSync(e)){let i=Fe.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function py(t){let e=Fe.readFileSync(t),s=He.extname(t).toLowerCase().replace(".",""),o=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:o}}function Sy(t){let e=eR(t),s=_y(t),o=QT.test(t),n=s.length>0||o;if(e.length===0&&!n)return t;if(!n){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=py(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}=py(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){I(`${p.yellow} \u26A0 Path resolution failed: ${a.message}${p.reset}`)}if(s.length>0){let i=await Promise.all(s.map(ky));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=xy();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
830
+ `;if(t("osascript",["-e",s],{timeout:5e3}).status===0&&Be.existsSync(e)){let i=Be.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function jy(t){let e=Be.readFileSync(t),n=Ge.extname(t).toLowerCase().replace(".",""),o=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:o}}function Ky(t){let e=DR(t),n=Yy(t),o=jR.test(t),s=n.length>0||o;if(e.length===0&&!s)return t;if(!s){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=jy(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}=jy(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){L(`${p.yellow} \u26A0 Path resolution failed: ${a.message}${p.reset}`)}if(n.length>0){let i=await Promise.all(n.map(Gy));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=zy();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
823
831
  [Clipboard image attached: ${i.path}]`):r[0].text+=`
824
- [No image found in clipboard]`}return r.length>1?r:t})()}var nR=[/\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 vy(t){return typeof t!="string"||!t?!1:nR.some(e=>e.test(t))}function sR(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 o=new Map;for(let l=0;l<=s.length-3;l++){let u=s.slice(l,l+3).join("").trim();u.length>30&&o.set(u,(o.get(u)||0)+1)}let n=0,r="";for(let[l,u]of o)u>n&&(n=u,r=l);if(n<3)return{text:t,truncated:!1,repeatCount:n};let i=`
832
+ [No image found in clipboard]`}return r.length>1?r:t})()}var FR=[/\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 Xy(t){return typeof t!="string"||!t?!1:FR.some(e=>e.test(t))}function BR(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let n=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(n.length<6)return{text:t,truncated:!1,repeatCount:0};let o=new Map;for(let l=0;l<=n.length-3;l++){let u=n.slice(l,l+3).join("").trim();u.length>30&&o.set(u,(o.get(u)||0)+1)}let s=0,r="";for(let[l,u]of o)u>s&&(s=u,r=l);if(s<3)return{text:t,truncated:!1,repeatCount:s};let i=`
825
833
 
826
- [SYSTEM: Output repetition detected \u2014 response truncated (${n}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let l=0,u=-1,c=0;for(;l<2;){let d=t.indexOf(r,c);if(d===-1)break;l++,u=d+r.length,c=d+1}a=u>0?t.slice(0,u)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:n}}function ou(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
827
- `),o=new Map;for(let h of s){let m=h.trim();m.length>=20&&o.set(m,(o.get(m)||0)+1)}let n=0,r="";for(let[h,m]of o)m>n&&(n=m,r=h);let a=r.toLowerCase().includes("read_file")||r.toLowerCase().includes("reading")?2:e;if(n<=a)return{text:t,truncated:!1,repeatCount:n};let l=`
834
+ [SYSTEM: Output repetition detected \u2014 response truncated (${s}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let l=0,u=-1,c=0;for(;l<2;){let d=t.indexOf(r,c);if(d===-1)break;l++,u=d+r.length,c=d+1}a=u>0?t.slice(0,u)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:s}}function du(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
835
+ `),o=new Map;for(let h of n){let m=h.trim();m.length>=20&&o.set(m,(o.get(m)||0)+1)}let s=0,r="";for(let[h,m]of o)m>s&&(s=m,r=h);let a=r.toLowerCase().includes("read_file")||r.toLowerCase().includes("reading")?2:e;if(s<=a)return{text:t,truncated:!1,repeatCount:s};let l=`
828
836
 
829
- \u26A0 [Response truncated: repeated paragraph detected (${n}\xD7)]`,u=0,c=-1,d=0;for(;u<e;){let h=t.indexOf(r,d);if(h===-1)break;u++,c=h+r.length,d=h+1}return{text:c>0?t.slice(0,c)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:n}}var Gc=null,Yc=null,zc=null;function ft(){if(Gc===null){let{TOOL_DEFINITIONS:t}=Ro();Gc=t}return Yc===null&&(Yc=WT()),zc===null&&(zc=BT()),[...Gc,...Yc,...zc]}var ru=50;function oR(t){Number.isFinite(t)&&t>0&&(ru=t)}var na=()=>null;function rR(t){na=t}var hr=null,iu=null,ro=null,io="",ao=0,au="",lu=0,sa=new Map,iR=1e4,aR=6e3,lR=/\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 cR(t){return!t||typeof t!="string"?t:t.replace(lR,(e,s)=>`${s}=***REDACTED***`)}var uR=7e3,dR=4e3;function fR(t,e=null){let s=cR(t),o=mT(s),n=e==="read_file"?uR:iR,r=e==="read_file"?dR:aR;if(o>n)try{let{compressToolResult:i}=ln();return i(s,r)}catch{return s}return s}function Ey(t){try{let{getActiveModel:e}=ut(),s=e(),o=s?`${s.provider}:${s.id}`:"default";if(sa.has(o))return sa.get(o);let n=dy(t);return sa.set(o,n),n}catch{return dy(t)}}function hR(){sa.clear()}function pR(t,e){let s=new Set(e);return(t||[]).some(o=>o.role!=="assistant"?!1:Array.isArray(o.tool_calls)?o.tool_calls.some(n=>s.has(n?.function?.name||n?.name)):Array.isArray(o.content)?o.content.some(n=>n?.type==="tool_use"&&s.has(n?.name)):!1)}var pr={hash:null,ts:0},mR=3e4;async function Ty(){if(pr.hash&&Date.now()-pr.ts<mR)return pr.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")],n=(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}=Ho(),a=i();a&&n.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Fe.existsSync(i)){let a=await t.stat(i);n.push(`brain:${a.mtimeMs}`)}}catch{}let r=n.join("|");return pr={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function cu(){hr=null,iu=null,pr={hash:null,ts:0},ro=null}var gR=new Set(["spawn_agents"]),Kc=10,Xc=10,Qi=5,my=6e4,Vc=12e4,yR=process.env.NEX_STALE_AUTO_SWITCH!=="0";function wR(t){try{let e=require("fs"),s=require("path"),o=s.join(process.cwd(),".nex","plans");e.existsSync(o)||e.mkdirSync(o,{recursive:!0});let n=s.join(o,"current-plan.md");e.writeFileSync(n,t,"utf-8")}catch{}}NT(t=>{AT(t,"allow"),OT(),console.log(`${p.green} \u2713 ${t}: always allow${p.reset}`)});async function $R(t){let e=t.function.name,s=dT(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let d=ft().find(h=>h.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return I(`${p.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${p.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
837
+ \u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,u=0,c=-1,d=0;for(;u<e;){let h=t.indexOf(r,d);if(h===-1)break;u++,c=h+r.length,d=h+1}return{text:c>0?t.slice(0,c)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:s}}var Zc=null,Qc=null,eu=null;function ht(){if(Zc===null){let{TOOL_DEFINITIONS:t}=Ao();Zc=t}return Qc===null&&(Qc=TR()),eu===null&&(eu=vR()),[...Zc,...Qc,...eu]}var fu=50;function UR(t){Number.isFinite(t)&&t>0&&(fu=t)}var ra=()=>null;function WR(t){ra=t}var mr=null,hu=null,uo=null,fo="",ho=0,pu="",mu=0,ia=new Map,HR=1e4,YR=6e3,GR=/\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 zR(t){return!t||typeof t!="string"?t:t.replace(GR,(e,n)=>`${n}=***REDACTED***`)}var KR=7e3,XR=4e3;function VR(t,e=null){let n=zR(t),o=QT(n),s=e==="read_file"?KR:HR,r=e==="read_file"?XR:YR;if(o>s)try{let{compressToolResult:i}=dn();return i(n,r)}catch{return n}return n}function Vy(t){try{let{getActiveModel:e}=dt(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(ia.has(o))return ia.get(o);let s=My(t);return ia.set(o,s),s}catch{return My(t)}}function JR(){ia.clear()}function ZR(t,e){let n=new Set(e);return(t||[]).some(o=>o.role!=="assistant"?!1:Array.isArray(o.tool_calls)?o.tool_calls.some(s=>n.has(s?.function?.name||s?.name)):Array.isArray(o.content)?o.content.some(s=>s?.type==="tool_use"&&n.has(s?.name)):!1)}var gr={hash:null,ts:0},QR=3e4;async function Jy(){if(gr.hash&&Date.now()-gr.ts<QR)return gr.hash;try{let t=require("fs").promises,e=require("path"),n=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(n.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=Go(),a=i();a&&s.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Be.existsSync(i)){let a=await t.stat(i);s.push(`brain:${a.mtimeMs}`)}}catch{}let r=s.join("|");return gr={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function gu(){mr=null,hu=null,gr={hash:null,ts:0},uo=null}var e1=new Set(["spawn_agents"]),tu=10,nu=10,na=5,Dy=6e4,su=12e4,t1=process.env.NEX_STALE_AUTO_SWITCH!=="0";function n1(t){try{let e=require("fs"),n=require("path"),o=n.join(process.cwd(),".nex","plans");e.existsSync(o)||e.mkdirSync(o,{recursive:!0});let s=n.join(o,"current-plan.md");e.writeFileSync(s,t,"utf-8")}catch{}}gR(t=>{pR(t,"allow"),mR(),console.log(`${p.green} \u2713 ${t}: always allow${p.reset}`)});async function s1(t){let e=t.function.name,n=XT(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!n){let d=ht().find(h=>h.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return L(`${p.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${p.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
830
838
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
831
839
 
832
840
  Expected JSON schema for "${e}":
833
841
  ${f}
834
842
 
835
- Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}if(s&&typeof s.path=="string")try{let c=require("os"),d=He.resolve(process.cwd(),s.path.replace(/^~/,c.homedir())),f=s.path;s.path=He.relative(process.cwd(),d)||".",Object.defineProperty(s,"_originalPath",{value:f,enumerable:!1})}catch(c){console.error("path resolution failed:",c.message)}let n=YT(e,s);if(!n.valid){I(`${p.yellow} \u26A0 ${e}: ${n.error.split(`
836
- `)[0]}${p.reset}`);let c=(yy.get(e)||0)+1;yy.set(e,c);let d=c>=2?`${n.error}
843
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}if(n&&typeof n.path=="string")try{let c=require("os"),d=Ge.resolve(process.cwd(),n.path.replace(/^~/,c.homedir())),f=n.path;n.path=Ge.relative(process.cwd(),d)||".",Object.defineProperty(n,"_originalPath",{value:f,enumerable:!1})}catch(c){console.error("path resolution failed:",c.message)}let s=AR(e,n);if(!s.valid){L(`${p.yellow} \u26A0 ${e}: ${s.error.split(`
844
+ `)[0]}${p.reset}`);let c=(Fy.get(e)||0)+1;Fy.set(e,c);let d=c>=2?`${s.error}
837
845
 
838
- [SYSTEM: This is argument error #${c} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:n.error;return{callId:o,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:o}}}let r=n.corrected||s;if(n.corrected){let c=Object.keys(s),d=Object.keys(n.corrected),f=c.filter(h=>!d.includes(h));f.length&&console.log(`${p.dim} \u2713 ${e}: corrected args (${f.join(", ")})${p.reset}`)}if(wr()&&!by.has(e))return console.log(`${p.yellow} \u2717 ${e}: blocked in plan mode${p.reset}`),{callId:o,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:o}};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(c=>c.background===!0);if($e&&Ae==="plan"&&!i.has(e)&&!e.startsWith("skill_")&&!l)return jn++,I(`${p.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${jn})${p.reset}`),{callId:o,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:o}};if($e&&Ae==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return I(`${p.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${p.reset}`),{callId:o,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:o}};let u=CT(e);if(u==="deny")return console.log(`${p.red} \u2717 ${e}: denied by permissions${p.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:o}};if(u==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await $y(c,{toolName:e})?{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:o,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:o}}}return{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function bR(t,e,s={}){let o=await HT(t,e);if(o!==null)return o;let n=await FT(t,e);return n!==null?n:fT(t,e,s)}function _R(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(lT(t.fnName,t.args));let s=ay("pre-tool",{tool_name:t.fnName}),o=s.results;if(s.blocked){let $=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${s.blockReason}`;e||console.log(`${p.yellow} [hook pre-tool] BLOCKED: ${s.blockReason}${p.reset}`);let k=nu(t.fnName,t.args,$,!0);return e||console.log(k),{msg:{role:"tool",content:$,tool_call_id:t.callId},summary:k}}if(!e&&o.length>0)for(let $ of o)$.success?console.log(`${p.dim} [hook pre-tool] ${$.command} \u2192 ${$.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook pre-tool] ${$.command} \u2192 ERROR: ${$.error}${p.reset}`);hn?.onToolStart&&hn.onToolStart(t.fnName,t.args);let n=await bR(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;n&&typeof n=="object"&&n.text?(i=String(n.text),Array.isArray(n.images)&&n.images.length>0&&(r=n.images)):i=String(n??"");let a=i.length>5e4?i.substring(0,5e4)+`
846
+ [SYSTEM: This is argument error #${c} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:s.error;return{callId:o,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:o}}}let r=s.corrected||n;if(s.corrected){let c=Object.keys(n),d=Object.keys(s.corrected),f=c.filter(h=>!d.includes(h));f.length&&console.log(`${p.dim} \u2713 ${e}: corrected args (${f.join(", ")})${p.reset}`)}if(_r()&&!Hy.has(e))return console.log(`${p.yellow} \u2717 ${e}: blocked in plan mode${p.reset}`),{callId:o,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:o}};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(c=>c.background===!0);if(ye&&Te==="plan"&&!i.has(e)&&!e.startsWith("skill_")&&!l)return Dn++,br=e,L(`${p.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${Dn})${p.reset}`),{callId:o,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:o}};if(ye&&Te==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return L(`${p.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${p.reset}`),{callId:o,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:o}};let u=hR(e);if(u==="deny")return console.log(`${p.red} \u2717 ${e}: denied by permissions${p.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:o}};if(u==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Wy(c,{toolName:e})?{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:o,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:o}}}return{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function o1(t,e,n={}){let o=await RR(t,e);if(o!==null)return o;let s=await SR(t,e);return s!==null?s:VT(t,e,n)}function r1(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 ou(t,e=!1){e||console.log(GT(t.fnName,t.args));let n=Ay("pre-tool",{tool_name:t.fnName}),o=n.results;if(n.blocked){let $=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${n.blockReason}`;e||console.log(`${p.yellow} [hook pre-tool] BLOCKED: ${n.blockReason}${p.reset}`);let x=cu(t.fnName,t.args,$,!0);return e||console.log(x),{msg:{role:"tool",content:$,tool_call_id:t.callId},summary:x}}if(!e&&o.length>0)for(let $ of o)$.success?console.log(`${p.dim} [hook pre-tool] ${$.command} \u2192 ${$.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook pre-tool] ${$.command} \u2192 ERROR: ${$.error}${p.reset}`);yn?.onToolStart&&yn.onToolStart(t.fnName,t.args);let s=await o1(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;s&&typeof s=="object"&&s.text?(i=String(s.text),Array.isArray(s.images)&&s.images.length>0&&(r=s.images)):i=String(s??"");let a=i.length>5e4?i.substring(0,5e4)+`
839
847
  ...(truncated ${i.length-5e4} chars)`:i,l=a.split(`
840
- `)[0],u=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),c=nu(t.fnName,t.args,a,u);e||console.log(c),hn?.onToolEnd&&hn.onToolEnd(t.fnName,c,!u);let f=ay("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let $ of f)$.success?console.log(`${p.dim} [hook post-tool] ${$.command} \u2192 ${$.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook post-tool] ${$.command} \u2192 ERROR: ${$.error}${p.reset}`);let m=fR(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let $=t.args.command.trim();!/cat\s*>|<</.test($)&&/\bcat\s+\S/.test($)?m+=`
848
+ `)[0],u=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),c=cu(t.fnName,t.args,a,u);e||console.log(c),yn?.onToolEnd&&yn.onToolEnd(t.fnName,c,!u);let f=Ay("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let $ of f)$.success?console.log(`${p.dim} [hook post-tool] ${$.command} \u2192 ${$.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook post-tool] ${$.command} \u2192 ERROR: ${$.error}${p.reset}`);let m=VR(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let $=t.args.command.trim();!/cat\s*>|<</.test($)&&/\bcat\s+\S/.test($)?m+=`
841
849
  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+=`
842
850
  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+=`
843
- 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:c}}var kR=[{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 Zc(t){for(let{re:e,label:s}of kR){let o=t.match(e);if(o){let n=(o[1]||"").trim();return n?`${s}: ${n}`:s}}return null}async function xR(t,e=!1,s={}){let o=new Array(t.length),n=[],r=[],i=null;if(e&&!s.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let c=l[0],d=_R(c.fnName,c.args);u=`\u23FA ${c.fnName}${d?`(${d})`:""}`}else{let c=l.map(d=>d.fnName).join(", ");u=`\u23FA ${l.length} tools: ${c.length>60?c.substring(0,57)+"\u2026":c}`}i=new so(u),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:c}=await Jc(t[l],e);o[l]=u,n.push(c)}else{let l=r.map(c=>Jc(t[c],e)),u=await Promise.all(l);for(let c=0;c<r.length;c++)o[r[c]]=u[c].msg,n.push(u[c].summary)}r=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await a(),o[l]=u.errorResult,n.push(nu(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(gR.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:c,summary:d}=await Jc(u,e);o[l]=c,n.push(d)}else r.push(l)}if(await a(),i&&i.stop(),e&&n.length>0&&!s.skipSummaries)for(let l of n)console.log(l);return{results:o,summaries:n}}var P=[],gy=300,Ry=900*1e3;function dn(t,e){let s=t.get(e);return s?Date.now()-s.ts>Ry?(t.delete(e),0):s.count:0}function ys(t,e){let s=t.get(e),o=s&&Date.now()-s.ts<=Ry?s.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function Qc(t,e,s){t.set(e,{count:s,ts:Date.now()})}var wu=new Map,Cy=new Map,oa=new Map,$r=new Set,Ay=new Map,ra=new Map,br=new Set,kn=new Map,In=new Map,_r=new Map,Dt=new Map,ks=new Map,yy=new Map,ma=new Map,uu=new Map,qt=0,mr=0,ia=0,du="",aa=0,Ot=!1,ea=0,la=0,ws=-1,fu=!1,ca=0,ua=!1,Bt=0,Ut=!1,Zt=0,Wt=0,at=!1,kt="",gr=0,Ln=0,da="",$s=0,bs=0,fa="",ur=0,Ft=!1,hu=!1,kr=new Map,xr=new Set,yr=null,eu=!1,dr=0,wy=!1,Ae="plan",ga=0,$e=!1,jn=0,xn=null,pu=null,mu=null,lo=0,co=0,uo=0,fo=!1,ho=0,po=null,xs=[];function no(t,e){t===du?(aa++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${aa})${p.reset}
844
- `)):(du=t,aa=1,I(`${e} \u26A0 ${t}${p.reset}`))}var ha=[];function SR(t){ha.push(t.trim())}function vR(){return ha.length===0?null:ha.splice(0,ha.length).join(`
845
- `)}function ER(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,s=e!==null?`
846
- Duration: ${e}s`:"",o=typeof t.result.result=="string"?t.result.result.slice(0,4e3):JSON.stringify(t.result.result||"").slice(0,4e3),n=t.result.filesModified&&t.result.filesModified.length>0?`
851
+ 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:c}}var i1=[{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 ru(t){for(let{re:e,label:n}of i1){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function a1(t,e=!1,n={}){let o=new Array(t.length),s=[],r=[],i=null;if(e&&!n.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let c=l[0],d=r1(c.fnName,c.args);u=`\u23FA ${c.fnName}${d?`(${d})`:""}`}else{let c=l.map(d=>d.fnName).join(", ");u=`\u23FA ${l.length} tools: ${c.length>60?c.substring(0,57)+"\u2026":c}`}i=new lo(u),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:c}=await ou(t[l],e);o[l]=u,s.push(c)}else{let l=r.map(c=>ou(t[c],e)),u=await Promise.all(l);for(let c=0;c<r.length;c++)o[r[c]]=u[c].msg,s.push(u[c].summary)}r=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await a(),o[l]=u.errorResult,s.push(cu(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(e1.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:c,summary:d}=await ou(u,e);o[l]=c,s.push(d)}else r.push(l)}if(await a(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let l of s)console.log(l);return{results:o,summaries:s}}var O=[],qy=300,Zy=900*1e3;function pn(t,e){let n=t.get(e);return n?Date.now()-n.ts>Zy?(t.delete(e),0):n.count:0}function ws(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=Zy?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function iu(t,e,n){t.set(e,{count:n,ts:Date.now()})}var Eu=new Map,Qy=new Map,aa=new Map,xr=new Set,e0=new Map,la=new Map,kr=new Set,gn=new Map,En=new Map,Sr=new Map,qt=new Map,Ss=new Map,Fy=new Map,wa=new Map,yu=new Map,Ft=0,yr=0,ca=0,wu="",ua=0,Nt=!1,sa=0,da=0,bs=-1,$u=!1,fa=0,ha=!1,Ut=0,Wt=!1,en=0,Ht=0,ct=!1,kt="",wr=0,jn=0,pa="",_s=0,xs=0,ma="",fr=0,Bt=!1,bu=!1,vr=new Map,Er=new Set,$r=null,au=!1,hr=0,By=!1,Te="plan",$a=0,ye=!1,Dn=0,br=null,nn=null,_u=null,xu=null,po=0,mo=0,go=0,yo=!1,wo=0,vs=null,Es=[],$s=new Set;function l1(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function Uy(t){let e=String(t||"");if(!e)return!1;let n=/(?:^|\s)(?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html)\b/i.test(e),o=/\b(create|write|add|make|build|scaffold)\b[\s\S]{0,160}\b(refactor|rename|improve|update|change|edit)\b/i.test(e)||/\b(refactor|update|change|edit)\b[\s\S]{0,160}\b(create|write|add|make|build|scaffold)\b/i.test(e),s=/\b(create|write|add|make|build|refactor|update|change|edit)\b[\s\S]{0,160}\bfile\b/i.test(e);return n&&(o||s)}function ku(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function c1(t){let n=String(t||"").match(/(?:^|\s)((?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html))\b/gi);return n?[...new Set(n.map(o=>ku(o)))]:[]}function ao(t,e){t===wu?(ua++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${ua})${p.reset}
852
+ `)):(wu=t,ua=1,L(`${e} \u26A0 ${t}${p.reset}`))}var ga=[];function u1(t){ga.push(t.trim())}function d1(){return ga.length===0?null:ga.splice(0,ga.length).join(`
853
+ `)}function f1(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,n=e!==null?`
854
+ Duration: ${e}s`:"",o=typeof t.result.result=="string"?t.result.result.slice(0,4e3):JSON.stringify(t.result.result||"").slice(0,4e3),s=t.result.filesModified&&t.result.filesModified.length>0?`
847
855
  Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
848
856
  Job: ${t.jobId}
849
- Task: "${t.agentDef.task}"`+s+`
850
- Status: ${t.result.status||"done"}`+n+`
851
- Result: ${o}`}function ta(t,e){let{getCompletedJobs:s}=to(),o=s();for(let n of o){let r={role:"user",content:ER(n)};t.push(r),e.push(r);let i=n.result?.status||"done",a=i==="failed"?p.red+" \u2717":p.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${n.agentDef.task.slice(0,50)} \u2014 ${String(n.result?.result||"").slice(0,80)}${p.reset}
852
- `)}}function Oy(t,e){let s=[],o=new Set([...e.keys(),...$r,...br]);if(!o.size||!t)return s;for(let n of o){let r=n.split("/").pop();if(r&&(t.includes(r)||t.includes(n))){let a=t.split(`
853
- `).find(l=>l.includes(r)||l.includes(n));s.push({file:n,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return s}function TR(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"]),o=new Set,n=[];for(let r of e){let i=r.toLowerCase();s.has(i)||o.has(i)||(o.add(i),n.push(r))}return n.sort((r,i)=>i.length-r.length),n.slice(0,6)}function RR(){return Fe.existsSync(He.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":Fe.existsSync(He.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function fn(t){let e=RR();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}`}function CR(t,e,s){let o=[...t||[]].slice(0,6).join(", ")||"recently modified files",n=(e||[]).slice(0,3),r=(s||[]).slice(0,3),i=[`[SYSTEM] You already changed code in: ${o}.`,"Run one narrow verification step next before more exploration."];return n.length>0&&i.push(`Suggested verification commands: ${n.join(" | ")}`),r.length>0&&i.push(`Likely related tests: ${r.join(", ")}`),i.push("Do not continue broad read/search loops until the latest edit has been checked."),i.join(`
854
- `)}function AR(t){if(!t||!t.fnName||!["bash","ssh_exec"].includes(t.fnName))return!1;let e=String(t.args?.command||"").toLowerCase();return/\b(test|jest|vitest|pytest|mocha|rspec|phpunit|cargo test|go test|tsc|build|lint|eslint|check)\b/.test(e)}async function Ny(t){let e=TR(t);if(e.length===0)return[];let{searchContentIndex:s}=sn(),o=[],n=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(!n.has(l)&&(n.add(l),o.push(a),o.length>=5))return o}}catch{}return o}async function My(t){let e=await Ny(t);if(e.length===0)return"";let{getRelatedFiles:s,findSymbolReferences:o}=sn(),n=["Likely symbol targets:"];for(let r=0;r<e.length;r++){let i=e[r],a=Math.max(1,i.line-20),l=i.line+40;n.push(`${r+1}. ${i.name} (${i.type}) in ${i.file}:${i.line} -> read_file(path='${i.file}', line_start=${a}, line_end=${l})`);try{let u=await s(i.file,process.cwd(),3);u.length>0&&n.push(` Follow-up files: ${u.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}try{let u=await o(i.name,process.cwd(),{excludeFile:i.file,excludeLine:i.line,limit:2});u.length>0&&n.push(` Likely callers/usages: ${u.map(c=>`${c.file}:${c.line}`).join(", ")} (read these next if behavior depends on where ${i.name} is invoked)`)}catch{}}return`${n.join(`
857
+ Task: "${t.agentDef.task}"`+n+`
858
+ Status: ${t.result.status||"done"}`+s+`
859
+ Result: ${o}`}function oa(t,e){let{getCompletedJobs:n}=io(),o=n();for(let s of o){let r={role:"user",content:f1(s)};t.push(r),e.push(r);let i=s.result?.status||"done",a=i==="failed"?p.red+" \u2717":p.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${s.agentDef.task.slice(0,50)} \u2014 ${String(s.result?.result||"").slice(0,80)}${p.reset}
860
+ `)}}function t0(t,e){let n=[],o=new Set([...e.keys(),...xr,...kr]);if(!o.size||!t)return n;for(let s of o){let r=s.split("/").pop();if(r&&(t.includes(r)||t.includes(s))){let a=t.split(`
861
+ `).find(l=>l.includes(r)||l.includes(s));n.push({file:s,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return n}function h1(t){if(!t||typeof t!="string")return[];let e=t.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g)||[],n=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"]),o=new Set,s=[];for(let r of e){let i=r.toLowerCase();n.has(i)||o.has(i)||(o.add(i),s.push(r))}return s.sort((r,i)=>i.length-r.length),s.slice(0,6)}function p1(){return Be.existsSync(Ge.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":Be.existsSync(Ge.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function mn(t){let e=p1();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}`}function m1(t,e,n){let o=[...t||[]].slice(0,6).join(", ")||"recently modified files",s=(e||[]).slice(0,3),r=(n||[]).slice(0,3),i=[`[SYSTEM] You already changed code in: ${o}.`,"Run one narrow verification step next before more exploration."];return s.length>0&&i.push(`Suggested verification commands: ${s.join(" | ")}`),r.length>0&&i.push(`Likely related tests: ${r.join(", ")}`),i.push("Do not continue broad read/search loops until the latest edit has been checked."),i.join(`
862
+ `)}function g1(t){if(!t||!t.fnName||!["bash","ssh_exec"].includes(t.fnName))return!1;let e=String(t.args?.command||"").toLowerCase();return/\b(test|jest|vitest|pytest|mocha|rspec|phpunit|cargo test|go test|tsc|build|lint|eslint|check)\b/.test(e)}async function n0(t){let e=h1(t);if(e.length===0)return[];let{searchContentIndex:n}=an(),o=[],s=new Set;for(let r of e)try{let i=await n(r,void 0,process.cwd());for(let a of i.slice(0,3)){let l=`${a.file}:${a.name}:${a.line}`;if(!s.has(l)&&(s.add(l),o.push(a),o.length>=5))return o}}catch{}return o}async function s0(t){let e=await n0(t);if(e.length===0)return"";let{getRelatedFiles:n,findSymbolReferences:o}=an(),s=["Likely symbol targets:"];for(let r=0;r<e.length;r++){let i=e[r],a=Math.max(1,i.line-20),l=i.line+40;s.push(`${r+1}. ${i.name} (${i.type}) in ${i.file}:${i.line} -> read_file(path='${i.file}', line_start=${a}, line_end=${l})`);try{let u=await n(i.file,process.cwd(),3);u.length>0&&s.push(` Follow-up files: ${u.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}try{let u=await o(i.name,process.cwd(),{excludeFile:i.file,excludeLine:i.line,limit:2});u.length>0&&s.push(` Likely callers/usages: ${u.map(c=>`${c.file}:${c.line}`).join(", ")} (read these next if behavior depends on where ${i.name} is invoked)`)}catch{}}return`${s.join(`
855
863
  `)}
856
864
  Use these exact targeted reads before broader searching.
857
865
 
858
- `}async function ya(t){let{getFileIndex:e}=sn(),{buildContentIndex:s,findSymbolReferences:o,getRelatedFiles:n}=sn(),i=e().filter(u=>/^tests?\//.test(u)||/\.test\./.test(u)||/\.spec\./.test(u));if(i.length===0)return[];let a=new Set,l=await s(process.cwd());for(let u of t||[]){let c=String(u),d=He.basename(c).replace(/\.[^.]+$/,"");if(d.length<3)continue;for(let m of i)if(m.includes(d)&&a.add(m),a.size>=4)return[...a];try{let m=await n(c,process.cwd(),4);for(let g of m){let $=He.basename(g).replace(/\.[^.]+$/,"");if(!($.length<3)){for(let k of i)if(k.includes($)&&a.add(k),a.size>=4)return[...a]}}}catch{}let h=(Array.isArray(l.files?.[c]?.defs)?l.files[c].defs:[]).filter(m=>["function","class","export"].includes(m.type)).map(m=>m.name).filter((m,g,$)=>m&&$.indexOf(m)===g).slice(0,3);for(let m of h)try{let g=await o(m,process.cwd(),{excludeFile:c,limit:8});for(let $ of g)if(i.includes($.file)&&a.add($.file),a.size>=4)return[...a]}catch{}}return[...a]}function OR(t,e={}){if(!Array.isArray(t)||t.length===0)return[];let s=t.slice(0,4).join(" "),o=[],n=String(e.test||"");return/vitest/.test(n)||Fe.existsSync(He.join(process.cwd(),"vitest.config.ts"))||Fe.existsSync(He.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${s}`):(/jest/.test(n)||Fe.existsSync(He.join(process.cwd(),"jest.config.js"))||Fe.existsSync(He.join(process.cwd(),"jest.config.cjs"))||Fe.existsSync(He.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${s}`),(Fe.existsSync(He.join(process.cwd(),"pytest.ini"))||Fe.existsSync(He.join(process.cwd(),"pyproject.toml")))&&t.some(r=>/\.py$/i.test(r))&&o.push(`pytest ${t.filter(r=>/\.py$/i.test(r)).slice(0,4).join(" ")}`),o}async function fr(t,e,s,o){if(!$e)return null;let n=Ae;Ae=t,ga=0,xn=su(t,po),t==="verify"&&(co=0,uo=0,fo=!1,ho=0),Bt=0,Ut=!1,Zt=0,Wt=0,ks.clear(),ma.clear(),wu.clear(),_r.clear(),t==="implement"&&(xs=Oy(e||"",kn));let r=xs.length>0?`
866
+ `}async function ba(t){let{getFileIndex:e}=an(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=an(),i=e().filter(u=>/^tests?\//.test(u)||/\.test\./.test(u)||/\.spec\./.test(u));if(i.length===0)return[];let a=new Set,l=await n(process.cwd());for(let u of t||[]){let c=String(u),d=Ge.basename(c).replace(/\.[^.]+$/,"");if(d.length<3)continue;for(let m of i)if(m.includes(d)&&a.add(m),a.size>=4)return[...a];try{let m=await s(c,process.cwd(),4);for(let g of m){let $=Ge.basename(g).replace(/\.[^.]+$/,"");if(!($.length<3)){for(let x of i)if(x.includes($)&&a.add(x),a.size>=4)return[...a]}}}catch{}let h=(Array.isArray(l.files?.[c]?.defs)?l.files[c].defs:[]).filter(m=>["function","class","export"].includes(m.type)).map(m=>m.name).filter((m,g,$)=>m&&$.indexOf(m)===g).slice(0,3);for(let m of h)try{let g=await o(m,process.cwd(),{excludeFile:c,limit:8});for(let $ of g)if(i.includes($.file)&&a.add($.file),a.size>=4)return[...a]}catch{}}return[...a]}function y1(t,e={}){if(!Array.isArray(t)||t.length===0)return[];let n=t.slice(0,4).join(" "),o=[],s=String(e.test||"");return/vitest/.test(s)||Be.existsSync(Ge.join(process.cwd(),"vitest.config.ts"))||Be.existsSync(Ge.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${n}`):(/jest/.test(s)||Be.existsSync(Ge.join(process.cwd(),"jest.config.js"))||Be.existsSync(Ge.join(process.cwd(),"jest.config.cjs"))||Be.existsSync(Ge.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${n}`),(Be.existsSync(Ge.join(process.cwd(),"pytest.ini"))||Be.existsSync(Ge.join(process.cwd(),"pyproject.toml")))&&t.some(r=>/\.py$/i.test(r))&&o.push(`pytest ${t.filter(r=>/\.py$/i.test(r)).slice(0,4).join(" ")}`),o}async function pr(t,e,n,o){if(!ye)return null;let s=Te;Te=t,$a=0,nn=uu(t,vs),t==="verify"&&(mo=0,go=0,yo=!1,wo=0),Ut=0,Wt=!1,en=0,Ht=0,Ss.clear(),wa.clear(),Eu.clear(),Sr.clear(),t==="implement"&&(Es=t0(e||"",gn));let r=Es.length>0?`
859
867
 
860
868
  ACTION ITEMS (execute these in order, do NOT re-read these files):
861
- `+xs.map((l,u)=>`${u+1}. ${l.file} \u2014 ${l.action}`).join(`
862
- `):"",i=await My(t==="verify"?o:e||o||""),a;if(t==="implement")pu=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
863
- ${pu}
869
+ `+Es.map((l,u)=>`${u+1}. ${l.file} \u2014 ${l.action}`).join(`
870
+ `):"",i=await s0(t==="verify"?o:e||o||""),a;if(t==="implement")_u=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
871
+ ${_u}
864
872
 
865
- ${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){mu=e?.slice(0,500)||"";let l=s?[...s].join(", "):"none",u=await $u(s),c=await ya(s),d=u.length>0?`Suggested checks (run the narrowest ones that fit the change):
873
+ ${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){xu=e?.slice(0,500)||"";let l=n?[...n].join(", "):"none",u=await Tu(n),c=await ba(n),d=u.length>0?`Suggested checks (run the narrowest ones that fit the change):
866
874
  ${u.map((h,m)=>`${m+1}. ${h}`).join(`
867
875
  `)}
868
876
 
@@ -879,21 +887,21 @@ Prefer these before broader suites when a targeted run is possible.
879
887
  Report PASS (all good) or FAIL (list specific issues).
880
888
 
881
889
  Files modified: ${l}
882
- ${i}${d}${f}Summary: ${mu}`}return I(`${p.cyan} \u21B3 Phase transition: ${n} \u2192 ${t} (model: ${xn||"default"})${p.reset}`),a?{role:"user",content:a}:null}async function $u(t){let e=[],o=[...t||[]].map(l=>String(l).toLowerCase()),n={};try{let l=He.join(process.cwd(),"package.json");if(Fe.existsSync(l)){n=JSON.parse(Fe.readFileSync(l,"utf-8")).scripts||{};let c=[["test",fn("test")],["lint",fn("lint")],["typecheck",fn("typecheck")],["check",fn("check")],["build",fn("build")]];for(let[d,f]of c)n[d]&&e.push(f)}}catch{}e.length===0&&(Fe.existsSync(He.join(process.cwd(),"package.json"))&&e.push(fn("test")),(Fe.existsSync(He.join(process.cwd(),"pytest.ini"))||Fe.existsSync(He.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await ya(t);e.unshift(...OR(r,n));let i=o.some(l=>/\.(ts|tsx)$/.test(l)),a=o.some(l=>/\.(js|jsx|ts|tsx)$/.test(l));return i&&!e.includes(fn("typecheck"))&&e.push(fn("typecheck")),a&&!e.includes(fn("lint"))&&e.push(fn("lint")),[...new Set(e)].slice(0,4)}function NR(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(Ly())return"English";let s=String(t||"").trim();if(!s)return"English";if(/[äöüß]/i.test(s))return"German";let o=s.toLowerCase().match(/[a-zA-Zäöüß]+/g)||[],n=new Set(["a","an","and","are","can","do","does","explain","file","folder","for","how","in","is","it","list","of","please","show","the","this","what","where","why","with"]),r=new Set(["aber","analysiere","bitte","das","den","der","die","dies","diese","diesem","du","ein","eine","einer","englisch","erkl\xE4re","f\xFCr","hier","im","ist","mit","ordner","und","warum","was","wie","wieso","zeige"]),i=0,a=0;for(let l of o)n.has(l)&&i++,r.has(l)&&a++;return a>i?"German":(i>a,"English")}function MR(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,o=Ly(),n=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
883
- `];n?r.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?r.push("RESPONSE LANGUAGE: This project requires English. Always respond in English, even if the user writes in another language."):r.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."),r.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),r.push("COMPLETENESS RULES:"),r.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),_s()?r.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."):r.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."),r.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),r.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),r.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),r.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),r.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.'),r.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."),r.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."),r.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.'),r.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).'),r.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)."),r.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."),r.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."),r.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."),r.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.'),r.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 i=e||"English";r.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${i}.`);let a=s||"English";return r.push(`COMMIT MESSAGES: Write all git commit messages in ${a}.`),n&&r.push(`
884
- 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}.`),r.join(`
890
+ ${i}${d}${f}Summary: ${xu}`}return L(`${p.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${nn||"default"})${p.reset}`),a?{role:"user",content:a}:null}async function Tu(t){let e=[],o=[...t||[]].map(l=>String(l).toLowerCase()),s={};try{let l=Ge.join(process.cwd(),"package.json");if(Be.existsSync(l)){s=JSON.parse(Be.readFileSync(l,"utf-8")).scripts||{};let c=[["test",mn("test")],["lint",mn("lint")],["typecheck",mn("typecheck")],["check",mn("check")],["build",mn("build")]];for(let[d,f]of c)s[d]&&e.push(f)}}catch{}e.length===0&&(Be.existsSync(Ge.join(process.cwd(),"package.json"))&&e.push(mn("test")),(Be.existsSync(Ge.join(process.cwd(),"pytest.ini"))||Be.existsSync(Ge.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await ba(t);e.unshift(...y1(r,s));let i=o.some(l=>/\.(ts|tsx)$/.test(l)),a=o.some(l=>/\.(js|jsx|ts|tsx)$/.test(l));return i&&!e.includes(mn("typecheck"))&&e.push(mn("typecheck")),a&&!e.includes(mn("lint"))&&e.push(mn("lint")),[...new Set(e)].slice(0,4)}function w1(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(r0())return"English";let n=String(t||"").trim();if(!n)return"English";if(/[äöüß]/i.test(n))return"German";let o=n.toLowerCase().match(/[a-zA-Zäöüß]+/g)||[],s=new Set(["a","an","and","are","can","do","does","explain","file","folder","for","how","in","is","it","list","of","please","show","the","this","what","where","why","with"]),r=new Set(["aber","analysiere","bitte","das","den","der","die","dies","diese","diesem","du","ein","eine","einer","englisch","erkl\xE4re","f\xFCr","hier","im","ist","mit","ordner","und","warum","was","wie","wieso","zeige"]),i=0,a=0;for(let l of o)s.has(l)&&i++,r.has(l)&&a++;return a>i?"German":(i>a,"English")}function $1(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,o=r0(),s=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
891
+ `];s?r.push(`RESPONSE LANGUAGE: You MUST always respond in ${s}. 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. ${s} only.`):o?r.push("RESPONSE LANGUAGE: This project requires English. Always respond in English, even if the user writes in another language."):r.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."),r.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),r.push("COMPLETENESS RULES:"),r.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),ks()?r.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."):r.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."),r.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),r.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),r.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),r.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),r.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.'),r.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."),r.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."),r.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.'),r.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).'),r.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)."),r.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."),r.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."),r.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."),r.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.'),r.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 i=e||"English";r.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${i}.`);let a=n||"English";return r.push(`COMMIT MESSAGES: Write all git commit messages in ${a}.`),s&&r.push(`
892
+ This is a hard requirement. Always respond in ${s}. 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 ${s}.`),r.join(`
885
893
  `)+`
886
894
 
887
- `}function PR(t){let e=NR(t);return`# Current Turn Language (CRITICAL \u2014 enforce strictly)
895
+ `}function b1(t){let e=w1(t);return`# Current Turn Language (CRITICAL \u2014 enforce strictly)
888
896
  The current user message is in ${e}. You MUST answer this turn in ${e}. Do NOT switch to another language because of repository files, prior conversation, examples, or project instructions.
889
897
 
890
- `}function LR(){if(ro!==null)return ro;try{let e=KT().flatMap(n=>n.models.map(r=>({spec:`${n.name}:${r.id}`,tier:zT(r.id,n.name),name:r.name})));if(e.length<2)return ro="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
898
+ `}function _1(){if(uo!==null)return uo;try{let e=NR().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:OR(r.id,s.name),name:r.name})));if(e.length<2)return uo="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
891
899
  # Sub-Agent Model Routing
892
900
 
893
901
  `;o+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',o+=`| Model | Tier | Auto-assigned for |
894
902
  |---|---|---|
895
- `;for(let n of e)o+=`| ${n.spec} | ${n.tier} | ${s[n.tier]||n.tier} |
896
- `;return ro=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),ro="",""}}var gu="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function IR(t){let e=t.indexOf(gu);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+gu.length).trimStart()}}async function yu(){let t=await Ty()+":"+Qt();if(hr!==null&&t===iu)return hr;let e=await hT(process.cwd()),s=vT(),o=UT(),n=wr()?MT():"",r=MR(),i=ET(),a=VT(Qt());return hr=`${a?`## Model Briefing
903
+ `;for(let s of e)o+=`| ${s.spec} | ${s.tier} | ${n[s.tier]||s.tier} |
904
+ `;return uo=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),uo="",""}}var Su="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function x1(t){let e=t.indexOf(Su);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Su.length).trimStart()}}async function vu(){let t=await Jy()+":"+tn();if(mr!==null&&t===hu)return mr;let e=await JT(process.cwd()),n=cR(),o=ER(),s=_r()?yR():"",r=$1(),i=uR(),a=MR(tn());return mr=`${a?`## Model Briefing
897
905
  ${a}
898
906
 
899
907
  ---
@@ -904,17 +912,17 @@ WORKING DIRECTORY: ${process.cwd()}
904
912
  All relative paths resolve from this directory.
905
913
  PROJECT CONTEXT:
906
914
  ${e}
907
- ${s?`
908
- ${s}
915
+ ${n?`
916
+ ${n}
909
917
  `:""}${o?`
910
918
  ${o}
911
- `:""}${n?`
912
- ${n}
919
+ `:""}${s?`
920
+ ${s}
913
921
  `:""}
914
922
  ${r?`${r}
915
923
  `:""}${i?`${i}
916
924
 
917
- `:""}${_s()?`# YOLO Mode \u2014 Auto-Execute
925
+ `:""}${ks()?`# YOLO Mode \u2014 Auto-Execute
918
926
 
919
927
  You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
920
928
  - NEVER ask for confirmation \u2014 just execute tasks directly
@@ -1154,7 +1162,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
1154
1162
  - Instead: use bash with inline node -e '...' for quick one-off checks.
1155
1163
  - If the test is worth keeping, write it to tests/ with a proper name.
1156
1164
  - Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
1157
- ${LR()}
1165
+ ${_1()}
1158
1166
 
1159
1167
  # Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
1160
1168
 
@@ -1346,91 +1354,91 @@ class ErrorBoundary extends React.Component {
1346
1354
  - Use migrations for schema changes, never manual ALTER TABLE
1347
1355
  - Add database-level constraints (unique, foreign key, check) not just app-level
1348
1356
 
1349
- `,iu=t,hr}function Py(){wu.clear(),Cy.clear(),oa.clear(),$r.clear(),Ay.clear(),ra.clear(),br.clear(),kn.clear(),In.clear(),_r.clear(),Dt.clear(),ks.clear(),ma.clear(),uu.clear(),qt=0,mr=0,ia=0,Ot=!1,la=0,ws=-1,fu=!1,ca=0,ua=!1,Bt=0,Ut=!1,Zt=0,Wt=0,at=!1,kt="",gr=0,da="",$s=0,fa="",bs=0,Ft=!1,hu=!1,Ae="plan",ga=0,$e=!1,xn=null,pu=null,mu=null,xs=[],lo=0,co=0,uo=0,fo=!1,ho=0,jn=0,po=null,kr.clear(),xr.clear(),du="",aa=0}function jR(){P=[],yr=null,io="",ao=0,au="",lu=0,Py();try{let{resetCompactionFailures:t}=nc();t()}catch{}try{let{cancelAllJobs:t}=to();t()}catch{}}function DR(){P.length>gy&&P.splice(0,P.length-gy)}function Ly(){try{let t=require("fs"),s=require("path").join(process.cwd(),"AGENTS.md");if(!t.existsSync(s))return!1;let o=t.readFileSync(s,"utf8");return/all.*english/i.test(o)&&/no german/i.test(o)}catch{return!1}}function tu(t,e,s,o=1500){return!t||!e?!1:t===e&&Date.now()-s<o}function qR(){return P.length}function FR(){return P}function BR(t){P=t}async function UR(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),o=(d,f)=>new Promise(h=>{t(d,f,{cwd:s,timeout:3e3},(m,g)=>{h(m?"":(g||"").trim())})}),[n]=await Promise.all([o("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=(n?n.split(`
1350
- `):[]).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 u=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,c=He.join(s,"package.json");if(e.existsSync(c))try{let d=JSON.parse(e.readFileSync(c,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let h=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";u+=`
1351
- \u{1F4E6} ${h}${m}`}}catch{}return u}function WR(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 Le(t,e,s,o,n,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((u,c)=>u+c,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,l=0;if(n){let u=Date.now()-n;l=Math.round(u/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(`
1352
- ${p.dim} ${a}${p.reset}`),l>=30&&process.stdout.isTTY){let u=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`;WR(u)}if(xr.size>0&&kr.size>0)for(let u of xr){let c=kr.get(u);c&&console.log(`${p.dim} \u2714 task #${u} auto-matched: ${c.slice(0,60)}${p.reset}`)}s.size>0?console.log(`${p.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${p.reset}`):!r&&o.size>=5&&s.size===0&&t>=3?console.log(`${p.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${p.reset}`):o.size>0&&t>=2&&console.log(`${p.dim} \u{1F4A1} /save \xB7 /clear${p.reset}`)}async function HR(){if(!process.stdout.isTTY)return{action:"quit"};let t=oo(),e=Qt(),s=pa.fast?.[t],o=pa.strong?.[t],n=s&&s!==e,r=o&&o!==e&&o!==s,i=[];i.push({key:"r",label:`Retry with current model ${p.dim}(${e})${p.reset}`}),n&&i.push({key:"f",label:`Switch to ${p.bold}${s}${p.reset} ${p.dim}\u2014 fast, low latency${p.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${p.bold}${o}${p.reset} ${p.dim}\u2014 reliable tool-calling, medium speed${p.reset}`,model:o}),i.push({key:"q",label:`${p.dim}Quit${p.reset}`}),console.log(),console.log(`${p.yellow} Stream stale \u2014 all retries exhausted.${p.reset} What would you like to do?`);for(let a of i)console.log(` ${p.cyan}[${a.key}]${p.reset} ${a.label}`);return process.stdout.write(` ${p.yellow}> ${p.reset}`),new Promise(a=>{let l=process.stdin,u=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let c=!1,d=f=>{if(c)return;c=!0,l.removeListener("data",d),l.setRawMode(u||!1),l.pause();let h=f.toLowerCase().trim();if(process.stdout.write(`${h}
1353
- `),f==="")return a({action:"quit"});let m=i.find(g=>g.key===h);!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 GR(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,s=new Set,o;for(;(o=e.exec(t))!==null;){let n=o[1].replace(/\/$/,"");n.length>1&&n.split("/").filter(i=>i.length>2).forEach(i=>s.add(i))}return Array.from(s)}function YR(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 hn=null;async function zR(t,e=null,s={}){let o=XT(Qt());my=o.staleWarn,Vc=o.staleAbort,hn=e;let n=t;if(yr&&typeof t=="string"&&(n=`${yr}
1357
+ `,hu=t,mr}function o0(){Eu.clear(),Qy.clear(),aa.clear(),xr.clear(),e0.clear(),la.clear(),kr.clear(),gn.clear(),En.clear(),Sr.clear(),qt.clear(),Ss.clear(),wa.clear(),yu.clear(),Ft=0,yr=0,ca=0,Nt=!1,da=0,bs=-1,$u=!1,fa=0,ha=!1,Ut=0,Wt=!1,en=0,Ht=0,ct=!1,kt="",wr=0,pa="",_s=0,ma="",xs=0,Bt=!1,bu=!1,Te="plan",$a=0,ye=!1,nn=null,_u=null,xu=null,Es=[],po=0,mo=0,go=0,yo=!1,wo=0,Dn=0,vs=null,vr.clear(),Er.clear(),wu="",ua=0}function k1(){O=[],$r=null,fo="",ho=0,pu="",mu=0,o0();try{let{resetCompactionFailures:t}=cc();t()}catch{}try{let{cancelAllJobs:t}=io();t()}catch{}}function S1(){O.length>qy&&O.splice(0,O.length-qy)}function r0(){try{let t=require("fs"),n=require("path").join(process.cwd(),"AGENTS.md");if(!t.existsSync(n))return!1;let o=t.readFileSync(n,"utf8");return/all.*english/i.test(o)&&/no german/i.test(o)}catch{return!1}}function lu(t,e,n,o=1500){return!t||!e?!1:t===e&&Date.now()-n<o}function v1(){return O.length}function E1(){return O}function T1(t){O=t}async function R1(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),o=(d,f)=>new Promise(h=>{t(d,f,{cwd:n,timeout:3e3},(m,g)=>{h(m?"":(g||"").trim())})}),[s]=await Promise.all([o("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=(s?s.split(`
1358
+ `):[]).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 u=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,c=Ge.join(n,"package.json");if(e.existsSync(c))try{let d=JSON.parse(e.readFileSync(c,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let h=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";u+=`
1359
+ \u{1F4E6} ${h}${m}`}}catch{}return u}function C1(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 Ie(t,e,n,o,s,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((u,c)=>u+c,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,l=0;if(s){let u=Date.now()-s;l=Math.round(u/1e3),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}if(n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1360
+ ${p.dim} ${a}${p.reset}`),l>=30&&process.stdout.isTTY){let u=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;C1(u)}if(Er.size>0&&vr.size>0)for(let u of Er){let c=vr.get(u);c&&console.log(`${p.dim} \u2714 task #${u} auto-matched: ${c.slice(0,60)}${p.reset}`)}n.size>0?console.log(`${p.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${p.reset}`):!r&&o.size>=5&&n.size===0&&t>=3?console.log(`${p.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${p.reset}`):o.size>0&&t>=2&&console.log(`${p.dim} \u{1F4A1} /save \xB7 /clear${p.reset}`)}async function A1(){if(!process.stdout.isTTY)return{action:"quit"};let t=co(),e=tn(),n=ya.fast?.[t],o=ya.strong?.[t],s=n&&n!==e,r=o&&o!==e&&o!==n,i=[];i.push({key:"r",label:`Retry with current model ${p.dim}(${e})${p.reset}`}),s&&i.push({key:"f",label:`Switch to ${p.bold}${n}${p.reset} ${p.dim}\u2014 fast, low latency${p.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${p.bold}${o}${p.reset} ${p.dim}\u2014 reliable tool-calling, medium speed${p.reset}`,model:o}),i.push({key:"q",label:`${p.dim}Quit${p.reset}`}),console.log(),console.log(`${p.yellow} Stream stale \u2014 all retries exhausted.${p.reset} What would you like to do?`);for(let a of i)console.log(` ${p.cyan}[${a.key}]${p.reset} ${a.label}`);return process.stdout.write(` ${p.yellow}> ${p.reset}`),new Promise(a=>{let l=process.stdin,u=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let c=!1,d=f=>{if(c)return;c=!0,l.removeListener("data",d),l.setRawMode(u||!1),l.pause();let h=f.toLowerCase().trim();if(process.stdout.write(`${h}
1361
+ `),f==="")return a({action:"quit"});let m=i.find(g=>g.key===h);!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 O1(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,n=new Set,o;for(;(o=e.exec(t))!==null;){let s=o[1].replace(/\/$/,"");s.length>1&&s.split("/").filter(i=>i.length>2).forEach(i=>n.add(i))}return Array.from(n)}function N1(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 yn=null;async function P1(t,e=null,n={}){let o=PR(tn());Dy=o.staleWarn,su=o.staleAbort,yn=e;let s=t;if($r&&typeof t=="string"&&(s=`${$r}
1354
1362
 
1355
- ${t}`,yr=null),typeof n=="string"){let be=GR(n),xe=YR(n);(be.length>0||xe.length>0)&&(n+=`
1363
+ ${t}`,$r=null),typeof s=="string"){let _e=O1(s),ge=N1(s);(_e.length>0||ge.length>0)&&(s+=`
1356
1364
 
1357
1365
  [System Note for Assistant: To resolve this task faster, consider these hints:
1358
- `,be.length>0&&(n+=`- The user mentioned URLs containing the paths/folders: ${be.join(", ")}. Prioritize searching these folder names using glob or grep first.
1359
- `),xe.length>0&&xe.forEach(Te=>{n+=`- ${Te}
1360
- `}),n+="Always prefer parallel search execution if unsure.]")}typeof n=="string"&&vy(n)&&(n+=`
1366
+ `,_e.length>0&&(s+=`- The user mentioned URLs containing the paths/folders: ${_e.join(", ")}. Prioritize searching these folder names using glob or grep first.
1367
+ `),ge.length>0&&ge.forEach(Re=>{s+=`- ${Re}
1368
+ `}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&Xy(s)&&(s+=`
1361
1369
 
1362
- [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?iy(t):null,i=Sy(n);i&&typeof i.then=="function"&&(i=await i),P.push({role:"user",content:i}),DR();let a=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",l=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:be,runOrchestrated:xe}=sy(),Te=be(typeof t=="string"?t:"");if(a&&Te.isComplex&&Te.estimatedGoals>=l){console.log(`${p.yellow}\u26A1 Auto-orchestrate: ${Te.estimatedGoals} goals \u2192 parallel agents${p.reset}`);let tt=await xe(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});if(tt&&tt.synthesis){let nt=tt.synthesis.summary||"",En=tt.synthesis.filesChanged?.length?`
1370
+ [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?Cy(t):null,i=Ky(s);i&&typeof i.then=="function"&&(i=await i),O.push({role:"user",content:i}),S1();let a=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",l=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:_e,runOrchestrated:ge}=Ey(),Re=_e(typeof t=="string"?t:"");if(a&&Re.isComplex&&Re.estimatedGoals>=l){console.log(`${p.yellow}\u26A1 Auto-orchestrate: ${Re.estimatedGoals} goals \u2192 parallel agents${p.reset}`);let Ke=await ge(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});if(Ke&&Ke.synthesis){let rt=Ke.synthesis.summary||"",Rn=Ke.synthesis.filesChanged?.length?`
1363
1371
 
1364
- Files changed: ${tt.synthesis.filesChanged.join(", ")}`:"",Ze=tt.synthesis.conflicts?.length?`
1372
+ Files changed: ${Ke.synthesis.filesChanged.join(", ")}`:"",st=Ke.synthesis.conflicts?.length?`
1365
1373
 
1366
1374
  Conflicts:
1367
- ${tt.synthesis.conflicts.map(Nt=>`- ${Nt}`).join(`
1368
- `)}`:"";P.push({role:"assistant",content:nt+En+Ze}),Ce(P),cr(P)}return tt}Te.isComplex&&process.stdout.isTTY&&console.log(`${p.dim}Hint: ~${Te.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${p.reset}`)}catch{}let{setOnChange:u}=ec(),c=null,d=0;u((be,xe)=>{be==="create"?(c&&c.stop(),c=new aT(xe.name,xe.tasks),c.setStats({tokens:d}),c.start()):be==="update"&&c?c.updateTask(xe.id,xe.status):be==="clear"&&c&&(c.stop(),c=null)});let f=await yu(),h=f;try{let{getBrainContext:be}=fc(),xe=await be(t);xe&&(h=f+`
1369
- `+xe+`
1370
- `)}catch(be){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",be.message)}let g=GT(typeof t=="string"?t:"");if(g.length>0){let be=g.map(xe=>`[Triggered: ${xe.name}]
1371
- ${xe.instructions}`).join(`
1375
+ ${Ke.synthesis.conflicts.map(Pt=>`- ${Pt}`).join(`
1376
+ `)}`:"";O.push({role:"assistant",content:rt+Rn+st}),Oe(O),dr(O)}return Ke}Re.isComplex&&process.stdout.isTTY&&console.log(`${p.dim}Hint: ~${Re.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${p.reset}`)}catch{}let{setOnChange:u}=ac(),c=null,d=0;u((_e,ge)=>{_e==="create"?(c&&c.stop(),c=new YT(ge.name,ge.tasks),c.setStats({tokens:d}),c.start()):_e==="update"&&c?c.updateTask(ge.id,ge.status):_e==="clear"&&c&&(c.stop(),c=null)});let f=await vu(),h=f;try{let{getBrainContext:_e}=$c(),ge=await _e(t);ge&&(h=f+`
1377
+ `+ge+`
1378
+ `)}catch(_e){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",_e.message)}let g=CR(typeof t=="string"?t:"");if(g.length>0){let _e=g.map(ge=>`[Triggered: ${ge.name}]
1379
+ ${ge.instructions}`).join(`
1372
1380
  `);h+=`
1373
- `+be+`
1381
+ `+_e+`
1374
1382
  `}h+=`
1375
- `+PR(t);let $=[{role:"system",content:h},...P];oy(Qt());let k=new so(Wc());k.start();let v=P.length===1,A=v?UR().catch(()=>null):Promise.resolve(null),E=v?TT(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),S=ft(),[{messages:N,compressed:ee,compacted:re,tokensRemoved:le},ue,oe]=await Promise.all([pT($,S),A,E]),ae=Jt($,S);if(k.stop(),ue&&console.log(`${p.dim}${ue}${p.reset}`),re)console.log(`${p.dim} [context compacted \u2014 summary (~${le} tokens freed)]${p.reset}`);else if(ee){let be=ae.limit>0?Math.round(le/ae.limit*100):0;I(`${p.dim} [context compressed \u2014 ~${le} tokens freed (${be}%)]${p.reset}`)}ae.percentage>85&&I(`${p.yellow} \u26A0 Context ${Math.round(ae.percentage)}% used (${Math.round(100-ae.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${p.reset}`);let T=N;if(oe&&v&&(T=[T[0],{role:"user",content:`[Server probe at task start]
1376
- ${oe}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...T.slice(1)]),r&&v){let be=r.shouldPreferSsh?`[Runtime URL detected]
1383
+ `+b1(t);let $=[{role:"system",content:h},...O];Ty(tn());let x=new lo(Vc());x.start();let E=O.length===1,N=E?R1().catch(()=>null):Promise.resolve(null),v=E?dR(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),S=ht(),[{messages:P,compressed:ne,compacted:re,tokensRemoved:ce},de,oe]=await Promise.all([ZT($,S),N,v]),le=Qt($,S);if(x.stop(),de&&console.log(`${p.dim}${de}${p.reset}`),re)console.log(`${p.dim} [context compacted \u2014 summary (~${ce} tokens freed)]${p.reset}`);else if(ne){let _e=le.limit>0?Math.round(ce/le.limit*100):0;L(`${p.dim} [context compressed \u2014 ~${ce} tokens freed (${_e}%)]${p.reset}`)}le.percentage>85&&L(`${p.yellow} \u26A0 Context ${Math.round(le.percentage)}% used (${Math.round(100-le.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${p.reset}`);let T=P;if(oe&&E&&(T=[T[0],{role:"user",content:`[Server probe at task start]
1384
+ ${oe}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...T.slice(1)]),r&&E){let _e=r.shouldPreferSsh?`[Runtime URL detected]
1377
1385
  The user linked a live app URL (${r.url}) and described broken behavior. Treat this as a runtime/deployed-instance issue first. Reproduce it with browser_open or browser_screenshot on the URL before reading local files. Because this URL matches server profile "${r.matchedName}", prefer ssh_exec/service_logs on that server for investigation before local repo inspection.`:`[Runtime URL detected]
1378
- The user linked a live app URL (${r.url}) and described broken behavior. Treat this as a runtime issue first. Reproduce it with browser_open or browser_screenshot before reading local files. Only inspect the local repo after you have confirmed the live behavior.`;T=[T[0],{role:"user",content:be},{role:"assistant",content:"Understood \u2014 I will inspect the live app/runtime first."},...T.slice(1)]}if(v){let be=RT(typeof t=="string"?t:"");be&&(T=[T[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1379
- `+be.user},{role:"assistant",content:be.assistant+`
1380
- [END EXAMPLE \u2014 wait for the real user request below]`},...T.slice(1)])}if(Jt(T,ft()).percentage>=65){let{messages:xe,tokensRemoved:Te}=un(T,ft());Te>0&&(T=xe,console.log(`${p.dim} [pre-flight compress \u2014 ${Te} tokens freed, now ${Math.round(Jt(T,ft()).percentage)}% used]${p.reset}`))}let U=0,Z=0,ye=0,ke=0,De=0,Oe=9,Se=0,_=new Set,L=(()=>{let be=P.find(xe=>xe.role==="user");return typeof be?.content=="string"?be.content:""})(),W=typeof L=="string"?iy(L):null,te=/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(L)||!!W?.shouldPreferSsh,z=!!W,R=0;if(!at){let be=P.filter(Te=>Te.role==="user"||Te.role==="tool").map(Te=>typeof Te.content=="string"?Te.content:"").join(`
1381
- `),xe=Zc(be);xe&&(at=!0,kt=xe.slice(0,120),I(`${p.yellow} \u26A1 Root cause in briefing: ${kt} \u2014 fix phase active from start (read budget: 3)${p.reset}`))}!at&&!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(L)&&(Ft=!0,I(`${p.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${p.reset}`)),P.length<=1&&!s.skipPhaseRouting&&($e=xT(),$e&&(po=kT(L)?.id||"coding",Ae="plan",xn=su("plan",po),ga=0,lo=0,jn=0,process.stdout.isTTY&&console.log(`${p.dim} \u21B3 Phase routing: plan(${xn||"default"}) \u2192 implement \u2192 verify${p.reset}`),I(`${p.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${xn||"default model"} (category: ${po})${p.reset}`)));let H=0,se=new Map,D=new Set,me=new Set,go=new Set,Sn=0,Ru=0,xa=0,Ss=0,Ne=Date.now(),l0=new uT(JT),c0=_r,Xe=s.skillLoop?10:1,u0=3*Xe,d0=5*Xe,Cu=wu,f0=5*Xe,h0=8*Xe,p0=Cy,m0=($e?6:4)*Xe,g0=($e?10:7)*Xe,Sa=oa,y0=($e?5:3)*Xe,Er=($e?8:5)*Xe,w0=Ay,$0=($e?4:3)*Xe,b0=($e?6:4)*Xe,_0=3*Xe,k0=4*Xe,vs=kn,x0=($e?6:4)*Xe,S0=($e?10:8)*Xe,Es=($e?12:10)*Xe,v0=25,Dn=0,E0=10*Xe,T0=15*Xe,qn=0,Au=5*Xe,Fn=0,R0=2*Xe,C0=3,va=0,yo=10,A0=16,Ou=s.skillLoop?999:o.investigationCap,Nu=async()=>{let{hasPendingOrCompletedJobs:be,getPendingJobSummary:xe}=to();if(be()){if(xe()){let Te=Date.now()+45e3;for(process.stderr.write(`${p.cyan} \u23F3 Waiting for background agents to finish\u2026${p.reset}
1382
- `);xe()&&Date.now()<Te;)await new Promise(tt=>setTimeout(tt,500).unref()),ta(P,T)}ta(P,T),P.length>0&&Ce(P)}},vn=typeof t=="string"?t.trim():"",Mu=vn.length>0&&/^\s*(analyze|analyse|analysiere|explain|erkläre|describe|beschreib|review|audit|summari[sz]e|zusammenfass|list|liste|understand|document|documentation|docs|what is|what does|wie funktioniert|wie geht|how does|show me|zeig|show the|show all|tell me about|erzähl)/i.test(vn)&&!/\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(vn),Tr=vn.length>0&&/\b(analyze|analyse|explain|describe|review|audit|summari[sz]e|understand|document|scan|count|inventory|map|list|identify)\b/i.test(vn)&&/\b(create|write|generate|produce|output)\b/i.test(vn)&&/\b([A-Z0-9_-]+\.md|markdown|report|summary|overview|architecture|audit|table|documentation|docs|inventory|catalog)\b/i.test(vn)&&!/\b(fix|bug|crash|error|implement|add(?!\s+(?:to|into)\b)|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|delete|remove|install|setup|deploy|run)\b/i.test(vn),Ge,St=s.maxIterations||($e?gs(Ae):ru);Mu&&(St=Math.min(St,4),I(`${p.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${St}${p.reset}`));let Ea=0,Pu=3,Ta=!1,Rr=0,Ra=!1;e:for(;;){for(Ta=!1,Ge=0;Ge<St&&!na()?.aborted;Ge++){ta(P,T);{let w=ft(),y=Jt(T,w),G=H===0?65:78;if(y.percentage>=G){if(D.size>0||$e&&Ae!=="plan"){let Q=gT(P,{filesModified:D,currentPhase:$e?Ae:null});if(Q){let q=T.findIndex(M=>M._progressSnapshot);q!==-1&&T.splice(q,1);let ce=T.findIndex(M=>M.role==="system");T.splice(ce+1,0,Q)}}let{messages:B,tokensRemoved:C}=un(T,w,H===0);if(C>0&&(T=B,C>50&&console.log(`${p.dim} [auto-compressed \u2014 ~${C} tokens freed, now ${Math.round(Jt(T,w).percentage)}%]${p.reset}`),Ft&&D.size>=3)){let Q=[...D].map(ce=>ce.split("/").pop()).slice(0,10).join(", "),q={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${D.size} files: ${Q}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};T.push(q)}}}if(Ot&&!at&&gr<2){gr++;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."};T.push(w),P.push(w),I(`${p.yellow} \u26A0 Pre-call SSH-blocked nudge #${gr} injected \u2014 model told to synthesize${p.reset}`)}Ot||(gr=0);let xe=!0;H>0&&jT();let Te=null;if(c&&c.isActive())c._paused&&c.resume();else if(!c){let w,y=DT();if(y&&y.total>1){let C=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;w=`Plan step ${y.current}/${y.total}: ${C}`}else w=H>0?`${Wc()} (step ${H+1})`:Wc();let{getPendingJobSummary:G}=to(),B=G();B&&(w+=` [${B}]`),Te=new so(w),Te.start()}let tt=!0,nt="",En=!1,Ze=new qT,Nt,Ca=Date.now(),Cr=!1,Aa=new AbortController,Lu=setInterval(()=>{let w=Date.now()-Ca;if(w>=Vc)Ze._clearCursorLine(),I(`${p.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${p.reset}`),Aa.abort();else if(w>=my&&!Cr){Cr=!0,Ze._clearCursorLine();let y=pa.fast?.[oo()],G=ye>0?` (retry ${ye+1}/${Qi})`:"",B=Math.round((Vc-w)/1e3);I(`${p.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${G}${p.reset}`),y&&y!==Qt()?console.log(`${p.dim} \u{1F4A1} Will auto-switch to ${y} in ~${B}s if no tokens arrive${p.reset}`):console.log(`${p.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${B}s${p.reset}`)}},5e3),Mt="",pn=null;try{let w=Ey(ft()),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"]),B;wr()?B=w.filter(q=>by.has(q.function.name)):$e&&Ae==="plan"?B=w.filter(q=>y.has(q.function.name)):$e&&Ae==="verify"?B=w.filter(q=>G.has(q.function.name)):B=w;let C=na(),Q=new AbortController;C&&C.addEventListener("abort",()=>Q.abort(),{once:!0}),Aa.signal.addEventListener("abort",()=>Q.abort(),{once:!0}),Nt=await ry(T,B,{signal:Q.signal,...xn?{model:xn}:{},onThinkingToken:()=>{Ca=Date.now(),Cr=!1,hn?.onThinkingToken&&hn.onThinkingToken()},onToken:q=>{if(Ca=Date.now(),Cr=!1,hn?.onToken){hn.onToken(q),nt+=q;return}if(nt+=q,!En&&nt.length>400&&nt.length%250<q.length+1){let ce=ou(nt,3);ce.truncated&&(En=!0,Ze._clearCursorLine?.(),I(`${p.yellow} \u26A0 LLM stream loop detected (${ce.repeatCount}\xD7 repeated) \u2014 suppressing display${p.reset}`))}En||(Mt+=q,process.stdout.isTTY?pn||(pn=setTimeout(()=>{Mt&&Ze&&Ze.push(Mt),Mt="",pn=null},50)):(Ze.push(Mt),Mt=""),tt&&(c&&!c._paused?c.pause():Te&&Te.stop(),xe||(xe=!0),Ze.startCursor(),tt=!1))}})}catch(w){if(clearInterval(Lu),pn&&(clearTimeout(pn),pn=null),Mt&&Ze&&(Ze.push(Mt),Mt=""),c&&!c._paused&&c.pause(),Te&&Te.stop(),Ze.stopCursor(),Aa.signal.aborted&&!na()?.aborted){if(ye++,ye>Qi){if(ke<1){ke++,no("Stale retries exhausted \u2014 last-resort force-compress...",p.yellow);let ce=ft(),{messages:M,tokensRemoved:O}=un(T,ce);T=M,O>50&&I(`${p.dim} [force-compressed \u2014 ~${O} tokens freed]${p.reset}`),ye=0,Ge--;continue}c&&(c.stop(),c=null);let q=await HR();if(q.action==="quit"){u(null),Le(H,se,D,me,Ne),Ce(P);break}q.action==="switch"&&(Hc(`${q.provider}:${q.model}`),console.log(`${p.green} \u2713 Switched to ${q.provider}:${q.model}${p.reset}`)),ye=0,Ge--;continue}let C=ye===1?3e3:5e3;if(ye>=1&&Se<1){Se++,no(`Stale retry ${ye}/${Qi} \u2014 force-compressing before retry...`,p.yellow);let q=ft(),{messages:ce,tokensRemoved:M}=un(T,q,!0);if(T=ce,M>0&&M>50&&I(`${p.dim} [force-compressed \u2014 ~${M} tokens freed]${p.reset}`),yR){let O=pa.fast?.[oo()];O&&O!==Qt()&&(Hc(`${oo()}:${O}`),console.log(`${p.cyan} \u26A1 Auto-switched to ${O} to avoid further stale timeouts${p.reset}`),console.log(`${p.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${p.reset}`))}}else I(`${p.yellow} \u26A0 Stale retry ${ye}/${Qi} \u2014 retrying in ${C/1e3}s...${p.reset}`);let Q=new so(`Waiting ${C/1e3}s before retry...`);Q.start(),await new Promise(q=>setTimeout(q,C)),Q.stop(),Ge--;continue}if(w.name==="AbortError"||w.name==="CanceledError"||w.message?.includes("canceled")||w.message?.includes("aborted")){c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne),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 C=Qt?Qt():"unknown",Q=M=>M.includes(":")&&M.split(":")[0].match(/^[a-z]+$/)&&!M.split(":")[1].includes(":")?M.split(":").slice(1).join(":"):M;_.add(Q(C));let ce=(()=>{let M=[];process.env.NEX_FALLBACK_MODEL&&M.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:O}=sr(),j=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let K of j){let pe=O(K);pe&&!M.includes(pe)&&M.push(pe)}}catch{}return M.filter(O=>!_.has(Q(O)))})()[0];if(ce){console.log(`${p.yellow} \u26A0 Model ${C} unavailable (404) \u2014 switching to ${ce}${p.reset}`),Hc(ce),oy(ce),Ge--;continue}y=`Model not found (404): ${C} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${p.red} \u2717 ${y}${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne),Ce(P);break}else if(w.message.includes("400")){if(ke<3&&De<Oe){ke++,De++;let C=H===0&&ke===1,Q=C||ke===3||Se>0;if(C){ke=3;let O=w.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);no(`Bad request (400) \u2014 ${O||"system prompt too large"}, compressing...`,p.yellow)}else no(Q?`Bad request (400) \u2014 nuclear compression (attempt ${ke}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${ke}/3)`,p.yellow);let q=ft(),{messages:ce,tokensRemoved:M}=un(T,q,Q);T=ce,M>50&&I(`${p.dim} [force-compressed \u2014 ~${M} tokens freed]${p.reset}`),Ge--;continue}{let C=T.find(j=>j.role==="system"),Q=T.find(j=>j.role==="user"&&!String(j.content).startsWith("[SYSTEM")&&!String(j.content).startsWith("BLOCKED:")),q=[C,Q].filter(Boolean),{getUsage:ce}=ln(),M=ln().estimateMessagesTokens(q),O=ln().estimateMessagesTokens(T);if(M<O){let j=[],K=P.filter(ne=>ne.role==="assistant"&&typeof ne.content=="string"&&ne.content.trim().length>30).slice(-5).map(ne=>ne.content.trim().slice(0,300).replace(/\n+/g," "));K.length>0&&j.push(`Key findings:
1383
- `+K.map(ne=>`- ${ne}`).join(`
1384
- `));let pe=P.filter(ne=>ne.role==="tool"&&typeof ne.content=="string"&&!ne.content.startsWith("BLOCKED:")&&ne.content.trim().length>10).slice(-5).map(ne=>ne.content.trim().split(`
1386
+ The user linked a live app URL (${r.url}) and described broken behavior. Treat this as a runtime issue first. Reproduce it with browser_open or browser_screenshot before reading local files. Only inspect the local repo after you have confirmed the live behavior.`;T=[T[0],{role:"user",content:_e},{role:"assistant",content:"Understood \u2014 I will inspect the live app/runtime first."},...T.slice(1)]}if(E){let _e=fR(typeof t=="string"?t:"");_e&&(T=[T[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1387
+ `+_e.user},{role:"assistant",content:_e.assistant+`
1388
+ [END EXAMPLE \u2014 wait for the real user request below]`},...T.slice(1)])}if(Qt(T,ht()).percentage>=65){let{messages:ge,tokensRemoved:Re}=hn(T,ht());Re>0&&(T=ge,console.log(`${p.dim} [pre-flight compress \u2014 ${Re} tokens freed, now ${Math.round(Qt(T,ht()).percentage)}% used]${p.reset}`))}let q=0,Q=0,we=0,ke=0,qe=0,Ne=9,ve=0,_=new Set,M=(()=>{let _e=O.find(ge=>ge.role==="user");return typeof _e?.content=="string"?_e.content:""})(),F=typeof M=="string"?Cy(M):null,ee=c1(M),K=/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(M)||!!F?.shouldPreferSsh,C=!!F,he=0;if(!ct){let _e=O.filter(Re=>Re.role==="user"||Re.role==="tool").map(Re=>typeof Re.content=="string"?Re.content:"").join(`
1389
+ `),ge=ru(_e);ge&&(ct=!0,kt=ge.slice(0,120),L(`${p.yellow} \u26A1 Root cause in briefing: ${kt} \u2014 fix phase active from start (read budget: 3)${p.reset}`))}if(!ct&&!Bt&&/\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(M)&&(Bt=!0,L(`${p.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${p.reset}`)),O.length<=1&&!n.skipPhaseRouting&&(ye=aR(),ye)){vs=iR(M)?.id||"coding";let ge=Uy(M);if(Te=ge?"implement":"plan",nn=uu(Te,vs),$a=0,po=0,Dn=0,br=null,$s.clear(),process.stdout.isTTY&&console.log(ge?`${p.dim} \u21B3 Phase routing: implement(${nn||"default"}) \u2192 verify ${p.yellow}[plan skipped: direct file task]${p.reset}`:`${p.dim} \u21B3 Phase routing: plan(${nn||"default"}) \u2192 implement \u2192 verify${p.reset}`),L(ge?`${p.cyan} \u26A1 Phase routing enabled \u2014 skipping plan phase for direct file task, starting in implement with ${nn||"default model"} (category: ${vs})${p.reset}`:`${p.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${nn||"default model"} (category: ${vs})${p.reset}`),ge&&ee.length>0){let Ke={role:"user",content:`[SYSTEM] This is a direct file task targeting: ${ee.slice(0,3).join(", ")}. Modify only the explicitly requested file(s) unless the user asks for more. Do NOT create extra helper or test files for verification. Prefer inline verification with bash or by reading the edited file.`};O.push(Ke),T.push(Ke)}}let H=0,se=new Map,J=new Set,Se=new Set,Ts=new Set,Rs=0,Iu=0,Ea=0,Cs=0,Pe=Date.now(),N0=new KT(LR),P0=Sr,Qe=n.skillLoop?10:1,M0=3*Qe,L0=5*Qe,ju=Eu,I0=5*Qe,j0=8*Qe,D0=Qy,q0=(ye?6:4)*Qe,F0=(ye?10:7)*Qe,Ta=aa,B0=(ye?5:3)*Qe,Cr=(ye?8:5)*Qe,U0=e0,W0=(ye?4:3)*Qe,H0=(ye?6:4)*Qe,Y0=3*Qe,G0=4*Qe,As=gn,z0=(ye?6:4)*Qe,K0=(ye?10:8)*Qe,Os=(ye?12:10)*Qe,X0=25,qn=0,V0=10*Qe,J0=15*Qe,Fn=0,Du=5*Qe,Bn=0,Z0=2*Qe,Q0=3,Ra=0,bo=10,ew=16,qu=n.skillLoop?999:o.investigationCap,Fu=async()=>{let{hasPendingOrCompletedJobs:_e,getPendingJobSummary:ge}=io();if(_e()){if(ge()){let Re=Date.now()+45e3;for(process.stderr.write(`${p.cyan} \u23F3 Waiting for background agents to finish\u2026${p.reset}
1390
+ `);ge()&&Date.now()<Re;)await new Promise(Ke=>setTimeout(Ke,500).unref()),oa(O,T)}oa(O,T),O.length>0&&Oe(O)}},Tn=typeof t=="string"?t.trim():"",Bu=Tn.length>0&&/^\s*(analyze|analyse|analysiere|explain|erkläre|describe|beschreib|review|audit|summari[sz]e|zusammenfass|list|liste|understand|document|documentation|docs|what is|what does|wie funktioniert|wie geht|how does|show me|zeig|show the|show all|tell me about|erzähl)/i.test(Tn)&&!/\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(Tn),Ar=Tn.length>0&&/\b(analyze|analyse|explain|describe|review|audit|summari[sz]e|understand|document|scan|count|inventory|map|list|identify)\b/i.test(Tn)&&/\b(create|write|generate|produce|output)\b/i.test(Tn)&&/\b([A-Z0-9_-]+\.md|markdown|report|summary|overview|architecture|audit|table|documentation|docs|inventory|catalog)\b/i.test(Tn)&&!/\b(fix|bug|crash|error|implement|add(?!\s+(?:to|into)\b)|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|delete|remove|install|setup|deploy|run)\b/i.test(Tn),ze,vt=n.maxIterations||(ye?ys(Te):fu);Bu&&(vt=Math.min(vt,4),L(`${p.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${vt}${p.reset}`));let Ca=0,Uu=3,Aa=!1,Or=0,Oa=!1;e:for(;;){for(Aa=!1,ze=0;ze<vt&&!ra()?.aborted;ze++){oa(O,T);{let w=ht(),y=Qt(T,w),Y=H===0?65:78;if(y.percentage>=Y){if(J.size>0||ye&&Te!=="plan"){let z=eR(O,{filesModified:J,currentPhase:ye?Te:null});if(z){let j=T.findIndex(A=>A._progressSnapshot);j!==-1&&T.splice(j,1);let ae=T.findIndex(A=>A.role==="system");T.splice(ae+1,0,z)}}let{messages:B,tokensRemoved:G}=hn(T,w,H===0);if(G>0&&(T=B,G>50&&console.log(`${p.dim} [auto-compressed \u2014 ~${G} tokens freed, now ${Math.round(Qt(T,w).percentage)}%]${p.reset}`),Bt&&J.size>=3)){let z=[...J].map(ae=>ae.split("/").pop()).slice(0,10).join(", "),j={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${J.size} files: ${z}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};T.push(j)}}}if(Nt&&!ct&&wr<2){wr++;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."};T.push(w),O.push(w),L(`${p.yellow} \u26A0 Pre-call SSH-blocked nudge #${wr} injected \u2014 model told to synthesize${p.reset}`)}Nt||(wr=0);let ge=!0;H>0&&_R();let Re=null;if(c&&c.isActive())c._paused&&c.resume();else if(!c){let w,y=xR();if(y&&y.total>1){let G=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;w=`Plan step ${y.current}/${y.total}: ${G}`}else w=H>0?`${Vc()} (step ${H+1})`:Vc();let{getPendingJobSummary:Y}=io(),B=Y();B&&(w+=` [${B}]`),Re=new lo(w),Re.start()}let Ke=!0,rt="",Rn=!1,st=new kR,Pt,Na=Date.now(),Nr=!1,Pa=new AbortController,Wu=setInterval(()=>{let w=Date.now()-Na;if(w>=su)st._clearCursorLine(),L(`${p.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${p.reset}`),Pa.abort();else if(w>=Dy&&!Nr){Nr=!0,st._clearCursorLine();let y=ya.fast?.[co()],Y=we>0?` (retry ${we+1}/${na})`:"",B=Math.round((su-w)/1e3);L(`${p.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${Y}${p.reset}`),y&&y!==tn()?console.log(`${p.dim} \u{1F4A1} Will auto-switch to ${y} in ~${B}s if no tokens arrive${p.reset}`):console.log(`${p.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${B}s${p.reset}`)}},5e3),Mt="",wn=null;try{let w=Vy(ht()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),Y=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),B;_r()?B=w.filter(j=>Hy.has(j.function.name)):ye&&Te==="plan"?B=w.filter(j=>y.has(j.function.name)):ye&&Te==="verify"?B=w.filter(j=>Y.has(j.function.name)):B=w;let G=ra(),z=new AbortController;G&&G.addEventListener("abort",()=>z.abort(),{once:!0}),Pa.signal.addEventListener("abort",()=>z.abort(),{once:!0}),Pt=await Ry(T,B,{signal:z.signal,...nn?{model:nn}:{},onThinkingToken:()=>{Na=Date.now(),Nr=!1,yn?.onThinkingToken&&yn.onThinkingToken()},onToken:j=>{if(Na=Date.now(),Nr=!1,yn?.onToken){yn.onToken(j),rt+=j;return}if(rt+=j,!Rn&&rt.length>400&&rt.length%250<j.length+1){let ae=du(rt,3);ae.truncated&&(Rn=!0,st._clearCursorLine?.(),L(`${p.yellow} \u26A0 LLM stream loop detected (${ae.repeatCount}\xD7 repeated) \u2014 suppressing display${p.reset}`))}Rn||(Mt+=j,process.stdout.isTTY?wn||(wn=setTimeout(()=>{Mt&&st&&st.push(Mt),Mt="",wn=null},50)):(st.push(Mt),Mt=""),Ke&&(c&&!c._paused?c.pause():Re&&Re.stop(),ge||(ge=!0),st.startCursor(),Ke=!1))}})}catch(w){if(clearInterval(Wu),wn&&(clearTimeout(wn),wn=null),Mt&&st&&(st.push(Mt),Mt=""),c&&!c._paused&&c.pause(),Re&&Re.stop(),st.stopCursor(),Pa.signal.aborted&&!ra()?.aborted){if(we++,we>na){if(ke<1){ke++,ao("Stale retries exhausted \u2014 last-resort force-compress...",p.yellow);let ae=ht(),{messages:A,tokensRemoved:U}=hn(T,ae);T=A,U>50&&L(`${p.dim} [force-compressed \u2014 ~${U} tokens freed]${p.reset}`),we=0,ze--;continue}c&&(c.stop(),c=null);let j=await A1();if(j.action==="quit"){u(null),Ie(H,se,J,Se,Pe),Oe(O);break}j.action==="switch"&&(Jc(`${j.provider}:${j.model}`),console.log(`${p.green} \u2713 Switched to ${j.provider}:${j.model}${p.reset}`)),we=0,ze--;continue}let G=we===1?3e3:5e3;if(we>=1&&ve<1){ve++,ao(`Stale retry ${we}/${na} \u2014 force-compressing before retry...`,p.yellow);let j=ht(),{messages:ae,tokensRemoved:A}=hn(T,j,!0);if(T=ae,A>0&&A>50&&L(`${p.dim} [force-compressed \u2014 ~${A} tokens freed]${p.reset}`),t1){let U=ya.fast?.[co()];U&&U!==tn()&&(Jc(`${co()}:${U}`),console.log(`${p.cyan} \u26A1 Auto-switched to ${U} to avoid further stale timeouts${p.reset}`),console.log(`${p.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${p.reset}`))}}else L(`${p.yellow} \u26A0 Stale retry ${we}/${na} \u2014 retrying in ${G/1e3}s...${p.reset}`);let z=new lo(`Waiting ${G/1e3}s before retry...`);z.start(),await new Promise(j=>setTimeout(j,G)),z.stop(),ze--;continue}if(w.name==="AbortError"||w.name==="CanceledError"||w.message?.includes("canceled")||w.message?.includes("aborted")){c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe),Oe(O);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 G=tn?tn():"unknown",z=A=>A.includes(":")&&A.split(":")[0].match(/^[a-z]+$/)&&!A.split(":")[1].includes(":")?A.split(":").slice(1).join(":"):A;_.add(z(G));let ae=(()=>{let A=[];process.env.NEX_FALLBACK_MODEL&&A.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:U}=rr(),R=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let W of R){let ue=U(W);ue&&!A.includes(ue)&&A.push(ue)}}catch{}return A.filter(U=>!_.has(z(U)))})()[0];if(ae){console.log(`${p.yellow} \u26A0 Model ${G} unavailable (404) \u2014 switching to ${ae}${p.reset}`),Jc(ae),Ty(ae),ze--;continue}y=`Model not found (404): ${G} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${p.red} \u2717 ${y}${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe),Oe(O);break}else if(w.message.includes("400")){if(ke<3&&qe<Ne){ke++,qe++;let G=H===0&&ke===1,z=G||ke===3||ve>0;if(G){ke=3;let U=w.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);ao(`Bad request (400) \u2014 ${U||"system prompt too large"}, compressing...`,p.yellow)}else ao(z?`Bad request (400) \u2014 nuclear compression (attempt ${ke}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${ke}/3)`,p.yellow);let j=ht(),{messages:ae,tokensRemoved:A}=hn(T,j,z);T=ae,A>50&&L(`${p.dim} [force-compressed \u2014 ~${A} tokens freed]${p.reset}`),ze--;continue}{let G=T.find(R=>R.role==="system"),z=T.find(R=>R.role==="user"&&!String(R.content).startsWith("[SYSTEM")&&!String(R.content).startsWith("BLOCKED:")),j=[G,z].filter(Boolean),{getUsage:ae}=dn(),A=dn().estimateMessagesTokens(j),U=dn().estimateMessagesTokens(T);if(A<U){let R=[],W=O.filter(I=>I.role==="assistant"&&typeof I.content=="string"&&I.content.trim().length>30).slice(-5).map(I=>I.content.trim().slice(0,300).replace(/\n+/g," "));W.length>0&&R.push(`Key findings:
1391
+ `+W.map(I=>`- ${I}`).join(`
1392
+ `));let ue=O.filter(I=>I.role==="tool"&&typeof I.content=="string"&&!I.content.startsWith("BLOCKED:")&&I.content.trim().length>10).slice(-5).map(I=>I.content.trim().split(`
1385
1393
  `).slice(0,8).join(`
1386
- `).slice(0,500));if(pe.length>0&&j.push(`Tool results summary:
1387
- `+pe.map(ne=>`- ${ne}`).join(`
1388
- `)),D.size>0){let ne=[...D].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");j.unshift(`Already modified: ${ne} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(me.size>0){let ne=[...me].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");j.push(`Files already investigated: ${ne}`)}let X=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(X,JSON.stringify({filesWritten:[...D].map(ne=>ne.split("/").slice(-2).join("/")),filesRead:[...me].map(ne=>ne.split("/").slice(-2).join("/")),isCreationTask:Ft,wipeNumber:mr+1,timestamp:Date.now()},null,2)),j.push(`Session checkpoint: ${X} \u2014 read it for exact file list`)}catch{}let fe=0;{let _e=((typeof Q?.content=="string"?Q.content:Array.isArray(Q?.content)?Q.content.filter(st=>st.type==="text").map(st=>st.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(st=>st.trim()).filter(Boolean),ve=[...D],ct=_e.filter(st=>!ve.some(Pa=>Pa.endsWith(st)||st.endsWith(Pa.split("/").pop())));fe=ct.length;let Qe=[...P].reverse().find(st=>st.role==="tool"&&typeof st.content=="string"&&!st.content.startsWith("BLOCKED:")&&st.content.length>5),Pt={completed:ve.map(st=>st.split("/").slice(-2).join("/")),pending:ct.length>0?ct:ve.length===0?["(task files not yet identified)"]:[],lastEdit:Qe?Qe.content.trim().slice(0,120):null};(Pt.completed.length>0||Pt.pending.length>0)&&j.unshift(`Work manifest:
1389
- ${JSON.stringify(Pt,null,2)}`)}if(j.length>0){let ne={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1390
- ${j.join(`
1394
+ `).slice(0,500));if(ue.length>0&&R.push(`Tool results summary:
1395
+ `+ue.map(I=>`- ${I}`).join(`
1396
+ `)),J.size>0){let I=[...J].map(be=>be.split("/").slice(-2).join("/")).join(", ");R.unshift(`Already modified: ${I} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(Se.size>0){let I=[...Se].map(be=>be.split("/").slice(-2).join("/")).join(", ");R.push(`Files already investigated: ${I}`)}let $e=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync($e,JSON.stringify({filesWritten:[...J].map(I=>I.split("/").slice(-2).join("/")),filesRead:[...Se].map(I=>I.split("/").slice(-2).join("/")),isCreationTask:Bt,wipeNumber:yr+1,timestamp:Date.now()},null,2)),R.push(`Session checkpoint: ${$e} \u2014 read it for exact file list`)}catch{}let te=0;{let be=((typeof z?.content=="string"?z.content:Array.isArray(z?.content)?z.content.filter(tt=>tt.type==="text").map(tt=>tt.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(tt=>tt.trim()).filter(Boolean),Ee=[...J],Ue=be.filter(tt=>!Ee.some(Lr=>Lr.endsWith(tt)||tt.endsWith(Lr.split("/").pop())));te=Ue.length;let Xe=[...O].reverse().find(tt=>tt.role==="tool"&&typeof tt.content=="string"&&!tt.content.startsWith("BLOCKED:")&&tt.content.length>5),Lt={completed:Ee.map(tt=>tt.split("/").slice(-2).join("/")),pending:Ue.length>0?Ue:Ee.length===0?["(task files not yet identified)"]:[],lastEdit:Xe?Xe.content.trim().slice(0,120):null};(Lt.completed.length>0||Lt.pending.length>0)&&R.unshift(`Work manifest:
1397
+ ${JSON.stringify(Lt,null,2)}`)}if(R.length>0){let I={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1398
+ ${R.join(`
1391
1399
  `)}
1392
- Continue implementing the fixes based on these findings.`};q.push(ne)}if(mr>=3){let ne=D.size>0?`
1393
- Files modified so far: ${[...D].map(_e=>_e.split("/").slice(-1)[0]).join(", ")}`:"";I(`${p.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${p.reset}`),console.log(`${p.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ne?p.dim+ne:""}${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne,{suppressHint:!0}),Ce(P);break}T=q,mr++,ws=10+Math.min(fe*3,7),fu=!0,ca=D.size,ua=!1,qt=0,R=0;for(let[ne,_e]of kn){let ve=_e?.count??_e??0;Qc(kn,ne,ve>=2?ve:1)}for(let[ne]of In)dn(kn,ne)<2&&In.delete(ne);Dt.clear(),ks.clear(),Ft&&Wt>0&&(Ut=!0,I(`${p.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Wt} edits already made)${p.reset}`));for(let[ne]of oa)Qc(oa,ne,Er-1);if(no(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${O-M} tokens freed)`,p.yellow),mr>=1){let ne=[...kn.entries()].filter(([,Qe])=>Qe>=Es).map(([Qe])=>Qe.split("/").slice(-1)[0]),_e=ne.length>0?`
1400
+ Continue implementing the fixes based on these findings.`};j.push(I)}if(yr>=3){let I=J.size>0?`
1401
+ Files modified so far: ${[...J].map(be=>be.split("/").slice(-1)[0]).join(", ")}`:"";L(`${p.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${p.reset}`),console.log(`${p.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${I?p.dim+I:""}${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe,{suppressHint:!0}),Oe(O);break}T=j,yr++,bs=10+Math.min(te*3,7),$u=!0,fa=J.size,ha=!1,Ft=0,he=0;for(let[I,be]of gn){let Ee=be?.count??be??0;iu(gn,I,Ee>=2?Ee:1)}for(let[I]of En)pn(gn,I)<2&&En.delete(I);qt.clear(),Ss.clear(),Bt&&Ht>0&&(Wt=!0,L(`${p.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Ht} edits already made)${p.reset}`));for(let[I]of aa)iu(aa,I,Cr-1);if(ao(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${U-A} tokens freed)`,p.yellow),yr>=1){let I=[...gn.entries()].filter(([,Xe])=>Xe>=Os).map(([Xe])=>Xe.split("/").slice(-1)[0]),be=I.length>0?`
1394
1402
 
1395
- Files already at read cap \u2014 use grep_search instead: ${ne.join(", ")}`:"",ct={role:"user",content:Ot&&!at?"[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(ct),T.push(ct)}ke=0,Ge--;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(`${p.red} \u2717 ${y}${p.reset}`),w.message.includes("429")){if(U++,U>Kc){console.log(`${p.red} Rate limit: max retries (${Kc}) exceeded. Try again later or use /budget to check your limits.${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne),Ce(P);break e}let C=Math.min(1e4*Math.pow(2,U-1),12e4),Q=new so(`Rate limit \u2014 waiting ${Math.round(C/1e3)}s (retry ${U}/${Kc})`);Q.start(),await new Promise(q=>setTimeout(q,C)),Q.stop();continue}let G=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return ut().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(Z++,Z>Xc){console.log(`${p.red} Network error: max retries (${Xc}) exceeded. Check your connection and try again.
1396
- Use /undo to revert changes made during this session.${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne),Ce(P);break e}let C=Math.min(2e3*Math.pow(2,Z-1),3e4),Q=new so(`API temporarily unavailable \u2014 retrying in ${Math.round(C/1e3)}s (${Z}/${Xc}). Your changes are safe.`);Q.start(),await new Promise(q=>setTimeout(q,C)),Q.stop(),Ge--;continue}c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne),Ce(P);break}if(clearInterval(Lu),U=0,Z=0,tt&&(c&&!c._paused&&c.pause(),Te&&Te.stop()),pn&&(clearTimeout(pn),pn=null),Mt&&Ze&&(Ze.push(Mt),Mt=""),nt&&Ze.flush(),Z=0,ye=0,Nt&&Nt.usage){let w=Nt.usage.prompt_tokens||0,y=Nt.usage.completion_tokens||0;ly(oo(),Qt(),w,y),d+=w+y,c&&c.setStats({tokens:d})}else if(Nt&&!Nt.usage){let w=T.map(B=>typeof B.content=="string"?B.content:Array.isArray(B.content)?B.content.map(C=>typeof C=="string"?C:C.text||"").join(""):"").join(" "),y=uy(w),G=uy(Nt.content||nt||"");ly(oo(),Qt(),y,G),d+=y+G,c&&c.setStats({tokens:d})}let{content:Iu,tool_calls:Ts}=Nt,en=Ts,Oa=!1;if(Array.isArray(Ts)&&Ts.length>0){let w=Ts.filter(y=>y?.function?.name==="ask_user");w.length>0&&(en=[w[0]],Oa=Ts.length!==1,Oa&&I(`${p.yellow} \u26A0 ask_user must run alone \u2014 deferring ${Ts.length-1} other tool call(s) until the user replies${p.reset}`))}let Ar=ou(Iu||""),ju=Ar.truncated?Ar.text:Iu;Ar.truncated&&I(`${p.yellow} \u26A0 LLM output loop detected (${Ar.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${p.reset}`);let Or=sR(ju||""),vt=Or.truncated?Or.text:ju;Or.truncated&&I(`${p.yellow} \u26A0 LLM output loop detected (${Or.repeatCount}\xD7 repeated window) \u2014 response truncated${p.reset}`);let wo={role:"assistant",content:vt||""};if(en&&en.length>0&&(wo.tool_calls=en),P.push(wo),T.push(wo),Mu&&!Zi(vt||nt||"")&&D.size===0&&Ss===0){I(`${p.green} \u2713 Analysis-only early exit: ${(vt||"").length} chars produced, no file changes${p.reset}`),wo.tool_calls&&delete wo.tool_calls,Le(H,se,D,me,Ne),Ce(P);break e}if(!at&&vt&&en&&en.length>0){let w=Zc(vt);if(w){at=!0,kt=w.slice(0,120),Bt=0,Ut=!1,Zt=0,I(`${p.yellow} \u26A1 Root cause in model analysis: ${kt} \u2014 fix phase (read budget: 3)${p.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${kt}. Read only the file that needs fixing, then edit it. Do not read other files.`};P.push(y),T.push(y)}}if(!en||en.length===0){let w=(vt||"").trim().length>0||nt.trim().length>0,y=!1;if(Ot&&w&&(ea>=2?I(`${p.yellow} \u26A0 SSH permanently blocked after ${ea} storm warnings \u2014 no further SSH calls allowed${p.reset}`):(Ot=!1,qt=yo-4,y=!0)),y&&w){let C=(vt||"").trim();if(C.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(C.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."};T.push(q),P.push(q);continue}}if(!w&&H>0&&Ge<ru-1){let C={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."};T.push(C),P.push(C);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&&Ge<3&&G.test((vt||"").slice(0,600)))if(fu&&ws<=0||Ot){I(`${p.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${p.reset}`);let Q={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."};T.push(Q),P.push(Q);continue}else{I(`${p.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${p.reset}`);let Q={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."};T.push(Q),P.push(Q);continue}if(s.skillLoop&&w&&H>3&&Rr<5){let C=(vt||nt||"").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(C.slice(-600))){Rr=(Rr||0)+1,I(`${p.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Rr}${p.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."};T.push(q),P.push(q);continue}}if(_s()&&!s.skillLoop&&(D.size>0||Ss>0)&&w&&!Zi(vt||nt||"")&&H>=1&&(!$e||Ae==="implement")){I(`${p.green} \u2713 Headless early exit: ${D.size} file(s) modified (+ ${Ss} bash writes), substantive text response received${p.reset}`),Le(H,se,D,me,Ne),Ce(P);break e}if($e&&Ae==="plan"&&jn>=2){I(`${p.cyan} \u21B3 Plan phase: ${jn} consecutive blocks \u2014 auto-advancing to implement${p.reset}`),jn=0;let C=await fr("implement","[auto-advance: task only requires direct action]");if(C){P.push(C),T.push(C),Ge=0,St=gs("implement");continue}}if($e&&w){let C=(vt||nt||"").trim();if(Ae==="plan"){let Q=/\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=Oy(C,kn).length===0,ce=$r.size>0,M=br.size>0,O=C.length>1500;if(_s()&&q&&!ce&&!M&&!O&&Q.test(C)){I(`${p.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${p.reset}`),process.stdout.isTTY&&process.stderr.write(`${p.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${p.reset}
1397
- `),Le(H,se,D,me,Ne),Ce(P);break e}let j=await fr("implement",C);if(j){P.push(j),T.push(j),Ge=0,St=gs("implement");continue}}else if(Ae==="implement"&&(D.size>0||Ss>0)){let Q=P.find(M=>M.role==="user"),q=typeof Q?.content=="string"?Q.content:"",ce=await fr("verify",C,D,q);if(ce){P.push(ce),T.push(ce),Ge=0,St=Math.min(gs("verify")+Math.max(0,(D.size-2)*2),20);continue}}else if(Ae==="verify"){let Q=/\bPASS\b/i.test(C.slice(0,500)),ce=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(C.slice(0,500)),M=co>0||T.some(O=>O.role==="assistant"&&typeof O.content=="string"&&/\bPASS\b/i.test(O.content.slice(0,500)));if(_s()&&!s.skillLoop&&M&&!ce&&!Zi(C)){I(`${p.green} \u2713 Verification phase complete (headless substantive summary)${p.reset}`),Le(H,se,D,me,Ne),Ce(P),cr(P);break e}if(ce&&lo<3){lo++;let O={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1398
- ${C.slice(0,400)}
1403
+ Files already at read cap \u2014 use grep_search instead: ${I.join(", ")}`:"",Ue={role:"user",content:Nt&&!ct?"[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.${be}`};O.push(Ue),T.push(Ue)}ke=0,ze--;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(`${p.red} \u2717 ${y}${p.reset}`),w.message.includes("429")){if(q++,q>tu){console.log(`${p.red} Rate limit: max retries (${tu}) exceeded. Try again later or use /budget to check your limits.${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe),Oe(O);break e}let G=Math.min(1e4*Math.pow(2,q-1),12e4),z=new lo(`Rate limit \u2014 waiting ${Math.round(G/1e3)}s (retry ${q}/${tu})`);z.start(),await new Promise(j=>setTimeout(j,G)),z.stop();continue}let Y=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return dt().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")||Y&&(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(Q++,Q>nu){console.log(`${p.red} Network error: max retries (${nu}) exceeded. Check your connection and try again.
1404
+ Use /undo to revert changes made during this session.${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe),Oe(O);break e}let G=Math.min(2e3*Math.pow(2,Q-1),3e4),z=new lo(`API temporarily unavailable \u2014 retrying in ${Math.round(G/1e3)}s (${Q}/${nu}). Your changes are safe.`);z.start(),await new Promise(j=>setTimeout(j,G)),z.stop(),ze--;continue}c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe),Oe(O);break}if(clearInterval(Wu),q=0,Q=0,Ke&&(c&&!c._paused&&c.pause(),Re&&Re.stop()),wn&&(clearTimeout(wn),wn=null),Mt&&st&&(st.push(Mt),Mt=""),rt&&st.flush(),Q=0,we=0,Pt&&Pt.usage){let w=Pt.usage.prompt_tokens||0,y=Pt.usage.completion_tokens||0;Oy(co(),tn(),w,y),d+=w+y,c&&c.setStats({tokens:d})}else if(Pt&&!Pt.usage){let w=T.map(B=>typeof B.content=="string"?B.content:Array.isArray(B.content)?B.content.map(G=>typeof G=="string"?G:G.text||"").join(""):"").join(" "),y=Py(w),Y=Py(Pt.content||rt||"");Oy(co(),tn(),y,Y),d+=y+Y,c&&c.setStats({tokens:d})}let{content:Hu,tool_calls:Ns}=Pt,sn=Ns,Ma=!1;if(Array.isArray(Ns)&&Ns.length>0){let w=Ns.filter(y=>y?.function?.name==="ask_user");w.length>0&&(sn=[w[0]],Ma=Ns.length!==1,Ma&&L(`${p.yellow} \u26A0 ask_user must run alone \u2014 deferring ${Ns.length-1} other tool call(s) until the user replies${p.reset}`))}let Pr=du(Hu||""),Yu=Pr.truncated?Pr.text:Hu;Pr.truncated&&L(`${p.yellow} \u26A0 LLM output loop detected (${Pr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${p.reset}`);let Mr=BR(Yu||""),Et=Mr.truncated?Mr.text:Yu;Mr.truncated&&L(`${p.yellow} \u26A0 LLM output loop detected (${Mr.repeatCount}\xD7 repeated window) \u2014 response truncated${p.reset}`);let _o={role:"assistant",content:Et||""};if(sn&&sn.length>0&&(_o.tool_calls=sn),O.push(_o),T.push(_o),Bu&&!ta(Et||rt||"")&&J.size===0&&Cs===0){L(`${p.green} \u2713 Analysis-only early exit: ${(Et||"").length} chars produced, no file changes${p.reset}`),_o.tool_calls&&delete _o.tool_calls,Ie(H,se,J,Se,Pe),Oe(O);break e}if(!ct&&Et&&sn&&sn.length>0){let w=ru(Et);if(w){ct=!0,kt=w.slice(0,120),Ut=0,Wt=!1,en=0,L(`${p.yellow} \u26A1 Root cause in model analysis: ${kt} \u2014 fix phase (read budget: 3)${p.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${kt}. Read only the file that needs fixing, then edit it. Do not read other files.`};O.push(y),T.push(y)}}if(!sn||sn.length===0){let w=(Et||"").trim().length>0||rt.trim().length>0,y=!1;if(Nt&&w&&(sa>=2?L(`${p.yellow} \u26A0 SSH permanently blocked after ${sa} storm warnings \u2014 no further SSH calls allowed${p.reset}`):(Nt=!1,Ft=bo-4,y=!0)),y&&w){let z=(Et||"").trim();if(z.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(z.slice(-200))){let ae={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};T.push(ae),O.push(ae);continue}}if(!w&&H>0&&ze<fu-1){let z={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."};T.push(z),O.push(z);continue}let Y=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(w&&ze<3&&Y.test((Et||"").slice(0,600)))if($u&&bs<=0||Nt){L(`${p.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${p.reset}`);let j={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."};T.push(j),O.push(j);continue}else{L(`${p.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${p.reset}`);let j={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."};T.push(j),O.push(j);continue}if(n.skillLoop&&w&&H>3&&Or<5){let z=(Et||rt||"").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(z.slice(-600))){Or=(Or||0)+1,L(`${p.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Or}${p.reset}`);let ae={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."};T.push(ae),O.push(ae);continue}}if(ks()&&!n.skillLoop&&(J.size>0||Cs>0)&&w&&!ta(Et||rt||"")&&H>=1&&(!ye||Te==="implement")){L(`${p.green} \u2713 Headless early exit: ${J.size} file(s) modified (+ ${Cs} bash writes), substantive text response received${p.reset}`),Ie(H,se,J,Se,Pe),Oe(O);break e}let G=l1(br)?1:2;if(ye&&Te==="plan"&&Dn>=G){L(`${p.cyan} \u21B3 Plan phase: ${Dn} consecutive blocks (last: ${br||"unknown"}) \u2014 auto-advancing to implement${p.reset}`),Dn=0,br=null;let z=await pr("implement","[auto-advance: task only requires direct action]");if(z){O.push(z),T.push(z),ze=0,vt=ys("implement");continue}}if(ye&&w){let z=(Et||rt||"").trim();if(Te==="plan"){let j=/\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,ae=t0(z,gn).length===0,A=xr.size>0,U=kr.size>0,R=z.length>1500;if(ks()&&ae&&!A&&!U&&!R&&j.test(z)){L(`${p.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${p.reset}`),process.stdout.isTTY&&process.stderr.write(`${p.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${p.reset}
1405
+ `),Ie(H,se,J,Se,Pe),Oe(O);break e}let W=await pr("implement",z);if(W){O.push(W),T.push(W),ze=0,vt=ys("implement");continue}}else if(Te==="implement"&&(J.size>0||Cs>0)){let j=O.find(U=>U.role==="user"),ae=typeof j?.content=="string"?j.content:"",A=await pr("verify",z,J,ae);if(A){O.push(A),T.push(A),ze=0,vt=Math.min(ys("verify")+Math.max(0,(J.size-2)*2),20);continue}}else if(Te==="verify"){let j=/\bPASS\b/i.test(z.slice(0,500)),A=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(z.slice(0,500)),U=mo>0||T.some(R=>R.role==="assistant"&&typeof R.content=="string"&&/\bPASS\b/i.test(R.content.slice(0,500)));if(ks()&&!n.skillLoop&&U&&!A&&!ta(z)){L(`${p.green} \u2713 Verification phase complete (headless substantive summary)${p.reset}`),Ie(H,se,J,Se,Pe),Oe(O),dr(O);break e}if(A&&po<3){po++;let R={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1406
+ ${z.slice(0,400)}
1399
1407
 
1400
- Fix the identified issues. This is attempt ${lo}/3.`};Ae="implement",xn=su("implement",po),P.push(O),T.push(O),Ge=0,St=gs("implement"),I(`${p.yellow} \u21B3 Verify \u2192 implement loop-back #${lo} (issues found)${p.reset}`);continue}if(!ce&&(!Q||co===0)){if(uo<2){uo++;let O=[];co===0&&O.push("run at least one verification tool"),Q||O.push("end your report with PASS or FAIL");let j={role:"user",content:`[SYSTEM] Verification is incomplete: ${O.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(j),T.push(j),I(`${p.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${uo}/2)${p.reset}`);continue}I(`${p.yellow} \u26A0 Verify phase completion accepted without full markers after ${uo} nudges${p.reset}`)}if(I(`${p.green} \u2713 Verification phase complete${ce?" (loop-back exhausted)":" (PASS)"}${p.reset}`),!ce){Le(H,se,D,me,Ne),Ce(P),cr(P);break e}}}if(wr()&&w&&H===0)if(ia++,ia>2)I(`${p.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${p.reset}`);else{let C={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.).
1408
+ Fix the identified issues. This is attempt ${po}/3.`};Te="implement",nn=uu("implement",vs),O.push(R),T.push(R),ze=0,vt=ys("implement"),L(`${p.yellow} \u21B3 Verify \u2192 implement loop-back #${po} (issues found)${p.reset}`);continue}if(!A&&(!j||mo===0)){if(go<2){go++;let R=[];mo===0&&R.push("run at least one verification tool"),j||R.push("end your report with PASS or FAIL");let W={role:"user",content:`[SYSTEM] Verification is incomplete: ${R.join(" and ")}. Do not stop yet. Re-read the modified files and/or run tests or linters, then respond with PASS or FAIL.`};O.push(W),T.push(W),L(`${p.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${go}/2)${p.reset}`);continue}L(`${p.yellow} \u26A0 Verify phase completion accepted without full markers after ${go} nudges${p.reset}`)}if(L(`${p.green} \u2713 Verification phase complete${A?" (loop-back exhausted)":" (PASS)"}${p.reset}`),!A){Ie(H,se,J,Se,Pe),Oe(O),dr(O);break e}}}if(_r()&&w&&H===0)if(ca++,ca>2)L(`${p.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${p.reset}`);else{let z={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.).
1401
1409
 
1402
- 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(C),T.push(C),I(`${p.yellow} \u26A0 Plan rejected (${ia}/2): no files read \u2014 forcing investigation${p.reset}`);continue}if(wr()&&w){let C=(vt||nt||"").trim();PT(C),wR(C);let Q=LT(C);if(Q.length>0){let q=P.find(K=>K.role==="user"),ce=typeof q?.content=="string"?q.content.slice(0,120):"Task";IT(ce,Q);let M=Q.length===1?"step":"steps",O=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:K,startExecution:pe,setPlanMode:X}=Ki();process.stdout.write(`
1403
- ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${Q.length} ${M})${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.yellow}[E]${p.reset}${p.dim}dit${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let fe=process.stdin.isRaw,ne=await new Promise(_e=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ve=>{try{process.stdin.setRawMode(fe||!1)}catch{}let ct=ve.toString().toLowerCase()[0]||"\r";_e(ct)})});if(process.stdout.write(`
1404
- `),ne==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(ne==="e")console.log(`${p.yellow}Type /plan edit to open in editor, or give feedback.${p.reset}`);else if(K()){pe(),X(!1),cu(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing ${Q.length} ${M}...`);let _e=`[PLAN APPROVED \u2014 EXECUTE NOW]
1410
+ 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.`};O.push(z),T.push(z),L(`${p.yellow} \u26A0 Plan rejected (${ca}/2): no files read \u2014 forcing investigation${p.reset}`);continue}if(_r()&&w){let z=(Et||rt||"").trim();wR(z),n1(z);let j=$R(z);if(j.length>0){let ae=O.find(ue=>ue.role==="user"),A=typeof ae?.content=="string"?ae.content.slice(0,120):"Task";bR(A,j);let U=j.length===1?"step":"steps",R=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:ue,startExecution:$e,setPlanMode:te}=Ji();process.stdout.write(`
1411
+ ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${j.length} ${U})${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.yellow}[E]${p.reset}${p.dim}dit${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let I=process.stdin.isRaw,be=await new Promise(Ee=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",Ue=>{try{process.stdin.setRawMode(I||!1)}catch{}let Xe=Ue.toString().toLowerCase()[0]||"\r";Ee(Xe)})});if(process.stdout.write(`
1412
+ `),be==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(be==="e")console.log(`${p.yellow}Type /plan edit to open in editor, or give feedback.${p.reset}`);else if(ue()){$e(),te(!1),gu(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing ${j.length} ${U}...`);let Ee=`[PLAN APPROVED \u2014 EXECUTE NOW]
1405
1413
 
1406
1414
  Implement the following plan step by step. All tools are now available.
1407
1415
 
1408
- ${C}`;P.push({role:"user",content:_e}),T.push({role:"user",content:_e}),O=!0}}else console.log(`
1409
- ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${Q.length} ${M} extracted).${p.reset} Type ${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ${p.reset}${p.cyan}/plan edit${p.reset}${p.dim} to review.${p.reset}`);if(O){c&&(c.stop(),c=null),Ge--;continue}}else{let q=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:M,startExecution:O,setPlanMode:j}=Ki();process.stdout.write(`
1410
- ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let K=process.stdin.isRaw,pe=await new Promise(X=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",fe=>{try{process.stdin.setRawMode(K||!1)}catch{}X(fe.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1411
- `),pe==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(M()){O(),j(!1),cu(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing...`);let fe=`[PLAN APPROVED \u2014 EXECUTE NOW]
1416
+ ${z}`;O.push({role:"user",content:Ee}),T.push({role:"user",content:Ee}),R=!0}}else console.log(`
1417
+ ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${j.length} ${U} extracted).${p.reset} Type ${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ${p.reset}${p.cyan}/plan edit${p.reset}${p.dim} to review.${p.reset}`);if(R){c&&(c.stop(),c=null),ze--;continue}}else{let ae=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:U,startExecution:R,setPlanMode:W}=Ji();process.stdout.write(`
1418
+ ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let ue=process.stdin.isRaw,$e=await new Promise(te=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",I=>{try{process.stdin.setRawMode(ue||!1)}catch{}te(I.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1419
+ `),$e==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(U()){R(),W(!1),gu(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing...`);let I=`[PLAN APPROVED \u2014 EXECUTE NOW]
1412
1420
 
1413
1421
  Implement the following plan step by step. All tools are now available.
1414
1422
 
1415
- ${getPlanContent()||Nt.content}`;P.push({role:"user",content:fe}),T.push({role:"user",content:fe}),q=!0}}else console.log(`
1416
- ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.dim}Type ${p.reset}${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ask follow-up questions to refine.${p.reset}`);if(q){c&&(c.stop(),c=null),Ge--;continue}}}if(c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne),Ft&&D.size>=3){let C=[...D].map(O=>O.split("/").pop()).slice(0,8).join(", "),Q=[...D].some(O=>O.endsWith("package.json")),q=[...D].some(O=>O.endsWith("requirements.txt")),ce=[...D].some(O=>O.endsWith("package-lock.json")||O.endsWith("yarn.lock")||O.endsWith("pnpm-lock.yaml")),M=Q&&!ce?"npm install not yet run":q?"pip install not yet run":null;yr=`[Previous session created ${D.size} files: ${C}`+(M?` \u2014 ${M}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Ft&&!hu&&H>0){let C=[...D].some(X=>X.endsWith("package.json")),Q=[...D].some(X=>X.endsWith("requirements.txt")||X.endsWith("Pipfile")||X.endsWith("pyproject.toml")),q=[...D].some(X=>X.endsWith("package-lock.json")||X.endsWith("yarn.lock")||X.endsWith("pnpm-lock.yaml")),ce=P.flatMap(X=>{let fe=Array.isArray(X.tool_calls)?X.tool_calls:[],ne=Array.isArray(X.content)?X.content.filter(_e=>_e?.type==="tool_use"):[];return[...fe,...ne]}).filter(X=>{let fe=X.function?.name||X.name||"";return fe==="bash"||fe==="Bash"}).map(X=>{try{let fe=X.function?.arguments??X.input??{};return(typeof fe=="string"?JSON.parse(fe):fe)?.command||""}catch{return""}}),M=ce.some(X=>/pip\s+install|python\s+-m\s+venv/.test(X)),O=ce.some(X=>/npm\s+install/.test(X)),K=[...D].some(X=>/\/App\.(js|ts|jsx|tsx)$/.test(X))&&!C&&!O;if(Q&&!M||C&&!q&&!O||K){hu=!0;let X=[];Q&&!M&&X.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),K?X.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):C&&!q&&!O&&X.push("npm install");let fe=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${X.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;I(`${p.dim} [post-creation] bootstrapping environment (${X.join(", ")})${p.reset}`),P.push({role:"user",content:fe}),T.push({role:"user",content:fe});continue}}if(H>0&&!s._isSummaryTurn&&Zi(vt))try{I(`${p.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${p.reset}`);let C=D.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.",Q=[...T,{role:"user",content:C}],ce=((await ry(Q,[],{}))?.content||"").trim();ce&&(console.log(`
1417
- ${ce}`),P.push({role:"user",content:C},{role:"assistant",content:ce}))}catch{}Ce(P),cr(P),await Nu();return}H++,ga++,H>=1&&(xe=!1);for(let w of en){let y=w.function.name;se.set(y,(se.get(y)||0)+1)}if(H>=30&&!wy){wy=!0,I(`${p.yellow} \u26A0 Tool budget warning: ${H} tool calls used \u2014 nudging model to wrap up${p.reset}`);let w={role:"user",content:"[SYSTEM] \u26A0 You have used "+H+" 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),T.push(w)}let we=await Promise.all(en.map(w=>$R(w)));if(Ra){let w=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let y of we)!y.canExecute||!w.has(y.fnName)||(y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: You already have enough evidence to produce the requested summary/document. Write the deliverable now and stop reading more files.",tool_call_id:y.callId})}{let w=Jt(T,ft()),y=w.percentage,G=we.some(q=>q.canExecute&&q.fnName==="read_file"&&!q.args?.line_end),B=we.filter(q=>q.canExecute&&q.fnName==="read_file"&&q.args?.path&&dn(vs,q.args.path)>=1&&!q.args?.line_start).map(q=>q.args.path.split("/").slice(-2).join("/")),C=B.length>0;if(y>=70&&G&&va<70||y>=85&&va<85||C){va=y;let q=y>=85?"URGENT":"WARNING",ce;C?(q="WARNING",ce=`Full-file read of ${B.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):G?ce=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:ce="Use targeted reads (line_start/line_end) to save space.";let M={role:"user",content:`[SYSTEM ${q}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${ce}`};if(P.push(M),T.push(M),y>=85){let O=C?` (re-read of: ${B.join(", ")})`:"";I(`${p.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${O}${p.reset}`)}}}let Na=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=dn(vs,y),B=Na.get(y)||0,C=G+B,Q=w.args?.line_start!=null,q=Dt.get(y)||0,ce=q>0,M=2;if(C>=Es){let O=y.split("/").slice(-2).join("/"),j=(ks.get(y)||0)+1;if(ks.set(y,j),j===1)I(`${p.red} \u2716 Blocked: "${O}" read ${C}\xD7 \u2014 hard cap (${Es}) reached${p.reset}`);else if(j===2){I(`${p.red} \u2716 Escalated block: "${O}" \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let K={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 (${Es}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};P.push(K),T.push(K)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${C}\xD7 (hard cap: ${Es}). 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(C>=1&&Q)if(ce&&q<=M){let O=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Targeted re-read: "${O}" (line_start=${w.args.line_start}) \u2014 edit recovery #${q}${p.reset}`),Dt.set(y,q-1)}else if(ce&&q>M){let O=y.split("/").slice(-2).join("/");I(`${p.red} \u2716 Edit recovery blocked: "${O}" \u2014 ${M} recovery reads already used. Use grep to find the exact line numbers, then retry.${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${M} 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 O=parseInt(w.args.line_start,10)||1,j=parseInt(w.args.line_end,10)||O+350,K=In.get(y)||[],pe=!1;for(let[X,fe]of K){let ne=Math.max(O,X),_e=Math.min(j,fe);if(_e>ne){let ve=_e-ne,ct=j-O||1,Qe=fe-X||1,Pt=ve/Qe>=.7&&ve/ct<.7,st=j-O<=v0;if(ve>=ct||!st&&(ve/ct>=.7||ve/Qe>=.7)){let La=y.split("/").slice(-2).join("/"),Uu=`${y}:${O}-${j}`,Cs=(ma.get(Uu)||0)+1;if(ma.set(Uu,Cs),I(Pt?`${p.red} \u2716 Blocked superread: "${La}" lines ${O}-${j} subsumes already-read ${X}-${fe} \u2014 use line_start=${fe+1} to skip known content (block #${Cs})${p.reset}`:`${p.red} \u2716 Blocked duplicate read: "${La}" lines ${O}-${j} (\u226570% overlap with lines ${X}-${fe} already in context, block #${Cs})${p.reset}`),Cs>=2){I(`${p.red} \u2716 Escalated range-block: "${La}" lines ${O}-${j} \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let Wu={role:"user",content:Pt?`[SYSTEM] Read blocked ${Cs}\xD7 for read_file("${y}", lines ${O}-${j}). Lines ${X}-${fe} were already read. Use line_start=${fe+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Cs}\xD7 for read_file("${y}", lines ${O}-${j}). Lines ${X}-${fe} were already read and will NOT change. Use grep_search to find specific content instead.`};P.push(Wu),T.push(Wu)}w.canExecute=!1,w.errorResult={role:"tool",content:Pt?`BLOCKED: read_file("${y}", lines ${O}-${j}) re-reads lines ${X}-${fe} already in context. Use line_start=${fe+1} to read only the new content beyond line ${fe}.`:`BLOCKED: read_file("${y}", lines ${O}-${j}) is a duplicate \u2014 lines ${X}-${fe} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:w.callId},pe=!0;break}}}if(!pe){let X=K.length,fe=2;if(X>=3){let _e=y.split("/").slice(-2).join("/");I(`${p.red} \u2716 Blocked file-scroll: "${_e}" \u2014 ${X} sections already read. Use grep to find specific content.${p.reset}`);let ve=dn(Sa,y)>=Er;w.canExecute=!1,w.errorResult={role:"tool",content:ve?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${X} 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 ${X} 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 X>=fe&&(w._scrollWarn={sectionCount:X+1,path:y})}}else if(C>=1){let O=Dt.get(y)||0;if(O>0){let j=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Full re-read: "${j}" \u2014 test-failure recovery (${O} remaining)${p.reset}`);let K=O-1;K<=0?Dt.delete(y):Dt.set(y,K)}else{let j=y.split("/").slice(-2).join("/"),K=(ks.get(y)||0)+1;if(ks.set(y,K),K===1)I(`${p.red} \u2716 Blocked unbounded re-read: "${j}" \u2014 already in context. Use line_start/line_end for specific sections.${p.reset}`);else if(K===2){I(`${p.red} \u2716 Escalated block: "${j}" \u2014 model ignored unbounded re-read block, injecting system warning${p.reset}`);let pe={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(pe),T.push(pe)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${C}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:w.callId}}}w.canExecute&&Na.set(y,(Na.get(y)||0)+1)}if(Ln>=3)for(let w of we)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(I(`${p.red} \u2716 Blocked ${w.fnName} \u2014 ${Ln} consecutive file-not-found errors, must search first${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${Ln} 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)){I(`${p.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${p.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)&&(I(`${p.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${p.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||"")&&(I(`${p.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${p.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 B=require("fs"),C=require("path").resolve(process.cwd(),y);if(B.existsSync(C)){let Q=B.statSync(C).size,q=Buffer.byteLength(G,"utf8"),ce=Q>0?q/Q:1;if(ce<.6&&Q>200){let M=y.split("/").slice(-2).join("/");console.log(`${p.red} \u2716 write_file shrink guard: "${M}" would shrink to ${Math.round(ce*100)}% of original \u2014 likely context loss${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(ce*100)}% of current file size (${Q} \u2192 ${q} 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 Du=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let G=Du.get(y)||0,B=dn(Sa,y)+G,C=dn(vs,y)>=1,Q=C?Math.min(3,Er):Er;if(B>=Q){let q=y.split("/").slice(-2).join("/");I(`${p.red} \u2716 Blocked grep: "${q}" grepped ${B}\xD7 with different patterns \u2014 flood threshold exceeded${p.reset}`);let ce=dn(vs,y),M=ce>=Es;if(M){let O={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${ce} sections and tried ${B} 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(O),T.push(O),I(`${p.red} \u2716 Deadlock detected: "${q}" \u2014 both read and grep blocked, injecting deadlock-break${p.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:M?`BLOCKED: grep("${y}") denied \u2014 ${B} 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.`:C?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${B} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${B} patterns already tried. Work with the grep results already in your context.`,tool_call_id:w.callId}}w.canExecute&&Du.set(y,G+1)}let O0=5,qu=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),B=qu.get(G)||0,C=dn(Cu,G)+B;C>=O0&&(I(`${p.yellow} \u26A0 Blocked ssh_exec: same command run ${C}\xD7 \u2014 result already in context${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${C} 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&&qu.set(G,B+1)}if(Ot){let w=we.filter(B=>B.canExecute&&B.fnName==="ssh_exec"),y=we.some(B=>B.canExecute&&B.fnName!=="ssh_exec"),G=te&&R<3;if(w.length>0&&!y&&G&&la<1)Ot=!1,la++,qt=Math.max(0,yo-2),I(`${p.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${la}/1)]${p.reset}`);else for(let B of w)B.canExecute=!1,B.errorResult={role:"tool",content:at?`BLOCKED: ssh_exec denied \u2014 SSH paused (${yo}+ calls). Root cause is known (${kt}). 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 (${yo}+ 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:B.callId}}let N0=pR(P,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((te||z)&&!N0&&R<3&&!Ot)for(let w of we){if(!w.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(w.fnName))continue;R++;{let B=ft(),{messages:C}=un(T,B);T=C}let y=W?.matchedName?`${W.matchedName} (${W.matchedProfile?.host||"server"})`:W?.url,G=W?.shouldPreferSsh?`BLOCKED: ${w.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${W?.url} with browser_open or use ssh_exec on ${y} first, then return to local code if needed.`:`BLOCKED: ${w.fnName} denied \u2014 this looks like a live app issue. Inspect ${W?.url} with browser_open first, then return to local code if needed.`;I(`${p.yellow} \u26A0 Runtime guard: blocking local ${w.fnName} \u2014 inspect the live app first${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:G,tool_call_id:w.callId};break}if(!$e&&Ut&&Ft&&Wt>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of we)y.canExecute&&w.includes(y.fnName)&&(I(`${p.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${p.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(ws>=0){let w=we.filter(y=>y.canExecute).length;if(w>0&&(ws-=w,ws<0))if(!ua&&D.size>ca){ua=!0,ws=5,I(`${p.green} \u2713 Post-wipe progress detected (${D.size-ca} files modified) \u2014 granting 5 bonus tool calls${p.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};P.push(y),T.push(y)}else{I(`${p.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${p.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),T.push(y)}}let M0=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||M0.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),G=`${w.fnName}|${y}`,B=dn(uu,G);B>=2?(I(`${p.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${B+1}\xD7 with identical args${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName}() with these exact arguments has already been called ${B}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:w.callId}):B===1&&I(`${p.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${p.reset}`),ys(uu,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&&(go.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},I(`${p.yellow} \u26A0 Map-first gate: blocked re-edit of "${G.split("/").slice(-1)[0]}" \u2014 re-read required${p.reset}`)):w.add(G))}}let $o=c?{skipSpinner:!0,skipSummaries:!0}:{},P0=we.some(w=>w.fnName==="ask_user"),Fu=!$o.skipSummaries&&!xe,Nr=null,Rs=null;if(Fu&&!P0){if(xe=!0,$o.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(Rs=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let w=lr(we,H,!1,"blink"),y=lr(we,H,!1);process.stdout.write(`${H>1?`
1418
- `:""}${w}`),io=y,ao=Date.now(),Nr=!0}else if(!hn){let w=lr(we,H,!1);tu(w,io,ao)||(process.stdout.write(`${H>1?`
1423
+ ${getPlanContent()||Pt.content}`;O.push({role:"user",content:I}),T.push({role:"user",content:I}),ae=!0}}else console.log(`
1424
+ ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.dim}Type ${p.reset}${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ask follow-up questions to refine.${p.reset}`);if(ae){c&&(c.stop(),c=null),ze--;continue}}}if(c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe),Bt&&J.size>=3){let z=[...J].map(R=>R.split("/").pop()).slice(0,8).join(", "),j=[...J].some(R=>R.endsWith("package.json")),ae=[...J].some(R=>R.endsWith("requirements.txt")),A=[...J].some(R=>R.endsWith("package-lock.json")||R.endsWith("yarn.lock")||R.endsWith("pnpm-lock.yaml")),U=j&&!A?"npm install not yet run":ae?"pip install not yet run":null;$r=`[Previous session created ${J.size} files: ${z}`+(U?` \u2014 ${U}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Bt&&!bu&&H>0){let z=[...J].some(te=>te.endsWith("package.json")),j=[...J].some(te=>te.endsWith("requirements.txt")||te.endsWith("Pipfile")||te.endsWith("pyproject.toml")),ae=[...J].some(te=>te.endsWith("package-lock.json")||te.endsWith("yarn.lock")||te.endsWith("pnpm-lock.yaml")),A=O.flatMap(te=>{let I=Array.isArray(te.tool_calls)?te.tool_calls:[],be=Array.isArray(te.content)?te.content.filter(Ee=>Ee?.type==="tool_use"):[];return[...I,...be]}).filter(te=>{let I=te.function?.name||te.name||"";return I==="bash"||I==="Bash"}).map(te=>{try{let I=te.function?.arguments??te.input??{};return(typeof I=="string"?JSON.parse(I):I)?.command||""}catch{return""}}),U=A.some(te=>/pip\s+install|python\s+-m\s+venv/.test(te)),R=A.some(te=>/npm\s+install/.test(te)),ue=[...J].some(te=>/\/App\.(js|ts|jsx|tsx)$/.test(te))&&!z&&!R;if(j&&!U||z&&!ae&&!R||ue){bu=!0;let te=[];j&&!U&&te.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),ue?te.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):z&&!ae&&!R&&te.push("npm install");let I=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${te.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;L(`${p.dim} [post-creation] bootstrapping environment (${te.join(", ")})${p.reset}`),O.push({role:"user",content:I}),T.push({role:"user",content:I});continue}}if(H>0&&!n._isSummaryTurn&&ta(Et))try{L(`${p.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${p.reset}`);let z=J.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.",j=[...T,{role:"user",content:z}],A=((await Ry(j,[],{}))?.content||"").trim();A&&(console.log(`
1425
+ ${A}`),O.push({role:"user",content:z},{role:"assistant",content:A}))}catch{}Oe(O),dr(O),await Fu();return}H++,$a++,H>=1&&(ge=!1);for(let w of sn){let y=w.function.name;se.set(y,(se.get(y)||0)+1)}if(H>=30&&!By){By=!0,L(`${p.yellow} \u26A0 Tool budget warning: ${H} tool calls used \u2014 nudging model to wrap up${p.reset}`);let w={role:"user",content:"[SYSTEM] \u26A0 You have used "+H+" 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."};O.push(w),T.push(w)}let xe=await Promise.all(sn.map(w=>s1(w)));if(Oa){let w=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let y of xe)!y.canExecute||!w.has(y.fnName)||(y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: You already have enough evidence to produce the requested summary/document. Write the deliverable now and stop reading more files.",tool_call_id:y.callId})}{let w=Qt(T,ht()),y=w.percentage,Y=xe.some(j=>j.canExecute&&j.fnName==="read_file"&&!j.args?.line_end),B=xe.filter(j=>j.canExecute&&j.fnName==="read_file"&&j.args?.path&&pn(As,j.args.path)>=1&&!j.args?.line_start).map(j=>j.args.path.split("/").slice(-2).join("/")),G=B.length>0;if(y>=70&&Y&&Ra<70||y>=85&&Ra<85||G){Ra=y;let j=y>=85?"URGENT":"WARNING",ae;G?(j="WARNING",ae=`Full-file read of ${B.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):Y?ae=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:ae="Use targeted reads (line_start/line_end) to save space.";let A={role:"user",content:`[SYSTEM ${j}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${ae}`};if(O.push(A),T.push(A),y>=85){let U=G?` (re-read of: ${B.join(", ")})`:"";L(`${p.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${U}${p.reset}`)}}}let La=new Map;for(let w of xe){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let Y=pn(As,y),B=La.get(y)||0,G=Y+B,z=$s.has(y),j=w.args?.line_start!=null,ae=qt.get(y)||0,A=ae>0,U=2;if(!z&&G>=Os){let R=y.split("/").slice(-2).join("/"),W=(Ss.get(y)||0)+1;if(Ss.set(y,W),W===1)L(`${p.red} \u2716 Blocked: "${R}" read ${G}\xD7 \u2014 hard cap (${Os}) reached${p.reset}`);else if(W===2){L(`${p.red} \u2716 Escalated block: "${R}" \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let ue={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 (${Os}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};O.push(ue),T.push(ue)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${G}\xD7 (hard cap: ${Os}). 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(!z&&G>=1&&j)if(A&&ae<=U){let R=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Targeted re-read: "${R}" (line_start=${w.args.line_start}) \u2014 edit recovery #${ae}${p.reset}`),qt.set(y,ae-1)}else if(A&&ae>U){let R=y.split("/").slice(-2).join("/");L(`${p.red} \u2716 Edit recovery blocked: "${R}" \u2014 ${U} recovery reads already used. Use grep to find the exact line numbers, then retry.${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${U} 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 R=parseInt(w.args.line_start,10)||1,W=parseInt(w.args.line_end,10)||R+350,ue=En.get(y)||[],$e=!1;for(let[te,I]of ue){let be=Math.max(R,te),Ee=Math.min(W,I);if(Ee>be){let Ue=Ee-be,Xe=W-R||1,Lt=I-te||1,tt=Ue/Lt>=.7&&Ue/Xe<.7,Lr=W-R<=X0;if(Ue>=Xe||!Lr&&(Ue/Xe>=.7||Ue/Lt>=.7)){let ja=y.split("/").slice(-2).join("/"),Vu=`${y}:${R}-${W}`,Ms=(wa.get(Vu)||0)+1;if(wa.set(Vu,Ms),L(tt?`${p.red} \u2716 Blocked superread: "${ja}" lines ${R}-${W} subsumes already-read ${te}-${I} \u2014 use line_start=${I+1} to skip known content (block #${Ms})${p.reset}`:`${p.red} \u2716 Blocked duplicate read: "${ja}" lines ${R}-${W} (\u226570% overlap with lines ${te}-${I} already in context, block #${Ms})${p.reset}`),Ms>=2){L(`${p.red} \u2716 Escalated range-block: "${ja}" lines ${R}-${W} \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let Ju={role:"user",content:tt?`[SYSTEM] Read blocked ${Ms}\xD7 for read_file("${y}", lines ${R}-${W}). Lines ${te}-${I} were already read. Use line_start=${I+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Ms}\xD7 for read_file("${y}", lines ${R}-${W}). Lines ${te}-${I} were already read and will NOT change. Use grep_search to find specific content instead.`};O.push(Ju),T.push(Ju)}w.canExecute=!1,w.errorResult={role:"tool",content:tt?`BLOCKED: read_file("${y}", lines ${R}-${W}) re-reads lines ${te}-${I} already in context. Use line_start=${I+1} to read only the new content beyond line ${I}.`:`BLOCKED: read_file("${y}", lines ${R}-${W}) is a duplicate \u2014 lines ${te}-${I} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:w.callId},$e=!0;break}}}if(!$e){let te=ue.length,I=2;if(te>=3){let Ee=y.split("/").slice(-2).join("/");L(`${p.red} \u2716 Blocked file-scroll: "${Ee}" \u2014 ${te} sections already read. Use grep to find specific content.${p.reset}`);let Ue=pn(Ta,y)>=Cr;w.canExecute=!1,w.errorResult={role:"tool",content:Ue?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${te} 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 ${te} 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 te>=I&&(w._scrollWarn={sectionCount:te+1,path:y})}}else if(!z&&G>=1){let R=qt.get(y)||0;if(R>0){let W=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Full re-read: "${W}" \u2014 test-failure recovery (${R} remaining)${p.reset}`);let ue=R-1;ue<=0?qt.delete(y):qt.set(y,ue)}else{let W=y.split("/").slice(-2).join("/"),ue=(Ss.get(y)||0)+1;if(Ss.set(y,ue),ue===1)L(`${p.red} \u2716 Blocked unbounded re-read: "${W}" \u2014 already in context. Use line_start/line_end for specific sections.${p.reset}`);else if(ue===2){L(`${p.red} \u2716 Escalated block: "${W}" \u2014 model ignored unbounded re-read block, injecting system warning${p.reset}`);let $e={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.`};O.push($e),T.push($e)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${G}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:w.callId}}}w.canExecute&&La.set(y,(La.get(y)||0)+1)}if(jn>=3)for(let w of xe)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(L(`${p.red} \u2716 Blocked ${w.fnName} \u2014 ${jn} consecutive file-not-found errors, must search first${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${jn} 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 xe){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)){L(`${p.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${p.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)&&(L(`${p.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${p.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 xe)w.canExecute&&(w.fnName!=="ssh_exec"&&w.fnName!=="bash"||/\bsed\s+-n\b/.test(w.args?.command||"")&&(L(`${p.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${p.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 xe){if(!w.canExecute||w.fnName!=="write_file")continue;let y=w.args?.path,Y=w.args?.content||"";if(y)try{let B=require("fs"),G=require("path").resolve(process.cwd(),y);if(B.existsSync(G)){let z=B.statSync(G).size,j=Buffer.byteLength(Y,"utf8"),ae=z>0?j/z:1,A=ku(M),U=ku(y);if(Uy(M)&&(A.includes(U)||A.includes(`./${U}`)))continue;if(ae<.6&&z>200){let W=y.split("/").slice(-2).join("/");console.log(`${p.red} \u2716 write_file shrink guard: "${W}" would shrink to ${Math.round(ae*100)}% of original \u2014 likely context loss${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(ae*100)}% of current file size (${z} \u2192 ${j} 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 Gu=new Map;for(let w of xe){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let Y=Gu.get(y)||0,B=pn(Ta,y)+Y,G=pn(As,y)>=1,z=G?Math.min(3,Cr):Cr;if(B>=z){let j=y.split("/").slice(-2).join("/");L(`${p.red} \u2716 Blocked grep: "${j}" grepped ${B}\xD7 with different patterns \u2014 flood threshold exceeded${p.reset}`);let ae=pn(As,y),A=ae>=Os;if(A){let U={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${ae} sections and tried ${B} 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.`};O.push(U),T.push(U),L(`${p.red} \u2716 Deadlock detected: "${j}" \u2014 both read and grep blocked, injecting deadlock-break${p.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:A?`BLOCKED: grep("${y}") denied \u2014 ${B} 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.`:G?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${B} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${B} patterns already tried. Work with the grep results already in your context.`,tool_call_id:w.callId}}w.canExecute&&Gu.set(y,Y+1)}let tw=5,zu=new Map;for(let w of xe){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let Y=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),B=zu.get(Y)||0,G=pn(ju,Y)+B;G>=tw&&(L(`${p.yellow} \u26A0 Blocked ssh_exec: same command run ${G}\xD7 \u2014 result already in context${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${G} 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&&zu.set(Y,B+1)}if(Nt){let w=xe.filter(B=>B.canExecute&&B.fnName==="ssh_exec"),y=xe.some(B=>B.canExecute&&B.fnName!=="ssh_exec"),Y=K&&he<3;if(w.length>0&&!y&&Y&&da<1)Nt=!1,da++,Ft=Math.max(0,bo-2),L(`${p.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${da}/1)]${p.reset}`);else for(let B of w)B.canExecute=!1,B.errorResult={role:"tool",content:ct?`BLOCKED: ssh_exec denied \u2014 SSH paused (${bo}+ calls). Root cause is known (${kt}). 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 (${bo}+ 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:B.callId}}let nw=ZR(O,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((K||C)&&!nw&&he<3&&!Nt)for(let w of xe){if(!w.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(w.fnName))continue;he++;{let B=ht(),{messages:G}=hn(T,B);T=G}let y=F?.matchedName?`${F.matchedName} (${F.matchedProfile?.host||"server"})`:F?.url,Y=F?.shouldPreferSsh?`BLOCKED: ${w.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${F?.url} with browser_open or use ssh_exec on ${y} first, then return to local code if needed.`:`BLOCKED: ${w.fnName} denied \u2014 this looks like a live app issue. Inspect ${F?.url} with browser_open first, then return to local code if needed.`;L(`${p.yellow} \u26A0 Runtime guard: blocking local ${w.fnName} \u2014 inspect the live app first${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:Y,tool_call_id:w.callId};break}if(!ye&&Wt&&Bt&&Ht>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of xe)y.canExecute&&w.includes(y.fnName)&&(L(`${p.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${p.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(bs>=0){let w=xe.filter(y=>y.canExecute).length;if(w>0&&(bs-=w,bs<0))if(!ha&&J.size>fa){ha=!0,bs=5,L(`${p.green} \u2713 Post-wipe progress detected (${J.size-fa} files modified) \u2014 granting 5 bonus tool calls${p.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};O.push(y),T.push(y)}else{L(`${p.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${p.reset}`);for(let Y of xe)Y.canExecute&&(Y.canExecute=!1,Y.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:Y.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."};O.push(y),T.push(y)}}let sw=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 xe){if(!w.canExecute||sw.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),Y=`${w.fnName}|${y}`,B=pn(yu,Y);B>=2?(L(`${p.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${B+1}\xD7 with identical args${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName}() with these exact arguments has already been called ${B}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:w.callId}):B===1&&L(`${p.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${p.reset}`),ws(yu,Y)}{let w=new Set;for(let y of xe){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let Y=y.args?.path;Y&&(w.has(Y)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${Y}" is already being edited in this batch. Finish one edit first, then re-read the changed section before the next one.`,tool_call_id:y.callId},L(`${p.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${Y.split("/").slice(-1)[0]}"${p.reset}`)):Ts.has(Y)&&!$s.has(Y)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${Y}" 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},L(`${p.yellow} \u26A0 Map-first gate: blocked re-edit of "${Y.split("/").slice(-1)[0]}" \u2014 re-read required${p.reset}`)):w.add(Y))}}let xo=c?{skipSpinner:!0,skipSummaries:!0}:{},ow=xe.some(w=>w.fnName==="ask_user"),Ku=!xo.skipSummaries&&!ge,Gt=null,Ps=null;if(Ku&&!ow){if(ge=!0,xo.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(Ps=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let w=ur(xe,H,!1,0),y=ur(xe,H,!1);process.stdout.write(`${H>1?`
1426
+ `:""}${w}`),fo=y,ho=Date.now(),Gt={start:Date.now(),frame:0,timer:null}}else if(!yn){let w=ur(xe,H,!1);lu(w,fo,ho)||(process.stdout.write(`${H>1?`
1419
1427
  `:""}${w}
1420
- `),io=w,ao=Date.now())}}else Fu&&(xe=!0,$o.skipSpinner=!0);c&&c._paused&&c.resume();let Mr=null;if(Nr&&process.stdout.isTTY&&we.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();Mr=setInterval(()=>{let G=Math.round((Date.now()-y)/1e3);if(G>=3){let B=`${lr(we,H,!1,"blink")} ${p.dim}[${G}s]${p.reset}`;Rs!==null?process.stdout.write(`\x1B[${Rs};1H\x1B[2K${B}`):process.stdout.write(`\r\x1B[2K${B}`)}},1e3)}let{results:Ve,summaries:L0}=await xR(we,!0,{...$o,skipSummaries:!0});if(Oa){let w={role:"user",content:"[SYSTEM] ask_user is exclusive. Wait for the user's answer before making any other tool calls."};P.push(w),T.push(w)}if(Mr&&(clearInterval(Mr),Mr=null),Nr){Nr=null;let w=lr(we,H,!1);tu(w,io,ao)||(Rs!==null?process.stdout.write(`\x1B[${Rs};1H\x1B[2K${w}
1428
+ `),fo=w,ho=Date.now())}}else Ku&&(ge=!0,xo.skipSpinner=!0);c&&c._paused&&c.resume(),Gt&&process.stdout.isTTY&&(Gt.timer=setInterval(()=>{Gt.frame++;let w=Math.round((Date.now()-Gt.start)/1e3),y=w>=1?` ${p.dim}[${w}s]${p.reset}`:"",Y=`${ur(xe,H,!1,Gt.frame)}${y}`;Ps!==null?process.stdout.write(`\x1B[${Ps};1H\x1B[2K${Y}`):process.stdout.write(`\r\x1B[2K${Y}`)},120));let{results:et,summaries:rw}=await a1(xe,!0,{...xo,skipSummaries:!0});if(Ma){let w={role:"user",content:"[SYSTEM] ask_user is exclusive. Wait for the user's answer before making any other tool calls."};O.push(w),T.push(w)}if(Gt){Gt.timer&&(clearInterval(Gt.timer),Gt.timer=null);let w=ur(xe,H,!1);lu(w,fo,ho)||(Ps!==null?process.stdout.write(`\x1B[${Ps};1H\x1B[2K${w}
1421
1429
  `):process.stdout.write(`\r\x1B[2K${w}
1422
- `),io=w,ao=Date.now()),Rs=null}if(!$o.skipSummaries){let w=L0.filter((B,C)=>!(we[C]&&we[C].fnName==="ask_user"));for(let B of w)tu(B,au,lu)||(console.log(B),au=B,lu=Date.now());let y=we.filter(B=>B&&B.fnName!=="ask_user").map(B=>B.fnName),G=l0.record(0,y,me,D);G&&ZT(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:"))&&(qn++,qn>=Au)){I(`${p.red} \u2716 Loop abort: ${qn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne,{suppressHint:!0}),Ce(P);return}}let Ma=!1;for(let w=0;w<we.length;w++){let y=we[w];if(!y.canExecute)continue;let G=Ve[w].content,B=G.split(`
1423
- `)[0],C=!B.startsWith("ERROR")&&!B.startsWith("CANCELLED")&&!B.startsWith("Command failed")&&!B.startsWith("EXIT");if(!C&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&B.includes("old_text not found")){let M=Dt.get(y.args.path)||0;Dt.set(y.args.path,M+1)}if(!C&&y.fnName==="bash"&&_r.size>0){let M=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(M))for(let[j]of _r)Dt.has(j)||(Dt.set(j,1),I(`${p.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${j.split("/").pop()}"${p.reset}`))}if(!C&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(B)){if(Ln++,Ln>=2){I(`${p.yellow} \u26A0 File-not-found streak: ${Ln} consecutive misses \u2014 forcing search${p.reset}`);let M={role:"user",content:`[SYSTEM] ${Ln} 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(M),T.push(M)}}else C&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(Ln=0);if(C&&y.fnName==="write_file"&&y.args?.path){let M=y.args.path.split("/").pop(),O=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(M)&&!O){I(`${p.yellow} \u26A0 Temp file: "${M}" \u2014 delete with bash rm when done to keep the workspace clean${p.reset}`);let K={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(K),T.push(K)}}if(C&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Dt.delete(y.args.path),D.add(y.args.path);for(let j of xs)!j.done&&y.args.path.endsWith(j.file.split("/").pop())&&(j.done=!0,I(`${p.green} \u2713 TODO done: ${j.file}${p.reset}`));let M=ys(c0,y.args.path),O=y.args.path.split("/").slice(-2).join("/");if(M===u0){I(`${p.yellow} \u26A0 Loop warning: "${O}" edited ${M}\xD7 \u2014 possible edit loop${p.reset}`);let j={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${M}\xD7. One more edit max, then move on.`};P.push(j),T.push(j)}else if(M>=d0){I(`${p.red} \u2716 Loop abort: "${O}" edited ${M}\xD7 \u2014 aborting to prevent runaway loop${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne,{suppressHint:!0}),Ce(P);return}$e&&Ae==="verify"||(fo=!0,ho=0,Ma=!0)}if(C&&y.canExecute&&$e&&(jn=0),C&&y.canExecute&&!($e&&Ae==="plan")){let M=["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,Zt=0,Wt++;let ne=y.args?.path||y.args?.file_path;ne&&(Qc(kn,ne,1),In.delete(ne),go.add(ne))}else if(M.includes(y.fnName)){if(Bt++,Ut&&Zt++,$e&&Ae==="implement"&&y.fnName==="read_file"&&xs.length>0){let ne=y.args?.path||y.args?.file_path||"",_e=xs.find(ve=>!ve.done&&ne.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}
1424
- Do NOT re-read \u2014 apply the edit directly with edit_file.`};P.push(ve),T.push(ve),I(`${p.yellow} \u26A0 TODO nudge: ${_e.file} \u2014 already analyzed, edit directly${p.reset}`)}}$e&&Ae==="implement"&&fo&&ho<1&&(ho++,Ma=!0)}$e&&Ae==="verify"&&co++,C&&AR(y)&&(fo=!1,ho=0);let j=o.postEditCap,K=$e&&Ae==="implement"?Math.min(Ou,10):Ou,pe=at?8:Tr?Wt>0?4:6:Ft?Wt>0?6:10:Wt>0?j:K,X=6,fe=!$e&&Ut&&(at&&Zt>=X||Ft&&Wt>=3&&Zt>=X||Zt>=X);if(ur<2&&!Ut&&Bt>=3&&D.size===0){let ne=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,_e=Date.now()-Ne,ve=ur===0?.4:.65;if(ne>0&&_e>ne*ve){ur++;let ct=Math.round(_e/6e4),Qe=Math.round(_e/ne*100);I(`${p.yellow} \u26A0 Time nudge #${ur}: ${ct}m elapsed (${Qe}%), ${Bt} reads, 0 edits${p.reset}`);let Pt={role:"user",content:ur===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),T.push(Pt)}}if(fe&&M.includes(y.fnName)){let ne=at?`root cause already identified (${kt})`:Zt>=X?`${Bt} consecutive reads without an edit`:`${Wt} file edit(s) already made`;I(`${p.red} \u2716 Blocked read-only tool: cap fired, ${ne}${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:at?`BLOCKED: root cause already identified (${kt}). 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.":Zt>=X?`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: ${Wt} 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>=pe&&!Ut){if(Ut=!0,Tr&&(Ra=!0),I(`${p.yellow} \u26A0 Investigation cap: ${Bt} read-only calls without an edit \u2014 forcing implementation${p.reset}`),$e&&Ae==="plan"){let ve=[...T].reverse().find(Pt=>Pt.role==="assistant"),ct=typeof ve?.content=="string"?ve.content:"",Qe=await fr("implement",ct);Qe&&(P.push(Qe),T.push(Qe),Ge=0,St=gs("implement"))}let ne;at?ne=`[SYSTEM] Root cause was already identified (${kt}). Edit the file now \u2014 do not read more files.`:Tr?ne="[SYSTEM] You have enough evidence to write the requested summary/document now. Use write_file or edit_file to produce the deliverable, and stop reading more files unless a required section is still unsupported.":Ot?ne="[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.":ne="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let _e={role:"user",content:ne};P.push(_e),T.push(_e)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let M=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),O=ys(Cu,M);if(O===f0){I(`${p.yellow} \u26A0 Loop warning: same bash command run ${O}\xD7 \u2014 possible debug loop${p.reset}`);let j={role:"user",content:`[SYSTEM WARNING] Same bash command ${O}\xD7. Debug loop detected \u2014 try a different approach.`};P.push(j),T.push(j)}else if(O>=h0){I(`${p.red} \u2716 Loop abort: same bash command run ${O}\xD7 \u2014 aborting runaway debug loop${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne,{suppressHint:!0}),Ce(P);return}}if(y.fnName==="ssh_exec"){qt++;{let j=(Ve[w]?.content??"").split(`
1425
- `).map(K=>K.trim()).find(K=>K.length>0&&!K.startsWith("**")&&(K.startsWith("EXIT")||/^[\w./-]+:\s/.test(K)||K.startsWith("bash:")||K.startsWith("sh:")))??"";if(j){if(j===da?$s++:(da=j,$s=1),$s===3&&!Ot){I(`${p.yellow} \u26A0 SSH repeated-error: "${j.slice(0,60)}" returned ${$s}\xD7 \u2014 nudging to change approach${p.reset}`);let K={role:"user",content:`[SYSTEM WARNING] The last ${$s} SSH commands all failed with the same error: "${j}". 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(K),T.push(K)}}else da="",$s=0}if(qt>=A0){I(`${p.red} \u2716 SSH storm abort: ${qt} consecutive ssh_exec calls \u2014 aborting${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne,{suppressHint:!0}),Ce(P);return}else if(qt===yo){{let j=ft(),{messages:K}=un(T,j);T=K}Ot=!0,ea++,I(`${p.yellow} \u26A0 SSH storm warning (#${ea}): ${qt} consecutive ssh_exec calls \u2014 blocking further SSH${p.reset}`);let O={role:"user",content:at?`[SYSTEM WARNING] ${qt} consecutive SSH calls. Root cause identified (${kt}). 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(O),T.push(O)}}else y.canExecute&&(qt=0);if(y.fnName==="bash"&&y.canExecute){let j=(Ve[w]?.content??"").split(`
1426
- `).map(K=>K.trim()).find(K=>K.length>0&&(K.startsWith("EXIT")||/^[\w./-]+:\s/.test(K)||K.startsWith("bash:")||K.startsWith("sh:")))??"";if(j){if(j===fa?bs++:(fa=j,bs=1),bs===3){I(`${p.yellow} \u26A0 Bash repeated-error: "${j.slice(0,60)}" returned ${bs}\xD7 \u2014 nudging to change approach${p.reset}`);let K={role:"user",content:`[SYSTEM WARNING] The last ${bs} bash commands all failed with the same error: "${j}". 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(K),T.push(K)}}else fa="",bs=0}if(y.fnName==="bash"&&y.canExecute&&!eu&&y.args?.command){let M=Ve[w]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!M.startsWith("EXIT")&&!M.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(M)||M.includes("files changed")||M.includes("file changed")||M.includes("insertions(+)")||M.includes("create mode"))){eu=!0,dr=0,I(`${p.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${p.reset}`);let K={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(K),T.push(K)}}if(eu&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(dr++,dr>2)){I(`${p.yellow} \u26A0 Post-commit git verification blocked (call ${dr})${p.reset}`);let O={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(dr-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(O),T.push(O)}if(C&&y.fnName==="grep"&&G&&!G.startsWith("(no matches)")){let M=G.split(`
1427
- `);for(let O of M){let j=O.indexOf(":");if(j>0){let K=O.substring(0,j);K.startsWith("/")&&!K.includes(" ")&&$r.add(K)}else O.startsWith("/")&&!O.includes(" ")&&$r.add(O.trim())}}{let M=["grep","search_files","glob","glob_files"].includes(y.fnName);if(M&&C&&G&&(G.startsWith("(no matches)")||G.trim()===""||/^No matches found/.test(G.trim())||/^\(0 results\)/.test(G.trim()))){if(xa++,xa===3){I(`${p.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${p.reset}`);let j={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(j),T.push(j)}}else M&&C&&G&&G.trim().length>0&&(xa=0)}if(C&&y.fnName==="grep"&&y.args&&y.args.pattern){let M=`${y.args.pattern}|${y.args.path||""}`,O=ys(p0,M);if(O===m0){I(`${p.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${O}\xD7 \u2014 possible search loop${p.reset}`);let j={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${O}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};P.push(j),T.push(j)}else if(O>=g0){I(`${p.red} \u2716 Loop abort: grep pattern run ${O}\xD7 \u2014 aborting runaway search loop${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne,{suppressHint:!0}),Ce(P);return}if(y.args.path){let j=ys(Sa,y.args.path),K=dn(vs,y.args.path)>=1;if(j===(K?1:y0)){let X=y.args.path.split("/").slice(-2).join("/");I(`${p.yellow} \u26A0 Loop warning: "${X}" grepped ${j}\xD7 with different patterns \u2014 context flood risk${p.reset}`);let fe={role:"user",content:K?`[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 ${j}\xD7 \u2014 use the search results already in context instead of searching again.`};P.push(fe),T.push(fe)}}}if(C&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(G&&!G.startsWith("(no matches)")){let K=G.split(`
1428
- `);for(let pe of K)(pe.startsWith("/")&&!pe.includes(" ")||!pe.includes(":")&&!pe.startsWith("["))&&br.add(pe.trim())}let M=y.args.pattern||y.args.query||y.args.path||"",O=ys(w0,M);if(O===$0){I(`${p.yellow} \u26A0 Loop warning: glob pattern "${M.slice(0,40)}" run ${O}\xD7 \u2014 possible search loop${p.reset}`);let K={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${O}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};P.push(K),T.push(K)}else if(O>=b0){I(`${p.red} \u2716 Loop abort: glob pattern run ${O}\xD7 \u2014 aborting runaway search loop${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne,{suppressHint:!0}),Ce(P);return}let j=M.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(K=>K.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(K));for(let K of j){let pe=K.toLowerCase();ra.has(pe)||ra.set(pe,new Set);let X=ra.get(pe);if(X.add(M),X.size===k0){I(`${p.red} \u2716 Glob core-term block: ${X.size} different patterns all searching for "${pe}" \u2014 search loop${p.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] You have searched for "${pe}" using ${X.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(fe),T.push(fe)}else if(X.size===_0){I(`${p.yellow} \u26A0 Glob core-term warning: ${X.size} different patterns searching for "${pe}"${p.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] ${X.size} different glob patterns all target "${pe}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};P.push(fe),T.push(fe)}}}let Q=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),q=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(Q)||/\/(health|status|ping|ready|alive)\b/.test(Q);if(C&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&q&&G.includes('"valid":true')){{let O=ft();if(Jt(T,O).percentage>=60){let{messages:K,tokensRemoved:pe}=un(T,O);pe>0&&(T=K,console.log(`${p.dim} [pre-stop-compress \u2014 ~${pe} tokens freed before STOP injection, now ${Math.round(Jt(T,O).percentage)}%]${p.reset}`))}}let M={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(M),T.push(M),console.log(`${p.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${p.reset}`)}if(C&&(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)&&(Ss++,I(`${p.dim} [bash write detected: _bashModifiedFiles=${Ss}]${p.reset}`)),G.startsWith("BLOCKED:")){if(qn++,qn>=Au){I(`${p.red} \u2716 Loop abort: ${qn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne,{suppressHint:!0}),Ce(P);return}}else qn=0;if(C)Dn=0,Ta=!0;else if(Dn++,Dn===E0){I(`${p.yellow} \u26A0 Loop warning: ${Dn} consecutive tool errors \u2014 possible stuck loop${p.reset}`);let M={role:"user",content:`[SYSTEM WARNING] ${Dn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};P.push(M),T.push(M)}else if(Dn>=T0){I(`${p.red} \u2716 Loop abort: ${Dn} consecutive errors \u2014 aborting stuck loop${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne,{suppressHint:!0}),Ce(P);return}if(C&&y.fnName==="read_file"&&y.args&&y.args.path){me.add(y.args.path),go.delete(y.args.path);let M=ys(vs,y.args.path);{let pe=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,X=y.args.line_start!=null?parseInt(y.args.line_end,10)||pe+350:350;In.has(y.args.path)||In.set(y.args.path,[]),In.get(y.args.path).push([pe,X])}if(y._scrollWarn){let{sectionCount:pe,path:X}=y._scrollWarn,fe={role:"user",content:`[SYSTEM WARNING] "${X}" \u2014 you have now read ${pe} 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(fe),T.push(fe),I(`${p.yellow} \u26A0 Scroll warning: "${X.split("/").slice(-2).join("/")}" \u2014 ${pe} sections read \u2014 use grep instead${p.reset}`)}let O=y.args.path.split("/").slice(-2).join("/"),j=!y.args?.line_start&&!y.args?.line_end,K=$e&&Ae==="plan";if(!K&&j&&M===x0){{let X=ft();if(Jt(T,X).percentage>=60){let{messages:ne}=un(T,X);T=ne}}I(`${p.yellow} \u26A0 Loop warning: "${O}" read unbounded ${M}\xD7 \u2014 use line_start/line_end${p.reset}`);let pe={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${M}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};P.push(pe),T.push(pe)}else if(!K&&j&&M>=S0){I(`${p.red} \u2716 Loop abort: "${O}" read unbounded ${M}\xD7 \u2014 aborting runaway read loop${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne,{suppressHint:!0}),Ce(P);return}}if(y.fnName==="spawn_agents"){let M=(G.match(/\bStatus: done\b/g)||[]).length;if((G.match(/\bStatus: truncated\b/g)||[]).length>0&&M===0){if(Fn++,Fn===R0){I(`${p.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Fn}\xD7 in a row${p.reset}`);let j={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Fn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};P.push(j),T.push(j)}else if(Fn>=C0){console.log(`${p.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Fn}\xD7 \u2014 aborting stuck swarm${p.reset}`),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne,{suppressHint:!0}),Ce(P);return}}else M>0&&(Fn=0)}}if(Ma&&fo&&!($e&&Ae==="verify")){let w=await $u(D),y=await ya(D),G={role:"user",content:CR(D,w,y)};P.push(G),T.push(G),I(`${p.cyan} \u21B3 Post-edit verify prompt injected (${w.length} checks, ${y.length} tests)${p.reset}`)}{let y=Ve.reduce((G,B)=>G+(typeof B.content=="string"?B.content.length:0),0);if(y>2e5){let G=Ve.map((B,C)=>({i:C,len:typeof B.content=="string"?B.content.length:0})).sort((B,C)=>C.len-B.len);for(let{i:B,len:C}of G){if(y<=2e5)break;let Q=y-2e5,q=Math.max(C-Q,500);q<C&&typeof Ve[B].content=="string"&&(Ve[B]={...Ve[B],content:Ve[B].content.substring(0,q)+`
1429
- ...(truncated ${C-q} chars \u2014 per-message budget)`},y-=C-q)}}}for(let w of Ve)P.push(w),T.push(w);let I0=Tr&&we.some((w,y)=>{if(!w||!["write_file","edit_file","patch_file"].includes(w.fnName))return!1;let G=w.args?.path||w.args?.file_path;return ST(G)&&typeof Ve[y]?.content=="string"&&!Ve[y].content.startsWith("ERROR")&&!Ve[y].content.startsWith("BLOCKED:")});if(_s()&&!s.skillLoop&&Ra&&I0){I(`${p.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${p.reset}`),Le(H,se,D,me,Ne),Ce(P);break e}if(ta(P,T),!at)for(let w=0;w<Ve.length;w++){if(!we[w]||we[w].fnName!=="ssh_exec")continue;let y=Ve[w];if(!y||typeof y.content!="string")continue;let G=Zc(y.content);if(G){at=!0,kt=G.slice(0,120),Bt=0,Ut=!1,Zt=0,I(`${p.yellow} \u26A1 Root cause detected: ${kt} \u2014 fix phase (read budget: 3)${p.reset}`);let B={role:"user",content:`[SYSTEM] Root cause identified: ${kt}. Read only the file that needs fixing, then edit it. Do not read other files.`};P.push(B),T.push(B);break}}for(let w=0;w<Ve.length;w++){let y=we[w];if(!y)continue;let G=typeof Ve[w]?.content=="string"?Ve[w].content:"";if(y.fnName==="create_task"){let B=G.match(/Task #(\d+) created/),C=typeof y.args?.subject=="string"?y.args.subject:"";B&&C&&kr.set(B[1],C)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!G.startsWith("BLOCKED:")&&G.trim().length>0){let C=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),Q=C.split(/[._\-/]/).filter(q=>q.length>2);for(let[q,ce]of kr){if(xr.has(q))continue;let M=ce.toLowerCase().split(/\W+/).filter(j=>j.length>3);Q.filter(j=>M.some(K=>K.includes(j)||j.includes(K))).length>=1&&(xr.add(q),I(`${p.green} \u2714 Auto-matched task #${q} to ${C}: ${ce.slice(0,60)}${p.reset}`))}}}{let w=ft();if(Jt(T,w).percentage>=78){let{messages:G,tokensRemoved:B}=un(T,w);B>0&&(T=G,console.log(`${p.dim} [auto-compressed \u2014 ~${B} tokens freed, now ${Math.round(Jt(T,w).percentage)}%]${p.reset}`))}}if(_s()&&!s.skillLoop&&(we.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?Sn=0:(Sn===0&&(Ru=D.size),Sn++),Sn>=9&&H>=4&&D.size===Ru)){I(`${p.green} \u2713 Stagnation exit: ${Sn} read-only iterations, no new file changes${p.reset}`),process.stdout.isTTY&&process.stderr.write(`${p.yellow} \u26A0 Stagnation detected: ${Sn} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${p.reset}
1430
- `),c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne),Ce(P);break e}let Bu=vR();if(Bu){let w={role:"user",content:`[User note mid-run]: ${Bu}`};P.push(w),T.push(w),console.log(`${p.cyan} \u270E Context added${p.reset}`)}}if(Ge>=St){if(c&&(c.stop(),c=null),u(null),Le(H,se,D,me,Ne),Ce(P),cr(P),$e&&Ae==="plan"){let tt=[...P].reverse().find(Ze=>Ze.role==="assistant"),nt=typeof tt?.content=="string"?tt.content:"",En=await fr("implement",nt);if(En){P.push(En),T=[{role:"system",content:await yu()},...P],St=gs("implement"),I(`${p.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${p.reset}`);continue e}}else if($e&&Ae==="verify"){I(`${p.yellow} \u26A0 Verify budget exhausted \u2014 completing session${p.reset}`);break e}let{getActiveProviderName:be}=ut();if(be()==="ollama"&&Ea<Pu){if(D.size===0&&!Ta){console.log(`${p.yellow} \u26A0 Max iterations reached with no progress. Stopping.${p.reset}`);break e}Ea++,St=20,console.log(`${p.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Ea}/${Pu}) \u2500\u2500${p.reset}`);continue e}if(console.log(`
1431
- ${p.yellow}\u26A0 Max iterations reached.${p.reset}`),await $y(" Continue for 20 more turns?")){St=20;continue e}console.log(`${p.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${p.reset}`)}break e}await Nu()}Iy.exports={processInput:zR,clearConversation:jR,getConversationLength:qR,getConversationMessages:FR,setConversationMessages:BR,setAbortSignalGetter:rR,setMaxIterations:oR,invalidateSystemPromptCache:cu,clearToolFilterCache:hR,getCachedFilteredTools:Ey,buildSystemPrompt:yu,splitSystemPrompt:IR,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:gu,getProjectContextHash:Ty,_inferVerificationCommands:$u,_inferRelevantTests:ya,_inferSymbolTargets:Ny,_buildSymbolHintBlock:My,buildUserContent:Sy,_detectImageURLs:_y,_downloadImageURL:ky,_grabClipboardImage:xy,detectFrustration:vy,detectAndTruncateLoop:ou,injectMidRunNote:SR,resetSessionTracking:Py}});var ut=V((hA,Fy)=>{var{OllamaProvider:KR}=Xu(),{OpenAIProvider:XR}=Qu(),{AnthropicProvider:VR}=sd(),{GeminiProvider:JR}=ad(),{LocalProvider:ZR}=ud(),{checkBudget:QR}=Gr(),ku={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"}},bu=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Dy={};for(let[t,e]of Object.entries(ku))for(let s of Object.values(e))Dy[s]=t;function _u(t,e){let s=Dy[t];return s&&ku[s][e]||t}var lt={},xt=null,Ke=null,Sr=[];function Ht(){if(Object.keys(lt).length>0)return;mo("ollama",new KR),mo("openai",new XR),mo("anthropic",new VR),mo("gemini",new JR),mo("local",new ZR);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;lt[t]?(xt=t,Ke=e||lt[t].defaultModel):(xt="ollama",Ke="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(Sr=s.split(",").map(o=>o.trim()).filter(Boolean))}function mo(t,e){lt[t]=e}function e1(t){return Ht(),lt[t]||null}function xu(){return Ht(),lt[xt]||null}function t1(){return Ht(),xt}function n1(){return Ht(),Ke}function s1(){Ht();let t=xu();if(!t)return{id:Ke,name:Ke,provider:xt};let e=t.getModel(Ke);return e?{...e,provider:xt}:{id:Ke,name:Ke,provider:xt}}function Su(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(lt[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function o1(t){Ht();let{provider:e,model:s}=Su(t);if(e){let n=lt[e];return n&&(n.getModel(s)||e==="local"||e==="ollama")?(xt=e,Ke=s,wa(),!0):!1}let o=xu();if(o&&o.getModel(s))return Ke=s,wa(),!0;for(let[n,r]of Object.entries(lt))if(r.getModel(s))return xt=n,Ke=s,wa(),!0;return!1}function wa(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Sc();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=ln();t()}catch{}}function r1(){Ht();let t=new Set;for(let e of Object.values(lt))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function i1(){return Ht(),Object.entries(lt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===xt&&s.id===Ke}))}))}function a1(){Ht();let t=[];for(let[e,s]of Object.entries(lt)){let o=s.isConfigured();for(let n of Object.values(s.getModels()))t.push({spec:`${e}:${n.id}`,name:n.name,provider:e,configured:o})}return t}function l1(t){Sr=Array.isArray(t)?t:[]}function c1(){return[...Sr]}function jy(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 qy(t){let e=[xt,...Sr.filter(r=>r!==xt)],s,o=0,n=0;for(let r=0;r<e.length;r++){let i=e[r],a=lt[i];if(!a||!a.isConfigured())continue;n++;let l=QR(i);if(!l.allowed){o++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,c=u?_u(Ke,i):Ke;return u&&c!==Ke&&process.stderr.write(` [fallback: ${i}:${c}]
1432
- `),await t(a,i,c)}catch(u){if(s=u,!jy(u)||r>=e.length-1)throw u;if(i==="ollama"&&bu.length>0){let c=isFallback?_u(Ke,i):Ke;for(let d of bu)if(d!==c)try{return process.stderr.write(` [ollama fallback: ${d}]
1433
- `),await t(a,i,d)}catch(f){if(s=f,!jy(f))throw f}}continue}}throw o>0&&o===n?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):n===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function u1(t,e,s={}){Ht();let o=s.model,n=o?(()=>{let{model:i}=Su(o);return i||o})():void 0,r=n!==o?{...s,model:n}:s;return qy((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function d1(t,e,s={}){if(Ht(),s.provider){let o=lt[s.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let n={model:s.model||Ke,...s};try{return await o.chat(t,e,n)}catch(r){if(typeof o.stream=="function")try{return await o.stream(t,e,{...n,onToken:()=>{}})}catch{}throw r}}return qy(async(o,n,r)=>{try{return await o.chat(t,e,{model:r,...s})}catch(i){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function f1(){Ht();let t=[];for(let[e,s]of Object.entries(lt))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function h1(){for(let t of Object.keys(lt))delete lt[t];xt=null,Ke=null,Sr=[]}Fy.exports={registerProvider:mo,getProvider:e1,getActiveProvider:xu,getActiveProviderName:t1,getActiveModelId:n1,getActiveModel:s1,setActiveModel:o1,getModelNames:r1,parseModelSpec:Su,listProviders:i1,listAllModels:a1,callStream:u1,callChat:d1,getConfiguredProviders:f1,setFallbackChain:l1,getFallbackChain:c1,resolveModelForProvider:_u,MODEL_EQUIVALENTS:ku,OLLAMA_FALLBACK_MODELS:bu,_reset:h1}});var Di=V((mA,a0)=>{var{callStream:p1,getActiveProviderName:ba,getActiveModelId:By,getConfiguredProviders:m1,getProvider:Uy,getActiveProvider:Wy,parseModelSpec:Hy}=ut(),{parseToolArgs:Gy}=Zr(),{filterToolsForModel:g1,getModelTier:$a}=Po(),{getModelBriefing:y1}=Vi(),{trackUsage:Yy,estimateTokens:zy}=Gr(),{MultiProgress:w1,C:pA}=ot();function Ky(t){return!t||typeof t!="string"?0:typeof zy=="function"?zy(t):Math.ceil(t.length/4)}var Jy=15,$1=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),Xy=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Zy=8,b1=2,_a=new Map,Qy=600*1e3;function _1(t,e){let s=_a.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Qy?!1:(_a.set(t,{agentId:e,timestamp:Date.now()}),!0)}function vr(t){_a.delete(t)}function vu(){_a.clear()}function Eu(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 e0(t){let e=Eu(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function t0(t,e,s){let o;for(let n=0;n<=Xy;n++)try{return await p1(t,e,s)}catch(r){o=r;let i=Eu(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(n<Xy&&e0(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,n),15e3):Math.min(500*Math.pow(2,n),4e3);await new Promise(u=>setTimeout(u,l).unref());continue}throw r}throw o}var Vy=new Set(["ask_user","task_list"]);function n0(t){return t>=2?new Set([...Vy,"spawn_agents"]):Vy}var k1=new Set(["write_file","edit_file","patch_file"]),s0={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:""}},x1=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,S1=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function o0(t){return S1.test(t)?"full":x1.test(t)?"essential":t.length>300?"full":"standard"}function r0(t){let e=m1(),s=ba(),o=[...e].sort((n,r)=>(n.name===s?-1:1)-(r.name===s?-1:1));for(let n of o)for(let r of n.models)if($a(r.id,n.name)===t)return{provider:n.name,model:r.id};return null}var v1={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function ka(t){if(t.model){let{provider:n,model:r}=Hy(t.model),i=n?Uy(n):Wy(),a=n||ba();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=$a(r,a);return{provider:a,model:r,tier:l}}}let e=o0(t.task),s=v1[e];if(s){let{provider:n,model:r}=Hy(s),i=n?Uy(n):Wy(),a=n||ba();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=$a(r,a);return{provider:a,model:r,tier:l}}}let o=r0(e);if(o){let n=$a(o.model,o.provider);return{provider:o.provider,model:o.model,tier:n}}return{provider:null,model:null,tier:null}}async function i0(t,e={},s=0){let o=s===0?Jy:Zy,n=Math.min(t.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},l=new Set,u=new Map,c=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
1430
+ `),fo=w,ho=Date.now()),Ps=null,Gt=null}if(!xo.skipSummaries){let w=rw.filter((B,G)=>!(xe[G]&&xe[G].fnName==="ask_user"));for(let B of w)lu(B,pu,mu)||(console.log(B),pu=B,mu=Date.now());let y=xe.filter(B=>B&&B.fnName!=="ask_user").map(B=>B.fnName),Y=N0.record(0,y,Se,J);Y&&IR(Y)}for(let w of xe){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:"))&&(Fn++,Fn>=Du)){L(`${p.red} \u2716 Loop abort: ${Fn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe,{suppressHint:!0}),Oe(O);return}}let Ia=!1;for(let w=0;w<xe.length;w++){let y=xe[w];if(!y.canExecute)continue;let Y=et[w].content,B=Y.split(`
1431
+ `)[0],G=!B.startsWith("ERROR")&&!B.startsWith("CANCELLED")&&!B.startsWith("Command failed")&&!B.startsWith("EXIT");if(!G&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&B.includes("old_text not found")){let A=qt.get(y.args.path)||0;qt.set(y.args.path,A+1)}if(!G&&y.fnName==="bash"&&Sr.size>0){let A=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(A))for(let[R]of Sr)qt.has(R)||(qt.set(R,1),L(`${p.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${R.split("/").pop()}"${p.reset}`))}if(!G&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(B)){if(jn++,jn>=2){L(`${p.yellow} \u26A0 File-not-found streak: ${jn} consecutive misses \u2014 forcing search${p.reset}`);let A={role:"user",content:`[SYSTEM] ${jn} 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.`};O.push(A),T.push(A)}}else G&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(jn=0);if(G&&y.fnName==="write_file"&&y.args?.path){let A=y.args.path.split("/").pop(),U=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(A)&&!U){L(`${p.yellow} \u26A0 Temp file: "${A}" \u2014 delete with bash rm when done to keep the workspace clean${p.reset}`);let W={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.`};O.push(W),T.push(W)}}if(G&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){qt.delete(y.args.path),J.add(y.args.path);for(let R of Es)!R.done&&y.args.path.endsWith(R.file.split("/").pop())&&(R.done=!0,L(`${p.green} \u2713 TODO done: ${R.file}${p.reset}`));let A=ws(P0,y.args.path),U=y.args.path.split("/").slice(-2).join("/");if(A===M0){L(`${p.yellow} \u26A0 Loop warning: "${U}" edited ${A}\xD7 \u2014 possible edit loop${p.reset}`);let R={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${A}\xD7. One more edit max, then move on.`};O.push(R),T.push(R)}else if(A>=L0){L(`${p.red} \u2716 Loop abort: "${U}" edited ${A}\xD7 \u2014 aborting to prevent runaway loop${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe,{suppressHint:!0}),Oe(O);return}ye&&Te==="verify"||(yo=!0,wo=0,Ia=!0)}if(G&&y.canExecute&&ye&&(Dn=0),G&&y.canExecute&&!(ye&&Te==="plan")){let A=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){Ut=0,Wt=!1,en=0,Ht++;let I=y.args?.path||y.args?.file_path;I&&(y.fnName==="write_file"?($s.add(I),gn.delete(I),En.delete(I),Ts.delete(I)):($s.delete(I),iu(gn,I,1),En.delete(I),Ts.add(I)))}else if(A.includes(y.fnName)){if(Ut++,Wt&&en++,ye&&Te==="implement"&&y.fnName==="read_file"){let I=y.args?.path||y.args?.file_path||"";if(I&&$s.has(I)){let be={role:"user",content:`[SYSTEM] You just created and re-read "${I}". Do NOT analyze further. Apply the requested refactor now with edit_file.`};O.push(be),T.push(be),L(`${p.yellow} \u26A0 Fresh-write nudge: ${I} \u2014 refactor directly after re-read${p.reset}`)}}if(ye&&Te==="implement"&&y.fnName==="read_file"&&Es.length>0){let I=y.args?.path||y.args?.file_path||"",be=Es.find(Ee=>!Ee.done&&I.endsWith(Ee.file.split("/").pop()));if(be){let Ee={role:"user",content:`[TODO OBSERVER] You already analyzed "${be.file}" in the plan phase. Action: ${be.action}
1432
+ Do NOT re-read \u2014 apply the edit directly with edit_file.`};O.push(Ee),T.push(Ee),L(`${p.yellow} \u26A0 TODO nudge: ${be.file} \u2014 already analyzed, edit directly${p.reset}`)}}ye&&Te==="implement"&&yo&&wo<1&&(wo++,Ia=!0)}ye&&Te==="verify"&&mo++,G&&g1(y)&&(yo=!1,wo=0);let R=o.postEditCap,W=ye&&Te==="implement"?Math.min(qu,10):qu,ue=ct?8:Ar?Ht>0?4:6:Bt?Ht>0?6:10:Ht>0?R:W,$e=6,te=!ye&&Wt&&(ct&&en>=$e||Bt&&Ht>=3&&en>=$e||en>=$e);if(fr<2&&!Wt&&Ut>=3&&J.size===0){let I=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,be=Date.now()-Pe,Ee=fr===0?.4:.65;if(I>0&&be>I*Ee){fr++;let Ue=Math.round(be/6e4),Xe=Math.round(be/I*100);L(`${p.yellow} \u26A0 Time nudge #${fr}: ${Ue}m elapsed (${Xe}%), ${Ut} reads, 0 edits${p.reset}`);let Lt={role:"user",content:fr===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.`};O.push(Lt),T.push(Lt)}}if(te&&A.includes(y.fnName)){let I=ct?`root cause already identified (${kt})`:en>=$e?`${Ut} consecutive reads without an edit`:`${Ht} file edit(s) already made`;L(`${p.red} \u2716 Blocked read-only tool: cap fired, ${I}${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:ct?`BLOCKED: root cause already identified (${kt}). Use edit_file to fix the issue \u2014 do not read more files.`:Bt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":en>=$e?`BLOCKED: You have read ${Ut} 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: ${Ht} 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(Ut>=ue&&!Wt){if(Wt=!0,Ar&&(Oa=!0),L(`${p.yellow} \u26A0 Investigation cap: ${Ut} read-only calls without an edit \u2014 forcing implementation${p.reset}`),ye&&Te==="plan"){let Ee=[...T].reverse().find(Lt=>Lt.role==="assistant"),Ue=typeof Ee?.content=="string"?Ee.content:"",Xe=await pr("implement",Ue);Xe&&(O.push(Xe),T.push(Xe),ze=0,vt=ys("implement"))}let I;ct?I=`[SYSTEM] Root cause was already identified (${kt}). Edit the file now \u2014 do not read more files.`:Ar?I="[SYSTEM] You have enough evidence to write the requested summary/document now. Use write_file or edit_file to produce the deliverable, and stop reading more files unless a required section is still unsupported.":Nt?I="[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.":I="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let be={role:"user",content:I};O.push(be),T.push(be)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let A=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),U=ws(ju,A);if(U===I0){L(`${p.yellow} \u26A0 Loop warning: same bash command run ${U}\xD7 \u2014 possible debug loop${p.reset}`);let R={role:"user",content:`[SYSTEM WARNING] Same bash command ${U}\xD7. Debug loop detected \u2014 try a different approach.`};O.push(R),T.push(R)}else if(U>=j0){L(`${p.red} \u2716 Loop abort: same bash command run ${U}\xD7 \u2014 aborting runaway debug loop${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe,{suppressHint:!0}),Oe(O);return}}if(y.fnName==="ssh_exec"){Ft++;{let R=(et[w]?.content??"").split(`
1433
+ `).map(W=>W.trim()).find(W=>W.length>0&&!W.startsWith("**")&&(W.startsWith("EXIT")||/^[\w./-]+:\s/.test(W)||W.startsWith("bash:")||W.startsWith("sh:")))??"";if(R){if(R===pa?_s++:(pa=R,_s=1),_s===3&&!Nt){L(`${p.yellow} \u26A0 SSH repeated-error: "${R.slice(0,60)}" returned ${_s}\xD7 \u2014 nudging to change approach${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] The last ${_s} SSH commands all failed with the same error: "${R}". 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).`};O.push(W),T.push(W)}}else pa="",_s=0}if(Ft>=ew){L(`${p.red} \u2716 SSH storm abort: ${Ft} consecutive ssh_exec calls \u2014 aborting${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe,{suppressHint:!0}),Oe(O);return}else if(Ft===bo){{let R=ht(),{messages:W}=hn(T,R);T=W}Nt=!0,sa++,L(`${p.yellow} \u26A0 SSH storm warning (#${sa}): ${Ft} consecutive ssh_exec calls \u2014 blocking further SSH${p.reset}`);let U={role:"user",content:ct?`[SYSTEM WARNING] ${Ft} consecutive SSH calls. Root cause identified (${kt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Ft} 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.`};O.push(U),T.push(U)}}else y.canExecute&&(Ft=0);if(y.fnName==="bash"&&y.canExecute){let R=(et[w]?.content??"").split(`
1434
+ `).map(W=>W.trim()).find(W=>W.length>0&&(W.startsWith("EXIT")||/^[\w./-]+:\s/.test(W)||W.startsWith("bash:")||W.startsWith("sh:")))??"";if(R){if(R===ma?xs++:(ma=R,xs=1),xs===3){L(`${p.yellow} \u26A0 Bash repeated-error: "${R.slice(0,60)}" returned ${xs}\xD7 \u2014 nudging to change approach${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] The last ${xs} bash commands all failed with the same error: "${R}". 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).`};O.push(W),T.push(W)}}else ma="",xs=0}if(y.fnName==="bash"&&y.canExecute&&!au&&y.args?.command){let A=et[w]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!A.startsWith("EXIT")&&!A.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(A)||A.includes("files changed")||A.includes("file changed")||A.includes("insertions(+)")||A.includes("create mode"))){au=!0,hr=0,L(`${p.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${p.reset}`);let W={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."};O.push(W),T.push(W)}}if(au&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(hr++,hr>2)){L(`${p.yellow} \u26A0 Post-commit git verification blocked (call ${hr})${p.reset}`);let U={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(hr-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};O.push(U),T.push(U)}if(G&&y.fnName==="grep"&&Y&&!Y.startsWith("(no matches)")){let A=Y.split(`
1435
+ `);for(let U of A){let R=U.indexOf(":");if(R>0){let W=U.substring(0,R);W.startsWith("/")&&!W.includes(" ")&&xr.add(W)}else U.startsWith("/")&&!U.includes(" ")&&xr.add(U.trim())}}{let A=["grep","search_files","glob","glob_files"].includes(y.fnName);if(A&&G&&Y&&(Y.startsWith("(no matches)")||Y.trim()===""||/^No matches found/.test(Y.trim())||/^\(0 results\)/.test(Y.trim()))){if(Ea++,Ea===3){L(`${p.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${p.reset}`);let R={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."};O.push(R),T.push(R)}}else A&&G&&Y&&Y.trim().length>0&&(Ea=0)}if(G&&y.fnName==="grep"&&y.args&&y.args.pattern){let A=`${y.args.pattern}|${y.args.path||""}`,U=ws(D0,A);if(U===q0){L(`${p.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${U}\xD7 \u2014 possible search loop${p.reset}`);let R={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${U}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};O.push(R),T.push(R)}else if(U>=F0){L(`${p.red} \u2716 Loop abort: grep pattern run ${U}\xD7 \u2014 aborting runaway search loop${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe,{suppressHint:!0}),Oe(O);return}if(y.args.path){let R=ws(Ta,y.args.path),W=pn(As,y.args.path)>=1;if(R===(W?1:B0)){let $e=y.args.path.split("/").slice(-2).join("/");L(`${p.yellow} \u26A0 Loop warning: "${$e}" grepped ${R}\xD7 with different patterns \u2014 context flood risk${p.reset}`);let te={role:"user",content:W?`[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 ${R}\xD7 \u2014 use the search results already in context instead of searching again.`};O.push(te),T.push(te)}}}if(G&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(Y&&!Y.startsWith("(no matches)")){let W=Y.split(`
1436
+ `);for(let ue of W)(ue.startsWith("/")&&!ue.includes(" ")||!ue.includes(":")&&!ue.startsWith("["))&&kr.add(ue.trim())}let A=y.args.pattern||y.args.query||y.args.path||"",U=ws(U0,A);if(U===W0){L(`${p.yellow} \u26A0 Loop warning: glob pattern "${A.slice(0,40)}" run ${U}\xD7 \u2014 possible search loop${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${U}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};O.push(W),T.push(W)}else if(U>=H0){L(`${p.red} \u2716 Loop abort: glob pattern run ${U}\xD7 \u2014 aborting runaway search loop${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe,{suppressHint:!0}),Oe(O);return}let R=A.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(W=>W.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(W));for(let W of R){let ue=W.toLowerCase();la.has(ue)||la.set(ue,new Set);let $e=la.get(ue);if($e.add(A),$e.size===G0){L(`${p.red} \u2716 Glob core-term block: ${$e.size} different patterns all searching for "${ue}" \u2014 search loop${p.reset}`);let te={role:"user",content:`[SYSTEM WARNING] You have searched for "${ue}" using ${$e.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.`};O.push(te),T.push(te)}else if($e.size===Y0){L(`${p.yellow} \u26A0 Glob core-term warning: ${$e.size} different patterns searching for "${ue}"${p.reset}`);let te={role:"user",content:`[SYSTEM WARNING] ${$e.size} different glob patterns all target "${ue}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};O.push(te),T.push(te)}}}let z=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),j=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(z)||/\/(health|status|ping|ready|alive)\b/.test(z);if(G&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&j&&Y.includes('"valid":true')){{let U=ht();if(Qt(T,U).percentage>=60){let{messages:W,tokensRemoved:ue}=hn(T,U);ue>0&&(T=W,console.log(`${p.dim} [pre-stop-compress \u2014 ~${ue} tokens freed before STOP injection, now ${Math.round(Qt(T,U).percentage)}%]${p.reset}`))}}let A={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.'};O.push(A),T.push(A),console.log(`${p.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${p.reset}`)}if(G&&(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)&&(Cs++,L(`${p.dim} [bash write detected: _bashModifiedFiles=${Cs}]${p.reset}`)),Y.startsWith("BLOCKED:")){if(Fn++,Fn>=Du){L(`${p.red} \u2716 Loop abort: ${Fn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe,{suppressHint:!0}),Oe(O);return}}else Fn=0;if(G)qn=0,Aa=!0;else if(qn++,qn===V0){L(`${p.yellow} \u26A0 Loop warning: ${qn} consecutive tool errors \u2014 possible stuck loop${p.reset}`);let A={role:"user",content:`[SYSTEM WARNING] ${qn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};O.push(A),T.push(A)}else if(qn>=J0){L(`${p.red} \u2716 Loop abort: ${qn} consecutive errors \u2014 aborting stuck loop${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe,{suppressHint:!0}),Oe(O);return}if(G&&y.fnName==="read_file"&&y.args&&y.args.path){Se.add(y.args.path),$s.delete(y.args.path),Ts.delete(y.args.path);let A=ws(As,y.args.path);{let ue=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,$e=y.args.line_start!=null?parseInt(y.args.line_end,10)||ue+350:350;En.has(y.args.path)||En.set(y.args.path,[]),En.get(y.args.path).push([ue,$e])}if(y._scrollWarn){let{sectionCount:ue,path:$e}=y._scrollWarn,te={role:"user",content:`[SYSTEM WARNING] "${$e}" \u2014 you have now read ${ue} 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.`};O.push(te),T.push(te),L(`${p.yellow} \u26A0 Scroll warning: "${$e.split("/").slice(-2).join("/")}" \u2014 ${ue} sections read \u2014 use grep instead${p.reset}`)}let U=y.args.path.split("/").slice(-2).join("/"),R=!y.args?.line_start&&!y.args?.line_end,W=ye&&Te==="plan";if(!W&&R&&A===z0){{let $e=ht();if(Qt(T,$e).percentage>=60){let{messages:I}=hn(T,$e);T=I}}L(`${p.yellow} \u26A0 Loop warning: "${U}" read unbounded ${A}\xD7 \u2014 use line_start/line_end${p.reset}`);let ue={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${A}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};O.push(ue),T.push(ue)}else if(!W&&R&&A>=K0){L(`${p.red} \u2716 Loop abort: "${U}" read unbounded ${A}\xD7 \u2014 aborting runaway read loop${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe,{suppressHint:!0}),Oe(O);return}}if(y.fnName==="spawn_agents"){let A=(Y.match(/\bStatus: done\b/g)||[]).length;if((Y.match(/\bStatus: truncated\b/g)||[]).length>0&&A===0){if(Bn++,Bn===Z0){L(`${p.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Bn}\xD7 in a row${p.reset}`);let R={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Bn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};O.push(R),T.push(R)}else if(Bn>=Q0){console.log(`${p.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Bn}\xD7 \u2014 aborting stuck swarm${p.reset}`),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe,{suppressHint:!0}),Oe(O);return}}else A>0&&(Bn=0)}}if(Ia&&yo&&!(ye&&Te==="verify")){let w=await Tu(J),y=await ba(J),Y={role:"user",content:m1(J,w,y)};O.push(Y),T.push(Y),L(`${p.cyan} \u21B3 Post-edit verify prompt injected (${w.length} checks, ${y.length} tests)${p.reset}`)}{let y=et.reduce((Y,B)=>Y+(typeof B.content=="string"?B.content.length:0),0);if(y>2e5){let Y=et.map((B,G)=>({i:G,len:typeof B.content=="string"?B.content.length:0})).sort((B,G)=>G.len-B.len);for(let{i:B,len:G}of Y){if(y<=2e5)break;let z=y-2e5,j=Math.max(G-z,500);j<G&&typeof et[B].content=="string"&&(et[B]={...et[B],content:et[B].content.substring(0,j)+`
1437
+ ...(truncated ${G-j} chars \u2014 per-message budget)`},y-=G-j)}}}for(let w of et)O.push(w),T.push(w);let iw=Ar&&xe.some((w,y)=>{if(!w||!["write_file","edit_file","patch_file"].includes(w.fnName))return!1;let Y=w.args?.path||w.args?.file_path;return lR(Y)&&typeof et[y]?.content=="string"&&!et[y].content.startsWith("ERROR")&&!et[y].content.startsWith("BLOCKED:")});if(ks()&&!n.skillLoop&&Oa&&iw){L(`${p.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${p.reset}`),Ie(H,se,J,Se,Pe),Oe(O);break e}if(oa(O,T),!ct)for(let w=0;w<et.length;w++){if(!xe[w]||xe[w].fnName!=="ssh_exec")continue;let y=et[w];if(!y||typeof y.content!="string")continue;let Y=ru(y.content);if(Y){ct=!0,kt=Y.slice(0,120),Ut=0,Wt=!1,en=0,L(`${p.yellow} \u26A1 Root cause detected: ${kt} \u2014 fix phase (read budget: 3)${p.reset}`);let B={role:"user",content:`[SYSTEM] Root cause identified: ${kt}. Read only the file that needs fixing, then edit it. Do not read other files.`};O.push(B),T.push(B);break}}for(let w=0;w<et.length;w++){let y=xe[w];if(!y)continue;let Y=typeof et[w]?.content=="string"?et[w].content:"";if(y.fnName==="create_task"){let B=Y.match(/Task #(\d+) created/),G=typeof y.args?.subject=="string"?y.args.subject:"";B&&G&&vr.set(B[1],G)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!Y.startsWith("BLOCKED:")&&Y.trim().length>0){let G=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),z=G.split(/[._\-/]/).filter(j=>j.length>2);for(let[j,ae]of vr){if(Er.has(j))continue;let A=ae.toLowerCase().split(/\W+/).filter(R=>R.length>3);z.filter(R=>A.some(W=>W.includes(R)||R.includes(W))).length>=1&&(Er.add(j),L(`${p.green} \u2714 Auto-matched task #${j} to ${G}: ${ae.slice(0,60)}${p.reset}`))}}}{let w=ht();if(Qt(T,w).percentage>=78){let{messages:Y,tokensRemoved:B}=hn(T,w);B>0&&(T=Y,console.log(`${p.dim} [auto-compressed \u2014 ~${B} tokens freed, now ${Math.round(Qt(T,w).percentage)}%]${p.reset}`))}}if(ks()&&!n.skillLoop&&(xe.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?Rs=0:(Rs===0&&(Iu=J.size),Rs++),Rs>=9&&H>=4&&J.size===Iu)){L(`${p.green} \u2713 Stagnation exit: ${Rs} read-only iterations, no new file changes${p.reset}`),process.stdout.isTTY&&process.stderr.write(`${p.yellow} \u26A0 Stagnation detected: ${Rs} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${p.reset}
1438
+ `),c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe),Oe(O);break e}let Xu=d1();if(Xu){let w={role:"user",content:`[User note mid-run]: ${Xu}`};O.push(w),T.push(w),console.log(`${p.cyan} \u270E Context added${p.reset}`)}}if(ze>=vt){if(c&&(c.stop(),c=null),u(null),Ie(H,se,J,Se,Pe),Oe(O),dr(O),ye&&Te==="plan"){let Ke=[...O].reverse().find(st=>st.role==="assistant"),rt=typeof Ke?.content=="string"?Ke.content:"",Rn=await pr("implement",rt);if(Rn){O.push(Rn),T=[{role:"system",content:await vu()},...O],vt=ys("implement"),L(`${p.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${p.reset}`);continue e}}else if(ye&&Te==="verify"){L(`${p.yellow} \u26A0 Verify budget exhausted \u2014 completing session${p.reset}`);break e}let{getActiveProviderName:_e}=dt();if(_e()==="ollama"&&Ca<Uu){if(J.size===0&&!Aa){console.log(`${p.yellow} \u26A0 Max iterations reached with no progress. Stopping.${p.reset}`);break e}Ca++,vt=20,console.log(`${p.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Ca}/${Uu}) \u2500\u2500${p.reset}`);continue e}if(console.log(`
1439
+ ${p.yellow}\u26A0 Max iterations reached.${p.reset}`),await Wy(" Continue for 20 more turns?")){vt=20;continue e}console.log(`${p.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${p.reset}`)}break e}await Fu()}i0.exports={processInput:P1,clearConversation:k1,getConversationLength:v1,getConversationMessages:E1,setConversationMessages:T1,setAbortSignalGetter:WR,setMaxIterations:UR,invalidateSystemPromptCache:gu,clearToolFilterCache:JR,getCachedFilteredTools:Vy,buildSystemPrompt:vu,splitSystemPrompt:x1,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Su,getProjectContextHash:Jy,_inferVerificationCommands:Tu,_inferRelevantTests:ba,_inferSymbolTargets:n0,_buildSymbolHintBlock:s0,buildUserContent:Ky,_detectImageURLs:Yy,_downloadImageURL:Gy,_grabClipboardImage:zy,detectFrustration:Xy,detectAndTruncateLoop:du,injectMidRunNote:u1,resetSessionTracking:o0}});var dt=Z((tO,u0)=>{var{OllamaProvider:M1}=sd(),{OpenAIProvider:L1}=ad(),{AnthropicProvider:I1}=dd(),{GeminiProvider:j1}=md(),{LocalProvider:D1}=wd(),{checkBudget:q1}=zr(),Au={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"}},Ru=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),l0={};for(let[t,e]of Object.entries(Au))for(let n of Object.values(e))l0[n]=t;function Cu(t,e){let n=l0[t];return n&&Au[n][e]||t}var ut={},St=null,Ze=null,Tr=[];function Yt(){if(Object.keys(ut).length>0)return;$o("ollama",new M1),$o("openai",new L1),$o("anthropic",new I1),$o("gemini",new j1),$o("local",new D1);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;ut[t]?(St=t,Ze=e||ut[t].defaultModel):(St="ollama",Ze="kimi-k2.5");let n=process.env.FALLBACK_CHAIN;n&&(Tr=n.split(",").map(o=>o.trim()).filter(Boolean))}function $o(t,e){ut[t]=e}function F1(t){return Yt(),ut[t]||null}function Ou(){return Yt(),ut[St]||null}function B1(){return Yt(),St}function U1(){return Yt(),Ze}function W1(){Yt();let t=Ou();if(!t)return{id:Ze,name:Ze,provider:St};let e=t.getModel(Ze);return e?{...e,provider:St}:{id:Ze,name:Ze,provider:St}}function Nu(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(ut[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function H1(t){Yt();let{provider:e,model:n}=Nu(t);if(e){let s=ut[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(St=e,Ze=n,_a(),!0):!1}let o=Ou();if(o&&o.getModel(n))return Ze=n,_a(),!0;for(let[s,r]of Object.entries(ut))if(r.getModel(n))return St=s,Ze=n,_a(),!0;return!1}function _a(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Oc();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=dn();t()}catch{}}function Y1(){Yt();let t=new Set;for(let e of Object.values(ut))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function G1(){return Yt(),Object.entries(ut).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===St&&n.id===Ze}))}))}function z1(){Yt();let t=[];for(let[e,n]of Object.entries(ut)){let o=n.isConfigured();for(let s of Object.values(n.getModels()))t.push({spec:`${e}:${s.id}`,name:s.name,provider:e,configured:o})}return t}function K1(t){Tr=Array.isArray(t)?t:[]}function X1(){return[...Tr]}function a0(t){let e=t.message||"",n=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ECONNRESET"||n==="EHOSTUNREACH"||n==="ENETUNREACH"||n==="EPIPE"||n==="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 c0(t){let e=[St,...Tr.filter(r=>r!==St)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],a=ut[i];if(!a||!a.isConfigured())continue;s++;let l=q1(i);if(!l.allowed){o++,n=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,c=u?Cu(Ze,i):Ze;return u&&c!==Ze&&process.stderr.write(` [fallback: ${i}:${c}]
1440
+ `),await t(a,i,c)}catch(u){if(n=u,!a0(u)||r>=e.length-1)throw u;if(i==="ollama"&&Ru.length>0){let c=isFallback?Cu(Ze,i):Ze;for(let d of Ru)if(d!==c)try{return process.stderr.write(` [ollama fallback: ${d}]
1441
+ `),await t(a,i,d)}catch(f){if(n=f,!a0(f))throw f}}continue}}throw o>0&&o===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):s===0?new Error("No configured provider available"):n||new Error("No configured provider available")}async function V1(t,e,n={}){Yt();let o=n.model,s=o?(()=>{let{model:i}=Nu(o);return i||o})():void 0,r=s!==o?{...n,model:s}:n;return c0((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function J1(t,e,n={}){if(Yt(),n.provider){let o=ut[n.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let s={model:n.model||Ze,...n};try{return await o.chat(t,e,s)}catch(r){if(typeof o.stream=="function")try{return await o.stream(t,e,{...s,onToken:()=>{}})}catch{}throw r}}return c0(async(o,s,r)=>{try{return await o.chat(t,e,{model:r,...n})}catch(i){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function Z1(){Yt();let t=[];for(let[e,n]of Object.entries(ut))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function Q1(){for(let t of Object.keys(ut))delete ut[t];St=null,Ze=null,Tr=[]}u0.exports={registerProvider:$o,getProvider:F1,getActiveProvider:Ou,getActiveProviderName:B1,getActiveModelId:U1,getActiveModel:W1,setActiveModel:H1,getModelNames:Y1,parseModelSpec:Nu,listProviders:G1,listAllModels:z1,callStream:V1,callChat:J1,getConfiguredProviders:Z1,setFallbackChain:K1,getFallbackChain:X1,resolveModelForProvider:Cu,MODEL_EQUIVALENTS:Au,OLLAMA_FALLBACK_MODELS:Ru,_reset:Q1}});var Bi=Z((sO,O0)=>{var{callStream:eC,getActiveProviderName:ka,getActiveModelId:d0,getConfiguredProviders:tC,getProvider:f0,getActiveProvider:h0,parseModelSpec:p0}=dt(),{parseToolArgs:m0}=ei(),{filterToolsForModel:nC,getModelTier:xa}=Io(),{getModelBriefing:sC}=Qi(),{trackUsage:g0,estimateTokens:y0}=zr(),{MultiProgress:oC,C:nO}=it();function w0(t){return!t||typeof t!="string"?0:typeof y0=="function"?y0(t):Math.ceil(t.length/4)}var _0=15,rC=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),$0=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),x0=8,iC=2,Sa=new Map,k0=600*1e3;function aC(t,e){let n=Sa.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<k0?!1:(Sa.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Rr(t){Sa.delete(t)}function Pu(){Sa.clear()}function Mu(t){let e=(t.message||"").toLowerCase(),n=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":n==="ECONNRESET"||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function S0(t){let e=Mu(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function v0(t,e,n){let o;for(let s=0;s<=$0;s++)try{return await eC(t,e,n)}catch(r){o=r;let i=Mu(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(s<$0&&S0(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(u=>setTimeout(u,l).unref());continue}throw r}throw o}var b0=new Set(["ask_user","task_list"]);function E0(t){return t>=2?new Set([...b0,"spawn_agents"]):b0}var lC=new Set(["write_file","edit_file","patch_file"]),T0={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:""}},cC=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,uC=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function R0(t){return uC.test(t)?"full":cC.test(t)?"essential":t.length>300?"full":"standard"}function C0(t){let e=tC(),n=ka(),o=[...e].sort((s,r)=>(s.name===n?-1:1)-(r.name===n?-1:1));for(let s of o)for(let r of s.models)if(xa(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var dC={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function va(t){if(t.model){let{provider:s,model:r}=p0(t.model),i=s?f0(s):h0(),a=s||ka();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=xa(r,a);return{provider:a,model:r,tier:l}}}let e=R0(t.task),n=dC[e];if(n){let{provider:s,model:r}=p0(n),i=s?f0(s):h0(),a=s||ka();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=xa(r,a);return{provider:a,model:r,tier:l}}}let o=C0(e);if(o){let s=xa(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function A0(t,e={},n=0){let o=n===0?_0:x0,s=Math.min(t.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},l=new Set,u=new Map,c=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
1434
1442
 
1435
1443
  TASK: ${t.task}
1436
1444
  ${t.context?`
@@ -1456,19 +1464,19 @@ TOOL STRATEGY:
1456
1464
  ERROR RECOVERY:
1457
1465
  - If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
1458
1466
  - If bash fails: read the error, fix the root cause, then retry.
1459
- - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&s0[t.type],f=d&&d.systemSuffix?`
1467
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&T0[t.type],f=d&&d.systemSuffix?`
1460
1468
 
1461
- ${d.systemSuffix}`:"",h=ka(t),m=h.provider,g=h.model,$=h.tier,k=y1(g||By()),A=[{role:"system",content:(k?`## Model Briefing
1462
- ${k}
1469
+ ${d.systemSuffix}`:"",h=va(t),m=h.provider,g=h.model,$=h.tier,x=sC(g||d0()),N=[{role:"system",content:(x?`## Model Briefing
1470
+ ${x}
1463
1471
 
1464
1472
  ---
1465
1473
 
1466
- `:"")+c+f}];A.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:E,executeTool:S}=Ro(),N=n0(s),ee=g1(E.filter(ue=>!N.has(ue.function.name)),$);if(d&&d.allowedTools&&(ee=ee.filter(ue=>d.allowedTools.has(ue.function.name))),g&&!t._skipLog){let ue=$?` (${$})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${ue}]
1467
- `)}let re={};m&&(re.provider=m),g&&(re.model=g);let le=new Set;try{for(let oe=0;oe<n;oe++){let ae=await t0(A,ee,re);if(!ae||typeof ae!="object")throw new Error("Empty or invalid response from provider");{let Oe=m||ba(),Se=g||By();if(ae.usage){let _=ae.usage.prompt_tokens||0,L=ae.usage.completion_tokens||0;a.input+=_,a.output+=L,Yy(Oe,Se,_,L)}else{let _=ae.content||"",L=A.map(z=>typeof z.content=="string"?z.content:Array.isArray(z.content)?z.content.map(R=>typeof R=="string"?R:R.text||"").join(""):"").join(" "),W=Ky(L),te=Ky(_);a.input+=W,a.output+=te,a._estimated=!0,Yy(Oe,Se,W,te)}}let T=ae.content||"",U=ae.tool_calls,Z={role:"assistant",content:T||""};if(U&&U.length>0&&(Z.tool_calls=U),A.push(Z),!U||U.length===0){for(let Oe of l)vr(Oe);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let ye=new Set,ke=U.map(Oe=>{let Se=Oe.function.name,_=Gy(Oe.function.arguments),L=Oe.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!_)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${Se}`,tool_call_id:L});if(["edit_file","patch_file"].includes(Se)&&_.path){if(le.has(_.path)||ye.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:L});ye.add(_.path)}let W=null;if(k1.has(Se)&&_.path){let z=require("path"),R=z.isAbsolute(_.path)?_.path:z.resolve(process.cwd(),_.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let H=z.relative(process.cwd(),R);if(t._readOnlyFiles.some(D=>H===D||H.startsWith(D+"/")||R===D||R.startsWith(D+"/")))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:L})}if(l.has(R)||!_1(R,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:L});l.add(R),W=R}return i.push(Se),e.onUpdate&&e.onUpdate({type:"tool_call",tool:Se,agentId:r}),(Se==="spawn_agents"?Tu(_,s+1):S(Se,_,{autoConfirm:!0,silent:!0})).then(z=>{W&&(vr(W),l.delete(W));let R=String(z??"");return _&&_.path&&(["edit_file","patch_file","write_file"].includes(Se)&&R.startsWith("Edited:")?le.add(_.path):Se==="read_file"&&!R.startsWith("ERROR")&&le.delete(_.path)),{role:"tool",content:R.length>2e4?R.substring(0,2e4)+`
1468
- ...(truncated)`:R,tool_call_id:L}}).catch(z=>(W&&(vr(W),l.delete(W)),{role:"tool",content:`ERROR: ${z.message}`,tool_call_id:L}))}),De=await Promise.all(ke);if(A.push(...De),oe>=7&&A.length>12)try{let{compressMessage:Oe}=ln(),Se=A.length-6;for(let _=1;_<Se;_++)A[_]._subAgentCompressed||(A[_]={...Oe(A[_],"light"),_subAgentCompressed:!0})}catch{}for(let Oe=0;Oe<U.length;Oe++){let Se=U[Oe];if(Se.function.name==="bash_exec"){let _=Gy(Se.function.arguments);if((De[Oe]?.content||"").startsWith("ERROR")&&_&&_.command){let W=_.command.replace(/\s+/g," ").trim().slice(0,100);u.set(W,(u.get(W)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${oe+1}/${n}`)}for(let oe of l)vr(oe);let ue=[...u.entries()].filter(([,oe])=>oe>=3).sort((oe,ae)=>ae[1]-oe[1]).slice(0,3).map(([oe,ae])=>`"${oe}" (failed ${ae}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ue,result:A[A.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(ue){for(let oe of l)vr(oe);return{task:t.task,status:"failed",result:`Error: ${ue.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function Tu(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?$1:b1,o=e===0?Jy:Zy,n=(t.agents||[]).slice(0,s);if(n.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=n.map(c=>ka(c)),l=n.map((c,d)=>{let f=a[d],h=f.model?` [${f.model}]`:"",m=c.task.substring(0,i-h.length);return`${r}Agent ${d+1}${h}: ${m}${c.task.length>m.length?"...":""}`}),u=new w1(l);u.start();try{let c=n.map((g,$)=>{let k=a[$],v=Math.min(g.max_iterations||o,o),A=k.model?{...g,model:`${k.provider}:${k.model}`,_skipLog:!0,max_iterations:v}:{...g,_skipLog:!0,max_iterations:v};return i0(A,{onUpdate:()=>{}},e).then(E=>(u.update($,E.status==="failed"?"error":"done"),E)).catch(E=>(u.update($,"error"),{task:g.task,status:"failed",result:`Error: ${E.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(c);u.stop(),vu();let f=["Sub-agent results:",""],h=0,m=0;for(let g=0;g<d.length;g++){let $=d[g],k=$.status==="done"?"\u2713":$.status==="truncated"?"\u26A0":"\u2717",v=$.modelSpec?` [${$.modelSpec}]`:"";f.push(`${k} Agent ${g+1}${v}: ${$.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(""),h+=$.tokensUsed.input,m+=$.tokensUsed.output}return f.push(`Total sub-agent tokens: ${h} input + ${m} output`),f.join(`
1469
- `)}catch(c){return u.stop(),vu(),`ERROR: Sub-agent execution failed: ${c.message}`}}async function E1(t){let{createJob:e}=to(),s=(t.agents||[]).filter(i=>i.background),o=(t.agents||[]).filter(i=>!i.background),n=s.map(i=>{let a=ka(i),l=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(l)}),r=[];if(n.length>0&&r.push(`Background agents started: [${n.join(", ")}]
1470
- `+s.map((i,a)=>` ${n[a]}: ${i.task}`).join(`
1474
+ `:"")+c+f}];N.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:v,executeTool:S}=Ao(),P=E0(n),ne=nC(v.filter(de=>!P.has(de.function.name)),$);if(d&&d.allowedTools&&(ne=ne.filter(de=>d.allowedTools.has(de.function.name))),g&&!t._skipLog){let de=$?` (${$})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${de}]
1475
+ `)}let re={};m&&(re.provider=m),g&&(re.model=g);let ce=new Set;try{for(let oe=0;oe<s;oe++){let le=await v0(N,ne,re);if(!le||typeof le!="object")throw new Error("Empty or invalid response from provider");{let Ne=m||ka(),ve=g||d0();if(le.usage){let _=le.usage.prompt_tokens||0,M=le.usage.completion_tokens||0;a.input+=_,a.output+=M,g0(Ne,ve,_,M)}else{let _=le.content||"",M=N.map(K=>typeof K.content=="string"?K.content:Array.isArray(K.content)?K.content.map(C=>typeof C=="string"?C:C.text||"").join(""):"").join(" "),F=w0(M),ee=w0(_);a.input+=F,a.output+=ee,a._estimated=!0,g0(Ne,ve,F,ee)}}let T=le.content||"",q=le.tool_calls,Q={role:"assistant",content:T||""};if(q&&q.length>0&&(Q.tool_calls=q),N.push(Q),!q||q.length===0){for(let Ne of l)Rr(Ne);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let we=new Set,ke=q.map(Ne=>{let ve=Ne.function.name,_=m0(Ne.function.arguments),M=Ne.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!_)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${ve}`,tool_call_id:M});if(["edit_file","patch_file"].includes(ve)&&_.path){if(ce.has(_.path)||we.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:M});we.add(_.path)}let F=null;if(lC.has(ve)&&_.path){let K=require("path"),C=K.isAbsolute(_.path)?_.path:K.resolve(process.cwd(),_.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let he=K.relative(process.cwd(),C);if(t._readOnlyFiles.some(se=>he===se||he.startsWith(se+"/")||C===se||C.startsWith(se+"/")))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:M})}if(l.has(C)||!aC(C,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:M});l.add(C),F=C}return i.push(ve),e.onUpdate&&e.onUpdate({type:"tool_call",tool:ve,agentId:r}),(ve==="spawn_agents"?Lu(_,n+1):S(ve,_,{autoConfirm:!0,silent:!0})).then(K=>{F&&(Rr(F),l.delete(F));let C=String(K??"");return _&&_.path&&(["edit_file","patch_file","write_file"].includes(ve)&&C.startsWith("Edited:")?ce.add(_.path):ve==="read_file"&&!C.startsWith("ERROR")&&ce.delete(_.path)),{role:"tool",content:C.length>2e4?C.substring(0,2e4)+`
1476
+ ...(truncated)`:C,tool_call_id:M}}).catch(K=>(F&&(Rr(F),l.delete(F)),{role:"tool",content:`ERROR: ${K.message}`,tool_call_id:M}))}),qe=await Promise.all(ke);if(N.push(...qe),oe>=7&&N.length>12)try{let{compressMessage:Ne}=dn(),ve=N.length-6;for(let _=1;_<ve;_++)N[_]._subAgentCompressed||(N[_]={...Ne(N[_],"light"),_subAgentCompressed:!0})}catch{}for(let Ne=0;Ne<q.length;Ne++){let ve=q[Ne];if(ve.function.name==="bash_exec"){let _=m0(ve.function.arguments);if((qe[Ne]?.content||"").startsWith("ERROR")&&_&&_.command){let F=_.command.replace(/\s+/g," ").trim().slice(0,100);u.set(F,(u.get(F)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${oe+1}/${s}`)}for(let oe of l)Rr(oe);let de=[...u.entries()].filter(([,oe])=>oe>=3).sort((oe,le)=>le[1]-oe[1]).slice(0,3).map(([oe,le])=>`"${oe}" (failed ${le}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:de,result:N[N.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(de){for(let oe of l)Rr(oe);return{task:t.task,status:"failed",result:`Error: ${de.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function Lu(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let n=e===0?rC:iC,o=e===0?_0:x0,s=(t.agents||[]).slice(0,n);if(s.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=s.map(c=>va(c)),l=s.map((c,d)=>{let f=a[d],h=f.model?` [${f.model}]`:"",m=c.task.substring(0,i-h.length);return`${r}Agent ${d+1}${h}: ${m}${c.task.length>m.length?"...":""}`}),u=new oC(l);u.start();try{let c=s.map((g,$)=>{let x=a[$],E=Math.min(g.max_iterations||o,o),N=x.model?{...g,model:`${x.provider}:${x.model}`,_skipLog:!0,max_iterations:E}:{...g,_skipLog:!0,max_iterations:E};return A0(N,{onUpdate:()=>{}},e).then(v=>(u.update($,v.status==="failed"?"error":"done"),v)).catch(v=>(u.update($,"error"),{task:g.task,status:"failed",result:`Error: ${v.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(c);u.stop(),Pu();let f=["Sub-agent results:",""],h=0,m=0;for(let g=0;g<d.length;g++){let $=d[g],x=$.status==="done"?"\u2713":$.status==="truncated"?"\u26A0":"\u2717",E=$.modelSpec?` [${$.modelSpec}]`:"";f.push(`${x} Agent ${g+1}${E}: ${$.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(""),h+=$.tokensUsed.input,m+=$.tokensUsed.output}return f.push(`Total sub-agent tokens: ${h} input + ${m} output`),f.join(`
1477
+ `)}catch(c){return u.stop(),Pu(),`ERROR: Sub-agent execution failed: ${c.message}`}}async function fC(t){let{createJob:e}=io(),n=(t.agents||[]).filter(i=>i.background),o=(t.agents||[]).filter(i=>!i.background),s=n.map(i=>{let a=va(i),l=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(l)}),r=[];if(s.length>0&&r.push(`Background agents started: [${s.join(", ")}]
1478
+ `+n.map((i,a)=>` ${s[a]}: ${i.task}`).join(`
1471
1479
  `)+`
1472
- Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await Tu({agents:o});r.push(i)}return r.join(`
1480
+ Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await Lu({agents:o});r.push(i)}return r.join(`
1473
1481
 
1474
- `)||"No agents specified."}a0.exports={runSubAgent:i0,executeSpawnAgents:Tu,executeSpawnAgentsBackground:E1,clearAllLocks:vu,classifyTask:o0,pickModelForTier:r0,resolveSubAgentModel:ka,classifyError:Eu,isRetryableError:e0,callWithRetry:t0,getExcludedTools:n0,LOCK_TIMEOUT_MS:Qy,SUB_AGENT_TYPES:s0}});var{runSubAgent:T1}=Di();process.on("message",async({jobId:t,agentDef:e})=>{try{let s=await T1({...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)}});
1482
+ `)||"No agents specified."}O0.exports={runSubAgent:A0,executeSpawnAgents:Lu,executeSpawnAgentsBackground:fC,clearAllLocks:Pu,classifyTask:R0,pickModelForTier:C0,resolveSubAgentModel:va,classifyError:Mu,isRetryableError:S0,callWithRetry:v0,getExcludedTools:E0,LOCK_TIMEOUT_MS:k0,SUB_AGENT_TYPES:T0}});var{runSubAgent:hC}=Bi();process.on("message",async({jobId:t,agentDef:e})=>{try{let n=await hC({...e,_skipLog:!0},{onUpdate:()=>{}},0);process.send({type:"result",jobId:t,payload:n})}catch(n){process.send({type:"error",jobId:t,error:n.message})}finally{process.exit(0)}});