nex-code 0.5.16 → 0.5.17

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,155 +1,155 @@
1
- var Da=Object.defineProperty;var lw=Object.getOwnPropertyDescriptor;var cw=Object.getOwnPropertyNames;var uw=Object.prototype.hasOwnProperty;var dw=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),fw=(t,e)=>{for(var s in e)Da(t,s,{get:e[s],enumerable:!0})},hw=(t,e,s,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of cw(e))!uw.call(t,n)&&n!==s&&Da(t,n,{get:()=>e[n],enumerable:!(o=lw(e,n))||o.enumerable});return t};var pw=t=>hw(Da({},"__esModule",{value:!0}),t);var Ls=Z(($C,Qu)=>{async function mw(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 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,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`)}};Qu.exports={BaseProvider:qa,readStreamErrorBody:mw}});var Ds=Z((bC,td)=>{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,s={}){throw new Error("createStreamParser() not implemented")}},js=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")}},Ir=class extends js{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}}))}}},jr=class extends Is{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 Ir(e,s)}},Dr=class extends js{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}}})}}},Fa="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",qr=class extends Is{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 c=a.system,u=c.indexOf(Fa);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+Fa.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=c}return 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 Dr(e,s)}};function ed(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,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:ed(e.function?.arguments??e.arguments)}}))}}},Br=class extends Is{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:ed(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,s={}){return new Fr(e,s)}},gw=new jr,yw=new qr,ww=new Br;td.exports={ANTHROPIC_CACHE_BOUNDARY:Fa,WireProtocol:Is,StreamParser:js,OpenAICompatibleProtocol:jr,AnthropicProtocol:qr,OllamaChatProtocol:Br,OpenAIStreamParser:Ir,AnthropicStreamParser:Dr,OllamaStreamParser:Fr,openaiProtocol:gw,anthropicProtocol:yw,ollamaProtocol:ww}});var od=Z((_C,sd)=>{var Ur=require("axios"),$w=require("http"),bw=require("https"),{BaseProvider:_w,readStreamErrorBody:xw}=Ls(),{ollamaProtocol:Un}=Ds(),Wr=new $w.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Hr=new bw.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),nd={"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 _w{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||nd,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 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 Ur.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Wr,httpsAgent:Hr})).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=Un.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 Ur.post(`${this.baseUrl}${Un.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Wr,httpsAgent:Hr})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=c.response?.data?.error||c.message;throw new Error(`API Error${u}: ${d}`)}return Un.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||(()=>{}),c=Un.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),u;try{u=await Ur.post(`${this.baseUrl}${Un.getEndpoint()}`,c,{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 xw(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",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),u.data.on("error",m=>{if(o.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,h(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Un.normalizeResponse(e)}};sd.exports={OllamaProvider:Ba,OLLAMA_MODELS:nd}});var ld=Z((xC,ad)=>{var rd=require("axios"),{BaseProvider:kw,readStreamErrorBody:Sw}=Ls(),{openaiProtocol:Wn}=Ds(),id={"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 kw{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||id,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=Wn.buildRequestBody({model:n,messages:a,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),c;try{c=await rd.post(`${this.baseUrl}${Wn.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Wn.normalizeResponse(c.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),c=Wn.buildRequestBody({model:n,messages:l,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),u;try{u=await rd.post(`${this.baseUrl}${Wn.getEndpoint()}`,c,{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 Sw(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",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),u.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Wn.normalizeResponse(e)}};ad.exports={OpenAIProvider:Ua,OPENAI_MODELS:id}});var fd=Z((kC,dd)=>{var cd=require("axios"),{BaseProvider:vw,readStreamErrorBody:Ew}=Ls(),{anthropicProtocol:Cn}=Ds(),ud={"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}},Tw="2023-06-01",Wa=class extends vw{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||ud,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Tw}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 Cn.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:c}=this.formatMessages(e),u=this.formatTools(s),d=Cn.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await cd.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,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:c,system:u}=this.formatMessages(e),d=this.formatTools(s),f=Cn.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:u}}),h;try{h=await cd.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 Ew(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)}};dd.exports={AnthropicProvider:Wa,ANTHROPIC_MODELS:ud}});var gd=Z((SC,md)=>{var hd=require("axios"),{BaseProvider:Rw,readStreamErrorBody:Cw}=Ls(),{openaiProtocol:Hn}=Ds(),pd={"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 Rw{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||pd,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=Hn.buildRequestBody({model:n,messages:a,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),c;try{c=await hd.post(`${this.baseUrl}${Hn.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Hn.normalizeResponse(c.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),c=Hn.buildRequestBody({model:n,messages:l,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),u;try{u=await hd.post(`${this.baseUrl}${Hn.getEndpoint()}`,c,{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 Cw(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",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),u.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Hn.normalizeResponse(e)}};md.exports={GeminiProvider:Ha,GEMINI_MODELS:pd}});var $d=Z((vC,wd)=>{var Yr=require("axios"),{BaseProvider:Aw,readStreamErrorBody:Ow}=Ls(),{ollamaProtocol:Yn}=Ds(),yd="http://localhost:11434",Ya=class extends Aw{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||yd,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 Yr.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 Yr.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=Yn.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,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}]`:"",c=a.response?.data?.error||a.message;throw new Error(`API Error${l}: ${c}`)}return Yn.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=Yn.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,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(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=await Ow(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=Yn.createStreamParser(r);return new Promise((c,u)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:h}=l.feed(d.toString());f&&c(h)}),a.data.on("error",d=>{o.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{c(l.flush())})})}normalizeResponse(e){return Yn.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}};wd.exports={LocalProvider:Ya,DEFAULT_LOCAL_URL:yd}});var Kt=Z((EC,Ed)=>{"use strict";var bd="\x1B[0m",_d="\x1B[1m",qs="\x1B[2m";function X(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function Nw(){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 xd(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Pw(t){try{let s=require("fs").readFileSync(xd(),"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 Mw(t,e){try{let s=require("fs"),o=require("path"),n=xd(),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 Lw(){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=Pw(s);if(o!==null)return o;let n=Nw(),r=n!==null?n:!0;return Mw(s,r),r}var kd=Lw(),Sd={reset:bd,bold:_d,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)},vd={reset:bd,bold:_d,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)},Iw=kd?Sd:vd;Ed.exports={T:Iw,isDark:kd,DARK:Sd,LIGHT:vd}});var Gn=Z((TC,Rd)=>{"use strict";var Rt=require("fs"),Td=require("path");function jw(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Dw(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function qw(t,e){let s=Td.dirname(t),o=Td.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{Rt.existsSync(s)||Rt.mkdirSync(s,{recursive:!0,mode:448}),Rt.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Rt.renameSync(o,t)}catch(n){try{Rt.unlinkSync(o)}catch{}throw n}}function Fw(t,e,{timeout:s=5e3,retryMs:o=50}={}){let n=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=Rt.openSync(n,"wx"),Rt.writeSync(i,Buffer.from(String(process.pid))),Rt.closeSync(i),i=-1;try{return e()}finally{try{Rt.unlinkSync(n)}catch{}}}catch(a){if(i!==-1)try{Rt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=Rt.readFileSync(n,"utf-8").trim(),c=parseInt(l,10);if(!jw(c)){try{Rt.unlinkSync(n)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Rt.unlinkSync(n)}catch{}return e()}Dw(o)}}}Rd.exports={atomicWrite:qw,withFileLockSync:Fw}});var zr=Z((RC,Id)=>{var Fs=require("fs"),Ga=require("path"),{T:Cd}=Kt(),{atomicWrite:Bw,withFileLockSync:Uw}=Gn(),Ad={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 Ww(t,e,s,o,n=0){if(Gr.push({provider:t,model:e,input:s,output:o,cacheRead:n}),An[t]!==void 0){let r=Md(t);r.allowed||process.stderr.write(`${Cd.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${Cd.reset}
9
- `)}}function za(t,e){let s=Ad[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Od(t){let e=za(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Nd(){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:Od(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 Hw(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:o}=Nd();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 Yw(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function Gw(t,e,s,o){let n=za(t,e),r=(s*n.input+o*n.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function zw(){Gr=[]}function Kw(t,e){An[t]=e}function Xw(t){delete An[t]}function Vw(){return{...An}}function Pd(t){let e=0;for(let s of Gr)s.provider===t&&(e+=Od(s));return e}function Md(t){let e=Pd(t),s=An[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 Ld(){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 Jw(){let t=Ga.join(process.cwd(),".nex"),e=Ga.join(t,"config.json");Fs.existsSync(t)||Fs.mkdirSync(t,{recursive:!0}),Uw(e,()=>{let s={};if(Fs.existsSync(e))try{s=JSON.parse(Fs.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=An,Bw(e,JSON.stringify(s,null,2))})}function Zw(){An={}}Ld();Id.exports={PRICING:Ad,trackUsage:Ww,getSessionCosts:Nd,formatCosts:Hw,formatCostHint:Gw,resetCosts:zw,getPricing:za,setCostLimit:Kw,removeCostLimit:Xw,getCostLimits:Vw,getProviderSpend:Pd,checkBudget:Md,loadCostLimits:Ld,saveCostLimits:Jw,resetCostLimits:Zw,estimateTokens:Yw}});var Ka=Z((CC,Qw)=>{Qw.exports={name:"nex-code",version:"0.5.16",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((AC,Ud)=>{var{T:V}=Kt(),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})(),jd=["\u273D","\u2726","\u2727","\u2726"],Dd=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function qd(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 Fd(t,e,s){let o="";for(let n=0;n<Xa;n++)n===t?o+=`${s}${e}${V.reset}`:n===t-1||n===t+1?o+=`${V.dim}\xB7${V.reset}`:o+=`${V.dim}\xB7${V.reset}`;return o}function Bd(t){return`${V.dim}${Dd[t%Dd.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],s=qd(this.text),o=Fd(e,s.glyph,s.color),n=Bd(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${s.color}${s.accent.toUpperCase()}${V.reset}${n} ${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 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=Bs[this.frame%Bs.length],s=`${V.cyan}\u25CC${V.reset}`,o=this._formatElapsed(),n=o?` ${V.dim}${o}${V.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let l,c;switch(this.statuses[a]){case"done":l=`${V.green}\u2713${V.reset}`,c=V.dim;break;case"error":l=`${V.red}\u2717${V.reset}`,c=V.dim;break;case"retry":l=`${V.yellow}\u21BB${V.reset}`,c=V.yellow;break;default:l=a===e?s:`${V.dim}\xB7${V.reset}`,c=""}let u=a===this.labels.length-1?n:"",d=r-4-(u?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} ${c}${f}${V.reset}${u}
1
+ var Fa=Object.defineProperty;var d0=Object.getOwnPropertyDescriptor;var f0=Object.getOwnPropertyNames;var p0=Object.prototype.hasOwnProperty;var h0=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),m0=(t,e)=>{for(var s in e)Fa(t,s,{get:e[s],enumerable:!0})},g0=(t,e,s,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of f0(e))!p0.call(t,n)&&n!==s&&Fa(t,n,{get:()=>e[n],enumerable:!(o=d0(e,n))||o.enumerable});return t};var y0=t=>g0(Fa({},"__esModule",{value:!0}),t);var Ls=Z((vC,nd)=>{async function w0(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 Ba=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`)}};nd.exports={BaseProvider:Ba,readStreamErrorBody:w0}});var Ds=Z((EC,od)=>{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,s={}){throw new Error("createStreamParser() not implemented")}},js=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")}},Ir=class extends js{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}}))}}},jr=class extends Is{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 Ir(e,s)}},Dr=class extends js{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}}})}}},Ua="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",qr=class extends Is{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 c=a.system,u=c.indexOf(Ua);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+Ua.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=c}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 Dr(e,s)}};function sd(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,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:sd(e.function?.arguments??e.arguments)}}))}}},Br=class extends Is{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:sd(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,s={}){return new Fr(e,s)}},b0=new jr,$0=new qr,_0=new Br;od.exports={ANTHROPIC_CACHE_BOUNDARY:Ua,WireProtocol:Is,StreamParser:js,OpenAICompatibleProtocol:jr,AnthropicProtocol:qr,OllamaChatProtocol:Br,OpenAIStreamParser:Ir,AnthropicStreamParser:Dr,OllamaStreamParser:Fr,openaiProtocol:b0,anthropicProtocol:$0,ollamaProtocol:_0}});var id=Z((TC,rd)=>{var Ur=require("axios"),x0=require("http"),k0=require("https"),{BaseProvider:S0,readStreamErrorBody:v0}=Ls(),{ollamaProtocol:Wn}=Ds(),Wr=new x0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Hr=new k0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Yr={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072,capability:"agentic",speed:"balanced",quality:98,recommendedFor:["coding","agentic","refactor"]},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144,capability:"agentic",speed:"balanced",quality:97,recommendedFor:["coding","agentic","large-context"]},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072,capability:"agentic",speed:"balanced",quality:94,recommendedFor:["coding","sysadmin","agentic"]},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072,capability:"fast-coding",speed:"fast",quality:82,recommendedFor:["quick-fix","sysadmin","fallback"]},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072,capability:"general",speed:"balanced",quality:90,recommendedFor:["coding","reasoning"]},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"balanced",quality:96,recommendedFor:["reasoning","large-context","review"]},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"deliberate",quality:99,recommendedFor:["reasoning","architecture","review"]},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"deliberate",quality:98,recommendedFor:["reasoning","debugging","review"]},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072,capability:"general",speed:"balanced",quality:94,recommendedFor:["coding","reasoning","fallback"]},"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,capability:"vision-language",speed:"balanced",quality:95,recommendedFor:["frontend","vision","large-context"]},"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,capability:"fast-coding",speed:"fast",quality:84,recommendedFor:["quick-fix","coding","fallback"]},"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,capability:"fast-coding",speed:"fast",quality:86,recommendedFor:["quick-fix","coding"]},"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,capability:"open-reasoning",speed:"balanced",quality:88,recommendedFor:["open-source","reasoning","coding"]},"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,capability:"fast-coding",speed:"fast",quality:78,recommendedFor:["quick-fix","fallback"]},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072,capability:"fast",speed:"very-fast",quality:72,recommendedFor:["quick-fix","fallback"]},"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}},Wa={coding:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b"],agentic:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b"],reasoning:["kimi-k2:1t","kimi-k2-thinking","kimi-k2.5"],"large-context":["qwen3-coder-next","qwen3.5:397b-cloud","kimi-k2.5"],frontend:["qwen3.5:397b-cloud","qwen3-coder-next","qwen3-coder:480b"],"quick-fix":["devstral-small-2:24b","qwen3-next:80b","ministral-3:14b"],fallback:["devstral-small-2:24b","deepseek-v3.2","qwen3.5:35b-a3b"],"open-source":["qwen3-coder:480b","devstral-2:123b","gpt-oss:120b"]};function E0(t="coding",e=5){let s=Wa[t]||Wa.coding;return s.map(n=>Yr[n]).filter(Boolean).concat(Object.values(Yr).filter(n=>!s.includes(n.id)).filter(n=>(n.recommendedFor||[]).includes(t))).sort((n,r)=>(r.quality||0)-(n.quality||0)).slice(0,e)}var Ha=class extends S0{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Yr,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 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 Ur.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Wr,httpsAgent:Hr})).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=Wn.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 Ur.post(`${this.baseUrl}${Wn.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Wr,httpsAgent:Hr})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=c.response?.data?.error||c.message;throw new Error(`API Error${u}: ${d}`)}return Wn.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||(()=>{}),c=Wn.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),u;try{u=await Ur.post(`${this.baseUrl}${Wn.getEndpoint()}`,c,{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 p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await v0(f,b=>b?.error),g=new Error(`API Error${p}: ${m}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=Wn.createStreamParser(a,{onThinkingToken:l});return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:b}=d.feed(m.toString());g&&f(b)}),u.data.on("error",m=>{if(o.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,p(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Wn.normalizeResponse(e)}};rd.exports={OllamaProvider:Ha,OLLAMA_MODELS:Yr,OLLAMA_USE_CASES:Wa,getOllamaRecommendations:E0}});var ud=Z((RC,cd)=>{var ad=require("axios"),{BaseProvider:T0,readStreamErrorBody:R0}=Ls(),{openaiProtocol:Hn}=Ds(),ld={"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}},Ya=class extends T0{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||ld,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=Hn.buildRequestBody({model:n,messages:a,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),c;try{c=await ad.post(`${this.baseUrl}${Hn.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Hn.normalizeResponse(c.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),c=Hn.buildRequestBody({model:n,messages:l,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),u;try{u=await ad.post(`${this.baseUrl}${Hn.getEndpoint()}`,c,{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 p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await R0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Hn.createStreamParser(a);return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:b}=d.feed(m.toString());g&&f(b)}),u.data.on("error",m=>{o.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Hn.normalizeResponse(e)}};cd.exports={OpenAIProvider:Ya,OPENAI_MODELS:ld}});var hd=Z((CC,pd)=>{var dd=require("axios"),{BaseProvider:C0,readStreamErrorBody:A0}=Ls(),{anthropicProtocol:Cn}=Ds(),fd={"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}},O0="2023-06-01",Ga=class extends C0{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||fd,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||O0}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 Cn.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:c}=this.formatMessages(e),u=this.formatTools(s),d=Cn.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await dd.post(`${this.baseUrl}${Cn.getEndpoint()}`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",g=p.response?.data?.error?.message||p.response?.data?.error||p.message;throw new Error(`API Error${m}: ${g}`)}return Cn.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:c,system:u}=this.formatMessages(e),d=this.formatTools(s),f=Cn.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await dd.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 b=g.response?.status?` [HTTP ${g.response.status}]`:"",x=await A0(g,E=>E?.error?.message||E?.error);throw new Error(`API Error${b}: ${x}`)}let m=Cn.createStreamParser(l);return new Promise((g,b)=>{o.signal&&o.signal.addEventListener("abort",()=>{p.data.destroy(),b(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",x=>{let{done:E,result:N}=m.feed(x.toString());E&&g(N)}),p.data.on("error",x=>{o.signal?.aborted||b(new Error(`Stream error: ${x.message}`))}),p.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return Cn.normalizeResponse(e)}};pd.exports={AnthropicProvider:Ga,ANTHROPIC_MODELS:fd}});var wd=Z((AC,yd)=>{var md=require("axios"),{BaseProvider:N0,readStreamErrorBody:P0}=Ls(),{openaiProtocol:Yn}=Ds(),gd={"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}},za=class extends N0{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||gd,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=Yn.buildRequestBody({model:n,messages:a,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),c;try{c=await md.post(`${this.baseUrl}${Yn.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Yn.normalizeResponse(c.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),c=Yn.buildRequestBody({model:n,messages:l,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),u;try{u=await md.post(`${this.baseUrl}${Yn.getEndpoint()}`,c,{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 p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await P0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Yn.createStreamParser(a);return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:b}=d.feed(m.toString());g&&f(b)}),u.data.on("error",m=>{o.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Yn.normalizeResponse(e)}};yd.exports={GeminiProvider:za,GEMINI_MODELS:gd}});var _d=Z((OC,$d)=>{var Gr=require("axios"),{BaseProvider:M0,readStreamErrorBody:L0}=Ls(),{ollamaProtocol:Gn}=Ds(),bd="http://localhost:11434",Ka=class extends M0{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||bd,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 Gr.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 Gr.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=Gn.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await Gr.post(`${this.baseUrl}${Gn.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}]`:"",c=a.response?.data?.error||a.message;throw new Error(`API Error${l}: ${c}`)}return Gn.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=Gn.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await Gr.post(`${this.baseUrl}${Gn.getEndpoint()}`,i,{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=await L0(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=Gn.createStreamParser(r);return new Promise((c,u)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:p}=l.feed(d.toString());f&&c(p)}),a.data.on("error",d=>{o.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{c(l.flush())})})}normalizeResponse(e){return Gn.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}};$d.exports={LocalProvider:Ka,DEFAULT_LOCAL_URL:bd}});var Kt=Z((NC,Rd)=>{"use strict";var xd="\x1B[0m",kd="\x1B[1m",qs="\x1B[2m";function X(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function I0(){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 Sd(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function j0(t){try{let s=require("fs").readFileSync(Sd(),"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 D0(t,e){try{let s=require("fs"),o=require("path"),n=Sd(),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 q0(){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=j0(s);if(o!==null)return o;let n=I0(),r=n!==null?n:!0;return D0(s,r),r}var vd=q0(),Ed={reset:xd,bold:kd,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)},Td={reset:xd,bold:kd,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)},F0=vd?Ed:Td;Rd.exports={T:F0,isDark:vd,DARK:Ed,LIGHT:Td}});var zn=Z((PC,Ad)=>{"use strict";var Rt=require("fs"),Cd=require("path");function B0(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function U0(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function W0(t,e){let s=Cd.dirname(t),o=Cd.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{Rt.existsSync(s)||Rt.mkdirSync(s,{recursive:!0,mode:448}),Rt.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Rt.renameSync(o,t)}catch(n){try{Rt.unlinkSync(o)}catch{}throw n}}function H0(t,e,{timeout:s=5e3,retryMs:o=50}={}){let n=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=Rt.openSync(n,"wx"),Rt.writeSync(i,Buffer.from(String(process.pid))),Rt.closeSync(i),i=-1;try{return e()}finally{try{Rt.unlinkSync(n)}catch{}}}catch(a){if(i!==-1)try{Rt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=Rt.readFileSync(n,"utf-8").trim(),c=parseInt(l,10);if(!B0(c)){try{Rt.unlinkSync(n)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Rt.unlinkSync(n)}catch{}return e()}U0(o)}}}Ad.exports={atomicWrite:W0,withFileLockSync:H0}});var Kr=Z((MC,Dd)=>{var Fs=require("fs"),Xa=require("path"),{T:Od}=Kt(),{atomicWrite:Y0,withFileLockSync:G0}=zn(),Nd={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:{}},zr=[],An={};function z0(t,e,s,o,n=0){if(zr.push({provider:t,model:e,input:s,output:o,cacheRead:n}),An[t]!==void 0){let r=Id(t);r.allowed||process.stderr.write(`${Od.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${Od.reset}
9
+ `)}}function Va(t,e){let s=Nd[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Pd(t){let e=Va(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Md(){let t={};for(let i of zr){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:Pd(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 K0(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:o}=Md();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 X0(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function V0(t,e,s,o){let n=Va(t,e),r=(s*n.input+o*n.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function J0(){zr=[]}function Z0(t,e){An[t]=e}function Q0(t){delete An[t]}function eb(){return{...An}}function Ld(t){let e=0;for(let s of zr)s.provider===t&&(e+=Pd(s));return e}function Id(t){let e=Ld(t),s=An[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 jd(){let t=Xa.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 tb(){let t=Xa.join(process.cwd(),".nex"),e=Xa.join(t,"config.json");Fs.existsSync(t)||Fs.mkdirSync(t,{recursive:!0}),G0(e,()=>{let s={};if(Fs.existsSync(e))try{s=JSON.parse(Fs.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=An,Y0(e,JSON.stringify(s,null,2))})}function nb(){An={}}jd();Dd.exports={PRICING:Nd,trackUsage:z0,getSessionCosts:Md,formatCosts:K0,formatCostHint:V0,resetCosts:J0,getPricing:Va,setCostLimit:Z0,removeCostLimit:Q0,getCostLimits:eb,getProviderSpend:Ld,checkBudget:Id,loadCostLimits:jd,saveCostLimits:tb,resetCostLimits:nb,estimateTokens:X0}});var Ja=Z((LC,sb)=>{sb.exports={name:"nex-code",version:"0.5.17",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 --runInBand","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 Kn=Z((IC,Hd)=>{var{T:V}=Kt(),Za=5,Bs=(()=>{let t=[];for(let e=0;e<Za;e++)t.push(e);for(let e=Za-2;e>=1;e--)t.push(e);return t})(),qd=["\u273D","\u2726","\u2727","\u2726"],Fd=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function Bd(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 Ud(t,e,s){let o="";for(let n=0;n<Za;n++)n===t?o+=`${s}${e}${V.reset}`:n===t-1||n===t+1?o+=`${V.dim}\xB7${V.reset}`:o+=`${V.dim}\xB7${V.reset}`;return o}function Wd(t){return`${V.dim}${Fd[t%Fd.length]}${V.reset}`}var Qa=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],s=Bd(this.text),o=Ud(e,s.glyph,s.color),n=Wd(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${s.color}${s.accent.toUpperCase()}${V.reset}${n} ${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}},el=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=Bs[this.frame%Bs.length],s=`${V.cyan}\u25CC${V.reset}`,o=this._formatElapsed(),n=o?` ${V.dim}${o}${V.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let l,c;switch(this.statuses[a]){case"done":l=`${V.green}\u2713${V.reset}`,c=V.dim;break;case"error":l=`${V.red}\u2717${V.reset}`,c=V.dim;break;case"retry":l=`${V.yellow}\u21BB${V.reset}`,c=V.yellow;break;default:l=a===e?s:`${V.dim}\xB7${V.reset}`,c=""}let u=a===this.labels.length-1?n:"",d=r-4-(u?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} ${c}${f}${V.reset}${u}
11
11
  `}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
12
12
  `;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let s="";for(let o=0;o<this.lineCount;o++)s+=`\x1B[2K
13
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?` ${V.dim}${e}${V.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=`${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?s:"",l=o-4-(a?e.length+1:0),c=this.labels[r].length>l?this.labels[r].substring(0,Math.max(10,l-3))+"...":this.labels[r];n+=`\x1B[2K ${i} ${V.dim}${c}${V.reset}${a}
14
- `}process.stderr.write(n)}},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,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=jd[this.frame%jd.length],s=this._formatElapsed(),o=this._formatTokens(),n=[s,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=n?` ${V.dim}(${n})${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],c=a===0?"\u23BF":"\u2502",u=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}${c}${V.reset} ${d}${u}${V.reset} ${f}
14
+ `}process.stderr.write(n)}},Xr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Vr={done:V.green,in_progress:V.cyan,pending:V.dim,failed:V.red},On=null,tl=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=qd[this.frame%qd.length],s=this._formatElapsed(),o=this._formatTokens(),n=[s,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=n?` ${V.dim}(${n})${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],c=a===0?"\u23BF":"\u2502",u=Xr[l.status]||Xr.pending,d=Vr[l.status]||Vr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${V.dim}${c}${V.reset} ${d}${u}${V.reset} ${f}
16
16
  `}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
17
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 s=0;s<this.lineCount;s++)e+=`\x1B[2K
18
18
  `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
19
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${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],c=a===0?"\u23BF":"\u2502",u=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}${c}${V.reset} ${d}${u}${V.reset} ${V.dim}${f}${V.reset}
21
- `}process.stderr.write(i)}},Qa=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=Bs[this.frame%Bs.length],s=qd(this.message),o=Fd(e,s.glyph,s.color),n=Bd(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${s.color}${s.accent.toUpperCase()}${V.reset}${n} ${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 e$(t){On=t}function t$(){return On}function n$(){On&&(On.stop(),On=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Ud.exports={C:V,Spinner:Va,MultiProgress:Ja,TaskProgress:Za,ToolProgress:Qa,setActiveTaskProgress:e$,getActiveTaskProgress:t$,cleanupTerminal:n$}});var Vr=Z((OC,zd)=>{"use strict";var{T:Kn}=Kt(),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},Wd={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"])},s$={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 Yd(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return s$[e]||null}var Hd=/\x1b\[[0-9;]*m/g;function $n(t,e,s){let o=t.split(Hd),n=t.match(Hd)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,s),i<n.length&&(r+=n[i]);return r}function o$(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,s=>pe.type+s+pe.reset),e=$n(e,/"([^"\\]|\\.)*"/g,s=>pe.str+s+pe.reset),e=$n(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,s=>pe.num+s+pe.reset),e=$n(e,/\b(true|false|null)\b/g,s=>pe.kw+s+pe.reset),e}function r$(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,s=>pe.cmt+s+pe.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(s,o,n)=>o+pe.type+n+pe.reset),e=$n(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(s,o)=>" "+pe.kw+o+pe.reset+"="),e=$n(e,/"([^"]*)"/g,s=>pe.str+s+pe.reset),e}function i$(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,s=>pe.cmt+s+pe.reset),e=$n(e,/#[0-9a-fA-F]{3,8}\b/g,s=>pe.num+s+pe.reset),e=$n(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(s,o,n)=>pe.num+o+pe.reset+n),e=$n(e,/([a-z][a-z-]*)(\s*:)/g,(s,o,n)=>pe.type+o+pe.reset+n),e=$n(e,/"[^"]*"|'[^']*'/g,s=>pe.str+s+pe.reset),e}function Gd(t,e,s){if(e==="json")return o$(t);if(e==="html"||e==="xml")return r$(t);if(e==="css")return i$(t);if(e==="md")return t;let o=Wd[e]||Wd.js,n="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return pe.cmt+t+pe.reset;if(n+=pe.cmt+t.slice(0,i+2)+pe.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return n}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return pe.str+t+pe.reset;if(n+=pe.str+t.slice(0,i+1)+pe.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+=pe.cmt+t.slice(r)+pe.reset,s.inBlockComment=!0,n;n+=pe.cmt+t.slice(r,a+2)+pe.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+=pe.cmt+t.slice(r)+pe.reset,n;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,n+=pe.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+pe.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+=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++];n+=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)?n+=pe.kw+a+pe.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?n+=pe.type+a+pe.reset:n+=a;continue}n+=i,r++}return s.inString&&s.inString!=="`"&&(n+=pe.reset,s.inString=null),n}function a$(t,e){let s=Yd(e);if(!s)return t.split(`
20
+ `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=Xr[l.status]||Xr.pending,d=Vr[l.status]||Vr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${V.dim}${c}${V.reset} ${d}${u}${V.reset} ${V.dim}${f}${V.reset}
21
+ `}process.stderr.write(i)}},nl=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=Bs[this.frame%Bs.length],s=Bd(this.message),o=Ud(e,s.glyph,s.color),n=Wd(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${s.color}${s.accent.toUpperCase()}${V.reset}${n} ${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 ob(t){On=t}function rb(){return On}function ib(){On&&(On.stop(),On=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Hd.exports={C:V,Spinner:Qa,MultiProgress:el,TaskProgress:tl,ToolProgress:nl,setActiveTaskProgress:ob,getActiveTaskProgress:rb,cleanupTerminal:ib}});var Jr=Z((jC,Xd)=>{"use strict";var{T:Xn}=Kt(),he={kw:Xn.syn_keyword,str:Xn.syn_string,cmt:Xn.syn_comment,num:Xn.syn_number,type:Xn.cyan,punct:Xn.magenta,reset:Xn.reset},Yd={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"])},ab={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 zd(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return ab[e]||null}var Gd=/\x1b\[[0-9;]*m/g;function bn(t,e,s){let o=t.split(Gd),n=t.match(Gd)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,s),i<n.length&&(r+=n[i]);return r}function lb(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,s=>he.type+s+he.reset),e=bn(e,/"([^"\\]|\\.)*"/g,s=>he.str+s+he.reset),e=bn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,s=>he.num+s+he.reset),e=bn(e,/\b(true|false|null)\b/g,s=>he.kw+s+he.reset),e}function cb(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=bn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(s,o)=>" "+he.kw+o+he.reset+"="),e=bn(e,/"([^"]*)"/g,s=>he.str+s+he.reset),e}function ub(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,s=>he.cmt+s+he.reset),e=bn(e,/#[0-9a-fA-F]{3,8}\b/g,s=>he.num+s+he.reset),e=bn(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=bn(e,/([a-z][a-z-]*)(\s*:)/g,(s,o,n)=>he.type+o+he.reset+n),e=bn(e,/"[^"]*"|'[^']*'/g,s=>he.str+s+he.reset),e}function Kd(t,e,s){if(e==="json")return lb(t);if(e==="html"||e==="xml")return cb(t);if(e==="css")return ub(t);if(e==="md")return t;let o=Yd[e]||Yd.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 db(t,e){let s=zd(e);if(!s)return t.split(`
22
22
  `);let o=t.split(`
23
- `),n={inString:null,inBlockComment:!1};return o.map(r=>Gd(r,s,n))}function l$(t,e){return e?Gd(t,e,{inString:null,inBlockComment:!1}):t}zd.exports={detectLang:Yd,highlightLine:l$,highlightLines:a$}});var sf=Z((NC,nf)=>{var{T:b}=Kt(),Le=b,Kd=require("path"),Xd=["\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 c$={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},Qd={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"},u$={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 u$[t]||{label:"Run",accent:b.tool_default,icon:"\u2022"}}function Vd(t){let e=tl(t);return`${e.accent}${Le.bold}${e.icon} ${e.label.toUpperCase()}${b.reset}`}function d$(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Jd(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):Qd[t]||d$(t)}function f$(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 h$(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}=Vr(),c=l(t||null),u=e.slice(0,o),d=u.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,c)}${b.reset}`});return i&&e.length>u.length&&d.push(`${n}${b.subtle}\u2026 +${e.length-u.length} more line${e.length-u.length!==1?"s":""}${b.reset}`),d.join(`
25
- `)}function p$(t,e=96){let s=String(t||"").replace(/\t/g," ").trimEnd();return s.length>e?s.substring(0,Math.max(1,e-1))+"\u2026":s}function el(t,e={}){let{maxLines:s=3,maxContent:o=96}=e,r=String(t||"").split(`
26
- `).filter((a,l,c)=>a.trim()||c.length===1||l===0),i=r.slice(0,s).map(a=>p$(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function ef(t,e={}){let{indent:s=" ",maxLines:o=2,maxContent:n=100}=e;if(!t)return"";let{shown:r,more:i}=el(t,{maxLines:o,maxContent:n});if(r.length===0)return"";let a=r.map((l,c)=>`${s}${b.subtle}${c===0?"$":">"}${b.reset} ${b.muted}${l}${b.reset}`);return i>0&&a.push(`${s}${b.subtle}\u2026 +${i} more command line${i!==1?"s":""}${b.reset}`),a.join(`
27
- `)}function nl(t,e,s,o={}){let{indent:n=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=o,{highlightLine:l,detectLang:c}=Vr(),u=c(t||null),{shown:d,more:f}=el(e,{maxLines:r,maxContent:i}),{shown:h,more:m}=el(s,{maxLines:r,maxContent:i}),g=[];return d.length>0&&a&&g.push(`${n}${b.subtle}before${b.reset}`),d.forEach($=>{g.push(`${n}${b.diff_rem}- ${b.reset}${l($,u)}${b.reset}`)}),f>0&&g.push(`${n}${b.subtle}\u2026 ${f} more removed line${f!==1?"s":""}${b.reset}`),h.length>0&&a&&g.push(`${n}${b.subtle}after${b.reset}`),h.forEach($=>{g.push(`${n}${b.diff_add}+ ${b.reset}${l($,u)}${b.reset}`)}),m>0&&g.push(`${n}${b.subtle}\u2026 ${m} more added line${m!==1?"s":""}${b.reset}`),g.join(`
28
- `)}function tf(t,e,s={}){let{indent:o=" ",maxPatches:n=2,maxLinesPerSide:r=2,maxContent:i=92}=s;if(!Array.isArray(e)||e.length===0)return"";let a=[];return e.slice(0,n).forEach((l,c)=>{a.push(`${o}${b.subtle}patch ${c+1}${b.reset}`);let u=nl(t,l.old_text,l.new_text,{indent:o+" ",maxLines:r,maxContent:i,includeLabels:!1});u&&a.push(u)}),e.length>n&&a.push(`${o}${b.subtle}\u2026 +${e.length-n} more patches${b.reset}`),a.join(`
29
- `)}function m$(t){let e=new Set,s=[];for(let o of t){let n=tl(o.fnName).label;e.has(n)||(e.add(n),s.push(n))}return s.length===0?"":s.length<=3?s.join(`${Le.dim} \u2192 ${Le.reset}`):`${s.slice(0,3).join(`${Le.dim} \u2192 ${Le.reset}`)}${Le.dim} \u2192 +${s.length-3}${Le.reset}`}function Jr(t,e=!1,s=null){if(e)return`${b.error}\u23FA${b.reset}`;let o=c$[t]||b.tool_default;if(s==="blink")return`${o}\x1B[5m\u23FA\x1B[25m${b.reset}`;let n=typeof s=="number"?Xd[s%Xd.length]:s!==null?s:"\u23FA";return`${o}${n}${b.reset}`}function g$(t,e,s=!1,o=null){let n=(t||[]).filter(c=>c&&c.canExecute!==!1);if(n.length===0)return`${Jr("",s,o)} Step ${e}`;if(n.length===1){let c=n[0],u=c.args||{},d=Jd(c.fnName,{...u,path:u._originalPath||u.path});return`${Jr(c.fnName,s,o)} ${Vd(c.fnName)} ${Le.bold}${d}${Le.reset}`}let r=n[0].fnName,i=m$(n)||`${n.length} tools`,a=n.slice(0,2).map(c=>Jd(c.fnName,c.args||{})).filter(Boolean).join(`${Le.dim} \xB7 ${Le.reset}`),l=a?` ${b.subtle}\xB7${b.reset} ${Le.dim}${a}${Le.reset}`:"";return`${Jr(r,s,o)} ${Vd(r)} ${Le.bold}${i}${Le.reset}${l}`}function y$(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,44);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=Qd[t]||t.replace(/_/g," "),n=s?`(${Le.dim}${s}${Le.reset})`:"",r=`${Jr(t)} ${Le.bold}${o}${Le.reset}${n}`;if(t==="bash"||t==="ssh_exec"){let i=ef(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=tf(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
32
- ${i}`:r}return r}function w$(t,e=8){let s=t.split(`
33
- `),o=s.slice(0,e),n=s.length-e,r=`${b.muted} \u23BF ${b.reset}`,i=" ",a=o.map((l,c)=>`${c===0?r:i}${b.success}${l}${b.reset}`).join(`
23
+ `),n={inString:null,inBlockComment:!1};return o.map(r=>Kd(r,s,n))}function fb(t,e){return e?Kd(t,e,{inString:null,inBlockComment:!1}):t}Xd.exports={detectLang:zd,highlightLine:fb,highlightLines:db}});var rf=Z((DC,of)=>{var{T:$}=Kt(),Le=$,Vd=require("path"),Jd=["\u23FA","\u25C9","\u25CE","\u25C9"];function Qr(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var pb={read_file:$.tool_read,list_directory:$.tool_read,write_file:$.tool_write,edit_file:$.tool_write,patch_file:$.tool_write,bash:$.tool_exec,grep:$.tool_search,search_files:$.tool_search,glob:$.tool_search,git_commit:$.tool_git,git_push:$.tool_git,git_pull:$.tool_git,git_status:$.tool_git,git_diff:$.tool_git,git_log:$.tool_git,git_branch:$.tool_git,git_stash:$.tool_git,web_fetch:$.tool_web,web_search:$.tool_web,sysadmin:$.tool_sysadmin,ssh_exec:$.tool_sysadmin,ssh_upload:$.tool_sysadmin,ssh_download:$.tool_sysadmin,deploy:$.tool_sysadmin},tf={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"},hb={read_file:{label:"Inspect",accent:$.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:$.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:$.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:$.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:$.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:$.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:$.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:$.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:$.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:$.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:$.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:$.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:$.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:$.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:$.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:$.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:$.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:$.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:$.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:$.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:$.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:$.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:$.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:$.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:$.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:$.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:$.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:$.tool_git,icon:"\u2713"}};function ol(t){return hb[t]||{label:"Run",accent:$.tool_default,icon:"\u2022"}}function Zd(t){let e=ol(t);return`${e.accent}${Le.bold}${e.icon} ${e.label.toUpperCase()}${$.reset}`}function mb(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Qd(t,e={}){return e.path?Qr(e.path):e.file?Qr(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):tf[t]||mb(t)}function gb(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 yb(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}=Jr(),c=l(t||null),u=e.slice(0,o),d=u.map(({lineNumber:f,content:p})=>{let m=p.length>r?p.substring(0,r-1)+"\u2026":p;return`${n}${$.subtle}${f}:${$.reset} ${a(m,c)}${$.reset}`});return i&&e.length>u.length&&d.push(`${n}${$.subtle}\u2026 +${e.length-u.length} more line${e.length-u.length!==1?"s":""}${$.reset}`),d.join(`
25
+ `)}function wb(t,e=96){let s=String(t||"").replace(/\t/g," ").trimEnd();return s.length>e?s.substring(0,Math.max(1,e-1))+"\u2026":s}function sl(t,e={}){let{maxLines:s=3,maxContent:o=96}=e,r=String(t||"").split(`
26
+ `).filter((a,l,c)=>a.trim()||c.length===1||l===0),i=r.slice(0,s).map(a=>wb(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function nf(t,e={}){let{indent:s=" ",maxLines:o=2,maxContent:n=100}=e;if(!t)return"";let{shown:r,more:i}=sl(t,{maxLines:o,maxContent:n});if(r.length===0)return"";let a=r.map((l,c)=>`${s}${$.subtle}${c===0?"$":">"}${$.reset} ${$.muted}${l}${$.reset}`);return i>0&&a.push(`${s}${$.subtle}\u2026 +${i} more command line${i!==1?"s":""}${$.reset}`),a.join(`
27
+ `)}function rl(t,e,s,o={}){let{indent:n=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=o,{highlightLine:l,detectLang:c}=Jr(),u=c(t||null),{shown:d,more:f}=sl(e,{maxLines:r,maxContent:i}),{shown:p,more:m}=sl(s,{maxLines:r,maxContent:i}),g=[];return d.length>0&&a&&g.push(`${n}${$.subtle}before${$.reset}`),d.forEach(b=>{g.push(`${n}${$.diff_rem}- ${$.reset}${l(b,u)}${$.reset}`)}),f>0&&g.push(`${n}${$.subtle}\u2026 ${f} more removed line${f!==1?"s":""}${$.reset}`),p.length>0&&a&&g.push(`${n}${$.subtle}after${$.reset}`),p.forEach(b=>{g.push(`${n}${$.diff_add}+ ${$.reset}${l(b,u)}${$.reset}`)}),m>0&&g.push(`${n}${$.subtle}\u2026 ${m} more added line${m!==1?"s":""}${$.reset}`),g.join(`
28
+ `)}function sf(t,e,s={}){let{indent:o=" ",maxPatches:n=2,maxLinesPerSide:r=2,maxContent:i=92}=s;if(!Array.isArray(e)||e.length===0)return"";let a=[];return e.slice(0,n).forEach((l,c)=>{a.push(`${o}${$.subtle}patch ${c+1}${$.reset}`);let u=rl(t,l.old_text,l.new_text,{indent:o+" ",maxLines:r,maxContent:i,includeLabels:!1});u&&a.push(u)}),e.length>n&&a.push(`${o}${$.subtle}\u2026 +${e.length-n} more patches${$.reset}`),a.join(`
29
+ `)}function bb(t){let e=new Set,s=[];for(let o of t){let n=ol(o.fnName).label;e.has(n)||(e.add(n),s.push(n))}return s.length===0?"":s.length<=3?s.join(`${Le.dim} \u2192 ${Le.reset}`):`${s.slice(0,3).join(`${Le.dim} \u2192 ${Le.reset}`)}${Le.dim} \u2192 +${s.length-3}${Le.reset}`}function Zr(t,e=!1,s=null){if(e)return`${$.error}\u23FA${$.reset}`;let o=pb[t]||$.tool_default;if(s==="blink")return`${o}\x1B[5m\u23FA\x1B[25m${$.reset}`;let n=typeof s=="number"?Jd[s%Jd.length]:s!==null?s:"\u23FA";return`${o}${n}${$.reset}`}function $b(t,e,s=!1,o=null){let n=(t||[]).filter(c=>c&&c.canExecute!==!1);if(n.length===0)return`${Zr("",s,o)} Step ${e}`;if(n.length===1){let c=n[0],u=c.args||{},d=Qd(c.fnName,{...u,path:u._originalPath||u.path});return`${Zr(c.fnName,s,o)} ${Zd(c.fnName)} ${Le.bold}${d}${Le.reset}`}let r=n[0].fnName,i=bb(n)||`${n.length} tools`,a=n.slice(0,2).map(c=>Qd(c.fnName,c.args||{})).filter(Boolean).join(`${Le.dim} \xB7 ${Le.reset}`),l=a?` ${$.subtle}\xB7${$.reset} ${Le.dim}${a}${Le.reset}`:"";return`${Zr(r,s,o)} ${Zd(r)} ${Le.bold}${i}${Le.reset}${l}`}function _b(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,44);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=tf[t]||t.replace(/_/g," "),n=s?`(${Le.dim}${s}${Le.reset})`:"",r=`${Zr(t)} ${Le.bold}${o}${Le.reset}${n}`;if(t==="bash"||t==="ssh_exec"){let i=nf(e.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
30
+ ${i}`:r}if(t==="edit_file"){let i=rl(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=sf(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
32
+ ${i}`:r}return r}function xb(t,e=8){let s=t.split(`
33
+ `),o=s.slice(0,e),n=s.length-e,r=`${$.muted} \u23BF ${$.reset}`,i=" ",a=o.map((l,c)=>`${c===0?r:i}${$.success}${l}${$.reset}`).join(`
34
34
  `);return n>0&&(a+=`
35
- ${b.subtle} \u2026 +${n} lines${b.reset}`),a}var Qr=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Zd=Math.floor(Math.random()*Qr.length),$$=null;function b$(t){$$=t}function _$(){let t=Qr[Zd%Qr.length];return Zd++,t}function x$(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 k$(t,e,s,o){let n=String(s||""),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 c=n.split(`
36
- `)[0];if(c.startsWith("BLOCKED:")){let h=c.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${b.muted}blocked: ${h}${b.reset}`}let u=c.replace(/^ERROR:\s*/i,"").substring(0,80),d=n.match(/\nHINT: (.+)/),f=d?`
37
- ${b.muted}${d[1].substring(0,100)}${b.reset}`:"";return`${i}${b.error}${u}${b.reset}${f}`}let a;switch(t){case"read_file":{let c=f$(n),u=c.length,d=c[c.length-1],f=d?parseInt(d.lineNumber||"0"):0,h=e.line_start||e.line_end,m=e.path?Kd.basename(e.path):null,g=m?` ${b.muted}from ${m}${b.reset}`:"";h&&f>u?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${u} line${u!==1?"s":""}${g}`;let $=h$(e.path,c,{maxLines:4,maxContent:120});$&&(a+=`
38
- ${$}`);break}case"write_file":{let u=(e.content||"").split(`
39
- `).length,d=e.path?Kd.basename(e.path):null,f=d?`Wrote ${d} \xB7 ${u} line${u!==1?"s":""}`:`Wrote ${u} line${u!==1?"s":""}`,{highlightLines:h}=Vr(),m=h(e.content||"",e.path||null),g=40,$=8;if(u<=g){let x=m.map(E=>` ${E}`).join(`
35
+ ${$.subtle} \u2026 +${n} lines${$.reset}`),a}var ei=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],ef=Math.floor(Math.random()*ei.length),kb=null;function Sb(t){kb=t}function vb(){let t=ei[ef%ei.length];return ef++,t}function Eb(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 Tb(t,e,s,o){let n=String(s||""),r=ol(t),i=` ${$.subtle}\u2502${$.reset} ${r.accent}${Le.bold}${r.label}${$.reset} ${$.subtle}\xB7${$.reset} `;if(o){let c=n.split(`
36
+ `)[0];if(c.startsWith("BLOCKED:")){let p=c.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${$.muted}blocked: ${p}${$.reset}`}let u=c.replace(/^ERROR:\s*/i,"").substring(0,80),d=n.match(/\nHINT: (.+)/),f=d?`
37
+ ${$.muted}${d[1].substring(0,100)}${$.reset}`:"";return`${i}${$.error}${u}${$.reset}${f}`}let a;switch(t){case"read_file":{let c=gb(n),u=c.length,d=c[c.length-1],f=d?parseInt(d.lineNumber||"0"):0,p=e.line_start||e.line_end,m=e.path?Vd.basename(e.path):null,g=m?` ${$.muted}from ${m}${$.reset}`:"";p&&f>u?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${u} line${u!==1?"s":""}${g}`;let b=yb(e.path,c,{maxLines:4,maxContent:120});b&&(a+=`
38
+ ${b}`);break}case"write_file":{let u=(e.content||"").split(`
39
+ `).length,d=e.path?Vd.basename(e.path):null,f=d?`Wrote ${d} \xB7 ${u} line${u!==1?"s":""}`:`Wrote ${u} line${u!==1?"s":""}`,{highlightLines:p}=Jr(),m=p(e.content||"",e.path||null),g=40,b=8;if(u<=g){let x=m.map(E=>` ${E}`).join(`
40
40
  `);a=`${f}
41
- ${x}`}else{let x=m.slice(0,$).map(E=>` ${E}`).join(`
41
+ ${x}`}else{let x=m.slice(0,b).map(E=>` ${E}`).join(`
42
42
  `);a=`${f}
43
43
  ${x}
44
- ${b.subtle}\u2026 +${u-$} lines${b.reset}`}break}case"edit_file":{let c=(e.old_text||"").split(`
44
+ ${$.subtle}\u2026 +${u-b} lines${$.reset}`}break}case"edit_file":{let c=(e.old_text||"").split(`
45
45
  `),u=(e.new_text||"").split(`
46
- `),d=c.length,f=u.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 c=e.patches||[],u=c.reduce((g,$)=>g+($.old_text||"").split(`
48
- `).length,0),d=c.reduce((g,$)=>g+($.new_text||"").split(`
49
- `).length,0),f=e.path?Zr(e.path):null,h=f?` ${b.muted}${f}${b.reset}`:"";a=`${c.length} patch${c.length!==1?"es":""} ${b.diff_rem}\u2212${u}${b.reset} ${b.diff_add}+${d}${b.reset}${h}`;let m=tf(e.path,c,{indent:" ",maxPatches:3,maxLinesPerSide:2,maxContent:92});m&&(a+=`
46
+ `),d=c.length,f=u.length,p=e.path?Qr(e.path):null,m=p?` ${$.muted}${p}${$.reset}`:"",g=rl(e.path,e.old_text,e.new_text,{indent:" ",maxLines:4,maxContent:96});a=`${$.diff_rem}\u2212${d}${$.reset} ${$.diff_add}+${f}${$.reset}${m}`+(g?`
47
+ `+g:"");break}case"patch_file":{let c=e.patches||[],u=c.reduce((g,b)=>g+(b.old_text||"").split(`
48
+ `).length,0),d=c.reduce((g,b)=>g+(b.new_text||"").split(`
49
+ `).length,0),f=e.path?Qr(e.path):null,p=f?` ${$.muted}${f}${$.reset}`:"";a=`${c.length} patch${c.length!==1?"es":""} ${$.diff_rem}\u2212${u}${$.reset} ${$.diff_add}+${d}${$.reset}${p}`;let m=sf(e.path,c,{indent:" ",maxPatches:3,maxLinesPerSide:2,maxContent:92});m&&(a+=`
50
50
  ${m}`);break}case"bash":{let u=n.match(/^EXIT (\d+)/),d=n.split(`
51
- `).filter(g=>g&&!g.startsWith("EXIT ")&&!g.startsWith("HINT:")&&g.trim()),f=u?u[1]==="0"?`${b.success}\u2713${b.reset}`:`${b.error}\u2717 Exit ${u[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 g=u&&u[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=ef(e.command,{indent:" ",maxLines:2,maxContent:108});m&&(a=`${m}
53
- ${a}`);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(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),se=ne.match(/^(\d+)[:-](.*)/s),ce=se?`:${se[1]}`:"",de=(se?se[2]:ne).trim(),re=`${b.subtle}${c.basename(P)}${ce}${b.reset}`,le=`${b.muted}${de.substring(0,80)}${de.length>80?"\u2026":""}${b.reset}`;return`${re} ${le}`};var l=$;let c=require("path"),u=n.split(`
54
- `).filter(Boolean),d=u.length,h=new Set(u.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=u.slice(0,5).map((v,S)=>S===0?`${g}${x}
56
- ${$(v)}`:` ${$(v)}`),N=u.length-5;N>0&&E.push(` ${b.subtle}\u2026 +${N} more matches${b.reset}`),a=E.join(`
57
- `)}break}case"glob":{let c=e.pattern?` ${b.muted}${String(e.pattern).substring(0,50)}${b.reset}`:"";if(n==="(no matches)")a=`No files found${c}`;else{let u=require("path"),d=n.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?`
59
- ${b.subtle}path:${b.reset} ${b.muted}${String(e.path).substring(0,70)}${b.reset}`:"";a=`${f} file${f!==1?"s":""}${c}${$}`+(g.length>0?`
51
+ `).filter(g=>g&&!g.startsWith("EXIT ")&&!g.startsWith("HINT:")&&g.trim()),f=u?u[1]==="0"?`${$.success}\u2713${$.reset}`:`${$.error}\u2717 Exit ${u[1]}${$.reset}`:`${$.success}\u2713${$.reset}`,p=n.match(/\nHINT: (.+)/);if(p)a=`${f} ${$.muted}\u2014 ${p[1].substring(0,100)}${$.reset}`;else if(d.length===0)a=f;else{let g=u&&u[1]!=="0",b=g?d.slice(-3):d.slice(0,3),x=d.length-3,E=b.map((N,v)=>v===0?`${f} ${$.muted}${N.substring(0,120)}${$.reset}`:` ${$.muted}${N.substring(0,120)}${$.reset}`);if(x>0){let N=g?` ${$.subtle}${x} lines above\u2026${$.reset}`:` ${$.subtle}\u2026 +${x} lines${$.reset}`;g?E.unshift(N):E.push(N)}a=E.join(`
52
+ `)}let m=nf(e.command,{indent:" ",maxLines:2,maxContent:108});m&&(a=`${m}
53
+ ${a}`);break}case"grep":case"search_files":{if(n.includes("(no matches)")||n==="no matches")a=`No matches${e.pattern?` ${$.muted}"${String(e.pattern).substring(0,40)}"${$.reset}`:""}`;else{let b=function(v){let S=v.indexOf(":");if(S===-1)return`${$.muted}${v.substring(0,90)}${$.reset}`;let P=v.substring(0,S),ne=v.substring(S+1),se=ne.match(/^(\d+)[:-](.*)/s),ce=se?`:${se[1]}`:"",de=(se?se[2]:ne).trim(),re=`${$.subtle}${c.basename(P)}${ce}${$.reset}`,le=`${$.muted}${de.substring(0,80)}${de.length>80?"\u2026":""}${$.reset}`;return`${re} ${le}`};var l=b;let c=require("path"),u=n.split(`
54
+ `).filter(Boolean),d=u.length,p=new Set(u.map(v=>v.split(":")[0]).filter(Boolean)).size,m=e.pattern?` ${$.muted}"${String(e.pattern).substring(0,40)}"${$.reset}`:"",g=p>1?`${d} match${d!==1?"es":""} in ${p} files${m}`:`${d} match${d!==1?"es":""}${m}`,x=e.path?`
55
+ ${$.subtle}path:${$.reset} ${$.muted}${String(e.path).substring(0,70)}${$.reset}`:"",E=u.slice(0,5).map((v,S)=>S===0?`${g}${x}
56
+ ${b(v)}`:` ${b(v)}`),N=u.length-5;N>0&&E.push(` ${$.subtle}\u2026 +${N} more matches${$.reset}`),a=E.join(`
57
+ `)}break}case"glob":{let c=e.pattern?` ${$.muted}${String(e.pattern).substring(0,50)}${$.reset}`:"";if(n==="(no matches)")a=`No files found${c}`;else{let u=require("path"),d=n.split(`
58
+ `).filter(Boolean),f=d.length,p=d.slice(0,8),m=f-p.length,g=p.map(x=>` ${$.muted}${x}${$.reset}`);m>0&&g.push(` ${$.subtle}\u2026 +${m} more files${$.reset}`);let b=e.path?`
59
+ ${$.subtle}path:${$.reset} ${$.muted}${String(e.path).substring(0,70)}${$.reset}`:"";a=`${f} file${f!==1?"s":""}${c}${b}`+(g.length>0?`
60
60
  ${g.join(`
61
61
  `)}`:"")}break}case"list_directory":{if(n==="(empty)")a="0 entries";else{let c=n.split(`
62
- `).filter(Boolean),u=c.length,d=c.slice(0,6).join(", "),f=u-6;a=f>0?`${u} entries \u2014 ${b.muted}${d}, +${f} more${b.reset}`:`${u} entr${u!==1?"ies":"y"} \u2014 ${b.muted}${d}${b.reset}`}break}case"git_status":{let c=n.match(/Branch:\s*(\S+)/),u=n.split(`
62
+ `).filter(Boolean),u=c.length,d=c.slice(0,6).join(", "),f=u-6;a=f>0?`${u} entries \u2014 ${$.muted}${d}, +${f} more${$.reset}`:`${u} entr${u!==1?"ies":"y"} \u2014 ${$.muted}${d}${$.reset}`}break}case"git_status":{let c=n.match(/Branch:\s*(\S+)/),u=n.split(`
63
63
  `).filter(d=>/^\s*[MADRCU?!]/.test(d)).length;a=c?`${c[1]} \xB7 ${u} change${u!==1?"s":""}`:"Done";break}case"git_diff":{let c=(n.match(/^\+[^+]/gm)||[]).length,u=(n.match(/^-[^-]/gm)||[]).length;a=c||u?`+${c} \u2212${u} lines`:"No diff";break}case"git_log":{let c=n.split(`
64
- `).filter(h=>/^commit\s+[0-9a-f]{7}/.test(h)),u=c.length,d=c[0]?c[0].replace(/^commit\s+/,"").substring(0,7):null,f=(()=>{let h=n.indexOf(c[0]||"\0");return h===-1?null:n.substring(h).split(`
65
- `).find((g,$)=>$>0&&g.trim()&&!g.startsWith("Author:")&&!g.startsWith("Date:")&&!g.startsWith("Merge:"))})();if(u===0)a="Log retrieved";else if(d&&f){let h=u>1?` ${b.muted}+${u-1} more${b.reset}`:"";a=`${d} ${b.muted}${f.trim().substring(0,60)}${b.reset}${h}`}else a=`${u} commit${u!==1?"s":""}`;break}case"git_commit":{let c=n.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),u=n.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);a=c?`${c[1]}${u?` \u2014 ${u[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let c=n.match(/(?:->|→)\s*(\S+)/);a=c?`\u2192 ${c[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(n))a="Already up to date";else{let c=(n.match(/^\+/gm)||[]).length;a=c>0?`Pulled \xB7 +${c} lines`:"Pulled"}break}case"web_fetch":{let c=n.match(/<title[^>]*>([^<]{1,80})<\/title>/i),u=n.match(/^#\s+(.{1,80})/m),d=e.url||"",f="";try{f=new URL(d).hostname}catch{f=d.substring(0,60)}let h=c?c[1].trim():u?u[1].trim():null;a=h?`${f} \u2014 ${b.muted}${h.substring(0,70)}${b.reset}`:`Fetched ${f}`;break}case"web_search":{let c=n.split(`
64
+ `).filter(p=>/^commit\s+[0-9a-f]{7}/.test(p)),u=c.length,d=c[0]?c[0].replace(/^commit\s+/,"").substring(0,7):null,f=(()=>{let p=n.indexOf(c[0]||"\0");return p===-1?null:n.substring(p).split(`
65
+ `).find((g,b)=>b>0&&g.trim()&&!g.startsWith("Author:")&&!g.startsWith("Date:")&&!g.startsWith("Merge:"))})();if(u===0)a="Log retrieved";else if(d&&f){let p=u>1?` ${$.muted}+${u-1} more${$.reset}`:"";a=`${d} ${$.muted}${f.trim().substring(0,60)}${$.reset}${p}`}else a=`${u} commit${u!==1?"s":""}`;break}case"git_commit":{let c=n.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),u=n.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);a=c?`${c[1]}${u?` \u2014 ${u[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let c=n.match(/(?:->|→)\s*(\S+)/);a=c?`\u2192 ${c[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(n))a="Already up to date";else{let c=(n.match(/^\+/gm)||[]).length;a=c>0?`Pulled \xB7 +${c} lines`:"Pulled"}break}case"web_fetch":{let c=n.match(/<title[^>]*>([^<]{1,80})<\/title>/i),u=n.match(/^#\s+(.{1,80})/m),d=e.url||"",f="";try{f=new URL(d).hostname}catch{f=d.substring(0,60)}let p=c?c[1].trim():u?u[1].trim():null;a=p?`${f} \u2014 ${$.muted}${p.substring(0,70)}${$.reset}`:`Fetched ${f}`;break}case"web_search":{let c=n.split(`
66
66
 
67
67
  `).filter(Boolean),u=c.length,d=c[0]?c[0].split(`
68
- `)[0].replace(/^\d+\.\s*/,"").trim():null,f=d?` ${b.muted}\u2014 ${d.substring(0,70)}${b.reset}`:"";a=`${u} result${u!==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 c=(n.match(/✓ Agent/g)||[]).length,u=(n.match(/✗ Agent/g)||[]).length;a=u>0?`${c} done, ${u} failed`:`${c} agent${c!==1?"s":""} done`;break}case"switch_model":{let c=n.match(/Switched to (.+)/);a=c?`\u2192 ${c[1]}`:"Done";break}case"ssh_exec":{let u=n.startsWith("EXIT ")||n.startsWith("Command failed"),d=n.split(`
69
- `).filter(h=>h.trim()&&!h.startsWith("EXIT ")),f=u?`${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=u?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=u?` ${b.subtle}${g} lines above\u2026${b.reset}`:` ${b.subtle}\u2026 +${g} lines${b.reset}`;u?$.unshift(x):$.push(x)}a=$.join(`
68
+ `)[0].replace(/^\d+\.\s*/,"").trim():null,f=d?` ${$.muted}\u2014 ${d.substring(0,70)}${$.reset}`:"";a=`${u} result${u!==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 c=(n.match(/✓ Agent/g)||[]).length,u=(n.match(/✗ Agent/g)||[]).length;a=u>0?`${c} done, ${u} failed`:`${c} agent${c!==1?"s":""} done`;break}case"switch_model":{let c=n.match(/Switched to (.+)/);a=c?`\u2192 ${c[1]}`:"Done";break}case"ssh_exec":{let u=n.startsWith("EXIT ")||n.startsWith("Command failed"),d=n.split(`
69
+ `).filter(p=>p.trim()&&!p.startsWith("EXIT ")),f=u?`${$.error}\u2717${$.reset}`:`${$.success}\u2713${$.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=u?d.slice(-3):d.slice(0,3),g=d.length-3,b=m.map((x,E)=>E===0?`${f} ${$.muted}${x.substring(0,120)}${$.reset}`:` ${$.muted}${x.substring(0,120)}${$.reset}`);if(g>0){let x=u?` ${$.subtle}${g} lines above\u2026${$.reset}`:` ${$.subtle}\u2026 +${g} lines${$.reset}`;u?b.unshift(x):b.push(x)}a=b.join(`
70
70
  `)}break}default:{let c=n.split(`
71
- `).filter(u=>u.trim()&&!u.startsWith("EXIT ")&&!u.startsWith("HINT:"));if(c.length>0){let u=c[0].trim().substring(0,90),d=c.length>1?` ${b.subtle}\u2026 +${c.length-1} lines${b.reset}`:"";a=`${b.muted}${u}${b.reset}${d}`}else a=`${r.label} complete`}}return`${i}${a}${b.reset}`}function S$(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=`
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`),n.size>0&&(l+=` \xB7 ${n.size} scanned`),l+=Le.reset,l}nf.exports={C:Le,formatToolCall:y$,formatResult:w$,getToolSpinnerText:x$,formatToolSummary:k$,formatSectionHeader:g$,formatMilestone:S$,getThinkingVerb:_$,setActiveModelForSpinner:b$,THINKING_VERBS:Qr}});var it=Z((PC,rf)=>{var{T:on}=Kt(),sl=on,v$=require("path"),of=["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=sl.bold,n=sl.reset,r=E$(of,on.banner_logo),i=s.yolo?` ${o}${on.banner_yolo}\u26A1 YOLO${n}`:"",a=s.gemini?` ${o}${on.banner_gemini}\u2726 GEMINI${n}`:"",l=Ka().version,c=e?v$.basename(e):null,u=`${on.banner_model}[${t||"model"}]${n}`,d=`${on.banner_version}[${c||"workspace"}]${n}`,f=[` ${on.banner_name}${o}nex-code${n} ${on.banner_version}v${l}${n}`,` ${u} ${d}`,` ${on.banner_logo}${o}terminal workbench${n} ${on.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),$=of[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(`
71
+ `).filter(u=>u.trim()&&!u.startsWith("EXIT ")&&!u.startsWith("HINT:"));if(c.length>0){let u=c[0].trim().substring(0,90),d=c.length>1?` ${$.subtle}\u2026 +${c.length-1} lines${$.reset}`:"";a=`${$.muted}${u}${$.reset}${d}`}else a=`${r.label} complete`}}return`${i}${a}${$.reset}`}function Rb(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=`
72
+ ${$.success}\u25C6${Le.reset} ${Le.bold}${t}${Le.reset}`;return l+=` ${$.subtle}\u2501\u2501${$.reset} ${Le.dim}${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),n.size>0&&(l+=` \xB7 ${n.size} scanned`),l+=Le.reset,l}of.exports={C:Le,formatToolCall:_b,formatResult:xb,getToolSpinnerText:Eb,formatToolSummary:Tb,formatSectionHeader:$b,formatMilestone:Rb,getThinkingVerb:vb,setActiveModelForSpinner:Sb,THINKING_VERBS:ei}});var at=Z((qC,lf)=>{var{T:rn}=Kt(),il=rn,Cb=require("path"),af=["01100110","01111110","01111110","01011010","01111110","00111100"];function Ab(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 Ob(t,e,s={}){let o=il.bold,n=il.reset,r=Ab(af,rn.banner_logo),i=s.yolo?` ${o}${rn.banner_yolo}\u26A1 YOLO${n}`:"",a=s.gemini?` ${o}${rn.banner_gemini}\u2726 GEMINI${n}`:"",l=Ja().version,c=e?Cb.basename(e):null,u=`${rn.banner_model}[${t||"model"}]${n}`,d=`${rn.banner_version}[${c||"workspace"}]${n}`,f=[` ${rn.banner_name}${o}nex-code${n} ${rn.banner_version}v${l}${n}`,` ${u} ${d}`,` ${rn.banner_logo}${o}terminal workbench${n} ${rn.muted}\xB7 /help${n}${a}${i}`,""],p=Math.max(r.length,f.length),m=Math.floor((p-r.length)/2),g=Math.floor((p-f.length)/2),b=af[0].length,x=[];for(let E=0;E<p;E++){let N=r[E-m]??" ".repeat(b),v=f[E-g]??"";x.push(N+v)}console.log(`
73
73
  `+x.join(`
74
74
  `)+`
75
- `)}var{Spinner:R$,MultiProgress:C$,TaskProgress:A$,ToolProgress:O$,setActiveTaskProgress:N$,getActiveTaskProgress:P$,cleanupTerminal:M$}=zn(),{formatToolCall:L$,formatResult:I$,getToolSpinnerText:j$,formatToolSummary:D$,formatSectionHeader:q$,formatMilestone:F$,getThinkingVerb:B$,setActiveModelForSpinner:U$}=sf();rf.exports={C:sl,banner:T$,Spinner:R$,MultiProgress:C$,TaskProgress:A$,ToolProgress:O$,setActiveTaskProgress:N$,getActiveTaskProgress:P$,cleanupTerminal:M$,formatToolCall:L$,formatResult:I$,getToolSpinnerText:j$,formatToolSummary:D$,formatSectionHeader:q$,formatMilestone:F$,getThinkingVerb:B$,setActiveModelForSpinner:U$}});var rl=Z((MC,af)=>{function ol(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var W$=ol();function H$(...t){ol()&&console.log(...t)}function Y$(...t){ol()&&console.warn(...t)}af.exports={DEBUG:W$,debugLog:H$,warnLog:Y$}});var uf=Z((LC,cf)=>{"use strict";var G$=new Set(["read_file","grep","glob","search_files","list_directory"]),z$=new Set(["write_file","edit_file","patch_file"]),K$=new Set(["bash"]),X$=new Set(["web_search","web_fetch","perplexity_search"]);function lf(t,e){let s=0,o=0,n=0,r=0,i=0;for(let[a,l]of t)i+=l,G$.has(a)&&(s+=l),z$.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 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,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:lf(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}};cf.exports={MilestoneTracker:il,_phaseName:lf}});var ei=Z((IC,df)=>{var ko=dt(),V$={"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 J$(){return ko.getActiveModel()}function Z$(t){return ko.setActiveModel(t)}function Q$(){return ko.getModelNames()}function eb(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 tb(t,e){let{C:s}=it(),{Spinner:o}=it(),n=new o("Thinking...");n.start();let r=!0,i="";try{let a=await ko.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}
76
- `),a}catch(a){throw n.stop(),a}}async function nb(t,e){return ko.callChat(t,e)}df.exports={MODELS:V$,getActiveModel:J$,setActiveModel:Z$,getModelNames:Q$,callOllamaStream:tb,callOllama:nb,parseToolArgs:eb}});var vo=Z((jC,yf)=>{var sb=require("readline"),{C:rn}=it(),ob=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,rb=/^=([\w-]+)/;function So(t){return typeof t!="string"?t:t.replace(ob,"").replace(rb,"$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/],ff=[...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 ib(t){for(let e of ff)if(e.test(t))return e;return null}var hf=[/\.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)/],ab=/\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 pf(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(c=>c.trim()).filter(Boolean).every(c=>n(c)):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(n)}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/],mf=[/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/],gf=[...ul,...mf],dl=!1,Xn=null,ll=null;function lb(t){dl=t}function cb(t){ll=t}function ub(){return dl}function db(t){Xn=t}function fb(t){let e=So(t);for(let s of cl)if(s.test(e))return s;return null}function hb(t){let e=So(t);if(/ssh\s/.test(e)&&pf(e))return!1;for(let s of gf)if(s.test(e))return!0;return!1}function pb(t){let e=So(t);for(let s of ul)if(s.test(e))return!0;return!1}function mb(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=So(t);if(!ab.test(e))return null;for(let s of hf)if(s.test(e))return s;return null}function gb(t,e={}){if(dl)return Promise.resolve(!0);if(ll)return ll(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return yb(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let n=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-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${rn.yellow}${t}${rn.reset}`;for(let h=0;h<s.length;h++){let m=h===n,g=m?`${rn.yellow}\u276F${rn.reset}`:" ",$=m?`${rn.yellow}${s[h]}${rn.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",u);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(),Xn&&Xn.resume(),o(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&ti(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
77
- `){c(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){ti(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function yb(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?(ti(e.toolName),o(!0)):o(i!=="n")};if(Xn)Xn.question(`${rn.yellow}${t} ${s}${rn.reset}`,n);else{let r=sb.createInterface({input:process.stdin,output:process.stdout});r.question(`${rn.yellow}${t} ${s}${rn.reset}`,i=>{r.close(),n(i)})}})}var ti=()=>{};function wb(t){ti=t}yf.exports={sanitizeBashCommand:So,FORBIDDEN_PATTERNS:cl,SSH_FORBIDDEN_PATTERNS:ff,BASH_PROTECTED_PATHS:hf,SSH_SAFE_PATTERNS:al,isSSHReadOnly:pf,DANGEROUS_BASH:gf,CRITICAL_BASH:ul,NOTABLE_BASH:mf,isForbidden:fb,isSSHForbidden:ib,isDangerous:hb,isCritical:pb,isBashPathForbidden:mb,confirm:gb,setAutoConfirm:lb,getAutoConfirm:ub,setConfirmHook:cb,setReadlineInterface:db,setAllowAlwaysHandler:wb}});var bf=Z((qC,$f)=>{var ni=require("path"),{C:D}=it(),{T:fl,isDark:DC}=Kt(),{confirm:$b,getAutoConfirm:bb}=vo(),wf=2e3;function Eo(t,e){let s=t.split(`
75
+ `)}var{Spinner:Nb,MultiProgress:Pb,TaskProgress:Mb,ToolProgress:Lb,setActiveTaskProgress:Ib,getActiveTaskProgress:jb,cleanupTerminal:Db}=Kn(),{formatToolCall:qb,formatResult:Fb,getToolSpinnerText:Bb,formatToolSummary:Ub,formatSectionHeader:Wb,formatMilestone:Hb,getThinkingVerb:Yb,setActiveModelForSpinner:Gb}=rf();lf.exports={C:il,banner:Ob,Spinner:Nb,MultiProgress:Pb,TaskProgress:Mb,ToolProgress:Lb,setActiveTaskProgress:Ib,getActiveTaskProgress:jb,cleanupTerminal:Db,formatToolCall:qb,formatResult:Fb,getToolSpinnerText:Bb,formatToolSummary:Ub,formatSectionHeader:Wb,formatMilestone:Hb,getThinkingVerb:Yb,setActiveModelForSpinner:Gb}});var ll=Z((FC,cf)=>{function al(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var zb=al();function Kb(...t){al()&&console.log(...t)}function Xb(...t){al()&&console.warn(...t)}cf.exports={DEBUG:zb,debugLog:Kb,warnLog:Xb}});var ff=Z((BC,df)=>{"use strict";var Vb=new Set(["read_file","grep","glob","search_files","list_directory"]),Jb=new Set(["write_file","edit_file","patch_file"]),Zb=new Set(["bash"]),Qb=new Set(["web_search","web_fetch","perplexity_search"]);function uf(t,e){let s=0,o=0,n=0,r=0,i=0;for(let[a,l]of t)i+=l,Vb.has(a)&&(s+=l),Jb.has(a)&&(o+=l),Zb.has(a)&&(n+=l),Qb.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 cl=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:uf(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}};df.exports={MilestoneTracker:cl,_phaseName:uf}});var ti=Z((UC,pf)=>{var ko=dt(),e$={"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 t$(){return ko.getActiveModel()}function n$(t){return ko.setActiveModel(t)}function s$(){return ko.getModelNames()}function o$(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 r$(t,e){let{C:s}=at(),{Spinner:o}=at(),n=new o("Thinking...");n.start();let r=!0,i="";try{let a=await ko.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}
76
+ `),a}catch(a){throw n.stop(),a}}async function i$(t,e){return ko.callChat(t,e)}pf.exports={MODELS:e$,getActiveModel:t$,setActiveModel:n$,getModelNames:s$,callOllamaStream:r$,callOllama:i$,parseToolArgs:o$}});var vo=Z((WC,bf)=>{var a$=require("readline"),{C:an}=at(),l$=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,c$=/^=([\w-]+)/;function So(t){return typeof t!="string"?t:t.replace(l$,"").replace(c$,"$1")}var fl=[/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/],hf=[...fl,/\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 u$(t){for(let e of hf)if(e.test(t))return e;return null}var mf=[/\.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)/],d$=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,ul=[/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 gf(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(c=>c.trim()).filter(Boolean).every(c=>n(c)):ul.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:ul.some(a=>a.test(i))};return o.every(n)}var pl=[/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/],yf=[/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/],wf=[...pl,...yf],hl=!1,Vn=null,dl=null;function f$(t){hl=t}function p$(t){dl=t}function h$(){return hl}function m$(t){Vn=t}function g$(t){let e=So(t);for(let s of fl)if(s.test(e))return s;return null}function y$(t){let e=So(t);if(/ssh\s/.test(e)&&gf(e))return!1;for(let s of wf)if(s.test(e))return!0;return!1}function w$(t){let e=So(t);for(let s of pl)if(s.test(e))return!0;return!1}function b$(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=So(t);if(!d$.test(e))return null;for(let s of mf)if(s.test(e))return s;return null}function $$(t,e={}){if(hl)return Promise.resolve(!0);if(dl)return dl(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return _$(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let n=0;Vn&&Vn.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${an.yellow}${t}${an.reset}`;for(let p=0;p<s.length;p++){let m=p===n,g=m?`${an.yellow}\u276F${an.reset}`:" ",b=m?`${an.yellow}${s[p]}${an.reset}`:s[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${b}`}r(f)},l=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),p=i(),m="";for(let g=0;g<s.length+1;g++)m+=`\x1B[${p+g};1H\x1B[2K`;f(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Vn&&Vn.resume(),o(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&ni(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
77
+ `){c(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 p=f.toLowerCase().trim();if(p==="y"){l(!0);return}if(p==="n"){l(!1);return}if(p==="a"&&e.toolName){ni(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function _$(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?(ni(e.toolName),o(!0)):o(i!=="n")};if(Vn)Vn.question(`${an.yellow}${t} ${s}${an.reset}`,n);else{let r=a$.createInterface({input:process.stdin,output:process.stdout});r.question(`${an.yellow}${t} ${s}${an.reset}`,i=>{r.close(),n(i)})}})}var ni=()=>{};function x$(t){ni=t}bf.exports={sanitizeBashCommand:So,FORBIDDEN_PATTERNS:fl,SSH_FORBIDDEN_PATTERNS:hf,BASH_PROTECTED_PATHS:mf,SSH_SAFE_PATTERNS:ul,isSSHReadOnly:gf,DANGEROUS_BASH:wf,CRITICAL_BASH:pl,NOTABLE_BASH:yf,isForbidden:g$,isSSHForbidden:u$,isDangerous:y$,isCritical:w$,isBashPathForbidden:b$,confirm:$$,setAutoConfirm:f$,getAutoConfirm:h$,setConfirmHook:p$,setReadlineInterface:m$,setAllowAlwaysHandler:x$}});var xf=Z((YC,_f)=>{var si=require("path"),{C:D}=at(),{T:ml,isDark:HC}=Kt(),{confirm:k$,getAutoConfirm:S$}=vo(),$f=2e3;function Eo(t,e){let s=t.split(`
78
78
  `),o=e.split(`
79
- `),n=[],r=s.length,i=o.length;if(r>wf||i>wf){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,c=i,u=[];for(;l>0||c>0;)l>0&&c>0&&s[l-1]===o[c-1]?(u.unshift({type:"same",line:s[l-1]}),l--,c--):c>0&&(l===0||a[l][c-1]>=a[l-1][c])?(u.unshift({type:"add",line:o[c-1]}),c--):(u.unshift({type:"remove",line:s[l-1]}),l--);return u}function _b(t,e,s,o=3){console.log(`
80
- ${D.bold}${D.cyan} Diff: ${t}${D.reset}`);let n=Eo(e,s),r=[];if(n.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${D.gray} (no changes)${D.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(`${D.gray} ...${D.reset}`);for(let l=i;l<a;l++){let c=n[l];switch(c.type){case"remove":console.log(`${D.red} - ${c.line}${D.reset}`);break;case"add":console.log(`${D.green} + ${c.line}${D.reset}`);break;default:console.log(`${D.gray} ${c.line}${D.reset}`)}}a<n.length&&console.log(`${D.gray} ...${D.reset}`),console.log()}function xb(t,e,s){console.log(`
81
- ${D.bold}${D.cyan} File exists \u2014 showing changes: ${t}${D.reset}`);let o=Eo(e,s),n=0;for(let i of o)i.type!=="same"&&n++;if(n===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} ...(${n-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 kb(t,e){console.log(`
79
+ `),n=[],r=s.length,i=o.length;if(r>$f||i>$f){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,c=i,u=[];for(;l>0||c>0;)l>0&&c>0&&s[l-1]===o[c-1]?(u.unshift({type:"same",line:s[l-1]}),l--,c--):c>0&&(l===0||a[l][c-1]>=a[l-1][c])?(u.unshift({type:"add",line:o[c-1]}),c--):(u.unshift({type:"remove",line:s[l-1]}),l--);return u}function v$(t,e,s,o=3){console.log(`
80
+ ${D.bold}${D.cyan} Diff: ${t}${D.reset}`);let n=Eo(e,s),r=[];if(n.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${D.gray} (no changes)${D.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(`${D.gray} ...${D.reset}`);for(let l=i;l<a;l++){let c=n[l];switch(c.type){case"remove":console.log(`${D.red} - ${c.line}${D.reset}`);break;case"add":console.log(`${D.green} + ${c.line}${D.reset}`);break;default:console.log(`${D.gray} ${c.line}${D.reset}`)}}a<n.length&&console.log(`${D.gray} ...${D.reset}`),console.log()}function E$(t,e,s){console.log(`
81
+ ${D.bold}${D.cyan} File exists \u2014 showing changes: ${t}${D.reset}`);let o=Eo(e,s),n=0;for(let i of o)i.type!=="same"&&n++;if(n===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} ...(${n-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 T$(t,e){console.log(`
82
82
  ${D.bold}${D.cyan} New file: ${t}${D.reset}`);let s=e.split(`
83
- `),o=s.slice(0,20);for(let n of o)console.log(`${D.green} + ${n}${D.reset}`);s.length>20&&console.log(`${D.gray} ...+${s.length-20} more lines${D.reset}`),console.log()}async function Sb(t){return bb()?!0:$b(` ${t}?`)}function vb(t,e,s,o){let n=o||process.stdout.columns||80,r=Math.floor((n-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,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 c=a.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(c.length===0){console.log(` ${D.gray}(no changes)${D.reset}`);return}let u=Math.max(0,c[0]-2),d=Math.min(a.length,c[c.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)};u>0&&console.log(` ${D.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${D.reset}`);for(let h=u;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 Eb(t,e,s,o={}){let n=o.label||"Update",r=o.context||3,i=o.annotations||[],a=ni.isAbsolute(t)?ni.relative(process.cwd(),t):t,l=Eo(e,s),c=1,u=1;for(let P of l)P.type==="same"?(P.oldLine=c++,P.newLine=u++):P.type==="remove"?(P.oldLine=c++,P.newLine=null):(P.oldLine=null,P.newLine=u++);let d=0,f=0;for(let P of l)P.type==="add"?d++:P.type==="remove"&&f++;if(console.log(`
83
+ `),o=s.slice(0,20);for(let n of o)console.log(`${D.green} + ${n}${D.reset}`);s.length>20&&console.log(`${D.gray} ...+${s.length-20} more lines${D.reset}`),console.log()}async function R$(t){return S$()?!0:k$(` ${t}?`)}function C$(t,e,s,o){let n=o||process.stdout.columns||80,r=Math.floor((n-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,s),a=[],l=0;for(;l<i.length;)if(i[l].type==="same")a.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let p=[];for(;l<i.length&&i[l].type==="remove";)p.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(p.length,m.length);for(let b=0;b<g;b++)a.push({left:b<p.length?p[b]:"",right:b<m.length?m[b]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let c=a.map((p,m)=>p.type!=="same"?m:-1).filter(p=>p>=0);if(c.length===0){console.log(` ${D.gray}(no changes)${D.reset}`);return}let u=Math.max(0,c[0]-2),d=Math.min(a.length,c[c.length-1]+3),f=(p,m)=>{let g=p.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?p.substring(0,m):p+" ".repeat(m-g.length)};u>0&&console.log(` ${D.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${D.reset}`);for(let p=u;p<d;p++){let m=a[p];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)}`,b=m.right?`${D.green}${f(m.right,r)}${D.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${b}`)}}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 A$(t,e,s,o={}){let n=o.label||"Update",r=o.context||3,i=o.annotations||[],a=si.isAbsolute(t)?si.relative(process.cwd(),t):t,l=Eo(e,s),c=1,u=1;for(let P of l)P.type==="same"?(P.oldLine=c++,P.newLine=u++):P.type==="remove"?(P.oldLine=c++,P.newLine=null):(P.oldLine=null,P.newLine=u++);let d=0,f=0;for(let P of l)P.type==="add"?d++:P.type==="remove"&&f++;if(console.log(`
86
86
  ${D.green}\u23FA${D.reset} ${D.bold}${n}(${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,se=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}`),se>0&&ce.push(`${D.cyan}${se} info${se!==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),se=Math.min(l.length-1,P+r);x===null?(x=ne,E=se):(ne<=E+1||($.push([x,E]),x=ne),E=se)}x!==null&&$.push([x,E]);let N=" ",v=process.stdout.columns||120;function S(P,ne,se){let ce=se.replace(/\x1b\[[0-9;]*m/g,""),de=se+" ".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,se]=$[P];for(let ce=ne;ce<=se;ce++){let de=l[ce],re=de.newLine!=null?de.newLine:de.oldLine,le=String(re).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 Tb(t,e,s={}){let o=ni.isAbsolute(t)?ni.relative(process.cwd(),t):t,n=e.split(`
87
+ `);return}let p=[];if(d>0&&p.push(`Added ${d} line${d!==1?"s":""}`),f>0&&p.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let P=i.filter(de=>de.severity==="error").length,ne=i.filter(de=>de.severity==="warn").length,se=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}`),se>0&&ce.push(`${D.cyan}${se} info${se!==1?"s":""}${D.dim}`),p.push(`found ${ce.join(", ")}`)}console.log(` ${D.dim}\u23BF ${p.join(", ")}${D.reset}`);let g=[];l.forEach((P,ne)=>{P.type!=="same"&&g.push(ne)});let b=[],x=null,E=null;for(let P of g){let ne=Math.max(0,P-r),se=Math.min(l.length-1,P+r);x===null?(x=ne,E=se):(ne<=E+1||(b.push([x,E]),x=ne),E=se)}x!==null&&b.push([x,E]);let N=" ",v=process.stdout.columns||120;function S(P,ne,se){let ce=se.replace(/\x1b\[[0-9;]*m/g,""),de=se+" ".repeat(Math.max(0,v-ce.length));return`${P}${ne}${de}${D.reset}`}for(let P=0;P<b.length;P++){P>0&&console.log(`${N}${D.dim}\xB7\xB7\xB7${D.reset}`);let[ne,se]=b[P];for(let ce=ne;ce<=se;ce++){let de=l[ce],re=de.newLine!=null?de.newLine:de.oldLine,le=String(re).padStart(4),T=de.type!=="remove"?i.filter(q=>q.line===de.newLine):[];de.type==="remove"?console.log(S(ml.diff_rem_bg,D.red,`${N}${le} - ${de.line}`)):de.type==="add"?console.log(S(ml.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 O$(t,e,s={}){let o=si.isAbsolute(t)?si.relative(process.cwd(),t):t,n=e.split(`
88
88
  `),r=s.annotations||[];console.log(`
89
- ${D.green}\u23FA${D.reset} ${D.bold}Create(${o})${D.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(`${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=" ",c=process.stdout.columns||120,u=Math.min(n.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),h=d+1,m=r.filter(E=>E.line===h),g=`${l}${f} + ${n[d]}`,$=g.replace(/\x1b\[[0-9;]*m/g,""),x=g+" ".repeat(Math.max(0,c-$.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}`)}}n.length>20&&console.log(`${l}${D.dim} ...+${n.length-20} more lines${D.reset}`),console.log()}$f.exports={diffLines:Eo,showEditDiff:_b,showWriteDiff:xb,showNewFilePreview:kb,confirmFileChange:Sb,showSideBySideDiff:vb,showDiff:Eb,showNewFile:Tb}});var ri=Z((FC,kf)=>{var _f=require("util").promisify(require("child_process").exec),Rb=require("util").promisify(require("child_process").execFile),{C:We}=it();async function hl(t){try{let{stdout:e}=await _f(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function si(...t){try{let{stdout:e}=await Rb("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Cb(){return await hl("git rev-parse --is-inside-work-tree")==="true"}async function Ab(){return await hl("git branch --show-current")}async function pl(){try{let{stdout:t}=await _f("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
90
- `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),o=e.substring(3);return{status:s,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 xf(){let t=await ml();if(t.length===0)return null;let e=await oi(),o=await oi(!0)||e,n=0,r=0;if(o){let u=o.split(`
91
- `);for(let d of u)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(u=>u.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 Ob(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await si("checkout","-b",s)!==null?s:null}async function Nb(t){return await si("add","-A"),await si("commit","-m",t)?await si("rev-parse","--short","HEAD"):null}async function Pb(){let t=await xf();if(!t)return`${We.dim}No changes${We.reset}`;let e=[];e.push(`
89
+ ${D.green}\u23FA${D.reset} ${D.bold}Create(${o})${D.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,p=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}`),p>0&&m.push(`${D.cyan}${p} info${p!==1?"s":""}${D.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${D.dim}\u23BF ${i.join(", ")}${D.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(n.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),p=d+1,m=r.filter(E=>E.line===p),g=`${l}${f} + ${n[d]}`,b=g.replace(/\x1b\[[0-9;]*m/g,""),x=g+" ".repeat(Math.max(0,c-b.length));console.log(`${ml.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}`)}}n.length>20&&console.log(`${l}${D.dim} ...+${n.length-20} more lines${D.reset}`),console.log()}_f.exports={diffLines:Eo,showEditDiff:v$,showWriteDiff:E$,showNewFilePreview:T$,confirmFileChange:R$,showSideBySideDiff:C$,showDiff:A$,showNewFile:O$}});var ii=Z((GC,vf)=>{var kf=require("util").promisify(require("child_process").exec),N$=require("util").promisify(require("child_process").execFile),{C:We}=at();async function gl(t){try{let{stdout:e}=await kf(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function oi(...t){try{let{stdout:e}=await N$("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function P$(){return await gl("git rev-parse --is-inside-work-tree")==="true"}async function M$(){return await gl("git branch --show-current")}async function yl(){try{let{stdout:t}=await kf("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
90
+ `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),o=e.substring(3);return{status:s,file:o}})}catch{return[]}}async function ri(t=!1){return await gl(`git diff ${t?"--cached":""}`)||""}async function wl(){return(await yl()).map(e=>e.file)}async function Sf(){let t=await wl();if(t.length===0)return null;let e=await ri(),o=await ri(!0)||e,n=0,r=0;if(o){let u=o.split(`
91
+ `);for(let d of u)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(u=>u.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 L$(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await oi("checkout","-b",s)!==null?s:null}async function I$(t){return await oi("add","-A"),await oi("commit","-m",t)?await oi("rev-parse","--short","HEAD"):null}async function j$(){let t=await Sf();if(!t)return`${We.dim}No changes${We.reset}`;let e=[];e.push(`
92
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
93
  ${We.bold}${We.cyan}Files:${We.reset}`);for(let s of t.files.slice(0,20))e.push(` ${We.dim}${s}${We.reset}`);return t.files.length>20&&e.push(` ${We.dim}...+${t.files.length-20} more${We.reset}`),e.push(`
94
94
  ${We.bold}${We.cyan}Suggested message:${We.reset}`),e.push(` ${We.cyan}${t.summary}${We.reset}
95
95
  `),e.join(`
96
- `)}async function Mb(){return(await pl()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Lb(){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 s=await oi();if(s){let o=s.length>5e3?s.substring(0,5e3)+`
96
+ `)}async function D$(){return(await yl()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function q$(){let t=await wl();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 ri();if(s){let o=s.length>5e3?s.substring(0,5e3)+`
97
97
  ...(truncated)`:s;e.push(`
98
98
  DIFF:
99
99
  ${o}`)}return e.join(`
100
- `)}kf.exports={isGitRepo:Cb,getCurrentBranch:Ab,getStatus:pl,getDiff:oi,getChangedFiles:ml,analyzeDiff:xf,createBranch:Ob,commit:Nb,formatDiffSummary:Pb,getDiffContext:Lb,getMergeConflicts:Mb}});var Of=Z((UC,Af)=>{var at=require("fs").promises,BC=require("fs"),jt=require("path"),Ib=require("crypto"),{execSync:gl,execFileSync:Ef}=require("child_process"),jb=100*1024,Tf=50,_t=[],Us=[];function Db(t,e,s,o){for(_t.push({tool:t,filePath:e,oldContent:s,newContent:o,timestamp:Date.now()});_t.length>Tf;)_t.shift();Us.length=0,Rf(_t[_t.length-1]).catch(()=>{})}async function qb(){if(_t.length===0)return null;let t=_t.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 Fb(){if(Us.length===0)return null;let t=Us.pop();return await at.writeFile(t.filePath,t.newContent,"utf-8"),_t.push(t),{tool:t.tool,filePath:t.filePath}}function Bb(t=10){return _t.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Ub(){return _t.length}function Wb(){return Us.length}function Hb({diskToo:t=!0}={}){if(_t.length=0,Us.length=0,t){let e=ai();at.readdir(e).then(s=>{for(let o of s)o.endsWith(".json")&&at.unlink(jt.join(e,o)).catch(()=>{})}).catch(()=>{})}}function ai(){return jt.join(process.cwd(),".nex","history")}async function Sf(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=jb)return{inline:!0,content:t};let s=Ib.createHash("sha256").update(t,"utf-8").digest("hex"),o=jt.join(e,"blobs");return await at.mkdir(o,{recursive:!0}),await at.writeFile(jt.join(o,s),t,"utf-8"),{inline:!1,hash:s}}async function Rf(t){let e=ai();await at.mkdir(e,{recursive:!0});let s=jt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${s}.json`,n=await Sf(t.oldContent,e),r=await Sf(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 at.writeFile(jt.join(e,o),JSON.stringify(i),"utf-8")}async function vf(t,e){if(!t)return null;if(t.inline)return t.content;let s=jt.join(e,"blobs",t.hash);return at.readFile(s,"utf-8")}async function Yb(){let t=ai(),e;try{e=await at.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 at.readFile(jt.join(t,n),"utf-8"),i=JSON.parse(r),a=await vf(i.oldContent,t),l=await vf(i.newContent,t);_t.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),o++}catch{}for(;_t.length>Tf;)_t.shift();return o}async function Gb(t=7){let e=ai(),s;try{s=await at.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,n=s.filter(c=>c.endsWith(".json")),r=0,i=new Set,a=[];for(let c of n)try{let u=await at.readFile(jt.join(e,c),"utf-8"),d=JSON.parse(u);d.timestamp<o?(a.push(c),r++):(d.oldContent&&!d.oldContent.inline&&d.oldContent.hash&&i.add(d.oldContent.hash),d.newContent&&!d.newContent.inline&&d.newContent.hash&&i.add(d.newContent.hash))}catch{}for(let c of a)try{await at.unlink(jt.join(e,c))}catch{}let l=jt.join(e,"blobs");try{let c=await at.readdir(l);for(let u of c)if(!i.has(u))try{await at.unlink(jt.join(l,u))}catch{}}catch{}return r}var ii="nex-snapshot";function zb(t,e=process.cwd()){let s=t?`${ii}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${ii}-${Date.now()}`;try{return gl("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Ef("git",["stash","push","-u","-m",s],{cwd:e,timeout:15e3}),gl("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 Cf(t=process.cwd()){try{let e=gl("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
101
- `).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(ii)?{index:parseInt(o[1],10),label:n,shortName:n.replace(`${ii}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function Kb(t,e=process.cwd()){try{let s=Cf(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?(Ef("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}}}Af.exports={recordChange:Db,undo:qb,redo:Fb,getHistory:Bb,getUndoCount:Ub,getRedoCount:Wb,clearHistory:Hb,persistEntry:Rf,loadPersistedHistory:Yb,pruneHistory:Gb,createSnapshot:zb,listSnapshots:Cf,restoreSnapshot:Kb}});var _l=Z((WC,jf)=>{var je=require("fs"),xt=require("path"),{atomicWrite:Xb,withFileLockSync:Vb}=Gn(),pt=[];function To(){return xt.join(process.cwd(),".nex","skills")}function Nf(){return xt.join(process.cwd(),".nex","config.json")}function Pf(){let t=To();return je.existsSync(t)||je.mkdirSync(t,{recursive:!0}),t}function $l(){let t=Nf();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 Mf(t){let e=Nf(),s=xt.dirname(e);je.existsSync(s)||je.mkdirSync(s,{recursive:!0}),Vb(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,Xb(e,JSON.stringify(o,null,2))})}function Lf(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 If(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(`
102
- `)){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 yl(t){try{let e=je.readFileSync(t,"utf-8").trim();if(!e)return null;let s=xt.basename(t,".md"),{triggers:o,body:n}=If(e);return{name:s,type:"prompt",filePath:t,instructions:n||e,triggers:o,commands:[],tools:[]}}catch{return null}}function wl(t){try{let e=require(t),{valid:s,errors:o}=Lf(e,t);return s?{name:e.name||xt.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
+ `)}vf.exports={isGitRepo:P$,getCurrentBranch:M$,getStatus:yl,getDiff:ri,getChangedFiles:wl,analyzeDiff:Sf,createBranch:L$,commit:I$,formatDiffSummary:j$,getDiffContext:q$,getMergeConflicts:D$}});var Pf=Z((KC,Nf)=>{var lt=require("fs").promises,zC=require("fs"),qt=require("path"),F$=require("crypto"),{execSync:bl,execFileSync:Rf}=require("child_process"),B$=100*1024,Cf=50,_t=[],Us=[];function U$(t,e,s,o){for(_t.push({tool:t,filePath:e,oldContent:s,newContent:o,timestamp:Date.now()});_t.length>Cf;)_t.shift();Us.length=0,Af(_t[_t.length-1]).catch(()=>{})}async function W$(){if(_t.length===0)return null;let t=_t.pop();if(t.oldContent===null)try{await lt.unlink(t.filePath)}catch{}else await lt.writeFile(t.filePath,t.oldContent,"utf-8");return Us.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function H$(){if(Us.length===0)return null;let t=Us.pop();return await lt.writeFile(t.filePath,t.newContent,"utf-8"),_t.push(t),{tool:t.tool,filePath:t.filePath}}function Y$(t=10){return _t.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function G$(){return _t.length}function z$(){return Us.length}function K$({diskToo:t=!0}={}){if(_t.length=0,Us.length=0,t){let e=li();lt.readdir(e).then(s=>{for(let o of s)o.endsWith(".json")&&lt.unlink(qt.join(e,o)).catch(()=>{})}).catch(()=>{})}}function li(){return qt.join(process.cwd(),".nex","history")}async function Ef(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=B$)return{inline:!0,content:t};let s=F$.createHash("sha256").update(t,"utf-8").digest("hex"),o=qt.join(e,"blobs");return await lt.mkdir(o,{recursive:!0}),await lt.writeFile(qt.join(o,s),t,"utf-8"),{inline:!1,hash:s}}async function Af(t){let e=li();await lt.mkdir(e,{recursive:!0});let s=qt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${s}.json`,n=await Ef(t.oldContent,e),r=await Ef(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 lt.writeFile(qt.join(e,o),JSON.stringify(i),"utf-8")}async function Tf(t,e){if(!t)return null;if(t.inline)return t.content;let s=qt.join(e,"blobs",t.hash);return lt.readFile(s,"utf-8")}async function X$(){let t=li(),e;try{e=await lt.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 lt.readFile(qt.join(t,n),"utf-8"),i=JSON.parse(r),a=await Tf(i.oldContent,t),l=await Tf(i.newContent,t);_t.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),o++}catch{}for(;_t.length>Cf;)_t.shift();return o}async function V$(t=7){let e=li(),s;try{s=await lt.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,n=s.filter(c=>c.endsWith(".json")),r=0,i=new Set,a=[];for(let c of n)try{let u=await lt.readFile(qt.join(e,c),"utf-8"),d=JSON.parse(u);d.timestamp<o?(a.push(c),r++):(d.oldContent&&!d.oldContent.inline&&d.oldContent.hash&&i.add(d.oldContent.hash),d.newContent&&!d.newContent.inline&&d.newContent.hash&&i.add(d.newContent.hash))}catch{}for(let c of a)try{await lt.unlink(qt.join(e,c))}catch{}let l=qt.join(e,"blobs");try{let c=await lt.readdir(l);for(let u of c)if(!i.has(u))try{await lt.unlink(qt.join(l,u))}catch{}}catch{}return r}var ai="nex-snapshot";function J$(t,e=process.cwd()){let s=t?`${ai}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${ai}-${Date.now()}`;try{return bl("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Rf("git",["stash","push","-u","-m",s],{cwd:e,timeout:15e3}),bl("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 Of(t=process.cwd()){try{let e=bl("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
101
+ `).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(ai)?{index:parseInt(o[1],10),label:n,shortName:n.replace(`${ai}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function Z$(t,e=process.cwd()){try{let s=Of(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?(Rf("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}}}Nf.exports={recordChange:U$,undo:W$,redo:H$,getHistory:Y$,getUndoCount:G$,getRedoCount:z$,clearHistory:K$,persistEntry:Af,loadPersistedHistory:X$,pruneHistory:V$,createSnapshot:J$,listSnapshots:Of,restoreSnapshot:Z$}});var Sl=Z((XC,qf)=>{var je=require("fs"),xt=require("path"),{atomicWrite:Q$,withFileLockSync:e_}=zn(),ht=[];function To(){return xt.join(process.cwd(),".nex","skills")}function Mf(){return xt.join(process.cwd(),".nex","config.json")}function Lf(){let t=To();return je.existsSync(t)||je.mkdirSync(t,{recursive:!0}),t}function xl(){let t=Mf();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 If(t){let e=Mf(),s=xt.dirname(e);je.existsSync(s)||je.mkdirSync(s,{recursive:!0}),e_(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,Q$(e,JSON.stringify(o,null,2))})}function jf(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 Df(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(`
102
+ `)){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 $l(t){try{let e=je.readFileSync(t,"utf-8").trim();if(!e)return null;let s=xt.basename(t,".md"),{triggers:o,body:n}=Df(e);return{name:s,type:"prompt",filePath:t,instructions:n||e,triggers:o,commands:[],tools:[]}}catch{return null}}function _l(t){try{let e=require(t),{valid:s,errors:o}=jf(e,t);return s?{name:e.name||xt.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}
103
103
  ${o.join(`
104
- `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function bl(){pt=[];let t=$l(),e=To(),s=[];if(je.existsSync(e))try{s=je.readdirSync(e)}catch{s=[]}for(let n of s){let r=xt.join(e,n),i;try{i=je.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;n.endsWith(".md")?a=yl(r):n.endsWith(".js")&&(a=wl(r)),a&&(a.enabled=!t.includes(a.name),pt.push(a))}let o=xt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&je.existsSync(o)){let n;try{n=je.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{n=[]}for(let r of n){let i=xt.join(o,r),a=xt.basename(r,xt.extname(r));if(pt.some(u=>u.name===a))continue;let l;try{l=je.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?yl(i):wl(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),pt.push(c))}}return pt}function Jb(){let t=[];for(let e of pt)!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 kl(){ht=[];let t=xl(),e=To(),s=[];if(je.existsSync(e))try{s=je.readdirSync(e)}catch{s=[]}for(let n of s){let r=xt.join(e,n),i;try{i=je.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;n.endsWith(".md")?a=$l(r):n.endsWith(".js")&&(a=_l(r)),a&&(a.enabled=!t.includes(a.name),ht.push(a))}let o=xt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&je.existsSync(o)){let n;try{n=je.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{n=[]}for(let r of n){let i=xt.join(o,r),a=xt.basename(r,xt.extname(r));if(ht.some(u=>u.name===a))continue;let l;try{l=je.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?$l(i):_l(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),ht.push(c))}}return ht}function t_(){let t=[];for(let e of ht)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
105
105
  ${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
106
106
  ${t.join(`
107
107
 
108
- `)}`}function Zb(){let t=[];for(let e of pt)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function Qb(){let t=[];for(let e of pt)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 e_(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let o of pt)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 t_(t){let[e,...s]=t.split(/\s+/),o=s.join(" ").trim();for(let n of pt)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 n_(){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 s_(t){let e=pt.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let s=$l().filter(o=>o!==t);return Mf(s),!0}function o_(t){let e=pt.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let s=$l();return s.includes(t)||(s.push(t),Mf(s)),!0}function r_(){return pt}async function i_(t,e={}){let{execFileSync:s}=require("child_process"),o=Pf(),n=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(n=`https://github.com/${t}.git`);let r=e.name||xt.basename(n,".git").replace(/^nex-skill-/,""),i=xt.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(n))throw new Error(`Invalid git URL: ${n}`);s("git",["clone","--depth","1",n,i],{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=xt.join(i,"skill.json"),l=je.existsSync(a),c=je.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{je.rmSync(i,{recursive:!0,force:!0})}catch(u){console.error("skills.js line 562 failed:",u.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let u=JSON.parse(je.readFileSync(a,"utf-8"));u.name||(u.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 a_(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 l_(t){let e=xt.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(s){return{ok:!1,error:s.message}}}function c_(t){if(!t)return[];let e=t.toLowerCase(),s=[];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(`
108
+ `)}`}function n_(){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 s_(){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 o_(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 r_(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 i_(){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 a_(t){let e=ht.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let s=xl().filter(o=>o!==t);return If(s),!0}function l_(t){let e=ht.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let s=xl();return s.includes(t)||(s.push(t),If(s)),!0}function c_(){return ht}async function u_(t,e={}){let{execFileSync:s}=require("child_process"),o=Lf(),n=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(n=`https://github.com/${t}.git`);let r=e.name||xt.basename(n,".git").replace(/^nex-skill-/,""),i=xt.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(n))throw new Error(`Invalid git URL: ${n}`);s("git",["clone","--depth","1",n,i],{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=xt.join(i,"skill.json"),l=je.existsSync(a),c=je.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{je.rmSync(i,{recursive:!0,force:!0})}catch(u){console.error("skills.js line 562 failed:",u.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let u=JSON.parse(je.readFileSync(a,"utf-8"));u.name||(u.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 kl(),{ok:!0,name:r}}async function d_(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 f_(t){let e=xt.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}),kl(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function p_(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(`
109
109
  `).slice(0,3).join(`
110
- `);s.push({name:o.name,instructions:r})}}return s}jf.exports={initSkillsDir:Pf,loadAllSkills:bl,getSkillInstructions:Jb,getSkillCommands:Zb,getSkillToolDefinitions:Qb,routeSkillCall:e_,handleSkillCommand:t_,listSkills:n_,enableSkill:s_,disableSkill:o_,getLoadedSkills:r_,installSkill:i_,searchSkills:a_,removeSkill:l_,matchSkillTriggers:c_,_getSkillsDir:To,_validateScriptSkill:Lf,_loadMarkdownSkill:yl,_loadScriptSkill:wl,_parseFrontmatter:If}});var kl=Z((HC,Wf)=>{var{spawn:u_}=require("child_process"),d_=require("path"),Df=require("fs"),bn=new Map;function f_(){return d_.join(process.cwd(),".nex","config.json")}function xl(){let t=f_();if(!Df.existsSync(t))return{};try{return JSON.parse(Df.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function li(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})+`
111
- `,l="",c=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},o);function u(f){l+=f.toString();let h=l.split(`
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)}`)):n(g.result);return}}catch{}l=h[h.length-1]||""}function d(){clearTimeout(c),t.stdout.removeListener("data",u)}t.stdout.on("data",u);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function qf(t,e){if(bn.has(t))return bn.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=u_(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:n,tools:[],config:e};try{await li(n,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await li(n,"tools/list",{});return r.tools=i&&i.tools||[],bn.set(t,r),r}catch(i){throw n.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Ff(t){let e=bn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return bn.delete(t),!0}function h_(){for(let[t]of bn)Ff(t)}async function Bf(t,e,s={}){let o=bn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let n=await li(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(`
113
- `):JSON.stringify(n)}function Uf(){let t=[];for(let[e,s]of bn)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 p_(){return Uf().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function m_(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 Bf(o,n,e)}function g_(){let t=xl();return Object.entries(t).map(([e,s])=>{let o=bn.get(e);return{name:e,command:s.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function y_(){let t=xl(),e=[];for(let[s,o]of Object.entries(t))try{let n=await qf(s,o);e.push({name:s,tools:n.tools.length})}catch(n){e.push({name:s,tools:0,error:n.message})}return e}Wf.exports={loadMCPConfig:xl,sendRequest:li,connectServer:qf,disconnectServer:Ff,disconnectAll:h_,callTool:Bf,getAllTools:Uf,getMCPToolDefinitions:p_,routeMCPCall:m_,listServers:g_,connectAll:y_}});var ui=Z((YC,zf)=>{var Hf=require("fs"),Sl=require("path"),ci=[],Ro=[],Vn={},Co=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Yf(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 Ro.some(o=>o.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(Ro.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Gf(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 s=Vn[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 w_(){let t=Sl.join(process.cwd(),".nex","plugins"),e=[];if(!Hf.existsSync(t))return{loaded:0,errors:[]};let s=Hf.readdirSync(t).filter(n=>n.endsWith(".js")),o={registerTool:Yf,registerHook:Gf,EVENTS:Co};for(let n of s){let r=Sl.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}ci.push({name:i.name||Sl.basename(n,".js"),filePath:r})}catch(i){e.push(`${n}: ${i.message}`)}}return{loaded:ci.length,errors:e}}function $_(){return Ro.map(t=>t.definition)}async function b_(t,e,s={}){let o=Ro.find(a=>a.definition.function.name===t);if(!o)return null;let n=await vl("beforeToolExec",{name:t,args:e,options:s}),r=await o.handler(n.args||e,s);return(await vl("afterToolExec",{name:t,args:e,result:r})).result||r}function __(){return[...ci]}function x_(){let t={};for(let e of Co)t[e]=(Vn[e]||[]).length;return t}function k_(){ci.length=0,Ro.length=0;for(let t of Object.keys(Vn))delete Vn[t]}zf.exports={registerTool:Yf,registerHook:Gf,emit:vl,loadPlugins:w_,getPluginToolDefinitions:$_,executePluginTool:b_,getLoadedPlugins:__,getHookCounts:x_,clearPlugins:k_,EVENTS:Co}});var El=Z((GC,Jf)=>{var{getSkillToolDefinitions:S_}=_l(),{getMCPToolDefinitions:v_}=kl(),{getPluginToolDefinitions:E_}=ui(),di=new Map;function Kf(){let{TOOL_DEFINITIONS:t}=Ao();return[...t,...S_(),...v_(),...E_()]}function Xf(t){if(di.has(t))return di.get(t);let s=Kf().find(n=>n.function.name===t);if(!s)return null;let o=s.function.parameters;return di.set(t,o),o}function T_(){di.clear()}function fi(t,e){if(!t||e.length===0)return null;let s=null,o=1/0;for(let n of e){let r=Vf(t.toLowerCase(),n.toLowerCase());r<o&&(o=r,s=n)}return o<=Math.ceil(t.length/2)?s:null}function Vf(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 R_(t,e){let s=Xf(t);if(s===null){let d=Kf().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(!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 u of o)if(!(u in e)||e[u]===void 0||e[u]===null){let d=fi(u,r);d&&!n.includes(d)?(a[u]=e[d],delete a[d],l=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!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 u of Object.keys(a))if(!n.includes(u)){let d=fi(u,n);if(d&&!(d in a))a[d]=a[u],delete a[u],l=!0;else if(!l){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${u}".${f}`)}}for(let u of Object.keys(a)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof a[u];d==="string"&&f==="number"?(a[u]=String(a[u]),l=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),l=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
110
+ `);s.push({name:o.name,instructions:r})}}return s}qf.exports={initSkillsDir:Lf,loadAllSkills:kl,getSkillInstructions:t_,getSkillCommands:n_,getSkillToolDefinitions:s_,routeSkillCall:o_,handleSkillCommand:r_,listSkills:i_,enableSkill:a_,disableSkill:l_,getLoadedSkills:c_,installSkill:u_,searchSkills:d_,removeSkill:f_,matchSkillTriggers:p_,_getSkillsDir:To,_validateScriptSkill:jf,_loadMarkdownSkill:$l,_loadScriptSkill:_l,_parseFrontmatter:Df}});var El=Z((VC,Yf)=>{var{spawn:h_}=require("child_process"),m_=require("path"),Ff=require("fs"),$n=new Map;function g_(){return m_.join(process.cwd(),".nex","config.json")}function vl(){let t=g_();if(!Ff.existsSync(t))return{};try{return JSON.parse(Ff.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function ci(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})+`
111
+ `,l="",c=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},o);function u(f){l+=f.toString();let p=l.split(`
112
+ `);for(let m of p)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):n(g.result);return}}catch{}l=p[p.length-1]||""}function d(){clearTimeout(c),t.stdout.removeListener("data",u)}t.stdout.on("data",u);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function Bf(t,e){if($n.has(t))return $n.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=h_(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:n,tools:[],config:e};try{await ci(n,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await ci(n,"tools/list",{});return r.tools=i&&i.tools||[],$n.set(t,r),r}catch(i){throw n.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Uf(t){let e=$n.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return $n.delete(t),!0}function y_(){for(let[t]of $n)Uf(t)}async function Wf(t,e,s={}){let o=$n.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let n=await ci(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(`
113
+ `):JSON.stringify(n)}function Hf(){let t=[];for(let[e,s]of $n)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 w_(){return Hf().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function b_(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 Wf(o,n,e)}function $_(){let t=vl();return Object.entries(t).map(([e,s])=>{let o=$n.get(e);return{name:e,command:s.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function __(){let t=vl(),e=[];for(let[s,o]of Object.entries(t))try{let n=await Bf(s,o);e.push({name:s,tools:n.tools.length})}catch(n){e.push({name:s,tools:0,error:n.message})}return e}Yf.exports={loadMCPConfig:vl,sendRequest:ci,connectServer:Bf,disconnectServer:Uf,disconnectAll:y_,callTool:Wf,getAllTools:Hf,getMCPToolDefinitions:w_,routeMCPCall:b_,listServers:$_,connectAll:__}});var di=Z((JC,Xf)=>{var Gf=require("fs"),Tl=require("path"),ui=[],Ro=[],Jn={},Co=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function zf(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 Ro.some(o=>o.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(Ro.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Kf(t,e){return Co.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Jn[t]||(Jn[t]=[]),Jn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Co.join(", ")}`}}async function Rl(t,e){let s=Jn[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 x_(){let t=Tl.join(process.cwd(),".nex","plugins"),e=[];if(!Gf.existsSync(t))return{loaded:0,errors:[]};let s=Gf.readdirSync(t).filter(n=>n.endsWith(".js")),o={registerTool:zf,registerHook:Kf,EVENTS:Co};for(let n of s){let r=Tl.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}ui.push({name:i.name||Tl.basename(n,".js"),filePath:r})}catch(i){e.push(`${n}: ${i.message}`)}}return{loaded:ui.length,errors:e}}function k_(){return Ro.map(t=>t.definition)}async function S_(t,e,s={}){let o=Ro.find(a=>a.definition.function.name===t);if(!o)return null;let n=await Rl("beforeToolExec",{name:t,args:e,options:s}),r=await o.handler(n.args||e,s);return(await Rl("afterToolExec",{name:t,args:e,result:r})).result||r}function v_(){return[...ui]}function E_(){let t={};for(let e of Co)t[e]=(Jn[e]||[]).length;return t}function T_(){ui.length=0,Ro.length=0;for(let t of Object.keys(Jn))delete Jn[t]}Xf.exports={registerTool:zf,registerHook:Kf,emit:Rl,loadPlugins:x_,getPluginToolDefinitions:k_,executePluginTool:S_,getLoadedPlugins:v_,getHookCounts:E_,clearPlugins:T_,EVENTS:Co}});var Cl=Z((ZC,Qf)=>{var{getSkillToolDefinitions:R_}=Sl(),{getMCPToolDefinitions:C_}=El(),{getPluginToolDefinitions:A_}=di(),fi=new Map;function Vf(){let{TOOL_DEFINITIONS:t}=Ao();return[...t,...R_(),...C_(),...A_()]}function Jf(t){if(fi.has(t))return fi.get(t);let s=Vf().find(n=>n.function.name===t);if(!s)return null;let o=s.function.parameters;return fi.set(t,o),o}function O_(){fi.clear()}function pi(t,e){if(!t||e.length===0)return null;let s=null,o=1/0;for(let n of e){let r=Zf(t.toLowerCase(),n.toLowerCase());r<o&&(o=r,s=n)}return o<=Math.ceil(t.length/2)?s:null}function Zf(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=Jf(t);if(s===null){let d=Vf().map(p=>p.function.name),f=pi(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
114
+ 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 u of o)if(!(u in e)||e[u]===void 0||e[u]===null){let d=pi(u,r);d&&!n.includes(d)?(a[u]=e[d],delete a[d],l=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!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 u of Object.keys(a))if(!n.includes(u)){let d=pi(u,n);if(d&&!(d in a))a[d]=a[u],delete a[u],l=!0;else if(!l){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${u}".${f}`)}}for(let u of Object.keys(a)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof a[u];d==="string"&&f==="number"?(a[u]=String(a[u]),l=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),l=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
115
115
  `+i.map(u=>` - ${u}`).join(`
116
116
  `)+`
117
117
 
118
- Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function C_(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}}Jf.exports={validateToolArgs:R_,validateToolCallFormat:C_,closestMatch:fi,levenshtein:Vf,getCachedSchema:Xf,clearSchemaCache:T_}});var th=Z((zC,eh)=>{var{levenshtein:hi}=El(),A_=200,O_=.3,N_=2;function Tl(t){return t.replace(/\r\n/g,`
118
+ Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function P_(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}}Qf.exports={validateToolArgs:N_,validateToolCallFormat:P_,closestMatch:pi,levenshtein:Zf,getCachedSchema:Jf,clearSchemaCache:O_}});var sp=Z((QC,np)=>{var{levenshtein:hi}=Cl(),M_=200,L_=.3,I_=2;function Al(t){return t.replace(/\r\n/g,`
119
119
  `).replace(/\r/g,`
120
- `).replace(/\t/g," ".repeat(N_)).split(`
120
+ `).replace(/\t/g," ".repeat(I_)).split(`
121
121
  `).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(`
122
- `)}function P_(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=Tl(t),o=Tl(e);if(!s.includes(o))return null;let n=t.split(`
122
+ `)}function j_(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=Al(t),o=Al(e);if(!s.includes(o))return null;let n=t.split(`
123
123
  `),r=s.split(`
124
124
  `),i=o.split(`
125
125
  `),a=i[0],l=i[i.length-1];for(let c=0;c<=r.length-i.length;c++){let u=!0;for(let d=0;d<i.length;d++)if(r[c+d]!==i[d]){u=!1;break}if(u)return n.slice(c,c+i.length).join(`
126
- `)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(o)!==-1)return n[c]}return null}function M_(t,e){if(!t||!e)return null;let s=t.split(`
126
+ `)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(o)!==-1)return n[c]}return null}function D_(t,e){if(!t||!e)return null;let s=t.split(`
127
127
  `),n=e.split(`
128
- `).length;return s.length===0||n===0?null:n===1?L_(s,e):j_(s,e,n)}function Zf(t){return Math.max(1,Math.floor(t/A_))}function Qf(t,e){return t<=Math.ceil(e*O_)}function L_(t,e){let s=e.trim(),o=Zf(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=hi(a.trim(),s);l<r&&(r=l,n={text:a,distance:l,line:i+1})}return n&&o>1&&(n=I_(t,s,n,o)||n,r=n.distance),Qf(r,e.length)?n:null}function I_(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 c=r;c<=i;c++){let u=t[c];if(!u.trim())continue;let d=hi(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function j_(t,e,s){let o=t.length-s+1;if(o<=0)return null;let n=Zf(o),r=null,i=1/0;for(let a=0;a<o;a+=n){let l=t.slice(a,a+s).join(`
129
- `),c=hi(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&n>1&&(r=D_(t,e,r,n,s,o)||r,i=r.distance),Qf(i,e.length)?r:null}function D_(t,e,s,o,n,r){let i=s.line-1,a=Math.max(0,i-o),l=Math.min(r-1,i+o),c=s.distance,u=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+n).join(`
130
- `),h=hi(f,e);h<c&&(c=h,u={text:f,distance:h,line:d+1})}return u}eh.exports={normalizeWhitespace:Tl,fuzzyFindText:P_,findMostSimilar:M_}});var uh=Z((KC,Cl)=>{var nh=require("fs"),q_=require("path"),{execFileSync:F_}=require("child_process"),sh=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],B_=/(^|\/)(tests\/.*\.test\.(js|ts|jsx|tsx)|__tests__\/.*\.(js|ts|jsx|tsx))$/i,oh=[{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}],U_=/(^|\/)\.env(?:\.[^/]+)?\.(example|sample|template)$/i,rh=[{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 F_("git",t,{cwd:e,encoding:"utf8"})}function W_(t=process.cwd()){return pi(["rev-parse","--show-toplevel"],t).trim()}function H_(t){let e=q_.join(t,".nex","push-allowlist");return nh.existsSync(e)?nh.readFileSync(e,"utf8").split(`
131
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")):[]}function Rl(t,e){return e.some(s=>t.includes(s))}function ih(t){return U_.test(t)}function ah(t,e){let s=[];for(let o of t)if(!ih(o))for(let n of rh)n.regex.test(o)&&(Rl(o,e)||s.push({category:n.category,location:o,preview:o}));return s}function Y_(t){let e=t.split(`
132
- `),s=[],o="";for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("+++ b/")){o=r.slice(6);continue}!r.startsWith("+")||r.startsWith("+++")||s.push({filePath:o,lineNumber:n+1,text:r.slice(1),raw:r})}return s}function lh(t,e){let s=[];for(let o of Y_(t))if(!B_.test(o.filePath||""))for(let n of oh)n.regex.test(o.text)&&(Rl(o.raw,e)||Rl(o.text,e)||s.push({category:n.category,location:`${o.lineNumber}:${o.raw}`,preview:o.raw}));return s}function G_(t){return pi(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function z_(t,e){return pi(["diff",e,...sh],t)}function K_(t){return pi(["diff","--cached",...sh],t)}function ch({repoRoot:t,mode:e,range:s}){let o=H_(t),n=e==="staged"?G_(t):[],r=ah(n,o),i=e==="range"?z_(t,s):K_(t),a=lh(i,o);return[...r,...a]}function X_(t){return t.map(e=>` [${e.category}]
128
+ `).length;return s.length===0||n===0?null:n===1?q_(s,e):B_(s,e,n)}function ep(t){return Math.max(1,Math.floor(t/M_))}function tp(t,e){return t<=Math.ceil(e*L_)}function q_(t,e){let s=e.trim(),o=ep(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=hi(a.trim(),s);l<r&&(r=l,n={text:a,distance:l,line:i+1})}return n&&o>1&&(n=F_(t,s,n,o)||n,r=n.distance),tp(r,e.length)?n:null}function F_(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 c=r;c<=i;c++){let u=t[c];if(!u.trim())continue;let d=hi(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function B_(t,e,s){let o=t.length-s+1;if(o<=0)return null;let n=ep(o),r=null,i=1/0;for(let a=0;a<o;a+=n){let l=t.slice(a,a+s).join(`
129
+ `),c=hi(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&n>1&&(r=U_(t,e,r,n,s,o)||r,i=r.distance),tp(i,e.length)?r:null}function U_(t,e,s,o,n,r){let i=s.line-1,a=Math.max(0,i-o),l=Math.min(r-1,i+o),c=s.distance,u=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+n).join(`
130
+ `),p=hi(f,e);p<c&&(c=p,u={text:f,distance:p,line:d+1})}return u}np.exports={normalizeWhitespace:Al,fuzzyFindText:j_,findMostSimilar:D_}});var fp=Z((eA,Nl)=>{var op=require("fs"),W_=require("path"),{execFileSync:H_}=require("child_process"),rp=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],Y_=/(^|\/)(tests\/.*\.test\.(js|ts|jsx|tsx)|__tests__\/.*\.(js|ts|jsx|tsx))$/i,ip=[{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}],G_=/(^|\/)\.env(?:\.[^/]+)?\.(example|sample|template)$/i,ap=[{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 mi(t,e=process.cwd()){return H_("git",t,{cwd:e,encoding:"utf8"})}function z_(t=process.cwd()){return mi(["rev-parse","--show-toplevel"],t).trim()}function K_(t){let e=W_.join(t,".nex","push-allowlist");return op.existsSync(e)?op.readFileSync(e,"utf8").split(`
131
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")):[]}function Ol(t,e){return e.some(s=>t.includes(s))}function lp(t){return G_.test(t)}function cp(t,e){let s=[];for(let o of t)if(!lp(o))for(let n of ap)n.regex.test(o)&&(Ol(o,e)||s.push({category:n.category,location:o,preview:o}));return s}function X_(t){let e=t.split(`
132
+ `),s=[],o="";for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("+++ b/")){o=r.slice(6);continue}!r.startsWith("+")||r.startsWith("+++")||s.push({filePath:o,lineNumber:n+1,text:r.slice(1),raw:r})}return s}function up(t,e){let s=[];for(let o of X_(t))if(!Y_.test(o.filePath||""))for(let n of ip)n.regex.test(o.text)&&(Ol(o.raw,e)||Ol(o.text,e)||s.push({category:n.category,location:`${o.lineNumber}:${o.raw}`,preview:o.raw}));return s}function V_(t){return mi(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function J_(t,e){return mi(["diff",e,...rp],t)}function Z_(t){return mi(["diff","--cached",...rp],t)}function dp({repoRoot:t,mode:e,range:s}){let o=K_(t),n=e==="staged"?V_(t):[],r=cp(n,o),i=e==="range"?J_(t,s):Z_(t),a=up(i,o);return[...r,...a]}function Q_(t){return t.map(e=>` [${e.category}]
133
133
  ${e.location}`).join(`
134
- `)}function V_(t){let e={mode:"staged",range:""};for(let s=0;s<t.length;s++)t[s]==="--staged"&&(e.mode="staged"),t[s]==="--range"&&(e.mode="range",e.range=t[s+1]||"",s++);return e}function J_(){let t=V_(process.argv.slice(2)),e=W_(),s=ch({repoRoot:e,mode:t.mode,range:t.range});if(s.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 ${s.length} potential secret(s) in ${o}:`),console.log(X_(s)),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&&J_();Cl.exports={SECRET_PATTERNS:oh,SENSITIVE_FILE_RULES:rh,scanDiffText:lh,scanFileNames:ah,scanRepo:ch,isSafeExampleFile:ih}});var fh=Z((VC,dh)=>{var{C:XC}=it(),{SECRET_PATTERNS:Z_}=uh(),Q_=[{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 ex(t,e){let s=e.split(`
135
- `),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 Z_)l.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${l.category}`,severity:"error"});for(let l of Q_)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 tx(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}dh.exports={runDiagnostics:ex,getMemoryUsage:tx}});var an=Z((JC,Sh)=>{var Jn=require("fs").promises,kt=require("path"),{exec:nx}=require("util").promisify(require("child_process").exec),Nn=[],Nl=null,mi=!1,Ol=0,sx=6e4;function Pl(t){return!(Nn.length===0||Nl!==t||Date.now()-Ol>sx)}async function yh(t){if(!mi&&!Pl(t)){mi=!0,Nl=t;try{try{let{stdout:o}=await nx("rg --files",{cwd:t,timeout:5e3});Nn=o.split(`
136
- `).filter(Boolean),Ol=Date.now(),mi=!1;return}catch{}let e=[],s=async(o,n)=>{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=n?`${n}/${i.name}`:i.name;i.isDirectory()?await s(kt.join(o,i.name),a):e.push(a)}};await s(t,""),Nn=e,Ol=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{mi=!1}}}function Oo(){return Nn}function ox(){return Nl}function rx(t){return Nn.filter(e=>kt.basename(e)===t)}function ix(t){let e=t.toLowerCase();return Nn.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}function wh(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 $h(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 u=1;u<=Math.min(n.length,r.length)&&n[n.length-u]===r[r.length-u];u++)i=u;if(i>0&&i===r.length)return 500+i*100;let a=kt.basename(t).toLowerCase(),l=kt.basename(e).toLowerCase(),c=0;if(a===l)c+=80;else{let u=Math.max(a.length,l.length);if(u>0&&u<100){let f=1-wh(a,l)/u;f>=.6&&(c+=Math.round(f*50))}}if((s.includes(o)||o.includes(s))&&(c+=20),r.length>1){let u=new Set(n),d=0;for(let f of r)u.has(f)&&d++;c+=d*10}return i>0&&(c+=i*30),c}function ax(t,{limit:e=10,minScore:s=15}={}){if(!t||Nn.length===0)return[];let o=[];for(let n of Nn){let r=$h(n,t);r>=s&&o.push({file:n,score:r})}return o.sort((n,r)=>r.score-n.score),o.slice(0,e)}var Al=null,hh=0,ph=null,bh=12e4,gi=null,mh=0,gh=null,_h=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function xh(t,e){let s=[],o=t.split(`
137
- `);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 c=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);c&&s.push({type:"function",name:c[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(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 c=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);c&&s.push({type:"import",name:c[1]||c[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&s.push({type:"class",name:l[1],line:i})}}return s}async function yi(t){t=t||process.cwd();let e=kt.join(t,".nex","index","content-index.json"),s={};if(Al&&ph===t&&Date.now()-hh<bh)return Al;try{let i=await Jn.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}let o=Oo();(!Pl(t)||o.length===0)&&(await yh(t),o=Oo());let n={files:{}},r=!1;for(let i of Oo()){let a=kt.extname(i);if(!_h.has(a))continue;let l=kt.join(t,i);try{let u=(await Jn.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){n.files[i]=s.files[i];continue}let d=await Jn.readFile(l,"utf-8"),f=xh(d,a);n.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=kt.join(t,".nex","index");await Jn.mkdir(i,{recursive:!0}),await Jn.writeFile(e,JSON.stringify(n),"utf-8")}return Al=n,hh=Date.now(),ph=t,n}async function lx(t,e,s){let o=await yi(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,c=a.name.toLowerCase()===r?0:1;if(l!==c)return l-c;let u=i.name.toLowerCase().startsWith(r)?0:1,d=a.name.toLowerCase().startsWith(r)?0:1;return u-d}),n.slice(0,50)}function cx(t,e,s){if(!e||!e.startsWith("."))return null;let o=kt.posix.dirname(t.replace(/\\/g,"/")),n=kt.posix.normalize(kt.posix.join(o==="."?"":o,e)),r=[];if(kt.posix.extname(n))r.push(n);else for(let a of _h)r.push(`${n}${a}`),r.push(kt.posix.join(n,`index${a}`));for(let a of r)if(s.has(a))return a;return null}async function Ml(t){if(t=t||process.cwd(),gi&&gh===t&&Date.now()-mh<bh)return gi;let e=await yi(t),s=Oo(),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:[],c=[],u=new Set;for(let d of l){if(d.type!=="import")continue;let f=cx(a,d.name,o);!f||f===a||u.has(f)||(u.add(f),c.push(f),r[f]||(r[f]=[]),r[f].push(a))}n[a]=c}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return gi={importsByFile:n,importedByFile:r},mh=Date.now(),gh=t,gi}async function ux(t,e,s=6){if(!t)return[];let o=await Ml(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 dx(t,e=4){let s=await Ml(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 kh(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fx(t,e){let s=kh(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 hx(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 yi(e),a=kh(t),l=new RegExp(`\\b${a}\\s*\\(`),c=new RegExp(`\\b${a}\\b`),u=[];for(let d of Object.keys(i.files||{})){let f=d.replace(/\\/g,"/");try{let h=kt.join(e,f),g=(await Jn.readFile(h,"utf-8")).split(`
138
- `);for(let $=0;$<g.length;$++){let x=g[$],E=$+1;if(!c.test(x)||o&&f===o&&n===E||fx(x,t))continue;let N=(f===o?0:4)+(l.test(x)?3:1);u.push({file:f,line:E,context:x.trim(),score:N})}}catch{}}return u.sort((d,f)=>f.score!==d.score?f.score-d.score:d.file.localeCompare(f.file)||d.line-f.line),u.slice(0,r)}Sh.exports={refreshIndex:yh,getFileIndex:Oo,getIndexedCwd:ox,findFileInIndex:rx,searchIndex:ix,isIndexValid:Pl,buildContentIndex:yi,searchContentIndex:lx,extractDefinitions:xh,buildImportGraph:Ml,getRelatedFiles:ux,summarizeModuleHubs:dx,findSymbolReferences:hx,smartSearch:ax,scorePathMatch:$h,pathLevenshtein:wh}});var Ws=Z((ZC,Ah)=>{var wi=require("fs"),xi=require("path"),ki=require("os"),{execFile:px}=require("child_process"),{promisify:mx}=require("util"),Ll=mx(px),gx=xi.join(ki.homedir(),".nex","servers.json"),$i=xi.join(ki.tmpdir(),"nex-ssh-sockets");function yx(){return xi.join(process.cwd(),".nex","servers.json")}function vh(){let t=o=>{if(!wi.existsSync(o))return{};try{return JSON.parse(wi.readFileSync(o,"utf-8"))}catch{return{}}},e=t(gx),s=t(yx());return{...e,...s}}function wx(t){let e=vh();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 $x(){wi.existsSync($i)||wi.mkdirSync($i,{recursive:!0})}function Eh(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)),$x();let s=t.user?`${t.user}@${t.host}`:t.host,o=xi.join($i,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Th(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:s=3e4,sudo:o=!1}={}){let{args:n}=Eh(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await Ll("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:Si(l,t)}}}async function bx(t,e,s,{timeout:o=12e4}={}){let n=Th(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await Ll("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(Si(a,t)||a)}}async function _x(t,e,s,{timeout:o=12e4}={}){let n=Th(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await Ll("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(Si(a,t)||a)}}function Si(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
134
+ `)}function ex(t){let e={mode:"staged",range:""};for(let s=0;s<t.length;s++)t[s]==="--staged"&&(e.mode="staged"),t[s]==="--range"&&(e.mode="range",e.range=t[s+1]||"",s++);return e}function tx(){let t=ex(process.argv.slice(2)),e=z_(),s=dp({repoRoot:e,mode:t.mode,range:t.range});if(s.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 ${s.length} potential secret(s) in ${o}:`),console.log(Q_(s)),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===Nl&&tx();Nl.exports={SECRET_PATTERNS:ip,SENSITIVE_FILE_RULES:ap,scanDiffText:up,scanFileNames:cp,scanRepo:dp,isSafeExampleFile:lp}});var hp=Z((nA,pp)=>{var{C:tA}=at(),{SECRET_PATTERNS:nx}=fp(),sx=[{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 ox(t,e){let s=e.split(`
135
+ `),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 nx)l.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${l.category}`,severity:"error"});for(let l of sx)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 rx(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}pp.exports={runDiagnostics:ox,getMemoryUsage:rx}});var ln=Z((sA,Ep)=>{var Zn=require("fs").promises,kt=require("path"),{exec:ix}=require("util").promisify(require("child_process").exec),Nn=[],Ll=null,gi=!1,Ml=0,ax=6e4;function Il(t){return!(Nn.length===0||Ll!==t||Date.now()-Ml>ax)}async function bp(t){if(!gi&&!Il(t)){gi=!0,Ll=t;try{try{let{stdout:o}=await ix("rg --files",{cwd:t,timeout:5e3});Nn=o.split(`
136
+ `).filter(Boolean),Ml=Date.now(),gi=!1;return}catch{}let e=[],s=async(o,n)=>{let r;try{r=await Zn.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(kt.join(o,i.name),a):e.push(a)}};await s(t,""),Nn=e,Ml=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{gi=!1}}}function Oo(){return Nn}function lx(){return Ll}function cx(t){return Nn.filter(e=>kt.basename(e)===t)}function ux(t){let e=t.toLowerCase();return Nn.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}function $p(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 _p(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 u=1;u<=Math.min(n.length,r.length)&&n[n.length-u]===r[r.length-u];u++)i=u;if(i>0&&i===r.length)return 500+i*100;let a=kt.basename(t).toLowerCase(),l=kt.basename(e).toLowerCase(),c=0;if(a===l)c+=80;else{let u=Math.max(a.length,l.length);if(u>0&&u<100){let f=1-$p(a,l)/u;f>=.6&&(c+=Math.round(f*50))}}if((s.includes(o)||o.includes(s))&&(c+=20),r.length>1){let u=new Set(n),d=0;for(let f of r)u.has(f)&&d++;c+=d*10}return i>0&&(c+=i*30),c}function dx(t,{limit:e=10,minScore:s=15}={}){if(!t||Nn.length===0)return[];let o=[];for(let n of Nn){let r=_p(n,t);r>=s&&o.push({file:n,score:r})}return o.sort((n,r)=>r.score-n.score),o.slice(0,e)}var Pl=null,mp=0,gp=null,xp=12e4,yi=null,yp=0,wp=null,kp=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Sp(t,e){let s=[],o=t.split(`
137
+ `);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 c=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);c&&s.push({type:"function",name:c[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&s.push({type:"export",name:p,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];s.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let c=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);c&&s.push({type:"import",name:c[1]||c[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&s.push({type:"class",name:l[1],line:i})}}return s}async function wi(t){t=t||process.cwd();let e=kt.join(t,".nex","index","content-index.json"),s={};if(Pl&&gp===t&&Date.now()-mp<xp)return Pl;try{let i=await Zn.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}let o=Oo();(!Il(t)||o.length===0)&&(await bp(t),o=Oo());let n={files:{}},r=!1;for(let i of Oo()){let a=kt.extname(i);if(!kp.has(a))continue;let l=kt.join(t,i);try{let u=(await Zn.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){n.files[i]=s.files[i];continue}let d=await Zn.readFile(l,"utf-8"),f=Sp(d,a);n.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=kt.join(t,".nex","index");await Zn.mkdir(i,{recursive:!0}),await Zn.writeFile(e,JSON.stringify(n),"utf-8")}return Pl=n,mp=Date.now(),gp=t,n}async function fx(t,e,s){let o=await wi(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,c=a.name.toLowerCase()===r?0:1;if(l!==c)return l-c;let u=i.name.toLowerCase().startsWith(r)?0:1,d=a.name.toLowerCase().startsWith(r)?0:1;return u-d}),n.slice(0,50)}function px(t,e,s){if(!e||!e.startsWith("."))return null;let o=kt.posix.dirname(t.replace(/\\/g,"/")),n=kt.posix.normalize(kt.posix.join(o==="."?"":o,e)),r=[];if(kt.posix.extname(n))r.push(n);else for(let a of kp)r.push(`${n}${a}`),r.push(kt.posix.join(n,`index${a}`));for(let a of r)if(s.has(a))return a;return null}async function jl(t){if(t=t||process.cwd(),yi&&wp===t&&Date.now()-yp<xp)return yi;let e=await wi(t),s=Oo(),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:[],c=[],u=new Set;for(let d of l){if(d.type!=="import")continue;let f=px(a,d.name,o);!f||f===a||u.has(f)||(u.add(f),c.push(f),r[f]||(r[f]=[]),r[f].push(a))}n[a]=c}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return yi={importsByFile:n,importedByFile:r},yp=Date.now(),wp=t,yi}async function hx(t,e,s=6){if(!t)return[];let o=await jl(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 mx(t,e=4){let s=await jl(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 vp(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gx(t,e){let s=vp(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 yx(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 wi(e),a=vp(t),l=new RegExp(`\\b${a}\\s*\\(`),c=new RegExp(`\\b${a}\\b`),u=[];for(let d of Object.keys(i.files||{})){let f=d.replace(/\\/g,"/");try{let p=kt.join(e,f),g=(await Zn.readFile(p,"utf-8")).split(`
138
+ `);for(let b=0;b<g.length;b++){let x=g[b],E=b+1;if(!c.test(x)||o&&f===o&&n===E||gx(x,t))continue;let N=(f===o?0:4)+(l.test(x)?3:1);u.push({file:f,line:E,context:x.trim(),score:N})}}catch{}}return u.sort((d,f)=>f.score!==d.score?f.score-d.score:d.file.localeCompare(f.file)||d.line-f.line),u.slice(0,r)}Ep.exports={refreshIndex:bp,getFileIndex:Oo,getIndexedCwd:lx,findFileInIndex:cx,searchIndex:ux,isIndexValid:Il,buildContentIndex:wi,searchContentIndex:fx,extractDefinitions:Sp,buildImportGraph:jl,getRelatedFiles:hx,summarizeModuleHubs:mx,findSymbolReferences:yx,smartSearch:dx,scorePathMatch:_p,pathLevenshtein:$p}});var Ws=Z((oA,Np)=>{var bi=require("fs"),ki=require("path"),Si=require("os"),{execFile:wx}=require("child_process"),{promisify:bx}=require("util"),Dl=bx(wx),$x=ki.join(Si.homedir(),".nex","servers.json"),$i=ki.join(Si.tmpdir(),"nex-ssh-sockets");function _x(){return ki.join(process.cwd(),".nex","servers.json")}function Tp(){let t=o=>{if(!bi.existsSync(o))return{};try{return JSON.parse(bi.readFileSync(o,"utf-8"))}catch{return{}}},e=t($x),s=t(_x());return{...e,...s}}function xx(t){let e=Tp();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 kx(){bi.existsSync($i)||bi.mkdirSync($i,{recursive:!0})}function Rp(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Si.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),kx();let s=t.user?`${t.user}@${t.host}`:t.host,o=ki.join($i,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Cp(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Si.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function _i(t,e,{timeout:s=3e4,sudo:o=!1}={}){let{args:n}=Rp(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await Dl("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:vi(l,t)}}}async function Sx(t,e,s,{timeout:o=12e4}={}){let n=Cp(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await Dl("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(vi(a,t)||a)}}async function vx(t,e,s,{timeout:o=12e4}={}){let n=Cp(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await Dl("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(vi(a,t)||a)}}function vi(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
139
139
  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}
140
140
  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}
141
141
  HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
142
142
  HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
143
143
  HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
144
- HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function xx(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 _i=new Map,kx=12e4;async function Rh(t,e,{force:s=!1}={}){let n=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=_i.get(n);if(!s&&r&&Date.now()-r.time<kx)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 c=e.endsWith("/")?e:e+"/",u=a.split(`
145
- `).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return _i.set(n,{files:u,time:Date.now()}),u}async function Ch(t,e,s,{limit:o=5,minScore:n=15}={}){let r=await Rh(t,e);if(r.length===0)return[];let{scorePathMatch:i}=an(),a=[];for(let l of r){let c=i(l,s);c>=n&&a.push({file:l,score:c})}return a.sort((l,c)=>c.score-l.score),a.slice(0,o)}async function Sx(t,e,s){if(!s)return{fixedPath:null,message:""};let o=s.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 n=await Ch(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:
144
+ HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function Ex(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 xi=new Map,Tx=12e4;async function Ap(t,e,{force:s=!1}={}){let n=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=xi.get(n);if(!s&&r&&Date.now()-r.time<Tx)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 _i(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let c=e.endsWith("/")?e:e+"/",u=a.split(`
145
+ `).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return xi.set(n,{files:u,time:Date.now()}),u}async function Op(t,e,s,{limit:o=5,minScore:n=15}={}){let r=await Ap(t,e);if(r.length===0)return[];let{scorePathMatch:i}=ln(),a=[];for(let l of r){let c=i(l,s);c>=n&&a.push({file:l,score:c})}return a.sort((l,c)=>c.score-l.score),a.slice(0,o)}async function Rx(t,e,s){if(!s)return{fixedPath:null,message:""};let o=s.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await _i(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await _i(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let n=await Op(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:
146
146
  ${n.map(a=>` - ${a.file}`).join(`
147
- `)}`}}return{fixedPath:null,message:""}}function vx(t){t?_i.delete(t):_i.clear()}Ah.exports={loadServerProfiles:vh,resolveProfile:wx,buildSSHArgs:Eh,sshExec:bi,scpUpload:bx,scpDownload:_x,enrichSSHError:Si,formatProfile:xx,SSH_SOCKET_DIR:$i,getRemoteIndex:Rh,remoteSmartSearch:Ch,remoteAutoFixPath:Sx,clearRemoteIndex:vx}});var Ph=Z((QC,Nh)=>{var No=require("fs"),Il=require("path"),Ex=Il.join(".nex","deploy.json");function jl(){return Il.join(process.cwd(),Ex)}function Oh(){let t=jl();if(!No.existsSync(t))return{};try{return JSON.parse(No.readFileSync(t,"utf-8"))}catch{return{}}}function Tx(t){let e=Oh();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 Rx(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")}Nh.exports={loadDeployConfigs:Oh,resolveDeployConfig:Tx,saveDeployConfigs:Rx,getDeployConfigPath:jl}});var Io=Z((eA,Ih)=>{var{getActiveModel:Cx,getActiveProviderName:Ax}=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 Lh(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(ln=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{ln={}}}Lh();function Dl(){let e=Cx()?.id,s=Ax();return e&&ln[e]?ln[e]:s&&ln[`${s}:*`]?ln[`${s}:*`]:e&&Mo[e]?Mo[e]:s&&Lo[s]?Lo[s]:"full"}var Ox=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"]),Mh={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function Nx(t,e){return t&&(Ox.has(t)||t.startsWith("claude-"))?"strict":e&&Mh[e]?Mh[e]:"fuzzy"}function Px(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 Mx(t,e){let s=e||Dl();if(s==="full"||!Po[s])return t;let o=new Set(Po[s]);return t.filter(n=>o.has(n.function.name))}function Lx(){let t=Dl(),e=Po[t]?Po[t].length:"all";return{tier:t,toolCount:e}}Ih.exports={filterToolsForModel:Mx,getActiveTier:Dl,getModelTier:Px,getEditMode:Nx,getTierInfo:Lx,TIERS:Po,MODEL_TIERS:Mo,PROVIDER_DEFAULT_TIER:Lo,loadConfigOverrides:Lh}});var xn=Z((tA,qh)=>{var ql=null,_n=null,jo=null,jh=`Playwright is not installed. Install with:
147
+ `)}`}}return{fixedPath:null,message:""}}function Cx(t){t?xi.delete(t):xi.clear()}Np.exports={loadServerProfiles:Tp,resolveProfile:xx,buildSSHArgs:Rp,sshExec:_i,scpUpload:Sx,scpDownload:vx,enrichSSHError:vi,formatProfile:Ex,SSH_SOCKET_DIR:$i,getRemoteIndex:Ap,remoteSmartSearch:Op,remoteAutoFixPath:Rx,clearRemoteIndex:Cx}});var Lp=Z((rA,Mp)=>{var No=require("fs"),ql=require("path"),Ax=ql.join(".nex","deploy.json");function Fl(){return ql.join(process.cwd(),Ax)}function Pp(){let t=Fl();if(!No.existsSync(t))return{};try{return JSON.parse(No.readFileSync(t,"utf-8"))}catch{return{}}}function Ox(t){let e=Pp();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 Nx(t){let e=ql.join(process.cwd(),".nex");No.existsSync(e)||No.mkdirSync(e,{recursive:!0}),No.writeFileSync(Fl(),JSON.stringify(t,null,2)+`
148
+ `,"utf-8")}Mp.exports={loadDeployConfigs:Pp,resolveDeployConfig:Ox,saveDeployConfigs:Nx,getDeployConfigPath:Fl}});var Io=Z((iA,Dp)=>{var{getActiveModel:Px,getActiveProviderName:Mx}=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"},cn={};function jp(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(cn=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{cn={}}}jp();function Bl(){let e=Px()?.id,s=Mx();return e&&cn[e]?cn[e]:s&&cn[`${s}:*`]?cn[`${s}:*`]:e&&Mo[e]?Mo[e]:s&&Lo[s]?Lo[s]:"full"}var Lx=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"]),Ip={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function Ix(t,e){return t&&(Lx.has(t)||t.startsWith("claude-"))?"strict":e&&Ip[e]?Ip[e]:"fuzzy"}function jx(t,e){return t&&cn[t]?cn[t]:e&&cn[`${e}:*`]?cn[`${e}:*`]:t&&Mo[t]?Mo[t]:e&&Lo[e]?Lo[e]:"full"}function Dx(t,e){let s=e||Bl();if(s==="full"||!Po[s])return t;let o=new Set(Po[s]);return t.filter(n=>o.has(n.function.name))}function qx(){let t=Bl(),e=Po[t]?Po[t].length:"all";return{tier:t,toolCount:e}}Dp.exports={filterToolsForModel:Dx,getActiveTier:Bl,getModelTier:jx,getEditMode:Ix,getTierInfo:qx,TIERS:Po,MODEL_TIERS:Mo,PROVIDER_DEFAULT_TIER:Lo,loadConfigOverrides:jp}});var xn=Z((aA,Up)=>{var Ul=null,_n=null,jo=null,Wl=Symbol.for("nex-code.browserExitCleanup"),qp=`Playwright is not installed. Install with:
149
149
  npm install playwright && npx playwright install chromium
150
- Then restart nex-code.`;function Dh(){if(jo!==null)return jo;try{require("playwright"),jo=!0}catch{jo=!1}return jo}async function vi(){if(!Dh())throw new Error(jh);return ql||(ql=require("playwright")),(!_n||!_n.isConnected())&&(_n=await ql.chromium.launch({headless:!0})),_n}async function Ix(){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 jx(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let n=await(await vi()).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(c=>c.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?`
151
- ...(truncated)`:""),links:a.slice(0,20)}}finally{await n.close()}}async function Dx(t,{width:e=1280,height:s=800,fullPage:o=!1,timeout:n=3e4}={}){let i=await(await vi()).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"),c=require("path"),u=require("fs"),d=c.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a,{mode:384}),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function qx(t,{selector:e,text:s,timeout:o=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await vi()).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 Fx(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 vi()).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()}}qh.exports={isPlaywrightAvailable:Dh,browserNavigate:jx,browserScreenshot:Dx,browserClick:qx,browserFill:Fx,closeBrowser:Ix,INSTALL_MSG:jh}});var Fl=Z((nA,Bh)=>{"use strict";var Bx=require("util"),Fh=require("stream"),Xt=Bh.exports=function(){Fh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Bx.inherits(Xt,Fh);Xt.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))};Xt.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};Xt.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()))};Xt.prototype.destroySoon=Xt.prototype.end;Xt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Xt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Xt.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))};Xt.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)};Xt.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 s=[],o=t%8,n=e%8,r=(t-o)/8,i=(e-n)/8;for(let a=0;a<Pn.length;a++){let l=Pn[a],c=r*l.x.length,u=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<o;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<n;d++)u++;c>0&&u>0&&s.push({width:c,height:u,index:a})}return s};Bl.getInterlaceIterator=function(t){return function(e,s,o){let n=e%Pn[o].x.length,r=(e-n)/Pn[o].x.length*8+Pn[o].x[n],i=s%Pn[o].y.length,a=(s-i)/Pn[o].y.length*8+Pn[o].y[i];return r*4+a*t*4}}});var Wl=Z((oA,Uh)=>{"use strict";Uh.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 Hl=Z((rA,Hh)=>{"use strict";var Ux=Ul(),Wx=Wl();function Wh(t,e,s){let o=t*e;return s!==8&&(o=Math.ceil(o/(8/s))),o}var Hs=Hh.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=Ux.getImagePasses(s,o);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Wh(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Wh(s,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,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}};Hs.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}};Hs.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,c=i>n?e[i-o]:0,u=Math.floor((c+l)/2);e[i]=a+u}};Hs.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,c=i>n?e[i-o]:0,u=i>n&&r?r[i-o]:0,d=Wx(c,l,u);e[i]=a+d}};Hs.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 zh=Z((iA,Gh)=>{"use strict";var Hx=require("util"),Yh=Fl(),Yx=Hl(),Gx=Gh.exports=function(t){Yh.call(this);let e=[],s=this;this._filter=new Yx(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};Hx.inherits(Gx,Yh)});var Ys=Z((aA,Kh)=>{"use strict";Kh.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((lA,Xh)=>{"use strict";var Yl=[];(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;Yl[t]=e}})();var Gl=Xh.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 s=0;s<t.length;s++)e=Yl[(e^t[s])&255]^e>>>8;return e^-1}});var Kl=Z((cA,Vh)=>{"use strict";var nt=Ys(),zx=zl(),ot=Vh.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 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))};ot.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!==nt.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new zx,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))};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),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))};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),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 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=n;let l=nt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:s,depth:o,interlace:!!a,palette:!!(n&nt.COLORTYPE_PALETTE),color:!!(n&nt.COLORTYPE_COLOR),alpha:!!(n&nt.COLORTYPE_ALPHA),bpp:l,colorType:n}),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 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()};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 s=t-e.length;s>0?this._handleIDAT(s):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(Zh=>{"use strict";var Jh=Ul(),Kx=[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]}],Xx=[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 Vx(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,c,u,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:u=r&3,d=r>>2&3,f=r>>4&3,h=r>>6&3,s.push(h,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,h=r>>7&1,s.push(h,f,d,u,c,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 Jx(t,e,s,o,n,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<i;u++){let d=s(u,c,l);Kx[o](e,n,d,r),r+=o}return r}function Zx(t,e,s,o,n,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<i;u++){let d=n.get(o),f=s(u,c,l);Xx[o](e,d,f,r)}n.resetAfterLine()}}Zh.dataToBitMap=function(t,e){let s=e.width,o=e.height,n=e.depth,r=e.bpp,i=e.interlace,a;n!==8&&(a=Vx(t,n));let l;n<=8?l=Buffer.alloc(s*o*4):l=new Uint16Array(s*o*4);let c=Math.pow(2,n)-1,u=0,d,f;if(i)d=Jh.getImagePasses(s,o),f=Jh.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?u=Jx(d[h],l,f,r,t,u):Zx(d[h],l,f,r,a,c);if(n===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Vl=Z((dA,Qh)=>{"use strict";function Qx(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 c=0;c<4;c++)e[r+c]=l[c];r+=4}}function ek(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 c=0;c<4;c++)e[r+c]=0;r+=4}}function tk(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 c=0;c<s;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}Qh.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,c=t;return i===3?Qx(t,c,n,r,l):(a&&ek(t,c,n,r,a),o!==8&&!s&&(o===16&&(c=Buffer.alloc(n*r*4)),tk(t,c,n,r,o))),c}});var np=Z((fA,tp)=>{"use strict";var nk=require("util"),Jl=require("zlib"),ep=Fl(),sk=zh(),ok=Kl(),rk=Xl(),ik=Vl(),cn=tp.exports=function(t){ep.call(this),this._parser=new ok(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()};nk.inherits(cn,ep);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 s=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,o=Math.max(s,Jl.Z_MIN_CHUNK);this._inflate=Jl.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)};cn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new sk(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 s=rk.dataToBitMap(t,this._bitmapInfo);e=ik(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var op=Z((hA,sp)=>{"use strict";var Dt=Ys();sp.exports=function(t,e,s,o){let n=[Dt.COLORTYPE_COLOR_ALPHA,Dt.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=Dt.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let l=Dt.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*s*l),u=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 Dt.COLORTYPE_COLOR_ALPHA:x=r[u+3],m=r[u],g=r[u+1],$=r[u+2];break;case Dt.COLORTYPE_COLOR:m=r[u],g=r[u+1],$=r[u+2];break;case Dt.COLORTYPE_ALPHA:x=r[u+1],m=r[u],g=m,$=m;break;case Dt.COLORTYPE_GRAYSCALE:m=r[u],g=m,$=m;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}return o.inputHasAlpha&&(n||(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<s;m++)for(let g=0;g<e;g++){let $=h(r,u);switch(o.colorType){case Dt.COLORTYPE_COLOR_ALPHA:case Dt.COLORTYPE_COLOR:o.bitDepth===8?(c[d]=$.red,c[d+1]=$.green,c[d+2]=$.blue,n&&(c[d+3]=$.alpha)):(c.writeUInt16BE($.red,d),c.writeUInt16BE($.green,d+2),c.writeUInt16BE($.blue,d+4),n&&c.writeUInt16BE($.alpha,d+6));break;case Dt.COLORTYPE_ALPHA:case Dt.COLORTYPE_GRAYSCALE:{let x=($.red+$.green+$.blue)/3;o.bitDepth===8?(c[d]=x,n&&(c[d+1]=$.alpha)):(c.writeUInt16BE(x,d),n&&c.writeUInt16BE($.alpha,d+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}u+=a,d+=l}return c}});var ap=Z((pA,ip)=>{"use strict";var rp=Wl();function ak(t,e,s,o,n){for(let r=0;r<s;r++)o[n+r]=t[e+r]}function lk(t,e,s){let o=0,n=e+s;for(let r=e;r<n;r++)o+=Math.abs(t[r]);return o}function ck(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 uk(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 dk(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 fk(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 hk(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,c=t[e+i]-(a+l>>1);o[n+i]=c}}function pk(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 mk(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,c=e>0&&i>=r?t[e+i-(s+r)]:0,u=t[e+i]-rp(a,l,c);o[n+i]=u}}function gk(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,c=t[e+r]-rp(i,a,l);n+=Math.abs(c)}return n}var yk={0:ak,1:ck,2:dk,3:hk,4:mk},wk={0:lk,1:uk,2:fk,3:pk,4:gk};ip.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,c=Buffer.alloc((i+1)*s),u=r[0];for(let d=0;d<s;d++){if(r.length>1){let f=1/0;for(let h=0;h<r.length;h++){let m=wk[r[h]](t,l,i,n);m<f&&(u=r[h],f=m)}}c[a]=u,a++,yk[u](t,l,i,c,a,n),a+=i,l+=i}return c}});var Zl=Z((mA,lp)=>{"use strict";var ft=Ys(),$k=zl(),bk=op(),_k=ap(),xk=require("zlib"),Mn=lp.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||xk.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,s){let o=bk(t,e,s,this._options),n=ft.COLORTYPE_TO_BPP_MAP[this._options.colorType];return _k(o,e,s,this._options,n)};Mn.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($k.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 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(ft.TYPE_IHDR,s)};Mn.prototype.packIDAT=function(t){return this._packChunk(ft.TYPE_IDAT,t)};Mn.prototype.packIEND=function(){return this._packChunk(ft.TYPE_IEND,null)}});var fp=Z((gA,dp)=>{"use strict";var kk=require("util"),cp=require("stream"),Sk=Ys(),vk=Zl(),up=dp.exports=function(t){cp.call(this);let e=t||{};this._packer=new vk(e),this._deflate=this._packer.createDeflate(),this.readable=!0};kk.inherits(up,cp);up.prototype.pack=function(t,e,s,o){this.emit("data",Buffer.from(Sk.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 wp=Z((Do,yp)=>{"use strict";var hp=require("assert").ok,Gs=require("zlib"),Ek=require("util"),pp=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 Tk(t){return new Zn(t)}function mp(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Zn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return Gs.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=[],c=0,u;this.on("error",function(m){u=m});function d(m,g){if(o._hadError)return;let $=r-g;if(hp($>=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),c+=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+=n-m,n=m,!0):!1}hp(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 u;if(c>=pp)throw mp(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+pp.toString(16)+" bytes");let h=Buffer.concat(l,c);return mp(this),h};Ek.inherits(Zn,Gs.Inflate);function Rk(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=Gs.Z_FINISH),t._processChunk(e,s)}function gp(t,e){return Rk(new Zn(e),t)}yp.exports=Do=gp;Do.Inflate=Zn;Do.createInflate=Tk;Do.inflateSync=gp});var Ql=Z((yA,bp)=>{"use strict";var $p=bp.exports=function(t){this._buffer=t,this._reads=[]};$p.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};$p.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 xp=Z(_p=>{"use strict";var Ck=Ql(),Ak=Hl();_p.process=function(t,e){let s=[],o=new Ck(t);return new Ak(e,{read:o.read.bind(o),write:function(r){s.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(s)}});var Ep=Z(($A,vp)=>{"use strict";var kp=!0,Sp=require("zlib"),Ok=wp();Sp.deflateSync||(kp=!1);var Nk=Ql(),Pk=xp(),Mk=Kl(),Lk=Xl(),Ik=Vl();vp.exports=function(t,e){if(!kp)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(v){s=v}let n;function r(v){n=v}function i(v){n.transColor=v}function a(v){n.palette=v}function l(){n.alpha=!0}let c;function u(v){c=v}let d=[];function f(v){d.push(v)}let h=new Nk(t);if(new Mk(e,{read:h.read.bind(h),error:o,metadata:r,gamma:u,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)$=Sp.inflateSync(g);else{let S=((n.width*n.bpp*n.depth+7>>3)+1)*n.height;$=Ok(g,{chunkSize:S,maxLength:S})}if(g=null,!$||!$.length)throw new Error("bad png - invalid inflate data response");let x=Pk.process($,n);g=null;let E=Lk.dataToBitMap(x,n);x=null;let N=Ik(E,n,e.skipRescale);return n.data=N,n.gamma=c||0,n}});var Ap=Z((bA,Cp)=>{"use strict";var Tp=!0,Rp=require("zlib");Rp.deflateSync||(Tp=!1);var jk=Ys(),Dk=Zl();Cp.exports=function(t,e){if(!Tp)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 Dk(s),n=[];n.push(Buffer.from(jk.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=Rp.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 Op=Z(ec=>{"use strict";var qk=Ep(),Fk=Ap();ec.read=function(t,e){return qk(t,e||{})};ec.write=function(t,e){return Fk(t,e)}});var Mp=Z(Pp=>{"use strict";var Bk=require("util"),Np=require("stream"),Uk=np(),Wk=fp(),Hk=Op(),mt=Pp.PNG=function(t){Np.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 Uk(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 Wk(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"))};Bk.inherits(mt,Np);mt.sync=Hk;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 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};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,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)};mt.prototype.bitblt=function(t,e,s,o,n,r,i){return mt.bitblt(this,t,e,s,o,n,r,i),this};mt.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}};mt.prototype.adjustGamma=function(){mt.adjustGamma(this)}});var qp={};fw(qp,{default:()=>jp});function jp(t,e,s,o,n,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:c=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=r;if(!tc(t)||!tc(e)||s&&!tc(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 le=0;le<h;le++)if(m[le]!==g[le]){$=!1;break}if($){if(s&&!f)for(let le=0;le<h;le++)Ip(t,4*le,a,s);return 0}let x=35215*i*i,[E,N,v]=l,[S,P,ne]=c,[se,ce,de]=d||c,re=0;for(let le=0;le<n;le++)for(let T=0;T<o;T++){let q=le*o+T,Q=q*4,we=m[q]===g[q]?0:Dp(t,e,Q,Q,!1);if(Math.abs(we)>x){let ke=Lp(t,T,le,o,n,m,g)||Lp(e,T,le,o,n,g,m);!u&&ke?s&&!f&&Ti(s,Q,E,N,v):(s&&(we<0?Ti(s,Q,se,ce,de):Ti(s,Q,S,P,ne)),re++)}else s&&!f&&Ip(t,Q,a,s)}return re}function tc(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Lp(t,e,s,o,n,r,i){let a=Math.max(e-1,0),l=Math.max(s-1,0),c=Math.min(e+1,o-1),u=Math.min(s+1,n-1),d=s*o+e,f=e===a||e===c||s===l||s===u?1:0,h=0,m=0,g=0,$=0,x=0,E=0;for(let N=a;N<=c;N++)for(let v=l;v<=u;v++){if(N===e&&v===s)continue;let S=Dp(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,n)&&Ei(i,g,$,o,n)||Ei(r,x,E,o,n)&&Ei(i,x,E,o,n)}function Ei(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),c=t[s*o+e],u=e===r||e===a||s===i||s===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===s)&&(u+=+(c===t[f*o+d]),u>2))return!0;return!1}function Dp(t,e,s,o,n){let r=t[s],i=t[s+1],a=t[s+2],l=t[s+3],c=e[o],u=e[o+1],d=e[o+2],f=e[o+3],h=r-c,m=i-u,g=a-d,$=l-f;if(!h&&!m&&!g&&!$)return 0;if(l<255||f<255){let S=48+159*(s%2),P=48+159*((s/1.618033988749895|0)%2),ne=48+159*((s/2.618033988749895|0)%2);h=(r*l-c*f-S*$)/255,m=(i*l-u*f-P*$)/255,g=(a*l-d*f-ne*$)/255}let x=h*.29889531+m*.58662247+g*.11448223;if(n)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,s,o,n){t[e+0]=s,t[e+1]=o,t[e+2]=n,t[e+3]=255}function Ip(t,e,s,o){let n=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;Ti(o,e,n,n,n)}var Fp=dw(()=>{});var Qn=Z((kA,Yp)=>{var kn=require("fs"),Yk=require("path"),Gk=require("os"),zk="nex-visual-";function Up(t){return Yk.join(Gk.tmpdir(),`${zk}${Date.now()}-${t}`)}var nc=null;function Ri(){return nc||(nc=Mp().PNG),nc}var sc=null;function Kk(){if(!sc){let t=(Fp(),pw(qp));sc=t.default||t}return sc}function ic(t,e,{threshold:s=.1}={}){let o=Ri(),n=Kk(),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),c=Bp(r,a,l),u=Bp(i,a,l),d=new o({width:a,height:l}),f=n(c,u,d.data,a,l,{threshold:s,includeAA:!1}),h=a*l,m=(f/h*100).toFixed(1),g=Xk(d.data,a,l,3,3),$=Up("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 Bp(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 Xk(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 c=0;c<n;c++)for(let u=0;u<o;u++){let d=0,f=0,h=u*i,m=c*a,g=Math.min(h+i,e),$=Math.min(m+a,s);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[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:E,changedPercent:parseFloat(x),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var Wp=[{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 Vk(t,{viewports:e=Wp,height:s=800,fullPage:o=!1,timeout:n=3e4}={}){let{browserScreenshot:r}=xn(),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 Hp(t,e=[]){let s=Ri(),o=s.sync.read(kn.readFileSync(t));for(let i of e){let a=Jk(i.color||"#FF0000");i.type==="box"?(Zk(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"?(Qk(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"&&(eS(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 n=Up("annotated.png");kn.writeFileSync(n,s.sync.write(o),{mode:384});let r=kn.readFileSync(n).toString("base64");return{path:n,base64:r,media_type:"image/png"}}function Jk(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,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 Zk(t,e,s,o,n,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<o;l++)un(t,e+l,s+a,r),un(t,e+l,s+n-1-a,r);for(let l=0;l<n;l++)un(t,e+a,s+l,r),un(t,e+o-1-a,s+l,r)}}function oc(t,e,s,o,n,r,i=3){let a=Math.abs(o-e),l=Math.abs(n-s),c=e<o?1:-1,u=s<n?1:-1,d=a-l,f=e,h=s;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===n)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,h+=u)}}function Qk(t,e,s,o,n,r,i=3){oc(t,e,s,o,n,r,i);let a=Math.atan2(n-s,o-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;oc(t,o,n,Math.round(o+l*Math.cos(c)),Math.round(n+l*Math.sin(c)),r,i),oc(t,o,n,Math.round(o+l*Math.cos(u)),Math.round(n+l*Math.sin(u)),r,i)}function eS(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 c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(s+a*Math.sin(c));un(t,u,d,n)}}}function rc(t,e,s,o,n){let i=o.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)un(t,e+c,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)un(t,e+l,s+a-1,n),un(t,e+l,s+a-2,n);for(let l=0;l<o.length;l++){let c=e+2+l*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)un(t,c+d,s+u,n)}}async function*tS(t,e,{maxIterations:s=20,hmrDelay:o=1500,width:n=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=xn(),l=nS("chokidar"),c=await a(t,{width:n,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:c.path,base64:c.base64,media_type:c.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let u=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;u<s;){await oS(()=>d,3e5),d=!1,u++,await sS(o);let h=await a(t,{width:n,height:r,timeout:i}),m=null;try{m=ic(c.path,h.path)}catch{}c=h,yield{iteration:u,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 nS(t){try{return require(t)}catch{return null}}function sS(t){return new Promise(e=>setTimeout(e,t))}function oS(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 rS(t,{sampleRate:e=4}={}){let o=Ri().sync.read(kn.readFileSync(t)),n=new Map;for(let c=0;c<o.height;c+=e)for(let u=0;u<o.width;u+=e){let d=(c*o.width+u)*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}`;n.set(N,(n.get(N)||0)+1)}let r=[...n.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,h]=c.split(",").map(Number);return{hex:iS(d,f,h),rgb:`rgb(${d}, ${f}, ${h})`,frequency:parseFloat((u/i*100).toFixed(1)),category:aS(d,f,h)}}),l=lS(o);return{colors:a,spacing:l,dimensions:{width:o.width,height:o.height},imagePath:t}}function iS(t,e,s){return"#"+[t,e,s].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function aS(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 lS(t){let e=[],s=!1,o=0,n=cS(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let c=(i*t.width+l)*4;if(Math.abs(t.data[c]-n.r)>20||Math.abs(t.data[c+1]-n.g)>20||Math.abs(t.data[c+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 cS(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 uS(t,e,{width:s,height:o=800,fullPage:n=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=xn(),c=Ri().sync.read(kn.readFileSync(e)),u=s||c.width,d=o||c.height,f=await a(t,{width:u,height:d,fullPage:n,timeout:i}),h=ic(e,f.path,{threshold:r}),m=Hp(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 se=0;se<3;se++)for(let ce=0;ce<3;ce++)S[se][ce]===g.name&&(P=ce,ne=se);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}}Yp.exports={pixelDiff:ic,responsiveSweep:Vk,annotateImage:Hp,visualWatch:tS,extractDesignTokens:rS,designCompare:uS,DEFAULT_VIEWPORTS:Wp}});var ac=Z((SA,Gp)=>{var{C:De}=it(),Fo="",gt=[],qo=0,es=null;function dS(t){es=t}function fS(t,e){Fo=t,gt=[],qo=0;for(let o of e){qo++;let n=`t${qo}`;gt.push({id:n,description:o.description||o.title||o.name||o.task||`Task ${qo}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let s=gt.map(o=>({...o}));return es&&es("create",{name:t,tasks:s}),s}function hS(t,e,s){let o=gt.find(n=>n.id===t);return o?(o.status=e,s!==void 0&&(o.result=s),es&&es("update",{id:t,status:e,result:s}),{...o}):null}function pS(){return{name:Fo,tasks:gt.map(t=>({...t}))}}function mS(){Fo="",gt=[],qo=0,es&&es("clear",{})}function gS(){return gt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=gt.find(o=>o.id===e);return s&&s.status==="done"}))}function yS(){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 n of gt){let r,i;switch(n.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=n.dependsOn.length>0?` ${De.dim}(after: ${n.dependsOn.join(", ")})${De.reset}`:"",l=`[${n.status}]`,c=n.description.length>50?n.description.substring(0,47)+"...":n.description;if(t.push(` ${i}${r}${De.reset} ${De.bold}${n.id}${De.reset} ${c.padEnd(40)} ${i}${l}${De.reset}${a}`),n.result&&n.status==="done"){let u=n.result.length>60?n.result.substring(0,57)+"...":n.result;t.push(` ${De.dim}\u2192 ${u}${De.reset}`)}}let e=gt.filter(n=>n.status==="done").length,s=gt.filter(n=>n.status==="failed").length,o=gt.length;return t.push(` ${De.dim}${"\u2500".repeat(40)}${De.reset}`),t.push(` ${De.dim}${e}/${o} done${s>0?`, ${s} failed`:""}${De.reset}`),t.join(`
152
- `)}function wS(){return gt.length>0&&gt.some(t=>t.status==="pending"||t.status==="in_progress")}Gp.exports={createTasks:fS,updateTask:hS,getTaskList:pS,clearTasks:mS,getReadyTasks:gS,renderTaskList:yS,setOnChange:dS,hasActiveTasks:wS}});var cc=Z((vA,Zp)=>{var{callChat:$S}=dt(),{estimateTokens:lc}=dn(),zp=process.env.NEX_COMPACTION!=="false",Kp=6,Xp=2e3,Vp=3,bS=`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 Fp(){if(jo!==null)return jo;try{require("playwright"),jo=!0}catch{jo=!1}return jo}async function Ei(){if(!Fp())throw new Error(qp);return Ul||(Ul=require("playwright")),(!_n||!_n.isConnected())&&(_n=await Ul.chromium.launch({headless:!0})),_n}async function Fx(){if(_n){try{await _n.close()}catch(t){console.error("closeBrowser failed:",t.message)}_n=null}}globalThis[Wl]&&process.off("exit",globalThis[Wl]);var Bp=()=>{if(_n)try{_n.close()}catch(t){console.error("Error closing browser on exit:",t.message)}};globalThis[Wl]=Bp;process.on("exit",Bp);async function Bx(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let n=await(await Ei()).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(c=>c.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?`
151
+ ...(truncated)`:""),links:a.slice(0,20)}}finally{await n.close()}}async function Ux(t,{width:e=1280,height:s=800,fullPage:o=!1,timeout:n=3e4}={}){let i=await(await Ei()).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"),c=require("path"),u=require("fs"),d=c.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a,{mode:384}),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function Wx(t,{selector:e,text:s,timeout:o=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await Ei()).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 Hx(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 Ei()).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()}}Up.exports={isPlaywrightAvailable:Fp,browserNavigate:Bx,browserScreenshot:Ux,browserClick:Wx,browserFill:Hx,closeBrowser:Fx,INSTALL_MSG:qp}});var Hl=Z((lA,Hp)=>{"use strict";var Yx=require("util"),Wp=require("stream"),Xt=Hp.exports=function(){Wp.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Yx.inherits(Xt,Wp);Xt.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))};Xt.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};Xt.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()))};Xt.prototype.destroySoon=Xt.prototype.end;Xt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Xt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Xt.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))};Xt.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)};Xt.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 Gl=Z(Yl=>{"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]}];Yl.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<Pn.length;a++){let l=Pn[a],c=r*l.x.length,u=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<o;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<n;d++)u++;c>0&&u>0&&s.push({width:c,height:u,index:a})}return s};Yl.getInterlaceIterator=function(t){return function(e,s,o){let n=e%Pn[o].x.length,r=(e-n)/Pn[o].x.length*8+Pn[o].x[n],i=s%Pn[o].y.length,a=(s-i)/Pn[o].y.length*8+Pn[o].y[i];return r*4+a*t*4}}});var zl=Z((uA,Yp)=>{"use strict";Yp.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 Kl=Z((dA,zp)=>{"use strict";var Gx=Gl(),zx=zl();function Gp(t,e,s){let o=t*e;return s!==8&&(o=Math.ceil(o/(8/s))),o}var Hs=zp.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=Gx.getImagePasses(s,o);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Gp(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Gp(s,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,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}};Hs.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}};Hs.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,c=i>n?e[i-o]:0,u=Math.floor((c+l)/2);e[i]=a+u}};Hs.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,c=i>n?e[i-o]:0,u=i>n&&r?r[i-o]:0,d=zx(c,l,u);e[i]=a+d}};Hs.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 Vp=Z((fA,Xp)=>{"use strict";var Kx=require("util"),Kp=Hl(),Xx=Kl(),Vx=Xp.exports=function(t){Kp.call(this);let e=[],s=this;this._filter=new Xx(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};Kx.inherits(Vx,Kp)});var Ys=Z((pA,Jp)=>{"use strict";Jp.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 Jl=Z((hA,Zp)=>{"use strict";var Xl=[];(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;Xl[t]=e}})();var Vl=Zp.exports=function(){this._crc=-1};Vl.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Xl[(this._crc^t[e])&255]^this._crc>>>8;return!0};Vl.prototype.crc32=function(){return this._crc^-1};Vl.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=Xl[(e^t[s])&255]^e>>>8;return e^-1}});var Zl=Z((mA,Qp)=>{"use strict";var nt=Ys(),Jx=Jl(),rt=Qp.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(){}};rt.prototype.start=function(){this.read(nt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};rt.prototype._parseSignature=function(t){let e=nt.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))};rt.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!==nt.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Jx,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))};rt.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};rt.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};rt.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))};rt.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};rt.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 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=n;let l=nt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:s,depth:o,interlace:!!a,palette:!!(n&nt.COLORTYPE_PALETTE),color:!!(n&nt.COLORTYPE_COLOR),alpha:!!(n&nt.COLORTYPE_ALPHA),bpp:l,colorType:n}),this._handleChunkEnd()};rt.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};rt.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()};rt.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};rt.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()};rt.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};rt.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/nt.GAMMA_DIVISION),this._handleChunkEnd()};rt.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};rt.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 s=t-e.length;s>0?this._handleIDAT(s):this._handleChunkEnd()};rt.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};rt.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Ql=Z(th=>{"use strict";var eh=Gl(),Zx=[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]}],Qx=[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 ek(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,c,u,d,f,p;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,p=r>>4,s.push(p,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,s.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,s.push(p,f,d,u,c,l,a,i);break}}return{get:function(r){for(;s.length<r;)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 tk(t,e,s,o,n,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<i;u++){let d=s(u,c,l);Zx[o](e,n,d,r),r+=o}return r}function nk(t,e,s,o,n,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<i;u++){let d=n.get(o),f=s(u,c,l);Qx[o](e,d,f,r)}n.resetAfterLine()}}th.dataToBitMap=function(t,e){let s=e.width,o=e.height,n=e.depth,r=e.bpp,i=e.interlace,a;n!==8&&(a=ek(t,n));let l;n<=8?l=Buffer.alloc(s*o*4):l=new Uint16Array(s*o*4);let c=Math.pow(2,n)-1,u=0,d,f;if(i)d=eh.getImagePasses(s,o),f=eh.getInterlaceIterator(s,o);else{let p=0;f=function(){let m=p;return p+=4,m},d=[{width:s,height:o}]}for(let p=0;p<d.length;p++)n===8?u=tk(d[p],l,f,r,t,u):nk(d[p],l,f,r,a,c);if(n===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var ec=Z((yA,nh)=>{"use strict";function sk(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 c=0;c<4;c++)e[r+c]=l[c];r+=4}}function ok(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 c=0;c<4;c++)e[r+c]=0;r+=4}}function rk(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 c=0;c<s;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}nh.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,c=t;return i===3?sk(t,c,n,r,l):(a&&ok(t,c,n,r,a),o!==8&&!s&&(o===16&&(c=Buffer.alloc(n*r*4)),rk(t,c,n,r,o))),c}});var rh=Z((wA,oh)=>{"use strict";var ik=require("util"),tc=require("zlib"),sh=Hl(),ak=Vp(),lk=Zl(),ck=Ql(),uk=ec(),un=oh.exports=function(t){sh.call(this),this._parser=new lk(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()};ik.inherits(un,sh);un.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};un.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=tc.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,tc.Z_MIN_CHUNK);this._inflate=tc.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)};un.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new ak(this._bitmapInfo)};un.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};un.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};un.prototype._simpleTransparency=function(){this._metaData.alpha=!0};un.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};un.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};un.prototype._complete=function(t){if(this.errord)return;let e;try{let s=ck.dataToBitMap(t,this._bitmapInfo);e=uk(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var ah=Z((bA,ih)=>{"use strict";var Ft=Ys();ih.exports=function(t,e,s,o){let n=[Ft.COLORTYPE_COLOR_ALPHA,Ft.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=Ft.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let l=Ft.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*s*l),u=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 p(){let m,g,b,x=i;switch(o.inputColorType){case Ft.COLORTYPE_COLOR_ALPHA:x=r[u+3],m=r[u],g=r[u+1],b=r[u+2];break;case Ft.COLORTYPE_COLOR:m=r[u],g=r[u+1],b=r[u+2];break;case Ft.COLORTYPE_ALPHA:x=r[u+1],m=r[u],g=m,b=m;break;case Ft.COLORTYPE_GRAYSCALE:m=r[u],g=m,b=m;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}return o.inputHasAlpha&&(n||(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),b=Math.min(Math.max(Math.round((1-x)*f.blue+x*b),0),i))),{red:m,green:g,blue:b,alpha:x}}for(let m=0;m<s;m++)for(let g=0;g<e;g++){let b=p(r,u);switch(o.colorType){case Ft.COLORTYPE_COLOR_ALPHA:case Ft.COLORTYPE_COLOR:o.bitDepth===8?(c[d]=b.red,c[d+1]=b.green,c[d+2]=b.blue,n&&(c[d+3]=b.alpha)):(c.writeUInt16BE(b.red,d),c.writeUInt16BE(b.green,d+2),c.writeUInt16BE(b.blue,d+4),n&&c.writeUInt16BE(b.alpha,d+6));break;case Ft.COLORTYPE_ALPHA:case Ft.COLORTYPE_GRAYSCALE:{let x=(b.red+b.green+b.blue)/3;o.bitDepth===8?(c[d]=x,n&&(c[d+1]=b.alpha)):(c.writeUInt16BE(x,d),n&&c.writeUInt16BE(b.alpha,d+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}u+=a,d+=l}return c}});var uh=Z(($A,ch)=>{"use strict";var lh=zl();function dk(t,e,s,o,n){for(let r=0;r<s;r++)o[n+r]=t[e+r]}function fk(t,e,s){let o=0,n=e+s;for(let r=e;r<n;r++)o+=Math.abs(t[r]);return o}function pk(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 hk(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 mk(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 gk(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 yk(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,c=t[e+i]-(a+l>>1);o[n+i]=c}}function wk(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 bk(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,c=e>0&&i>=r?t[e+i-(s+r)]:0,u=t[e+i]-lh(a,l,c);o[n+i]=u}}function $k(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,c=t[e+r]-lh(i,a,l);n+=Math.abs(c)}return n}var _k={0:dk,1:pk,2:mk,3:yk,4:bk},xk={0:fk,1:hk,2:gk,3:wk,4:$k};ch.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,c=Buffer.alloc((i+1)*s),u=r[0];for(let d=0;d<s;d++){if(r.length>1){let f=1/0;for(let p=0;p<r.length;p++){let m=xk[r[p]](t,l,i,n);m<f&&(u=r[p],f=m)}}c[a]=u,a++,_k[u](t,l,i,c,a,n),a+=i,l+=i}return c}});var nc=Z((_A,dh)=>{"use strict";var ft=Ys(),kk=Jl(),Sk=ah(),vk=uh(),Ek=require("zlib"),Mn=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||Ek.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,s){let o=Sk(t,e,s,this._options),n=ft.COLORTYPE_TO_BPP_MAP[this._options.colorType];return vk(o,e,s,this._options,n)};Mn.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(kk.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 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(ft.TYPE_IHDR,s)};Mn.prototype.packIDAT=function(t){return this._packChunk(ft.TYPE_IDAT,t)};Mn.prototype.packIEND=function(){return this._packChunk(ft.TYPE_IEND,null)}});var mh=Z((xA,hh)=>{"use strict";var Tk=require("util"),fh=require("stream"),Rk=Ys(),Ck=nc(),ph=hh.exports=function(t){fh.call(this);let e=t||{};this._packer=new Ck(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Tk.inherits(ph,fh);ph.prototype.pack=function(t,e,s,o){this.emit("data",Buffer.from(Rk.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 _h=Z((Do,$h)=>{"use strict";var gh=require("assert").ok,Gs=require("zlib"),Ak=require("util"),yh=require("buffer").kMaxLength;function Qn(t){if(!(this instanceof Qn))return new Qn(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 Ok(t){return new Qn(t)}function wh(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Qn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return Gs.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=[],c=0,u;this.on("error",function(m){u=m});function d(m,g){if(o._hadError)return;let b=r-g;if(gh(b>=0,"have should not go down"),b>0){let x=o._buffer.slice(o._offset,o._offset+b);if(o._offset+=b,x.length>i&&(x=x.slice(0,i)),l.push(x),c+=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+=n-m,n=m,!0):!1}gh(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 u;if(c>=yh)throw wh(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+yh.toString(16)+" bytes");let p=Buffer.concat(l,c);return wh(this),p};Ak.inherits(Qn,Gs.Inflate);function Nk(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=Gs.Z_FINISH),t._processChunk(e,s)}function bh(t,e){return Nk(new Qn(e),t)}$h.exports=Do=bh;Do.Inflate=Qn;Do.createInflate=Ok;Do.inflateSync=bh});var sc=Z((kA,kh)=>{"use strict";var xh=kh.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 vh=Z(Sh=>{"use strict";var Pk=sc(),Mk=Kl();Sh.process=function(t,e){let s=[],o=new Pk(t);return new Mk(e,{read:o.read.bind(o),write:function(r){s.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(s)}});var Ch=Z((vA,Rh)=>{"use strict";var Eh=!0,Th=require("zlib"),Lk=_h();Th.deflateSync||(Eh=!1);var Ik=sc(),jk=vh(),Dk=Zl(),qk=Ql(),Fk=ec();Rh.exports=function(t,e){if(!Eh)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(v){s=v}let n;function r(v){n=v}function i(v){n.transColor=v}function a(v){n.palette=v}function l(){n.alpha=!0}let c;function u(v){c=v}let d=[];function f(v){d.push(v)}let p=new Ik(t);if(new Dk(e,{read:p.read.bind(p),error:o,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),p.process(),s)throw s;let g=Buffer.concat(d);d.length=0;let b;if(n.interlace)b=Th.inflateSync(g);else{let S=((n.width*n.bpp*n.depth+7>>3)+1)*n.height;b=Lk(g,{chunkSize:S,maxLength:S})}if(g=null,!b||!b.length)throw new Error("bad png - invalid inflate data response");let x=jk.process(b,n);g=null;let E=qk.dataToBitMap(x,n);x=null;let N=Fk(E,n,e.skipRescale);return n.data=N,n.gamma=c||0,n}});var Ph=Z((EA,Nh)=>{"use strict";var Ah=!0,Oh=require("zlib");Oh.deflateSync||(Ah=!1);var Bk=Ys(),Uk=nc();Nh.exports=function(t,e){if(!Ah)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 Uk(s),n=[];n.push(Buffer.from(Bk.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=Oh.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 Mh=Z(oc=>{"use strict";var Wk=Ch(),Hk=Ph();oc.read=function(t,e){return Wk(t,e||{})};oc.write=function(t,e){return Hk(t,e)}});var jh=Z(Ih=>{"use strict";var Yk=require("util"),Lh=require("stream"),Gk=rh(),zk=mh(),Kk=Mh(),mt=Ih.PNG=function(t){Lh.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 Gk(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 zk(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"))};Yk.inherits(mt,Lh);mt.sync=Kk;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 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};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,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)};mt.prototype.bitblt=function(t,e,s,o,n,r,i){return mt.bitblt(this,t,e,s,o,n,r,i),this};mt.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}};mt.prototype.adjustGamma=function(){mt.adjustGamma(this)}});var Uh={};m0(Uh,{default:()=>Fh});function Fh(t,e,s,o,n,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:c=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=r;if(!rc(t)||!rc(e)||s&&!rc(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 p=o*n,m=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),b=!0;for(let le=0;le<p;le++)if(m[le]!==g[le]){b=!1;break}if(b){if(s&&!f)for(let le=0;le<p;le++)qh(t,4*le,a,s);return 0}let x=35215*i*i,[E,N,v]=l,[S,P,ne]=c,[se,ce,de]=d||c,re=0;for(let le=0;le<n;le++)for(let T=0;T<o;T++){let q=le*o+T,Q=q*4,we=m[q]===g[q]?0:Bh(t,e,Q,Q,!1);if(Math.abs(we)>x){let ke=Dh(t,T,le,o,n,m,g)||Dh(e,T,le,o,n,g,m);!u&&ke?s&&!f&&Ri(s,Q,E,N,v):(s&&(we<0?Ri(s,Q,se,ce,de):Ri(s,Q,S,P,ne)),re++)}else s&&!f&&qh(t,Q,a,s)}return re}function rc(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Dh(t,e,s,o,n,r,i){let a=Math.max(e-1,0),l=Math.max(s-1,0),c=Math.min(e+1,o-1),u=Math.min(s+1,n-1),d=s*o+e,f=e===a||e===c||s===l||s===u?1:0,p=0,m=0,g=0,b=0,x=0,E=0;for(let N=a;N<=c;N++)for(let v=l;v<=u;v++){if(N===e&&v===s)continue;let S=Bh(t,t,d*4,(v*o+N)*4,!0);if(S===0){if(f++,f>2)return!1}else S<p?(p=S,g=N,b=v):S>m&&(m=S,x=N,E=v)}return p===0||m===0?!1:Ti(r,g,b,o,n)&&Ti(i,g,b,o,n)||Ti(r,x,E,o,n)&&Ti(i,x,E,o,n)}function Ti(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),c=t[s*o+e],u=e===r||e===a||s===i||s===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===s)&&(u+=+(c===t[f*o+d]),u>2))return!0;return!1}function Bh(t,e,s,o,n){let r=t[s],i=t[s+1],a=t[s+2],l=t[s+3],c=e[o],u=e[o+1],d=e[o+2],f=e[o+3],p=r-c,m=i-u,g=a-d,b=l-f;if(!p&&!m&&!g&&!b)return 0;if(l<255||f<255){let S=48+159*(s%2),P=48+159*((s/1.618033988749895|0)%2),ne=48+159*((s/2.618033988749895|0)%2);p=(r*l-c*f-S*b)/255,m=(i*l-u*f-P*b)/255,g=(a*l-d*f-ne*b)/255}let x=p*.29889531+m*.58662247+g*.11448223;if(n)return x;let E=p*.59597799-m*.2741761-g*.32180189,N=p*.21147017-m*.52261711+g*.31114694,v=.5053*x*x+.299*E*E+.1957*N*N;return x>0?-v:v}function Ri(t,e,s,o,n){t[e+0]=s,t[e+1]=o,t[e+2]=n,t[e+3]=255}function qh(t,e,s,o){let n=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;Ri(o,e,n,n,n)}var Wh=h0(()=>{});var es=Z((CA,Kh)=>{var kn=require("fs"),Xk=require("path"),Vk=require("os"),Jk="nex-visual-";function Yh(t){return Xk.join(Vk.tmpdir(),`${Jk}${Date.now()}-${t}`)}var ic=null;function Ci(){return ic||(ic=jh().PNG),ic}var ac=null;function Zk(){if(!ac){let t=(Wh(),y0(Uh));ac=t.default||t}return ac}function uc(t,e,{threshold:s=.1}={}){let o=Ci(),n=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),c=Hh(r,a,l),u=Hh(i,a,l),d=new o({width:a,height:l}),f=n(c,u,d.data,a,l,{threshold:s,includeAA:!1}),p=a*l,m=(f/p*100).toFixed(1),g=Qk(d.data,a,l,3,3),b=Yh("diff.png");return kn.writeFileSync(b,o.sync.write(d),{mode:384}),{diffPath:b,diffPercent:parseFloat(m),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function Hh(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 Qk(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 c=0;c<n;c++)for(let u=0;u<o;u++){let d=0,f=0,p=u*i,m=c*a,g=Math.min(p+i,e),b=Math.min(m+a,s);for(let x=m;x<b;x++)for(let E=p;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[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:E,changedPercent:parseFloat(x),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var Gh=[{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 eS(t,{viewports:e=Gh,height:s=800,fullPage:o=!1,timeout:n=3e4}={}){let{browserScreenshot:r}=xn(),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 zh(t,e=[]){let s=Ci(),o=s.sync.read(kn.readFileSync(t));for(let i of e){let a=tS(i.color||"#FF0000");i.type==="box"?(nS(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&cc(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(sS(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&cc(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(oS(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&cc(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let n=Yh("annotated.png");kn.writeFileSync(n,s.sync.write(o),{mode:384});let r=kn.readFileSync(n).toString("base64");return{path:n,base64:r,media_type:"image/png"}}function tS(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 dn(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 nS(t,e,s,o,n,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<o;l++)dn(t,e+l,s+a,r),dn(t,e+l,s+n-1-a,r);for(let l=0;l<n;l++)dn(t,e+a,s+l,r),dn(t,e+o-1-a,s+l,r)}}function lc(t,e,s,o,n,r,i=3){let a=Math.abs(o-e),l=Math.abs(n-s),c=e<o?1:-1,u=s<n?1:-1,d=a-l,f=e,p=s;for(;;){let m=Math.floor(i/2);for(let b=-m;b<=m;b++)for(let x=-m;x<=m;x++)dn(t,f+b,p+x,r);if(f===o&&p===n)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,p+=u)}}function sS(t,e,s,o,n,r,i=3){lc(t,e,s,o,n,r,i);let a=Math.atan2(n-s,o-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;lc(t,o,n,Math.round(o+l*Math.cos(c)),Math.round(n+l*Math.sin(c)),r,i),lc(t,o,n,Math.round(o+l*Math.cos(u)),Math.round(n+l*Math.sin(u)),r,i)}function oS(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 c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(s+a*Math.sin(c));dn(t,u,d,n)}}}function cc(t,e,s,o,n){let i=o.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)dn(t,e+c,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)dn(t,e+l,s+a-1,n),dn(t,e+l,s+a-2,n);for(let l=0;l<o.length;l++){let c=e+2+l*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)dn(t,c+d,s+u,n)}}async function*rS(t,e,{maxIterations:s=20,hmrDelay:o=1500,width:n=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=xn(),l=iS("chokidar"),c=await a(t,{width:n,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:c.path,base64:c.base64,media_type:c.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let u=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;u<s;){await lS(()=>d,3e5),d=!1,u++,await aS(o);let p=await a(t,{width:n,height:r,timeout:i}),m=null;try{m=uc(c.path,p.path)}catch{}c=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function iS(t){try{return require(t)}catch{return null}}function aS(t){return new Promise(e=>setTimeout(e,t))}function lS(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 cS(t,{sampleRate:e=4}={}){let o=Ci().sync.read(kn.readFileSync(t)),n=new Map;for(let c=0;c<o.height;c+=e)for(let u=0;u<o.width;u+=e){let d=(c*o.width+u)*4,f=o.data[d],p=o.data[d+1],m=o.data[d+2];if(o.data[d+3]<128)continue;let b=Math.round(f/8)*8,x=Math.round(p/8)*8,E=Math.round(m/8)*8,N=`${b},${x},${E}`;n.set(N,(n.get(N)||0)+1)}let r=[...n.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,p]=c.split(",").map(Number);return{hex:uS(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:dS(d,f,p)}}),l=fS(o);return{colors:a,spacing:l,dimensions:{width:o.width,height:o.height},imagePath:t}}function uS(t,e,s){return"#"+[t,e,s].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function dS(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 fS(t){let e=[],s=!1,o=0,n=pS(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let c=(i*t.width+l)*4;if(Math.abs(t.data[c]-n.r)>20||Math.abs(t.data[c+1]-n.g)>20||Math.abs(t.data[c+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 pS(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 hS(t,e,{width:s,height:o=800,fullPage:n=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=xn(),c=Ci().sync.read(kn.readFileSync(e)),u=s||c.width,d=o||c.height,f=await a(t,{width:u,height:d,fullPage:n,timeout:i}),p=uc(e,f.path,{threshold:r}),m=zh(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,b)=>{let N=Math.ceil(p.width/3),v=Math.ceil(p.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 se=0;se<3;se++)for(let ce=0;ce<3;ce++)S[se][ce]===g.name&&(P=ce,ne=se);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:p.diffPath,annotatedPath:m.path,diffPercent:p.diffPercent,changedPixels:p.changedPixels,totalPixels:p.totalPixels,regions:p.regionSummary,liveBase64:f.base64,diffBase64:kn.readFileSync(p.diffPath).toString("base64"),annotatedBase64:m.base64}}Kh.exports={pixelDiff:uc,responsiveSweep:eS,annotateImage:zh,visualWatch:rS,extractDesignTokens:cS,designCompare:hS,DEFAULT_VIEWPORTS:Gh}});var dc=Z((AA,Xh)=>{var{C:De}=at(),Fo="",gt=[],qo=0,ts=null;function mS(t){ts=t}function gS(t,e){Fo=t,gt=[],qo=0;for(let o of e){qo++;let n=`t${qo}`;gt.push({id:n,description:o.description||o.title||o.name||o.task||`Task ${qo}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let s=gt.map(o=>({...o}));return ts&&ts("create",{name:t,tasks:s}),s}function yS(t,e,s){let o=gt.find(n=>n.id===t);return o?(o.status=e,s!==void 0&&(o.result=s),ts&&ts("update",{id:t,status:e,result:s}),{...o}):null}function wS(){return{name:Fo,tasks:gt.map(t=>({...t}))}}function bS(){Fo="",gt=[],qo=0,ts&&ts("clear",{})}function $S(){return gt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=gt.find(o=>o.id===e);return s&&s.status==="done"}))}function _S(){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 n of gt){let r,i;switch(n.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=n.dependsOn.length>0?` ${De.dim}(after: ${n.dependsOn.join(", ")})${De.reset}`:"",l=`[${n.status}]`,c=n.description.length>50?n.description.substring(0,47)+"...":n.description;if(t.push(` ${i}${r}${De.reset} ${De.bold}${n.id}${De.reset} ${c.padEnd(40)} ${i}${l}${De.reset}${a}`),n.result&&n.status==="done"){let u=n.result.length>60?n.result.substring(0,57)+"...":n.result;t.push(` ${De.dim}\u2192 ${u}${De.reset}`)}}let e=gt.filter(n=>n.status==="done").length,s=gt.filter(n=>n.status==="failed").length,o=gt.length;return t.push(` ${De.dim}${"\u2500".repeat(40)}${De.reset}`),t.push(` ${De.dim}${e}/${o} done${s>0?`, ${s} failed`:""}${De.reset}`),t.join(`
152
+ `)}function xS(){return gt.length>0&&gt.some(t=>t.status==="pending"||t.status==="in_progress")}Xh.exports={createTasks:gS,updateTask:yS,getTaskList:wS,clearTasks:bS,getReadyTasks:$S,renderTaskList:_S,setOnChange:mS,hasActiveTasks:xS}});var pc=Z((OA,tm)=>{var{callChat:kS}=dt(),{estimateTokens:fc}=fn(),Vh=process.env.NEX_COMPACTION!=="false",Jh=6,Zh=2e3,Qh=3,SS=`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.
153
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.
154
154
 
155
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:
@@ -181,38 +181,38 @@ Format your output as:
181
181
 
182
182
  <summary>
183
183
  [Sections 1-9 above]
184
- </summary>`,ts=0;async function _S(t){if(!zp||t.length<Kp||ts>=Vp)return null;let e=[{role:"system",content:bS},{role:"user",content:Jp(t)}];try{let o=((await $S(e,[],{temperature:0,maxTokens:Xp})).content||"").trim();if(!o)return ts++,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 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 xS(){ts=0}function Jp(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}
184
+ </summary>`,ns=0;async function vS(t){if(!Vh||t.length<Jh||ns>=Qh)return null;let e=[{role:"system",content:SS},{role:"user",content:em(t)}];try{let o=((await kS(e,[],{temperature:0,maxTokens:Zh})).content||"").trim();if(!o)return ns++,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 ns++,null;let r=t.reduce((a,l)=>a+fc(l.content||"")+(l.tool_calls?fc(JSON.stringify(l.tool_calls)):0),0),i=fc(o);return i>=r*.8?(ns++,null):(ns=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
185
+ ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return ns++,null}}function ES(){ns=0}function em(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}
186
186
  tools: ${n}`}return`[${s}] ${o}`}).join(`
187
187
 
188
- `)}Zp.exports={compactMessages:_S,formatMessagesForSummary:Jp,resetCompactionFailures:xS,COMPACTION_ENABLED:zp,COMPACTION_MIN_MESSAGES:Kp,COMPACTION_SUMMARY_BUDGET:Xp,MAX_CONSECUTIVE_FAILURES:Vp}});var dn=Z((EA,lm)=>{var kS=require("path");function em(){return dt().getActiveModel()}var SS={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},vS={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,Qp=1e3,uc=new WeakMap,ss=null;function ES(){if(ss!==null)return ss;try{let t=em(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[o,n]of Object.entries(vS))if(s.startsWith(o))return ss=n,ss;return ss=SS[e]||4,ss}catch{return 4}}function TS(){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)}`,s=ns.get(e);if(s!==void 0)return ns.delete(e),ns.set(e,s),s;let o=Math.ceil(t.length/ES());if(ns.size>=Qp){let n=Qp>>1,r=ns.keys();for(let i=0;i<n;i++)ns.delete(r.next().value)}return ns.set(e,o),o}function RS(t){if(uc.has(t))return uc.get(t);let e=JSON.stringify(t);return uc.set(t,e),e}function rs(t){let s=4;if(t.content&&(s+=os(t.content)),t.tool_calls)for(let o of t.tool_calls){s+=4,s+=os(o.function?.name||"");let n=o.function?.arguments;typeof n=="string"?s+=os(n):n&&(s+=os(JSON.stringify(n)))}return s}function Vt(t){let e=0;for(let s of t)e+=rs(s);return e}function CS(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+=rs(e[r]);return n}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 em()?.contextWindow||32768}var yt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function AS(t,e){let s=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(yt.result&&t.length===yt.msgCount&&s===yt.lastMsgRef&&o===yt.toolCount)return yt.result;let n,r,i,a;if(yt.messagesRef===t&&t.length>yt.msgCount&&yt.msgCount>=0){n=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]);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=rs(h);n+=m,h.role==="system"?r+=m:h.role==="tool"?a+=m:i+=m}}let l=Ci(e),c=n+l,u=Ai(),d=u>0?c/u*100:0,f={used:c,limit:u,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return yt={msgCount:t.length,lastMsgRef:s,toolCount:o,result:f,messagesRef:t,messageTokens:n,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Bo=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,tm=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,nm=parseInt(process.env.NEX_KEEP_RECENT,10)||10,sm={essential:.6,standard:.65,full:Math.min(Bo,.75)};function om(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Bo;try{let{getActiveTier:t}=Io(),e=t();return sm[e]??Bo}catch{return Bo}}var OS=200,NS=1e3;function rm(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(`
189
- `);if(n.length<=10){let m=Math.floor(o*.6),g=Math.floor(o*.4),$=t.substring(0,m),x=t.substring(t.length-g);return $+`
188
+ `)}tm.exports={compactMessages:vS,formatMessagesForSummary:em,resetCompactionFailures:ES,COMPACTION_ENABLED:Vh,COMPACTION_MIN_MESSAGES:Jh,COMPACTION_SUMMARY_BUDGET:Zh,MAX_CONSECUTIVE_FAILURES:Qh}});var fn=Z((NA,dm)=>{var TS=require("path");function sm(){return dt().getActiveModel()}var RS={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},CS={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},ss=new Map,nm=1e3,hc=new WeakMap,os=null;function AS(){if(os!==null)return os;try{let t=sm(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[o,n]of Object.entries(CS))if(s.startsWith(o))return os=n,os;return os=RS[e]||4,os}catch{return 4}}function OS(){os=null}function rs(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=ss.get(e);if(s!==void 0)return ss.delete(e),ss.set(e,s),s;let o=Math.ceil(t.length/AS());if(ss.size>=nm){let n=nm>>1,r=ss.keys();for(let i=0;i<n;i++)ss.delete(r.next().value)}return ss.set(e,o),o}function NS(t){if(hc.has(t))return hc.get(t);let e=JSON.stringify(t);return hc.set(t,e),e}function is(t){let s=4;if(t.content&&(s+=rs(t.content)),t.tool_calls)for(let o of t.tool_calls){s+=4,s+=rs(o.function?.name||"");let n=o.function?.arguments;typeof n=="string"?s+=rs(n):n&&(s+=rs(JSON.stringify(n)))}return s}function Vt(t){let e=0;for(let s of t)e+=is(s);return e}function PS(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+=is(e[r]);return n}var mc=new WeakMap;function Ai(t){if(!t||t.length===0)return 0;if(mc.has(t))return mc.get(t);let e=rs(JSON.stringify(t));return mc.set(t,e),e}function Oi(){return sm()?.contextWindow||32768}var yt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function MS(t,e){let s=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(yt.result&&t.length===yt.msgCount&&s===yt.lastMsgRef&&o===yt.toolCount)return yt.result;let n,r,i,a;if(yt.messagesRef===t&&t.length>yt.msgCount&&yt.msgCount>=0){n=yt.messageTokens,r=yt.systemTokens,i=yt.conversationTokens,a=yt.toolResultTokens;for(let p=yt.msgCount;p<t.length;p++){let m=is(t[p]);n+=m,t[p].role==="system"?r+=m:t[p].role==="tool"?a+=m:i+=m}}else{n=0,r=0,i=0,a=0;for(let p of t){let m=is(p);n+=m,p.role==="system"?r+=m:p.role==="tool"?a+=m:i+=m}}let l=Ai(e),c=n+l,u=Oi(),d=u>0?c/u*100:0,f={used:c,limit:u,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return yt={msgCount:t.length,lastMsgRef:s,toolCount:o,result:f,messagesRef:t,messageTokens:n,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Bo=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,om=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,rm=parseInt(process.env.NEX_KEEP_RECENT,10)||10,im={essential:.6,standard:.65,full:Math.min(Bo,.75)};function am(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Bo;try{let{getActiveTier:t}=Io(),e=t();return im[e]??Bo}catch{return Bo}}var LS=200,IS=1e3;function lm(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(`
189
+ `);if(n.length<=10){let m=Math.floor(o*.6),g=Math.floor(o*.4),b=t.substring(0,m),x=t.substring(t.length-g);return b+`
190
190
  ...(${t.length} chars total)...
191
- `+x}let r=Math.floor(n.length*.4),i=Math.floor(n.length*.4),a=[],l=0,c=Math.floor(o*.4);for(let m=0;m<r&&l<c;m++)if(l+n[m].length+1>c&&n[m].trim().startsWith("```")){a.push(n[m]),l+=n[m].length+1;let g=m+1;for(;g<n.length&&l<c*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 u=[],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("```")){u.push(n[m]),d+=n[m].length+1;let g=m-1;for(;g>=0&&d<f*1.5&&!n[g].trim().startsWith("```");)u.push(n[g]),d+=n[g].length+1,g--;g>=0&&n[g].trim().startsWith("```")&&(u.push(n[g]),d+=n[g].length+1),m=g}else u.push(n[m]),d+=n[m].length+1;u.reverse();let h=n.length-a.length-u.length;return a.join(`
191
+ `+x}let r=Math.floor(n.length*.4),i=Math.floor(n.length*.4),a=[],l=0,c=Math.floor(o*.4);for(let m=0;m<r&&l<c;m++)if(l+n[m].length+1>c&&n[m].trim().startsWith("```")){a.push(n[m]),l+=n[m].length+1;let g=m+1;for(;g<n.length&&l<c*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 u=[],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("```")){u.push(n[m]),d+=n[m].length+1;let g=m-1;for(;g>=0&&d<f*1.5&&!n[g].trim().startsWith("```");)u.push(n[g]),d+=n[g].length+1,g--;g>=0&&n[g].trim().startsWith("```")&&(u.push(n[g]),d+=n[g].length+1),m=g}else u.push(n[m]),d+=n[m].length+1;u.reverse();let p=n.length-a.length-u.length;return a.join(`
192
192
  `)+`
193
- ...(${h} lines omitted, ${n.length} total)...
193
+ ...(${p} lines omitted, ${n.length} total)...
194
194
  `+u.join(`
195
- `)}function Ks(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:NS,o=e==="aggressive"?50:e==="medium"?100:OS;if(t.role==="tool"){let n=typeof t.content=="string"?t.content:JSON.stringify(t.content);return n.length>o?{...t,content:rm(n,o)}:t}if(t.role==="assistant"){let n={...t};return n.content&&n.content.length>s&&(n.content=n.content.substring(0,s)+`
196
- ...(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 im(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(kS.basename(l)))&&a++;n+=Math.min(30,a*10)}return Math.min(100,n)}function am(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 PS(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:
195
+ `)}function Ks(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:IS,o=e==="aggressive"?50:e==="medium"?100:LS;if(t.role==="tool"){let n=typeof t.content=="string"?t.content:JSON.stringify(t.content);return n.length>o?{...t,content:lm(n,o)}:t}if(t.role==="assistant"){let n={...t};return n.content&&n.content.length>s&&(n.content=n.content.substring(0,s)+`
196
+ ...(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 cm(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(TS.basename(l)))&&a++;n+=Math.min(30,a*10)}return Math.min(100,n)}function um(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 jS(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:
197
197
  `+n.map(r=>`- ${r}`).join(`
198
198
  `)),o.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
199
199
  ${o.join(`
200
- `)}`,_pinned:!0,_progressSnapshot:!0}}var zs={msgCount:-1,lastMsgRef:null,result:null};function MS(){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 LS(t,e,s={}){let o=t.length>0?t[t.length-1]:null;if(!s.force&&zs.result&&t.length===zs.msgCount&&o===zs.lastMsgRef)return zs.result;let n=s.threshold??om(),r=s.safetyMargin??tm,i=s.keepRecent??nm,a=Ai(),l=Ci(e),c=Math.floor(a*(n-r)),u=c-l,d=Vt(t);if(d+l<=c){let re={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return zs={msgCount:t.length,lastMsgRef:o,result:re},re}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(re=>Ks(re,"light")),v=Ln(m,N,E),S=Vt(v);if(S+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:h-S};if(N=x.map(re=>Ks(re,"medium")),v=Ln(m,N,E),S=Vt(v),S+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:h-S};if(N=x.map(re=>Ks(re,"aggressive")),v=Ln(m,N,E),S=Vt(v),S+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:h-S};let P=process.env.NEX_SKIP_COMPACTOR==="1",ne=x.filter(re=>re._pinned),se=x.filter(re=>!re._compacted&&!re._pinned);if(!P&&se.length>=6)try{let{compactMessages:re}=cc(),le=await re(se);if(le){let T=x.filter(ke=>ke._compacted&&!ke._pinned),q=[...ne,...T,le.message],Q=Ln(m,q,E),we=Vt(Q);if(we+l<=c)return{messages:Q,compressed:!0,compacted:!0,tokensRemoved:h-we};x=q}}catch(re){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",re.message)}let ce=am([...N,...E]),de=N.map((re,le)=>({msg:re,score:re._pinned?1/0:im(re,le,N.length,ce),tokens:rs(re)}));for(;de.length>0&&S>u;){let re=-1;for(let le=0;le<de.length;le++)de[le].score!==1/0&&(re===-1||de[le].score<de[re].score)&&(re=le);if(re===-1)break;S-=de[re].tokens,de.splice(re,1)}return N=de.map(re=>re.msg),v=Ln(m,N,E),S=Vt(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:h-S}}function Ln(t,e,s){let o=[];return t&&o.push(t),o.push(...e,...s),o}function IS(t,e){if(!t)return"";if(os(t)<=e)return t;let o=e*4,n=t.split(`
201
- `),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?`
202
- `:"")+h,l++}let c="",u=0;for(let h=n.length-1;h>=l;h--){let m=n[h]+(c?`
200
+ `)}`,_pinned:!0,_progressSnapshot:!0}}var zs={msgCount:-1,lastMsgRef:null,result:null};function DS(){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 qS(t,e,s={}){let o=t.length>0?t[t.length-1]:null;if(!s.force&&zs.result&&t.length===zs.msgCount&&o===zs.lastMsgRef)return zs.result;let n=s.threshold??am(),r=s.safetyMargin??om,i=s.keepRecent??rm,a=Oi(),l=Ai(e),c=Math.floor(a*(n-r)),u=c-l,d=Vt(t);if(d+l<=c){let re={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return zs={msgCount:t.length,lastMsgRef:o,result:re},re}let p=d,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let b=Math.max(g,t.length-i),x=t.slice(g,b),E=t.slice(b),N=x.map(re=>Ks(re,"light")),v=Ln(m,N,E),S=Vt(v);if(S+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-S};if(N=x.map(re=>Ks(re,"medium")),v=Ln(m,N,E),S=Vt(v),S+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-S};if(N=x.map(re=>Ks(re,"aggressive")),v=Ln(m,N,E),S=Vt(v),S+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-S};let P=process.env.NEX_SKIP_COMPACTOR==="1",ne=x.filter(re=>re._pinned),se=x.filter(re=>!re._compacted&&!re._pinned);if(!P&&se.length>=6)try{let{compactMessages:re}=pc(),le=await re(se);if(le){let T=x.filter(ke=>ke._compacted&&!ke._pinned),q=[...ne,...T,le.message],Q=Ln(m,q,E),we=Vt(Q);if(we+l<=c)return{messages:Q,compressed:!0,compacted:!0,tokensRemoved:p-we};x=q}}catch(re){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",re.message)}let ce=um([...N,...E]),de=N.map((re,le)=>({msg:re,score:re._pinned?1/0:cm(re,le,N.length,ce),tokens:is(re)}));for(;de.length>0&&S>u;){let re=-1;for(let le=0;le<de.length;le++)de[le].score!==1/0&&(re===-1||de[le].score<de[re].score)&&(re=le);if(re===-1)break;S-=de[re].tokens,de.splice(re,1)}return N=de.map(re=>re.msg),v=Ln(m,N,E),S=Vt(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-S}}function Ln(t,e,s){let o=[];return t&&o.push(t),o.push(...e,...s),o}function FS(t,e){if(!t)return"";if(rs(t)<=e)return t;let o=e*4,n=t.split(`
201
+ `),r=Math.floor(o*.6),i=Math.floor(o*.4),a="",l=0;for(let p of n){if(a.length+p.length+1>r)break;a+=(a?`
202
+ `:"")+p,l++}let c="",u=0;for(let p=n.length-1;p>=l;p--){let m=n[p]+(c?`
203
203
  `:"")+c;if(m.length>i)break;c=m,u++}let f=`
204
204
 
205
205
  ... (${n.length-l-u} lines omitted, ${n.length} total) ...
206
206
 
207
- `;return a+f+c}var jS=6;function DS(t,e,s=!1){let o=Ai(),n=Ci(e),r=Math.floor(o*(s?.35:.5))-n,i=Vt(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let l=null,c=0;t.length>0&&t[0].role==="system"&&(l=t[0],c=1);let u=s?2:jS,d=Math.max(c,t.length-u),f=t.slice(c,d),h=t.slice(d),m=f.map(S=>Ks(S,"aggressive"));s&&(h=h.map(S=>Ks(S,"aggressive")));let g=Ln(l,m,h),$=Vt(g);for(;m.length>0&&$>r;){let S=m.shift();$-=rs(S)}s&&$>r&&(h=h.filter(P=>P.role==="user").slice(-1),g=Ln(l,[],h),$=Vt(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-Vt(g)}}lm.exports={estimateTokens:os,estimateMessageTokens:rs,estimateMessagesTokens:Vt,estimateDeltaTokens:CS,estimateToolsTokens:Ci,serializeMessage:RS,getContextWindow:Ai,getUsage:AS,compressMessage:Ks,compressToolResult:rm,scoreMessageRelevance:im,extractActiveFiles:am,buildProgressSnapshot:PS,fitToContext:LS,forceCompress:DS,truncateFileContent:IS,invalidateTokenRatioCache:TS,invalidateFitToContextCache:MS,getEffectiveCompressionThreshold:om,COMPRESSION_THRESHOLD:Bo,TIER_COMPRESSION_THRESHOLDS:sm,SAFETY_MARGIN:tm,KEEP_RECENT:nm}});var $c=Z((TA,xm)=>{var Ve=require("fs"),Sn=require("path"),{atomicWrite:cm,withFileLockSync:um}=Gn(),qS=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 s=Sn.join(t,e),o=Ve.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 Wo(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(`
208
- `);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(c=>c.trim()).filter(Boolean):e[a]=l}s=o[2]}return{frontmatter:e,body:s}}function dm(t){let e=Sn.join(Vs(),`${t}.md`);if(!Ve.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Ve.readFileSync(e,"utf-8"),{frontmatter:o,body:n}=Wo(s);return{name:t,content:s,body:n,frontmatter:o}}function FS(t,e){let s=Sn.join(Vs(),`${t}.md`);cm(s,e),WS(t,e),BS()}function BS(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=pc();Ve.existsSync(t)&&setImmediate(async()=>{try{await wm()}catch{}})}function US(t){let e=Sn.join(Vs(),`${t}.md`);return Ve.existsSync(e)?(Ve.unlinkSync(e),HS(t),!0):!1}function Oi(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!qS.has(e))}function mc(t){let e={},{frontmatter:s,body:o}=Wo(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(`
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){cm(Ni(),JSON.stringify(t,null,2))}function WS(t,e){um(Ni(),()=>{let s=gc(),{frontmatter:o}=Wo(e),n=Array.isArray(o.tags)?o.tags:[];s.documents[t]={keywords:mc(e),tags:n,modified:new Date().toISOString()},yc(s)})}function HS(t){um(Ni(),()=>{let e=gc();delete e.documents[t],yc(e)})}function hc(){let t=Uo(),e={documents:{}};for(let s of t){let o=Ve.readFileSync(s.path,"utf-8"),{frontmatter:n}=Wo(o),r=Array.isArray(n.tags)?n.tags:[];e.documents[s.name]={keywords:mc(o),tags:r,modified:s.modified.toISOString()}}return yc(e),e}function fm(){let t=gc(),e=Uo();for(let s of e){let o=t.documents[s.name];if(!o||new Date(o.modified)<s.modified)return hc()}for(let s of Object.keys(t.documents))if(!e.some(o=>o.name===s))return hc();return t}function hm(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=Oi(t);if(n.length===0)return[];let r=fm(),i=[];for(let[a,l]of Object.entries(r.documents)){let c=0;for(let u of n){l.keywords[u]&&(c+=l.keywords[u]);for(let[d,f]of Object.entries(l.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(c+=f*.3)}c>=o&&i.push({name:a,score:c})}return i.sort((a,l)=>l.score-a.score),i.slice(0,s)}var pm=process.env.NEX_EMBED_MODEL||"nomic-embed-text",fc=400,YS=50;async function mm(){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 c=n.get(o.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{l(new Error("bad json"))}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(pm.split(":")[0]))}catch{return!1}}async function wc(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:pm,prompt:t});return new Promise((a,l)=>{let c=r.request(n,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){l(f)}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("embedding timeout"))}),c.write(i),c.end()})}function gm(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 ym(t){let e=t.split(/\s+/),s=[],o=0;for(;o<e.length;){let n=e.slice(o,o+fc).join(" ");if(s.push({text:n,offset:o}),o+fc>=e.length)break;o+=fc-YS}return s}async function wm(){let t=Uo(),e={documents:{}},s=pc();if(Ve.existsSync(s))try{e=JSON.parse(Ve.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=Ve.readFileSync(o.path,"utf-8"),i=ym(r),a=[];for(let l of i){let c=await wc(l.text);a.push({text:l.text,embedding:c,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 Ve.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function $m(t,e={}){let{topK:s=3,minSimilarity:o=.3}=e,n=pc();if(!Ve.existsSync(n))return[];let r;try{r=JSON.parse(Ve.readFileSync(n,"utf-8"))}catch{return[]}let i=await wc(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let h=gm(i,f.embedding);h>u&&(u=h,d=f.text)}u>=o&&a.push({name:l,score:u,bestChunk:d})}return a.sort((l,c)=>c.score-l.score),a.slice(0,s)}function bm(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 _m(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=hm(t,{topK:s,minScore:o}),r=n;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await mm()){let a=await $m(t,{topK:s});r=bm(n,a,{topK:s})}}catch{}return r.map(i=>{let a=dm(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},GS=3e5;async function zS(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<GS)return Xs.result;let n;try{n=await _m(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let r;try{r=dn().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],l=0;for(let u of n){let d=u.content||"",f=r(d);if(l+f>i){let m=i-l;if(m<100)break;let g=m/f;d=d.slice(0,Math.floor(d.length*g))+`
210
- ...(truncated)`}let h=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${h}) ---
207
+ `;return a+f+c}var BS=6;function US(t,e,s=!1){let o=Oi(),n=Ai(e),r=Math.floor(o*(s?.35:.5))-n,i=Vt(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let l=null,c=0;t.length>0&&t[0].role==="system"&&(l=t[0],c=1);let u=s?2:BS,d=Math.max(c,t.length-u),f=t.slice(c,d),p=t.slice(d),m=f.map(S=>Ks(S,"aggressive"));s&&(p=p.map(S=>Ks(S,"aggressive")));let g=Ln(l,m,p),b=Vt(g);for(;m.length>0&&b>r;){let S=m.shift();b-=is(S)}s&&b>r&&(p=p.filter(P=>P.role==="user").slice(-1),g=Ln(l,[],p),b=Vt(g)),g=Ln(l,m,p);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-Vt(g)}}dm.exports={estimateTokens:rs,estimateMessageTokens:is,estimateMessagesTokens:Vt,estimateDeltaTokens:PS,estimateToolsTokens:Ai,serializeMessage:NS,getContextWindow:Oi,getUsage:MS,compressMessage:Ks,compressToolResult:lm,scoreMessageRelevance:cm,extractActiveFiles:um,buildProgressSnapshot:jS,fitToContext:qS,forceCompress:US,truncateFileContent:FS,invalidateTokenRatioCache:OS,invalidateFitToContextCache:DS,getEffectiveCompressionThreshold:am,COMPRESSION_THRESHOLD:Bo,TIER_COMPRESSION_THRESHOLDS:im,SAFETY_MARGIN:om,KEEP_RECENT:rm}});var kc=Z((PA,vm)=>{var Ve=require("fs"),Sn=require("path"),{atomicWrite:fm,withFileLockSync:pm}=zn(),WS=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 Pi(){return Sn.join(Vs(),".brain-index.json")}function wc(){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 s=Sn.join(t,e),o=Ve.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 Wo(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(`
208
+ `);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(c=>c.trim()).filter(Boolean):e[a]=l}s=o[2]}return{frontmatter:e,body:s}}function hm(t){let e=Sn.join(Vs(),`${t}.md`);if(!Ve.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Ve.readFileSync(e,"utf-8"),{frontmatter:o,body:n}=Wo(s);return{name:t,content:s,body:n,frontmatter:o}}function HS(t,e){let s=Sn.join(Vs(),`${t}.md`);fm(s,e),zS(t,e),YS()}function YS(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=wc();Ve.existsSync(t)&&setImmediate(async()=>{try{await _m()}catch{}})}function GS(t){let e=Sn.join(Vs(),`${t}.md`);return Ve.existsSync(e)?(Ve.unlinkSync(e),KS(t),!0):!1}function Ni(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!WS.has(e))}function bc(t){let e={},{frontmatter:s,body:o}=Wo(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(`
209
+ `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of Ni(a))e[l]=(e[l]||0)+3}for(let i of Ni(o||t))e[i]=(e[i]||0)+1;return e}function $c(){let t=Pi();if(!Ve.existsSync(t))return{documents:{}};try{return JSON.parse(Ve.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function _c(t){fm(Pi(),JSON.stringify(t,null,2))}function zS(t,e){pm(Pi(),()=>{let s=$c(),{frontmatter:o}=Wo(e),n=Array.isArray(o.tags)?o.tags:[];s.documents[t]={keywords:bc(e),tags:n,modified:new Date().toISOString()},_c(s)})}function KS(t){pm(Pi(),()=>{let e=$c();delete e.documents[t],_c(e)})}function yc(){let t=Uo(),e={documents:{}};for(let s of t){let o=Ve.readFileSync(s.path,"utf-8"),{frontmatter:n}=Wo(o),r=Array.isArray(n.tags)?n.tags:[];e.documents[s.name]={keywords:bc(o),tags:r,modified:s.modified.toISOString()}}return _c(e),e}function mm(){let t=$c(),e=Uo();for(let s of e){let o=t.documents[s.name];if(!o||new Date(o.modified)<s.modified)return yc()}for(let s of Object.keys(t.documents))if(!e.some(o=>o.name===s))return yc();return t}function gm(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=Ni(t);if(n.length===0)return[];let r=mm(),i=[];for(let[a,l]of Object.entries(r.documents)){let c=0;for(let u of n){l.keywords[u]&&(c+=l.keywords[u]);for(let[d,f]of Object.entries(l.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(c+=f*.3)}c>=o&&i.push({name:a,score:c})}return i.sort((a,l)=>l.score-a.score),i.slice(0,s)}var ym=process.env.NEX_EMBED_MODEL||"nomic-embed-text",gc=400,XS=50;async function wm(){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 c=n.get(o.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{l(new Error("bad json"))}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(ym.split(":")[0]))}catch{return!1}}async function xc(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:ym,prompt:t});return new Promise((a,l)=>{let c=r.request(n,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){l(f)}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("embedding timeout"))}),c.write(i),c.end()})}function bm(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 $m(t){let e=t.split(/\s+/),s=[],o=0;for(;o<e.length;){let n=e.slice(o,o+gc).join(" ");if(s.push({text:n,offset:o}),o+gc>=e.length)break;o+=gc-XS}return s}async function _m(){let t=Uo(),e={documents:{}},s=wc();if(Ve.existsSync(s))try{e=JSON.parse(Ve.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=Ve.readFileSync(o.path,"utf-8"),i=$m(r),a=[];for(let l of i){let c=await xc(l.text);a.push({text:l.text,embedding:c,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 Ve.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function xm(t,e={}){let{topK:s=3,minSimilarity:o=.3}=e,n=wc();if(!Ve.existsSync(n))return[];let r;try{r=JSON.parse(Ve.readFileSync(n,"utf-8"))}catch{return[]}let i=await xc(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let p=bm(i,f.embedding);p>u&&(u=p,d=f.text)}u>=o&&a.push({name:l,score:u,bestChunk:d})}return a.sort((l,c)=>c.score-l.score),a.slice(0,s)}function km(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 Sm(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=gm(t,{topK:s,minScore:o}),r=n;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await wm()){let a=await xm(t,{topK:s});r=km(n,a,{topK:s})}}catch{}return r.map(i=>{let a=hm(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},VS=3e5;async function JS(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<VS)return Xs.result;let n;try{n=await Sm(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let r;try{r=fn().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],l=0;for(let u of n){let d=u.content||"",f=r(d);if(l+f>i){let m=i-l;if(m<100)break;let g=m/f;d=d.slice(0,Math.floor(d.length*g))+`
210
+ ...(truncated)`}let p=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${p}) ---
211
211
  ${d}`),l+=r(d),l>=i)break}if(a.length===0)return Xs={queryKey:o,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
212
212
 
213
213
  ${a.join(`
214
214
 
215
- `)}`;return Xs={queryKey:o,result:c,ts:Date.now()},c}xm.exports={getBrainDir:Vs,listDocuments:Uo,readDocument:dm,writeDocument:FS,removeDocument:US,buildIndex:hc,getIndex:fm,query:_m,getBrainContext:zS,isEmbeddingAvailable:mm,generateEmbedding:wc,buildEmbeddingIndex:wm,semanticQuery:$m,cosineSimilarity:gm,_keywordQuery:hm,_extractKeywords:mc,_chunkText:ym,parseFrontmatter:Wo,tokenize:Oi,_fuseResults:bm}});var Go=Z((RA,Mm)=>{var Fe=require("fs"),Ct=require("path"),KS=require("os"),{atomicWrite:Pi,withFileLockSync:km}=Gn(),Ho=["user","feedback","project","reference"],XS=50;function is(){return Ct.join(process.cwd(),".nex","memory")}function Js(){return Ct.join(is(),"memory.json")}function Sm(){return Ct.join(is(),"MEMORY.md")}function VS(){return Ct.join(process.cwd(),"NEX.md")}function vm(){return Ct.join(KS.homedir(),".nex","NEX.md")}function Mi(){let t=is();Fe.existsSync(t)||Fe.mkdirSync(t,{recursive:!0})}function Em(t){let e=Ct.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 Tm(t){Mi(),Pi(Js(),JSON.stringify(t,null,2))}function Rm(){let t=Js();if(!Fe.existsSync(t))return;let e=Yo(),s=Object.keys(e);if(s.length===0){try{Fe.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=Em("project"),l=Ct.join(a,`${i}.md`),c=r.split(`
215
+ `)}`;return Xs={queryKey:o,result:c,ts:Date.now()},c}vm.exports={getBrainDir:Vs,listDocuments:Uo,readDocument:hm,writeDocument:HS,removeDocument:GS,buildIndex:yc,getIndex:mm,query:Sm,getBrainContext:JS,isEmbeddingAvailable:wm,generateEmbedding:xc,buildEmbeddingIndex:_m,semanticQuery:xm,cosineSimilarity:bm,_keywordQuery:gm,_extractKeywords:bc,_chunkText:$m,parseFrontmatter:Wo,tokenize:Ni,_fuseResults:km}});var Go=Z((MA,jm)=>{var Fe=require("fs"),Ct=require("path"),ZS=require("os"),{atomicWrite:Mi,withFileLockSync:Em}=zn(),Ho=["user","feedback","project","reference"],QS=50;function as(){return Ct.join(process.cwd(),".nex","memory")}function Js(){return Ct.join(as(),"memory.json")}function Tm(){return Ct.join(as(),"MEMORY.md")}function ev(){return Ct.join(process.cwd(),"NEX.md")}function Rm(){return Ct.join(ZS.homedir(),".nex","NEX.md")}function Li(){let t=as();Fe.existsSync(t)||Fe.mkdirSync(t,{recursive:!0})}function Cm(t){let e=Ct.join(as(),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 Am(t){Li(),Mi(Js(),JSON.stringify(t,null,2))}function Om(){let t=Js();if(!Fe.existsSync(t))return;let e=Yo(),s=Object.keys(e);if(s.length===0){try{Fe.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=Cm("project"),l=Ct.join(a,`${i}.md`),c=r.split(`
216
216
  `)[0].slice(0,100),u=`---
217
217
  name: ${o}
218
218
  description: ${c}
@@ -220,7 +220,7 @@ type: project
220
220
  ---
221
221
 
222
222
  ${r}
223
- `;Pi(l,u)}Li();try{Fe.renameSync(t,t+".bak")}catch{}}function JS(t,e,s,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(!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=Em(t),i=Ct.join(r,`${n}.md`);if(Fe.existsSync(i))try{if(bc(Fe.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
+ `;Mi(l,u)}Ii();try{Fe.renameSync(t,t+".bak")}catch{}}function tv(t,e,s,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(!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=Cm(t),i=Ct.join(r,`${n}.md`);if(Fe.existsSync(i))try{if(Sc(Fe.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(`
224
224
  `)[0].slice(0,100),l=`---
225
225
  name: ${e}
226
226
  description: ${a}
@@ -228,83 +228,83 @@ type: ${t}
228
228
  ---
229
229
 
230
230
  ${s}
231
- `;return Pi(i,l),Li(),{ok:!0,path:i,updated:!0}}function ZS(t,e){if(!Ho.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=Ct.join(is(),t,`${s}.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 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 Cm(){let t=[],e=is();for(let s of Ho){let o=Ct.join(e,s);if(!Fe.existsSync(o))continue;let n;try{n=Fe.readdirSync(o).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of n){let i=Ct.join(o,r);try{let a=Fe.readFileSync(i,"utf-8"),l=bc(a);t.push({type:s,name:l.name||Ct.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function Li(){let t=Cm(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=XS+2)break;let o=`${s.type}/${Ct.basename(s.filePath)}`;e.push(`- [${s.name}](${o}) \u2014 ${s.description||"(no description)"}`)}Mi(),Pi(Sm(),e.join(`
231
+ `;return Mi(i,l),Ii(),{ok:!0,path:i,updated:!0}}function nv(t,e){if(!Ho.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=Ct.join(as(),t,`${s}.md`);if(!Fe.existsSync(o))return!1;try{return Fe.unlinkSync(o),Ii(),!0}catch{return!1}}function Sc(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 Nm(){let t=[],e=as();for(let s of Ho){let o=Ct.join(e,s);if(!Fe.existsSync(o))continue;let n;try{n=Fe.readdirSync(o).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of n){let i=Ct.join(o,r);try{let a=Fe.readFileSync(i,"utf-8"),l=Sc(a);t.push({type:s,name:l.name||Ct.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function Ii(){let t=Nm(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=QS+2)break;let o=`${s.type}/${Ct.basename(s.filePath)}`;e.push(`- [${s.name}](${o}) \u2014 ${s.description||"(no description)"}`)}Li(),Mi(Tm(),e.join(`
232
232
  `)+`
233
- `)}function Am(){let t=Sm();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function QS(t,e){Mi(),km(Js(),()=>{let s=Yo();s[t]={value:e,updatedAt:new Date().toISOString()},Tm(s)})}function ev(t){let e=Yo();return e[t]?e[t].value:null}function tv(t){return Mi(),km(Js(),()=>{let e=Yo();return t in e?(delete e[t],Tm(e),!0):!1})}function Om(){let t=Yo();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Nm(){let t=vm();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function Pm(){let t=VS();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function nv(){Rm();let t=[],e=Nm();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
234
- ${e}`);let s=Pm();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
235
- ${s}`);let o="",n=Am();if(n)o=n;else{let d=Om();d.length>0&&(o=`PROJECT MEMORY:
236
- ${d.map(h=>` ${h.key}: ${h.value}`).join(`
233
+ `)}function Pm(){let t=Tm();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function sv(t,e){Li(),Em(Js(),()=>{let s=Yo();s[t]={value:e,updatedAt:new Date().toISOString()},Am(s)})}function ov(t){let e=Yo();return e[t]?e[t].value:null}function rv(t){return Li(),Em(Js(),()=>{let e=Yo();return t in e?(delete e[t],Am(e),!0):!1})}function Mm(){let t=Yo();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Lm(){let t=Rm();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function Im(){let t=ev();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function iv(){Om();let t=[],e=Lm();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
234
+ ${e}`);let s=Im();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
235
+ ${s}`);let o="",n=Pm();if(n)o=n;else{let d=Mm();d.length>0&&(o=`PROJECT MEMORY:
236
+ ${d.map(p=>` ${p.key}: ${p.value}`).join(`
237
237
  `)}`)}let r=t.join(`
238
238
 
239
239
  `),i="You can save insights with save_memory(type, name, content) and remove them with delete_memory(type, name).",c=Math.max(1500,16e3-r.length-i.length-10);if(o.length>c&&c>200){let d=o.split(`
240
- `),f="";for(let h of d){if(f.length+h.length+1>c-60)break;f+=h+`
240
+ `),f="";for(let p of d){if(f.length+p.length+1>c-60)break;f+=p+`
241
241
  `}o=f.trimEnd()+`
242
242
  [Memory index truncated \u2014 use delete_memory to prune old entries]`}else o.length>c&&(o="");let u=[...t];return o&&u.push(o),u.length>0&&u.push(i),u.join(`
243
243
 
244
- `)}Mm.exports={saveMemory:JS,deleteMemory:ZS,scanMemories:Cm,rebuildIndex:Li,loadMemoryIndex:Am,remember:QS,recall:ev,forget:tv,listMemories:Om,loadGlobalInstructions:Nm,loadProjectInstructions:Pm,getMemoryContext:nv,_getMemoryDir:is,_getMemoryFile:Js,_getGlobalNexMdPath:vm,_parseMemoryFile:bc,_migrateIfNeeded:Rm,VALID_TYPES:Ho}});var Fm=Z((CA,qm)=>{var zo=require("fs"),_c=require("path"),xc=process.env.NEX_AUDIT!=="false",as=null;function Lm(){return as||(as=_c.join(process.cwd(),".nex","audit"),zo.existsSync(as)||zo.mkdirSync(as,{recursive:!0}),as)}function Im(){let t=new Date().toISOString().split("T")[0];return _c.join(Lm(),`${t}.jsonl`)}function sv(t){if(xc)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:jm(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)+`
245
- `;zo.appendFileSync(Im(),s,"utf-8")}catch{}}function jm(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 Dm(t={}){let e=Lm(),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=_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 c=JSON.parse(l);if(t.tool&&c.tool!==t.tool)continue;o.push(c)}catch{}if(t.date)break}return o}function ov(t=1){let e=Dm({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 rv(t){xc=t}function iv(){return xc}function av(){as=null}qm.exports={logToolExecution:sv,sanitizeArgs:jm,readAuditLog:Dm,getAuditSummary:ov,setAuditEnabled:rv,isAuditEnabled:iv,getAuditLogPath:Im,_reset:av}});var rg=Z((OA,og)=>{var Je=require("fs").promises,Zt=require("fs"),ie=require("path"),He=require("util").promisify(require("child_process").exec),ls=require("util").promisify(require("child_process").execFile),{spawnSync:lv}=require("child_process"),kc=require("axios"),{isForbidden:cv,isSSHForbidden:uv,isDangerous:dv,isCritical:Bm,isBashPathForbidden:fv,confirm:Jt}=vo(),{showDiff:Ii,showNewFile:hv,showEditDiff:AA,confirmFileChange:Ko}=bf(),{C:fe,Spinner:pv,getToolSpinnerText:mv}=it(),{ToolProgress:ji}=zn(),{isGitRepo:Sc,getCurrentBranch:Um,getStatus:gv,getDiff:yv}=ri(),{recordChange:Di}=Of(),{fuzzyFindText:Wm,findMostSimilar:Qo}=th(),{runDiagnostics:Xo}=fh(),{findFileInIndex:wv,getFileIndex:Hm,searchContentIndex:$v,scorePathMatch:Ym,refreshIndex:bv,isIndexValid:_v}=an(),{resolveProfile:qt,sshExec:wt,scpUpload:xv,scpDownload:Gm}=Ws(),{resolveDeployConfig:kv,loadDeployConfigs:Sv}=Ph(),{getEditMode:zm}=Io(),vv=/^(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/,Ev=/^ssh\s/,Tv=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function At(t){return Je.access(t).then(()=>!0).catch(()=>!1)}var qi=null,Km=0,Rv=12e4;function Cv(){let t=Date.now();if(qi&&t-Km<Rv)return qi;let e=ie.dirname(process.cwd());try{let s=Zt.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 qi=n.length>0?n:null,Km=t,qi}catch{return null}}function vc(t){if(t&&ie.resolve(t)!==process.cwd())return"";let e=Cv();if(!e)return"";let s=ie.dirname(process.cwd());return`
244
+ `)}jm.exports={saveMemory:tv,deleteMemory:nv,scanMemories:Nm,rebuildIndex:Ii,loadMemoryIndex:Pm,remember:sv,recall:ov,forget:rv,listMemories:Mm,loadGlobalInstructions:Lm,loadProjectInstructions:Im,getMemoryContext:iv,_getMemoryDir:as,_getMemoryFile:Js,_getGlobalNexMdPath:Rm,_parseMemoryFile:Sc,_migrateIfNeeded:Om,VALID_TYPES:Ho}});var Wm=Z((LA,Um)=>{var zo=require("fs"),vc=require("path"),Ec=process.env.NEX_AUDIT!=="false",ls=null;function Dm(){return ls||(ls=vc.join(process.cwd(),".nex","audit"),zo.existsSync(ls)||zo.mkdirSync(ls,{recursive:!0}),ls)}function qm(){let t=new Date().toISOString().split("T")[0];return vc.join(Dm(),`${t}.jsonl`)}function av(t){if(Ec)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Fm(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)+`
245
+ `;zo.appendFileSync(qm(),s,"utf-8")}catch{}}function Fm(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 Bm(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=vc.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 c=JSON.parse(l);if(t.tool&&c.tool!==t.tool)continue;o.push(c)}catch{}if(t.date)break}return o}function lv(t=1){let e=Bm({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 cv(t){Ec=t}function uv(){return Ec}function dv(){ls=null}Um.exports={logToolExecution:av,sanitizeArgs:Fm,readAuditLog:Bm,getAuditSummary:lv,setAuditEnabled:cv,isAuditEnabled:uv,getAuditLogPath:qm,_reset:dv}});var lg=Z((jA,ag)=>{var Je=require("fs").promises,Zt=require("fs"),ie=require("path"),He=require("util").promisify(require("child_process").exec),cs=require("util").promisify(require("child_process").execFile),{spawnSync:fv}=require("child_process"),Tc=require("axios"),{isForbidden:pv,isSSHForbidden:hv,isDangerous:mv,isCritical:Hm,isBashPathForbidden:gv,confirm:Jt}=vo(),{showDiff:ji,showNewFile:yv,showEditDiff:IA,confirmFileChange:Ko}=xf(),{C:fe,Spinner:wv,getToolSpinnerText:bv}=at(),{ToolProgress:Di}=Kn(),{isGitRepo:Rc,getCurrentBranch:Ym,getStatus:$v,getDiff:_v}=ii(),{recordChange:qi}=Pf(),{fuzzyFindText:Gm,findMostSimilar:Qo}=sp(),{runDiagnostics:Xo}=hp(),{findFileInIndex:xv,getFileIndex:zm,searchContentIndex:kv,scorePathMatch:Km,refreshIndex:Sv,isIndexValid:vv}=ln(),{resolveProfile:Bt,sshExec:wt,scpUpload:Ev,scpDownload:Xm}=Ws(),{resolveDeployConfig:Tv,loadDeployConfigs:Rv}=Lp(),{getEditMode:Vm}=Io(),Cv=/^(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/,Av=/^ssh\s/,Ov=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function At(t){return Je.access(t).then(()=>!0).catch(()=>!1)}var Fi=null,Jm=0,Nv=12e4;function Pv(){let t=Date.now();if(Fi&&t-Jm<Nv)return Fi;let e=ie.dirname(process.cwd());try{let s=Zt.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 Fi=n.length>0?n:null,Jm=t,Fi}catch{return null}}function Cc(t){if(t&&ie.resolve(t)!==process.cwd())return"";let e=Pv();if(!e)return"";let s=ie.dirname(process.cwd());return`
247
247
  Hint: no matches in current project. Sibling directories in ${s}/:
248
248
  ${e.join(", ")}
249
- You can search there with: grep pattern --path ${s}/<dir>`}async function Fi(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=lt(e);if(s&&await At(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=lt(t+i);if(a&&await At(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=lt(i+a);if(l&&await At(l))return{fixedPath:l,message:`(auto-fixed: ${n} \u2192 ${a})`}}}let r=ie.basename(t);if(r&&r.length>2)try{let i=wv(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:
249
+ You can search there with: grep pattern --path ${s}/<dir>`}async function Bi(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=ct(e);if(s&&await At(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=ct(t+i);if(a&&await At(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=ct(i+a);if(l&&await At(l))return{fixedPath:l,message:`(auto-fixed: ${n} \u2192 ${a})`}}}let r=ie.basename(t);if(r&&r.length>2)try{let i=xv(r).map(a=>ct(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:
250
250
  ${i.map(l=>ie.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
251
- `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=an(),l=a().filter(c=>ie.basename(c).toLowerCase()===i).map(c=>lt(c));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}=ln(),l=a().filter(c=>ie.basename(c).toLowerCase()===i).map(c=>ct(c));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:
252
252
  ${l.map(u=>ie.relative(process.cwd(),u)).map(u=>` - ${u}`).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(u=>ie.relative(process.cwd(),lt(u.file))).map(u=>` - ${u}`).join(`
255
- `)}`}}}catch{}return{fixedPath:null,message:""}}function Av(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 Zm(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 Qm(t,e){let s=Zm(t);if(!s)return new Map;try{let o=await $v(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 Xm(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 Vo(t,e){let s=(t||"").trim();return s?e==="files_with_matches"||e==="count"?s.split(`
253
+ `)}`}}catch{}try{let{smartSearch:i}=ln(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=ct(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(u=>ie.relative(process.cwd(),ct(u.file))).map(u=>` - ${u}`).join(`
255
+ `)}`}}}catch{}return{fixedPath:null,message:""}}function Mv(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 tg(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 ng(t,e){let s=tg(t);if(!s)return new Map;try{let o=await kv(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 Zm(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 Vo(t,e){let s=(t||"").trim();return s?e==="files_with_matches"||e==="count"?s.split(`
256
256
  `).filter(o=>o.trim()):s.split(`
257
- `).filter(o=>o.trim()):[]}function eg(t,{query:e,basePath:s,definitionScores:o=new Map,mtimeByPath:n=new Map}={}){let r=Zm(e);return[...t].sort((i,a)=>{let l=Xm(i,s),c=Xm(a,s),u=0,d=0;if(r&&(u+=Ym(l,r),d+=Ym(c,r)),u+=o.get(l)||0,d+=o.get(c)||0,u!==d)return d-u;let f=n.get(i)||0,h=n.get(a)||0;return f!==h?h-f:l.localeCompare(c)})}async function Ec(t,{query:e,basePath:s,outputMode:o}={}){if(!Array.isArray(t)||t.length<=1)return t;let n=new Map,r=[];for(let c of t){if(!c)continue;let u=c;(o==="count"||o!=="files_with_matches")&&(u=c.split(":")[0]),n.has(u)||(n.set(u,[]),r.push(u)),n.get(u).push(c)}let i=await Qm(e,s),a=eg(r,{query:e,basePath:s,definitionScores:i}),l=[];for(let c of a)l.push(...n.get(c)||[]);return l}function tg(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+`
257
+ `).filter(o=>o.trim()):[]}function sg(t,{query:e,basePath:s,definitionScores:o=new Map,mtimeByPath:n=new Map}={}){let r=tg(e);return[...t].sort((i,a)=>{let l=Zm(i,s),c=Zm(a,s),u=0,d=0;if(r&&(u+=Km(l,r),d+=Km(c,r)),u+=o.get(l)||0,d+=o.get(c)||0,u!==d)return d-u;let f=n.get(i)||0,p=n.get(a)||0;return f!==p?p-f:l.localeCompare(c)})}async function Ac(t,{query:e,basePath:s,outputMode:o}={}){if(!Array.isArray(t)||t.length<=1)return t;let n=new Map,r=[];for(let c of t){if(!c)continue;let u=c;(o==="count"||o!=="files_with_matches")&&(u=c.split(":")[0]),n.has(u)||(n.set(u,[]),r.push(u)),n.get(u).push(c)}let i=await ng(e,s),a=sg(r,{query:e,basePath:s,definitionScores:i}),l=[];for(let c of a)l.push(...n.get(c)||[]);return l}function og(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+`
258
258
 
259
259
  `+s.join(`
260
- `)}function ng(t,e,s){let o=Qo(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 Vm=!1,cs=null;function Ov(){cs&&(cs(),cs=null)}var Ac=null;function Nv(t){Ac=t}async function Tc(){if(!Vm){Vm=!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 Pv=[/\.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 Mv(){let t=process.cwd();try{return Zt.realpathSync(t)}catch{return ie.resolve(t)}}function Lv(t,e){let s=ie.relative(e,t);return s===""||!s.startsWith("..")&&!ie.isAbsolute(s)}function Iv(t){if(Zt.existsSync(t))return Zt.realpathSync(t);let e=ie.dirname(t);for(;e&&e!==ie.dirname(e);){if(Zt.existsSync(e)){let s=Zt.realpathSync(e),o=ie.relative(e,t);return ie.resolve(s,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 Pv)if(o.test(e))return null;let s=Iv(e);return Lv(s,Mv())?s:null}function Ce(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function sg(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function jv(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function Dv(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 qv(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Jo(t,e="user"){return sg(t)?null:`ERROR: ${e} contains unsafe characters`}function Cc(t,e="service"){return jv(t)?null:`ERROR: ${e} contains unsafe characters`}var Fv=[{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: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 Jm(t,e,s={}){switch(t){case"bash":{let o=e.command,n=cv(o);if(n){let d=Av(o);return`BLOCKED: Command matches forbidden pattern: ${n}${d?`
261
- HINT: ${d}`:""}`}let r=fv(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(s.autoConfirm?Bm(o):dv(o)){let d=Bm(o)?"\u26D4":"\u26A0";if(!await Jt(` ${d} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Zt.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${fe.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${fe.reset}`)}let l=Ev.test(o.trim())&&!Tv.test(o.trim());if(vv.test(o.trim())||l){s.silent||console.log(`${fe.dim} \u25B6 interactive: ${o}${fe.reset}`);let d=lv("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:c}=zn(),u=s.silent?null:new c("bash",`$ ${o.substring(0,72)}`);u&&u.start();try{let{stdout:d,stderr:f}=await He(o,{cwd:a,timeout:9e4,maxBuffer:5242880});return u&&u.stop(),d||f||"(no output)"}catch(d){u&&u.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),h=tg(f,o);return`EXIT ${d.code||1}
263
- ${h}`}}case"read_file":{let o=new ji("read_file","Reading file...");o.start();try{let n=lt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(n)){let ce=await Fi(e.path);if(ce.fixedPath)n=ce.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),n)}${fe.reset}`),o.update({message:"Resolved path",detail:ie.relative(process.cwd(),n)});else return`ERROR: File not found: ${e.path}${ce.message?`
260
+ `)}function rg(t,e,s){let o=Qo(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 Qm=!1,us=null;function Lv(){us&&(us(),us=null)}var Mc=null;function Iv(t){Mc=t}async function Oc(){if(!Qm){Qm=!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 jv=[/\.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 Dv(){let t=process.cwd();try{return Zt.realpathSync(t)}catch{return ie.resolve(t)}}function qv(t,e){let s=ie.relative(e,t);return s===""||!s.startsWith("..")&&!ie.isAbsolute(s)}function Fv(t){if(Zt.existsSync(t))return Zt.realpathSync(t);let e=ie.dirname(t);for(;e&&e!==ie.dirname(e);){if(Zt.existsSync(e)){let s=Zt.realpathSync(e),o=ie.relative(e,t);return ie.resolve(s,o)}e=ie.dirname(e)}return t}function ct(t){let e=ie.isAbsolute(t)?ie.resolve(t):ie.resolve(process.cwd(),t);for(let o of jv)if(o.test(e))return null;let s=Fv(e);return qv(s,Dv())?s:null}function Ce(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function ig(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function Bv(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function Uv(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function Nc(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function Wv(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Jo(t,e="user"){return ig(t)?null:`ERROR: ${e} contains unsafe characters`}function Pc(t,e="service"){return Bv(t)?null:`ERROR: ${e} contains unsafe characters`}var Hv=[{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: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 eg(t,e,s={}){switch(t){case"bash":{let o=e.command,n=pv(o);if(n){let d=Mv(o);return`BLOCKED: Command matches forbidden pattern: ${n}${d?`
261
+ HINT: ${d}`:""}`}let r=gv(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(s.autoConfirm?Hm(o):mv(o)){let d=Hm(o)?"\u26D4":"\u26A0";if(!await Jt(` ${d} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Zt.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${fe.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${fe.reset}`)}let l=Av.test(o.trim())&&!Ov.test(o.trim());if(Cv.test(o.trim())||l){s.silent||console.log(`${fe.dim} \u25B6 interactive: ${o}${fe.reset}`);let d=fv("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:c}=Kn(),u=s.silent?null:new c("bash",`$ ${o.substring(0,72)}`);u&&u.start();try{let{stdout:d,stderr:f}=await He(o,{cwd:a,timeout:9e4,maxBuffer:5242880});return u&&u.stop(),d||f||"(no output)"}catch(d){u&&u.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),p=og(f,o);return`EXIT ${d.code||1}
263
+ ${p}`}}case"read_file":{let o=new Di("read_file","Reading file...");o.start();try{let n=ct(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(n)){let ce=await Bi(e.path);if(ce.fixedPath)n=ce.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),n)}${fe.reset}`),o.update({message:"Resolved path",detail:ie.relative(process.cwd(),n)});else return`ERROR: File not found: ${e.path}${ce.message?`
264
264
  `+ce.message:""}`}let i=ie.relative(process.cwd(),n);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),l=await Zt.promises.open(n,"r"),{bytesRead:c}=await l.read(a,0,8192,0);await l.close();for(let ce=0;ce<c;ce++)if(a[ce]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let u=await Je.readFile(n,"utf-8");if(!u&&(await Je.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let d=u.split(`
265
- `),f=await Je.stat(n),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(`
266
- `),se=$?`
265
+ `),f=await Je.stat(n),p=d.length,m=350,g=!e.line_start&&!e.line_end,b=g&&p>m,x=(e.line_start||1)-1,E=b?m:e.line_end||d.length,N=x+1,v=E;o.update({count:Math.max(0,E-x),total:p,detail:`${i} lines ${N}-${v}`,message:b?"Reading excerpt":"Reading"});let S=b?`showing lines 1-${m} of ${p}`:e.line_start||e.line_end?`lines ${x+1}-${E} of ${p}`:`${p} lines`,P=`File: ${i} (${S}, ${f.size} bytes)`,ne=d.slice(x,E).map((ce,de)=>`${x+de+1}: ${ce}`).join(`
266
+ `),se=b?`
267
267
 
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?`
268
+ [\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${m} of ${p} 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&&p>E?`
269
269
 
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}${se}`}finally{o.stop()}}case"write_file":{let o=new ji("write_file","Preparing write...");o.start();try{await Tc();let n=lt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await At(n),i=null,a=String(e.content||"").split(`
272
- `).length;if(o.update({count:a,detail:`${ie.relative(process.cwd(),n)} ${a} lines`,message:r?"Overwriting":"Creating"}),s.autoConfirm)r&&(i=await Je.readFile(n,"utf-8"));else if(r){i=await Je.readFile(n,"utf-8");let f=await Xo(n,e.content);if(Ii(n,i,e.content,{annotations:f}),!await Ko("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let f=await Xo(n,e.content);if(hv(n,e.content,{annotations:f}),!await Ko("Create"))return"CANCELLED: User declined to create file."}let l=ie.dirname(n);await At(l)||await Je.mkdir(l,{recursive:!0}),o.update({message:"Writing",detail:`${ie.relative(process.cwd(),n)} ${a} lines`}),await Je.writeFile(n,e.content,"utf-8");let u=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");u&&(o.update({message:"Chmod",detail:ie.relative(process.cwd(),n)}),await Je.chmod(n,493)),Di("write_file",n,i,e.content);let d=u?" [chmod +x applied]":"";return`Written: ${n} (${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 n=lt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(n)){let d=await Fi(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),n)}${fe.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
270
+ [\u{1F6A8} FILE CONTINUES: This is only lines ${x+1} to ${E} of ${p} total. The rest is HIDDEN. Use line_start=${E+1} to read the next section, or grep_search for keywords.]`:"";return`${P}
271
+ ${ne}${se}`}finally{o.stop()}}case"write_file":{let o=new Di("write_file","Preparing write...");o.start();try{await Oc();let n=ct(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await At(n),i=null,a=String(e.content||"").split(`
272
+ `).length;if(o.update({count:a,detail:`${ie.relative(process.cwd(),n)} ${a} lines`,message:r?"Overwriting":"Creating"}),s.autoConfirm)r&&(i=await Je.readFile(n,"utf-8"));else if(r){i=await Je.readFile(n,"utf-8");let f=await Xo(n,e.content);if(ji(n,i,e.content,{annotations:f}),!await Ko("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let f=await Xo(n,e.content);if(yv(n,e.content,{annotations:f}),!await Ko("Create"))return"CANCELLED: User declined to create file."}let l=ie.dirname(n);await At(l)||await Je.mkdir(l,{recursive:!0}),o.update({message:"Writing",detail:`${ie.relative(process.cwd(),n)} ${a} lines`}),await Je.writeFile(n,e.content,"utf-8");let u=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");u&&(o.update({message:"Chmod",detail:ie.relative(process.cwd(),n)}),await Je.chmod(n,493)),qi("write_file",n,i,e.content);let d=u?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${d}`}finally{o.stop()}}case"edit_file":{let o=new Di("edit_file","Preparing edit...");o.start();try{await Oc();let n=ct(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(n)){let d=await Bi(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),n)}${fe.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
273
273
  `+d.message:""}`}o.update({message:"Loading",detail:ie.relative(process.cwd(),n)});let i=await Je.readFile(n,"utf-8"),a=e.old_text,l=!1,c=!1;if(!i.includes(e.old_text)){o.update({message:"Matching target",detail:`${ie.relative(process.cwd(),n)} ${String(e.old_text||"").trim().split(`
274
- `)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=dt();if(zm(d(),f())==="strict"){let g=Qo(i,e.old_text);return g?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
274
+ `)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=dt();if(Vm(d(),f())==="strict"){let g=Qo(i,e.old_text);return g?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
275
275
  Most similar text (line ${g.line}, distance ${g.distance}):
276
- ${g.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let m=Wm(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(`${fe.dim} \u2713 fuzzy whitespace match applied${fe.reset}`);else{let g=ng(i,e.old_text,e.new_text);if(g){if(!s.autoConfirm){let v=await Xo(n,g.content);if(Ii(n,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(n,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||g.content.startsWith("#!"))&&await Je.chmod(n,493),Di("edit_file",n,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: ${n} (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((se,ce)=>`${v+ce+1}: ${se}`).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 ${n} (most similar at line ${$.line}, distance ${$.distance})
276
+ ${g.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let m=Gm(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(`${fe.dim} \u2713 fuzzy whitespace match applied${fe.reset}`);else{let g=rg(i,e.old_text,e.new_text);if(g){if(!s.autoConfirm){let v=await Xo(n,g.content);if(ji(n,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(n,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||g.content.startsWith("#!"))&&await Je.chmod(n,493),qi("edit_file",n,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: ${n} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${N}")`}let b=Qo(i,e.old_text);if(b){let N=i.split(`
277
+ `),v=Math.max(0,b.line-6),S=Math.min(N.length,b.line+10),P=N.slice(v,S).map((se,ce)=>`${v+ce+1}: ${se}`).join(`
278
+ `),ne=`line_start=${Math.max(1,b.line-5)} line_end=${Math.min(N.length,b.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${b.line}, distance ${b.distance})
279
279
 
280
- Actual file content around line ${$.line} \u2014 use this to correct old_text:
280
+ Actual file content around line ${b.line} \u2014 use this to correct old_text:
281
281
  ${P}
282
282
 
283
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
284
  `)[0].slice(0,60),E=x?`
285
285
  Recovery: grep -n "${x.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
286
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 ${n}${E}`}}if(!s.autoConfirm){o.update({message:"Previewing edit",detail:`${ie.relative(process.cwd(),n)} ${String(e.new_text||"").trim().split(`
287
- `)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await Xo(n,d);if(Ii(n,i,d,{annotations:f}),!await Ko(l?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=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(`
288
- `)[0].slice(0,40)}`}),await Je.writeFile(n,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||u.startsWith("#!"))&&(o.update({message:"Chmod",detail:ie.relative(process.cwd(),n)}),await Je.chmod(n,493)),Di("edit_file",n,i,u),l?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}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 At(o)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=lt(c),d=await At(u);if(u&&d)o=u;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let c=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${c}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],l=async(c,u,d)=>{if(u>r)return;let f;try{f=await Je.readdir(c,{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(c,h.name),u+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 n=["-rn","-H"];e.file_pattern&&n.push(`--include=${e.file_pattern}`),n.push(e.pattern,o);try{let{stdout:r}=await ls("grep",n,{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 n=process.cwd(),r=e.path?lt(e.path):n,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),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=zn(),f=new d("glob","Finding files...");f.start();let h=Hm();_v(r)||(await bv(r),h=Hm());let m=h.filter(S=>l.test(S)||u.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 Qm(i,r),E=eg(g.map(S=>S.path),{query:i,basePath:r,definitionScores:x,mtimeByPath:$}),N=m.length>200,v=E.slice(0,200).join(`
287
+ `)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await Xo(n,d);if(ji(n,i,d,{annotations:f}),!await Ko(l?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=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(`
288
+ `)[0].slice(0,40)}`}),await Je.writeFile(n,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||u.startsWith("#!"))&&(o.update({message:"Chmod",detail:ie.relative(process.cwd(),n)}),await Je.chmod(n,493)),qi("edit_file",n,i,u),l?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}finally{o.stop()}}case"list_directory":{let o=ct(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(o)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=ct(c),d=await At(u);if(u&&d)o=u;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let c=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${c}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],l=async(c,u,d)=>{if(u>r)return;let f;try{f=await Je.readdir(c,{withFileTypes:!0})}catch{return}f=f.filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules");for(let p of f){if(i&&!p.isDirectory()&&!i.test(p.name))continue;let m=p.isDirectory()?"/":"";a.push(`${d}${p.name}${m}`),p.isDirectory()&&await l(ie.join(c,p.name),u+1,d+" ")}};return await l(o,1,""),a.join(`
289
+ `)||"(empty)"}case"search_files":{let o=ct(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 cs("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=Vo(r).slice(0,50);return(await Ac(i,{query:e.pattern,basePath:o})).join(`
290
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let n=process.cwd(),r=e.path?ct(e.path):n,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),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=Kn(),f=new d("glob","Finding files...");f.start();let p=zm();vv(r)||(await Sv(r),p=zm());let m=p.filter(S=>l.test(S)||u.test(ie.basename(S))).map(S=>ie.join(r,S));if(m.length===0)return f.stop(),"(no matches)"+Cc(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}}})),b=new Map(g.map(S=>[S.path,S.mtime])),x=await ng(i,r),E=sg(g.map(S=>S.path),{query:i,basePath:r,definitionScores:x,mtimeByPath:b}),N=m.length>200,v=E.slice(0,200).join(`
291
291
  `);return f.update({count:m.length,detail:e.pattern}),f.stop(),N?`${v}
292
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(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
294
- `);for(let $ of d)if($.startsWith("diff --git")){let x=$.match(/diff --git a\/(.+) b\/(.+)/);x&&u.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 u)try{let x=ie.join(process.cwd(),$);if(await At(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 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}=zn(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await ls("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;e.output_mode==="files_with_matches"||e.output_mode==="count"?c=Vo(l,e.output_mode):c=Vo(l);let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=await Ec(c,{query:e.pattern,basePath:o,outputMode:e.output_mode}),c=c.slice(u,u+d),a.update({count:c.length,detail:`in ${o}`}),a.stop(),c.join(`
296
- `).trim()||"(no matches)"+vc(e.path)}catch(l){if(a.stop(),l.code===2){let c=(l.stderr||l.message||"").toString().trim();return c.includes("No such file or directory")?`ERROR: Directory not found: ${o}`:c.includes("Invalid")||c.includes("Unmatched")||c.includes("unterminated")||c.includes("unclosed")||c.includes("parse error")||c.includes("brackets")||c.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${c.slice(0,200)||"exit code 2"}`}return"(no matches)"+vc(e.path)}}case"patch_file":{let o=new ji("patch_file","Preparing patches...");o.start();try{await Tc();let n=lt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(n)){let E=await Fi(e.path);if(E.fixedPath)n=E.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),n)}${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(),n)} ${i.length} patches`,message:"Validating patches"});let a=await Je.readFile(n,"utf-8"),{getActiveModelId:l,getActiveProviderName:c}=dt(),u=zm(l(),c()),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(),n)} 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(u==="strict"){let S=Qo(a,N);return S?`ERROR: Patch ${E+1} old_text not found in ${n} (strict mode \u2014 exact match required)
293
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:v}case"grep":{let o=e.path?ct(e.path):process.cwd();if(e.staged){let{getDiff:l}=ii(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
294
+ `);for(let b of d)if(b.startsWith("diff --git")){let x=b.match(/diff --git a\/(.+) b\/(.+)/);x&&u.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:p}=Kn(),m=new p("grep","Searching staged content...");m.start();let g=[];for(let b of u)try{let x=ie.join(process.cwd(),b);if(await At(x)){let E=[...f];E.push(e.pattern,x);let{stdout:N}=await cs("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 Ac(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 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}=Kn(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await cs("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;e.output_mode==="files_with_matches"||e.output_mode==="count"?c=Vo(l,e.output_mode):c=Vo(l);let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=await Ac(c,{query:e.pattern,basePath:o,outputMode:e.output_mode}),c=c.slice(u,u+d),a.update({count:c.length,detail:`in ${o}`}),a.stop(),c.join(`
296
+ `).trim()||"(no matches)"+Cc(e.path)}catch(l){if(a.stop(),l.code===2){let c=(l.stderr||l.message||"").toString().trim();return c.includes("No such file or directory")?`ERROR: Directory not found: ${o}`:c.includes("Invalid")||c.includes("Unmatched")||c.includes("unterminated")||c.includes("unclosed")||c.includes("parse error")||c.includes("brackets")||c.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${c.slice(0,200)||"exit code 2"}`}return"(no matches)"+Cc(e.path)}}case"patch_file":{let o=new Di("patch_file","Preparing patches...");o.start();try{await Oc();let n=ct(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(n)){let E=await Bi(e.path);if(E.fixedPath)n=E.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ie.relative(process.cwd(),n)}${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(),n)} ${i.length} patches`,message:"Validating patches"});let a=await Je.readFile(n,"utf-8"),{getActiveModelId:l,getActiveProviderName:c}=dt(),u=Vm(l(),c()),d=[],f=!1,p=!1;for(let E=0;E<i.length;E++){o.update({count:E+1,total:i.length,detail:`${ie.relative(process.cwd(),n)} 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(u==="strict"){let S=Qo(a,N);return S?`ERROR: Patch ${E+1} old_text not found in ${n} (strict mode \u2014 exact match required)
298
298
  Most similar text (line ${S.line}, distance ${S.distance}):
299
- ${S.text}`:`ERROR: Patch ${E+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let S=Wm(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 ${n}
299
+ ${S.text}`:`ERROR: Patch ${E+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let S=Gm(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}),p=!0;else return`ERROR: Patch ${E+1} old_text not found in ${n}
300
300
  Most similar text (line ${P.line}, distance ${P.distance}):
301
- ${P.text}`}else return`ERROR: Patch ${E+1} old_text not found in ${n}`}}}let m=a;for(let{old_text:E,new_text:N}of d)m=m.split(E).join(N);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 E=await Xo(n,m);if(Ii(n,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(),n)} ${d.length} matched`}),await Je.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 Je.chmod(n,493)),Di("patch_file",n,a,m);let $=h?" (auto-fixed)":f?" (fuzzy match)":"",x=g?" [chmod +x applied]":"";return`Patched: ${n} (${i.length} replacements)${$}${x}`}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 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,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 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=n.data?.choices?.[0]?.message?.content||"",i=n.data?.citations||[],a=`[Perplexity grounded search]
301
+ ${P.text}`}else return`ERROR: Patch ${E+1} old_text not found in ${n}`}}}let m=a;for(let{old_text:E,new_text:N}of d)m=m.split(E).join(N);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 E=await Xo(n,m);if(ji(n,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(),n)} ${d.length} matched`}),await Je.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 Je.chmod(n,493)),qi("patch_file",n,a,m);let b=p?" (auto-fixed)":f?" (fuzzy match)":"",x=g?" [chmod +x applied]":"";return`Patched: ${n} (${i.length} replacements)${b}${x}`}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 Tc.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 Tc.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]
302
302
 
303
303
  ${r}`;return i.length>0&&(a+=`
304
304
 
305
305
  Sources:
306
306
  `+i.slice(0,o).map((l,c)=>`${c+1}. ${l}`).join(`
307
- `)),a}catch(n){console.error(`${fe.dim} Perplexity search failed (${n.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 c=l[1].replace(/.*uddg=/,"").split("&")[0],u=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(c)})}catch{i.push({title:u,url:c})}}return i.length===0?"(no results)":i.map((c,u)=>`${u+1}. ${c.title}
307
+ `)),a}catch(n){console.error(`${fe.dim} Perplexity search failed (${n.message}), falling back to DuckDuckGo${fe.reset}`)}try{let r=(await Tc.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 c=l[1].replace(/.*uddg=/,"").split("&")[0],u=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(c)})}catch{i.push({title:u,url:c})}}return i.length===0?"(no results)":i.map((c,u)=>`${u+1}. ${c.title}
308
308
  ${c.url}`).join(`
309
309
 
310
310
  `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=xn();try{let n=await o(e.url,{waitFor:e.wait_for}),r=n.links.length>0?`
@@ -335,10 +335,10 @@ Analyze the screenshot above and provide structured feedback:
335
335
  4. Responsiveness concerns at this viewport
336
336
  5. Specific issues related to: ${r}`;return e.compare_with&&Zt.existsSync(e.compare_with)&&(i+=`
337
337
 
338
- 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}=Oc(),n=o();return n?{text:`Clipboard image captured: ${n.path}
338
+ 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}=Lc(),n=o();return n?{text:`Clipboard image captured: ${n.path}
339
339
  Size: ${Math.round(Buffer.from(n.data,"base64").length/1024)} KB
340
340
 
341
- [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}=xn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(n){return`ERROR: ${n.message}`}}case"browser_fill":{let{browserFill:o}=xn();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}=Qn(),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(`
341
+ [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}=xn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(n){return`ERROR: ${n.message}`}}case"browser_fill":{let{browserFill:o}=xn();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}=es(),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(`
342
342
  `):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${n.diffPercent}% of pixels changed
343
343
  Changed: ${n.changedPixels.toLocaleString()} / ${n.totalPixels.toLocaleString()} pixels
344
344
  Canvas: ${n.width}\xD7${n.height}
@@ -347,7 +347,7 @@ Diff image: ${n.diffPath}
347
347
  Regional breakdown:
348
348
  ${i}
349
349
 
350
- [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:n.diffPath,base64:Zt.readFileSync(n.diffPath).toString("base64"),media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"responsive_sweep":try{let{responsiveSweep:o}=Qn(),n=await o(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=n.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
350
+ [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:n.diffPath,base64:Zt.readFileSync(n.diffPath).toString("base64"),media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"responsive_sweep":try{let{responsiveSweep:o}=es(),n=await o(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=n.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
351
351
  `);return{text:`RESPONSIVE SWEEP \u2014 ${n.length} viewports captured
352
352
  URL: ${e.url}
353
353
 
@@ -361,15 +361,15 @@ Analyze these screenshots for:
361
361
  2. Typography scaling (text too small on mobile, too large on desktop)
362
362
  3. Navigation pattern changes across viewports
363
363
  4. Image/media sizing and aspect ratio issues
364
- 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}=Qn(),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: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}=es(),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})
365
365
  Source: ${e.image}
366
366
  Output: ${n.path}
367
367
 
368
- [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}=Qn(),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(u=>`${u.name}:${u.changedPercent}%`).join(", ")}`);let c=[{path:l.path,base64:l.base64,media_type:l.media_type}];return l.diff?.diffPath&&c.push({path:l.diff.diffPath,base64:Zt.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
368
+ [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}=es(),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(u=>`${u.name}:${u.changedPercent}%`).join(", ")}`);let c=[{path:l.path,base64:l.base64,media_type:l.media_type}];return l.diff?.diffPath&&c.push({path:l.diff.diffPath,base64:Zt.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
369
369
  `),images:c}}return{text:i.join(`
370
370
  `)+`
371
371
 
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(),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(`
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}=es(),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(`
373
373
  `),i=n.spacing.length?n.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
374
374
  `):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${n.dimensions.width}\xD7${n.dimensions.height} image
375
375
  Source: ${n.imagePath}
@@ -383,7 +383,7 @@ ${i}
383
383
  Use these values to:
384
384
  - Compare against CSS variables / design system tokens
385
385
  - Identify inconsistent colors or spacing
386
- - Generate a color palette from the rendered output`}catch(o){return`ERROR: ${o.message}`}case"design_compare":try{let{designCompare:o}=Qn(),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(`
386
+ - Generate a color palette from the rendered output`}catch(o){return`ERROR: ${o.message}`}case"design_compare":try{let{designCompare:o}=es(),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(`
387
387
  `)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${n.diffPercent}% deviation from reference
388
388
  Reference: ${n.referencePath}
389
389
  Live: ${n.livePath}
@@ -395,24 +395,24 @@ Pixel deviation: ${n.changedPixels.toLocaleString()} / ${n.totalPixels.toLocaleS
395
395
  Regional breakdown:
396
396
  ${r}
397
397
 
398
- [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 Ac?new Promise(r=>{cs=()=>r("CANCELLED"),Ac(o,n).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=n.length>0?`
398
+ [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 Mc?new Promise(r=>{us=()=>r("CANCELLED"),Mc(o,n).then(i=>{us=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});us=()=>{i.close(),r("CANCELLED")};let a=n.length>0?`
399
399
  ${n.map((l,c)=>` ${c+1}. ${l}`).join(`
400
400
  `)}
401
401
  `:"";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 Um()||"(detached)",n=await gv();if(n.length===0)return`Branch: ${o}
402
+ ${fe.cyan}${fe.bold} ? ${o}${fe.reset}${a}`),i.question(`${fe.cyan} > ${fe.reset}`,l=>{us=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Rc())return"ERROR: Not a git repository";let o=await Ym()||"(detached)",n=await $v();if(n.length===0)return`Branch: ${o}
403
403
  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(`
404
- `)}case"git_diff":{if(!await Sc())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 yv(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await Sc())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}=ac(),{getActiveTaskProgress:l}=it(),c=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let u=o(e.name,e.tasks);return c||console.log(`
404
+ `)}case"git_diff":{if(!await Rc())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 _v(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await Rc())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}=dc(),{getActiveTaskProgress:l}=at(),c=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let u=o(e.name,e.tasks);return c||console.log(`
405
405
  `+i()),`Created task list "${e.name}" with ${u.length} tasks:
406
406
  `+u.map(d=>` ${d.id}: ${d.description}`).join(`
407
407
  `)}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)?(c||console.log(`
408
408
  `+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let u=r();return u.tasks.length===0?"No active tasks":(c||console.log(`
409
- `+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o,executeSpawnAgentsBackground:n}=Bi();return e.agents?.some(r=>r.background)?n(e):o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:n,getActiveModelId:r}=dt();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 ls("gh",n,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let c=l.conclusion||l.status||"unknown",u=c==="success"?"\u2713":c==="failure"?"\u2717":c==="in_progress"?"\u283F":"\u25CB",d=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${c} \xB7 ${d}`}).join(`
409
+ `+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o,executeSpawnAgentsBackground:n}=Ui();return e.agents?.some(r=>r.background)?n(e):o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:n,getActiveModelId:r}=dt();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 cs("gh",n,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let c=l.conclusion||l.status||"unknown",u=c==="success"?"\u2713":c==="failure"?"\u2717":c==="in_progress"?"\u283F":"\u25CB",d=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${c} \xB7 ${d}`}).join(`
410
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(`
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}),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 c=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${c} ${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 cs("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 cs("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 c=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${c} ${l.name}`)}}return r.join(`
413
413
  `)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
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(),n=e.branch||await Um()||"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(`
415
- ${fe.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${n}${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 "${n}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
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(),n=e.branch||await Ym()||"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(`
415
+ ${fe.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${n}${fe.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await cs("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(`
416
416
  `)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",n=e.label?`-l ${e.label}`:"",r=Zo(`get pods ${o} ${n} -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
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",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=Zo(r,e);try{let{stdout:a,stderr:l}=await He(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
418
418
  ...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
@@ -422,81 +422,81 @@ ${fe.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${fe.reset}`),con
422
422
  ${fe.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${fe.reset}`),!await Jt(" 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=Zo(n,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(`
423
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(`
424
424
  ${fe.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${fe.reset}`),!await Jt(` ${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:n}=$c(),{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),c=l.content?l.content+`
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:n}=kc(),{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),c=l.content?l.content+`
426
426
 
427
- `+i:i;return o(r,c),`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=qt(e.server)}catch(P){return`ERROR: ${P.message}`}let n=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=uv(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,c),`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=Bt(e.server)}catch(P){return`ERROR: ${P.message}`}let n=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=hv(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:
428
428
  grep -n "pattern" /path/to/file -A 50
429
429
  or to read the whole file:
430
430
  cat /path/to/file
431
431
  NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
432
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(n=n.replace(/(-[BAC])\s*(\d+)/g,(P,ne,se)=>{let ce=Math.min(Number(se),20);return`${ne} ${ce}`}),n=n.replace(/(--(?:before|after|context)=)(\d+)/g,(P,ne,se)=>ne+Math.min(Number(se),20)),/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(n)){let P=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
433
- ${fe.yellow} \u26A0 Remote command on ${P}: ${n}${fe.reset}`),!await Jt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await wt(o,n,{timeout:i,sudo:r}),h=[c,u].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),se=n.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),ce=ne&&ne[1]||se&&se[1];if(ce)try{let{remoteAutoFixPath:de}=Ws(),re=ce.startsWith("/")?ce.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(o.user||"root"),le=await de(o,re,ce);if(le.fixedPath){let T=n.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(`
433
+ ${fe.yellow} \u26A0 Remote command on ${P}: ${n}${fe.reset}`),!await Jt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await wt(o,n,{timeout:i,sudo:r}),p=[c,u].filter(Boolean).join(`
434
+ `).trim();if(d!==0){if(/no such file or directory/i.test(p)){let ne=p.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),se=n.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),ce=ne&&ne[1]||se&&se[1];if(ce)try{let{remoteAutoFixPath:de}=Ws(),re=ce.startsWith("/")?ce.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(o.user||"root"),le=await de(o,re,ce);if(le.fixedPath){let T=n.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
435
  `).trim();if(q.exitCode===0)return`${le.message}
436
436
  ${Q}`||"(command completed, no output)"}else if(le.message)return`EXIT ${d}
437
- ${f||h}
437
+ ${f||p}
438
438
 
439
439
  ${le.message}`}catch{}}return`EXIT ${d}
440
- ${f||h||"(no output)"}`}let m=/\bgrep\b/.test(n),g=h;m&&(g=g.split(`
440
+ ${f||p||"(no output)"}`}let m=/\bgrep\b/.test(n),g=p;m&&(g=g.split(`
441
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(`
442
+ `));let b=m?60:100,x=g.split(`
443
+ `);x.length>b&&(g=`(${x.length-b} earlier lines omitted \u2014 showing last ${b})
444
+ `+x.slice(-b).join(`
445
445
  `));let E=4,N=g.split(`
446
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 se=1;se<ne;se++)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=qt(e.server)}catch(i){return`ERROR: ${i.message}`}let n=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
448
- ${fe.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${n}:${e.remote_path}${fe.reset}`),!await Jt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await xv(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=qt(e.server)}catch(n){return`ERROR: ${n.message}`}try{return await Gm(o,e.remote_path,e.local_path)}catch(n){if(/no such file|not found/i.test(n.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 Gm(o,a.fixedPath,e.local_path);return`${a.message}
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=Bt(e.server)}catch(i){return`ERROR: ${i.message}`}let n=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
448
+ ${fe.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${n}:${e.remote_path}${fe.reset}`),!await Jt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await Ev(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=Bt(e.server)}catch(n){return`ERROR: ${n.message}`}try{return await Xm(o,e.remote_path,e.local_path)}catch(n){if(/no such file|not found/i.test(n.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 Xm(o,a.fixedPath,e.local_path);return`${a.message}
449
449
  ${l}`}if(a.message)return`ERROR: ${n.message}
450
450
 
451
- ${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,""),u=['TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt) && chmod 600 "$TMPFILE"',`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",r,`bash -c '${u}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let 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 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=qt(e.server)}catch(u){return`ERROR: ${u.message}`}if(!i){let u=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
453
- ${fe.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${u}${fe.reset}`),!await Jt(" Execute?"))return"CANCELLED: User declined service action."}let l=e.service.includes(".")?e.service:`${e.service}.service`,c=`systemctl ${e.action} ${Ce(l)}`;if(r){let d=e.action!=="status"?`sudo ${c}`:c;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:u,stderr:d,exitCode:f,error:h}=await wt(a,c,{timeout:15e3,sudo:!0}),m=[u,d].filter(Boolean).join(`
451
+ ${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,""),u=['TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt) && chmod 600 "$TMPFILE"',`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",r,`bash -c '${u}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let p=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
452
+ ${p.slice(-2e3)}`:p.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=Pc(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=Bt(e.server)}catch(u){return`ERROR: ${u.message}`}if(!i){let u=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
453
+ ${fe.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${u}${fe.reset}`),!await Jt(" Execute?"))return"CANCELLED: User declined service action."}let l=e.service.includes(".")?e.service:`${e.service}.service`,c=`systemctl ${e.action} ${Ce(l)}`;if(r){let d=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:f,stderr:p}=await He(d,{timeout:15e3});return(f||p||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(f){let p=(f.stderr||f.message||"").toString().trim();return/not found|loaded.*not-found/i.test(p)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${f.code||1}
454
+ ${p}`}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await wt(a,c,{timeout:15e3,sudo:!0}),m=[u,d].filter(Boolean).join(`
455
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}
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 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 ${Ce(e.since)}`:"",l=e.follow?"-f":"",c=`journalctl -u ${Ce(i)} -n ${r} ${a} ${l} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:$,stderr:x}=await He(c,{timeout:15e3});return($||x||"(no log output)").trim()}catch($){return`EXIT ${$.code||1}
457
- ${($.stderr||$.message||"").toString().trim()}`}let u;try{u=qt(e.server)}catch($){return`ERROR: ${$.message}`}let{stdout:d,stderr:f,exitCode:h,error:m}=await wt(u,c,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
458
- `).trim();return h!==0?`EXIT ${h}
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=qt(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await wt(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
456
+ ${p||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=Pc(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 ${Ce(e.since)}`:"",l=e.follow?"-f":"",c=`journalctl -u ${Ce(i)} -n ${r} ${a} ${l} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:b,stderr:x}=await He(c,{timeout:15e3});return(b||x||"(no log output)").trim()}catch(b){return`EXIT ${b.code||1}
457
+ ${(b.stderr||b.message||"").toString().trim()}`}let u;try{u=Bt(e.server)}catch(b){return`ERROR: ${b.message}`}let{stdout:d,stderr:f,exitCode:p,error:m}=await wt(u,c,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
458
+ `).trim();return p!==0?`EXIT ${p}
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:p}=await He(r,{timeout:1e4});return(f||p||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
460
+ ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=Bt(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await wt(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
461
461
  `).trim();return c!==0?`EXIT ${c}
462
- ${u||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 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=qt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await wt(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
462
+ ${u||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:p,stderr:m}=await He(i,{timeout:15e3});return(p||m||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
463
+ ${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=Bt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await wt(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
464
464
  `).trim();return u!==0?`EXIT ${u}
465
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",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(`
466
466
  ${fe.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${fe.reset}`),!await Jt(" 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=qt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await wt(l,a,{timeout:35e3}),h=[c,u].filter(Boolean).join(`
467
+ ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Bt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await wt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
468
468
  `).trim();return d!==0?`EXIT ${d}
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 n=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let m=n?"local":e.server;if(console.log(`
469
+ ${f||p}`:p||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let 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(`
470
470
  ${fe.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${fe.reset}`),!await Jt(" 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 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=qt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await wt(l,a,{timeout:35e3}),h=[c,u].filter(Boolean).join(`
471
+ ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Bt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await wt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
472
472
  `).trim();return d!==0?`EXIT ${d}
473
- ${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...kv(e.config),...e},delete e.config,delete e._name}catch(u){return`ERROR: ${u.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let o=e.method||"rsync";if(o==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let n;try{n=qt(e.server)}catch(u){return`ERROR: ${u.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(`
473
+ ${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...Tv(e.config),...e},delete e.config,delete e._name}catch(u){return`ERROR: ${u.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let o=e.method||"rsync";if(o==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let n;try{n=Bt(e.server)}catch(u){return`ERROR: ${u.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(`
474
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
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 Jt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(o==="git"){let u=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&u!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=u?`cd '${d}' && git fetch origin && git checkout '${u}' && git pull origin '${u}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
476
476
  ${f}${e.deploy_script?`
477
- ${e.deploy_script}`:""}`;let{stdout:h,stderr:m,exitCode:g,error:$}=await wt(n,f,{timeout:12e4});if(i=[h,m].filter(Boolean).join(`
477
+ ${e.deploy_script}`:""}`;let{stdout:p,stderr:m,exitCode:g,error:b}=await wt(n,f,{timeout:12e4});if(i=[p,m].filter(Boolean).join(`
478
478
  `).trim(),g!==0)return`ERROR (git pull, exit ${g}):
479
- ${$||i}`}else{let u=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} ${u} ${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:u,stderr:d,exitCode:f,error:h}=await wt(n,e.deploy_script,{timeout:12e4}),m=[u,d].filter(Boolean).join(`
479
+ ${b||i}`}else{let u=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":"",p=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,m=`rsync -avz --delete ${f} ${d} ${u} ${p} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:b}=await He(m,{timeout:12e4});i=(g||b||"").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:u,stderr:d,exitCode:f,error:p}=await wt(n,e.deploy_script,{timeout:12e4}),m=[u,d].filter(Boolean).join(`
481
481
  `).trim();if(f!==0)return`${o==="git"?"git pull":"rsync"} OK
482
482
 
483
483
  ERROR (deploy_script, exit ${f}):
484
- ${h||m}`;a=`
484
+ ${p||m}`;a=`
485
485
 
486
486
  Deploy script output:
487
- ${m||"(no output)"}`}let l="";if(e.health_check){let u=e.health_check.trim();if(/^https?:\/\//.test(u))try{let f=require("node-fetch"),h=await Promise.race([f(u),new Promise((m,g)=>setTimeout(()=>g(new Error("timeout")),15e3))]);if(h.ok)l=`
487
+ ${m||"(no output)"}`}let l="";if(e.health_check){let u=e.health_check.trim();if(/^https?:\/\//.test(u))try{let f=require("node-fetch"),p=await Promise.race([f(u),new Promise((m,g)=>setTimeout(()=>g(new Error("timeout")),15e3))]);if(p.ok)l=`
488
488
 
489
- Health check: \u2713 ${u} \u2192 ${h.status}`;else return l=`
489
+ Health check: \u2713 ${u} \u2192 ${p.status}`;else return l=`
490
490
 
491
- Health check FAILED: ${u} \u2192 HTTP ${h.status}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l}catch(f){return l=`
491
+ Health check FAILED: ${u} \u2192 HTTP ${p.status}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l}catch(f){return l=`
492
492
 
493
- Health check FAILED: ${u} \u2192 ${f.message}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l}else{let{stdout:f,stderr:h,exitCode:m}=await wt(n,u,{timeout:15e3}),g=[f,h].filter(Boolean).join(`
493
+ Health check FAILED: ${u} \u2192 ${f.message}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l}else{let{stdout:f,stderr:p,exitCode:m}=await wt(n,u,{timeout:15e3}),g=[f,p].filter(Boolean).join(`
494
494
  `).trim();if(m!==0)return l=`
495
495
 
496
496
  Health check FAILED (exit ${m}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
497
497
 
498
498
  Health check: \u2713 ${g||"(exit 0)"}`}}let c=o==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${o}] ${c}
499
- ${i}${a}${l}`.trim()}case"deployment_status":{let o=Sv(),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=qt(a.server||i),u=(await wt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&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=${u?"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=Rv(),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=Bt(a.server||i),u=(await wt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await wt(l,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let m=require("node-fetch"),g=await Promise.race([m(p),new Promise((b,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,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
500
500
  ${r.join(`
501
501
  `)}`}case"frontend_recon":{let o=process.cwd(),n=(e.type||"").toLowerCase(),r=[],i=async(v,S=120)=>{try{let P=ie.isAbsolute(v)?v:ie.join(o,v),se=(await Je.readFile(P,"utf8")).split(`
502
502
  `),ce=se.slice(0,S).join(`
@@ -507,21 +507,21 @@ ${r.join(`
507
507
  `);let d=[...await c("tailwind.config.js"),...await c("tailwind.config.ts"),...await c("tailwind.config.mjs")];if(d.length>0){let v=await i(d[0],80);v&&r.push(`### Tailwind config (${ie.relative(o,d[0])})
508
508
  \`\`\`js
509
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 c(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)})
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"],p=!1;for(let v of f){let S=await c(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)})
511
511
  \`\`\`css
512
512
  ${ne}
513
- \`\`\``),h=!0;break}}if(h)break}if(!h){let v=await u(":root","*.css");if(v.length>0){let S=await i(v[0],100);S&&r.push(`### CSS Variables (${ie.relative(o,v[0])})
513
+ \`\`\``),p=!0;break}}if(p)break}if(!p){let v=await u(":root","*.css");if(v.length>0){let S=await i(v[0],100);S&&r.push(`### CSS Variables (${ie.relative(o,v[0])})
514
514
  \`\`\`css
515
515
  ${S}
516
- \`\`\``),h=!0}}h||r.push("(no CSS custom properties / :root found)"),r.push(`
516
+ \`\`\``),p=!0}}p||r.push("(no CSS custom properties / :root found)"),r.push(`
517
517
  ## STEP 2: Main Layout / Index Page
518
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 c(v);if(S.length>0){let P=await i(S[0],150);if(P){r.push(`### Main layout: ${ie.relative(o,S[0])}
519
519
  \`\`\`html
520
520
  ${P}
521
521
  \`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
522
522
  ## STEP 3: Reference Component (same type)
523
- `);let $=[];if(n){for(let v of["*.html","*.vue","*.jsx","*.tsx"])if($=await u(n,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)}
523
+ `);let b=[];if(n){for(let v of["*.html","*.vue","*.jsx","*.tsx"])if(b=await u(n,v),b.length>0)break}if(b.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});b=v.trim().split(`
524
+ `).filter(Boolean)}catch{b=[]}if(b.length>0){let v=b[0],S=await i(v,150);S?r.push(`### Reference: ${ie.relative(o,v)}
525
525
  \`\`\`html
526
526
  ${S}
527
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(`
@@ -531,20 +531,20 @@ ${S}
531
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(`
532
532
  ---
533
533
  \u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
534
- `)}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=qt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(o)try{let{stdout:u,stderr:d}=await He(l,{timeout:c});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:h}=await wt(n,l,{timeout:c}),m=[u,d].filter(Boolean).join(`
535
- `).trim();return{out:h&&f!==0&&!u.trim()?(h+`
534
+ `)}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=Bt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(o)try{let{stdout:u,stderr:d}=await He(l,{timeout:c});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await wt(n,l,{timeout:c}),m=[u,d].filter(Boolean).join(`
535
+ `).trim();return{out:p&&f!==0&&!u.trim()?(p+`
536
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))&&!s.autoConfirm){let l=o?"local":e.server;if(!await Jt(`sysadmin [${e.action}] on ${l} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let l=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:c,exitCode:u}=await r(l,45e3);return c||`EXIT ${u}
537
537
  (no output)`}case"disk_usage":{let l=e.path||"/",c=Ce(l),u=`df -h ${c}; echo '--- Top subdirs ---'; du -d1 -x -h ${c} 2>/dev/null | sort -rh | head -20`,{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
538
538
  ${d}`:d}case"process_list":{let l=e.sort_by==="mem"?"4":"3",c=(e.limit||20)+1,u=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${c} || ps aux | awk 'NR==1{print; next} {print | "sort -k${l} -rn"}' | head -${c}`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
539
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:c,exitCode:u}=await r(l,15e3);return u!==0?`EXIT ${u}
540
- ${c}`:c}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:l}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),c=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!c)return"ERROR: No supported package manager found (dnf/apt)";let u=e.packages||[];if(!u.every(Dv))return"ERROR: package names contain unsafe characters";let d=u.map(Ce).join(" "),f;switch(e.package_action){case"list":f=c==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=c==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:$}=await r(g,6e4);return $||"(no output from package check)"}case"install":if(!d)return"ERROR: packages required for install";f=c==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=c==="dnf"?`dnf remove -y ${d}`:`apt-get remove -y ${d}`;break;case"update":if(!d)return"ERROR: packages required for update (use upgrade for full system upgrade)";f=c==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=c==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:h,exitCode:m}=await r(f,12e4);return m!==0?`EXIT ${m}
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:c,exitCode:u}=await r(l,1e4);return u!==0?`EXIT ${u}
540
+ ${c}`:c}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:l}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),c=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!c)return"ERROR: No supported package manager found (dnf/apt)";let u=e.packages||[];if(!u.every(Uv))return"ERROR: package names contain unsafe characters";let d=u.map(Ce).join(" "),f;switch(e.package_action){case"list":f=c==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=c==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:b}=await r(g,6e4);return b||"(no output from package check)"}case"install":if(!d)return"ERROR: packages required for install";f=c==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=c==="dnf"?`dnf remove -y ${d}`:`apt-get remove -y ${d}`;break;case"update":if(!d)return"ERROR: packages required for update (use upgrade for full system upgrade)";f=c==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=c==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:p,exitCode:m}=await r(f,12e4);return m!==0?`EXIT ${m}
541
+ ${p}`:p||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let l=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:c,exitCode:u}=await r(l,1e4);return u!==0?`EXIT ${u}
542
542
  ${c}`:c||"(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 c=Ce(e.user),u=`id ${c} && echo '--- Groups ---' && groups ${c} && echo '--- Last login ---' && lastlog -u ${c} 2>/dev/null`,{out:d,exitCode:f}=await r(u,1e4);return f!==0?`EXIT ${f}
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(sg))return"ERROR: groups contain unsafe characters";let c=(e.groups||[]).map(m=>`-G ${Ce(m)}`).join(" "),u=Ce(e.user),d=`useradd -m ${c} ${u} && echo "User ${e.user} created"`,{out:f,exitCode:h}=await r(d,15e3);return h!==0?`EXIT ${h}
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(ig))return"ERROR: groups contain unsafe characters";let c=(e.groups||[]).map(m=>`-G ${Ce(m)}`).join(" "),u=Ce(e.user),d=`useradd -m ${c} ${u} && echo "User ${e.user} created"`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
544
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 u=`userdel -r ${Ce(e.user)} && echo "User ${e.user} deleted"`,{out:d,exitCode:f}=await r(u,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 u=`${`/home/${e.user}`}/.ssh`,d=`${u}/authorized_keys`,f=Ce(e.user),h=`mkdir -p ${Ce(u)} && chmod 700 ${Ce(u)} && printf '%s
546
- ' ${Ce(e.ssh_key)} >> ${Ce(d)} && chmod 600 ${Ce(d)} && chown -R ${Ce(`${e.user}:${e.user}`)} ${Ce(u)} && 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),c=l.includes("firewalld")?"firewalld":l.includes("ufw")?"ufw":"iptables",u;switch(e.firewall_action){case"status":u=c==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":c==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';if(!Rc(e.port))return"ERROR: port contains unsafe characters";u=c==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw allow ${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";u=c==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:c==="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";u=c==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:c==="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":u=c==="firewalld"?"firewall-cmd --reload":c==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
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 u=`${`/home/${e.user}`}/.ssh`,d=`${u}/authorized_keys`,f=Ce(e.user),p=`mkdir -p ${Ce(u)} && chmod 700 ${Ce(u)} && printf '%s
546
+ ' ${Ce(e.ssh_key)} >> ${Ce(d)} && chmod 600 ${Ce(d)} && chown -R ${Ce(`${e.user}:${e.user}`)} ${Ce(u)} && echo "SSH key added for ${e.user}"`,{out:m,exitCode:g}=await r(p,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),c=l.includes("firewalld")?"firewalld":l.includes("ufw")?"ufw":"iptables",u;switch(e.firewall_action){case"status":u=c==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":c==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';if(!Nc(e.port))return"ERROR: port contains unsafe characters";u=c==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw allow ${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(!Nc(e.port))return"ERROR: port contains unsafe characters";u=c==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw deny ${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(!Nc(e.port))return"ERROR: port contains unsafe characters";u=c==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw delete allow ${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":u=c==="firewalld"?"firewall-cmd --reload":c==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
548
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 c=Jo(e.user);if(c)return c}let l=e.user?`-u ${Ce(e.user)}`:"";switch(e.cron_action){case"list":{let c=`crontab ${l} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:u}=await r(c,1e4);return u||"(empty crontab)"}case"add":{if(!e.schedule)return"ERROR: schedule is required for cron add";if(!e.command)return"ERROR: command is required for cron add";let c=`${e.schedule} ${e.command}`,u=`(crontab ${l} -l 2>/dev/null; printf '%s
549
549
  ' ${Ce(c)}) | crontab ${l} - && echo "Cron entry added: ${c}"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
550
550
  ${d}`:d}case"remove":{if(!e.command)return"ERROR: command (substring to match) is required for cron remove";let c=e.command.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=`crontab ${l} -l 2>/dev/null | grep -v "${c}" | crontab ${l} - && echo "Matching cron entries removed"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
@@ -573,12 +573,12 @@ if [ -n "$EXPIRY" ]; then
573
573
  fi
574
574
  `.trim();let{out:c,exitCode:u}=await r(l,25e3),d=/notAfter=|Days until expiry:/i.test(c);return u!==0&&!d?`EXIT ${u}
575
575
  ${c}`:c||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let c=`tail -n ${e.lines||100} ${Ce(e.path)} 2>&1`,{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
576
- ${u}`:u||"(empty log)"}case"find_large":{let l=e.path||"/",c=e.limit||20,u=e.min_size||"100M",d=`find ${Ce(l)} -xdev -type f -size +${Ce(u)} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${c}`,{out:f,exitCode:h}=await r(d,6e4);return h!==0?`EXIT ${h}
577
- ${f}`:f||`(no files larger than ${u} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";if(e.service_name){let 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`:"",c;switch(e.service_action){case"status":c=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":c="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":c=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":c=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":c=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":c=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":c=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":c=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(c,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
578
- ${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let l=e.signal||"SIGTERM";if(!qv(l))return"ERROR: signal contains unsafe characters";let c;if(e.pid){if(!/^\d+$/.test(String(e.pid)))return"ERROR: pid must be numeric";c=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${l} ${e.pid} && echo "Sent ${l} to PID ${e.pid}"`}else c=`pgrep -a ${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:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
576
+ ${u}`:u||"(empty log)"}case"find_large":{let l=e.path||"/",c=e.limit||20,u=e.min_size||"100M",d=`find ${Ce(l)} -xdev -type f -size +${Ce(u)} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${c}`,{out:f,exitCode:p}=await r(d,6e4);return p!==0?`EXIT ${p}
577
+ ${f}`:f||`(no files larger than ${u} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";if(e.service_name){let p=Pc(e.service_name,"service_name");if(p)return p}let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",c;switch(e.service_action){case"status":c=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":c="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":c=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":c=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":c=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":c=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":c=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":c=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(c,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
578
+ ${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let l=e.signal||"SIGTERM";if(!Wv(l))return"ERROR: signal contains unsafe characters";let c;if(e.pid){if(!/^\d+$/.test(String(e.pid)))return"ERROR: pid must be numeric";c=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${l} ${e.pid} && echo "Sent ${l} to PID ${e.pid}"`}else c=`pgrep -a ${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:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
579
579
  ${u}`:u}case"journalctl":{let l=e.lines||100,c=["journalctl","--no-pager","-n",String(l)];e.unit&&c.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&c.push("-p",e.priority),e.since&&c.push(`--since="${e.since}"`),c.push('2>/dev/null || echo "(journalctl not available)"');let{out:u,exitCode:d}=await r(c.join(" "),2e4);return d!==0?`EXIT ${d}
580
- ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=Go(),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}=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(),n=await o(t,e,s);return n!==null?n:`ERROR: Unknown tool: ${t}`}}}async function Bv(t,e,s={}){let{emit:o}=ui(),{logToolExecution:n}=Fm(),r=Date.now(),i=s.silent?null:mv(t,e);if(!i){let l=await Jm(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 pv(i);a.start();try{let l=await Jm(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}}og.exports={TOOL_DEFINITIONS:Fv,executeTool:Bv,resolvePath:lt,autoFixPath:Fi,autoFixEdit:ng,enrichBashError:tg,cancelPendingAskUser:Ov,setAskUserHandler:Nv,fileExists:At}});var Ao=Z((NA,ig)=>{ig.exports=rg()});var Pc=Z((MA,lg)=>{var{loadServerProfiles:Zs,resolveProfile:PA,sshExec:Uv}=Ws(),Wv=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,Hv=/\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,Yv=/https?:\/\/[^\s)]+/gi;function Gv(t){if(typeof t!="string")return[];let e=new Set,s=[];for(let o of t.match(Yv)||[]){let n=o.replace(/[.,;!?]+$/g,"");e.has(n)||(e.add(n),s.push(n))}return s}function zv(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 ag(t,e=Zs()){if(typeof t!="string"||!Hv.test(t))return null;let s=Gv(t).filter(o=>!Wv.test(o));if(s.length===0)return null;for(let o of s){let n=zv(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 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 Kv(){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}`:"",c=r.sudo?", sudo available":"";s.push(`- **${n}**: ${i}${a}${l}${c}`)}let o=new Set;for(let n of Object.values(t))n.os&&Nc[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 Nc[n])s.push(`- ${i}`)}}return s.join(`
581
- `)}function Xv(t){let e=Zs();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function Vv(){return Object.keys(Zs())}function Jv(){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 c=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(`
580
+ ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=Go(),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}=Go();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=di(),n=await o(t,e,s);return n!==null?n:`ERROR: Unknown tool: ${t}`}}}async function Yv(t,e,s={}){let{emit:o}=di(),{logToolExecution:n}=Wm(),r=Date.now(),i=s.silent?null:bv(t,e);if(!i){let l=await eg(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 wv(i);a.start();try{let l=await eg(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}}ag.exports={TOOL_DEFINITIONS:Hv,executeTool:Yv,resolvePath:ct,autoFixPath:Bi,autoFixEdit:rg,enrichBashError:og,cancelPendingAskUser:Lv,setAskUserHandler:Iv,fileExists:At}});var Ao=Z((DA,cg)=>{cg.exports=lg()});var jc=Z((FA,dg)=>{var{loadServerProfiles:Zs,resolveProfile:qA,sshExec:Gv}=Ws(),zv=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,Kv=/\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,Xv=/https?:\/\/[^\s)]+/gi;function Vv(t){if(typeof t!="string")return[];let e=new Set,s=[];for(let o of t.match(Xv)||[]){let n=o.replace(/[.,;!?]+$/g,"");e.has(n)||(e.add(n),s.push(n))}return s}function Jv(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 ug(t,e=Zs()){if(typeof t!="string"||!Kv.test(t))return null;let s=Vv(t).filter(o=>!zv.test(o));if(s.length===0)return null;for(let o of s){let n=Jv(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 Ic={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 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}`:"",c=r.sudo?", sudo available":"";s.push(`- **${n}**: ${i}${a}${l}${c}`)}let o=new Set;for(let n of Object.values(t))n.os&&Ic[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 Ic[n])s.push(`- ${i}`)}}return s.join(`
581
+ `)}function Qv(t){let e=Zs();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function eE(){return Object.keys(Zs())}function tE(){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 c=r.map(f=>{let p=n[f],m=p.user?`${p.user}@${p.host}`:p.host,g=p.port&&Number(p.port)!==22?`:${p.port}`:"";return` - **${f}**: ${m}${g}${p.os?` (${p.os})`:""}`}).join(`
582
582
  `),u=r.map(f=>n[f].log_path).filter(Boolean),d=u.length>0?`
583
583
  - Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
584
584
 
@@ -597,7 +597,7 @@ ${c}
597
597
  - \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
598
598
  - \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
599
599
 
600
- **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${Zv(n)}`}function Zv(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.${nE(n)}`}function nE(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
601
601
 
602
602
  ## Server Debugging Rules
603
603
 
@@ -608,36 +608,36 @@ ${c}
608
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.
609
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.
610
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.
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 Qv(t){let e=Zs(),s=ag(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 Uv(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]
612
- `+i.trim()}catch{return null}}lg.exports={getServerContext:Kv,getDeploymentContextBlock:Jv,hasServerOS:Xv,getProfileNames:Vv,probeUrlServer:Qv,detectRuntimeDebugTarget:ag,OS_HINTS:Nc}});var fg=Z((LA,dg)=>{var $t=require("fs").promises,Wi=require("fs"),Ye=require("path"),Ui=require("util").promisify(require("child_process").exec),{C:Qs}=it(),{getMergeConflicts:ug}=ri(),{getServerContext:eE}=Pc(),{refreshIndex:tE,getFileIndex:nE,buildContentIndex:sE,summarizeModuleHubs:oE}=an(),rE=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),iE=[{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 aE(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 lE(t){let e=new Set(t),s=new Set;for(let o of iE)(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 cE(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 uE(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=Ye.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 dE(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function fE(t){try{await tE(t);let e=nE();if(!e||e.length===0)return"";let s=lE(e),o=aE(e),n=cE(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=uE(e),a=[];try{let d=Ye.join(t,"package.json");if(Wi.existsSync(d)){let f=JSON.parse(Wi.readFileSync(d,"utf-8"));a=dE(f)}}catch{}let l="",c="";try{let d=await sE(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 oE(t,4);d.length>0&&(c=`MODULE HUBS: ${d.join(", ")}`)}catch{}let u=[`REPO MAP: ${e.length} indexed files${s.length?` | stack: ${s.join(", ")}`:""}`];return o.length>0&&u.push(`WORK AREAS: ${o.join(", ")}`),n.length>0&&u.push(`LIKELY ENTRY POINTS: ${n.join(", ")}`),a.length>0&&u.push(`WORKSPACES: ${a.join(", ")}`),r>0&&u.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&u.push(`TEST MAP: ${i.join(" | ")}`),l&&u.push(l),c&&u.push(c),u.push("RETRIEVAL RULE: Prefer the smallest verified path set first \u2014 identify likely files, then read only the exact symbols/sections you need before editing."),u.join(`
613
- `)}catch{return""}}function hE(t){try{return Wi.readFileSync(t,"utf-8").split(`
614
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function pE(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 mE(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:o=[]}={}){let n=Ye.join(t,".gitignore"),r=[...o,...hE(n)],i=0,a=[Ye.basename(t)+"/"];function l(c,u,d){if(d>e||i>=s)return;let f;try{f=Wi.readdirSync(c,{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=>!(rE.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||pE(m.name,r)));for(let m=0;m<h.length;m++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],$=m===h.length-1,x=$?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",E=u+($?" ":"\u2502 "),N=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${x}${N}`),i++,g.isDirectory()&&l(Ye.join(c,g.name),E,d+1)}}return l(t,"",1),a.join(`
615
- `)}var Mc=new Map,to=new Map,Hi=null,cg=3e4,eo={result:null,expiry:0,cwd:null};async function fn(t){try{return await t()}catch{return null}}async function gE(){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 s=await $t.stat(e),o=to.get(e);if(!o||s.mtimeMs!==o)return!1}catch{if(to.has(e))return!1}try{let e=Ye.join(process.cwd(),".git","HEAD"),s=await $t.stat(e),o=to.get(e);if(!o||s.mtimeMs!==o)return!1}catch{}return!0}async function yE(){let t=[Ye.join(process.cwd(),"package.json"),Ye.join(process.cwd(),"README.md"),Ye.join(process.cwd(),".gitignore"),Ye.join(process.cwd(),".git","HEAD"),Ye.join(process.cwd(),"CLAUDE.md"),Ye.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let s=await $t.stat(e);to.set(e,s.mtimeMs)}catch{to.delete(e)}}async function wE(t){let e="fileContext",s=Mc.get(e),o=!1;if(s&&await gE()&&(o=!0),!o){let c=[],u=Ye.join(t,"package.json");if(await fn(()=>$t.access(u).then(()=>!0).catch(()=>!1)))try{let S=await $t.readFile(u,"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),c.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(`
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 sE(t){let e=Zs(),s=ug(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 Gv(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]
612
+ `+i.trim()}catch{return null}}dg.exports={getServerContext:Zv,getDeploymentContextBlock:tE,hasServerOS:Qv,getProfileNames:eE,probeUrlServer:sE,detectRuntimeDebugTarget:ug,OS_HINTS:Ic}});var mg=Z((BA,hg)=>{var bt=require("fs").promises,Hi=require("fs"),Ye=require("path"),Wi=require("util").promisify(require("child_process").exec),{C:Qs}=at(),{getMergeConflicts:pg}=ii(),{getServerContext:oE}=jc(),{refreshIndex:rE,getFileIndex:iE,buildContentIndex:aE,summarizeModuleHubs:lE}=ln(),cE=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),uE=[{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 dE(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 fE(t){let e=new Set(t),s=new Set;for(let o of uE)(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 pE(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 hE(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=Ye.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 mE(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function gE(t){try{await rE(t);let e=iE();if(!e||e.length===0)return"";let s=fE(e),o=dE(e),n=pE(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=hE(e),a=[];try{let d=Ye.join(t,"package.json");if(Hi.existsSync(d)){let f=JSON.parse(Hi.readFileSync(d,"utf-8"));a=mE(f)}}catch{}let l="",c="";try{let d=await aE(t),f=Object.entries(d.files||{}).map(([p,m])=>({file:p,defs:Array.isArray(m.defs)?m.defs.length:0})).filter(p=>p.defs>0).sort((p,m)=>m.defs-p.defs||p.file.localeCompare(m.file)).slice(0,4).map(p=>`${p.file} (${p.defs} defs)`);f.length>0&&(l=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await lE(t,4);d.length>0&&(c=`MODULE HUBS: ${d.join(", ")}`)}catch{}let u=[`REPO MAP: ${e.length} indexed files${s.length?` | stack: ${s.join(", ")}`:""}`];return o.length>0&&u.push(`WORK AREAS: ${o.join(", ")}`),n.length>0&&u.push(`LIKELY ENTRY POINTS: ${n.join(", ")}`),a.length>0&&u.push(`WORKSPACES: ${a.join(", ")}`),r>0&&u.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&u.push(`TEST MAP: ${i.join(" | ")}`),l&&u.push(l),c&&u.push(c),u.push("RETRIEVAL RULE: Prefer the smallest verified path set first \u2014 identify likely files, then read only the exact symbols/sections you need before editing."),u.join(`
613
+ `)}catch{return""}}function yE(t){try{return Hi.readFileSync(t,"utf-8").split(`
614
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function wE(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 bE(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:o=[]}={}){let n=Ye.join(t,".gitignore"),r=[...o,...yE(n)],i=0,a=[Ye.basename(t)+"/"];function l(c,u,d){if(d>e||i>=s)return;let f;try{f=Hi.readdirSync(c,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let p=f.filter(m=>!(cE.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||wE(m.name,r)));for(let m=0;m<p.length;m++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=p[m],b=m===p.length-1,x=b?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",E=u+(b?" ":"\u2502 "),N=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${x}${N}`),i++,g.isDirectory()&&l(Ye.join(c,g.name),E,d+1)}}return l(t,"",1),a.join(`
615
+ `)}var Dc=new Map,to=new Map,Yi=null,fg=3e4,eo={result:null,expiry:0,cwd:null};async function pn(t){try{return await t()}catch{return null}}async function $E(){if(!Yi||Date.now()>Yi)return!1;let t=[Ye.join(process.cwd(),"package.json"),Ye.join(process.cwd(),"README.md"),Ye.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await bt.stat(e),o=to.get(e);if(!o||s.mtimeMs!==o)return!1}catch{if(to.has(e))return!1}try{let e=Ye.join(process.cwd(),".git","HEAD"),s=await bt.stat(e),o=to.get(e);if(!o||s.mtimeMs!==o)return!1}catch{}return!0}async function _E(){let t=[Ye.join(process.cwd(),"package.json"),Ye.join(process.cwd(),"README.md"),Ye.join(process.cwd(),".gitignore"),Ye.join(process.cwd(),".git","HEAD"),Ye.join(process.cwd(),"CLAUDE.md"),Ye.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let s=await bt.stat(e);to.set(e,s.mtimeMs)}catch{to.delete(e)}}async function xE(t){let e="fileContext",s=Dc.get(e),o=!1;if(s&&await $E()&&(o=!0),!o){let c=[],u=Ye.join(t,"package.json");if(await pn(()=>bt.access(u).then(()=>!0).catch(()=>!1)))try{let S=await bt.readFile(u,"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),c.push(`PACKAGE: ${JSON.stringify(ne)}`)}catch{}let f=Ye.join(t,"README.md");if(await pn(()=>bt.access(f).then(()=>!0).catch(()=>!1))){let P=(await bt.readFile(f,"utf-8")).split(`
616
616
  `).slice(0,50);c.push(`README (first 50 lines):
617
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");c.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()&&c.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()&&c.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
621
- ${S.trim()}`)}let v=await fE(t);v&&c.push(v),s=c.join(`
618
+ `)}`)}let m=Ye.join(t,".gitignore");if(await pn(()=>bt.access(m).then(()=>!0).catch(()=>!1))){let S=await bt.readFile(m,"utf-8");c.push(`GITIGNORE:
619
+ ${S.trim()}`)}let b=Ye.join(t,"CLAUDE.md");if(await pn(()=>bt.access(b).then(()=>!0).catch(()=>!1))){let S=await bt.readFile(b,"utf-8");S.trim()&&c.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
620
+ ${S.trim()}`)}let E=Ye.join(t,".nex","CLAUDE.md");if(await pn(()=>bt.access(E).then(()=>!0).catch(()=>!1))){let S=await bt.readFile(E,"utf-8");S.trim()&&c.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
621
+ ${S.trim()}`)}let v=await gE(t);v&&c.push(v),s=c.join(`
622
622
 
623
- `),Mc.set(e,s),Hi=Date.now()+cg,await yE()}let n=[s],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:c}=await Ui("git branch --show-current",{cwd:t,timeout:5e3});return c.trim()}),fn(async()=>{let{stdout:c}=await Ui("git status --short",{cwd:t,timeout:5e3});return c.trim()}),fn(async()=>{let{stdout:c}=await Ui("git log --oneline -5",{cwd:t,timeout:5e3});return c.trim()}),ug()]),eo={result:{branch:r,status:i,log:a,conflicts:l},expiry:Date.now()+cg,cwd:t}),r&&n.push(`GIT BRANCH: ${r}`),i&&n.push(`GIT STATUS:
623
+ `),Dc.set(e,s),Yi=Date.now()+fg,await _E()}let n=[s],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([pn(async()=>{let{stdout:c}=await Wi("git branch --show-current",{cwd:t,timeout:5e3});return c.trim()}),pn(async()=>{let{stdout:c}=await Wi("git status --short",{cwd:t,timeout:5e3});return c.trim()}),pn(async()=>{let{stdout:c}=await Wi("git log --oneline -5",{cwd:t,timeout:5e3});return c.trim()}),pg()]),eo={result:{branch:r,status:i,log:a,conflicts:l},expiry:Date.now()+fg,cwd:t}),r&&n.push(`GIT BRANCH: ${r}`),i&&n.push(`GIT STATUS:
624
624
  ${i}`),a&&n.push(`RECENT COMMITS:
625
625
  ${a}`),l&&l.length>0){let c=l.map(u=>` ${u.file}`).join(`
626
626
  `);n.push(`MERGE CONFLICTS (resolve before editing these files):
627
- ${c}`)}try{let c=eE();c&&n.push(c)}catch{}return n.join(`
627
+ ${c}`)}try{let c=oE();c&&n.push(c)}catch{}return n.join(`
628
628
 
629
- `)}async function $E(t){let e=Ye.join(t,"package.json"),s="";if(await fn(()=>$t.access(e).then(()=>!0).catch(()=>!1)))try{let i=await $t.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[n,r]=await Promise.all([fn(async()=>{let{stdout:i}=await Ui("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),ug()]);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()}dg.exports={gatherProjectContext:wE,printContext:$E,generateFileTree:mE,_clearContextCache:()=>{Mc.clear(),to.clear(),Hi=null,eo={result:null,expiry:0,cwd:null}}}});var Gi=Z((IA,mg)=>{var Qt=require("fs"),Yi=require("path"),{atomicWrite:bE}=Gn();function tr(){return Yi.join(process.cwd(),".nex","sessions")}function Lc(){let t=tr();Qt.existsSync(t)||Qt.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,s={}){Lc();let o=Ic(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 bE(o,JSON.stringify(n,null,2)),{path:o,name:t}}function hg(t){let e=Ic(t);if(!Qt.existsSync(e))return null;try{return JSON.parse(Qt.readFileSync(e,"utf-8"))}catch{return null}}function pg(){Lc();let t=tr(),e=Qt.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(Qt.readFileSync(Yi.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 _E(t){let e=Ic(t);return Qt.existsSync(e)?(Qt.unlinkSync(e),!0):!1}function xE(){let t=pg();return t.length===0?null:hg(t[0].name)}var us=null,vn=null,er=null;function kE(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 SE(){us&&(clearTimeout(us),us=null),vn&&vn.length>0&&(jc("_autosave",vn,er),vn=null,er=null)}function vE(){Lc();let t=tr(),e=Qt.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=Yi.join(t,r);try{let a=Qt.statSync(i);new Date(a.mtime)<o&&(Qt.unlinkSync(i),n++)}catch{}}return n}mg.exports={saveSession:jc,loadSession:hg,listSessions:pg,deleteSession:_E,getLastSession:xE,autoSave:kE,flushAutoSave:SE,clearOldSessions:vE,_getSessionsDir:tr}});var Sg=Z((jA,kg)=>{"use strict";var nr=require("fs"),gg=require("path");function yg(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 EE(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 wg(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 $g(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 bg(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 _g(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 xg(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=yg(t),n=wg(t),r=o.length,i=EE(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 c=o.find(_=>{let M=_.input?.command||_.input?.cmd||"";return/\bsed\s+-n\b/.test(M)});if(c){let _=(c.input?.command||c.input?.cmd||"").slice(0,80);n.some(F=>F.content.includes("BLOCKED: sed -n is forbidden")||F.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 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,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(_=>_.role==="assistant"),f=$g(t),m=bg(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 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,s.push("Auto-compress triggered (context flood indicator)"));let x=_g(a),E=0,N="";for(let[_,M]of x)M>E&&(E=M,N=_);if(E>=3){let[_]=N.split("|");e-=1,s.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,s.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,s.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,s.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 se(_,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,oe=M-_||1;if(H/oe>=.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&&se(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&&se(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("/");s.push(`read_file loop: "${_}" read ${ce}\xD7 (file already in context)`)}let re=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&&se(K,C,F)){ee=!0;break}F.push([K,C])}!ee&&M.ranges.length>re&&(re=M.ranges.length,le=_)}if(re>=4){e-=.5;let _=le.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${_}" read in ${re} 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("/");s.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+/),oe=H[H.length-1];for(let J of _)(J.endsWith(oe)||oe.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(", ");s.push(`Temp file write-then-delete: ${C} \u2014 write inline logic or use tests/ instead`)}}let we=n.filter(_=>_.content.startsWith("EXIT")).length;we>=10?(e-=1,s.push(`Bash exit-error storm: ${we} tool results started with EXIT (repeated failing commands)`)):we>=5&&(e-=.5,s.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(oe=>oe&&(oe.type==="text"||typeof oe=="string")).map(oe=>typeof oe=="string"?oe:oe.text||"").join("")),M.length<=5e3)continue;let F=M.split(/(?<=\. )/).filter(oe=>oe.trim().length>0);if(F.length<6)continue;let ee=new Map;for(let oe=0;oe<=F.length-3;oe++){let J=F.slice(oe,oe+3).join("").trim();J.length>30&&ee.set(J,(ee.get(J)||0)+1)}let K=0,C="";for(let[oe,J]of ee)J>K&&(K=J,C=oe);if(K<3)continue;let H=C.length*K/M.length;if(H>=.4||K>=10){e-=1.5,s.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,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 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-=_,s.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)"),s.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,s.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,s.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);s.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,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 F=(_.match(/^```/gm)||[]).length%2!==0,ee=/"\s*:\s*$/.test(_.trimEnd()),K=/[,\[{]\s*$/.test(_.trimEnd());(F||ee||K)&&(e-=.75,s.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,s.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 _=n.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,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,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,s.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=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:Ne,issues:s,summary:ve}}function TE(t){try{let{loadSession:e}=Gi(),s=e(t);return s?xg(s.messages||[]):null}catch{return null}}function RE(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(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(s>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
629
+ `)}async function kE(t){let e=Ye.join(t,"package.json"),s="";if(await pn(()=>bt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await bt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[n,r]=await Promise.all([pn(async()=>{let{stdout:i}=await Wi("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),pg()]);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()}hg.exports={gatherProjectContext:xE,printContext:kE,generateFileTree:bE,_clearContextCache:()=>{Dc.clear(),to.clear(),Yi=null,eo={result:null,expiry:0,cwd:null}}}});var zi=Z((UA,wg)=>{var Qt=require("fs"),Gi=require("path"),{atomicWrite:SE}=zn();function tr(){return Gi.join(process.cwd(),".nex","sessions")}function qc(){let t=tr();Qt.existsSync(t)||Qt.mkdirSync(t,{recursive:!0,mode:448})}function Fc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Gi.join(tr(),`${e}.json`)}function Bc(t,e,s={}){qc();let o=Fc(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 SE(o,JSON.stringify(n,null,2)),{path:o,name:t}}function gg(t){let e=Fc(t);if(!Qt.existsSync(e))return null;try{return JSON.parse(Qt.readFileSync(e,"utf-8"))}catch{return null}}function yg(){qc();let t=tr(),e=Qt.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(Qt.readFileSync(Gi.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 vE(t){let e=Fc(t);return Qt.existsSync(e)?(Qt.unlinkSync(e),!0):!1}function EE(){let t=yg();return t.length===0?null:gg(t[0].name)}var In=null,vn=null,er=null;function TE(t,e={}){t.length!==0&&(In&&clearTimeout(In),vn=t,er=e||{},In=setTimeout(()=>{vn&&vn.length>0&&Bc("_autosave",vn,er),In=null,vn=null,er=null},5e3),In.unref?.())}function RE(){In&&(clearTimeout(In),In=null),vn&&vn.length>0&&(Bc("_autosave",vn,er),vn=null,er=null)}function CE(){qc();let t=tr(),e=Qt.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=Gi.join(t,r);try{let a=Qt.statSync(i);new Date(a.mtime)<o&&(Qt.unlinkSync(i),n++)}catch{}}return n}wg.exports={saveSession:Bc,loadSession:gg,listSessions:yg,deleteSession:vE,getLastSession:EE,autoSave:TE,flushAutoSave:RE,clearOldSessions:CE,_getSessionsDir:tr}});var Tg=Z((WA,Eg)=>{"use strict";var nr=require("fs"),bg=require("path");function $g(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 AE(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 _g(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 xg(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 kg(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 Sg(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 vg(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=$g(t),n=_g(t),r=o.length,i=AE(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 c=o.find(_=>{let M=_.input?.command||_.input?.cmd||"";return/\bsed\s+-n\b/.test(M)});if(c){let _=(c.input?.command||c.input?.cmd||"").slice(0,80);n.some(F=>F.content.includes("BLOCKED: sed -n is forbidden")||F.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 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,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(_=>_.role==="assistant"),f=xg(t),m=kg(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 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,s.push("Auto-compress triggered (context flood indicator)"));let x=Sg(a),E=0,N="";for(let[_,M]of x)M>E&&(E=M,N=_);if(E>=3){let[_]=N.split("|");e-=1,s.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,s.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,s.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,s.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 se(_,M,F){for(let[ee,K]of F){let C=Math.max(_,ee),pe=Math.min(M,K);if(pe>C){let H=pe-C,oe=M-_||1;if(H/oe>=.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[pe,H]of M.ranges){if(C.length>0&&se(pe,H,C)){K=!0;break}C.push([pe,H])}if(!K)continue}if(M.count-M.ranges.length<=2&&M.ranges.length>=1){let K=!1,C=[];for(let[pe,H]of M.ranges){if(C.length>0&&se(pe,H,C)){K=!0;break}C.push([pe,H])}if(!K)continue}M.count>ce&&(ce=M.count,de=_)}if(ce>=3){e-=1;let _=de.split("/").slice(-2).join("/");s.push(`read_file loop: "${_}" read ${ce}\xD7 (file already in context)`)}let re=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&&se(K,C,F)){ee=!0;break}F.push([K,C])}!ee&&M.ranges.length>re&&(re=M.ranges.length,le=_)}if(re>=4){e-=.5;let _=le.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${_}" read in ${re} 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("/");s.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(),pe=K.input.path.includes("/tests/");F.test(C)&&!pe&&_.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 pe of C){let H=pe.split(/\s+/),oe=H[H.length-1];for(let J of _)(J.endsWith(oe)||oe.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(pe=>pe.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${C} \u2014 write inline logic or use tests/ instead`)}}let we=n.filter(_=>_.content.startsWith("EXIT")).length;we>=10?(e-=1,s.push(`Bash exit-error storm: ${we} tool results started with EXIT (repeated failing commands)`)):we>=5&&(e-=.5,s.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(oe=>oe&&(oe.type==="text"||typeof oe=="string")).map(oe=>typeof oe=="string"?oe:oe.text||"").join("")),M.length<=5e3)continue;let F=M.split(/(?<=\. )/).filter(oe=>oe.trim().length>0);if(F.length<6)continue;let ee=new Map;for(let oe=0;oe<=F.length-3;oe++){let J=F.slice(oe,oe+3).join("").trim();J.length>30&&ee.set(J,(ee.get(J)||0)+1)}let K=0,C="";for(let[oe,J]of ee)J>K&&(K=J,C=oe);if(K<3)continue;let H=C.length*K/M.length;if(H>=.4||K>=10){e-=1.5,s.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,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 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-=_,s.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)"),s.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,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):M&&!K&&o.some(pe=>(pe.name==="write_file"||pe.name==="Write")&&pe.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(pe.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(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 pe=C.trim();return pe.length>0&&pe.length<=30&&/^\d/.test(pe)&&/=/.test(pe)&&!/[a-zA-Z]/.test(pe)});if(ee.test(F)||K){e-=1.5;let C=(K||F.split(`
631
+ `)[0]).trim().slice(0,40);s.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(pe=>pe&&(pe.type==="text"||typeof pe=="string")).map(pe=>typeof pe=="string"?pe:pe.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,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 F=(_.match(/^```/gm)||[]).length%2!==0,ee=/"\s*:\s*$/.test(_.trimEnd()),K=/[,\[{]\s*$/.test(_.trimEnd());(F||ee||K)&&(e-=.75,s.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 pe=C.content.find(H=>H&&H.type==="tool_result"&&H.tool_use_id===F.id);if(pe){ee=typeof pe.content=="string"?pe.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,s.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 _=n.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,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,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,s.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=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:Ne,issues:s,summary:ve}}function OE(t){try{let{loadSession:e}=zi(),s=e(t);return s?vg(s.messages||[]):null}catch{return null}}function NE(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(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(s>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
633
633
  ${n}${f}${r}`}let l="";for(let u of a.slice(0,4))l+=`
634
634
  ${i}\u26A0${r} ${n}${u}${r}`;let c=a.length-4;return c>0&&(l+=`
635
- ${n}(+${c} more)${r}`),l}function CE(t,e={}){try{let s=gg.join(process.cwd(),".nex");nr.existsSync(s)||nr.mkdirSync(s,{recursive:!0});let o=gg.join(s,"benchmark-history.json"),n=[];if(nr.existsSync(o))try{n=JSON.parse(nr.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)),nr.writeFileSync(o,JSON.stringify(n,null,2))}catch{}}kg.exports={scoreMessages:xg,scoreSession:TE,formatScore:RE,appendScoreHistory:CE,_extractToolCalls:yg,_extractToolResults:wg,_getLastAssistantText:$g,_getLastNAssistantTexts:bg,_countDuplicateToolCalls:_g}});var rr=Z((DA,Cg)=>{"use strict";var AE=require("os"),Dc=require("path"),In=require("fs"),sr=Dc.join(AE.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}},vg=["agentic","frontend","sysadmin","data","coding"];function OE(t){if(!t||t.length<8)return null;for(let e of vg){let s=zi[e];if(!s.pattern||s.pattern.test(t))return s}return zi.coding}function or(){try{if(In.existsSync(sr))return JSON.parse(In.readFileSync(sr,"utf-8"))}catch{}return{}}function Eg(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 Tg={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 Rg(){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 NE(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let s=Rg();return s?.[t]?s[t]:e?Eg(e):null}function PE(t){return or().phaseBudgets?.[t]||Tg[t]||20}function ME(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:Rg()!==null}function LE(t){let e=Dc.dirname(sr);In.existsSync(e)||In.mkdirSync(e,{recursive:!0});let s=or(),o={...s,...t};!t.phases&&s.phases&&(o.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(o.phaseBudgets=s.phaseBudgets),In.writeFileSync(sr,JSON.stringify(o,null,2));try{let n=Dc.join(e,".env"),r="";In.existsSync(n)&&(r=In.readFileSync(n,"utf-8"));let i=r.split(/\r?\n/),a=(l,c)=>{let u=i.findIndex(d=>d.startsWith(l+"="));u>=0?i[u]=`${l}=${c}`:i.push(`${l}=${c}`)};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(n,i.filter(l=>l.trim()!=="").join(`
635
+ ${n}(+${c} more)${r}`),l}function PE(t,e={}){try{let s=bg.join(process.cwd(),".nex");nr.existsSync(s)||nr.mkdirSync(s,{recursive:!0});let o=bg.join(s,"benchmark-history.json"),n=[];if(nr.existsSync(o))try{n=JSON.parse(nr.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)),nr.writeFileSync(o,JSON.stringify(n,null,2))}catch{}}Eg.exports={scoreMessages:vg,scoreSession:OE,formatScore:NE,appendScoreHistory:PE,_extractToolCalls:$g,_extractToolResults:_g,_getLastAssistantText:xg,_getLastNAssistantTexts:kg,_countDuplicateToolCalls:Sg}});var rr=Z((HA,Ng)=>{"use strict";var ME=require("os"),Uc=require("path"),jn=require("fs"),sr=Uc.join(ME.homedir(),".nex-code","model-routing.json"),Ki={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}},Rg=["agentic","frontend","sysadmin","data","coding"];function LE(t){if(!t||t.length<8)return null;for(let e of Rg){let s=Ki[e];if(!s.pattern||s.pattern.test(t))return s}return Ki.coding}function or(){try{if(jn.existsSync(sr))return JSON.parse(jn.readFileSync(sr,"utf-8"))}catch{}return{}}function Cg(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=Ki[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:or()[t]||null}var Ag={explore:10,plan:10,implement:35,verify:8},Wc={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Og(){let t=or();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=dt();if(e()==="ollama")return Wc}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Wc:null}function IE(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let s=Og();return s?.[t]?s[t]:e?Cg(e):null}function jE(t){return or().phaseBudgets?.[t]||Ag[t]||20}function DE(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:Og()!==null}function qE(t){let e=Uc.dirname(sr);jn.existsSync(e)||jn.mkdirSync(e,{recursive:!0});let s=or(),o={...s,...t};!t.phases&&s.phases&&(o.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(o.phaseBudgets=s.phaseBudgets),jn.writeFileSync(sr,JSON.stringify(o,null,2));try{let n=Uc.join(e,".env"),r="";jn.existsSync(n)&&(r=jn.readFileSync(n,"utf-8"));let i=r.split(/\r?\n/),a=(l,c)=>{let u=i.findIndex(d=>d.startsWith(l+"="));u>=0?i[u]=`${l}=${c}`:i.push(`${l}=${c}`)};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)),jn.writeFileSync(n,i.filter(l=>l.trim()!=="").join(`
636
636
  `)+`
637
- `)}catch{}}Cg.exports={CATEGORIES:zi,DETECTION_ORDER:vg,detectCategory:OE,getModelForCategory:Eg,getModelForPhase:NE,getPhaseBudget:PE,isPhaseRoutingEnabled:ME,DEFAULT_PHASE_BUDGETS:Tg,BUILTIN_PHASE_DEFAULTS:qc,saveRoutingConfig:LE,loadRoutingConfig:or,ROUTING_CONFIG_PATH:sr}});var Pg=Z((qA,Ng)=>{"use strict";var ds=require("fs"),ir=require("path"),IE=require("os"),{detectCategory:jE}=rr(),no=ir.join(IE.homedir(),".nex-code","examples"),Fc=ir.join(__dirname,"..","examples");function Ag(t){try{let s=ds.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(`
637
+ `)}catch{}}Ng.exports={CATEGORIES:Ki,DETECTION_ORDER:Rg,detectCategory:LE,getModelForCategory:Cg,getModelForPhase:IE,getPhaseBudget:jE,isPhaseRoutingEnabled:DE,DEFAULT_PHASE_BUDGETS:Ag,BUILTIN_PHASE_DEFAULTS:Wc,saveRoutingConfig:qE,loadRoutingConfig:or,ROUTING_CONFIG_PATH:sr}});var Ig=Z((YA,Lg)=>{"use strict";var ds=require("fs"),ir=require("path"),FE=require("os"),{detectCategory:BE}=rr(),no=ir.join(FE.homedir(),".nex-code","examples"),Hc=ir.join(__dirname,"..","examples");function Pg(t){try{let s=ds.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(`
638
638
  A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],l=0;for(let u of i.split(`
639
639
  `))if(u.startsWith(" ")){for(;l>0;)a.push(""),l--;a.push(u.slice(2))}else if(u.trim()==="")a.length>0&&l++;else break;if(a.length===0)return null;let c=a.join(`
640
- `).trim();return{user:n,assistant:c}}catch{return null}}function Og(t){let e=`${t}.md`,s=ir.join(no,e);if(ds.existsSync(s)){let n=Ag(s);if(n)return n}let o=ir.join(Fc,e);return ds.existsSync(o)?Ag(o):null}function DE(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=jE(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:Og(e.id)}function qE(){let t=new Set;for(let e of[no,Fc])try{for(let s of ds.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function FE(t,e){ds.existsSync(no)||ds.mkdirSync(no,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
640
+ `).trim();return{user:n,assistant:c}}catch{return null}}function Mg(t){let e=`${t}.md`,s=ir.join(no,e);if(ds.existsSync(s)){let n=Pg(s);if(n)return n}let o=ir.join(Hc,e);return ds.existsSync(o)?Pg(o):null}function UE(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=BE(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:Mg(e.id)}function WE(){let t=new Set;for(let e of[no,Hc])try{for(let s of ds.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function HE(t,e){ds.existsSync(no)||ds.mkdirSync(no,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
641
641
 
642
642
  user: ${e.user}
643
643
 
@@ -645,14 +645,14 @@ A: |
645
645
  ${e.assistant.split(`
646
646
  `).map(o=>` ${o}`).join(`
647
647
  `)}
648
- `;ds.writeFileSync(ir.join(no,`${t}.md`),s,"utf-8")}Ng.exports={getFewShotForInput:DE,loadExampleForCategory:Og,listAvailableExamples:qE,savePrivateExample:FE,PRIVATE_EXAMPLES_DIR:no,BUNDLED_EXAMPLES_DIR:Fc}});var qg=Z((BA,Dg)=>{var Ot=require("fs"),so=require("path"),{C:FA}=it(),{atomicWrite:BE,withFileLockSync:UE}=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 Mg(){let t=so.join(process.cwd(),".nex","config.json");if(Ot.existsSync(t))try{let e=JSON.parse(Ot.readFileSync(t,"utf-8"));e.permissions&&(oo={...Ki,...e.permissions})}catch{}}function WE(){let t=so.join(process.cwd(),".nex"),e=so.join(t,"config.json");Ot.existsSync(t)||Ot.mkdirSync(t,{recursive:!0}),UE(e,()=>{let s={};if(Ot.existsSync(e))try{s=JSON.parse(Ot.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=oo,BE(e,JSON.stringify(s,null,2))})}function Lg(t){return oo[t]||"ask"}function HE(t,e){return["allow","ask","deny"].includes(e)?(oo[t]=e,!0):!1}function YE(t){return Lg(t)}function GE(){return Object.entries(oo).map(([t,e])=>({tool:t,mode:e}))}function zE(){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 Ig(){let t=so.join(process.cwd(),".nex","config.json");try{return Ot.existsSync(t)&&JSON.parse(Ot.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function KE(t){let e=so.join(process.cwd(),".nex"),s=so.join(e,"config.json");Ot.existsSync(e)||Ot.mkdirSync(e,{recursive:!0});let o={};try{Ot.existsSync(s)&&(o=JSON.parse(Ot.readFileSync(s,"utf-8")))}catch{o={}}o.teamPermissions=t,Ot.writeFileSync(s,JSON.stringify(o,null,2),"utf-8")}function jg(){let t=Ig();if(!t)return ar.admin;let e=t.role||"admin",s=ar[e]||ar.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function XE(t){let e=jg();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 VE(){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}))}Mg();Dg.exports={getPermission:Lg,setPermission:HE,checkPermission:YE,listPermissions:GE,loadPermissions:Mg,savePermissions:WE,resetPermissions:zE,DEFAULT_PERMISSIONS:Ki,PERMISSION_PRESETS:ar,loadPresetConfig:Ig,savePresetConfig:KE,getEffectivePreset:jg,isToolAllowed:XE,listPresets:VE}});var Ji=Z((WA,Hg)=>{var hs=require("fs"),Xi=require("path"),UA=require("readline"),{C:Me}=it(),Ae=null,Uc=!1,Wc=null,Fg=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 Bg(){let t=Vi();hs.existsSync(t)||hs.mkdirSync(t,{recursive:!0})}function JE(t,e=[]){return Ae={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()},Ae}function ZE(){return Ae}function QE(t){Uc=t}function eT(){return Uc}function tT(){return!Ae||Ae.status!=="draft"?!1:(Ae.status="approved",Ae.updatedAt=new Date().toISOString(),!0)}function nT(){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(s=>s.status==="done"||s.status==="skipped")&&(Ae.status="completed"),!0)}function sT(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(`
648
+ `;ds.writeFileSync(ir.join(no,`${t}.md`),s,"utf-8")}Lg.exports={getFewShotForInput:UE,loadExampleForCategory:Mg,listAvailableExamples:WE,savePrivateExample:HE,PRIVATE_EXAMPLES_DIR:no,BUNDLED_EXAMPLES_DIR:Hc}});var Ug=Z((zA,Bg)=>{var Ot=require("fs"),so=require("path"),{C:GA}=at(),{atomicWrite:YE,withFileLockSync:GE}=zn(),Xi={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={...Xi};function jg(){let t=so.join(process.cwd(),".nex","config.json");if(Ot.existsSync(t))try{let e=JSON.parse(Ot.readFileSync(t,"utf-8"));e.permissions&&(oo={...Xi,...e.permissions})}catch{}}function zE(){let t=so.join(process.cwd(),".nex"),e=so.join(t,"config.json");Ot.existsSync(t)||Ot.mkdirSync(t,{recursive:!0}),GE(e,()=>{let s={};if(Ot.existsSync(e))try{s=JSON.parse(Ot.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=oo,YE(e,JSON.stringify(s,null,2))})}function Dg(t){return oo[t]||"ask"}function KE(t,e){return["allow","ask","deny"].includes(e)?(oo[t]=e,!0):!1}function XE(t){return Dg(t)}function VE(){return Object.entries(oo).map(([t,e])=>({tool:t,mode:e}))}function JE(){oo={...Xi}}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 qg(){let t=so.join(process.cwd(),".nex","config.json");try{return Ot.existsSync(t)&&JSON.parse(Ot.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function ZE(t){let e=so.join(process.cwd(),".nex"),s=so.join(e,"config.json");Ot.existsSync(e)||Ot.mkdirSync(e,{recursive:!0});let o={};try{Ot.existsSync(s)&&(o=JSON.parse(Ot.readFileSync(s,"utf-8")))}catch{o={}}o.teamPermissions=t,Ot.writeFileSync(s,JSON.stringify(o,null,2),"utf-8")}function Fg(){let t=qg();if(!t)return ar.admin;let e=t.role||"admin",s=ar[e]||ar.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function QE(t){let e=Fg();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 eT(){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}))}jg();Bg.exports={getPermission:Dg,setPermission:KE,checkPermission:XE,listPermissions:VE,loadPermissions:jg,savePermissions:zE,resetPermissions:JE,DEFAULT_PERMISSIONS:Xi,PERMISSION_PRESETS:ar,loadPresetConfig:qg,savePresetConfig:ZE,getEffectivePreset:Fg,isToolAllowed:QE,listPresets:eT}});var Zi=Z((XA,zg)=>{var ps=require("fs"),Vi=require("path"),KA=require("readline"),{C:Me}=at(),Ae=null,Gc=!1,zc=null,Wg=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Ji(){return Vi.join(process.cwd(),".nex","plans")}function Hg(){let t=Ji();ps.existsSync(t)||ps.mkdirSync(t,{recursive:!0})}function tT(t,e=[]){return Ae={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()},Ae}function nT(){return Ae}function sT(t){Gc=t}function oT(){return Gc}function rT(){return!Ae||Ae.status!=="draft"?!1:(Ae.status="approved",Ae.updatedAt=new Date().toISOString(),!0)}function iT(){return!Ae||Ae.status!=="approved"?!1:(Ae.status="executing",!0)}function Yc(t,e){return!Ae||t<0||t>=Ae.steps.length?!1:(Ae.steps[t].status=e,Ae.updatedAt=new Date().toISOString(),Ae.steps.every(s=>s.status==="done"||s.status==="skipped")&&(Ae.status="completed"),!0)}function aT(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(`
649
649
  ${Me.bold}${Me.cyan}Plan: ${t.task}${Me.reset}`),s.push(`${Me.dim}Status: ${e[t.status]||t.status}${Me.reset}
650
650
  `);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(`
651
- `)}function oT(t){if(t||(t=Ae),!t)return null;Bg();let e=Xi.join(Vi(),`${t.name}.json`);return hs.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function rT(t){let e=Xi.join(Vi(),`${t}.json`);if(!hs.existsSync(e))return null;try{let s=JSON.parse(hs.readFileSync(e,"utf-8"));return Ae=s,s}catch{return null}}function iT(){Bg();let t=Vi(),e=hs.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(hs.readFileSync(Xi.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 aT(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 c=a[l][1];e[l].files=c.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function lT(t){Wc=t}function cT(){return Wc}function uT(){Ae=null,Uc=!1,Wc=null,pT()}function dT(){return`
651
+ `)}function lT(t){if(t||(t=Ae),!t)return null;Hg();let e=Vi.join(Ji(),`${t.name}.json`);return ps.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function cT(t){let e=Vi.join(Ji(),`${t}.json`);if(!ps.existsSync(e))return null;try{let s=JSON.parse(ps.readFileSync(e,"utf-8"));return Ae=s,s}catch{return null}}function uT(){Hg();let t=Ji(),e=ps.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(ps.readFileSync(Vi.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 dT(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 c=a[l][1];e[l].files=c.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function fT(t){zc=t}function pT(){return zc}function hT(){Ae=null,Gc=!1,zc=null,wT()}function mT(){return`
652
652
  PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
653
653
 
654
654
  # Allowed Tools (read-only)
655
- You may ONLY use these tools: ${[...Fg].join(", ")}
655
+ You may ONLY use these tools: ${[...Wg].join(", ")}
656
656
  Any other tool call will be blocked and returned with an error.
657
657
 
658
658
  # MANDATORY: Read Before You Plan
@@ -704,26 +704,26 @@ Bullet list of potential issues and mitigations.
704
704
  - Order steps by dependency (later steps may depend on earlier ones).
705
705
  - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
706
706
  - Do NOT make any file changes \u2014 your role is analysis and planning only.
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 fT(){!Ae||Ae.status!=="executing"||(fs>0&&Bc(fs-1,"done"),fs<Ae.steps.length&&(Bc(fs,"in_progress"),fs++))}function hT(){if(!Ae||Ae.status!=="executing"||Ae.steps.length===0)return null;let t=Math.min(fs,Ae.steps.length),e=Ae.steps.length,s=Math.max(0,t-1),o=Ae.steps[s]?.description||"";return{current:t,total:e,description:o}}function pT(){fs=0}var Ug=["interactive","semi-auto","autonomous"],Wg="interactive";function mT(t){return Ug.includes(t)?(Wg=t,!0):!1}function gT(){return Wg}Hg.exports={createPlan:JE,getActivePlan:ZE,setPlanMode:QE,isPlanMode:eT,approvePlan:tT,startExecution:nT,updateStep:Bc,formatPlan:sT,savePlan:oT,loadPlan:rT,listPlans:iT,clearPlan:uT,getPlanModePrompt:dT,setPlanContent:lT,getPlanContent:cT,extractStepsFromText:aT,advancePlanStep:fT,getPlanStepInfo:hT,PLAN_MODE_ALLOWED_TOOLS:Fg,setAutonomyLevel:mT,getAutonomyLevel:gT,AUTONOMY_LEVELS:Ug}});var ty=Z((HA,ey)=>{var{C:k}=it();function Yg(){return Math.max(10,(process.stdout.columns||80)-2)}function yT(t){if(!t)return"";let e=t.split(`
708
- `),s=[],o=!1,n="";for(let r of e){let i=Yg();if(r.trim().startsWith("```")){if(o)s.push(`${k.dim}${"\u2500".repeat(40)}${k.reset}`),o=!1,n="";else{o=!0,n=r.trim().substring(3).trim();let a=n?` ${n} `:"";s.push(`${k.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${k.reset}`)}continue}if(o){s.push(` ${Yc(r,n)}`);continue}if(r.startsWith("###### ")){s.push(`${k.bold}${k.cyan} ${Nt(r.substring(7))}${k.reset}`);continue}if(r.startsWith("##### ")){s.push(`${k.bold}${k.cyan} ${Nt(r.substring(6))}${k.reset}`);continue}if(r.startsWith("#### ")){s.push(`${k.bold}${k.cyan} ${Nt(r.substring(5))}${k.reset}`);continue}if(r.startsWith("### ")){s.push(`${k.bold}${k.cyan} ${Nt(r.substring(4))}${k.reset}`);continue}if(r.startsWith("## ")){s.push(`${k.bold}${k.cyan} ${Nt(r.substring(3))}${k.reset}`);continue}if(r.startsWith("# ")){s.push(`${k.bold}${k.cyan}${Nt(r.substring(2))}${k.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${k.cyan}\u2022${k.reset} ${ps(l)}`;s.push(ms(c,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let l=a[1],c=a[2],u=a[3],d=`${l}${k.cyan}${c}.${k.reset} ${ps(u)}`,f=l+" ".repeat(c.length+2);s.push(ms(d,i,f));continue}}s.push(ms(ps(r),i))}return s.join(`
709
- `)}function Nt(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?Gg(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?zg(t):e==="json"||e==="jsonc"?Kg(t):e==="python"||e==="py"?Xg(t):e==="go"||e==="golang"?Vg(t):e==="rust"||e==="rs"?Jg(t):e==="css"||e==="scss"||e==="less"?Zg(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Qg(t):t:""}function Gg(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,`${k.yellow}$1${k.reset}`),r=r.replace(e,`${k.magenta}$1${k.reset}`),r=r.replace(s,`${k.green}$&${k.reset}`),r=r.replace(o,`${k.dim}$1${k.reset}`),r}function zg(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(#.*$)/,r=t;return r=r.replace(s,`${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(n,`${k.dim}$1${k.reset}`),r}function Kg(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,`${k.cyan}$1${k.reset}:`),r=r.replace(s,`: ${k.green}$1${k.reset}`),r=r.replace(o,`: ${k.yellow}$1${k.reset}`),r=r.replace(n,`: ${k.magenta}$1${k.reset}`),r}function Xg(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,`${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(s,`${k.green}$&${k.reset}`),i=i.replace(o,`${k.dim}$1${k.reset}`),i}function Vg(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,`${k.yellow}$1${k.reset}`),i=i.replace(s,`${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(n,`${k.dim}$1${k.reset}`),i}function Jg(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,`${k.yellow}$1${k.reset}`),a=a.replace(s,`${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(n,`${k.dim}$1${k.reset}`),a}function Zg(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,`${k.yellow}$1${k.reset}`),a=a.replace(n,`${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 Qg(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,`${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(s,` ${k.cyan}$1${k.reset}=`),i=i.replace(r,`${k.yellow}$1${k.reset}`),i}function ms(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 c=i+1;if(c<l&&t[c]==="["){for(c++;c<l&&!/[a-zA-Z]/.test(t[c]);)c++;c<l&&c++}i=c;continue}if(t[i]===" "&&(r=i),n++,n>e&&r!==-1){o+=t.slice(a,r)+`
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 gT(){!Ae||Ae.status!=="executing"||(fs>0&&Yc(fs-1,"done"),fs<Ae.steps.length&&(Yc(fs,"in_progress"),fs++))}function yT(){if(!Ae||Ae.status!=="executing"||Ae.steps.length===0)return null;let t=Math.min(fs,Ae.steps.length),e=Ae.steps.length,s=Math.max(0,t-1),o=Ae.steps[s]?.description||"";return{current:t,total:e,description:o}}function wT(){fs=0}var Yg=["interactive","semi-auto","autonomous"],Gg="interactive";function bT(t){return Yg.includes(t)?(Gg=t,!0):!1}function $T(){return Gg}zg.exports={createPlan:tT,getActivePlan:nT,setPlanMode:sT,isPlanMode:oT,approvePlan:rT,startExecution:iT,updateStep:Yc,formatPlan:aT,savePlan:lT,loadPlan:cT,listPlans:uT,clearPlan:hT,getPlanModePrompt:mT,setPlanContent:fT,getPlanContent:pT,extractStepsFromText:dT,advancePlanStep:gT,getPlanStepInfo:yT,PLAN_MODE_ALLOWED_TOOLS:Wg,setAutonomyLevel:bT,getAutonomyLevel:$T,AUTONOMY_LEVELS:Yg}});var oy=Z((VA,sy)=>{var{C:k}=at();function Kg(){return Math.max(10,(process.stdout.columns||80)-2)}function _T(t){if(!t)return"";let e=t.split(`
708
+ `),s=[],o=!1,n="";for(let r of e){let i=Kg();if(r.trim().startsWith("```")){if(o)s.push(`${k.dim}${"\u2500".repeat(40)}${k.reset}`),o=!1,n="";else{o=!0,n=r.trim().substring(3).trim();let a=n?` ${n} `:"";s.push(`${k.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${k.reset}`)}continue}if(o){s.push(` ${Xc(r,n)}`);continue}if(r.startsWith("###### ")){s.push(`${k.bold}${k.cyan} ${Nt(r.substring(7))}${k.reset}`);continue}if(r.startsWith("##### ")){s.push(`${k.bold}${k.cyan} ${Nt(r.substring(6))}${k.reset}`);continue}if(r.startsWith("#### ")){s.push(`${k.bold}${k.cyan} ${Nt(r.substring(5))}${k.reset}`);continue}if(r.startsWith("### ")){s.push(`${k.bold}${k.cyan} ${Nt(r.substring(4))}${k.reset}`);continue}if(r.startsWith("## ")){s.push(`${k.bold}${k.cyan} ${Nt(r.substring(3))}${k.reset}`);continue}if(r.startsWith("# ")){s.push(`${k.bold}${k.cyan}${Nt(r.substring(2))}${k.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${k.cyan}\u2022${k.reset} ${hs(l)}`;s.push(ms(c,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let l=a[1],c=a[2],u=a[3],d=`${l}${k.cyan}${c}.${k.reset} ${hs(u)}`,f=l+" ".repeat(c.length+2);s.push(ms(d,i,f));continue}}s.push(ms(hs(r),i))}return s.join(`
709
+ `)}function Nt(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,`${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 Xc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Xg(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Vg(t):e==="json"||e==="jsonc"?Jg(t):e==="python"||e==="py"?Zg(t):e==="go"||e==="golang"?Qg(t):e==="rust"||e==="rs"?ey(t):e==="css"||e==="scss"||e==="less"?ty(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?ny(t):t:""}function Xg(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,`${k.yellow}$1${k.reset}`),r=r.replace(e,`${k.magenta}$1${k.reset}`),r=r.replace(s,`${k.green}$&${k.reset}`),r=r.replace(o,`${k.dim}$1${k.reset}`),r}function Vg(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(#.*$)/,r=t;return r=r.replace(s,`${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(n,`${k.dim}$1${k.reset}`),r}function Jg(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,`${k.cyan}$1${k.reset}:`),r=r.replace(s,`: ${k.green}$1${k.reset}`),r=r.replace(o,`: ${k.yellow}$1${k.reset}`),r=r.replace(n,`: ${k.magenta}$1${k.reset}`),r}function Zg(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,`${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(s,`${k.green}$&${k.reset}`),i=i.replace(o,`${k.dim}$1${k.reset}`),i}function Qg(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,`${k.yellow}$1${k.reset}`),i=i.replace(s,`${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(n,`${k.dim}$1${k.reset}`),i}function ey(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,`${k.yellow}$1${k.reset}`),a=a.replace(s,`${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(n,`${k.dim}$1${k.reset}`),a}function ty(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,`${k.yellow}$1${k.reset}`),a=a.replace(n,`${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 ny(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,`${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(s,` ${k.cyan}$1${k.reset}=`),i=i.replace(r,`${k.yellow}$1${k.reset}`),i}function ms(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 c=i+1;if(c<l&&t[c]==="["){for(c++;c<l&&!/[a-zA-Z]/.test(t[c]);)c++;c<l&&c++}i=c;continue}if(t[i]===" "&&(r=i),n++,n>e&&r!==-1){o+=t.slice(a,r)+`
710
710
  `+s,a=r+1,i=a,n=s.length,r=-1;continue}n>e&&r===-1&&(o+=t.slice(a,i)+`
711
- `+s,a=i,n=s.length+1),i++}return o+=t.slice(a),o}function wT(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let l=e.reduce((c,u)=>Math.max(c,(u[a]||"").length),0);return Math.max(i.length,l)}),o=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),n=t.map((i,a)=>` ${k.bold}${i.padEnd(s[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}${n}${k.dim}\u2502${k.reset}`),r.push(`${k.dim}\u251C${o}\u2524${k.reset}`);for(let i of e){let a=t.map((l,c)=>` ${(i[c]||"").padEnd(s[c])} `).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 $T(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?k.green:n>50?k.yellow:k.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${k.dim}${"\u2591".repeat(i)}${k.reset} ${n}% (${e}/${s})`}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(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?`${Kt().T.cyan}\u25CF${Kt().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(`
711
+ `+s,a=i,n=s.length+1),i++}return o+=t.slice(a),o}function xT(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let l=e.reduce((c,u)=>Math.max(c,(u[a]||"").length),0);return Math.max(i.length,l)}),o=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),n=t.map((i,a)=>` ${k.bold}${i.padEnd(s[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}${n}${k.dim}\u2502${k.reset}`),r.push(`${k.dim}\u251C${o}\u2524${k.reset}`);for(let i of e){let a=t.map((l,c)=>` ${(i[c]||"").padEnd(s[c])} `).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 kT(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?k.green:n>50?k.yellow:k.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${k.dim}${"\u2591".repeat(i)}${k.reset} ${n}% (${e}/${s})`}var Kc=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?`${Kt().T.cyan}\u25CF${Kt().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(`
713
713
  `))!==-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(`${k.dim}${"\u2500".repeat(40)}${k.reset}
714
- `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=Yg();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${k.dim}${"\u2500".repeat(40)}${k.reset}
714
+ `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=Kg();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${k.dim}${"\u2500".repeat(40)}${k.reset}
715
715
  `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let n=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${k.dim}${"\u2500".repeat(3)}${n}${"\u2500".repeat(Math.max(0,37-n.length))}${k.reset}
716
- `)}return}if(this.inCodeBlock){this._safeWrite(` ${Yc(e,this.codeBlockLang)}
716
+ `)}return}if(this.inCodeBlock){this._safeWrite(` ${Xc(e,this.codeBlockLang)}
717
717
  `);return}if(e.startsWith("###### ")){this._safeWrite(`${k.bold}${k.cyan} ${Nt(e.substring(7))}${k.reset}
718
718
  `);return}if(e.startsWith("##### ")){this._safeWrite(`${k.bold}${k.cyan} ${Nt(e.substring(6))}${k.reset}
719
719
  `);return}if(e.startsWith("#### ")){this._safeWrite(`${k.bold}${k.cyan} ${Nt(e.substring(5))}${k.reset}
720
720
  `);return}if(e.startsWith("### ")){this._safeWrite(`${k.bold}${k.cyan} ${Nt(e.substring(4))}${k.reset}
721
721
  `);return}if(e.startsWith("## ")){this._safeWrite(`${k.bold}${k.cyan} ${Nt(e.substring(3))}${k.reset}
722
722
  `);return}if(e.startsWith("# ")){this._safeWrite(`${k.bold}${k.cyan}${Nt(e.substring(2))}${k.reset}
723
- `);return}if(/^\s*[-*]\s/.test(e)){let n=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${n}${k.cyan}\u2022${k.reset} ${ps(r)}`,a=ms(i,s,n+" ");this._safeWrite(`${a}
724
- `);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}${k.cyan}${i}.${k.reset} ${ps(a)}`,c=r+" ".repeat(i.length+2),u=ms(l,s,c);this._safeWrite(`${u}
725
- `);return}}let o=ms(ps(e),s);this._safeWrite(`${o}
726
- `)}};ey.exports={renderMarkdown:yT,renderInline:ps,stripHeadingMarkers:Nt,highlightCode:Yc,highlightJS:Gg,highlightBash:zg,highlightJSON:Kg,highlightPython:Xg,highlightGo:Vg,highlightRust:Jg,highlightCSS:Zg,highlightHTML:Qg,renderTable:wT,renderProgress:$T,wrapAnsi:ms,StreamRenderer:Hc}});var iy=Z((YA,ry)=>{var{execSync:bT}=require("child_process"),Gc=require("path"),lr=require("fs"),zc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function ny(){return Gc.join(process.cwd(),".nex","hooks")}function _T(){return Gc.join(process.cwd(),".nex","config.json")}function sy(){let t=_T();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=[],s=ny(),o=Gc.join(s,t);lr.existsSync(o)&&e.push(o);let n=sy();if(n[t]){let r=Array.isArray(n[t])?n[t]:[n[t]];e.push(...r)}return e}function oy(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:bT(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 xT(t,e={}){let s=Zi(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=oy(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 kT(t){return Zi(t).length>0}function ST(){let t=[];for(let e of zc){let s=Zi(e);s.length>0&&t.push({event:e,commands:s})}return t}function vT(){let t=ny();return lr.existsSync(t)||lr.mkdirSync(t,{recursive:!0}),t}ry.exports={HOOK_EVENTS:zc,loadHookConfig:sy,getHooksForEvent:Zi,executeHook:oy,runHooks:xT,hasHooks:kT,listHooks:ST,initHooksDir:vT}});var Qi=Z((GA,ly)=>{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.
723
+ `);return}if(/^\s*[-*]\s/.test(e)){let n=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${n}${k.cyan}\u2022${k.reset} ${hs(r)}`,a=ms(i,s,n+" ");this._safeWrite(`${a}
724
+ `);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}${k.cyan}${i}.${k.reset} ${hs(a)}`,c=r+" ".repeat(i.length+2),u=ms(l,s,c);this._safeWrite(`${u}
725
+ `);return}}let o=ms(hs(e),s);this._safeWrite(`${o}
726
+ `)}};sy.exports={renderMarkdown:_T,renderInline:hs,stripHeadingMarkers:Nt,highlightCode:Xc,highlightJS:Xg,highlightBash:Vg,highlightJSON:Jg,highlightPython:Zg,highlightGo:Qg,highlightRust:ey,highlightCSS:ty,highlightHTML:ny,renderTable:xT,renderProgress:kT,wrapAnsi:ms,StreamRenderer:Kc}});var cy=Z((JA,ly)=>{var{execSync:ST}=require("child_process"),Vc=require("path"),lr=require("fs"),Jc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function ry(){return Vc.join(process.cwd(),".nex","hooks")}function vT(){return Vc.join(process.cwd(),".nex","config.json")}function iy(){let t=vT();if(!lr.existsSync(t))return{};try{return JSON.parse(lr.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Qi(t){if(!Jc.includes(t))return[];let e=[],s=ry(),o=Vc.join(s,t);lr.existsSync(o)&&e.push(o);let n=iy();if(n[t]){let r=Array.isArray(n[t])?n[t]:[n[t]];e.push(...r)}return e}function ay(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:ST(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 ET(t,e={}){let s=Qi(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=ay(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 TT(t){return Qi(t).length>0}function RT(){let t=[];for(let e of Jc){let s=Qi(e);s.length>0&&t.push({event:e,commands:s})}return t}function CT(){let t=ry();return lr.existsSync(t)||lr.mkdirSync(t,{recursive:!0}),t}ly.exports={HOOK_EVENTS:Jc,loadHookConfig:iy,getHooksForEvent:Qi,executeHook:ay,runHooks:ET,hasHooks:TT,listHooks:RT,initHooksDir:CT}});var ea=Z((ZA,dy)=>{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.
727
727
  Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
728
728
  You excel at sysadmin, frontend, and multi-step coding tasks.
729
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.
@@ -736,7 +736,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
736
736
  Prioritize decisive, targeted edits. Read only what you need, then fix.
737
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.
738
738
  Trust your reasoning. Use tools thoroughly when the task demands it.
739
- You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},ay={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function ET(t){let e=(t||"").toLowerCase(),s=null,o=0;for(let r of Object.keys(cr))e.startsWith(r)&&r.length>o&&(s=r,o=r.length);let n=s?{...cr[s]}:{...ay};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 TT(t){let e=(t||"").toLowerCase(),s=null,o=0;for(let n of Object.keys(cr))e.startsWith(n)&&n.length>o&&(s=n,o=n.length);return s&&cr[s].briefing||""}ly.exports={getModelProfile:ET,getModelBriefing:TT,PROFILES:cr,DEFAULTS:ay}});var io=Z((zA,cy)=>{var{fork:RT}=require("child_process"),CT=require("path"),AT=CT.join(__dirname,"background-worker.js"),gs=new Map,ro=new Map;function OT(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function NT(t){let e=OT(),s=RT(AT,[],{silent:!0,env:process.env,cwd:process.cwd()});return s.send({jobId:e,agentDef:t}),s.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}})}),s.on("exit",(o,n)=>{if(gs.has(e)){let r=n?`killed (${n})`:`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:s,agentDef:t,startedAt:Date.now()}),e}function Kc(t,e,s){gs.delete(t),ro.set(t,{jobId:t,agentDef:e,result:s,finishedAt:Date.now()})}function PT(){if(ro.size===0)return[];let t=[...ro.values()];return ro.clear(),t}function MT(){return gs.size>0||ro.size>0}function LT(){let t=gs.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function IT(){for(let[t,e]of gs){try{e.process.kill("SIGTERM")}catch{}gs.delete(t)}ro.clear()}cy.exports={createJob:NT,getCompletedJobs:PT,getPendingJobSummary:LT,hasPendingOrCompletedJobs:MT,cancelAllJobs:IT}});var Ry=Z((JA,Ty)=>{"use strict";var{callWithRetry:fy,runSubAgent:uy,clearAllLocks:jT}=Bi(),{parseModelSpec:hy,getActiveProviderName:KA,getActiveModelId:XA}=dt(),{detectCategory:DT,getModelForCategory:dy}=rr(),{MultiProgress:qT,C:me}=it(),{getModelBriefing:VA}=Qi(),py=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),ea=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),my="devstral-2:123b",gy="kimi-k2.5",yy=`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.`}},uy={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function AT(t){let e=(t||"").toLowerCase(),s=null,o=0;for(let r of Object.keys(cr))e.startsWith(r)&&r.length>o&&(s=r,o=r.length);let n=s?{...cr[s]}:{...uy};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 OT(t){let e=(t||"").toLowerCase(),s=null,o=0;for(let n of Object.keys(cr))e.startsWith(n)&&n.length>o&&(s=n,o=n.length);return s&&cr[s].briefing||""}dy.exports={getModelProfile:AT,getModelBriefing:OT,PROFILES:cr,DEFAULTS:uy}});var io=Z((QA,fy)=>{var{fork:NT}=require("child_process"),PT=require("path"),MT=PT.join(__dirname,"background-worker.js"),gs=new Map,ro=new Map;function LT(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function IT(t){let e=LT(),s=NT(MT,[],{silent:!0,env:process.env,cwd:process.cwd()});return s.send({jobId:e,agentDef:t}),s.on("message",o=>{o.type==="result"?Zc(e,t,o.payload):o.type==="error"&&Zc(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(gs.has(e)){let r=n?`killed (${n})`:`exit code ${o}`;Zc(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),gs.set(e,{process:s,agentDef:t,startedAt:Date.now()}),e}function Zc(t,e,s){gs.delete(t),ro.set(t,{jobId:t,agentDef:e,result:s,finishedAt:Date.now()})}function jT(){if(ro.size===0)return[];let t=[...ro.values()];return ro.clear(),t}function DT(){return gs.size>0||ro.size>0}function qT(){let t=gs.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function FT(){for(let[t,e]of gs){try{e.process.kill("SIGTERM")}catch{}gs.delete(t)}ro.clear()}fy.exports={createJob:IT,getCompletedJobs:jT,getPendingJobSummary:qT,hasPendingOrCompletedJobs:DT,cancelAllJobs:FT}});var Oy=Z((sO,Ay)=>{"use strict";var{callWithRetry:my,runSubAgent:py,clearAllLocks:BT}=Ui(),{parseModelSpec:gy,getActiveProviderName:eO,getActiveModelId:tO}=dt(),{detectCategory:UT,getModelForCategory:hy}=rr(),{MultiProgress:WT,C:me}=at(),{getModelBriefing:nO}=ea(),yy=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),ta=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),wy="devstral-2:123b",by="kimi-k2.5",$y=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
740
740
 
741
741
  RULES:
742
742
  - Output ONLY a JSON array, no markdown fences, no explanation.
@@ -751,7 +751,7 @@ RULES:
751
751
  - If the request is simple (single goal), return an array with exactly 1 item.
752
752
 
753
753
  USER REQUEST:
754
- {prompt}`,wy=`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}`,_y=`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.
755
755
 
756
756
  RULES:
757
757
  - Output ONLY a JSON object with these fields:
@@ -767,16 +767,16 @@ ORIGINAL REQUEST:
767
767
  {prompt}
768
768
 
769
769
  SUB-AGENT RESULTS:
770
- {results}`;async function $y(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 by(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 FT(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(c=>c.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),s.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),s.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:s.length>0?s.join(", "):"single goal"}}function 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 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:
771
- ${e.slice(0,200)}`)}async function _y(t,e,s={}){let o=s.maxSubTasks||ea,r=[{role:"system",content:yy.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=hy(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await fy(r,[],i)).content||"",c=Xc(l);if(!Array.isArray(c))throw new Error(`Decompose returned non-array: ${typeof c}`);let u=10,f=c.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,u):8,priority:typeof g.priority=="number"?g.priority:$+1})).filter(g=>g.task.length>0),h=f.reduce((g,$)=>g+$.estimatedCalls,0),m=ea*u;if(h>m){let{debugLog:g}=rl();g(`${Kt().T.yellow} \u26A0 Orchestrator: total estimated calls ${h} > ${m} \u2014 consider raising maxSubTasks${Kt().T.reset}`)}return f}async function xy(t,e,s){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((f,h)=>{let m=f.status==="done"?"SUCCESS":f.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${h+1} [${m}] ---
770
+ {results}`;async function xy(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 ky(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 HT(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(c=>c.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),s.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),s.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:s.length>0?s.join(", "):"single goal"}}function Qc(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:
771
+ ${e.slice(0,200)}`)}async function Sy(t,e,s={}){let o=s.maxSubTasks||ta,r=[{role:"system",content:$y.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=gy(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await my(r,[],i)).content||"",c=Qc(l);if(!Array.isArray(c))throw new Error(`Decompose returned non-array: ${typeof c}`);let u=10,f=c.slice(0,o).map((g,b)=>({id:g.id||`t${b+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,u):8,priority:typeof g.priority=="number"?g.priority:b+1})).filter(g=>g.task.length>0),p=f.reduce((g,b)=>g+b.estimatedCalls,0),m=ta*u;if(p>m){let{debugLog:g}=ll();g(`${Kt().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${m} \u2014 consider raising maxSubTasks${Kt().T.reset}`)}return f}async function vy(t,e,s){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((f,p)=>{let m=f.status==="done"?"SUCCESS":f.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${p+1} [${m}] ---
772
772
  Task: ${f.task}
773
773
  Result: ${f.result}
774
774
  Tools: ${(f.toolsUsed||[]).join(", ")||"none"}`}).join(`
775
775
 
776
- `),r=[{role:"system",content:wy.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let f=hy(s);f.provider&&(i.provider=f.provider),f.model&&(i.model=f.model)}let l=(await fy(r,[],i)).content||"",c=Xc(l),u={summary:String(c.summary||""),conflicts:Array.isArray(c.conflicts)?c.conflicts:[],commitMessage:String(c.commitMessage||""),filesChanged:Array.isArray(c.filesChanged)?c.filesChanged:[]},d=ky(u,t);return d&&(u.commitMessage="",u.commitSuppressedReason=d),u}function ky(t,e){let s=/\b(fail(?:ed|ure|s)?|did not pass|tests? (?:are )?failing|red|broken)\b/i,o=/\b(reported|claimed|said)\b.*\b(pass|fail)/i;for(let n of t.conflicts)if(typeof n=="string"){if(s.test(n))return"conflict mentions failure";if(o.test(n)&&/pass/i.test(n)&&/fail/i.test(n))return"agents disagree on pass/fail"}for(let n of e){if(n.status==="error"||n.status==="failed")return`agent reported ${n.status}`;let r=String(n.result||"");if(/\b(test(?:s)? fail|verification fail|build (?:error|fail))/i.test(r))return"agent result describes test/build failure"}return null}async function BT(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||gy,o=e.workerModel||my,n=e.maxParallel||py,r=e.maxSubTasks||ea,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
776
+ `),r=[{role:"system",content:_y.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let f=gy(s);f.provider&&(i.provider=f.provider),f.model&&(i.model=f.model)}let l=(await my(r,[],i)).content||"",c=Qc(l),u={summary:String(c.summary||""),conflicts:Array.isArray(c.conflicts)?c.conflicts:[],commitMessage:String(c.commitMessage||""),filesChanged:Array.isArray(c.filesChanged)?c.filesChanged:[]},d=Ey(u,t);return d&&(u.commitMessage="",u.commitSuppressedReason=d),u}function Ey(t,e){let s=/\b(fail(?:ed|ure|s)?|did not pass|tests? (?:are )?failing|red|broken)\b/i,o=/\b(reported|claimed|said)\b.*\b(pass|fail)/i;for(let n of t.conflicts)if(typeof n=="string"){if(s.test(n))return"conflict mentions failure";if(o.test(n)&&/pass/i.test(n)&&/fail/i.test(n))return"agents disagree on pass/fail"}for(let n of e){if(n.status==="error"||n.status==="failed")return`agent reported ${n.status}`;let r=String(n.result||"");if(/\b(test(?:s)? fail|verification fail|build (?:error|fail))/i.test(r))return"agent result describes test/build failure"}return null}async function YT(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||by,o=e.workerModel||wy,n=e.maxParallel||yy,r=e.maxSubTasks||ta,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
777
777
  ${me.bold}Orchestrator${me.reset} ${me.dim}model: ${s} | workers: ${o} | max parallel: ${n}${me.reset}
778
- `),i("decomposing"),console.log(`${me.dim}Phase 1: Decomposing prompt into sub-tasks...${me.reset}`);let l;try{l=await _y(t,s,{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 c=new Map;for(let q=0;q<l.length;q++)for(let Q of l[q].scope)Q&&!c.has(Q)&&c.set(Q,q);i("executing"),console.log(`${me.dim}Phase 2: Running ${l.length} sub-agents (max ${n} parallel)...${me.reset}
779
- `);let u=Date.now(),d=by(n),f={findings:[],_lock:!1},h=l.map(q=>{let Q=DT(q.task);return(Q?dy(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 qT(m);g.start();let $=`
778
+ `),i("decomposing"),console.log(`${me.dim}Phase 1: Decomposing prompt into sub-tasks...${me.reset}`);let l;try{l=await Sy(t,s,{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 c=new Map;for(let q=0;q<l.length;q++)for(let Q of l[q].scope)Q&&!c.has(Q)&&c.set(Q,q);i("executing"),console.log(`${me.dim}Phase 2: Running ${l.length} sub-agents (max ${n} parallel)...${me.reset}
779
+ `);let u=Date.now(),d=ky(n),f={findings:[],_lock:!1},p=l.map(q=>{let Q=UT(q.task);return(Q?hy(Q.id):null)||o}),m=l.map((q,Q)=>{let we=`Agent ${Q+1} [${p[Q]}]: `,ke=Math.max(20,60-we.length),qe=q.task.substring(0,ke)+(q.task.length>ke?"...":"");return we+qe}),g=new WT(m);g.start();let b=`
780
780
  You are a focused coding agent executing ONE specific sub-task.
781
781
  Your scope is limited to the files listed in your task definition.
782
782
 
@@ -801,24 +801,24 @@ RULES:
801
801
  - Start with symbol-aware reads inside your scope: locate the target function/class/module, then read the exact section instead of scanning broadly.
802
802
  - Before finishing, run the smallest relevant verification for your scope and report any residual risk explicitly.
803
803
  - 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.
804
- `,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:c,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(`
804
+ `,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:p,labels:m,progress:g,sharedContext:f,_fileOwnership:c,workerModel:o,WORKER_SYSTEM_PROMPT:b});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(`
805
805
  `),qe=[...c.entries()].filter(([,H])=>H===Q).map(([H])=>H),Ne=[...c.entries()].filter(([,H])=>H!==Q).map(([H])=>H),ve=[ke?`Prior agent findings:
806
806
  ${ke}
807
- `:"",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),_=Ey(q.task),M=h[Q],F=process.env.NEX_FALLBACK_MODEL||dy("agentic")||o,ee=0,K=await $y(async()=>{let H=ee>0;H&&(g.update(Q,"retry"),process.stderr.write(` ${me.dim}[Agent ${Q+1}] retrying after error...${me.reset}
808
- `)),ee++;let oe=H&&M!==F?F:M;return uy({task:q.task,type:_,context:ve.length>0?ve.join(`
809
- `):void 0,max_iterations:Math.min(q.estimatedCalls||10,15),model:oe,_skipLog:!0,_systemPrompt:$,_readOnlyFiles:Ne},{onUpdate:J=>{if(J&&J.type==="tool_call"&&process.stderr.isTTY){let Se=`Agent ${Q+1} [${oe}]`,Ts=J.tool||"...";g.labels[Q]=`${Se}: ${Ts}`}}})},1,2e3),C="";if(vy(_,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 oe=await uy({task:`Review the completed changes for: ${q.task}`,type:"review",context:YT(q,K,H),max_iterations:4,model:M,_skipLog:!0,_systemPrompt:$},{onUpdate:()=>{}},1);Sy(oe.result)?(C=`
807
+ `:"",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),_=Cy(q.task),M=p[Q],F=process.env.NEX_FALLBACK_MODEL||hy("agentic")||o,ee=0,K=await xy(async()=>{let H=ee>0;H&&(g.update(Q,"retry"),process.stderr.write(` ${me.dim}[Agent ${Q+1}] retrying after error...${me.reset}
808
+ `)),ee++;let oe=H&&M!==F?F:M;return py({task:q.task,type:_,context:ve.length>0?ve.join(`
809
+ `):void 0,max_iterations:Math.min(q.estimatedCalls||10,15),model:oe,_skipLog:!0,_systemPrompt:b,_readOnlyFiles:Ne},{onUpdate:J=>{if(J&&J.type==="tool_call"&&process.stderr.isTTY){let Se=`Agent ${Q+1} [${oe}]`,Ts=J.tool||"...";g.labels[Q]=`${Se}: ${Ts}`}}})},1,2e3),C="";if(Ry(_,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 oe=await py({task:`Review the completed changes for: ${q.task}`,type:"review",context:XT(q,K,H),max_iterations:4,model:M,_skipLog:!0,_systemPrompt:b},{onUpdate:()=>{}},1);Ty(oe.result)?(C=`
810
810
 
811
811
  Reviewer findings:
812
812
  ${oe.result}`,f.findings.push({agentId:`${q.id}-review`,summary:String(oe.result||"").slice(0,200),files:H})):oe.result&&(C=`
813
813
 
814
814
  Reviewer: ${oe.result}`)}catch(oe){C=`
815
815
 
816
- Reviewer note: review pass failed (${oe.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}),jT()}console.log("");let P=Math.round((Date.now()-u)/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 se;try{se=await xy(S,t,s)}catch(q){console.log(`${me.yellow}Synthesize failed: ${q.message} \u2014 using raw results.${me.reset}`),se={summary:S.map(Q=>Q.result).join(`
816
+ Reviewer note: review pass failed (${oe.message})`}}let pe=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:pe,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}),BT()}console.log("");let P=Math.round((Date.now()-u)/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 se;try{se=await vy(S,t,s)}catch(q){console.log(`${me.yellow}Synthesize failed: ${q.message} \u2014 using raw results.${me.reset}`),se={summary:S.map(Q=>Q.result).join(`
817
817
  `),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 re=[...de.values()].some(q=>q>1),le=f.findings.length>1&&re?` ${me.dim}(agents shared context)${me.reset}`:"";if(console.log(`
818
818
  ${me.bold}Summary:${me.reset} ${se.summary}${le}`),se.conflicts.length>0){console.log(`${me.yellow}Conflicts:${me.reset}`);for(let q of se.conflicts)console.log(` - ${q}`)}se.commitMessage?console.log(`${me.dim}Suggested commit: ${se.commitMessage}${me.reset}`):se.commitSuppressedReason&&console.log(`${me.yellow}No commit suggested:${me.reset} ${se.commitSuppressedReason}`);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}
819
- `),{results:S,synthesis:se,totalTokens:a}}var UT=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,WT=/\b(review|audit|verify|validate|inspect|critique)\b/i,HT=/\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 YT(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(`
820
- `)}function Sy(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function vy(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 Ey(t){if(!t)return"implement";let e=UT.test(t),s=WT.test(t);return HT.test(t)?"implement":s?"review":e?"explore":"implement"}Ty.exports={runOrchestrated:BT,decompose:_y,synthesize:xy,shouldSuppressCommit:ky,detectComplexPrompt:FT,extractJSON:Xc,createSemaphore:by,DECOMPOSE_PROMPT:yy,SYNTHESIZE_PROMPT:wy,DEFAULT_ORCHESTRATOR_MODEL:gy,DEFAULT_WORKER_MODEL:my,DEFAULT_MAX_PARALLEL:py,DEFAULT_MAX_SUBTASKS:ea,withRetry:$y,_classifyWorkerType:Ey,_hasMaterialReviewFindings:Sy,_shouldRunFollowUpReview:vy}});var Oc=Z((sO,a0)=>{var{C:p,Spinner:lo,TaskProgress:GT,formatToolCall:zT,formatToolSummary:cu,formatSectionHeader:ur,formatMilestone:KT,setActiveTaskProgress:ZA,getThinkingVerb:Vc,setActiveModelForSpinner:Cy}=it(),{debugLog:L,warnLog:QA}=rl(),{MilestoneTracker:XT}=uf(),{callStream:Ay}=dt(),{parseToolArgs:VT}=ei(),{executeTool:JT}=Ao(),{gatherProjectContext:ZT}=fg(),{fitToContext:QT,forceCompress:hn,getUsage:en,estimateTokens:eR,buildProgressSnapshot:tR}=dn(),{autoSave:nR,flushAutoSave:sR}=Gi(),{scoreMessages:oR,formatScore:rR,appendScoreHistory:iR}=Sg(),{detectCategory:aR,getModelForPhase:uu,getPhaseBudget:ys,isPhaseRoutingEnabled:lR}=rr();function Oe(t){nR(t),sR()}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 cR(t){if(!t||typeof t!="string")return!1;let e=t.trim();if(!e)return!1;let s=e.slice(-300);return s.includes("?")?/(?:would you like|do you want|should i|shall i|can you clarify|could you clarify|what would you like me to|which (?:one|option|area|approach)|how would you like me to)\b/i.test(s):!1}function uR(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(n=>n&&n.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let s=oR(t);if(!s)return;console.log(rR(s,p));try{let{_getSessionsDir:o}=Gi(),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}=ei(),n=Ka();iR(s.score,{version:n.version,model:o?o():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:dR}=Go(),{getDeploymentContextBlock:fR,probeUrlServer:hR,detectRuntimeDebugTarget:Oy}=Pc(),{getFewShotForInput:pR}=Pg(),{checkPermission:mR,setPermission:gR,savePermissions:yR}=qg(),{confirm:Yy,setAllowAlwaysHandler:wR,getAutoConfirm:ks}=vo(),{isPlanMode:_r,getPlanModePrompt:$R,PLAN_MODE_ALLOWED_TOOLS:Gy,setPlanContent:bR,extractStepsFromText:_R,createPlan:xR,getActivePlan:eO,startExecution:tO,advancePlanStep:kR,getPlanStepInfo:SR}=Ji(),{StreamRenderer:vR}=ty(),{runHooks:Ny}=iy(),{routeMCPCall:ER,getMCPToolDefinitions:TR}=kl(),{getSkillInstructions:RR,getSkillToolDefinitions:CR,routeSkillCall:AR,matchSkillTriggers:OR}=_l(),{trackUsage:Py,estimateTokens:My}=zr();function Ly(t){return!t||typeof t!="string"?0:typeof My=="function"?My(t):Math.ceil(t.length/4)}var{validateToolArgs:NR}=El(),{filterToolsForModel:Iy,getModelTier:PR,PROVIDER_DEFAULT_TIER:nO}=Io(),{getConfiguredProviders:MR,getActiveProviderName:co,getActiveModelId:nn,setActiveModel:Jc,MODEL_EQUIVALENTS:ya}=dt(),{getModelProfile:LR,getModelBriefing:IR}=Qi(),Be=require("fs"),Ge=require("path"),jR=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function DR(t){let e=KT(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
821
- `)}var jy=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,Dy=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,qR=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function FR(t){let e=[],s;for(jy.lastIndex=0;(s=jy.exec(t))!==null;){let o=s[1].trim(),n=o.startsWith("~")?o.replace("~",process.env.HOME||""):Ge.resolve(o);Be.existsSync(n)&&e.push({raw:o,abs:n})}return e}function zy(t){let e=[],s;for(Dy.lastIndex=0;(s=Dy.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]:BR(t);return{data:Buffer.from(s.data).toString("base64"),media_type:n}}catch{return null}}function BR(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=Ge.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&Be.existsSync(e)){let n=Be.readFileSync(e);if(n.length>100)return{data:n.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
819
+ `),{results:S,synthesis:se,totalTokens:a}}var GT=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,zT=/\b(review|audit|verify|validate|inspect|critique)\b/i,KT=/\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 XT(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(`
820
+ `)}function Ty(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function Ry(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 Cy(t){if(!t)return"implement";let e=GT.test(t),s=zT.test(t);return KT.test(t)?"implement":s?"review":e?"explore":"implement"}Ay.exports={runOrchestrated:YT,decompose:Sy,synthesize:vy,shouldSuppressCommit:Ey,detectComplexPrompt:HT,extractJSON:Qc,createSemaphore:ky,DECOMPOSE_PROMPT:$y,SYNTHESIZE_PROMPT:_y,DEFAULT_ORCHESTRATOR_MODEL:by,DEFAULT_WORKER_MODEL:wy,DEFAULT_MAX_PARALLEL:yy,DEFAULT_MAX_SUBTASKS:ta,withRetry:xy,_classifyWorkerType:Cy,_hasMaterialReviewFindings:Ty,_shouldRunFollowUpReview:Ry}});var Lc=Z((cO,uw)=>{var{C:h,Spinner:lo,TaskProgress:VT,formatToolCall:JT,formatToolSummary:pu,formatSectionHeader:ur,formatMilestone:ZT,setActiveTaskProgress:oO,getThinkingVerb:eu,setActiveModelForSpinner:Ny}=at(),{debugLog:L,warnLog:rO}=ll(),{MilestoneTracker:QT}=ff(),{callStream:Py}=dt(),{parseToolArgs:eR}=ti(),{executeTool:tR}=Ao(),{gatherProjectContext:nR}=mg(),{fitToContext:sR,forceCompress:hn,getUsage:en,estimateTokens:oR,buildProgressSnapshot:rR}=fn(),{autoSave:iR,flushAutoSave:aR}=zi(),{scoreMessages:lR,formatScore:cR,appendScoreHistory:uR}=Tg(),{detectCategory:dR,getModelForPhase:hu,getPhaseBudget:ys,isPhaseRoutingEnabled:fR}=rr();function Oe(t){iR(t),aR()}function na(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 pR(t){if(!t||typeof t!="string")return!1;let e=t.trim();if(!e)return!1;let s=e.slice(-300);return s.includes("?")?/(?:would you like|do you want|should i|shall i|can you clarify|could you clarify|what would you like me to|which (?:one|option|area|approach)|how would you like me to)\b/i.test(s):!1}function hR(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(n=>n&&n.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let s=lR(t);if(!s)return;console.log(cR(s,h));try{let{_getSessionsDir:o}=zi(),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}=ti(),n=Ja();uR(s.score,{version:n.version,model:o?o():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:mR}=Go(),{getDeploymentContextBlock:gR,probeUrlServer:yR,detectRuntimeDebugTarget:My}=jc(),{getFewShotForInput:wR}=Ig(),{checkPermission:bR,setPermission:$R,savePermissions:_R}=Ug(),{confirm:Ky,setAllowAlwaysHandler:xR,getAutoConfirm:ks}=vo(),{isPlanMode:_r,getPlanModePrompt:kR,PLAN_MODE_ALLOWED_TOOLS:Xy,setPlanContent:SR,extractStepsFromText:vR,createPlan:ER,getActivePlan:iO,startExecution:aO,advancePlanStep:TR,getPlanStepInfo:RR}=Zi(),{StreamRenderer:CR}=oy(),{runHooks:Ly}=cy(),{routeMCPCall:AR,getMCPToolDefinitions:OR}=El(),{getSkillInstructions:NR,getSkillToolDefinitions:PR,routeSkillCall:MR,matchSkillTriggers:LR}=Sl(),{trackUsage:Iy,estimateTokens:jy}=Kr();function Dy(t){return!t||typeof t!="string"?0:typeof jy=="function"?jy(t):Math.ceil(t.length/4)}var{validateToolArgs:IR}=Cl(),{filterToolsForModel:qy,getModelTier:jR,PROVIDER_DEFAULT_TIER:lO}=Io(),{getConfiguredProviders:DR,getActiveProviderName:co,getActiveModelId:nn,setActiveModel:tu,MODEL_EQUIVALENTS:wa}=dt(),{getModelProfile:qR,getModelBriefing:FR}=ea(),Be=require("fs"),Ge=require("path"),BR=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function UR(t){let e=ZT(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
821
+ `)}var Fy=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,By=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,WR=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function HR(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||""):Ge.resolve(o);Be.existsSync(n)&&e.push({raw:o,abs:n})}return e}function Vy(t){let e=[],s;for(By.lastIndex=0;(s=By.exec(t))!==null;)e.push(s[1].trim());return e}async function Jy(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]:YR(t);return{data:Buffer.from(s.data).toString("base64"),media_type:n}}catch{return null}}function YR(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 n=Be.readFileSync(e);if(n.length>100)return{data:n.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
822
822
  set imgData to the clipboard as \xABclass PNGf\xBB
823
823
  return "has_image"
824
824
  on error
@@ -829,55 +829,55 @@ end try`],{timeout:3e3});if(o.stdout&&o.stdout.toString().trim()==="has_image"){
829
829
  set fRef to open for access filePath with write permission
830
830
  write imgData to fRef
831
831
  close access fRef
832
- `;if(t("osascript",["-e",n],{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 qy(t){let e=Be.readFileSync(t),s=Ge.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 Vy(t){let e=FR(t),s=zy(t),o=qR.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}=qy(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}=qy(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(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+=`
832
+ `;if(t("osascript",["-e",n],{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 Uy(t){let e=Be.readFileSync(t),s=Ge.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 Qy(t){let e=HR(t),s=Vy(t),o=WR.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}=Uy(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}=Uy(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){L(`${h.yellow} \u26A0 Path resolution failed: ${a.message}${h.reset}`)}if(s.length>0){let i=await Promise.all(s.map(Jy));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+=`
833
833
  [Clipboard image attached: ${i.path}]`):r[0].text+=`
834
- [No image found in clipboard]`}return r.length>1?r:t})()}var UR=[/\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 Jy(t){return typeof t!="string"||!t?!1:UR.some(e=>e.test(t))}function WR(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 c=s.slice(l,l+3).join("").trim();c.length>30&&o.set(c,(o.get(c)||0)+1)}let n=0,r="";for(let[l,c]of o)c>n&&(n=c,r=l);if(n<3)return{text:t,truncated:!1,repeatCount:n};let i=`
834
+ [No image found in clipboard]`}return r.length>1?r:t})()}var GR=[/\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 ew(t){return typeof t!="string"||!t?!1:GR.some(e=>e.test(t))}function zR(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 c=s.slice(l,l+3).join("").trim();c.length>30&&o.set(c,(o.get(c)||0)+1)}let n=0,r="";for(let[l,c]of o)c>n&&(n=c,r=l);if(n<3)return{text:t,truncated:!1,repeatCount:n};let i=`
835
835
 
836
- [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,c=-1,u=0;for(;l<2;){let d=t.indexOf(r,u);if(d===-1)break;l++,c=d+r.length,u=d+1}a=c>0?t.slice(0,c)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:n}}function du(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
837
- `),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=`
836
+ [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,c=-1,u=0;for(;l<2;){let d=t.indexOf(r,u);if(d===-1)break;l++,c=d+r.length,u=d+1}a=c>0?t.slice(0,c)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:n}}function mu(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
837
+ `),o=new Map;for(let p of s){let m=p.trim();m.length>=20&&o.set(m,(o.get(m)||0)+1)}let n=0,r="";for(let[p,m]of o)m>n&&(n=m,r=p);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=`
838
838
 
839
- \u26A0 [Response truncated: repeated paragraph detected (${n}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let h=t.indexOf(r,d);if(h===-1)break;c++,u=h+r.length,d=h+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:n}}var Zc=null,Qc=null,eu=null;function ht(){if(Zc===null){let{TOOL_DEFINITIONS:t}=Ao();Zc=t}return Qc===null&&(Qc=CR()),eu===null&&(eu=TR()),[...Zc,...Qc,...eu]}var fu=50;function HR(t){Number.isFinite(t)&&t>0&&(fu=t)}var ra=()=>null;function YR(t){ra=t}var mr=null,hu=null,uo=null,fo="",ho=0,pu="",mu=0,ia=new Map,GR=1e4,zR=6e3,KR=/\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 XR(t){return!t||typeof t!="string"?t:t.replace(KR,(e,s)=>`${s}=***REDACTED***`)}var VR=7e3,JR=4e3;function ZR(t,e=null){let s=XR(t),o=eR(s),n=e==="read_file"?VR:GR,r=e==="read_file"?JR:zR;if(o>n)try{let{compressToolResult:i}=dn();return i(s,r)}catch{return s}return s}function Zy(t){try{let{getActiveModel:e}=dt(),s=e(),o=s?`${s.provider}:${s.id}`:"default";if(ia.has(o))return ia.get(o);let n=Iy(t);return ia.set(o,n),n}catch{return Iy(t)}}function QR(){ia.clear()}function e1(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 gr={hash:null,ts:0},t1=3e4;async function Qy(){if(gr.hash&&Date.now()-gr.ts<t1)return gr.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}=Go(),a=i();a&&n.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Be.existsSync(i)){let a=await t.stat(i);n.push(`brain:${a.mtimeMs}`)}}catch{}let r=n.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 n1=new Set(["spawn_agents"]),tu=10,nu=10,na=5,Fy=6e4,su=12e4,s1=process.env.NEX_STALE_AUTO_SWITCH!=="0";function o1(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{}}wR(t=>{gR(t,"allow"),yR(),console.log(`${p.green} \u2713 ${t}: always allow${p.reset}`)});async function r1(t){let e=t.function.name,s=VT(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){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.
839
+ \u26A0 [Response truncated: repeated paragraph detected (${n}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let p=t.indexOf(r,d);if(p===-1)break;c++,u=p+r.length,d=p+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:n}}var nu=null,su=null,ou=null;function pt(){if(nu===null){let{TOOL_DEFINITIONS:t}=Ao();nu=t}return su===null&&(su=PR()),ou===null&&(ou=OR()),[...nu,...su,...ou]}var gu=50;function KR(t){Number.isFinite(t)&&t>0&&(gu=t)}var ia=()=>null;function XR(t){ia=t}var mr=null,yu=null,uo=null,fo="",po=0,wu="",bu=0,aa=new Map,VR=1e4,JR=6e3,ZR=/\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 QR(t){return!t||typeof t!="string"?t:t.replace(ZR,(e,s)=>`${s}=***REDACTED***`)}var e1=7e3,t1=4e3;function n1(t,e=null){let s=QR(t),o=oR(s),n=e==="read_file"?e1:VR,r=e==="read_file"?t1:JR;if(o>n)try{let{compressToolResult:i}=fn();return i(s,r)}catch{return s}return s}function tw(t){try{let{getActiveModel:e}=dt(),s=e(),o=s?`${s.provider}:${s.id}`:"default";if(aa.has(o))return aa.get(o);let n=qy(t);return aa.set(o,n),n}catch{return qy(t)}}function s1(){aa.clear()}function o1(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 gr={hash:null,ts:0},r1=3e4;async function nw(){if(gr.hash&&Date.now()-gr.ts<r1)return gr.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}=Go(),a=i();a&&n.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Be.existsSync(i)){let a=await t.stat(i);n.push(`brain:${a.mtimeMs}`)}}catch{}let r=n.join("|");return gr={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function $u(){mr=null,yu=null,gr={hash:null,ts:0},uo=null}var i1=new Set(["spawn_agents"]),ru=10,iu=10,sa=5,Wy=6e4,au=12e4,a1=process.env.NEX_STALE_AUTO_SWITCH!=="0";function l1(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{}}xR(t=>{$R(t,"allow"),_R(),console.log(`${h.green} \u2713 ${t}: always allow${h.reset}`)});async function c1(t){let e=t.function.name,s=eR(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let d=pt().find(p=>p.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return L(`${h.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${h.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
840
840
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
841
841
 
842
842
  Expected JSON schema for "${e}":
843
843
  ${f}
844
844
 
845
- Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}if(s&&typeof s.path=="string")try{let u=require("os"),d=Ge.resolve(process.cwd(),s.path.replace(/^~/,u.homedir())),f=s.path;s.path=Ge.relative(process.cwd(),d)||".",Object.defineProperty(s,"_originalPath",{value:f,enumerable:!1})}catch(u){console.error("path resolution failed:",u.message)}let n=NR(e,s);if(!n.valid){L(`${p.yellow} \u26A0 ${e}: ${n.error.split(`
846
- `)[0]}${p.reset}`);let u=(Uy.get(e)||0)+1;Uy.set(e,u);let d=u>=2?`${n.error}
845
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}if(s&&typeof s.path=="string")try{let u=require("os"),d=Ge.resolve(process.cwd(),s.path.replace(/^~/,u.homedir())),f=s.path;s.path=Ge.relative(process.cwd(),d)||".",Object.defineProperty(s,"_originalPath",{value:f,enumerable:!1})}catch(u){console.error("path resolution failed:",u.message)}let n=IR(e,s);if(!n.valid){L(`${h.yellow} \u26A0 ${e}: ${n.error.split(`
846
+ `)[0]}${h.reset}`);let u=(Yy.get(e)||0)+1;Yy.set(e,u);let d=u>=2?`${n.error}
847
847
 
848
- [SYSTEM: This is argument error #${u} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`: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 u=Object.keys(s),d=Object.keys(n.corrected),f=u.filter(h=>!d.includes(h));f.length&&console.log(`${p.dim} \u2713 ${e}: corrected args (${f.join(", ")})${p.reset}`)}if(_r()&&!Gy.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(u=>u.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 c=mR(e);if(c==="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(c==="ask"){let u=` Allow ${e}?`;return e==="bash"&&r.command&&(u=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Yy(u,{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 i1(t,e,s={}){let o=await AR(t,e);if(o!==null)return o;let n=await ER(t,e);return n!==null?n:JT(t,e,s)}function a1(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(zT(t.fnName,t.args));let s=Ny("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 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 n=await i1(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)+`
848
+ [SYSTEM: This is argument error #${u} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`: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 u=Object.keys(s),d=Object.keys(n.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${h.dim} \u2713 ${e}: corrected args (${f.join(", ")})${h.reset}`)}if(_r()&&!Xy.has(e))return console.log(`${h.yellow} \u2717 ${e}: blocked in plan mode${h.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(u=>u.background===!0);if(ye&&Te==="plan"&&!i.has(e)&&!e.startsWith("skill_")&&!l)return qn++,$r=e,L(`${h.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${qn})${h.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(`${h.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${h.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 c=bR(e);if(c==="deny")return console.log(`${h.red} \u2717 ${e}: denied by permissions${h.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(c==="ask"){let u=` Allow ${e}?`;return e==="bash"&&r.command&&(u=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Ky(u,{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 u1(t,e,s={}){let o=await MR(t,e);if(o!==null)return o;let n=await AR(t,e);return n!==null?n:tR(t,e,s)}function d1(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 lu(t,e=!1){e||console.log(JT(t.fnName,t.args));let s=Ly("pre-tool",{tool_name:t.fnName}),o=s.results;if(s.blocked){let b=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${s.blockReason}`;e||console.log(`${h.yellow} [hook pre-tool] BLOCKED: ${s.blockReason}${h.reset}`);let x=pu(t.fnName,t.args,b,!0);return e||console.log(x),{msg:{role:"tool",content:b,tool_call_id:t.callId},summary:x}}if(!e&&o.length>0)for(let b of o)b.success?console.log(`${h.dim} [hook pre-tool] ${b.command} \u2192 ${b.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook pre-tool] ${b.command} \u2192 ERROR: ${b.error}${h.reset}`);wn?.onToolStart&&wn.onToolStart(t.fnName,t.args);let n=await u1(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)+`
849
849
  ...(truncated ${i.length-5e4} chars)`:i,l=a.split(`
850
- `)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=cu(t.fnName,t.args,a,c);e||console.log(u),yn?.onToolEnd&&yn.onToolEnd(t.fnName,u,!c);let f=Ny("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=ZR(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let $=t.args.command.trim();!/cat\s*>|<</.test($)&&/\bcat\s+\S/.test($)?m+=`
851
- 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+=`
852
- 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+=`
853
- HINT: use glob instead of bash find for file discovery \u2014 it is faster and the preferred tool (e.g. glob('**/*.jsx')).`)}return{msg:{role:"tool",content:r?[{type:"text",text:m},...r.map($=>({type:"image",media_type:$.media_type,data:$.base64}))]:m,tool_call_id:t.callId},summary:u}}var l1=[{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:s}of l1){let o=t.match(e);if(o){let n=(o[1]||"").trim();return n?`${s}: ${n}`:s}}return null}async function c1(t,e=!1,s={}){let o=new Array(t.length),n=[],r=[],i=null;if(e&&!s.skipSpinner){let l=t.filter(c=>c.canExecute);if(l.length>0){let c;if(l.length===1){let u=l[0],d=a1(u.fnName,u.args);c=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=l.map(d=>d.fnName).join(", ");c=`\u23FA ${l.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new lo(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await ou(t[l],e);o[l]=c,n.push(u)}else{let l=r.map(u=>ou(t[u],e)),c=await Promise.all(l);for(let u=0;u<r.length;u++)o[r[u]]=c[u].msg,n.push(c[u].summary)}r=[]}}for(let l=0;l<t.length;l++){let c=t[l];if(!c.canExecute){await a(),o[l]=c.errorResult,n.push(cu(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(n1.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await ou(c,e);o[l]=u,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 O=[],By=300,e0=900*1e3;function pn(t,e){let s=t.get(e);return s?Date.now()-s.ts>e0?(t.delete(e),0):s.count:0}function ws(t,e){let s=t.get(e),o=s&&Date.now()-s.ts<=e0?s.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function iu(t,e,s){t.set(e,{count:s,ts:Date.now()})}var Eu=new Map,t0=new Map,aa=new Map,xr=new Set,n0=new Map,la=new Map,kr=new Set,gn=new Map,En=new Map,Sr=new Map,Ft=new Map,Ss=new Map,Uy=new Map,wa=new Map,yu=new Map,Bt=0,yr=0,ca=0,wu="",ua=0,Pt=!1,sa=0,da=0,bs=-1,$u=!1,fa=0,ha=!1,Wt=0,Ht=!1,tn=0,Yt=0,ct=!1,St="",wr=0,jn=0,pa="",_s=0,xs=0,ma="",fr=0,Ut=!1,bu=!1,vr=new Map,Er=new Set,$r=null,au=!1,hr=0,Wy=!1,Te="plan",$a=0,ye=!1,Dn=0,br=null,sn=null,_u=null,xu=null,po=0,mo=0,go=0,yo=!1,wo=0,vs=null,Es=[],$s=new Set;function u1(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function Hy(t){let e=String(t||"");if(!e)return!1;let s=/(?:^|\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),n=/\b(create|write|add|make|build|refactor|update|change|edit)\b[\s\S]{0,160}\bfile\b/i.test(e);return s&&(o||n)}function d1(t){let e=String(t||"").trim();return e?/^(hi|hello|hey|yo)\b/i.test(e)||/\b(introduce yourself|who are you|what can you do|tell me about yourself)\b/i.test(e):!1}function ku(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function f1(t){let s=String(t||"").match(/(?:^|\s)((?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html))\b/gi);return s?[...new Set(s.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}
854
- `)):(wu=t,ua=1,L(`${e} \u26A0 ${t}${p.reset}`))}var ga=[];function h1(t){ga.push(t.trim())}function p1(){return ga.length===0?null:ga.splice(0,ga.length).join(`
855
- `)}function m1(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,s=e!==null?`
850
+ `)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=pu(t.fnName,t.args,a,c);e||console.log(u),wn?.onToolEnd&&wn.onToolEnd(t.fnName,u,!c);let f=Ly("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let b of f)b.success?console.log(`${h.dim} [hook post-tool] ${b.command} \u2192 ${b.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook post-tool] ${b.command} \u2192 ERROR: ${b.error}${h.reset}`);let m=n1(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let b=t.args.command.trim();!/cat\s*>|<</.test(b)&&/\bcat\s+\S/.test(b)?m+=`
851
+ 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(b)&&!/npm|yarn|pnpm|make|git\b/.test(b)?m+=`
852
+ HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(b)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(b)&&(m+=`
853
+ 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(b=>({type:"image",media_type:b.media_type,data:b.base64}))]:m,tool_call_id:t.callId},summary:u}}var f1=[{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 cu(t){for(let{re:e,label:s}of f1){let o=t.match(e);if(o){let n=(o[1]||"").trim();return n?`${s}: ${n}`:s}}return null}async function p1(t,e=!1,s={}){let o=new Array(t.length),n=[],r=[],i=null;if(e&&!s.skipSpinner){let l=t.filter(c=>c.canExecute);if(l.length>0){let c;if(l.length===1){let u=l[0],d=d1(u.fnName,u.args);c=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=l.map(d=>d.fnName).join(", ");c=`\u23FA ${l.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new lo(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await lu(t[l],e);o[l]=c,n.push(u)}else{let l=r.map(u=>lu(t[u],e)),c=await Promise.all(l);for(let u=0;u<r.length;u++)o[r[u]]=c[u].msg,n.push(c[u].summary)}r=[]}}for(let l=0;l<t.length;l++){let c=t[l];if(!c.canExecute){await a(),o[l]=c.errorResult,n.push(pu(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(i1.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await lu(c,e);o[l]=u,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 O=[],Hy=300,sw=900*1e3;function mn(t,e){let s=t.get(e);return s?Date.now()-s.ts>sw?(t.delete(e),0):s.count:0}function ws(t,e){let s=t.get(e),o=s&&Date.now()-s.ts<=sw?s.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function uu(t,e,s){t.set(e,{count:s,ts:Date.now()})}var Au=new Map,ow=new Map,la=new Map,xr=new Set,rw=new Map,ca=new Map,kr=new Set,yn=new Map,En=new Map,Sr=new Map,Ut=new Map,Ss=new Map,Yy=new Map,ba=new Map,_u=new Map,Wt=0,yr=0,ua=0,xu="",da=0,Pt=!1,oa=0,fa=0,$s=-1,ku=!1,pa=0,ha=!1,Yt=0,Gt=!1,tn=0,zt=0,ut=!1,St="",wr=0,Dn=0,ma="",_s=0,xs=0,ga="",fr=0,Ht=!1,Su=!1,vr=new Map,Er=new Set,br=null,du=!1,pr=0,Gy=!1,Te="plan",$a=0,ye=!1,qn=0,$r=null,sn=null,vu=null,Eu=null,ho=0,mo=0,go=0,yo=!1,wo=0,vs=null,Es=[],bs=new Set;function h1(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function zy(t){let e=String(t||"");if(!e)return!1;let s=/(?:^|\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),n=/\b(create|write|add|make|build|refactor|update|change|edit)\b[\s\S]{0,160}\bfile\b/i.test(e);return s&&(o||n)}function m1(t){let e=String(t||"").trim();return e?/^(hi|hello|hey|yo)\b/i.test(e)||/\b(introduce yourself|who are you|what can you do|tell me about yourself)\b/i.test(e):!1}function Tu(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function g1(t){let s=String(t||"").match(/(?:^|\s)((?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html))\b/gi);return s?[...new Set(s.map(o=>Tu(o)))]:[]}function ao(t,e){t===xu?(da++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${da})${h.reset}
854
+ `)):(xu=t,da=1,L(`${e} \u26A0 ${t}${h.reset}`))}var ya=[];function y1(t){ya.push(t.trim())}function w1(){return ya.length===0?null:ya.splice(0,ya.length).join(`
855
+ `)}function b1(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,s=e!==null?`
856
856
  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?`
857
857
  Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
858
858
  Job: ${t.jobId}
859
859
  Task: "${t.agentDef.task}"`+s+`
860
860
  Status: ${t.result.status||"done"}`+n+`
861
- Result: ${o}`}function oa(t,e){let{getCompletedJobs:s}=io(),o=s();for(let n of o){let r={role:"user",content:m1(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}
862
- `)}}function s0(t,e){let s=[],o=new Set([...e.keys(),...xr,...kr]);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(`
863
- `).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 g1(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 y1(){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=y1();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 w1(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(`
864
- `)}function $1(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 o0(t){let e=g1(t);if(e.length===0)return[];let{searchContentIndex:s}=an(),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 r0(t){let e=await o0(t);if(e.length===0)return"";let{getRelatedFiles:s,findSymbolReferences:o}=an(),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 c=await s(i.file,process.cwd(),3);c.length>0&&n.push(` Follow-up files: ${c.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}try{let c=await o(i.name,process.cwd(),{excludeFile:i.file,excludeLine:i.line,limit:2});c.length>0&&n.push(` Likely callers/usages: ${c.map(u=>`${u.file}:${u.line}`).join(", ")} (read these next if behavior depends on where ${i.name} is invoked)`)}catch{}}return`${n.join(`
861
+ Result: ${o}`}function ra(t,e){let{getCompletedJobs:s}=io(),o=s();for(let n of o){let r={role:"user",content:b1(n)};t.push(r),e.push(r);let i=n.result?.status||"done",a=i==="failed"?h.red+" \u2717":h.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${n.agentDef.task.slice(0,50)} \u2014 ${String(n.result?.result||"").slice(0,80)}${h.reset}
862
+ `)}}function iw(t,e){let s=[],o=new Set([...e.keys(),...xr,...kr]);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(`
863
+ `).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 $1(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 _1(){return Be.existsSync(Ge.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":Be.existsSync(Ge.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function gn(t){let e=_1();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 x1(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(`
864
+ `)}function k1(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 aw(t){let e=$1(t);if(e.length===0)return[];let{searchContentIndex:s}=ln(),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 lw(t){let e=await aw(t);if(e.length===0)return"";let{getRelatedFiles:s,findSymbolReferences:o}=ln(),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 c=await s(i.file,process.cwd(),3);c.length>0&&n.push(` Follow-up files: ${c.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}try{let c=await o(i.name,process.cwd(),{excludeFile:i.file,excludeLine:i.line,limit:2});c.length>0&&n.push(` Likely callers/usages: ${c.map(u=>`${u.file}:${u.line}`).join(", ")} (read these next if behavior depends on where ${i.name} is invoked)`)}catch{}}return`${n.join(`
865
865
  `)}
866
866
  Use these exact targeted reads before broader searching.
867
867
 
868
- `}async function ba(t){let{getFileIndex:e}=an(),{buildContentIndex:s,findSymbolReferences:o,getRelatedFiles:n}=an(),i=e().filter(c=>/^tests?\//.test(c)||/\.test\./.test(c)||/\.spec\./.test(c));if(i.length===0)return[];let a=new Set,l=await s(process.cwd());for(let c of t||[]){let u=String(c),d=Ge.basename(u).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(u,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?.[u]?.defs)?l.files[u].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:u,limit:8});for(let $ of g)if(i.includes($.file)&&a.add($.file),a.size>=4)return[...a]}catch{}}return[...a]}function b1(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)||Be.existsSync(Ge.join(process.cwd(),"vitest.config.ts"))||Be.existsSync(Ge.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${s}`):(/jest/.test(n)||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 ${s}`),(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,s,o){if(!ye)return null;let n=Te;Te=t,$a=0,sn=uu(t,vs),t==="verify"&&(mo=0,go=0,yo=!1,wo=0),Wt=0,Ht=!1,tn=0,Yt=0,Ss.clear(),wa.clear(),Eu.clear(),Sr.clear(),t==="implement"&&(Es=s0(e||"",gn));let r=Es.length>0?`
868
+ `}async function _a(t){let{getFileIndex:e}=ln(),{buildContentIndex:s,findSymbolReferences:o,getRelatedFiles:n}=ln(),i=e().filter(c=>/^tests?\//.test(c)||/\.test\./.test(c)||/\.spec\./.test(c));if(i.length===0)return[];let a=new Set,l=await s(process.cwd());for(let c of t||[]){let u=String(c),d=Ge.basename(u).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(u,process.cwd(),4);for(let g of m){let b=Ge.basename(g).replace(/\.[^.]+$/,"");if(!(b.length<3)){for(let x of i)if(x.includes(b)&&a.add(x),a.size>=4)return[...a]}}}catch{}let p=(Array.isArray(l.files?.[u]?.defs)?l.files[u].defs:[]).filter(m=>["function","class","export"].includes(m.type)).map(m=>m.name).filter((m,g,b)=>m&&b.indexOf(m)===g).slice(0,3);for(let m of p)try{let g=await o(m,process.cwd(),{excludeFile:u,limit:8});for(let b of g)if(i.includes(b.file)&&a.add(b.file),a.size>=4)return[...a]}catch{}}return[...a]}function S1(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)||Be.existsSync(Ge.join(process.cwd(),"vitest.config.ts"))||Be.existsSync(Ge.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${s}`):(/jest/.test(n)||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 ${s}`),(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 hr(t,e,s,o){if(!ye)return null;let n=Te;Te=t,$a=0,sn=hu(t,vs),t==="verify"&&(mo=0,go=0,yo=!1,wo=0),Yt=0,Gt=!1,tn=0,zt=0,Ss.clear(),ba.clear(),Au.clear(),Sr.clear(),t==="implement"&&(Es=iw(e||"",yn));let r=Es.length>0?`
869
869
 
870
870
  ACTION ITEMS (execute these in order, do NOT re-read these files):
871
871
  `+Es.map((l,c)=>`${c+1}. ${l.file} \u2014 ${l.action}`).join(`
872
- `):"",i=await r0(t==="verify"?o:e||o||""),a;if(t==="implement")_u=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
873
- ${_u}
872
+ `):"",i=await lw(t==="verify"?o:e||o||""),a;if(t==="implement")vu=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
873
+ ${vu}
874
874
 
875
- ${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=s?[...s].join(", "):"none",c=await Tu(s),u=await ba(s),d=c.length>0?`Suggested checks (run the narrowest ones that fit the change):
876
- ${c.map((h,m)=>`${m+1}. ${h}`).join(`
875
+ ${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){Eu=e?.slice(0,500)||"";let l=s?[...s].join(", "):"none",c=await Ou(s),u=await _a(s),d=c.length>0?`Suggested checks (run the narrowest ones that fit the change):
876
+ ${c.map((p,m)=>`${m+1}. ${p}`).join(`
877
877
  `)}
878
878
 
879
879
  `:"",f=u.length>0?`Likely related tests:
880
- ${u.map((h,m)=>`${m+1}. ${h}`).join(`
880
+ ${u.map((p,m)=>`${m+1}. ${p}`).join(`
881
881
  `)}
882
882
  Prefer these before broader suites when a targeted run is possible.
883
883
 
@@ -889,24 +889,24 @@ Prefer these before broader suites when a targeted run is possible.
889
889
  Report PASS (all good) or FAIL (list specific issues).
890
890
 
891
891
  Files modified: ${l}
892
- ${i}${d}${f}Summary: ${xu}`}return L(`${p.cyan} \u21B3 Phase transition: ${n} \u2192 ${t} (model: ${sn||"default"})${p.reset}`),a?{role:"user",content:a}:null}async function Tu(t){let e=[],o=[...t||[]].map(l=>String(l).toLowerCase()),n={};try{let l=Ge.join(process.cwd(),"package.json");if(Be.existsSync(l)){n=JSON.parse(Be.readFileSync(l,"utf-8")).scripts||{};let u=[["test",mn("test")],["lint",mn("lint")],["typecheck",mn("typecheck")],["check",mn("check")],["build",mn("build")]];for(let[d,f]of u)n[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(...b1(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(mn("typecheck"))&&e.push(mn("typecheck")),a&&!e.includes(mn("lint"))&&e.push(mn("lint")),[...new Set(e)].slice(0,4)}function _1(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(Ru())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 x1(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,o=Ru(),n=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
892
+ ${i}${d}${f}Summary: ${Eu}`}return L(`${h.cyan} \u21B3 Phase transition: ${n} \u2192 ${t} (model: ${sn||"default"})${h.reset}`),a?{role:"user",content:a}:null}async function Ou(t){let e=[],o=[...t||[]].map(l=>String(l).toLowerCase()),n={};try{let l=Ge.join(process.cwd(),"package.json");if(Be.existsSync(l)){n=JSON.parse(Be.readFileSync(l,"utf-8")).scripts||{};let u=[["test",gn("test")],["lint",gn("lint")],["typecheck",gn("typecheck")],["check",gn("check")],["build",gn("build")]];for(let[d,f]of u)n[d]&&e.push(f)}}catch{}e.length===0&&(Be.existsSync(Ge.join(process.cwd(),"package.json"))&&e.push(gn("test")),(Be.existsSync(Ge.join(process.cwd(),"pytest.ini"))||Be.existsSync(Ge.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await _a(t);e.unshift(...S1(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(gn("typecheck"))&&e.push(gn("typecheck")),a&&!e.includes(gn("lint"))&&e.push(gn("lint")),[...new Set(e)].slice(0,4)}function v1(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(Nu())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 E1(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,o=Nu(),n=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
893
893
  `];o?r.push("RESPONSE LANGUAGE: This project requires English. Always respond in English, even if the user writes in another language."):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.`):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=s||"English";return r.push(`COMMIT MESSAGES: Write all git commit messages in ${a}.`),n&&r.push(`
894
894
  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(`
895
895
  `)+`
896
896
 
897
- `}function k1(t){let e=_1(t);return Ru()?`# Current Turn Language (CRITICAL \u2014 enforce strictly)
897
+ `}function T1(t){let e=v1(t);return Nu()?`# Current Turn Language (CRITICAL \u2014 enforce strictly)
898
898
  This repository is English-only. You MUST answer this turn in English, even if the user's message is written in German or any other language. Treat non-English input as content to answer, not as a language-switch instruction. Do NOT switch to another language because of the user's wording, repository files, prior conversation, examples, or project instructions.
899
899
 
900
900
  `:`# Current Turn Language (CRITICAL \u2014 enforce strictly)
901
901
  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.
902
902
 
903
- `}function S1(){if(uo!==null)return uo;try{let e=MR().flatMap(n=>n.models.map(r=>({spec:`${n.name}:${r.id}`,tier:PR(r.id,n.name),name:r.name})));if(e.length<2)return uo="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
903
+ `}function R1(){if(uo!==null)return uo;try{let e=DR().flatMap(n=>n.models.map(r=>({spec:`${n.name}:${r.id}`,tier:jR(r.id,n.name),name:r.name})));if(e.length<2)return uo="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
904
904
  # Sub-Agent Model Routing
905
905
 
906
906
  `;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 |
907
907
  |---|---|---|
908
908
  `;for(let n of e)o+=`| ${n.spec} | ${n.tier} | ${s[n.tier]||n.tier} |
909
- `;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 v1(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 Qy()+":"+nn();if(mr!==null&&t===hu)return mr;let e=await ZT(process.cwd()),s=dR(),o=RR(),n=_r()?$R():"",r=x1(),i=fR(),a=IR(nn());return mr=`${a?`## Model Briefing
909
+ `;return uo=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),uo="",""}}var Ru="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function C1(t){let e=t.indexOf(Ru);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Ru.length).trimStart()}}async function Cu(){let t=await nw()+":"+nn();if(mr!==null&&t===yu)return mr;let e=await nR(process.cwd()),s=mR(),o=NR(),n=_r()?kR():"",r=E1(),i=gR(),a=FR(nn());return mr=`${a?`## Model Briefing
910
910
  ${a}
911
911
 
912
912
  ---
@@ -1167,7 +1167,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
1167
1167
  - Instead: use bash with inline node -e '...' for quick one-off checks.
1168
1168
  - If the test is worth keeping, write it to tests/ with a proper name.
1169
1169
  - Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
1170
- ${S1()}
1170
+ ${R1()}
1171
1171
 
1172
1172
  # Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
1173
1173
 
@@ -1359,91 +1359,91 @@ class ErrorBoundary extends React.Component {
1359
1359
  - Use migrations for schema changes, never manual ALTER TABLE
1360
1360
  - Add database-level constraints (unique, foreign key, check) not just app-level
1361
1361
 
1362
- `,hu=t,mr}function i0(){Eu.clear(),t0.clear(),aa.clear(),xr.clear(),n0.clear(),la.clear(),kr.clear(),gn.clear(),En.clear(),Sr.clear(),Ft.clear(),Ss.clear(),wa.clear(),yu.clear(),Bt=0,yr=0,ca=0,Pt=!1,da=0,bs=-1,$u=!1,fa=0,ha=!1,Wt=0,Ht=!1,tn=0,Yt=0,ct=!1,St="",wr=0,pa="",_s=0,ma="",xs=0,Ut=!1,bu=!1,Te="plan",$a=0,ye=!1,sn=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 E1(){O=[],$r=null,fo="",ho=0,pu="",mu=0,i0();try{let{resetCompactionFailures:t}=cc();t()}catch{}try{let{cancelAllJobs:t}=io();t()}catch{}}function T1(){O.length>By&&O.splice(0,O.length-By)}function Ru(){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 lu(t,e,s,o=1500){return!t||!e?!1:t===e&&Date.now()-s<o}function R1(){return O.length}function C1(){return O}function A1(t){O=t}async function O1(){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(`
1363
- `):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let c=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=Ge.join(s,"package.json");if(e.existsSync(u))try{let d=JSON.parse(e.readFileSync(u,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let h=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";c+=`
1364
- \u{1F4E6} ${h}${m}`}}catch{}return c}function N1(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,s,o,n,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((c,u)=>c+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,l=0;if(n){let c=Date.now()-n;l=Math.round(c/1e3),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1365
- ${p.dim} ${a}${p.reset}`),l>=30&&process.stdout.isTTY){let c=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;N1(c)}if(Er.size>0&&vr.size>0)for(let c of Er){let u=vr.get(c);u&&console.log(`${p.dim} \u2714 task #${c} auto-matched: ${u.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 P1(){if(!process.stdout.isTTY)return{action:"quit"};let t=co(),e=nn(),s=ya.fast?.[t],o=ya.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,c=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,l.removeListener("data",d),l.setRawMode(c||!1),l.pause();let h=f.toLowerCase().trim();if(process.stdout.write(`${h}
1366
- `),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 M1(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 L1(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 I1(t,e=null,s={}){let o=LR(nn());Fy=o.staleWarn,su=o.staleAbort,yn=e;let n=t;if($r&&typeof t=="string"&&(n=`${$r}
1362
+ `,yu=t,mr}function cw(){Au.clear(),ow.clear(),la.clear(),xr.clear(),rw.clear(),ca.clear(),kr.clear(),yn.clear(),En.clear(),Sr.clear(),Ut.clear(),Ss.clear(),ba.clear(),_u.clear(),Wt=0,yr=0,ua=0,Pt=!1,fa=0,$s=-1,ku=!1,pa=0,ha=!1,Yt=0,Gt=!1,tn=0,zt=0,ut=!1,St="",wr=0,ma="",_s=0,ga="",xs=0,Ht=!1,Su=!1,Te="plan",$a=0,ye=!1,sn=null,vu=null,Eu=null,Es=[],ho=0,mo=0,go=0,yo=!1,wo=0,qn=0,vs=null,vr.clear(),Er.clear(),xu="",da=0}function A1(){O=[],br=null,fo="",po=0,wu="",bu=0,cw();try{let{resetCompactionFailures:t}=pc();t()}catch{}try{let{cancelAllJobs:t}=io();t()}catch{}}function O1(){O.length>Hy&&O.splice(0,O.length-Hy)}function Nu(){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 fu(t,e,s,o=1500){return!t||!e?!1:t===e&&Date.now()-s<o}function N1(){return O.length}function P1(){return O}function M1(t){O=t}async function L1(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),o=(d,f)=>new Promise(p=>{t(d,f,{cwd:s,timeout:3e3},(m,g)=>{p(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(`
1363
+ `):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let c=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=Ge.join(s,"package.json");if(e.existsSync(u))try{let d=JSON.parse(e.readFileSync(u,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let p=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";c+=`
1364
+ \u{1F4E6} ${p}${m}`}}catch{}return c}function I1(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,s,o,n,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((c,u)=>c+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,l=0;if(n){let c=Date.now()-n;l=Math.round(c/1e3),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1365
+ ${h.dim} ${a}${h.reset}`),l>=30&&process.stdout.isTTY){let c=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;I1(c)}if(Er.size>0&&vr.size>0)for(let c of Er){let u=vr.get(c);u&&console.log(`${h.dim} \u2714 task #${c} auto-matched: ${u.slice(0,60)}${h.reset}`)}s.size>0?console.log(`${h.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${h.reset}`):!r&&o.size>=5&&s.size===0&&t>=3?console.log(`${h.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${h.reset}`):o.size>0&&t>=2&&console.log(`${h.dim} \u{1F4A1} /save \xB7 /clear${h.reset}`)}async function j1(){if(!process.stdout.isTTY)return{action:"quit"};let t=co(),e=nn(),s=wa.fast?.[t],o=wa.strong?.[t],n=s&&s!==e,r=o&&o!==e&&o!==s,i=[];i.push({key:"r",label:`Retry with current model ${h.dim}(${e})${h.reset}`}),n&&i.push({key:"f",label:`Switch to ${h.bold}${s}${h.reset} ${h.dim}\u2014 fast, low latency${h.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${h.bold}${o}${h.reset} ${h.dim}\u2014 reliable tool-calling, medium speed${h.reset}`,model:o}),i.push({key:"q",label:`${h.dim}Quit${h.reset}`}),console.log(),console.log(`${h.yellow} Stream stale \u2014 all retries exhausted.${h.reset} What would you like to do?`);for(let a of i)console.log(` ${h.cyan}[${a.key}]${h.reset} ${a.label}`);return process.stdout.write(` ${h.yellow}> ${h.reset}`),new Promise(a=>{let l=process.stdin,c=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,l.removeListener("data",d),l.setRawMode(c||!1),l.pause();let p=f.toLowerCase().trim();if(process.stdout.write(`${p}
1366
+ `),f==="")return a({action:"quit"});let m=i.find(g=>g.key===p);!m||m.key==="q"||!m.model&&m.key!=="r"?a({action:"quit"}):m.key==="r"?a({action:"retry"}):a({action:"switch",model:m.model,provider:t})};l.on("data",d)})}function D1(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 q1(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 wn=null;async function F1(t,e=null,s={}){let o=qR(nn());Wy=o.staleWarn,au=o.staleAbort,wn=e;let n=t;if(br&&typeof t=="string"&&(n=`${br}
1367
1367
 
1368
- ${t}`,$r=null),typeof n=="string"){let _e=M1(n),ge=L1(n);(_e.length>0||ge.length>0)&&(n+=`
1368
+ ${t}`,br=null),typeof n=="string"){let _e=D1(n),ge=q1(n);(_e.length>0||ge.length>0)&&(n+=`
1369
1369
 
1370
1370
  [System Note for Assistant: To resolve this task faster, consider these hints:
1371
1371
  `,_e.length>0&&(n+=`- The user mentioned URLs containing the paths/folders: ${_e.join(", ")}. Prioritize searching these folder names using glob or grep first.
1372
1372
  `),ge.length>0&&ge.forEach(Re=>{n+=`- ${Re}
1373
- `}),n+="Always prefer parallel search execution if unsure.]")}typeof n=="string"&&Jy(n)&&(n+=`
1373
+ `}),n+="Always prefer parallel search execution if unsure.]")}typeof n=="string"&&ew(n)&&(n+=`
1374
1374
 
1375
- [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?Oy(t):null,i=Vy(n);i&&typeof i.then=="function"&&(i=await i),O.push({role:"user",content:i}),T1();let a=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",l=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:_e,runOrchestrated:ge}=Ry(),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:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});if(Ke&&Ke.synthesis){let rt=Ke.synthesis.summary||"",Rn=Ke.synthesis.filesChanged?.length?`
1375
+ [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?My(t):null,i=Qy(n);i&&typeof i.then=="function"&&(i=await i),O.push({role:"user",content:i}),O1();let a=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",l=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:_e,runOrchestrated:ge}=Oy(),Re=_e(typeof t=="string"?t:"");if(a&&Re.isComplex&&Re.estimatedGoals>=l){console.log(`${h.yellow}\u26A1 Auto-orchestrate: ${Re.estimatedGoals} goals \u2192 parallel agents${h.reset}`);let Ke=await ge(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});if(Ke&&Ke.synthesis){let it=Ke.synthesis.summary||"",Rn=Ke.synthesis.filesChanged?.length?`
1376
1376
 
1377
- Files changed: ${Ke.synthesis.filesChanged.join(", ")}`:"",st=Ke.synthesis.conflicts?.length?`
1377
+ Files changed: ${Ke.synthesis.filesChanged.join(", ")}`:"",ot=Ke.synthesis.conflicts?.length?`
1378
1378
 
1379
1379
  Conflicts:
1380
- ${Ke.synthesis.conflicts.map(Mt=>`- ${Mt}`).join(`
1381
- `)}`:"";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:c}=ac(),u=null,d=0;c((_e,ge)=>{_e==="create"?(u&&u.stop(),u=new GT(ge.name,ge.tasks),u.setStats({tokens:d}),u.start()):_e==="update"&&u?u.updateTask(ge.id,ge.status):_e==="clear"&&u&&(u.stop(),u=null)});let f=await vu(),h=f;try{let{getBrainContext:_e}=$c(),ge=await _e(t);ge&&(h=f+`
1380
+ ${Ke.synthesis.conflicts.map(Lt=>`- ${Lt}`).join(`
1381
+ `)}`:"";O.push({role:"assistant",content:it+Rn+ot}),Oe(O),dr(O)}return Ke}Re.isComplex&&process.stdout.isTTY&&console.log(`${h.dim}Hint: ~${Re.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${h.reset}`)}catch{}let{setOnChange:c}=dc(),u=null,d=0;c((_e,ge)=>{_e==="create"?(u&&u.stop(),u=new VT(ge.name,ge.tasks),u.setStats({tokens:d}),u.start()):_e==="update"&&u?u.updateTask(ge.id,ge.status):_e==="clear"&&u&&(u.stop(),u=null)});let f=await Cu(),p=f;try{let{getBrainContext:_e}=kc(),ge=await _e(t);ge&&(p=f+`
1382
1382
  `+ge+`
1383
- `)}catch(_e){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",_e.message)}let g=OR(typeof t=="string"?t:"");if(g.length>0){let _e=g.map(ge=>`[Triggered: ${ge.name}]
1383
+ `)}catch(_e){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",_e.message)}let g=LR(typeof t=="string"?t:"");if(g.length>0){let _e=g.map(ge=>`[Triggered: ${ge.name}]
1384
1384
  ${ge.instructions}`).join(`
1385
- `);h+=`
1385
+ `);p+=`
1386
1386
  `+_e+`
1387
- `}h+=`
1388
- `+k1(t);let $=[{role:"system",content:h},...O];Cy(nn());let x=new lo(Vc());x.start();let E=O.length===1,N=E?O1().catch(()=>null):Promise.resolve(null),v=E?hR(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),S=ht(),[{messages:P,compressed:ne,compacted:se,tokensRemoved:ce},de,re]=await Promise.all([QT($,S),N,v]),le=en($,S);if(x.stop(),de&&console.log(`${p.dim}${de}${p.reset}`),se)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(re&&E&&(T=[T[0],{role:"user",content:`[Server probe at task start]
1387
+ `}p+=`
1388
+ `+T1(t);let b=[{role:"system",content:p},...O];Ny(nn());let x=new lo(eu());x.start();let E=O.length===1,N=E?L1().catch(()=>null):Promise.resolve(null),v=E?yR(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),S=pt(),[{messages:P,compressed:ne,compacted:se,tokensRemoved:ce},de,re]=await Promise.all([sR(b,S),N,v]),le=en(b,S);if(x.stop(),de&&console.log(`${h.dim}${de}${h.reset}`),se)console.log(`${h.dim} [context compacted \u2014 summary (~${ce} tokens freed)]${h.reset}`);else if(ne){let _e=le.limit>0?Math.round(ce/le.limit*100):0;L(`${h.dim} [context compressed \u2014 ~${ce} tokens freed (${_e}%)]${h.reset}`)}le.percentage>85&&L(`${h.yellow} \u26A0 Context ${Math.round(le.percentage)}% used (${Math.round(100-le.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${h.reset}`);let T=P;if(re&&E&&(T=[T[0],{role:"user",content:`[Server probe at task start]
1389
1389
  ${re}`},{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]
1390
1390
  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]
1391
- 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=pR(typeof t=="string"?t:"");_e&&(T=[T[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1391
+ 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=wR(typeof t=="string"?t:"");_e&&(T=[T[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1392
1392
  `+_e.user},{role:"assistant",content:_e.assistant+`
1393
- [END EXAMPLE \u2014 wait for the real user request below]`},...T.slice(1)])}if(en(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(en(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"?Oy(M):null,ee=f1(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(`
1394
- `),ge=ru(_e);ge&&(ct=!0,St=ge.slice(0,120),L(`${p.yellow} \u26A1 Root cause in briefing: ${St} \u2014 fix phase active from start (read budget: 3)${p.reset}`))}if(!ct&&!Ut&&/\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)&&(Ut=!0,L(`${p.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${p.reset}`)),O.length<=1&&!s.skipPhaseRouting&&!d1(M)&&(ye=lR(),ye)){vs=aR(M)?.id||"coding";let ge=Hy(M);if(Te=ge?"implement":"plan",sn=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(${sn||"default"}) \u2192 verify ${p.yellow}[plan skipped: direct file task]${p.reset}`:`${p.dim} \u21B3 Phase routing: plan(${sn||"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 ${sn||"default model"} (category: ${vs})${p.reset}`:`${p.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${sn||"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,oe=new Map,J=new Set,Se=new Set,Ts=new Set,Rs=0,ju=0,Ea=0,Cs=0,Pe=Date.now(),P0=new XT(jR),M0=Sr,Qe=s.skillLoop?10:1,L0=3*Qe,I0=5*Qe,Du=Eu,j0=5*Qe,D0=8*Qe,q0=t0,F0=(ye?6:4)*Qe,B0=(ye?10:7)*Qe,Ta=aa,U0=(ye?5:3)*Qe,Cr=(ye?8:5)*Qe,W0=n0,H0=(ye?4:3)*Qe,Y0=(ye?6:4)*Qe,G0=3*Qe,z0=4*Qe,As=gn,K0=(ye?6:4)*Qe,X0=(ye?10:8)*Qe,Os=(ye?12:10)*Qe,V0=25,qn=0,J0=10*Qe,Z0=15*Qe,Fn=0,qu=5*Qe,Bn=0,Q0=2*Qe,ew=3,Ra=0,bo=10,tw=16,Fu=s.skillLoop?999:o.investigationCap,Bu=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}
1395
- `);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():"",Uu=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,Et=s.maxIterations||(ye?ys(Te):fu);Uu&&(Et=Math.min(Et,4),L(`${p.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${Et}${p.reset}`));let Ca=0,Wu=3,Aa=!1,Or=0,Oa=!1;e:for(;;){for(Aa=!1,ze=0;ze<Et&&!ra()?.aborted;ze++){oa(O,T);{let w=ht(),y=en(T,w),Y=H===0?65:78;if(y.percentage>=Y){if(J.size>0||ye&&Te!=="plan"){let z=tR(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(en(T,w).percentage)}%]${p.reset}`),Ut&&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(Pt&&!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}`)}Pt||(wr=0);let ge=!0;H>0&&kR();let Re=null;if(u&&u.isActive())u._paused&&u.resume();else if(!u){let w,y=SR();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 vR,Mt,Na=Date.now(),Nr=!1,Pa=new AbortController,Hu=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>=Fy&&!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!==nn()?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),Lt="",wn=null;try{let w=Zy(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=>Gy.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}),Mt=await Ay(T,B,{signal:z.signal,...sn?{model:sn}:{},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||(Lt+=j,process.stdout.isTTY?wn||(wn=setTimeout(()=>{Lt&&st&&st.push(Lt),Lt="",wn=null},50)):(st.push(Lt),Lt=""),Ke&&(u&&!u._paused?u.pause():Re&&Re.stop(),ge||(ge=!0),st.startCursor(),Ke=!1))}})}catch(w){if(clearInterval(Hu),wn&&(clearTimeout(wn),wn=null),Lt&&st&&(st.push(Lt),Lt=""),u&&!u._paused&&u.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}u&&(u.stop(),u=null);let j=await P1();if(j.action==="quit"){c(null),Ie(H,oe,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}`),s1){let U=ya.fast?.[co()];U&&U!==nn()&&(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")){u&&(u.stop(),u=null),c(null),Ie(H,oe,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=nn?nn():"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),Cy(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}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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:
1393
+ [END EXAMPLE \u2014 wait for the real user request below]`},...T.slice(1)])}if(en(T,pt()).percentage>=65){let{messages:ge,tokensRemoved:Re}=hn(T,pt());Re>0&&(T=ge,console.log(`${h.dim} [pre-flight compress \u2014 ${Re} tokens freed, now ${Math.round(en(T,pt()).percentage)}% used]${h.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"?My(M):null,ee=g1(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,pe=0;if(!ut){let _e=O.filter(Re=>Re.role==="user"||Re.role==="tool").map(Re=>typeof Re.content=="string"?Re.content:"").join(`
1394
+ `),ge=cu(_e);ge&&(ut=!0,St=ge.slice(0,120),L(`${h.yellow} \u26A1 Root cause in briefing: ${St} \u2014 fix phase active from start (read budget: 3)${h.reset}`))}if(!ut&&!Ht&&/\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)&&(Ht=!0,L(`${h.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${h.reset}`)),O.length<=1&&!s.skipPhaseRouting&&!m1(M)&&(ye=fR(),ye)){vs=dR(M)?.id||"coding";let ge=zy(M);if(Te=ge?"implement":"plan",sn=hu(Te,vs),$a=0,ho=0,qn=0,$r=null,bs.clear(),process.stdout.isTTY&&console.log(ge?`${h.dim} \u21B3 Phase routing: implement(${sn||"default"}) \u2192 verify ${h.yellow}[plan skipped: direct file task]${h.reset}`:`${h.dim} \u21B3 Phase routing: plan(${sn||"default"}) \u2192 implement \u2192 verify${h.reset}`),L(ge?`${h.cyan} \u26A1 Phase routing enabled \u2014 skipping plan phase for direct file task, starting in implement with ${sn||"default model"} (category: ${vs})${h.reset}`:`${h.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${sn||"default model"} (category: ${vs})${h.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,oe=new Map,J=new Set,Se=new Set,Ts=new Set,Rs=0,Bu=0,Ta=0,Cs=0,Pe=Date.now(),Iw=new QT(BR),jw=Sr,Qe=s.skillLoop?10:1,Dw=3*Qe,qw=5*Qe,Uu=Au,Fw=5*Qe,Bw=8*Qe,Uw=ow,Ww=(ye?6:4)*Qe,Hw=(ye?10:7)*Qe,Ra=la,Yw=(ye?5:3)*Qe,Cr=(ye?8:5)*Qe,Gw=rw,zw=(ye?4:3)*Qe,Kw=(ye?6:4)*Qe,Xw=3*Qe,Vw=4*Qe,As=yn,Jw=(ye?6:4)*Qe,Zw=(ye?10:8)*Qe,Os=(ye?12:10)*Qe,Qw=25,Fn=0,e0=10*Qe,t0=15*Qe,Bn=0,Wu=5*Qe,Un=0,n0=2*Qe,s0=3,Ca=0,$o=10,o0=16,Hu=s.skillLoop?999:o.investigationCap,Yu=async()=>{let{hasPendingOrCompletedJobs:_e,getPendingJobSummary:ge}=io();if(_e()){if(ge()){let Re=Date.now()+45e3;for(process.stderr.write(`${h.cyan} \u23F3 Waiting for background agents to finish\u2026${h.reset}
1395
+ `);ge()&&Date.now()<Re;)await new Promise(Ke=>setTimeout(Ke,500).unref()),ra(O,T)}ra(O,T),O.length>0&&Oe(O)}},Tn=typeof t=="string"?t.trim():"",Gu=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,Et=s.maxIterations||(ye?ys(Te):gu);Gu&&(Et=Math.min(Et,4),L(`${h.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${Et}${h.reset}`));let Aa=0,zu=3,Oa=!1,Or=0,Na=!1;e:for(;;){for(Oa=!1,ze=0;ze<Et&&!ia()?.aborted;ze++){ra(O,T);{let w=pt(),y=en(T,w),Y=H===0?65:78;if(y.percentage>=Y){if(J.size>0||ye&&Te!=="plan"){let z=rR(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(`${h.dim} [auto-compressed \u2014 ~${G} tokens freed, now ${Math.round(en(T,w).percentage)}%]${h.reset}`),Ht&&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(Pt&&!ut&&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(`${h.yellow} \u26A0 Pre-call SSH-blocked nudge #${wr} injected \u2014 model told to synthesize${h.reset}`)}Pt||(wr=0);let ge=!0;H>0&&TR();let Re=null;if(u&&u.isActive())u._paused&&u.resume();else if(!u){let w,y=RR();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?`${eu()} (step ${H+1})`:eu();let{getPendingJobSummary:Y}=io(),B=Y();B&&(w+=` [${B}]`),Re=new lo(w),Re.start()}let Ke=!0,it="",Rn=!1,ot=new CR,Lt,Pa=Date.now(),Nr=!1,Ma=new AbortController,La=setInterval(()=>{let w=Date.now()-Pa;if(w>=au)ot._clearCursorLine(),L(`${h.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${h.reset}`),Ma.abort();else if(w>=Wy&&!Nr){Nr=!0,ot._clearCursorLine();let y=wa.fast?.[co()],Y=we>0?` (retry ${we+1}/${sa})`:"",B=Math.round((au-w)/1e3);L(`${h.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${Y}${h.reset}`),y&&y!==nn()?console.log(`${h.dim} \u{1F4A1} Will auto-switch to ${y} in ~${B}s if no tokens arrive${h.reset}`):console.log(`${h.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${B}s${h.reset}`)}},5e3);La.unref?.();let It="",on=null;try{let w=tw(pt()),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=>Xy.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=ia(),z=new AbortController;G&&G.addEventListener("abort",()=>z.abort(),{once:!0}),Ma.signal.addEventListener("abort",()=>z.abort(),{once:!0}),Lt=await Py(T,B,{signal:z.signal,...sn?{model:sn}:{},onThinkingToken:()=>{Pa=Date.now(),Nr=!1,wn?.onThinkingToken&&wn.onThinkingToken()},onToken:j=>{if(Pa=Date.now(),Nr=!1,wn?.onToken){wn.onToken(j),it+=j;return}if(it+=j,!Rn&&it.length>400&&it.length%250<j.length+1){let ae=mu(it,3);ae.truncated&&(Rn=!0,ot._clearCursorLine?.(),L(`${h.yellow} \u26A0 LLM stream loop detected (${ae.repeatCount}\xD7 repeated) \u2014 suppressing display${h.reset}`))}Rn||(It+=j,process.stdout.isTTY?on||(on=setTimeout(()=>{It&&ot&&ot.push(It),It="",on=null},50),on.unref?.()):(ot.push(It),It=""),Ke&&(u&&!u._paused?u.pause():Re&&Re.stop(),ge||(ge=!0),ot.startCursor(),Ke=!1))}})}catch(w){if(clearInterval(La),on&&(clearTimeout(on),on=null),It&&ot&&(ot.push(It),It=""),u&&!u._paused&&u.pause(),Re&&Re.stop(),ot.stopCursor(),Ma.signal.aborted&&!ia()?.aborted){if(we++,we>sa){if(ke<1){ke++,ao("Stale retries exhausted \u2014 last-resort force-compress...",h.yellow);let ae=pt(),{messages:A,tokensRemoved:U}=hn(T,ae);T=A,U>50&&L(`${h.dim} [force-compressed \u2014 ~${U} tokens freed]${h.reset}`),we=0,ze--;continue}u&&(u.stop(),u=null);let j=await j1();if(j.action==="quit"){c(null),Ie(H,oe,J,Se,Pe),Oe(O);break}j.action==="switch"&&(tu(`${j.provider}:${j.model}`),console.log(`${h.green} \u2713 Switched to ${j.provider}:${j.model}${h.reset}`)),we=0,ze--;continue}let G=we===1?3e3:5e3;if(we>=1&&ve<1){ve++,ao(`Stale retry ${we}/${sa} \u2014 force-compressing before retry...`,h.yellow);let j=pt(),{messages:ae,tokensRemoved:A}=hn(T,j,!0);if(T=ae,A>0&&A>50&&L(`${h.dim} [force-compressed \u2014 ~${A} tokens freed]${h.reset}`),a1){let U=wa.fast?.[co()];U&&U!==nn()&&(tu(`${co()}:${U}`),console.log(`${h.cyan} \u26A1 Auto-switched to ${U} to avoid further stale timeouts${h.reset}`),console.log(`${h.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${h.reset}`))}}else L(`${h.yellow} \u26A0 Stale retry ${we}/${sa} \u2014 retrying in ${G/1e3}s...${h.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")){u&&(u.stop(),u=null),c(null),Ie(H,oe,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=nn?nn():"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(`${h.yellow} \u26A0 Model ${G} unavailable (404) \u2014 switching to ${ae}${h.reset}`),tu(ae),Ny(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(`${h.red} \u2717 ${y}${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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...`,h.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)`,h.yellow);let j=pt(),{messages:ae,tokensRemoved:A}=hn(T,j,z);T=ae,A>50&&L(`${h.dim} [force-compressed \u2014 ~${A} tokens freed]${h.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}=fn(),A=fn().estimateMessagesTokens(j),U=fn().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:
1396
1396
  `+W.map(I=>`- ${I}`).join(`
1397
1397
  `));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(`
1398
1398
  `).slice(0,8).join(`
1399
1399
  `).slice(0,500));if(ue.length>0&&R.push(`Tool results summary:
1400
1400
  `+ue.map(I=>`- ${I}`).join(`
1401
- `)),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:Ut,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),It={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};(It.completed.length>0||It.pending.length>0)&&R.unshift(`Work manifest:
1402
- ${JSON.stringify(It,null,2)}`)}if(R.length>0){let I={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1401
+ `)),J.size>0){let I=[...J].map($e=>$e.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($e=>$e.split("/").slice(-2).join("/")).join(", ");R.push(`Files already investigated: ${I}`)}let be=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(be,JSON.stringify({filesWritten:[...J].map(I=>I.split("/").slice(-2).join("/")),filesRead:[...Se].map(I=>I.split("/").slice(-2).join("/")),isCreationTask:Ht,wipeNumber:yr+1,timestamp:Date.now()},null,2)),R.push(`Session checkpoint: ${be} \u2014 read it for exact file list`)}catch{}let te=0;{let $e=((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=$e.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),Dt={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};(Dt.completed.length>0||Dt.pending.length>0)&&R.unshift(`Work manifest:
1402
+ ${JSON.stringify(Dt,null,2)}`)}if(R.length>0){let I={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1403
1403
  ${R.join(`
1404
1404
  `)}
1405
1405
  Continue implementing the fixes based on these findings.`};j.push(I)}if(yr>=3){let I=J.size>0?`
1406
- 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}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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,Bt=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);Ft.clear(),Ss.clear(),Ut&&Yt>0&&(Ht=!0,L(`${p.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Yt} 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?`
1406
+ Files modified so far: ${[...J].map($e=>$e.split("/").slice(-1)[0]).join(", ")}`:"";L(`${h.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${h.reset}`),console.log(`${h.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${I?h.dim+I:""}${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);break}T=j,yr++,$s=10+Math.min(te*3,7),ku=!0,pa=J.size,ha=!1,Wt=0,pe=0;for(let[I,$e]of yn){let Ee=$e?.count??$e??0;uu(yn,I,Ee>=2?Ee:1)}for(let[I]of En)mn(yn,I)<2&&En.delete(I);Ut.clear(),Ss.clear(),Ht&&zt>0&&(Gt=!0,L(`${h.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${zt} edits already made)${h.reset}`));for(let[I]of la)uu(la,I,Cr-1);if(ao(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${U-A} tokens freed)`,h.yellow),yr>=1){let I=[...yn.entries()].filter(([,Xe])=>Xe>=Os).map(([Xe])=>Xe.split("/").slice(-1)[0]),$e=I.length>0?`
1407
1407
 
1408
- Files already at read cap \u2014 use grep_search instead: ${I.join(", ")}`:"",Ue={role:"user",content:Pt&&!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}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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.
1409
- Use /undo to revert changes made during this session.${p.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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}u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe),Oe(O);break}if(clearInterval(Hu),q=0,Q=0,Ke&&(u&&!u._paused&&u.pause(),Re&&Re.stop()),wn&&(clearTimeout(wn),wn=null),Lt&&st&&(st.push(Lt),Lt=""),rt&&st.flush(),Q=0,we=0,Mt&&Mt.usage){let w=Mt.usage.prompt_tokens||0,y=Mt.usage.completion_tokens||0;Py(co(),nn(),w,y),d+=w+y,u&&u.setStats({tokens:d})}else if(Mt&&!Mt.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=Ly(w),Y=Ly(Mt.content||rt||"");Py(co(),nn(),y,Y),d+=y+Y,u&&u.setStats({tokens:d})}let{content:Yu,tool_calls:Ns}=Mt,Tt=Ns,Ma=!1;if(Array.isArray(Ns)&&Ns.length>0){let w=Ns.filter(y=>y?.function?.name==="ask_user");w.length>0&&(Tt=[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(Yu||""),Gu=Pr.truncated?Pr.text:Yu;Pr.truncated&&L(`${p.yellow} \u26A0 LLM output loop detected (${Pr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${p.reset}`);let Mr=WR(Gu||""),bt=Mr.truncated?Mr.text:Gu;Mr.truncated&&L(`${p.yellow} \u26A0 LLM output loop detected (${Mr.repeatCount}\xD7 repeated window) \u2014 response truncated${p.reset}`),Array.isArray(Tt)&&Tt.length>0&&cR(bt||"")&&(L(`${p.yellow} \u26A0 Assistant asked the user a direct question in text \u2014 dropping tool calls and waiting for user input${p.reset}`),Tt=[]);let _o={role:"assistant",content:bt||""};if(Tt&&Tt.length>0&&(_o.tool_calls=Tt),O.push(_o),T.push(_o),Uu&&!ta(bt||rt||"")&&J.size===0&&Cs===0){L(`${p.green} \u2713 Analysis-only early exit: ${(bt||"").length} chars produced, no file changes${p.reset}`),_o.tool_calls&&delete _o.tool_calls,Ie(H,oe,J,Se,Pe),Oe(O);break e}if(!ct&&bt&&Tt&&Tt.length>0){let w=ru(bt);if(w){ct=!0,St=w.slice(0,120),Wt=0,Ht=!1,tn=0,L(`${p.yellow} \u26A1 Root cause in model analysis: ${St} \u2014 fix phase (read budget: 3)${p.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${St}. Read only the file that needs fixing, then edit it. Do not read other files.`};O.push(y),T.push(y)}}if(!Tt||Tt.length===0){let w=(bt||"").trim().length>0||rt.trim().length>0,y=!1;if(Pt&&w&&(sa>=2?L(`${p.yellow} \u26A0 SSH permanently blocked after ${sa} storm warnings \u2014 no further SSH calls allowed${p.reset}`):(Pt=!1,Bt=bo-4,y=!0)),y&&w){let z=(bt||"").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((bt||"").slice(0,600)))if($u&&bs<=0||Pt){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(s.skillLoop&&w&&H>3&&Or<5){let z=(bt||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()&&!s.skillLoop&&(J.size>0||Cs>0)&&w&&!ta(bt||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,oe,J,Se,Pe),Oe(O);break e}let G=u1(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,Et=ys("implement");continue}}if(ye&&w){let z=(bt||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=s0(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}
1410
- `),Ie(H,oe,J,Se,Pe),Oe(O);break e}let W=await pr("implement",z);if(W){O.push(W),T.push(W),ze=0,Et=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,Et=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()&&!s.skillLoop&&U&&!A&&!ta(z)){L(`${p.green} \u2713 Verification phase complete (headless substantive summary)${p.reset}`),Ie(H,oe,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:
1408
+ Files already at read cap \u2014 use grep_search instead: ${I.join(", ")}`:"",Ue={role:"user",content:Pt&&!ut?"[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}`};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(`${h.red} \u2717 ${y}${h.reset}`),w.message.includes("429")){if(q++,q>ru){console.log(`${h.red} Rate limit: max retries (${ru}) exceeded. Try again later or use /budget to check your limits.${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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}/${ru})`);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>iu){console.log(`${h.red} Network error: max retries (${iu}) exceeded. Check your connection and try again.
1409
+ Use /undo to revert changes made during this session.${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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}/${iu}). Your changes are safe.`);z.start(),await new Promise(j=>setTimeout(j,G)),z.stop(),ze--;continue}u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe),Oe(O);break}if(clearInterval(La),q=0,Q=0,Ke&&(u&&!u._paused&&u.pause(),Re&&Re.stop()),on&&(clearTimeout(on),on=null),It&&ot&&(ot.push(It),It=""),it&&ot.flush(),Q=0,we=0,Lt&&Lt.usage){let w=Lt.usage.prompt_tokens||0,y=Lt.usage.completion_tokens||0;Iy(co(),nn(),w,y),d+=w+y,u&&u.setStats({tokens:d})}else if(Lt&&!Lt.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=Dy(w),Y=Dy(Lt.content||it||"");Iy(co(),nn(),y,Y),d+=y+Y,u&&u.setStats({tokens:d})}let{content:Ku,tool_calls:Ns}=Lt,Tt=Ns,Ia=!1;if(Array.isArray(Ns)&&Ns.length>0){let w=Ns.filter(y=>y?.function?.name==="ask_user");w.length>0&&(Tt=[w[0]],Ia=Ns.length!==1,Ia&&L(`${h.yellow} \u26A0 ask_user must run alone \u2014 deferring ${Ns.length-1} other tool call(s) until the user replies${h.reset}`))}let Pr=mu(Ku||""),Xu=Pr.truncated?Pr.text:Ku;Pr.truncated&&L(`${h.yellow} \u26A0 LLM output loop detected (${Pr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${h.reset}`);let Mr=zR(Xu||""),$t=Mr.truncated?Mr.text:Xu;Mr.truncated&&L(`${h.yellow} \u26A0 LLM output loop detected (${Mr.repeatCount}\xD7 repeated window) \u2014 response truncated${h.reset}`),Array.isArray(Tt)&&Tt.length>0&&pR($t||"")&&(L(`${h.yellow} \u26A0 Assistant asked the user a direct question in text \u2014 dropping tool calls and waiting for user input${h.reset}`),Tt=[]);let _o={role:"assistant",content:$t||""};if(Tt&&Tt.length>0&&(_o.tool_calls=Tt),O.push(_o),T.push(_o),Gu&&!na($t||it||"")&&J.size===0&&Cs===0){L(`${h.green} \u2713 Analysis-only early exit: ${($t||"").length} chars produced, no file changes${h.reset}`),_o.tool_calls&&delete _o.tool_calls,Ie(H,oe,J,Se,Pe),Oe(O);break e}if(!ut&&$t&&Tt&&Tt.length>0){let w=cu($t);if(w){ut=!0,St=w.slice(0,120),Yt=0,Gt=!1,tn=0,L(`${h.yellow} \u26A1 Root cause in model analysis: ${St} \u2014 fix phase (read budget: 3)${h.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${St}. Read only the file that needs fixing, then edit it. Do not read other files.`};O.push(y),T.push(y)}}if(!Tt||Tt.length===0){let w=($t||"").trim().length>0||it.trim().length>0,y=!1;if(Pt&&w&&(oa>=2?L(`${h.yellow} \u26A0 SSH permanently blocked after ${oa} storm warnings \u2014 no further SSH calls allowed${h.reset}`):(Pt=!1,Wt=$o-4,y=!0)),y&&w){let z=($t||"").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<gu-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(($t||"").slice(0,600)))if(ku&&$s<=0||Pt){L(`${h.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${h.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(`${h.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${h.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(s.skillLoop&&w&&H>3&&Or<5){let z=($t||it||"").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(`${h.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Or}${h.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()&&!s.skillLoop&&(J.size>0||Cs>0)&&w&&!na($t||it||"")&&H>=1&&(!ye||Te==="implement")){L(`${h.green} \u2713 Headless early exit: ${J.size} file(s) modified (+ ${Cs} bash writes), substantive text response received${h.reset}`),Ie(H,oe,J,Se,Pe),Oe(O);break e}let G=h1($r)?1:2;if(ye&&Te==="plan"&&qn>=G){L(`${h.cyan} \u21B3 Plan phase: ${qn} consecutive blocks (last: ${$r||"unknown"}) \u2014 auto-advancing to implement${h.reset}`),qn=0,$r=null;let z=await hr("implement","[auto-advance: task only requires direct action]");if(z){O.push(z),T.push(z),ze=0,Et=ys("implement");continue}}if(ye&&w){let z=($t||it||"").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=iw(z,yn).length===0,A=xr.size>0,U=kr.size>0,R=z.length>1500;if(ks()&&ae&&!A&&!U&&!R&&j.test(z)){L(`${h.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${h.reset}
1410
+ `),Ie(H,oe,J,Se,Pe),Oe(O);break e}let W=await hr("implement",z);if(W){O.push(W),T.push(W),ze=0,Et=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 hr("verify",z,J,ae);if(A){O.push(A),T.push(A),ze=0,Et=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()&&!s.skillLoop&&U&&!A&&!na(z)){L(`${h.green} \u2713 Verification phase complete (headless substantive summary)${h.reset}`),Ie(H,oe,J,Se,Pe),Oe(O),dr(O);break e}if(A&&ho<3){ho++;let R={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1411
1411
  ${z.slice(0,400)}
1412
1412
 
1413
- Fix the identified issues. This is attempt ${po}/3.`};Te="implement",sn=uu("implement",vs),O.push(R),T.push(R),ze=0,Et=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,oe,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.).
1413
+ Fix the identified issues. This is attempt ${ho}/3.`};Te="implement",sn=hu("implement",vs),O.push(R),T.push(R),ze=0,Et=ys("implement"),L(`${h.yellow} \u21B3 Verify \u2192 implement loop-back #${ho} (issues found)${h.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(`${h.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${go}/2)${h.reset}`);continue}L(`${h.yellow} \u26A0 Verify phase completion accepted without full markers after ${go} nudges${h.reset}`)}if(L(`${h.green} \u2713 Verification phase complete${A?" (loop-back exhausted)":" (PASS)"}${h.reset}`),!A){Ie(H,oe,J,Se,Pe),Oe(O),dr(O);break e}}}if(_r()&&w&&H===0)if(ua++,ua>2)L(`${h.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${h.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.).
1414
1414
 
1415
- 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=(bt||rt||"").trim();bR(z),o1(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";xR(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(`
1416
- ${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(`
1417
- `),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]
1415
+ 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(`${h.yellow} \u26A0 Plan rejected (${ua}/2): no files read \u2014 forcing investigation${h.reset}`);continue}if(_r()&&w){let z=($t||it||"").trim();SR(z),l1(z);let j=vR(z);if(j.length>0){let ae=O.find(ue=>ue.role==="user"),A=typeof ae?.content=="string"?ae.content.slice(0,120):"Task";ER(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:be,setPlanMode:te}=Zi();process.stdout.write(`
1416
+ ${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${j.length} ${U})${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.yellow}[E]${h.reset}${h.dim}dit${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let I=process.stdin.isRaw,$e=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(`
1417
+ `),$e==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if($e==="e")console.log(`${h.yellow}Type /plan edit to open in editor, or give feedback.${h.reset}`);else if(ue()){be(),te(!1),$u(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing ${j.length} ${U}...`);let Ee=`[PLAN APPROVED \u2014 EXECUTE NOW]
1418
1418
 
1419
1419
  Implement the following plan step by step. All tools are now available.
1420
1420
 
1421
1421
  ${z}`;O.push({role:"user",content:Ee}),T.push({role:"user",content:Ee}),R=!0}}else console.log(`
1422
- ${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){u&&(u.stop(),u=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(`
1423
- ${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(`
1424
- `),$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]
1422
+ ${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${j.length} ${U} extracted).${h.reset} Type ${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ${h.reset}${h.cyan}/plan edit${h.reset}${h.dim} to review.${h.reset}`);if(R){u&&(u.stop(),u=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}=Zi();process.stdout.write(`
1423
+ ${h.cyan}${h.bold}Plan ready.${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let ue=process.stdin.isRaw,be=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(`
1424
+ `),be==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(U()){R(),W(!1),$u(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing...`);let I=`[PLAN APPROVED \u2014 EXECUTE NOW]
1425
1425
 
1426
1426
  Implement the following plan step by step. All tools are now available.
1427
1427
 
1428
- ${getPlanContent()||Mt.content}`;O.push({role:"user",content:I}),T.push({role:"user",content:I}),ae=!0}}else console.log(`
1429
- ${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){u&&(u.stop(),u=null),ze--;continue}}}if(u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe),Ut&&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(Ut&&!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&&!s._isSummaryTurn&&ta(bt))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 Ay(j,[],{}))?.content||"").trim();A&&(console.log(`
1430
- ${A}`),O.push({role:"user",content:z},{role:"assistant",content:A}))}catch{}Oe(O),dr(O),await Bu();return}H++,$a++,H>=1&&(ge=!1);for(let w of Tt){let y=w.function.name;oe.set(y,(oe.get(y)||0)+1)}if(H>=30&&!Wy){Wy=!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(Tt.map(w=>r1(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=en(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=Ft.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}`),Ft.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,It=I-te||1,tt=Ue/It>=.7&&Ue/Xe<.7,Lr=W-R<=V0;if(Ue>=Xe||!Lr&&(Ue/Xe>=.7||Ue/It>=.7)){let ja=y.split("/").slice(-2).join("/"),Ju=`${y}:${R}-${W}`,Ms=(wa.get(Ju)||0)+1;if(wa.set(Ju,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 Zu={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(Zu),T.push(Zu)}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=Ft.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?Ft.delete(y):Ft.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(Hy(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 zu=new Map;for(let w of xe){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let Y=zu.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&&zu.set(y,Y+1)}let nw=5,Ku=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=Ku.get(Y)||0,G=pn(Du,Y)+B;G>=nw&&(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&&Ku.set(Y,B+1)}if(Pt){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)Pt=!1,da++,Bt=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 (${St}). 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 sw=e1(O,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((K||C)&&!sw&&he<3&&!Pt)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&&Ht&&Ut&&Yt>=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 ow=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||ow.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=u?{skipSpinner:!0,skipSummaries:!0}:{},rw=xe.some(w=>w.fnName==="ask_user"),Xu=!xo.skipSummaries&&!ge,zt=null,Ps=null;if(Xu&&!rw){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?`
1431
- `:""}${w}`),fo=y,ho=Date.now(),zt={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?`
1428
+ ${getPlanContent()||Lt.content}`;O.push({role:"user",content:I}),T.push({role:"user",content:I}),ae=!0}}else console.log(`
1429
+ ${h.cyan}${h.bold}Plan ready.${h.reset} ${h.dim}Type ${h.reset}${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ask follow-up questions to refine.${h.reset}`);if(ae){u&&(u.stop(),u=null),ze--;continue}}}if(u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe),Ht&&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;br=`[Previous session created ${J.size} files: ${z}`+(U?` \u2014 ${U}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Ht&&!Su&&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:[],$e=Array.isArray(te.content)?te.content.filter(Ee=>Ee?.type==="tool_use"):[];return[...I,...$e]}).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){Su=!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(`${h.dim} [post-creation] bootstrapping environment (${te.join(", ")})${h.reset}`),O.push({role:"user",content:I}),T.push({role:"user",content:I});continue}}if(H>0&&!s._isSummaryTurn&&na($t))try{L(`${h.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${h.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 Py(j,[],{}))?.content||"").trim();A&&(console.log(`
1430
+ ${A}`),O.push({role:"user",content:z},{role:"assistant",content:A}))}catch{}Oe(O),dr(O),await Yu();return}H++,$a++,H>=1&&(ge=!1);for(let w of Tt){let y=w.function.name;oe.set(y,(oe.get(y)||0)+1)}if(H>=30&&!Gy){Gy=!0,L(`${h.yellow} \u26A0 Tool budget warning: ${H} tool calls used \u2014 nudging model to wrap up${h.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(Tt.map(w=>c1(w)));if(Na){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=en(T,pt()),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&&mn(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&&Ca<70||y>=85&&Ca<85||G){Ca=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(`${h.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${U}${h.reset}`)}}}let ja=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=mn(As,y),B=ja.get(y)||0,G=Y+B,z=bs.has(y),j=w.args?.line_start!=null,ae=Ut.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(`${h.red} \u2716 Blocked: "${R}" read ${G}\xD7 \u2014 hard cap (${Os}) reached${h.reset}`);else if(W===2){L(`${h.red} \u2716 Escalated block: "${R}" \u2014 model ignored BLOCKED, injecting system warning${h.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(`${h.cyan} \u21A9 Targeted re-read: "${R}" (line_start=${w.args.line_start}) \u2014 edit recovery #${ae}${h.reset}`),Ut.set(y,ae-1)}else if(A&&ae>U){let R=y.split("/").slice(-2).join("/");L(`${h.red} \u2716 Edit recovery blocked: "${R}" \u2014 ${U} recovery reads already used. Use grep to find the exact line numbers, then retry.${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${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)||[],be=!1;for(let[te,I]of ue){let $e=Math.max(R,te),Ee=Math.min(W,I);if(Ee>$e){let Ue=Ee-$e,Xe=W-R||1,Dt=I-te||1,tt=Ue/Dt>=.7&&Ue/Xe<.7,Lr=W-R<=Qw;if(Ue>=Xe||!Lr&&(Ue/Xe>=.7||Ue/Dt>=.7)){let qa=y.split("/").slice(-2).join("/"),ed=`${y}:${R}-${W}`,Ms=(ba.get(ed)||0)+1;if(ba.set(ed,Ms),L(tt?`${h.red} \u2716 Blocked superread: "${qa}" lines ${R}-${W} subsumes already-read ${te}-${I} \u2014 use line_start=${I+1} to skip known content (block #${Ms})${h.reset}`:`${h.red} \u2716 Blocked duplicate read: "${qa}" lines ${R}-${W} (\u226570% overlap with lines ${te}-${I} already in context, block #${Ms})${h.reset}`),Ms>=2){L(`${h.red} \u2716 Escalated range-block: "${qa}" lines ${R}-${W} \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let td={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(td),T.push(td)}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},be=!0;break}}}if(!be){let te=ue.length,I=2;if(te>=3){let Ee=y.split("/").slice(-2).join("/");L(`${h.red} \u2716 Blocked file-scroll: "${Ee}" \u2014 ${te} sections already read. Use grep to find specific content.${h.reset}`);let Ue=mn(Ra,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=Ut.get(y)||0;if(R>0){let W=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Full re-read: "${W}" \u2014 test-failure recovery (${R} remaining)${h.reset}`);let ue=R-1;ue<=0?Ut.delete(y):Ut.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(`${h.red} \u2716 Blocked unbounded re-read: "${W}" \u2014 already in context. Use line_start/line_end for specific sections.${h.reset}`);else if(ue===2){L(`${h.red} \u2716 Escalated block: "${W}" \u2014 model ignored unbounded re-read block, injecting system warning${h.reset}`);let be={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(be),T.push(be)}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&&ja.set(y,(ja.get(y)||0)+1)}if(Dn>=3)for(let w of xe)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(L(`${h.red} \u2716 Blocked ${w.fnName} \u2014 ${Dn} consecutive file-not-found errors, must search first${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${Dn} 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(`${h.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:w.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(L(`${h.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:w.callId})}for(let w of xe)w.canExecute&&(w.fnName!=="ssh_exec"&&w.fnName!=="bash"||/\bsed\s+-n\b/.test(w.args?.command||"")&&(L(`${h.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:w.callId}));for(let w of 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=Tu(M),U=Tu(y);if(zy(M)&&(A.includes(U)||A.includes(`./${U}`)))continue;if(ae<.6&&z>200){let W=y.split("/").slice(-2).join("/");console.log(`${h.red} \u2716 write_file shrink guard: "${W}" would shrink to ${Math.round(ae*100)}% of original \u2014 likely context loss${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(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 Vu=new Map;for(let w of xe){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let Y=Vu.get(y)||0,B=mn(Ra,y)+Y,G=mn(As,y)>=1,z=G?Math.min(3,Cr):Cr;if(B>=z){let j=y.split("/").slice(-2).join("/");L(`${h.red} \u2716 Blocked grep: "${j}" grepped ${B}\xD7 with different patterns \u2014 flood threshold exceeded${h.reset}`);let ae=mn(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(`${h.red} \u2716 Deadlock detected: "${j}" \u2014 both read and grep blocked, injecting deadlock-break${h.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&&Vu.set(y,Y+1)}let r0=5,Ju=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=Ju.get(Y)||0,G=mn(Uu,Y)+B;G>=r0&&(L(`${h.yellow} \u26A0 Blocked ssh_exec: same command run ${G}\xD7 \u2014 result already in context${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${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&&Ju.set(Y,B+1)}if(Pt){let w=xe.filter(B=>B.canExecute&&B.fnName==="ssh_exec"),y=xe.some(B=>B.canExecute&&B.fnName!=="ssh_exec"),Y=K&&pe<3;if(w.length>0&&!y&&Y&&fa<1)Pt=!1,fa++,Wt=Math.max(0,$o-2),L(`${h.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${fa}/1)]${h.reset}`);else for(let B of w)B.canExecute=!1,B.errorResult={role:"tool",content:ut?`BLOCKED: ssh_exec denied \u2014 SSH paused (${$o}+ calls). Root cause is known (${St}). 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 (${$o}+ 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 i0=o1(O,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((K||C)&&!i0&&pe<3&&!Pt)for(let w of xe){if(!w.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(w.fnName))continue;pe++;{let B=pt(),{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(`${h.yellow} \u26A0 Runtime guard: blocking local ${w.fnName} \u2014 inspect the live app first${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:Y,tool_call_id:w.callId};break}if(!ye&&Gt&&Ht&&zt>=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(`${h.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if($s>=0){let w=xe.filter(y=>y.canExecute).length;if(w>0&&($s-=w,$s<0))if(!ha&&J.size>pa){ha=!0,$s=5,L(`${h.green} \u2713 Post-wipe progress detected (${J.size-pa} files modified) \u2014 granting 5 bonus tool calls${h.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};O.push(y),T.push(y)}else{L(`${h.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${h.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 a0=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||a0.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),Y=`${w.fnName}|${y}`,B=mn(_u,Y);B>=2?(L(`${h.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${B+1}\xD7 with identical args${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName}() with these exact arguments has already been called ${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(`${h.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${h.reset}`),ws(_u,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(`${h.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${Y.split("/").slice(-1)[0]}"${h.reset}`)):Ts.has(Y)&&!bs.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(`${h.yellow} \u26A0 Map-first gate: blocked re-edit of "${Y.split("/").slice(-1)[0]}" \u2014 re-read required${h.reset}`)):w.add(Y))}}let xo=u?{skipSpinner:!0,skipSummaries:!0}:{},l0=xe.some(w=>w.fnName==="ask_user"),Zu=!xo.skipSummaries&&!ge,jt=null,Ps=null;if(Zu&&!l0){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?`
1431
+ `:""}${w}`),fo=y,po=Date.now(),jt={start:Date.now(),frame:0,timer:null}}else if(!wn){let w=ur(xe,H,!1);fu(w,fo,po)||(process.stdout.write(`${H>1?`
1432
1432
  `:""}${w}
1433
- `),fo=w,ho=Date.now())}}else Xu&&(ge=!0,xo.skipSpinner=!0);u&&u._paused&&u.resume(),zt&&process.stdout.isTTY&&(zt.timer=setInterval(()=>{zt.frame++;let w=Math.round((Date.now()-zt.start)/1e3),y=w>=1?` ${p.dim}[${w}s]${p.reset}`:"",Y=`${ur(xe,H,!1,zt.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:iw}=await c1(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(zt){zt.timer&&(clearInterval(zt.timer),zt.timer=null);let w=ur(xe,H,!1);lu(w,fo,ho)||(Ps!==null?process.stdout.write(`\x1B[${Ps};1H\x1B[2K${w}
1433
+ `),fo=w,po=Date.now())}}else Zu&&(ge=!0,xo.skipSpinner=!0);u&&u._paused&&u.resume(),jt&&process.stdout.isTTY&&(jt.timer=setInterval(()=>{jt.frame++;let w=Math.round((Date.now()-jt.start)/1e3),y=w>=1?` ${h.dim}[${w}s]${h.reset}`:"",Y=`${ur(xe,H,!1,jt.frame)}${y}`;Ps!==null?process.stdout.write(`\x1B[${Ps};1H\x1B[2K${Y}`):process.stdout.write(`\r\x1B[2K${Y}`)},120),jt.timer.unref?.());let{results:et,summaries:c0}=await p1(xe,!0,{...xo,skipSummaries:!0});if(Ia){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(jt){jt.timer&&(clearInterval(jt.timer),jt.timer=null);let w=ur(xe,H,!1);fu(w,fo,po)||(Ps!==null?process.stdout.write(`\x1B[${Ps};1H\x1B[2K${w}
1434
1434
  `):process.stdout.write(`\r\x1B[2K${w}
1435
- `),fo=w,ho=Date.now()),Ps=null,zt=null}if(!xo.skipSummaries){let w=iw.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=P0.record(0,y,Se,J);Y&&DR(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>=qu)){L(`${p.red} \u2716 Loop abort: ${Fn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${p.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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(`
1436
- `)[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=Ft.get(y.args.path)||0;Ft.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)Ft.has(R)||(Ft.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){Ft.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(M0,y.args.path),U=y.args.path.split("/").slice(-2).join("/");if(A===L0){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>=I0){L(`${p.red} \u2716 Loop abort: "${U}" edited ${A}\xD7 \u2014 aborting to prevent runaway loop${p.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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)){Wt=0,Ht=!1,tn=0,Yt++;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(Wt++,Ht&&tn++,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}
1437
- 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&&$1(y)&&(yo=!1,wo=0);let R=o.postEditCap,W=ye&&Te==="implement"?Math.min(Fu,10):Fu,ue=ct?8:Ar?Yt>0?4:6:Ut?Yt>0?6:10:Yt>0?R:W,$e=6,te=!ye&&Ht&&(ct&&tn>=$e||Ut&&Yt>=3&&tn>=$e||tn>=$e);if(fr<2&&!Ht&&Wt>=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}%), ${Wt} reads, 0 edits${p.reset}`);let It={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(It),T.push(It)}}if(te&&A.includes(y.fnName)){let I=ct?`root cause already identified (${St})`:tn>=$e?`${Wt} consecutive reads without an edit`:`${Yt} 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 (${St}). Use edit_file to fix the issue \u2014 do not read more files.`:Ut?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":tn>=$e?`BLOCKED: You have read ${Wt} 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: ${Yt} 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(Wt>=ue&&!Ht){if(Ht=!0,Ar&&(Oa=!0),L(`${p.yellow} \u26A0 Investigation cap: ${Wt} read-only calls without an edit \u2014 forcing implementation${p.reset}`),ye&&Te==="plan"){let Ee=[...T].reverse().find(It=>It.role==="assistant"),Ue=typeof Ee?.content=="string"?Ee.content:"",Xe=await pr("implement",Ue);Xe&&(O.push(Xe),T.push(Xe),ze=0,Et=ys("implement"))}let I;ct?I=`[SYSTEM] Root cause was already identified (${St}). 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.":Pt?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(Du,A);if(U===j0){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>=D0){L(`${p.red} \u2716 Loop abort: same bash command run ${U}\xD7 \u2014 aborting runaway debug loop${p.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);return}}if(y.fnName==="ssh_exec"){Bt++;{let R=(et[w]?.content??"").split(`
1438
- `).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&&!Pt){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(Bt>=tw){L(`${p.red} \u2716 SSH storm abort: ${Bt} consecutive ssh_exec calls \u2014 aborting${p.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);return}else if(Bt===bo){{let R=ht(),{messages:W}=hn(T,R);T=W}Pt=!0,sa++,L(`${p.yellow} \u26A0 SSH storm warning (#${sa}): ${Bt} consecutive ssh_exec calls \u2014 blocking further SSH${p.reset}`);let U={role:"user",content:ct?`[SYSTEM WARNING] ${Bt} consecutive SSH calls. Root cause identified (${St}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Bt} 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&&(Bt=0);if(y.fnName==="bash"&&y.canExecute){let R=(et[w]?.content??"").split(`
1439
- `).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(`
1440
- `);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(q0,A);if(U===F0){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>=B0){L(`${p.red} \u2716 Loop abort: grep pattern run ${U}\xD7 \u2014 aborting runaway search loop${p.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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:U0)){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(`
1441
- `);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(W0,A);if(U===H0){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>=Y0){L(`${p.red} \u2716 Loop abort: glob pattern run ${U}\xD7 \u2014 aborting runaway search loop${p.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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===z0){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===G0){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(en(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(en(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>=qu){L(`${p.red} \u2716 Loop abort: ${Fn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${p.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);return}}else Fn=0;if(G)qn=0,Aa=!0;else if(qn++,qn===J0){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>=Z0){L(`${p.red} \u2716 Loop abort: ${qn} consecutive errors \u2014 aborting stuck loop${p.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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===K0){{let $e=ht();if(en(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>=X0){L(`${p.red} \u2716 Loop abort: "${U}" read unbounded ${A}\xD7 \u2014 aborting runaway read loop${p.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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===Q0){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>=ew){console.log(`${p.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Bn}\xD7 \u2014 aborting stuck swarm${p.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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:w1(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)+`
1442
- ...(truncated ${G-j} chars \u2014 per-message budget)`},y-=G-j)}}}for(let w of et)O.push(w),T.push(w);let aw=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 uR(Y)&&typeof et[y]?.content=="string"&&!et[y].content.startsWith("ERROR")&&!et[y].content.startsWith("BLOCKED:")});if(ks()&&!s.skillLoop&&Oa&&aw){L(`${p.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${p.reset}`),Ie(H,oe,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,St=Y.slice(0,120),Wt=0,Ht=!1,tn=0,L(`${p.yellow} \u26A1 Root cause detected: ${St} \u2014 fix phase (read budget: 3)${p.reset}`);let B={role:"user",content:`[SYSTEM] Root cause identified: ${St}. 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(en(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(en(T,w).percentage)}%]${p.reset}`))}}if(ks()&&!s.skillLoop&&(xe.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?Rs=0:(Rs===0&&(ju=J.size),Rs++),Rs>=9&&H>=4&&J.size===ju)){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}
1443
- `),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe),Oe(O);break e}let Vu=p1();if(Vu){let w={role:"user",content:`[User note mid-run]: ${Vu}`};O.push(w),T.push(w),console.log(`${p.cyan} \u270E Context added${p.reset}`)}}if(ze>=Et){if(u&&(u.stop(),u=null),c(null),Ie(H,oe,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],Et=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<Wu){if(J.size===0&&!Aa){console.log(`${p.yellow} \u26A0 Max iterations reached with no progress. Stopping.${p.reset}`);break e}Ca++,Et=20,console.log(`${p.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Ca}/${Wu}) \u2500\u2500${p.reset}`);continue e}if(console.log(`
1444
- ${p.yellow}\u26A0 Max iterations reached.${p.reset}`),await Yy(" Continue for 20 more turns?")){Et=20;continue e}console.log(`${p.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${p.reset}`)}break e}await Bu()}a0.exports={processInput:I1,clearConversation:E1,getConversationLength:R1,getConversationMessages:C1,setConversationMessages:A1,setAbortSignalGetter:YR,setMaxIterations:HR,invalidateSystemPromptCache:gu,clearToolFilterCache:QR,getCachedFilteredTools:Zy,buildSystemPrompt:vu,splitSystemPrompt:v1,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Su,getProjectContextHash:Qy,_inferVerificationCommands:Tu,_inferRelevantTests:ba,_inferSymbolTargets:o0,_buildSymbolHintBlock:r0,buildUserContent:Vy,_detectImageURLs:zy,_downloadImageURL:Ky,_grabClipboardImage:Xy,detectFrustration:Jy,detectAndTruncateLoop:du,injectMidRunNote:h1,resetSessionTracking:i0}});var dt=Z((oO,d0)=>{var{OllamaProvider:j1}=od(),{OpenAIProvider:D1}=ld(),{AnthropicProvider:q1}=fd(),{GeminiProvider:F1}=gd(),{LocalProvider:B1}=$d(),{checkBudget:U1}=zr(),Ou={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"}},Cu=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),c0={};for(let[t,e]of Object.entries(Ou))for(let s of Object.values(e))c0[s]=t;function Au(t,e){let s=c0[t];return s&&Ou[s][e]||t}var ut={},vt=null,Ze=null,Tr=[];function Gt(){if(Object.keys(ut).length>0)return;$o("ollama",new j1),$o("openai",new D1),$o("anthropic",new q1),$o("gemini",new F1),$o("local",new B1);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;ut[t]?(vt=t,Ze=e||ut[t].defaultModel):(vt="ollama",Ze="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(Tr=s.split(",").map(o=>o.trim()).filter(Boolean))}function $o(t,e){ut[t]=e}function W1(t){return Gt(),ut[t]||null}function Nu(){return Gt(),ut[vt]||null}function H1(){return Gt(),vt}function Y1(){return Gt(),Ze}function G1(){Gt();let t=Nu();if(!t)return{id:Ze,name:Ze,provider:vt};let e=t.getModel(Ze);return e?{...e,provider:vt}:{id:Ze,name:Ze,provider:vt}}function Pu(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(ut[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function z1(t){Gt();let{provider:e,model:s}=Pu(t);if(e){let n=ut[e];return n&&(n.getModel(s)||e==="local"||e==="ollama")?(vt=e,Ze=s,_a(),!0):!1}let o=Nu();if(o&&o.getModel(s))return Ze=s,_a(),!0;for(let[n,r]of Object.entries(ut))if(r.getModel(s))return vt=n,Ze=s,_a(),!0;return!1}function _a(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Oc();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=dn();t()}catch{}}function K1(){Gt();let t=new Set;for(let e of Object.values(ut))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function X1(){return Gt(),Object.entries(ut).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===vt&&s.id===Ze}))}))}function V1(){Gt();let t=[];for(let[e,s]of Object.entries(ut)){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 J1(t){Tr=Array.isArray(t)?t:[]}function Z1(){return[...Tr]}function l0(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 u0(t){let e=[vt,...Tr.filter(r=>r!==vt)],s,o=0,n=0;for(let r=0;r<e.length;r++){let i=e[r],a=ut[i];if(!a||!a.isConfigured())continue;n++;let l=U1(i);if(!l.allowed){o++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let c=r>0,u=c?Au(Ze,i):Ze;return c&&u!==Ze&&process.stderr.write(` [fallback: ${i}:${u}]
1445
- `),await t(a,i,u)}catch(c){if(s=c,!l0(c)||r>=e.length-1)throw c;if(i==="ollama"&&Cu.length>0){let u=isFallback?Au(Ze,i):Ze;for(let d of Cu)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
1446
- `),await t(a,i,d)}catch(f){if(s=f,!l0(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 Q1(t,e,s={}){Gt();let o=s.model,n=o?(()=>{let{model:i}=Pu(o);return i||o})():void 0,r=n!==o?{...s,model:n}:s;return u0((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function eC(t,e,s={}){if(Gt(),s.provider){let o=ut[s.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let n={model:s.model||Ze,...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 u0(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 tC(){Gt();let t=[];for(let[e,s]of Object.entries(ut))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function nC(){for(let t of Object.keys(ut))delete ut[t];vt=null,Ze=null,Tr=[]}d0.exports={registerProvider:$o,getProvider:W1,getActiveProvider:Nu,getActiveProviderName:H1,getActiveModelId:Y1,getActiveModel:G1,setActiveModel:z1,getModelNames:K1,parseModelSpec:Pu,listProviders:X1,listAllModels:V1,callStream:Q1,callChat:eC,getConfiguredProviders:tC,setFallbackChain:J1,getFallbackChain:Z1,resolveModelForProvider:Au,MODEL_EQUIVALENTS:Ou,OLLAMA_FALLBACK_MODELS:Cu,_reset:nC}});var Bi=Z((iO,N0)=>{var{callStream:sC,getActiveProviderName:ka,getActiveModelId:f0,getConfiguredProviders:oC,getProvider:h0,getActiveProvider:p0,parseModelSpec:m0}=dt(),{parseToolArgs:g0}=ei(),{filterToolsForModel:rC,getModelTier:xa}=Io(),{getModelBriefing:iC}=Qi(),{trackUsage:y0,estimateTokens:w0}=zr(),{MultiProgress:aC,C:rO}=it();function $0(t){return!t||typeof t!="string"?0:typeof w0=="function"?w0(t):Math.ceil(t.length/4)}var x0=15,lC=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),b0=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),k0=8,cC=2,Sa=new Map,S0=600*1e3;function uC(t,e){let s=Sa.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<S0?!1:(Sa.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Rr(t){Sa.delete(t)}function Mu(){Sa.clear()}function Lu(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 v0(t){let e=Lu(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function E0(t,e,s){let o;for(let n=0;n<=b0;n++)try{return await sC(t,e,s)}catch(r){o=r;let i=Lu(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<b0&&v0(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(c=>setTimeout(c,l).unref());continue}throw r}throw o}var _0=new Set(["ask_user","task_list"]);function T0(t){return t>=2?new Set([..._0,"spawn_agents"]):_0}var dC=new Set(["write_file","edit_file","patch_file"]),R0={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:""}},fC=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,hC=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function C0(t){return hC.test(t)?"full":fC.test(t)?"essential":t.length>300?"full":"standard"}function A0(t){let e=oC(),s=ka(),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(xa(r.id,n.name)===t)return{provider:n.name,model:r.id};return null}var pC={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:n,model:r}=m0(t.model),i=n?h0(n):p0(),a=n||ka();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=xa(r,a);return{provider:a,model:r,tier:l}}}let e=C0(t.task),s=pC[e];if(s){let{provider:n,model:r}=m0(s),i=n?h0(n):p0(),a=n||ka();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=xa(r,a);return{provider:a,model:r,tier:l}}}let o=A0(e);if(o){let n=xa(o.model,o.provider);return{provider:o.provider,model:o.model,tier:n}}return{provider:null,model:null,tier:null}}async function O0(t,e={},s=0){let o=s===0?x0:k0,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,c=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
1435
+ `),fo=w,po=Date.now()),Ps=null,jt=null}if(!xo.skipSummaries){let w=c0.filter((B,G)=>!(xe[G]&&xe[G].fnName==="ask_user"));for(let B of w)fu(B,wu,bu)||(console.log(B),wu=B,bu=Date.now());let y=xe.filter(B=>B&&B.fnName!=="ask_user").map(B=>B.fnName),Y=Iw.record(0,y,Se,J);Y&&UR(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:"))&&(Bn++,Bn>=Wu)){L(`${h.red} \u2716 Loop abort: ${Bn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);return}}let Da=!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(`
1436
+ `)[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=Ut.get(y.args.path)||0;Ut.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)Ut.has(R)||(Ut.set(R,1),L(`${h.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${R.split("/").pop()}"${h.reset}`))}if(!G&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(B)){if(Dn++,Dn>=2){L(`${h.yellow} \u26A0 File-not-found streak: ${Dn} consecutive misses \u2014 forcing search${h.reset}`);let A={role:"user",content:`[SYSTEM] ${Dn} 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")&&(Dn=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(`${h.yellow} \u26A0 Temp file: "${A}" \u2014 delete with bash rm when done to keep the workspace clean${h.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){Ut.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(`${h.green} \u2713 TODO done: ${R.file}${h.reset}`));let A=ws(jw,y.args.path),U=y.args.path.split("/").slice(-2).join("/");if(A===Dw){L(`${h.yellow} \u26A0 Loop warning: "${U}" edited ${A}\xD7 \u2014 possible edit loop${h.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>=qw){L(`${h.red} \u2716 Loop abort: "${U}" edited ${A}\xD7 \u2014 aborting to prevent runaway loop${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);return}ye&&Te==="verify"||(yo=!0,wo=0,Da=!0)}if(G&&y.canExecute&&ye&&(qn=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)){Yt=0,Gt=!1,tn=0,zt++;let I=y.args?.path||y.args?.file_path;I&&(y.fnName==="write_file"?(bs.add(I),yn.delete(I),En.delete(I),Ts.delete(I)):(bs.delete(I),uu(yn,I,1),En.delete(I),Ts.add(I)))}else if(A.includes(y.fnName)){if(Yt++,Gt&&tn++,ye&&Te==="implement"&&y.fnName==="read_file"){let I=y.args?.path||y.args?.file_path||"";if(I&&bs.has(I)){let $e={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($e),T.push($e),L(`${h.yellow} \u26A0 Fresh-write nudge: ${I} \u2014 refactor directly after re-read${h.reset}`)}}if(ye&&Te==="implement"&&y.fnName==="read_file"&&Es.length>0){let I=y.args?.path||y.args?.file_path||"",$e=Es.find(Ee=>!Ee.done&&I.endsWith(Ee.file.split("/").pop()));if($e){let Ee={role:"user",content:`[TODO OBSERVER] You already analyzed "${$e.file}" in the plan phase. Action: ${$e.action}
1437
+ Do NOT re-read \u2014 apply the edit directly with edit_file.`};O.push(Ee),T.push(Ee),L(`${h.yellow} \u26A0 TODO nudge: ${$e.file} \u2014 already analyzed, edit directly${h.reset}`)}}ye&&Te==="implement"&&yo&&wo<1&&(wo++,Da=!0)}ye&&Te==="verify"&&mo++,G&&k1(y)&&(yo=!1,wo=0);let R=o.postEditCap,W=ye&&Te==="implement"?Math.min(Hu,10):Hu,ue=ut?8:Ar?zt>0?4:6:Ht?zt>0?6:10:zt>0?R:W,be=6,te=!ye&&Gt&&(ut&&tn>=be||Ht&&zt>=3&&tn>=be||tn>=be);if(fr<2&&!Gt&&Yt>=3&&J.size===0){let I=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,$e=Date.now()-Pe,Ee=fr===0?.4:.65;if(I>0&&$e>I*Ee){fr++;let Ue=Math.round($e/6e4),Xe=Math.round($e/I*100);L(`${h.yellow} \u26A0 Time nudge #${fr}: ${Ue}m elapsed (${Xe}%), ${Yt} reads, 0 edits${h.reset}`);let Dt={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(Dt),T.push(Dt)}}if(te&&A.includes(y.fnName)){let I=ut?`root cause already identified (${St})`:tn>=be?`${Yt} consecutive reads without an edit`:`${zt} file edit(s) already made`;L(`${h.red} \u2716 Blocked read-only tool: cap fired, ${I}${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:ut?`BLOCKED: root cause already identified (${St}). Use edit_file to fix the issue \u2014 do not read more files.`:Ht?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":tn>=be?`BLOCKED: You have read ${Yt} files without making any edits. Stop investigating and either implement a fix with edit_file/write_file, or write your diagnosis as text output. Do not read more files.`:`BLOCKED: ${zt} file edit(s) already made and post-edit investigation cap reached. The fix is in place. Do not read more files \u2014 proceed with the task.`,tool_call_id:y.callId}}else if(Yt>=ue&&!Gt){if(Gt=!0,Ar&&(Na=!0),L(`${h.yellow} \u26A0 Investigation cap: ${Yt} read-only calls without an edit \u2014 forcing implementation${h.reset}`),ye&&Te==="plan"){let Ee=[...T].reverse().find(Dt=>Dt.role==="assistant"),Ue=typeof Ee?.content=="string"?Ee.content:"",Xe=await hr("implement",Ue);Xe&&(O.push(Xe),T.push(Xe),ze=0,Et=ys("implement"))}let I;ut?I=`[SYSTEM] Root cause was already identified (${St}). 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.":Pt?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 $e={role:"user",content:I};O.push($e),T.push($e)}}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(Uu,A);if(U===Fw){L(`${h.yellow} \u26A0 Loop warning: same bash command run ${U}\xD7 \u2014 possible debug loop${h.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>=Bw){L(`${h.red} \u2716 Loop abort: same bash command run ${U}\xD7 \u2014 aborting runaway debug loop${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);return}}if(y.fnName==="ssh_exec"){Wt++;{let R=(et[w]?.content??"").split(`
1438
+ `).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===ma?_s++:(ma=R,_s=1),_s===3&&!Pt){L(`${h.yellow} \u26A0 SSH repeated-error: "${R.slice(0,60)}" returned ${_s}\xD7 \u2014 nudging to change approach${h.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 ma="",_s=0}if(Wt>=o0){L(`${h.red} \u2716 SSH storm abort: ${Wt} consecutive ssh_exec calls \u2014 aborting${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);return}else if(Wt===$o){{let R=pt(),{messages:W}=hn(T,R);T=W}Pt=!0,oa++,L(`${h.yellow} \u26A0 SSH storm warning (#${oa}): ${Wt} consecutive ssh_exec calls \u2014 blocking further SSH${h.reset}`);let U={role:"user",content:ut?`[SYSTEM WARNING] ${Wt} consecutive SSH calls. Root cause identified (${St}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Wt} 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&&(Wt=0);if(y.fnName==="bash"&&y.canExecute){let R=(et[w]?.content??"").split(`
1439
+ `).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===ga?xs++:(ga=R,xs=1),xs===3){L(`${h.yellow} \u26A0 Bash repeated-error: "${R.slice(0,60)}" returned ${xs}\xD7 \u2014 nudging to change approach${h.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 ga="",xs=0}if(y.fnName==="bash"&&y.canExecute&&!du&&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"))){du=!0,pr=0,L(`${h.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${h.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(du&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(pr++,pr>2)){L(`${h.yellow} \u26A0 Post-commit git verification blocked (call ${pr})${h.reset}`);let U={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(pr-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(`
1440
+ `);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(Ta++,Ta===3){L(`${h.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${h.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&&(Ta=0)}if(G&&y.fnName==="grep"&&y.args&&y.args.pattern){let A=`${y.args.pattern}|${y.args.path||""}`,U=ws(Uw,A);if(U===Ww){L(`${h.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${U}\xD7 \u2014 possible search loop${h.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>=Hw){L(`${h.red} \u2716 Loop abort: grep pattern run ${U}\xD7 \u2014 aborting runaway search loop${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);return}if(y.args.path){let R=ws(Ra,y.args.path),W=mn(As,y.args.path)>=1;if(R===(W?1:Yw)){let be=y.args.path.split("/").slice(-2).join("/");L(`${h.yellow} \u26A0 Loop warning: "${be}" grepped ${R}\xD7 with different patterns \u2014 context flood risk${h.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(`
1441
+ `);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(Gw,A);if(U===zw){L(`${h.yellow} \u26A0 Loop warning: glob pattern "${A.slice(0,40)}" run ${U}\xD7 \u2014 possible search loop${h.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>=Kw){L(`${h.red} \u2716 Loop abort: glob pattern run ${U}\xD7 \u2014 aborting runaway search loop${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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();ca.has(ue)||ca.set(ue,new Set);let be=ca.get(ue);if(be.add(A),be.size===Vw){L(`${h.red} \u2716 Glob core-term block: ${be.size} different patterns all searching for "${ue}" \u2014 search loop${h.reset}`);let te={role:"user",content:`[SYSTEM WARNING] You have searched for "${ue}" using ${be.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(be.size===Xw){L(`${h.yellow} \u26A0 Glob core-term warning: ${be.size} different patterns searching for "${ue}"${h.reset}`);let te={role:"user",content:`[SYSTEM WARNING] ${be.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=pt();if(en(T,U).percentage>=60){let{messages:W,tokensRemoved:ue}=hn(T,U);ue>0&&(T=W,console.log(`${h.dim} [pre-stop-compress \u2014 ~${ue} tokens freed before STOP injection, now ${Math.round(en(T,U).percentage)}%]${h.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(`${h.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${h.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(`${h.dim} [bash write detected: _bashModifiedFiles=${Cs}]${h.reset}`)),Y.startsWith("BLOCKED:")){if(Bn++,Bn>=Wu){L(`${h.red} \u2716 Loop abort: ${Bn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);return}}else Bn=0;if(G)Fn=0,Oa=!0;else if(Fn++,Fn===e0){L(`${h.yellow} \u26A0 Loop warning: ${Fn} consecutive tool errors \u2014 possible stuck loop${h.reset}`);let A={role:"user",content:`[SYSTEM WARNING] ${Fn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};O.push(A),T.push(A)}else if(Fn>=t0){L(`${h.red} \u2716 Loop abort: ${Fn} consecutive errors \u2014 aborting stuck loop${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);return}if(G&&y.fnName==="read_file"&&y.args&&y.args.path){Se.add(y.args.path),bs.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,be=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,be])}if(y._scrollWarn){let{sectionCount:ue,path:be}=y._scrollWarn,te={role:"user",content:`[SYSTEM WARNING] "${be}" \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(`${h.yellow} \u26A0 Scroll warning: "${be.split("/").slice(-2).join("/")}" \u2014 ${ue} sections read \u2014 use grep instead${h.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===Jw){{let be=pt();if(en(T,be).percentage>=60){let{messages:I}=hn(T,be);T=I}}L(`${h.yellow} \u26A0 Loop warning: "${U}" read unbounded ${A}\xD7 \u2014 use line_start/line_end${h.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>=Zw){L(`${h.red} \u2716 Loop abort: "${U}" read unbounded ${A}\xD7 \u2014 aborting runaway read loop${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,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(Un++,Un===n0){L(`${h.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Un}\xD7 in a row${h.reset}`);let R={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Un}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};O.push(R),T.push(R)}else if(Un>=s0){console.log(`${h.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Un}\xD7 \u2014 aborting stuck swarm${h.reset}`),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe,{suppressHint:!0}),Oe(O);return}}else A>0&&(Un=0)}}if(Da&&yo&&!(ye&&Te==="verify")){let w=await Ou(J),y=await _a(J),Y={role:"user",content:x1(J,w,y)};O.push(Y),T.push(Y),L(`${h.cyan} \u21B3 Post-edit verify prompt injected (${w.length} checks, ${y.length} tests)${h.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)+`
1442
+ ...(truncated ${G-j} chars \u2014 per-message budget)`},y-=G-j)}}}for(let w of et)O.push(w),T.push(w);let u0=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 hR(Y)&&typeof et[y]?.content=="string"&&!et[y].content.startsWith("ERROR")&&!et[y].content.startsWith("BLOCKED:")});if(ks()&&!s.skillLoop&&Na&&u0){L(`${h.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${h.reset}`),Ie(H,oe,J,Se,Pe),Oe(O);break e}if(ra(O,T),!ut)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=cu(y.content);if(Y){ut=!0,St=Y.slice(0,120),Yt=0,Gt=!1,tn=0,L(`${h.yellow} \u26A1 Root cause detected: ${St} \u2014 fix phase (read budget: 3)${h.reset}`);let B={role:"user",content:`[SYSTEM] Root cause identified: ${St}. 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(`${h.green} \u2714 Auto-matched task #${j} to ${G}: ${ae.slice(0,60)}${h.reset}`))}}}{let w=pt();if(en(T,w).percentage>=78){let{messages:Y,tokensRemoved:B}=hn(T,w);B>0&&(T=Y,console.log(`${h.dim} [auto-compressed \u2014 ~${B} tokens freed, now ${Math.round(en(T,w).percentage)}%]${h.reset}`))}}if(ks()&&!s.skillLoop&&(xe.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?Rs=0:(Rs===0&&(Bu=J.size),Rs++),Rs>=9&&H>=4&&J.size===Bu)){L(`${h.green} \u2713 Stagnation exit: ${Rs} read-only iterations, no new file changes${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Stagnation detected: ${Rs} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${h.reset}
1443
+ `),u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe),Oe(O);break e}let Qu=w1();if(Qu){let w={role:"user",content:`[User note mid-run]: ${Qu}`};O.push(w),T.push(w),console.log(`${h.cyan} \u270E Context added${h.reset}`)}}if(ze>=Et){if(u&&(u.stop(),u=null),c(null),Ie(H,oe,J,Se,Pe),Oe(O),dr(O),ye&&Te==="plan"){let Ke=[...O].reverse().find(ot=>ot.role==="assistant"),it=typeof Ke?.content=="string"?Ke.content:"",Rn=await hr("implement",it);if(Rn){O.push(Rn),T=[{role:"system",content:await Cu()},...O],Et=ys("implement"),L(`${h.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${h.reset}`);continue e}}else if(ye&&Te==="verify"){L(`${h.yellow} \u26A0 Verify budget exhausted \u2014 completing session${h.reset}`);break e}let{getActiveProviderName:_e}=dt();if(_e()==="ollama"&&Aa<zu){if(J.size===0&&!Oa){console.log(`${h.yellow} \u26A0 Max iterations reached with no progress. Stopping.${h.reset}`);break e}Aa++,Et=20,console.log(`${h.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Aa}/${zu}) \u2500\u2500${h.reset}`);continue e}if(console.log(`
1444
+ ${h.yellow}\u26A0 Max iterations reached.${h.reset}`),await Ky(" Continue for 20 more turns?")){Et=20;continue e}console.log(`${h.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${h.reset}`)}break e}await Yu()}uw.exports={processInput:F1,clearConversation:A1,getConversationLength:N1,getConversationMessages:P1,setConversationMessages:M1,setAbortSignalGetter:XR,setMaxIterations:KR,invalidateSystemPromptCache:$u,clearToolFilterCache:s1,getCachedFilteredTools:tw,buildSystemPrompt:Cu,splitSystemPrompt:C1,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Ru,getProjectContextHash:nw,_inferVerificationCommands:Ou,_inferRelevantTests:_a,_inferSymbolTargets:aw,_buildSymbolHintBlock:lw,buildUserContent:Qy,_detectImageURLs:Vy,_downloadImageURL:Jy,_grabClipboardImage:Zy,detectFrustration:ew,detectAndTruncateLoop:mu,injectMidRunNote:y1,resetSessionTracking:cw}});var dt=Z((uO,hw)=>{var{OllamaProvider:B1,getOllamaRecommendations:U1}=id(),{OpenAIProvider:W1}=ud(),{AnthropicProvider:H1}=hd(),{GeminiProvider:Y1}=wd(),{LocalProvider:G1}=_d(),{checkBudget:z1}=Kr(),Lu={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"}},Pu=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),fw={};for(let[t,e]of Object.entries(Lu))for(let s of Object.values(e))fw[s]=t;function Mu(t,e){let s=fw[t];return s&&Lu[s][e]||t}var st={},vt=null,Ze=null,Tr=[];function Mt(){if(Object.keys(st).length>0)return;bo("ollama",new B1),bo("openai",new W1),bo("anthropic",new H1),bo("gemini",new Y1),bo("local",new G1);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;st[t]?(vt=t,Ze=e||st[t].defaultModel):(vt="ollama",Ze="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(Tr=s.split(",").map(o=>o.trim()).filter(Boolean))}function bo(t,e){st[t]=e}function K1(t){return Mt(),st[t]||null}function Iu(){return Mt(),st[vt]||null}function X1(){return Mt(),vt}function V1(){return Mt(),Ze}function J1(){Mt();let t=Iu();if(!t)return{id:Ze,name:Ze,provider:vt};let e=t.getModel(Ze);return e?{...e,provider:vt}:{id:Ze,name:Ze,provider:vt}}function ju(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(st[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function Z1(t){Mt();let{provider:e,model:s}=ju(t);if(e){let n=st[e];return n&&(n.getModel(s)||e==="local"||e==="ollama")?(vt=e,Ze=s,xa(),!0):!1}let o=Iu();if(o&&o.getModel(s))return Ze=s,xa(),!0;for(let[n,r]of Object.entries(st))if(r.getModel(s))return vt=n,Ze=s,xa(),!0;return!1}function xa(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Lc();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=fn();t()}catch{}}function Q1(){Mt();let t=new Set;for(let e of Object.values(st))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function eC(){return Mt(),Object.entries(st).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===vt&&s.id===Ze}))}))}function tC(){Mt();let t=[];for(let[e,s]of Object.entries(st)){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,maxTokens:n.maxTokens,contextWindow:n.contextWindow,capability:n.capability,speed:n.speed,quality:n.quality,recommendedFor:n.recommendedFor||[]})}return t}function nC(t="coding",e={}){Mt();let s=e.limit||5,o=e.configuredOnly!==!1,n=[],r=st.ollama;if(r&&(!o||r.isConfigured()))for(let i of U1(t,s))n.push({...i,spec:`ollama:${i.id}`,provider:"ollama",configured:r.isConfigured()});if(n.length>=s)return n.slice(0,s);for(let[i,a]of Object.entries(st)){if(i==="ollama"||o&&!a.isConfigured())continue;let l=a.getModel(a.defaultModel);if(l&&(n.push({...l,spec:`${i}:${l.id}`,provider:i,configured:a.isConfigured()}),n.length>=s))break}return n}function sC(t){Tr=Array.isArray(t)?t:[]}function oC(){return[...Tr]}function dw(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 pw(t){let e=[vt,...Tr.filter(r=>r!==vt)],s,o=0,n=0;for(let r=0;r<e.length;r++){let i=e[r],a=st[i];if(!a||!a.isConfigured())continue;n++;let l=z1(i);if(!l.allowed){o++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let c=r>0,u=c?Mu(Ze,i):Ze;return c&&u!==Ze&&process.stderr.write(` [fallback: ${i}:${u}]
1445
+ `),await t(a,i,u)}catch(c){if(s=c,!dw(c)||r>=e.length-1)throw c;if(i==="ollama"&&Pu.length>0){let u=isFallback?Mu(Ze,i):Ze;for(let d of Pu)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
1446
+ `),await t(a,i,d)}catch(f){if(s=f,!dw(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 rC(t,e,s={}){Mt();let o=s.model,n=o?(()=>{let{model:i}=ju(o);return i||o})():void 0,r=n!==o?{...s,model:n}:s;return pw((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function iC(t,e,s={}){if(Mt(),s.provider){let o=st[s.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let n={model:s.model||Ze,...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 pw(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 aC(){Mt();let t=[];for(let[e,s]of Object.entries(st))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function lC(){for(let t of Object.keys(st))delete st[t];vt=null,Ze=null,Tr=[]}hw.exports={registerProvider:bo,getProvider:K1,getActiveProvider:Iu,getActiveProviderName:X1,getActiveModelId:V1,getActiveModel:J1,setActiveModel:Z1,getModelNames:Q1,parseModelSpec:ju,listProviders:eC,listAllModels:tC,recommendModels:nC,callStream:rC,callChat:iC,getConfiguredProviders:aC,setFallbackChain:sC,getFallbackChain:oC,resolveModelForProvider:Mu,MODEL_EQUIVALENTS:Lu,OLLAMA_FALLBACK_MODELS:Pu,_reset:lC}});var Ui=Z((fO,Lw)=>{var{callStream:cC,getActiveProviderName:Sa,getActiveModelId:mw,getConfiguredProviders:uC,getProvider:gw,getActiveProvider:yw,parseModelSpec:ww}=dt(),{parseToolArgs:bw}=ti(),{filterToolsForModel:dC,getModelTier:ka}=Io(),{getModelBriefing:fC}=ea(),{trackUsage:$w,estimateTokens:_w}=Kr(),{MultiProgress:pC,C:dO}=at();function xw(t){return!t||typeof t!="string"?0:typeof _w=="function"?_w(t):Math.ceil(t.length/4)}var vw=15,hC=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),kw=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Ew=8,mC=2,va=new Map,Tw=600*1e3;function gC(t,e){let s=va.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Tw?!1:(va.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Rr(t){va.delete(t)}function Du(){va.clear()}function qu(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 Rw(t){let e=qu(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Cw(t,e,s){let o;for(let n=0;n<=kw;n++)try{return await cC(t,e,s)}catch(r){o=r;let i=qu(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<kw&&Rw(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(c=>setTimeout(c,l).unref());continue}throw r}throw o}var Sw=new Set(["ask_user","task_list"]);function Aw(t){return t>=2?new Set([...Sw,"spawn_agents"]):Sw}var yC=new Set(["write_file","edit_file","patch_file"]),Ow={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:""}},wC=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,bC=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Nw(t){return bC.test(t)?"full":wC.test(t)?"essential":t.length>300?"full":"standard"}function Pw(t){let e=uC(),s=Sa(),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(ka(r.id,n.name)===t)return{provider:n.name,model:r.id};return null}var $C={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Ea(t){if(t.model){let{provider:n,model:r}=ww(t.model),i=n?gw(n):yw(),a=n||Sa();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=ka(r,a);return{provider:a,model:r,tier:l}}}let e=Nw(t.task),s=$C[e];if(s){let{provider:n,model:r}=ww(s),i=n?gw(n):yw(),a=n||Sa();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=ka(r,a);return{provider:a,model:r,tier:l}}}let o=Pw(e);if(o){let n=ka(o.model,o.provider);return{provider:o.provider,model:o.model,tier:n}}return{provider:null,model:null,tier:null}}async function Mw(t,e={},s=0){let o=s===0?vw:Ew,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,c=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
1447
1447
 
1448
1448
  TASK: ${t.task}
1449
1449
  ${t.context?`
@@ -1469,19 +1469,19 @@ TOOL STRATEGY:
1469
1469
  ERROR RECOVERY:
1470
1470
  - If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
1471
1471
  - If bash fails: read the error, fix the root cause, then retry.
1472
- - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&R0[t.type],f=d&&d.systemSuffix?`
1472
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Ow[t.type],f=d&&d.systemSuffix?`
1473
1473
 
1474
- ${d.systemSuffix}`:"",h=va(t),m=h.provider,g=h.model,$=h.tier,x=iC(g||f0()),N=[{role:"system",content:(x?`## Model Briefing
1474
+ ${d.systemSuffix}`:"",p=Ea(t),m=p.provider,g=p.model,b=p.tier,x=fC(g||mw()),N=[{role:"system",content:(x?`## Model Briefing
1475
1475
  ${x}
1476
1476
 
1477
1477
  ---
1478
1478
 
1479
- `:"")+u+f}];N.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:v,executeTool:S}=Ao(),P=T0(s),ne=rC(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}]
1480
- `)}let se={};m&&(se.provider=m),g&&(se.model=g);let ce=new Set;try{for(let re=0;re<n;re++){let le=await E0(N,ne,se);if(!le||typeof le!="object")throw new Error("Empty or invalid response from provider");{let Ne=m||ka(),ve=g||f0();if(le.usage){let _=le.usage.prompt_tokens||0,M=le.usage.completion_tokens||0;a.input+=_,a.output+=M,y0(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=$0(M),ee=$0(_);a.input+=F,a.output+=ee,a._estimated=!0,y0(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,_=g0(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(dC.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(oe=>he===oe||he.startsWith(oe+"/")||C===oe||C.startsWith(oe+"/")))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)||!uC(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"?Iu(_,s+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)+`
1481
- ...(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),re>=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 _=g0(ve.function.arguments);if((qe[Ne]?.content||"").startsWith("ERROR")&&_&&_.command){let F=_.command.replace(/\s+/g," ").trim().slice(0,100);c.set(F,(c.get(F)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${re+1}/${n}`)}for(let re of l)Rr(re);let de=[...c.entries()].filter(([,re])=>re>=3).sort((re,le)=>le[1]-re[1]).slice(0,3).map(([re,le])=>`"${re}" (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 re of l)Rr(re);return{task:t.task,status:"failed",result:`Error: ${de.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function Iu(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?lC:cC,o=e===0?x0:k0,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(u=>va(u)),l=n.map((u,d)=>{let f=a[d],h=f.model?` [${f.model}]`:"",m=u.task.substring(0,i-h.length);return`${r}Agent ${d+1}${h}: ${m}${u.task.length>m.length?"...":""}`}),c=new aC(l);c.start();try{let u=n.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 O0(N,{onUpdate:()=>{}},e).then(v=>(c.update($,v.status==="failed"?"error":"done"),v)).catch(v=>(c.update($,"error"),{task:g.task,status:"failed",result:`Error: ${v.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),Mu();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(`
1482
- `)}catch(u){return c.stop(),Mu(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function mC(t){let{createJob:e}=io(),s=(t.agents||[]).filter(i=>i.background),o=(t.agents||[]).filter(i=>!i.background),n=s.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(n.length>0&&r.push(`Background agents started: [${n.join(", ")}]
1479
+ `:"")+u+f}];N.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:v,executeTool:S}=Ao(),P=Aw(s),ne=dC(v.filter(de=>!P.has(de.function.name)),b);if(d&&d.allowedTools&&(ne=ne.filter(de=>d.allowedTools.has(de.function.name))),g&&!t._skipLog){let de=b?` (${b})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${de}]
1480
+ `)}let se={};m&&(se.provider=m),g&&(se.model=g);let ce=new Set;try{for(let re=0;re<n;re++){let le=await Cw(N,ne,se);if(!le||typeof le!="object")throw new Error("Empty or invalid response from provider");{let Ne=m||Sa(),ve=g||mw();if(le.usage){let _=le.usage.prompt_tokens||0,M=le.usage.completion_tokens||0;a.input+=_,a.output+=M,$w(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=xw(M),ee=xw(_);a.input+=F,a.output+=ee,a._estimated=!0,$w(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,_=bw(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(yC.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 pe=K.relative(process.cwd(),C);if(t._readOnlyFiles.some(oe=>pe===oe||pe.startsWith(oe+"/")||C===oe||C.startsWith(oe+"/")))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)||!gC(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"?Fu(_,s+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)+`
1481
+ ...(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),re>=7&&N.length>12)try{let{compressMessage:Ne}=fn(),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 _=bw(ve.function.arguments);if((qe[Ne]?.content||"").startsWith("ERROR")&&_&&_.command){let F=_.command.replace(/\s+/g," ").trim().slice(0,100);c.set(F,(c.get(F)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${re+1}/${n}`)}for(let re of l)Rr(re);let de=[...c.entries()].filter(([,re])=>re>=3).sort((re,le)=>le[1]-re[1]).slice(0,3).map(([re,le])=>`"${re}" (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 re of l)Rr(re);return{task:t.task,status:"failed",result:`Error: ${de.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function Fu(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?hC:mC,o=e===0?vw:Ew,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(u=>Ea(u)),l=n.map((u,d)=>{let f=a[d],p=f.model?` [${f.model}]`:"",m=u.task.substring(0,i-p.length);return`${r}Agent ${d+1}${p}: ${m}${u.task.length>m.length?"...":""}`}),c=new pC(l);c.start();try{let u=n.map((g,b)=>{let x=a[b],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 Mw(N,{onUpdate:()=>{}},e).then(v=>(c.update(b,v.status==="failed"?"error":"done"),v)).catch(v=>(c.update(b,"error"),{task:g.task,status:"failed",result:`Error: ${v.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),Du();let f=["Sub-agent results:",""],p=0,m=0;for(let g=0;g<d.length;g++){let b=d[g],x=b.status==="done"?"\u2713":b.status==="truncated"?"\u26A0":"\u2717",E=b.modelSpec?` [${b.modelSpec}]`:"";f.push(`${x} Agent ${g+1}${E}: ${b.task}`),f.push(` Status: ${b.status}`),f.push(` Tools used: ${b.toolsUsed.length>0?b.toolsUsed.join(", "):"none"}`),f.push(` Result: ${b.result}`),b.repeatedFailures&&b.repeatedFailures.length>0&&f.push(` Repeated failures: ${b.repeatedFailures.join("; ")}`),f.push(""),p+=b.tokensUsed.input,m+=b.tokensUsed.output}return f.push(`Total sub-agent tokens: ${p} input + ${m} output`),f.join(`
1482
+ `)}catch(u){return c.stop(),Du(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function _C(t){let{createJob:e}=io(),s=(t.agents||[]).filter(i=>i.background),o=(t.agents||[]).filter(i=>!i.background),n=s.map(i=>{let a=Ea(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(", ")}]
1483
1483
  `+s.map((i,a)=>` ${n[a]}: ${i.task}`).join(`
1484
1484
  `)+`
1485
- Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await Iu({agents:o});r.push(i)}return r.join(`
1485
+ Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await Fu({agents:o});r.push(i)}return r.join(`
1486
1486
 
1487
- `)||"No agents specified."}N0.exports={runSubAgent:O0,executeSpawnAgents:Iu,executeSpawnAgentsBackground:mC,clearAllLocks:Mu,classifyTask:C0,pickModelForTier:A0,resolveSubAgentModel:va,classifyError:Lu,isRetryableError:v0,callWithRetry:E0,getExcludedTools:T0,LOCK_TIMEOUT_MS:S0,SUB_AGENT_TYPES:R0}});var{runSubAgent:gC}=Bi();process.on("message",async({jobId:t,agentDef:e})=>{try{let s=await gC({...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)}});
1487
+ `)||"No agents specified."}Lw.exports={runSubAgent:Mw,executeSpawnAgents:Fu,executeSpawnAgentsBackground:_C,clearAllLocks:Du,classifyTask:Nw,pickModelForTier:Pw,resolveSubAgentModel:Ea,classifyError:qu,isRetryableError:Rw,callWithRetry:Cw,getExcludedTools:Aw,LOCK_TIMEOUT_MS:Tw,SUB_AGENT_TYPES:Ow}});var{runSubAgent:xC}=Ui();process.on("message",async({jobId:t,agentDef:e})=>{try{let s=await xC({...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)}});