nex-code 0.5.11 → 0.5.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -28
- package/dist/background-worker.js +511 -489
- package/dist/benchmark.js +559 -536
- package/dist/nex-code.js +899 -861
- package/package.json +1 -1
|
@@ -1,136 +1,147 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);this.buffer=s.pop()||"";for(let n of s){let o=this.parseLine(n);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},xr=class extends vs{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Sr=class extends Es{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:s,max_tokens:o,temperature:r};return i&&(a.stream=!0),n&&n.length>0&&(a.tools=n),a}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}createStreamParser(e,s={}){return new xr(e,s)}},Er=class extends vs{constructor(e,s={}){super(e,s),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let s=e.trim();if(!s.startsWith("data: "))return{done:!1};let n=s.slice(6),o;try{o=JSON.parse(n)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let s={};if(e.inputJson)try{s=JSON.parse(e.inputJson)}catch{s=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:s}}})}}},ba="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",vr=class extends Es{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,max_tokens:o,temperature:r};if(i&&(l.stream=!0),a?.system){let c=a.system,u=c.indexOf(ba);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+ba.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=c}return n&&n.length>0&&(l.tools=n),l}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}createStreamParser(e,s={}){return new Er(e,s)}};function Tu(t){if(t!==null&&typeof t=="object")return t;if(typeof t!="string")return t||{};try{return JSON.parse(t)}catch{}let e=t.replace(/,\s*([}\]])/g,"$1");e=e.replace(/([^\\])\n/g,"$1\\n");try{return JSON.parse(e)}catch{}return{}}var Tr=class extends vs{constructor(e,s={}){super(e,s),this.toolCalls=[],this.onThinkingToken=s.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let s;try{s=JSON.parse(e)}catch{return{done:!1}}return s.message?.thinking&&this.onThinkingToken(s.message.thinking),s.message?.content&&(this.onToken(s.message.content),this.content+=s.message.content),s.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(s.message.tool_calls)),s.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,s)=>({id:e.id||`ollama-${Date.now()}-${s}`,function:{name:e.function?.name||e.name||"unknown",arguments:Tu(e.function?.arguments??e.arguments)}}))}}},Rr=class extends Es{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(l.tools=n),l}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:(s.tool_calls||[]).map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:Tu(n.function?.arguments??n.arguments)}}))}}createStreamParser(e,s={}){return new Tr(e,s)}},y0=new Sr,w0=new vr,$0=new Rr;Ru.exports={ANTHROPIC_CACHE_BOUNDARY:ba,WireProtocol:Es,StreamParser:vs,OpenAICompatibleProtocol:Sr,AnthropicProtocol:vr,OllamaChatProtocol:Rr,OpenAIStreamParser:xr,AnthropicStreamParser:Er,OllamaStreamParser:Tr,openaiProtocol:y0,anthropicProtocol:w0,ollamaProtocol:$0}});var Ou=V((DR,Au)=>{var Cr=require("axios"),_0=require("http"),b0=require("https"),{BaseProvider:k0,readStreamErrorBody:x0}=Ss(),{ollamaProtocol:Fn}=Ts(),Ar=new _0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Or=new b0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Cu={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemma4:e2b":{id:"gemma4:e2b",name:"Gemma 4 E2B",maxTokens:8192,contextWindow:131072},"gemma4:e4b":{id:"gemma4:e4b",name:"Gemma 4 E4B",maxTokens:8192,contextWindow:131072},"gemma4:26b-a4b":{id:"gemma4:26b-a4b",name:"Gemma 4 26B A4B",maxTokens:16384,contextWindow:262144},"gemma4:31b":{id:"gemma4:31b",name:"Gemma 4 31B",maxTokens:16384,contextWindow:262144},"gemma4:31b-cloud":{id:"gemma4:31b-cloud",name:"Gemma 4 31B Cloud",maxTokens:16384,contextWindow:262144},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},ka=class extends k0{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Cu,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){Cr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ar,httpsAgent:Or}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Cr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ar,httpsAgent:Or})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:s.role,content:n.join(`
|
|
3
|
-
`)};return
|
|
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
|
|
5
|
-
|
|
6
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}for(let o=n.length-1;o>0;o--)n[o].role==="user"&&n[o-1].role==="user"&&n.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});o=i}else o=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:o};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return En.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,{messages:l,system:c}=this.formatMessages(e),u=this.formatTools(s),d=En.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Iu.post(`${this.baseUrl}${En.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",g=p.response?.data?.error?.message||p.response?.data?.error||p.message;throw new Error(`API Error${m}: ${g}`)}return En.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(s),f=En.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await Iu.post(`${this.baseUrl}${En.getEndpoint()}`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let $=g.response?.status?` [HTTP ${g.response.status}]`:"",k=await T0(g,M=>M?.error?.message||M?.error);throw new Error(`API Error${$}: ${k}`)}let m=En.createStreamParser(l);return new Promise((g,$)=>{n.signal&&n.signal.addEventListener("abort",()=>{p.data.destroy(),$(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",k=>{let{done:M,result:D}=m.feed(k.toString());M&&g(D)}),p.data.on("error",k=>{n.signal?.aborted||$(new Error(`Stream error: ${k.message}`))}),p.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return En.normalizeResponse(e)}};Du.exports={AnthropicProvider:Sa,ANTHROPIC_MODELS:ju}});var Wu=V((BR,Uu)=>{var Fu=require("axios"),{BaseProvider:C0,readStreamErrorBody:A0}=Ss(),{openaiProtocol:Un}=Ts(),Bu={"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",maxTokens:65536,contextWindow:1048576},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:65536,contextWindow:1048576},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",maxTokens:65536,contextWindow:1048576},"gemini-2.0-flash":{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash",maxTokens:8192,contextWindow:1048576},"gemini-2.0-flash-lite":{id:"gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite",maxTokens:8192,contextWindow:1048576},"gemini-1.5-pro":{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",maxTokens:8192,contextWindow:1048576},"gemini-1.5-flash":{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",maxTokens:8192,contextWindow:1048576}},Ea=class extends C0{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Bu,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),l=Un.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await Fu.post(`${this.baseUrl}${Un.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Un.normalizeResponse(c.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,a=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=Un.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Fu.post(`${this.baseUrl}${Un.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await A0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Un.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:$}=d.feed(m.toString());g&&f($)}),u.data.on("error",m=>{n.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Un.normalizeResponse(e)}};Uu.exports={GeminiProvider:Ea,GEMINI_MODELS:Bu}});var Gu=V((UR,Yu)=>{var Nr=require("axios"),{BaseProvider:O0,readStreamErrorBody:N0}=Ss(),{ollamaProtocol:Wn}=Ts(),Hu="http://localhost:11434",va=class extends O0{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Hu,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Nr.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await Nr.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=a.data?.model_info||a.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
|
|
7
|
-
`)};return
|
|
8
|
-
`),
|
|
9
|
-
`)}}function
|
|
10
|
-
`)}function
|
|
1
|
+
var Oa=Object.defineProperty;var T0=Object.getOwnPropertyDescriptor;var R0=Object.getOwnPropertyNames;var C0=Object.prototype.hasOwnProperty;var A0=(t,e)=>()=>(t&&(e=t(t=0)),e);var V=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),O0=(t,e)=>{for(var s in e)Oa(t,s,{get:e[s],enumerable:!0})},N0=(t,e,s,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of R0(e))!C0.call(t,n)&&n!==s&&Oa(t,n,{get:()=>e[n],enumerable:!(o=T0(e,n))||o.enumerable});return t};var M0=t=>N0(Oa({},"__esModule",{value:!0}),t);var Ts=V((p1,Du)=>{async function P0(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 Na=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`)}};Du.exports={BaseProvider:Na,readStreamErrorBody:P0}});var As=V((h1,Fu)=>{var Rs=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")}},Cs=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")}},Ar=class extends Cs{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}}))}}},Or=class extends Rs{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 Ar(e,s)}},Nr=class extends Cs{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}}})}}},Ma="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Mr=class extends Rs{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(Ma);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+Ma.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 Nr(e,s)}};function qu(t){if(t!==null&&typeof t=="object")return t;if(typeof t!="string")return t||{};try{return JSON.parse(t)}catch{}let e=t.replace(/,\s*([}\]])/g,"$1");e=e.replace(/([^\\])\n/g,"$1\\n");try{return JSON.parse(e)}catch{}return{}}var Pr=class extends Cs{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:qu(e.function?.arguments??e.arguments)}}))}}},Lr=class extends Rs{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:qu(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,s={}){return new Pr(e,s)}},L0=new Or,I0=new Mr,j0=new Lr;Fu.exports={ANTHROPIC_CACHE_BOUNDARY:Ma,WireProtocol:Rs,StreamParser:Cs,OpenAICompatibleProtocol:Or,AnthropicProtocol:Mr,OllamaChatProtocol:Lr,OpenAIStreamParser:Ar,AnthropicStreamParser:Nr,OllamaStreamParser:Pr,openaiProtocol:L0,anthropicProtocol:I0,ollamaProtocol:j0}});var Wu=V((m1,Uu)=>{var Ir=require("axios"),D0=require("http"),q0=require("https"),{BaseProvider:F0,readStreamErrorBody:B0}=Ts(),{ollamaProtocol:Fn}=As(),jr=new D0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Dr=new q0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Bu={"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}},Pa=class extends F0{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Bu,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){Ir.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:jr,httpsAgent:Dr}).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 Ir.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:jr,httpsAgent:Dr})).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=Fn.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 Ir.post(`${this.baseUrl}${Fn.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:jr,httpsAgent:Dr})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=c.response?.data?.error||c.message;throw new Error(`API Error${u}: ${d}`)}return Fn.normalizeResponse(l.data)}async stream(e,s,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=Fn.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 Ir.post(`${this.baseUrl}${Fn.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:jr,httpsAgent:Dr})}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 B0(f,$=>$?.error),g=new Error(`API Error${p}: ${m}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=Fn.createStreamParser(a,{onThinkingToken:l});return new Promise((f,p)=>{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:$}=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,p(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Fn.normalizeResponse(e)}};Uu.exports={OllamaProvider:Pa,OLLAMA_MODELS:Bu}});var zu=V((g1,Yu)=>{var Hu=require("axios"),{BaseProvider:U0,readStreamErrorBody:W0}=Ts(),{openaiProtocol:Bn}=As(),Gu={"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}},La=class extends U0{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Gu,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=Bn.buildRequestBody({model:n,messages:a,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),c;try{c=await Hu.post(`${this.baseUrl}${Bn.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 Bn.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=Bn.buildRequestBody({model:n,messages:l,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),u;try{u=await Hu.post(`${this.baseUrl}${Bn.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 W0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Bn.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:$}=d.feed(m.toString());g&&f($)}),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 Bn.normalizeResponse(e)}};Yu.exports={OpenAIProvider:La,OPENAI_MODELS:Gu}});var Ju=V((y1,Vu)=>{var Ku=require("axios"),{BaseProvider:H0,readStreamErrorBody:G0}=Ts(),{anthropicProtocol:vn}=As(),Xu={"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}},Y0="2023-06-01",Ia=class extends H0{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Xu,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Y0}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 vn.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=vn.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Ku.post(`${this.baseUrl}${vn.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 vn.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=vn.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await Ku.post(`${this.baseUrl}${vn.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 G0(g,T=>T?.error?.message||T?.error);throw new Error(`API Error${$}: ${x}`)}let m=vn.createStreamParser(l);return new Promise((g,$)=>{o.signal&&o.signal.addEventListener("abort",()=>{p.data.destroy(),$(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",x=>{let{done:T,result:A}=m.feed(x.toString());T&&g(A)}),p.data.on("error",x=>{o.signal?.aborted||$(new Error(`Stream error: ${x.message}`))}),p.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return vn.normalizeResponse(e)}};Vu.exports={AnthropicProvider:Ia,ANTHROPIC_MODELS:Xu}});var td=V((w1,ed)=>{var Zu=require("axios"),{BaseProvider:z0,readStreamErrorBody:K0}=Ts(),{openaiProtocol:Un}=As(),Qu={"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}},ja=class extends z0{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Qu,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=Un.buildRequestBody({model:n,messages:a,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),c;try{c=await Zu.post(`${this.baseUrl}${Un.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 Un.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=Un.buildRequestBody({model:n,messages:l,tools:s,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),u;try{u=await Zu.post(`${this.baseUrl}${Un.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 K0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Un.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:$}=d.feed(m.toString());g&&f($)}),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 Un.normalizeResponse(e)}};ed.exports={GeminiProvider:ja,GEMINI_MODELS:Qu}});var od=V(($1,sd)=>{var qr=require("axios"),{BaseProvider:X0,readStreamErrorBody:V0}=Ts(),{ollamaProtocol:Wn}=As(),nd="http://localhost:11434",Da=class extends X0{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||nd,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 qr.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 qr.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=Wn.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await qr.post(`${this.baseUrl}${Wn.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 Wn.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=Wn.buildRequestBody({model:n,messages:this._formatMessages(e),tools:s,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await qr.post(`${this.baseUrl}${Wn.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 V0(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=Wn.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 Wn.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}};sd.exports={LocalProvider:Da,DEFAULT_LOCAL_URL:nd}});var Ht=V((b1,dd)=>{"use strict";var rd="\x1B[0m",id="\x1B[1m",Os="\x1B[2m";function Y(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function J0(){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 ad(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Z0(t){try{let s=require("fs").readFileSync(ad(),"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 Q0(t,e){try{let s=require("fs"),o=require("path"),n=ad(),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 ew(){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=Z0(s);if(o!==null)return o;let n=J0(),r=n!==null?n:!0;return Q0(s,r),r}var ld=ew(),cd={reset:rd,bold:id,dim:Os,primary:Y(80,190,255),secondary:Y(60,170,190),success:Y(80,210,120),warning:Y(245,175,50),error:Y(230,80,80),muted:Os,subtle:Y(130,130,145),tool_read:Y(80,190,255),tool_write:Y(245,165,55),tool_exec:Y(185,100,235),tool_search:Y(70,185,190),tool_git:Y(90,210,100),tool_web:Y(100,215,250),tool_sysadmin:Y(225,150,75),tool_default:Y(100,205,115),syn_keyword:Y(185,100,235),syn_string:Y(90,210,120),syn_number:Y(245,175,50),syn_comment:Os,syn_key:Y(80,190,255),diff_add:Y(80,210,120),diff_rem:Y(230,80,80),banner_logo:Y(80,200,255),banner_name:Y(80,200,255),banner_version:Os,banner_model:Os,banner_yolo:Y(245,175,50),banner_gemini:Y(138,180,248),footer_sep:Os,footer_model:Y(80,175,235),footer_branch:Y(80,210,100),footer_project:Y(130,130,145),footer_divider:Y(80,80,95),footer_mode:Y(210,150,50),white:Y(210,210,220),red:Y(220,85,85),green:Y(80,200,110),yellow:Y(230,185,60),blue:Y(70,140,230),magenta:Y(200,120,190),cyan:Y(90,200,215),gray:Y(120,120,135),bgRed:"\x1B[48;2;140;40;40m",bgGreen:"\x1B[48;2;30;100;50m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:Y(110,215,230),brightMagenta:Y(220,140,210),brightBlue:Y(100,160,240)},ud={reset:rd,bold:id,dim:Y(110,110,120),primary:Y(0,110,190),secondary:Y(0,125,148),success:Y(0,148,62),warning:Y(168,92,0),error:Y(188,32,32),muted:Y(110,110,120),subtle:Y(155,155,165),tool_read:Y(0,110,190),tool_write:Y(168,92,0),tool_exec:Y(128,42,188),tool_search:Y(0,122,148),tool_git:Y(0,138,62),tool_web:Y(0,112,178),tool_sysadmin:Y(168,82,0),tool_default:Y(0,138,62),syn_keyword:Y(128,42,188),syn_string:Y(0,138,62),syn_number:Y(168,92,0),syn_comment:Y(135,135,148),syn_key:Y(0,110,190),diff_add:Y(0,148,62),diff_rem:Y(188,32,32),banner_logo:Y(0,122,205),banner_name:Y(0,122,205),banner_version:Y(100,100,118),banner_model:Y(100,100,118),banner_yolo:Y(168,62,0),banner_gemini:Y(26,115,232),footer_sep:Y(168,168,178),footer_model:Y(0,102,175),footer_branch:Y(0,138,62),footer_project:Y(135,135,148),footer_divider:Y(168,168,178),footer_mode:Y(148,88,0),white:Y(40,40,52),red:Y(188,32,32),green:Y(0,148,62),yellow:Y(168,92,0),blue:Y(0,110,190),magenta:Y(128,42,188),cyan:Y(0,125,148),gray:Y(132,132,142),bgRed:"\x1B[48;2;180;50;50m",bgGreen:"\x1B[48;2;30;130;60m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:Y(0,158,182),brightMagenta:Y(158,52,208),brightBlue:Y(0,112,208)},tw=ld?cd:ud;dd.exports={T:tw,isDark:ld,DARK:cd,LIGHT:ud}});var Hn=V((_1,pd)=>{"use strict";var Et=require("fs"),fd=require("path");function nw(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function sw(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function ow(t,e){let s=fd.dirname(t),o=fd.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{Et.existsSync(s)||Et.mkdirSync(s,{recursive:!0,mode:448}),Et.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Et.renameSync(o,t)}catch(n){try{Et.unlinkSync(o)}catch{}throw n}}function rw(t,e,{timeout:s=5e3,retryMs:o=50}={}){let n=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=Et.openSync(n,"wx"),Et.writeSync(i,Buffer.from(String(process.pid))),Et.closeSync(i),i=-1;try{return e()}finally{try{Et.unlinkSync(n)}catch{}}}catch(a){if(i!==-1)try{Et.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=Et.readFileSync(n,"utf-8").trim(),c=parseInt(l,10);if(!nw(c)){try{Et.unlinkSync(n)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Et.unlinkSync(n)}catch{}return e()}sw(o)}}}pd.exports={atomicWrite:ow,withFileLockSync:rw}});var Br=V((k1,_d)=>{var Ns=require("fs"),qa=require("path"),{T:hd}=Ht(),{atomicWrite:iw,withFileLockSync:aw}=Hn(),md={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:{}},Fr=[],Tn={};function lw(t,e,s,o,n=0){if(Fr.push({provider:t,model:e,input:s,output:o,cacheRead:n}),Tn[t]!==void 0){let r=$d(t);r.allowed||process.stderr.write(`${hd.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${hd.reset}
|
|
9
|
+
`)}}function Fa(t,e){let s=md[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function gd(t){let e=Fa(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function yd(){let t={};for(let i of Fr){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:gd(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 cw(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:o}=yd();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 uw(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function dw(t,e,s,o){let n=Fa(t,e),r=(s*n.input+o*n.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function fw(){Fr=[]}function pw(t,e){Tn[t]=e}function hw(t){delete Tn[t]}function mw(){return{...Tn}}function wd(t){let e=0;for(let s of Fr)s.provider===t&&(e+=gd(s));return e}function $d(t){let e=wd(t),s=Tn[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 bd(){let t=qa.join(process.cwd(),".nex","config.json");if(Ns.existsSync(t))try{let e=JSON.parse(Ns.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Tn={...e.costLimits})}catch{}}function gw(){let t=qa.join(process.cwd(),".nex"),e=qa.join(t,"config.json");Ns.existsSync(t)||Ns.mkdirSync(t,{recursive:!0}),aw(e,()=>{let s={};if(Ns.existsSync(e))try{s=JSON.parse(Ns.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Tn,iw(e,JSON.stringify(s,null,2))})}function yw(){Tn={}}bd();_d.exports={PRICING:md,trackUsage:lw,getSessionCosts:yd,formatCosts:cw,formatCostHint:dw,resetCosts:fw,getPricing:Fa,setCostLimit:pw,removeCostLimit:hw,getCostLimits:mw,getProviderSpend:wd,checkBudget:$d,loadCostLimits:bd,saveCostLimits:gw,resetCostLimits:yw,estimateTokens:uw}});var Ba=V((x1,ww)=>{ww.exports={name:"nex-code",version:"0.5.12",description:"Run 400B+ open coding models on your codebase without the hardware bill. Ollama Cloud first \u2014 OpenAI, Anthropic, and Gemini when you need them.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","examples/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --forceExit --maxWorkers=50%","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",format:"prettier --write .","install-hooks":"ln -sf ../../hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-commit, pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0",prettier:"^3.8.1",typescript:"^5.9.3"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var Gn=V((S1,Sd)=>{var{T:J}=Ht(),Hr=5,Ms=(()=>{let t=[];for(let e=0;e<Hr;e++)t.push(e);for(let e=Hr-2;e>=1;e--)t.push(e);return t})(),kd=["\u273D","\u2726","\u2727","\u2726"];function xd(t=""){let e=String(t).toLowerCase();return e.includes("search")||e.includes("read")||e.includes("list")||e.includes("inspect")?{glyph:"\u25CC",color:J.cyan,accent:"scan"}:e.includes("write")||e.includes("edit")||e.includes("patch")||e.includes("build")?{glyph:"\u2726",color:J.yellow,accent:"shape"}:e.includes("test")||e.includes("diff")||e.includes("check")||e.includes("verify")?{glyph:"\u25A3",color:J.green,accent:"verify"}:e.includes("wait")||e.includes("github")||e.includes("fetch")||e.includes("browser")?{glyph:"\u25CD",color:J.blue,accent:"wait"}:{glyph:"\u25CF",color:J.cyan,accent:"think"}}var Ua=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Ms[this.frame%Ms.length],s=xd(this.text),o="";for(let r=0;r<Hr;r++)o+=r===e?`${s.color}${s.glyph}${J.reset}`:" ";let n="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);if(r>=60){let i=Math.floor(r/60),a=r%60;n=` ${J.dim}${i}m ${String(a).padStart(2,"0")}s${J.reset}`}else r>=1&&(n=` ${J.dim}${r}s${J.reset}`)}process.stderr.write(`\x1B[2K\r${s.color}${s.accent.toUpperCase()}${J.reset} ${o} ${J.dim}${this.text}${J.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},Wa=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=Ms[this.frame%Ms.length],s=`${J.cyan}\u25CC${J.reset}`,o=this._formatElapsed(),n=o?` ${J.dim}${o}${J.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let l,c;switch(this.statuses[a]){case"done":l=`${J.green}\u2713${J.reset}`,c=J.dim;break;case"error":l=`${J.red}\u2717${J.reset}`,c=J.dim;break;case"retry":l=`${J.yellow}\u21BB${J.reset}`,c=J.yellow;break;default:l=a===e?s:`${J.dim}\xB7${J.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}${J.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
|
-
`;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
|
|
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?` ${
|
|
14
|
-
`}process.stderr.write(
|
|
15
|
-
`;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"
|
|
12
|
+
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let s="";for(let o=0;o<this.lineCount;o++)s+=`\x1B[2K
|
|
13
|
+
`;this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${J.dim}${e}${J.reset}`:"",o=process.stderr.columns||80,n="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${J.green}\u2713${J.reset}`;break;case"error":i=`${J.red}\u2717${J.reset}`;break;case"retry":i=`${J.yellow}\u21BB${J.reset}`;break;default:i=`${J.yellow}\u25CB${J.reset}`}let a=r===this.labels.length-1?s:"",l=o-4-(a?e.length+1:0),c=this.labels[r].length>l?this.labels[r].substring(0,Math.max(10,l-3))+"...":this.labels[r];n+=`\x1B[2K ${i} ${J.dim}${c}${J.reset}${a}
|
|
14
|
+
`}process.stderr.write(n)}},Ur={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Wr={done:J.green,in_progress:J.cyan,pending:J.dim,failed:J.red},Rn=null,Ha=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=kd[this.frame%kd.length],s=this._formatElapsed(),o=this._formatTokens(),n=[s,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=n?` ${J.dim}(${n})${J.reset}`:"",i=`\x1B[2K${J.cyan}${J.bold}${e}${J.reset} ${J.bold}${this.name}${J.reset}${J.dim}\u2026${J.reset}${r}
|
|
15
|
+
`;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=Ur[l.status]||Ur.pending,d=Wr[l.status]||Wr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${J.dim}${c}${J.reset} ${d}${u}${J.reset} ${f}
|
|
16
16
|
`}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
17
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
17
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Rn=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,Rn===this&&(Rn=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
|
|
18
18
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
19
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let
|
|
20
|
-
`;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"
|
|
21
|
-
`}process.stderr.write(i)}},
|
|
22
|
-
`);let
|
|
23
|
-
`),
|
|
24
|
-
`),n=s.slice(0,
|
|
25
|
-
`);return o
|
|
26
|
-
|
|
27
|
-
`)
|
|
28
|
-
|
|
29
|
-
`).
|
|
30
|
-
`).length,c=
|
|
31
|
-
`);
|
|
32
|
-
${
|
|
33
|
-
`);
|
|
34
|
-
${
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
`):
|
|
40
|
-
|
|
41
|
-
`)
|
|
42
|
-
`).
|
|
43
|
-
`)
|
|
44
|
-
`).
|
|
45
|
-
${m(
|
|
46
|
-
|
|
47
|
-
`)
|
|
48
|
-
`).filter(
|
|
49
|
-
`).
|
|
50
|
-
`).filter(
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
`).
|
|
54
|
-
`)
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
`)
|
|
58
|
-
|
|
59
|
-
|
|
19
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let o=this.tasks.find(n=>n.id===e);o&&(o.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(a=>a.status==="done").length,o=this.tasks.filter(a=>a.status==="failed").length,n=this.tasks.length,r=o>0?`${s}/${n} done, ${o} failed`:`${s}/${n} done`,i=`\x1B[2K${J.green}${J.bold}\u2714${J.reset} ${J.bold}${this.name}${J.reset} ${J.dim}(${e} \xB7 ${r})${J.reset}
|
|
20
|
+
`;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=Ur[l.status]||Ur.pending,d=Wr[l.status]||Wr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${J.dim}${c}${J.reset} ${d}${u}${J.reset} ${J.dim}${f}${J.reset}
|
|
21
|
+
`}process.stderr.write(i)}},Ga=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=Ms[this.frame%Ms.length],s=xd(this.message),o="";for(let i=0;i<Hr;i++)o+=i===e?`${s.color}${s.glyph}${J.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${J.cyan}${this.count}${J.reset}`,this.total&&(n+=`/${this.total}`)),this.detail&&(n+=` ${J.dim}${this.detail}${J.reset}`);let r="";if(this.startTime){let i=Math.floor((Date.now()-this.startTime)/1e3);i>=1&&(r=` ${J.dim}${i}s${J.reset}`)}process.stderr.write(`\x1B[2K\r${s.color}${s.accent.toUpperCase()}${J.reset} ${o} ${J.dim}${n}${J.reset}${r}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function $w(t){Rn=t}function bw(){return Rn}function _w(){Rn&&(Rn.stop(),Rn=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Sd.exports={C:J,Spinner:Ua,MultiProgress:Wa,TaskProgress:Ha,ToolProgress:Ga,setActiveTaskProgress:$w,getActiveTaskProgress:bw,cleanupTerminal:_w}});var mo=V((E1,Cd)=>{"use strict";var{T:Yn}=Ht(),ue={kw:Yn.syn_keyword,str:Yn.syn_string,cmt:Yn.syn_comment,num:Yn.syn_number,type:Yn.cyan,punct:Yn.magenta,reset:Yn.reset},Ed={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"])},kw={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 Td(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return kw[e]||null}var vd=/\x1b\[[0-9;]*m/g;function mn(t,e,s){let o=t.split(vd),n=t.match(vd)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,s),i<n.length&&(r+=n[i]);return r}function xw(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,s=>ue.type+s+ue.reset),e=mn(e,/"([^"\\]|\\.)*"/g,s=>ue.str+s+ue.reset),e=mn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,s=>ue.num+s+ue.reset),e=mn(e,/\b(true|false|null)\b/g,s=>ue.kw+s+ue.reset),e}function Sw(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,s=>ue.cmt+s+ue.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(s,o,n)=>o+ue.type+n+ue.reset),e=mn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(s,o)=>" "+ue.kw+o+ue.reset+"="),e=mn(e,/"([^"]*)"/g,s=>ue.str+s+ue.reset),e}function Ew(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,s=>ue.cmt+s+ue.reset),e=mn(e,/#[0-9a-fA-F]{3,8}\b/g,s=>ue.num+s+ue.reset),e=mn(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(s,o,n)=>ue.num+o+ue.reset+n),e=mn(e,/([a-z][a-z-]*)(\s*:)/g,(s,o,n)=>ue.type+o+ue.reset+n),e=mn(e,/"[^"]*"|'[^']*'/g,s=>ue.str+s+ue.reset),e}function Rd(t,e,s){if(e==="json")return xw(t);if(e==="html"||e==="xml")return Sw(t);if(e==="css")return Ew(t);if(e==="md")return t;let o=Ed[e]||Ed.js,n="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ue.cmt+t+ue.reset;if(n+=ue.cmt+t.slice(0,i+2)+ue.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return n}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return ue.str+t+ue.reset;if(n+=ue.str+t.slice(0,i+1)+ue.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+=ue.cmt+t.slice(r)+ue.reset,s.inBlockComment=!0,n;n+=ue.cmt+t.slice(r,a+2)+ue.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+=ue.cmt+t.slice(r)+ue.reset,n;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,n+=ue.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+ue.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+=ue.num+a+ue.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+=ue.punct+a+ue.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+=ue.kw+a+ue.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?n+=ue.type+a+ue.reset:n+=a;continue}n+=i,r++}return s.inString&&s.inString!=="`"&&(n+=ue.reset,s.inString=null),n}function vw(t,e){let s=Td(e);if(!s)return t.split(`
|
|
22
|
+
`);let o=t.split(`
|
|
23
|
+
`),n={inString:null,inBlockComment:!1};return o.map(r=>Rd(r,s,n))}function Tw(t,e){return e?Rd(t,e,{inString:null,inBlockComment:!1}):t}Cd.exports={detectLang:Td,highlightLine:Tw,highlightLines:vw}});var Id=V((v1,Ld)=>{var{T:b}=Ht(),Oe=b,Gr=require("path");function Ad(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var Rw={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},Pd={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"},Cw={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 Ya(t){return Cw[t]||{label:"Run",accent:b.tool_default,icon:"\u2022"}}function Od(t){let e=Ya(t);return`${e.accent}${Oe.bold}${e.icon} ${e.label.toUpperCase()}${b.reset}`}function Aw(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Nd(t,e={}){return e.path?Ad(e.path):e.file?Ad(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):Pd[t]||Aw(t)}function Ow(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 Nw(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}=mo(),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}${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 Mw(t){let e=new Set,s=[];for(let o of t){let n=Ya(o.fnName).label;e.has(n)||(e.add(n),s.push(n))}return s.length===0?"":s.length<=3?s.join(`${Oe.dim} \u2192 ${Oe.reset}`):`${s.slice(0,3).join(`${Oe.dim} \u2192 ${Oe.reset}`)}${Oe.dim} \u2192 +${s.length-3}${Oe.reset}`}function Yr(t,e=!1,s=null){if(e)return`${b.error}\u23FA${b.reset}`;let o=Rw[t]||b.tool_default;return s==="blink"?`${o}\x1B[5m\u23FA\x1B[25m${b.reset}`:`${o}${s!==null?s:"\u23FA"}${b.reset}`}function Pw(t,e,s=!1,o=null){let n=(t||[]).filter(c=>c&&c.canExecute!==!1);if(n.length===0)return`${Yr("",s,o)} Step ${e}`;if(n.length===1){let c=n[0],u=c.args||{},d=Nd(c.fnName,{...u,path:u._originalPath||u.path});return`${Yr(c.fnName,s,o)} ${Od(c.fnName)} ${Oe.bold}${d}${Oe.reset}`}let r=n[0].fnName,i=Mw(n)||`${n.length} tools`,a=n.slice(0,2).map(c=>Nd(c.fnName,c.args||{})).filter(Boolean).join(`${Oe.dim} \xB7 ${Oe.reset}`),l=a?` ${b.subtle}\xB7${b.reset} ${Oe.dim}${a}${Oe.reset}`:"";return`${Yr(r,s,o)} ${Od(r)} ${Oe.bold}${i}${Oe.reset}${l}`}function Lw(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=e.path||"";break;case"bash":case"ssh_exec":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let o=Pd[t]||t.replace(/_/g," "),n=s?`(${Oe.dim}${s}${Oe.reset})`:"";return`${Yr(t)} ${Oe.bold}${o}${Oe.reset}${n}`}function Iw(t,e=8){let s=t.split(`
|
|
26
|
+
`),o=s.slice(0,e),n=s.length-e,r=`${b.muted} \u23BF ${b.reset}`,i=" ",a=o.map((l,c)=>`${c===0?r:i}${b.success}${l}${b.reset}`).join(`
|
|
27
|
+
`);return n>0&&(a+=`
|
|
28
|
+
${b.subtle} \u2026 +${n} lines${b.reset}`),a}var zr=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Md=Math.floor(Math.random()*zr.length),jw=null;function Dw(t){jw=t}function qw(){let t=zr[Md%zr.length];return Md++,t}function Fw(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 Bw(t,e,s,o){let n=String(s||""),r=Ya(t),i=` ${b.subtle}\u2502${b.reset} ${r.accent}${Oe.bold}${r.label}${b.reset} ${b.subtle}\xB7${b.reset} `;if(o){let c=n.split(`
|
|
29
|
+
`)[0];if(c.startsWith("BLOCKED:")){let p=c.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${b.muted}blocked: ${p}${b.reset}`}let u=c.replace(/^ERROR:\s*/i,"").substring(0,80),d=n.match(/\nHINT: (.+)/),f=d?`
|
|
30
|
+
${b.muted}${d[1].substring(0,100)}${b.reset}`:"";return`${i}${b.error}${u}${b.reset}${f}`}let a;switch(t){case"read_file":{let c=Ow(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?Gr.basename(e.path):null,g=m?` ${b.muted}from ${m}${b.reset}`:"";p&&f>u?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${u} line${u!==1?"s":""}${g}`;let $=Nw(e.path,c,{maxLines:4,maxContent:120});$&&(a+=`
|
|
31
|
+
${$}`);break}case"write_file":{let u=(e.content||"").split(`
|
|
32
|
+
`).length,d=e.path?Gr.basename(e.path):null,f=d?`Wrote ${d} \xB7 ${u} line${u!==1?"s":""}`:`Wrote ${u} line${u!==1?"s":""}`,{highlightLines:p}=mo(),m=p(e.content||"",e.path||null),g=40,$=8;if(u<=g){let x=m.map(T=>` ${T}`).join(`
|
|
33
|
+
`);a=`${f}
|
|
34
|
+
${x}`}else{let x=m.slice(0,$).map(T=>` ${T}`).join(`
|
|
35
|
+
`);a=`${f}
|
|
36
|
+
${x}
|
|
37
|
+
${b.subtle}\u2026 +${u-$} lines${b.reset}`}break}case"edit_file":{let c=(e.old_text||"").split(`
|
|
38
|
+
`),u=(e.new_text||"").split(`
|
|
39
|
+
`),d=c.length,f=u.length,p=e.path?Gr.basename(e.path):null,m=p?` ${b.muted}${p}${b.reset}`:"",{highlightLine:g,detectLang:$}=mo(),x=$(e.path||null),T=[],A=c.filter((v,N,Q)=>v.trim()||Q.length===1||N===0).slice(0,3),R=u.filter((v,N,Q)=>v.trim()||Q.length===1||N===0).slice(0,3);A.forEach(v=>{T.push(` ${b.diff_rem}- ${b.reset}${g(v.trimEnd().substring(0,96),x)}${b.reset}`)}),c.length>A.length&&T.push(` ${b.subtle}\u2026 ${c.length-A.length} more removed line${c.length-A.length!==1?"s":""}${b.reset}`),R.forEach(v=>{T.push(` ${b.diff_add}+ ${b.reset}${g(v.trimEnd().substring(0,96),x)}${b.reset}`)}),u.length>R.length&&T.push(` ${b.subtle}\u2026 ${u.length-R.length} more added line${u.length-R.length!==1?"s":""}${b.reset}`),a=`${b.diff_rem}\u2212${d}${b.reset} ${b.diff_add}+${f}${b.reset}${m}`+(T.length>0?`
|
|
40
|
+
`+T.join(`
|
|
41
|
+
`):"");break}case"patch_file":{let c=e.patches||[],u=c.reduce((T,A)=>T+(A.old_text||"").split(`
|
|
42
|
+
`).length,0),d=c.reduce((T,A)=>T+(A.new_text||"").split(`
|
|
43
|
+
`).length,0),f=e.path?Gr.basename(e.path):null,p=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}${p}`;let m=[],{highlightLine:g,detectLang:$}=mo(),x=$(e.path||null);c.slice(0,2).forEach((T,A)=>{let R=String(T.old_text||"").split(`
|
|
44
|
+
`).find(Boolean),v=String(T.new_text||"").split(`
|
|
45
|
+
`).find(Boolean);m.push(` ${b.subtle}patch ${A+1}${b.reset}`),R&&m.push(` ${b.diff_rem}- ${b.reset}${g(R.trimEnd().substring(0,92),x)}${b.reset}`),v&&m.push(` ${b.diff_add}+ ${b.reset}${g(v.trimEnd().substring(0,92),x)}${b.reset}`)}),c.length>2&&m.push(` ${b.subtle}\u2026 +${c.length-2} more patches${b.reset}`),m.length>0&&(a+=`
|
|
46
|
+
${m.join(`
|
|
47
|
+
`)}`);break}case"bash":{let u=n.match(/^EXIT (\d+)/),d=n.split(`
|
|
48
|
+
`).filter(m=>m&&!m.startsWith("EXIT ")&&!m.startsWith("HINT:")&&m.trim()),f=u?u[1]==="0"?`${b.success}\u2713${b.reset}`:`${b.error}\u2717 Exit ${u[1]}${b.reset}`:`${b.success}\u2713${b.reset}`,p=n.match(/\nHINT: (.+)/);if(p)a=`${f} ${b.muted}\u2014 ${p[1].substring(0,100)}${b.reset}`;else if(d.length===0)a=f;else{let m=u&&u[1]!=="0",g=m?d.slice(-3):d.slice(0,3),$=d.length-3,x=g.map((T,A)=>A===0?`${f} ${b.muted}${T.substring(0,120)}${b.reset}`:` ${b.muted}${T.substring(0,120)}${b.reset}`);if($>0){let T=m?` ${b.subtle}${$} lines above\u2026${b.reset}`:` ${b.subtle}\u2026 +${$} lines${b.reset}`;m?x.unshift(T):x.push(T)}a=x.join(`
|
|
49
|
+
`)}break}case"grep":case"search_files":{if(n.includes("(no matches)")||n==="no matches")a=`No matches${e.pattern?` ${b.muted}"${String(e.pattern).substring(0,40)}"${b.reset}`:""}`;else{let $=function(R){let v=R.indexOf(":");if(v===-1)return`${b.muted}${R.substring(0,90)}${b.reset}`;let N=R.substring(0,v),Q=R.substring(v+1),se=Q.match(/^(\d+)[:-](.*)/s),re=se?`:${se[1]}`:"",le=(se?se[2]:Q).trim(),ne=`${b.subtle}${c.basename(N)}${re}${b.reset}`,S=`${b.muted}${le.substring(0,80)}${le.length>80?"\u2026":""}${b.reset}`;return`${ne} ${S}`};var l=$;let c=require("path"),u=n.split(`
|
|
50
|
+
`).filter(Boolean),d=u.length,p=new Set(u.map(R=>R.split(":")[0]).filter(Boolean)).size,m=e.pattern?` ${b.muted}"${String(e.pattern).substring(0,40)}"${b.reset}`:"",g=p>1?`${d} match${d!==1?"es":""} in ${p} files${m}`:`${d} match${d!==1?"es":""}${m}`,x=e.path?`
|
|
51
|
+
${b.subtle}path:${b.reset} ${b.muted}${String(e.path).substring(0,70)}${b.reset}`:"",T=u.slice(0,5).map((R,v)=>v===0?`${g}${x}
|
|
52
|
+
${$(R)}`:` ${$(R)}`),A=u.length-5;A>0&&T.push(` ${b.subtle}\u2026 +${A} more matches${b.reset}`),a=T.join(`
|
|
53
|
+
`)}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(`
|
|
54
|
+
`).filter(Boolean),f=d.length,p=d.slice(0,8),m=f-p.length,g=p.map(x=>` ${b.muted}${x}${b.reset}`);m>0&&g.push(` ${b.subtle}\u2026 +${m} more files${b.reset}`);let $=e.path?`
|
|
55
|
+
${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?`
|
|
56
|
+
${g.join(`
|
|
57
|
+
`)}`:"")}break}case"list_directory":{if(n==="(empty)")a="0 entries";else{let c=n.split(`
|
|
58
|
+
`).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(`
|
|
59
|
+
`).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(`
|
|
60
|
+
`).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(`
|
|
61
|
+
`).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 p=u>1?` ${b.muted}+${u-1} more${b.reset}`:"";a=`${d} ${b.muted}${f.trim().substring(0,60)}${b.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 ${b.muted}${p.substring(0,70)}${b.reset}`:`Fetched ${f}`;break}case"web_search":{let c=n.split(`
|
|
62
|
+
|
|
63
|
+
`).filter(Boolean),u=c.length,d=c[0]?c[0].split(`
|
|
64
|
+
`)[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(`
|
|
65
|
+
`).filter(p=>p.trim()&&!p.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,T)=>T===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(`
|
|
66
|
+
`)}break}default:{let c=n.split(`
|
|
67
|
+
`).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 Uw(t,e,s,o,n,r){let i=Math.round(o/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,l=`
|
|
68
|
+
${b.success}\u25C6${Oe.reset} ${Oe.bold}${t}${Oe.reset}`;return l+=` ${b.subtle}\u2501\u2501${b.reset} ${Oe.dim}${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),n.size>0&&(l+=` \xB7 ${n.size} scanned`),l+=Oe.reset,l}Ld.exports={C:Oe,formatToolCall:Lw,formatResult:Iw,getToolSpinnerText:Fw,formatToolSummary:Bw,formatSectionHeader:Pw,formatMilestone:Uw,getThinkingVerb:qw,setActiveModelForSpinner:Dw,THINKING_VERBS:zr}});var nt=V((T1,Dd)=>{var{T:tn}=Ht(),za=tn,Ww=require("path"),jd=["01100110","01111110","01111110","01011010","01111110","00111100"];function Hw(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 Gw(t,e,s={}){let o=za.bold,n=za.reset,r=Hw(jd,tn.banner_logo),i=s.yolo?` ${o}${tn.banner_yolo}\u26A1 YOLO${n}`:"",a=s.gemini?` ${o}${tn.banner_gemini}\u2726 GEMINI${n}`:"",l=Ba().version,c=e?Ww.basename(e):null,u=`${tn.banner_model}[${t||"model"}]${n}`,d=`${tn.banner_version}[${c||"workspace"}]${n}`,f=[` ${tn.banner_name}${o}nex-code${n} ${tn.banner_version}v${l}${n}`,` ${u} ${d}`,` ${tn.banner_logo}${o}terminal workbench${n} ${tn.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),$=jd[0].length,x=[];for(let T=0;T<p;T++){let A=r[T-m]??" ".repeat($),R=f[T-g]??"";x.push(A+R)}console.log(`
|
|
69
|
+
`+x.join(`
|
|
60
70
|
`)+`
|
|
61
|
-
`)}var{Spinner:
|
|
62
|
-
`),a}catch(a){throw
|
|
63
|
-
`){c(
|
|
64
|
-
`),
|
|
65
|
-
`),
|
|
66
|
-
${U.bold}${U.cyan} Diff: ${t}${U.reset}`);let o
|
|
67
|
-
${U.bold}${U.cyan} File exists \u2014 showing changes: ${t}${U.reset}`);let
|
|
71
|
+
`)}var{Spinner:Yw,MultiProgress:zw,TaskProgress:Kw,ToolProgress:Xw,setActiveTaskProgress:Vw,getActiveTaskProgress:Jw,cleanupTerminal:Zw}=Gn(),{formatToolCall:Qw,formatResult:e$,getToolSpinnerText:t$,formatToolSummary:n$,formatSectionHeader:s$,formatMilestone:o$,getThinkingVerb:r$,setActiveModelForSpinner:i$}=Id();Dd.exports={C:za,banner:Gw,Spinner:Yw,MultiProgress:zw,TaskProgress:Kw,ToolProgress:Xw,setActiveTaskProgress:Vw,getActiveTaskProgress:Jw,cleanupTerminal:Zw,formatToolCall:Qw,formatResult:e$,getToolSpinnerText:t$,formatToolSummary:n$,formatSectionHeader:s$,formatMilestone:o$,getThinkingVerb:r$,setActiveModelForSpinner:i$}});var Xa=V((R1,qd)=>{function Ka(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var a$=Ka();function l$(...t){Ka()&&console.log(...t)}function c$(...t){Ka()&&console.warn(...t)}qd.exports={DEBUG:a$,debugLog:l$,warnLog:c$}});var Ud=V((C1,Bd)=>{"use strict";var u$=new Set(["read_file","grep","glob","search_files","list_directory"]),d$=new Set(["write_file","edit_file","patch_file"]),f$=new Set(["bash"]),p$=new Set(["web_search","web_fetch","perplexity_search"]);function Fd(t,e){let s=0,o=0,n=0,r=0,i=0;for(let[a,l]of t)i+=l,u$.has(a)&&(s+=l),d$.has(a)&&(o+=l),f$.has(a)&&(n+=l),p$.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 Va=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:Fd(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}};Bd.exports={MilestoneTracker:Va,_phaseName:Fd}});var Kr=V((A1,Wd)=>{var go=lt(),h$={"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 m$(){return go.getActiveModel()}function g$(t){return go.setActiveModel(t)}function y$(){return go.getModelNames()}function w$(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 $$(t,e){let{C:s}=nt(),{Spinner:o}=nt(),n=new o("Thinking...");n.start();let r=!0,i="";try{let a=await go.callStream(t,e,{onToken:l=>{r&&(n.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?n.stop():process.stdout.write(`${s.reset}
|
|
72
|
+
`),a}catch(a){throw n.stop(),a}}async function b$(t,e){return go.callChat(t,e)}Wd.exports={MODELS:h$,getActiveModel:m$,setActiveModel:g$,getModelNames:y$,callOllamaStream:$$,callOllama:b$,parseToolArgs:w$}});var wo=V((O1,Xd)=>{var _$=require("readline"),{C:nn}=nt(),k$=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,x$=/^=([\w-]+)/;function yo(t){return typeof t!="string"?t:t.replace(k$,"").replace(x$,"$1")}var Qa=[/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/],Hd=[...Qa,/\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 S$(t){for(let e of Hd)if(e.test(t))return e;return null}var Gd=[/\.env\b/,/credentials\b/i,/\.ssh\b/,/\.gnupg\b/,/\.aws\b/,/\.npmrc\b/,/\.docker\/config/,/\.kube\/config/,/venv\b/,/\.venv\b/,/\.sqlite3\b/,/\.git\/(?!hooks)/],E$=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Ja=[/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 Yd(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)):Ja.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Ja.some(a=>a.test(i))};return o.every(n)}var el=[/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/],zd=[/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/],Kd=[...el,...zd],tl=!1,zn=null,Za=null;function v$(t){tl=t}function T$(t){Za=t}function R$(){return tl}function C$(t){zn=t}function A$(t){let e=yo(t);for(let s of Qa)if(s.test(e))return s;return null}function O$(t){let e=yo(t);if(/ssh\s/.test(e)&&Yd(e))return!1;for(let s of Kd)if(s.test(e))return!0;return!1}function N$(t){let e=yo(t);for(let s of el)if(s.test(e))return!0;return!1}function M$(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=yo(t);if(!E$.test(e))return null;for(let s of Gd)if(s.test(e))return s;return null}function P$(t,e={}){if(tl)return Promise.resolve(!0);if(Za)return Za(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return L$(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let n=0;zn&&zn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-s.length-2)},a=()=>{let d=i();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${nn.yellow}${t}${nn.reset}`;for(let p=0;p<s.length;p++){let m=p===n,g=m?`${nn.yellow}\u276F${nn.reset}`:" ",$=m?`${nn.yellow}${s[p]}${nn.reset}`:s[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${$}`}r(f)},l=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),p=i(),m="";for(let g=0;g<s.length+1;g++)m+=`\x1B[${p+g};1H\x1B[2K`;f(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),zn&&zn.resume(),o(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&Xr(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
|
|
73
|
+
`){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){Xr(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function L$(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?(Xr(e.toolName),o(!0)):o(i!=="n")};if(zn)zn.question(`${nn.yellow}${t} ${s}${nn.reset}`,n);else{let r=_$.createInterface({input:process.stdin,output:process.stdout});r.question(`${nn.yellow}${t} ${s}${nn.reset}`,i=>{r.close(),n(i)})}})}var Xr=()=>{};function I$(t){Xr=t}Xd.exports={sanitizeBashCommand:yo,FORBIDDEN_PATTERNS:Qa,SSH_FORBIDDEN_PATTERNS:Hd,BASH_PROTECTED_PATHS:Gd,SSH_SAFE_PATTERNS:Ja,isSSHReadOnly:Yd,DANGEROUS_BASH:Kd,CRITICAL_BASH:el,NOTABLE_BASH:zd,isForbidden:A$,isSSHForbidden:S$,isDangerous:O$,isCritical:N$,isBashPathForbidden:M$,confirm:P$,setAutoConfirm:v$,getAutoConfirm:R$,setConfirmHook:T$,setReadlineInterface:C$,setAllowAlwaysHandler:I$}});var Zd=V((M1,Jd)=>{var Vr=require("path"),{C:U}=nt(),{T:nl,isDark:N1}=Ht(),{confirm:j$,getAutoConfirm:D$}=wo(),Vd=2e3;function $o(t,e){let s=t.split(`
|
|
74
|
+
`),o=e.split(`
|
|
75
|
+
`),n=[],r=s.length,i=o.length;if(r>Vd||i>Vd){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 q$(t,e,s,o=3){console.log(`
|
|
76
|
+
${U.bold}${U.cyan} Diff: ${t}${U.reset}`);let n=$o(e,s),r=[];if(n.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${U.gray} (no changes)${U.reset}`);return}let i=Math.max(0,r[0]-o),a=Math.min(n.length,r[r.length-1]+o+1);i>0&&console.log(`${U.gray} ...${U.reset}`);for(let l=i;l<a;l++){let c=n[l];switch(c.type){case"remove":console.log(`${U.red} - ${c.line}${U.reset}`);break;case"add":console.log(`${U.green} + ${c.line}${U.reset}`);break;default:console.log(`${U.gray} ${c.line}${U.reset}`)}}a<n.length&&console.log(`${U.gray} ...${U.reset}`),console.log()}function F$(t,e,s){console.log(`
|
|
77
|
+
${U.bold}${U.cyan} File exists \u2014 showing changes: ${t}${U.reset}`);let o=$o(e,s),n=0;for(let i of o)i.type!=="same"&&n++;if(n===0){console.log(`${U.gray} (identical content)${U.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${U.gray} ...(${n-r} more changes)${U.reset}`);break}switch(i.type){case"remove":console.log(`${U.red} - ${i.line}${U.reset}`),r++;break;case"add":console.log(`${U.green} + ${i.line}${U.reset}`),r++;break;default:r>0&&console.log(`${U.gray} ${i.line}${U.reset}`)}}console.log()}function B$(t,e){console.log(`
|
|
68
78
|
${U.bold}${U.cyan} New file: ${t}${U.reset}`);let s=e.split(`
|
|
69
|
-
`),
|
|
70
|
-
${U.bold}${U.cyan} Side-by-side: ${t}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${U.reset}`);let i
|
|
71
|
-
`)}function
|
|
72
|
-
${U.green}\u23FA${U.reset} ${U.bold}${
|
|
73
|
-
`);return}let p=[];if(d>0&&p.push(`Added ${d} line${d!==1?"s":""}`),f>0&&p.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let
|
|
79
|
+
`),o=s.slice(0,20);for(let n of o)console.log(`${U.green} + ${n}${U.reset}`);s.length>20&&console.log(`${U.gray} ...+${s.length-20} more lines${U.reset}`),console.log()}async function U$(t){return D$()?!0:j$(` ${t}?`)}function W$(t,e,s,o){let n=o||process.stdout.columns||80,r=Math.floor((n-3)/2);console.log(`
|
|
80
|
+
${U.bold}${U.cyan} Side-by-side: ${t}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${U.reset}`);let i=$o(e,s),a=[],l=0;for(;l<i.length;)if(i[l].type==="same")a.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let p=[];for(;l<i.length&&i[l].type==="remove";)p.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(p.length,m.length);for(let $=0;$<g;$++)a.push({left:$<p.length?p[$]:"",right:$<m.length?m[$]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let c=a.map((p,m)=>p.type!=="same"?m:-1).filter(p=>p>=0);if(c.length===0){console.log(` ${U.gray}(no changes)${U.reset}`);return}let u=Math.max(0,c[0]-2),d=Math.min(a.length,c[c.length-1]+3),f=(p,m)=>{let g=p.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?p.substring(0,m):p+" ".repeat(m-g.length)};u>0&&console.log(` ${U.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${U.reset}`);for(let p=u;p<d;p++){let m=a[p];if(m.type==="same")console.log(` ${U.gray}${f(m.left,r)}${U.reset}\u2502${U.gray}${f(m.right,r)}${U.reset}`);else{let g=m.left?`${U.red}${f(m.left,r)}${U.reset}`:`${f("",r)}`,$=m.right?`${U.green}${f(m.right,r)}${U.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${$}`)}}d<a.length&&console.log(` ${U.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${U.reset}
|
|
81
|
+
`)}function H$(t,e,s,o={}){let n=o.label||"Update",r=o.context||3,i=o.annotations||[],a=Vr.isAbsolute(t)?Vr.relative(process.cwd(),t):t,l=$o(e,s),c=1,u=1;for(let N of l)N.type==="same"?(N.oldLine=c++,N.newLine=u++):N.type==="remove"?(N.oldLine=c++,N.newLine=null):(N.oldLine=null,N.newLine=u++);let d=0,f=0;for(let N of l)N.type==="add"?d++:N.type==="remove"&&f++;if(console.log(`
|
|
82
|
+
${U.green}\u23FA${U.reset} ${U.bold}${n}(${a})${U.reset}`),d===0&&f===0){console.log(` ${U.dim}\u23BF (no changes)${U.reset}
|
|
83
|
+
`);return}let p=[];if(d>0&&p.push(`Added ${d} line${d!==1?"s":""}`),f>0&&p.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let N=i.filter(le=>le.severity==="error").length,Q=i.filter(le=>le.severity==="warn").length,se=i.filter(le=>le.severity==="info").length,re=[];N>0&&re.push(`${U.red}${N} error${N!==1?"s":""}${U.dim}`),Q>0&&re.push(`${U.yellow}${Q} warning${Q!==1?"s":""}${U.dim}`),se>0&&re.push(`${U.cyan}${se} info${se!==1?"s":""}${U.dim}`),p.push(`found ${re.join(", ")}`)}console.log(` ${U.dim}\u23BF ${p.join(", ")}${U.reset}`);let g=[];l.forEach((N,Q)=>{N.type!=="same"&&g.push(Q)});let $=[],x=null,T=null;for(let N of g){let Q=Math.max(0,N-r),se=Math.min(l.length-1,N+r);x===null?(x=Q,T=se):(Q<=T+1||($.push([x,T]),x=Q),T=se)}x!==null&&$.push([x,T]);let A=" ",R=process.stdout.columns||120;function v(N,Q,se){let re=se.replace(/\x1b\[[0-9;]*m/g,""),le=se+" ".repeat(Math.max(0,R-re.length));return`${N}${Q}${le}${U.reset}`}for(let N=0;N<$.length;N++){N>0&&console.log(`${A}${U.dim}\xB7\xB7\xB7${U.reset}`);let[Q,se]=$[N];for(let re=Q;re<=se;re++){let le=l[re],ne=le.newLine!=null?le.newLine:le.oldLine,S=String(ne).padStart(4),ve=le.type!=="remove"?i.filter(W=>W.line===le.newLine):[];le.type==="remove"?console.log(v(nl.diff_rem_bg,U.red,`${A}${S} - ${le.line}`)):le.type==="add"?console.log(v(nl.diff_add_bg,U.green,`${A}${S} + ${le.line}`)):console.log(`${A}${U.dim}${S} ${U.reset}${le.line}`);for(let W of ve){let z=U.cyan,ge="\u2139";W.severity==="error"?(z=U.red,ge="\u2716"):W.severity==="warn"&&(z=U.yellow,ge="\u26A0"),console.log(`${A} ${z}${ge} ${W.message}${U.reset}`)}}}console.log()}function G$(t,e,s={}){let o=Vr.isAbsolute(t)?Vr.relative(process.cwd(),t):t,n=e.split(`
|
|
74
84
|
`),r=s.annotations||[];console.log(`
|
|
75
|
-
${U.green}\u23FA${U.reset} ${U.bold}Create(${
|
|
76
|
-
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),
|
|
77
|
-
`);for(let d of u)d.startsWith("+")&&!d.startsWith("+++")&&
|
|
78
|
-
${
|
|
79
|
-
${
|
|
80
|
-
${
|
|
85
|
+
${U.green}\u23FA${U.reset} ${U.bold}Create(${o})${U.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(`${U.red}${d} error${d!==1?"s":""}${U.dim}`),f>0&&m.push(`${U.yellow}${f} warning${f!==1?"s":""}${U.dim}`),p>0&&m.push(`${U.cyan}${p} info${p!==1?"s":""}${U.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${U.dim}\u23BF ${i.join(", ")}${U.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(n.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),p=d+1,m=r.filter(T=>T.line===p),g=`${l}${f} + ${n[d]}`,$=g.replace(/\x1b\[[0-9;]*m/g,""),x=g+" ".repeat(Math.max(0,c-$.length));console.log(`${nl.diff_add_bg}${U.green}${x}${U.reset}`);for(let T of m){let A=U.cyan,R="\u2139";T.severity==="error"?(A=U.red,R="\u2716"):T.severity==="warn"&&(A=U.yellow,R="\u26A0"),console.log(`${l} ${A}${R} ${T.message}${U.reset}`)}}n.length>20&&console.log(`${l}${U.dim} ...+${n.length-20} more lines${U.reset}`),console.log()}Jd.exports={diffLines:$o,showEditDiff:q$,showWriteDiff:F$,showNewFilePreview:B$,confirmFileChange:U$,showSideBySideDiff:W$,showDiff:H$,showNewFile:G$}});var Qr=V((P1,tf)=>{var Qd=require("util").promisify(require("child_process").exec),Y$=require("util").promisify(require("child_process").execFile),{C:Fe}=nt();async function sl(t){try{let{stdout:e}=await Qd(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Jr(...t){try{let{stdout:e}=await Y$("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function z$(){return await sl("git rev-parse --is-inside-work-tree")==="true"}async function K$(){return await sl("git branch --show-current")}async function ol(){try{let{stdout:t}=await Qd("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
86
|
+
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),o=e.substring(3);return{status:s,file:o}})}catch{return[]}}async function Zr(t=!1){return await sl(`git diff ${t?"--cached":""}`)||""}async function rl(){return(await ol()).map(e=>e.file)}async function ef(){let t=await rl();if(t.length===0)return null;let e=await Zr(),o=await Zr(!0)||e,n=0,r=0;if(o){let u=o.split(`
|
|
87
|
+
`);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 X$(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Jr("checkout","-b",s)!==null?s:null}async function V$(t){return await Jr("add","-A"),await Jr("commit","-m",t)?await Jr("rev-parse","--short","HEAD"):null}async function J$(){let t=await ef();if(!t)return`${Fe.dim}No changes${Fe.reset}`;let e=[];e.push(`
|
|
88
|
+
${Fe.bold}${Fe.cyan}Git Diff Summary:${Fe.reset}`),e.push(` ${Fe.green}+${t.stats.additions}${Fe.reset} ${Fe.red}-${t.stats.deletions}${Fe.reset} in ${t.files.length} file(s)`),e.push(`
|
|
89
|
+
${Fe.bold}${Fe.cyan}Files:${Fe.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Fe.dim}${s}${Fe.reset}`);return t.files.length>20&&e.push(` ${Fe.dim}...+${t.files.length-20} more${Fe.reset}`),e.push(`
|
|
90
|
+
${Fe.bold}${Fe.cyan}Suggested message:${Fe.reset}`),e.push(` ${Fe.cyan}${t.summary}${Fe.reset}
|
|
81
91
|
`),e.join(`
|
|
82
|
-
`)}async function
|
|
92
|
+
`)}async function Z$(){return(await ol()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Q$(){let t=await rl();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 Zr();if(s){let o=s.length>5e3?s.substring(0,5e3)+`
|
|
83
93
|
...(truncated)`:s;e.push(`
|
|
84
94
|
DIFF:
|
|
85
|
-
${
|
|
86
|
-
`)}
|
|
87
|
-
`).map(s=>{let
|
|
88
|
-
`)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?
|
|
89
|
-
${
|
|
90
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
95
|
+
${o}`)}return e.join(`
|
|
96
|
+
`)}tf.exports={isGitRepo:z$,getCurrentBranch:K$,getStatus:ol,getDiff:Zr,getChangedFiles:rl,analyzeDiff:ef,createBranch:X$,commit:V$,formatDiffSummary:J$,getDiffContext:Q$,getMergeConflicts:Z$}});var uf=V((I1,cf)=>{var st=require("fs").promises,L1=require("fs"),Lt=require("path"),eb=require("crypto"),{execSync:il,execFileSync:of}=require("child_process"),tb=100*1024,rf=50,$t=[],Ps=[];function nb(t,e,s,o){for($t.push({tool:t,filePath:e,oldContent:s,newContent:o,timestamp:Date.now()});$t.length>rf;)$t.shift();Ps.length=0,af($t[$t.length-1]).catch(()=>{})}async function sb(){if($t.length===0)return null;let t=$t.pop();if(t.oldContent===null)try{await st.unlink(t.filePath)}catch{}else await st.writeFile(t.filePath,t.oldContent,"utf-8");return Ps.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function ob(){if(Ps.length===0)return null;let t=Ps.pop();return await st.writeFile(t.filePath,t.newContent,"utf-8"),$t.push(t),{tool:t.tool,filePath:t.filePath}}function rb(t=10){return $t.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function ib(){return $t.length}function ab(){return Ps.length}function lb({diskToo:t=!0}={}){if($t.length=0,Ps.length=0,t){let e=ti();st.readdir(e).then(s=>{for(let o of s)o.endsWith(".json")&&st.unlink(Lt.join(e,o)).catch(()=>{})}).catch(()=>{})}}function ti(){return Lt.join(process.cwd(),".nex","history")}async function nf(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=tb)return{inline:!0,content:t};let s=eb.createHash("sha256").update(t,"utf-8").digest("hex"),o=Lt.join(e,"blobs");return await st.mkdir(o,{recursive:!0}),await st.writeFile(Lt.join(o,s),t,"utf-8"),{inline:!1,hash:s}}async function af(t){let e=ti();await st.mkdir(e,{recursive:!0});let s=Lt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${s}.json`,n=await nf(t.oldContent,e),r=await nf(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 st.writeFile(Lt.join(e,o),JSON.stringify(i),"utf-8")}async function sf(t,e){if(!t)return null;if(t.inline)return t.content;let s=Lt.join(e,"blobs",t.hash);return st.readFile(s,"utf-8")}async function cb(){let t=ti(),e;try{e=await st.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 st.readFile(Lt.join(t,n),"utf-8"),i=JSON.parse(r),a=await sf(i.oldContent,t),l=await sf(i.newContent,t);$t.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),o++}catch{}for(;$t.length>rf;)$t.shift();return o}async function ub(t=7){let e=ti(),s;try{s=await st.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 st.readFile(Lt.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 st.unlink(Lt.join(e,c))}catch{}let l=Lt.join(e,"blobs");try{let c=await st.readdir(l);for(let u of c)if(!i.has(u))try{await st.unlink(Lt.join(l,u))}catch{}}catch{}return r}var ei="nex-snapshot";function db(t,e=process.cwd()){let s=t?`${ei}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${ei}-${Date.now()}`;try{return il("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(of("git",["stash","push","-u","-m",s],{cwd:e,timeout:15e3}),il("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 lf(t=process.cwd()){try{let e=il("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
|
|
97
|
+
`).map(s=>{let o=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let n=o[2].trim();return n.startsWith(ei)?{index:parseInt(o[1],10),label:n,shortName:n.replace(`${ei}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function fb(t,e=process.cwd()){try{let s=lf(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?(of("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}}}cf.exports={recordChange:nb,undo:sb,redo:ob,getHistory:rb,getUndoCount:ib,getRedoCount:ab,clearHistory:lb,persistEntry:af,loadPersistedHistory:cb,pruneHistory:ub,createSnapshot:db,listSnapshots:lf,restoreSnapshot:fb}});var dl=V((j1,gf)=>{var Le=require("fs"),bt=require("path"),{atomicWrite:pb,withFileLockSync:hb}=Hn(),ft=[];function bo(){return bt.join(process.cwd(),".nex","skills")}function df(){return bt.join(process.cwd(),".nex","config.json")}function ff(){let t=bo();return Le.existsSync(t)||Le.mkdirSync(t,{recursive:!0}),t}function cl(){let t=df();if(!Le.existsSync(t))return[];try{let e=JSON.parse(Le.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function pf(t){let e=df(),s=bt.dirname(e);Le.existsSync(s)||Le.mkdirSync(s,{recursive:!0}),hb(e,()=>{let o={};if(Le.existsSync(e))try{o=JSON.parse(Le.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,pb(e,JSON.stringify(o,null,2))})}function hf(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 mf(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let s=e[1],o=e[2].trim(),n=[],r=!1;for(let i of s.split(`
|
|
98
|
+
`)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?n.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:n,body:o}}function al(t){try{let e=Le.readFileSync(t,"utf-8").trim();if(!e)return null;let s=bt.basename(t,".md"),{triggers:o,body:n}=mf(e);return{name:s,type:"prompt",filePath:t,instructions:n||e,triggers:o,commands:[],tools:[]}}catch{return null}}function ll(t){try{let e=require(t),{valid:s,errors:o}=hf(e,t);return s?{name:e.name||bt.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
|
|
99
|
+
${o.join(`
|
|
100
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function ul(){ft=[];let t=cl(),e=bo(),s=[];if(Le.existsSync(e))try{s=Le.readdirSync(e)}catch{s=[]}for(let n of s){let r=bt.join(e,n),i;try{i=Le.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;n.endsWith(".md")?a=al(r):n.endsWith(".js")&&(a=ll(r)),a&&(a.enabled=!t.includes(a.name),ft.push(a))}let o=bt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Le.existsSync(o)){let n;try{n=Le.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{n=[]}for(let r of n){let i=bt.join(o,r),a=bt.basename(r,bt.extname(r));if(ft.some(u=>u.name===a))continue;let l;try{l=Le.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?al(i):ll(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),ft.push(c))}}return ft}function mb(){let t=[];for(let e of ft)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
91
101
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
92
102
|
${t.join(`
|
|
93
103
|
|
|
94
|
-
`)}`}function
|
|
104
|
+
`)}`}function gb(){let t=[];for(let e of ft)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function yb(){let t=[];for(let e of ft)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function wb(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let o of ft)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 $b(t){let[e,...s]=t.split(/\s+/),o=s.join(" ").trim();for(let n of ft)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 bb(){return ft.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function _b(t){let e=ft.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let s=cl().filter(o=>o!==t);return pf(s),!0}function kb(t){let e=ft.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let s=cl();return s.includes(t)||(s.push(t),pf(s)),!0}function xb(){return ft}async function Sb(t,e={}){let{execFileSync:s}=require("child_process"),o=ff(),n=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(n=`https://github.com/${t}.git`);let r=e.name||bt.basename(n,".git").replace(/^nex-skill-/,""),i=bt.join(o,r);if(Le.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=bt.join(i,"skill.json"),l=Le.existsSync(a),c=Le.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{Le.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(Le.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Le.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return ul(),{ok:!0,name:r}}async function Eb(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 vb(t){let e=bt.join(bo(),t);if(!Le.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${bo()}`};try{return Le.rmSync(e,{recursive:!0,force:!0}),ul(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function Tb(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let o of ft){if(!o.enabled||!o.triggers||o.triggers.length===0)continue;if(o.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(o.instructions||"").split(`
|
|
95
105
|
`).slice(0,3).join(`
|
|
96
|
-
`);s.push({name:
|
|
97
|
-
`,l="",c=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},
|
|
98
|
-
`);for(let m of p)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):
|
|
99
|
-
`):JSON.stringify(
|
|
100
|
-
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let
|
|
106
|
+
`);s.push({name:o.name,instructions:r})}}return s}gf.exports={initSkillsDir:ff,loadAllSkills:ul,getSkillInstructions:mb,getSkillCommands:gb,getSkillToolDefinitions:yb,routeSkillCall:wb,handleSkillCommand:$b,listSkills:bb,enableSkill:_b,disableSkill:kb,getLoadedSkills:xb,installSkill:Sb,searchSkills:Eb,removeSkill:vb,matchSkillTriggers:Tb,_getSkillsDir:bo,_validateScriptSkill:hf,_loadMarkdownSkill:al,_loadScriptSkill:ll,_parseFrontmatter:mf}});var pl=V((D1,kf)=>{var{spawn:Rb}=require("child_process"),Cb=require("path"),yf=require("fs"),gn=new Map;function Ab(){return Cb.join(process.cwd(),".nex","config.json")}function fl(){let t=Ab();if(!yf.existsSync(t))return{};try{return JSON.parse(yf.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function ni(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})+`
|
|
107
|
+
`,l="",c=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},o);function u(f){l+=f.toString();let p=l.split(`
|
|
108
|
+
`);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 wf(t,e){if(gn.has(t))return gn.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of s)process.env[i]&&(o[i]=process.env[i]);let n=Rb(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:n,tools:[],config:e};try{await ni(n,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await ni(n,"tools/list",{});return r.tools=i&&i.tools||[],gn.set(t,r),r}catch(i){throw n.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function $f(t){let e=gn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return gn.delete(t),!0}function Ob(){for(let[t]of gn)$f(t)}async function bf(t,e,s={}){let o=gn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let n=await ni(o.proc,"tools/call",{name:e,arguments:s});return n&&Array.isArray(n.content)?n.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
109
|
+
`):JSON.stringify(n)}function _f(){let t=[];for(let[e,s]of gn)for(let o of s.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function Nb(){return _f().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Mb(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 Pb(){let t=fl();return Object.entries(t).map(([e,s])=>{let o=gn.get(e);return{name:e,command:s.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function Lb(){let t=fl(),e=[];for(let[s,o]of Object.entries(t))try{let n=await wf(s,o);e.push({name:s,tools:n.tools.length})}catch(n){e.push({name:s,tools:0,error:n.message})}return e}kf.exports={loadMCPConfig:fl,sendRequest:ni,connectServer:wf,disconnectServer:$f,disconnectAll:Ob,callTool:bf,getAllTools:_f,getMCPToolDefinitions:Nb,routeMCPCall:Mb,listServers:Pb,connectAll:Lb}});var oi=V((q1,vf)=>{var xf=require("fs"),hl=require("path"),si=[],_o=[],Kn={},ko=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Sf(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 _o.some(o=>o.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(_o.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Ef(t,e){return ko.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Kn[t]||(Kn[t]=[]),Kn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${ko.join(", ")}`}}async function ml(t,e){let s=Kn[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 Ib(){let t=hl.join(process.cwd(),".nex","plugins"),e=[];if(!xf.existsSync(t))return{loaded:0,errors:[]};let s=xf.readdirSync(t).filter(n=>n.endsWith(".js")),o={registerTool:Sf,registerHook:Ef,EVENTS:ko};for(let n of s){let r=hl.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}si.push({name:i.name||hl.basename(n,".js"),filePath:r})}catch(i){e.push(`${n}: ${i.message}`)}}return{loaded:si.length,errors:e}}function jb(){return _o.map(t=>t.definition)}async function Db(t,e,s={}){let o=_o.find(a=>a.definition.function.name===t);if(!o)return null;let n=await ml("beforeToolExec",{name:t,args:e,options:s}),r=await o.handler(n.args||e,s);return(await ml("afterToolExec",{name:t,args:e,result:r})).result||r}function qb(){return[...si]}function Fb(){let t={};for(let e of ko)t[e]=(Kn[e]||[]).length;return t}function Bb(){si.length=0,_o.length=0;for(let t of Object.keys(Kn))delete Kn[t]}vf.exports={registerTool:Sf,registerHook:Ef,emit:ml,loadPlugins:Ib,getPluginToolDefinitions:jb,executePluginTool:Db,getLoadedPlugins:qb,getHookCounts:Fb,clearPlugins:Bb,EVENTS:ko}});var gl=V((F1,Af)=>{var{getSkillToolDefinitions:Ub}=dl(),{getMCPToolDefinitions:Wb}=pl(),{getPluginToolDefinitions:Hb}=oi(),ri=new Map;function Tf(){let{TOOL_DEFINITIONS:t}=xo();return[...t,...Ub(),...Wb(),...Hb()]}function Rf(t){if(ri.has(t))return ri.get(t);let s=Tf().find(n=>n.function.name===t);if(!s)return null;let o=s.function.parameters;return ri.set(t,o),o}function Gb(){ri.clear()}function ii(t,e){if(!t||e.length===0)return null;let s=null,o=1/0;for(let n of e){let r=Cf(t.toLowerCase(),n.toLowerCase());r<o&&(o=r,s=n)}return o<=Math.ceil(t.length/2)?s:null}function Cf(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 Yb(t,e){let s=Rf(t);if(s===null){let d=Tf().map(p=>p.function.name),f=ii(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
110
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let o=s.required||[],n=Object.keys(s.properties),r=Object.keys(e),i=[],a={...e},l=!1;for(let u of o)if(!(u in e)||e[u]===void 0||e[u]===null){let d=ii(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=ii(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:
|
|
101
111
|
`+i.map(u=>` - ${u}`).join(`
|
|
102
112
|
`)+`
|
|
103
113
|
|
|
104
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function
|
|
114
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function zb(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}}Af.exports={validateToolArgs:Yb,validateToolCallFormat:zb,closestMatch:ii,levenshtein:Cf,getCachedSchema:Rf,clearSchemaCache:Gb}});var Pf=V((B1,Mf)=>{var{levenshtein:ai}=gl(),Kb=200,Xb=.3,Vb=2;function yl(t){return t.replace(/\r\n/g,`
|
|
105
115
|
`).replace(/\r/g,`
|
|
106
|
-
`).replace(/\t/g," ".repeat(
|
|
107
|
-
`).map(e=>{let s=e.replace(/\s+$/,""),
|
|
108
|
-
`)}function
|
|
116
|
+
`).replace(/\t/g," ".repeat(Vb)).split(`
|
|
117
|
+
`).map(e=>{let s=e.replace(/\s+$/,""),o=s.match(/^(\s*)(.*)/);if(!o)return s;let[,n,r]=o;return n+r.replace(/ {2,}/g," ")}).join(`
|
|
118
|
+
`)}function Jb(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=yl(t),o=yl(e);if(!s.includes(o))return null;let n=t.split(`
|
|
109
119
|
`),r=s.split(`
|
|
110
|
-
`),i=
|
|
111
|
-
`),a=i[0],l=i[i.length-1];for(let c=0;c<=r.length-i.length;c++){let u=!0;for(let d=0;d<i.length;d++)if(r[c+d]!==i[d]){u=!1;break}if(u)return
|
|
112
|
-
`)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(
|
|
113
|
-
`),
|
|
114
|
-
`).length;return s.length===0||
|
|
115
|
-
`),c=
|
|
116
|
-
`),p=
|
|
117
|
-
`),
|
|
118
|
-
`).filter(Boolean)
|
|
119
|
-
`);for(let
|
|
120
|
+
`),i=o.split(`
|
|
121
|
+
`),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(`
|
|
122
|
+
`)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(o)!==-1)return n[c]}return null}function Zb(t,e){if(!t||!e)return null;let s=t.split(`
|
|
123
|
+
`),n=e.split(`
|
|
124
|
+
`).length;return s.length===0||n===0?null:n===1?Qb(s,e):t_(s,e,n)}function Of(t){return Math.max(1,Math.floor(t/Kb))}function Nf(t,e){return t<=Math.ceil(e*Xb)}function Qb(t,e){let s=e.trim(),o=Of(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=ai(a.trim(),s);l<r&&(r=l,n={text:a,distance:l,line:i+1})}return n&&o>1&&(n=e_(t,s,n,o)||n,r=n.distance),Nf(r,e.length)?n:null}function e_(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=ai(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function t_(t,e,s){let o=t.length-s+1;if(o<=0)return null;let n=Of(o),r=null,i=1/0;for(let a=0;a<o;a+=n){let l=t.slice(a,a+s).join(`
|
|
125
|
+
`),c=ai(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&n>1&&(r=n_(t,e,r,n,s,o)||r,i=r.distance),Nf(i,e.length)?r:null}function n_(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(`
|
|
126
|
+
`),p=ai(f,e);p<c&&(c=p,u={text:f,distance:p,line:d+1})}return u}Mf.exports={normalizeWhitespace:yl,fuzzyFindText:Jb,findMostSimilar:Zb}});var If=V((W1,Lf)=>{var{C:U1}=nt(),s_=[{name:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{name:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{name:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{name:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{name:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36}/i},{name:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{name:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{name:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"'][^'"']{8,}/i}],o_=[{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 r_(t,e){let s=e.split(`
|
|
127
|
+
`),o=[],n=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let l of s_)l.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of o_)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 i_(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Lf.exports={runDiagnostics:r_,getMemoryUsage:i_}});var sn=V((H1,Kf)=>{var Xn=require("fs").promises,_t=require("path"),{exec:a_}=require("util").promisify(require("child_process").exec),Cn=[],bl=null,li=!1,$l=0,l_=6e4;function _l(t){return!(Cn.length===0||bl!==t||Date.now()-$l>l_)}async function Bf(t){if(!li&&!_l(t)){li=!0,bl=t;try{try{let{stdout:o}=await a_("rg --files",{cwd:t,timeout:5e3});Cn=o.split(`
|
|
128
|
+
`).filter(Boolean),$l=Date.now(),li=!1;return}catch{}let e=[],s=async(o,n)=>{let r;try{r=await Xn.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=n?`${n}/${i.name}`:i.name;i.isDirectory()?await s(_t.join(o,i.name),a):e.push(a)}};await s(t,""),Cn=e,$l=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{li=!1}}}function So(){return Cn}function c_(){return bl}function u_(t){return Cn.filter(e=>_t.basename(e)===t)}function d_(t){let e=t.toLowerCase();return Cn.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}function Uf(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 Wf(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=_t.basename(t).toLowerCase(),l=_t.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-Uf(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 f_(t,{limit:e=10,minScore:s=15}={}){if(!t||Cn.length===0)return[];let o=[];for(let n of Cn){let r=Wf(n,t);r>=s&&o.push({file:n,score:r})}return o.sort((n,r)=>r.score-n.score),o.slice(0,e)}var wl=null,jf=0,Df=null,Hf=12e4,ci=null,qf=0,Ff=null,Gf=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Yf(t,e){let s=[],o=t.split(`
|
|
129
|
+
`);for(let n=0;n<o.length;n++){let r=o[n],i=n+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let 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 ui(t){t=t||process.cwd();let e=_t.join(t,".nex","index","content-index.json"),s={};if(wl&&Df===t&&Date.now()-jf<Hf)return wl;try{let i=await Xn.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}let o=So();(!_l(t)||o.length===0)&&(await Bf(t),o=So());let n={files:{}},r=!1;for(let i of So()){let a=_t.extname(i);if(!Gf.has(a))continue;let l=_t.join(t,i);try{let u=(await Xn.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){n.files[i]=s.files[i];continue}let d=await Xn.readFile(l,"utf-8"),f=Yf(d,a);n.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=_t.join(t,".nex","index");await Xn.mkdir(i,{recursive:!0}),await Xn.writeFile(e,JSON.stringify(n),"utf-8")}return wl=n,jf=Date.now(),Df=t,n}async function p_(t,e,s){let o=await ui(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 h_(t,e,s){if(!e||!e.startsWith("."))return null;let o=_t.posix.dirname(t.replace(/\\/g,"/")),n=_t.posix.normalize(_t.posix.join(o==="."?"":o,e)),r=[];if(_t.posix.extname(n))r.push(n);else for(let a of Gf)r.push(`${n}${a}`),r.push(_t.posix.join(n,`index${a}`));for(let a of r)if(s.has(a))return a;return null}async function kl(t){if(t=t||process.cwd(),ci&&Ff===t&&Date.now()-qf<Hf)return ci;let e=await ui(t),s=So(),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=h_(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 ci={importsByFile:n,importedByFile:r},qf=Date.now(),Ff=t,ci}async function m_(t,e,s=6){if(!t)return[];let o=await kl(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 g_(t,e=4){let s=await kl(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 zf(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y_(t,e){let s=zf(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 w_(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 ui(e),a=zf(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=_t.join(e,f),g=(await Xn.readFile(p,"utf-8")).split(`
|
|
130
|
+
`);for(let $=0;$<g.length;$++){let x=g[$],T=$+1;if(!c.test(x)||o&&f===o&&n===T||y_(x,t))continue;let A=(f===o?0:4)+(l.test(x)?3:1);u.push({file:f,line:T,context:x.trim(),score:A})}}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)}Kf.exports={refreshIndex:Bf,getFileIndex:So,getIndexedCwd:c_,findFileInIndex:u_,searchIndex:d_,isIndexValid:_l,buildContentIndex:ui,searchContentIndex:p_,extractDefinitions:Yf,buildImportGraph:kl,getRelatedFiles:m_,summarizeModuleHubs:g_,findSymbolReferences:w_,smartSearch:f_,scorePathMatch:Wf,pathLevenshtein:Uf}});var Ls=V((G1,ep)=>{var di=require("fs"),mi=require("path"),gi=require("os"),{execFile:$_}=require("child_process"),{promisify:b_}=require("util"),xl=b_($_),__=mi.join(gi.homedir(),".nex","servers.json"),fi=mi.join(gi.tmpdir(),"nex-ssh-sockets");function k_(){return mi.join(process.cwd(),".nex","servers.json")}function Xf(){let t=o=>{if(!di.existsSync(o))return{};try{return JSON.parse(di.readFileSync(o,"utf-8"))}catch{return{}}},e=t(__),s=t(k_());return{...e,...s}}function x_(t){let e=Xf();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 S_(){di.existsSync(fi)||di.mkdirSync(fi,{recursive:!0})}function Vf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,gi.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),S_();let s=t.user?`${t.user}@${t.host}`:t.host,o=mi.join(fi,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Jf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,gi.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function pi(t,e,{timeout:s=3e4,sudo:o=!1}={}){let{args:n}=Vf(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await xl("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:yi(l,t)}}}async function E_(t,e,s,{timeout:o=12e4}={}){let n=Jf(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await xl("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(yi(a,t)||a)}}async function v_(t,e,s,{timeout:o=12e4}={}){let n=Jf(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await xl("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(yi(a,t)||a)}}function yi(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
120
131
|
HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
121
132
|
HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
|
|
122
133
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
123
134
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
124
135
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
125
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
126
|
-
`).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return
|
|
127
|
-
${
|
|
128
|
-
`)}`}}return{fixedPath:null,message:""}}function
|
|
129
|
-
`,"utf-8")}
|
|
136
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function T_(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 hi=new Map,R_=12e4;async function Zf(t,e,{force:s=!1}={}){let n=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=hi.get(n);if(!s&&r&&Date.now()-r.time<R_)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 pi(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let c=e.endsWith("/")?e:e+"/",u=a.split(`
|
|
137
|
+
`).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return hi.set(n,{files:u,time:Date.now()}),u}async function Qf(t,e,s,{limit:o=5,minScore:n=15}={}){let r=await Zf(t,e);if(r.length===0)return[];let{scorePathMatch:i}=sn(),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 C_(t,e,s){if(!s)return{fixedPath:null,message:""};let o=s.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await pi(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await pi(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let n=await Qf(t,e,s,{limit:5,minScore:15});if(n.length>0){let i=(e.endsWith("/")?e:e+"/")+n[0].file;if(n[0].score>=200||n.length===1&&n[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${n[0].file})`};if(n.length>=2&&n[0].score>=80&&n[0].score>=n[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${n[0].file})`};if(n.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
|
|
138
|
+
${n.map(a=>` - ${a.file}`).join(`
|
|
139
|
+
`)}`}}return{fixedPath:null,message:""}}function A_(t){t?hi.delete(t):hi.clear()}ep.exports={loadServerProfiles:Xf,resolveProfile:x_,buildSSHArgs:Vf,sshExec:pi,scpUpload:E_,scpDownload:v_,enrichSSHError:yi,formatProfile:T_,SSH_SOCKET_DIR:fi,getRemoteIndex:Zf,remoteSmartSearch:Qf,remoteAutoFixPath:C_,clearRemoteIndex:A_}});var sp=V((Y1,np)=>{var Eo=require("fs"),Sl=require("path"),O_=Sl.join(".nex","deploy.json");function El(){return Sl.join(process.cwd(),O_)}function tp(){let t=El();if(!Eo.existsSync(t))return{};try{return JSON.parse(Eo.readFileSync(t,"utf-8"))}catch{return{}}}function N_(t){let e=tp();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 M_(t){let e=Sl.join(process.cwd(),".nex");Eo.existsSync(e)||Eo.mkdirSync(e,{recursive:!0}),Eo.writeFileSync(El(),JSON.stringify(t,null,2)+`
|
|
140
|
+
`,"utf-8")}np.exports={loadDeployConfigs:tp,resolveDeployConfig:N_,saveDeployConfigs:M_,getDeployConfigPath:El}});var Co=V((z1,ip)=>{var{getActiveModel:P_,getActiveProviderName:L_}=lt(),vo={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},To={"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"},Ro={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},on={};function rp(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(on=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{on={}}}rp();function vl(){let e=P_()?.id,s=L_();return e&&on[e]?on[e]:s&&on[`${s}:*`]?on[`${s}:*`]:e&&To[e]?To[e]:s&&Ro[s]?Ro[s]:"full"}var I_=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"]),op={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function j_(t,e){return t&&(I_.has(t)||t.startsWith("claude-"))?"strict":e&&op[e]?op[e]:"fuzzy"}function D_(t,e){return t&&on[t]?on[t]:e&&on[`${e}:*`]?on[`${e}:*`]:t&&To[t]?To[t]:e&&Ro[e]?Ro[e]:"full"}function q_(t,e){let s=e||vl();if(s==="full"||!vo[s])return t;let o=new Set(vo[s]);return t.filter(n=>o.has(n.function.name))}function F_(){let t=vl(),e=vo[t]?vo[t].length:"all";return{tier:t,toolCount:e}}ip.exports={filterToolsForModel:q_,getActiveTier:vl,getModelTier:D_,getEditMode:j_,getTierInfo:F_,TIERS:vo,MODEL_TIERS:To,PROVIDER_DEFAULT_TIER:Ro,loadConfigOverrides:rp}});var wn=V((K1,cp)=>{var Tl=null,yn=null,Ao=null,ap=`Playwright is not installed. Install with:
|
|
130
141
|
npm install playwright && npx playwright install chromium
|
|
131
|
-
Then restart nex-code.`;function
|
|
132
|
-
...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function gb(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await ci()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:n}),l=require("os"),c=require("path"),u=require("fs"),d=c.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a,{mode:384}),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function yb(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await ci()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function wb(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await ci()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}Yf.exports={isPlaywrightAvailable:Hf,browserNavigate:mb,browserScreenshot:gb,browserClick:yb,browserFill:wb,closeBrowser:hb,INSTALL_MSG:Wf}});var $l=V((w1,zf)=>{"use strict";var $b=require("util"),Gf=require("stream"),Yt=zf.exports=function(){Gf.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};$b.inherits(Yt,Gf);Yt.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};Yt.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let s;return Buffer.isBuffer(t)?s=t:s=Buffer.from(t,e||this._encoding),this._buffers.push(s),this._buffered+=s.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Yt.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};Yt.prototype.destroySoon=Yt.prototype.end;Yt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Yt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Yt.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};Yt.prototype._processRead=function(t){this._reads.shift();let e=0,s=0,n=Buffer.alloc(t.length);for(;e<t.length;){let o=this._buffers[s++],r=Math.min(o.length,t.length-e);o.copy(n,e,0,r),e+=r,r!==o.length&&(this._buffers[--s]=o.slice(r))}s>0&&this._buffers.splice(0,s),this._buffered-=t.length,t.func.call(this,n)};Yt.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var bl=V(_l=>{"use strict";var An=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];_l.getImagePasses=function(t,e){let s=[],n=t%8,o=e%8,r=(t-n)/8,i=(e-o)/8;for(let a=0;a<An.length;a++){let l=An[a],c=r*l.x.length,u=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<n;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<o;d++)u++;c>0&&u>0&&s.push({width:c,height:u,index:a})}return s};_l.getInterlaceIterator=function(t){return function(e,s,n){let o=e%An[n].x.length,r=(e-o)/An[n].x.length*8+An[n].x[o],i=s%An[n].y.length,a=(s-i)/An[n].y.length*8+An[n].y[i];return r*4+a*t*4}}});var kl=V((_1,Kf)=>{"use strict";Kf.exports=function(e,s,n){let o=e+s-n,r=Math.abs(o-e),i=Math.abs(o-s),a=Math.abs(o-n);return r<=i&&r<=a?e:i<=a?s:n}});var xl=V((b1,Vf)=>{"use strict";var _b=bl(),bb=kl();function Xf(t,e,s){let n=t*e;return s!==8&&(n=Math.ceil(n/(8/s))),n}var Ls=Vf.exports=function(t,e){let s=t.width,n=t.height,o=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],o){let a=_b.getImagePasses(s,n);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Xf(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Xf(s,r,i),height:n,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Ls.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ls.prototype._unFilterType1=function(t,e,s){let n=this._xComparison,o=n-1;for(let r=0;r<s;r++){let i=t[1+r],a=r>o?e[r-n]:0;e[r]=i+a}};Ls.prototype._unFilterType2=function(t,e,s){let n=this._lastLine;for(let o=0;o<s;o++){let r=t[1+o],i=n?n[o]:0;e[o]=r+i}};Ls.prototype._unFilterType3=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=Math.floor((c+l)/2);e[i]=a+u}};Ls.prototype._unFilterType4=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=i>o&&r?r[i-n]:0,d=bb(c,l,u);e[i]=a+d}};Ls.prototype._reverseFilterLine=function(t){let e=t[0],s,n=this._images[this._imageIndex],o=n.byteWidth;if(e===0)s=t.slice(1,o+1);else switch(s=Buffer.alloc(o),e){case 1:this._unFilterType1(t,s,o);break;case 2:this._unFilterType2(t,s,o);break;case 3:this._unFilterType3(t,s,o);break;case 4:this._unFilterType4(t,s,o);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(s),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=s,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Qf=V((k1,Zf)=>{"use strict";var kb=require("util"),Jf=$l(),xb=xl(),Sb=Zf.exports=function(t){Jf.call(this);let e=[],s=this;this._filter=new xb(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};kb.inherits(Sb,Jf)});var Is=V((x1,ep)=>{"use strict";ep.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var vl=V((S1,tp)=>{"use strict";var Sl=[];(function(){for(let t=0;t<256;t++){let e=t;for(let s=0;s<8;s++)e&1?e=3988292384^e>>>1:e=e>>>1;Sl[t]=e}})();var El=tp.exports=function(){this._crc=-1};El.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Sl[(this._crc^t[e])&255]^this._crc>>>8;return!0};El.prototype.crc32=function(){return this._crc^-1};El.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=Sl[(e^t[s])&255]^e>>>8;return e^-1}});var Tl=V((E1,np)=>{"use strict";var Ke=Is(),Eb=vl(),Ve=np.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Ke.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ke.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ke.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ke.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ke.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ke.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Ve.prototype.start=function(){this.read(Ke.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ve.prototype._parseSignature=function(t){let e=Ke.PNG_SIGNATURE;for(let s=0;s<e.length;s++)if(t[s]!==e[s]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ve.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n="";for(let r=4;r<8;r++)n+=String.fromCharCode(t[r]);let o=!!(t[4]&32);if(!this._hasIHDR&&s!==Ke.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Eb,this._crc.write(Buffer.from(n)),this._chunks[s])return this._chunks[s](e);if(!o){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};Ve.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ve.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ve.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),s=this._crc.crc32();if(this._options.checkCRC&&s!==e){this.error(new Error("Crc error - "+e+" - "+s));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};Ve.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Ve.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n=t[8],o=t[9],r=t[10],i=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(o in Ke.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=o;let l=Ke.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:s,depth:n,interlace:!!a,palette:!!(o&Ke.COLORTYPE_PALETTE),color:!!(o&Ke.COLORTYPE_COLOR),alpha:!!(o&Ke.COLORTYPE_ALPHA),bpp:l,colorType:o}),this._handleChunkEnd()};Ve.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Ve.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let s=0;s<e;s++)this._palette.push([t[s*3],t[s*3+1],t[s*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ve.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Ve.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Ke.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===Ke.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===Ke.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};Ve.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Ve.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Ke.GAMMA_DIVISION),this._handleChunkEnd()};Ve.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};Ve.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Ke.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let s=t-e.length;s>0?this._handleIDAT(s):this._handleChunkEnd()};Ve.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Ve.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Rl=V(op=>{"use strict";var sp=bl(),vb=[function(){},function(t,e,s,n){if(n===e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=255},function(t,e,s,n){if(n+1>=e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=e[n+1]},function(t,e,s,n){if(n+2>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=255},function(t,e,s,n){if(n+3>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=e[n+3]}],Tb=[function(){},function(t,e,s,n){let o=e[0];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=n},function(t,e,s){let n=e[0];t[s]=n,t[s+1]=n,t[s+2]=n,t[s+3]=e[1]},function(t,e,s,n){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=n},function(t,e,s){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=e[3]}];function Rb(t,e){let s=[],n=0;function o(){if(n===t.length)throw new Error("Ran out of data");let r=t[n];n++;let i,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[n],n++,s.push((r<<8)+f);break;case 4:f=r&15,p=r>>4,s.push(p,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,s.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,s.push(p,f,d,u,c,l,a,i);break}}return{get:function(r){for(;s.length<r;)o();let i=s.slice(0,r);return s=s.slice(r),i},resetAfterLine:function(){s.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function Cb(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<i;u++){let d=s(u,c,l);vb[n](e,o,d,r),r+=n}return r}function Ab(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<i;u++){let d=o.get(n),f=s(u,c,l);Tb[n](e,d,f,r)}o.resetAfterLine()}}op.dataToBitMap=function(t,e){let s=e.width,n=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=Rb(t,o));let l;o<=8?l=Buffer.alloc(s*n*4):l=new Uint16Array(s*n*4);let c=Math.pow(2,o)-1,u=0,d,f;if(i)d=sp.getImagePasses(s,n),f=sp.getInterlaceIterator(s,n);else{let p=0;f=function(){let m=p;return p+=4,m},d=[{width:s,height:n}]}for(let p=0;p<d.length;p++)o===8?u=Cb(d[p],l,f,r,t,u):Ab(d[p],l,f,r,a,c);if(o===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Cl=V((T1,rp)=>{"use strict";function Ob(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=o[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let c=0;c<4;c++)e[r+c]=l[c];r+=4}}function Nb(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=!1;if(o.length===1?o[0]===t[r]&&(l=!0):o[0]===t[r]&&o[1]===t[r+1]&&o[2]===t[r+2]&&(l=!0),l)for(let c=0;c<4;c++)e[r+c]=0;r+=4}}function Mb(t,e,s,n,o){let r=255,i=Math.pow(2,o)-1,a=0;for(let l=0;l<n;l++)for(let c=0;c<s;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}rp.exports=function(t,e,s=!1){let n=e.depth,o=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,c=t;return i===3?Ob(t,c,o,r,l):(a&&Nb(t,c,o,r,a),n!==8&&!s&&(n===16&&(c=Buffer.alloc(o*r*4)),Mb(t,c,o,r,n))),c}});var lp=V((R1,ap)=>{"use strict";var Pb=require("util"),Al=require("zlib"),ip=$l(),Lb=Qf(),Ib=Tl(),jb=Rl(),Db=Cl(),nn=ap.exports=function(t){ip.call(this),this._parser=new Ib(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Pb.inherits(nn,ip);nn.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};nn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Al.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let s=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(s,Al.Z_MIN_CHUNK);this._inflate=Al.createInflate({chunkSize:n});let o=s,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){o&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){o&&(a.length>o&&(a=a.slice(0,o)),o-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};nn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Lb(this._bitmapInfo)};nn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};nn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};nn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};nn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};nn.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};nn.prototype._complete=function(t){if(this.errord)return;let e;try{let s=jb.dataToBitMap(t,this._bitmapInfo);e=Db(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var up=V((C1,cp)=>{"use strict";var It=Is();cp.exports=function(t,e,s,n){let o=[It.COLORTYPE_COLOR_ALPHA,It.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let m=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&m)return t}let r=n.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=It.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let l=It.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*s*l),u=0,d=0,f=n.bgColor||{};f.red===void 0&&(f.red=i),f.green===void 0&&(f.green=i),f.blue===void 0&&(f.blue=i);function p(){let m,g,$,k=i;switch(n.inputColorType){case It.COLORTYPE_COLOR_ALPHA:k=r[u+3],m=r[u],g=r[u+1],$=r[u+2];break;case It.COLORTYPE_COLOR:m=r[u],g=r[u+1],$=r[u+2];break;case It.COLORTYPE_ALPHA:k=r[u+1],m=r[u],g=m,$=m;break;case It.COLORTYPE_GRAYSCALE:m=r[u],g=m,$=m;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(o||(k/=i,m=Math.min(Math.max(Math.round((1-k)*f.red+k*m),0),i),g=Math.min(Math.max(Math.round((1-k)*f.green+k*g),0),i),$=Math.min(Math.max(Math.round((1-k)*f.blue+k*$),0),i))),{red:m,green:g,blue:$,alpha:k}}for(let m=0;m<s;m++)for(let g=0;g<e;g++){let $=p(r,u);switch(n.colorType){case It.COLORTYPE_COLOR_ALPHA:case It.COLORTYPE_COLOR:n.bitDepth===8?(c[d]=$.red,c[d+1]=$.green,c[d+2]=$.blue,o&&(c[d+3]=$.alpha)):(c.writeUInt16BE($.red,d),c.writeUInt16BE($.green,d+2),c.writeUInt16BE($.blue,d+4),o&&c.writeUInt16BE($.alpha,d+6));break;case It.COLORTYPE_ALPHA:case It.COLORTYPE_GRAYSCALE:{let k=($.red+$.green+$.blue)/3;n.bitDepth===8?(c[d]=k,o&&(c[d+1]=$.alpha)):(c.writeUInt16BE(k,d),o&&c.writeUInt16BE($.alpha,d+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}u+=a,d+=l}return c}});var pp=V((A1,fp)=>{"use strict";var dp=kl();function qb(t,e,s,n,o){for(let r=0;r<s;r++)n[o+r]=t[e+r]}function Fb(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++)n+=Math.abs(t[r]);return n}function Bb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;n[o+i]=l}}function Ub(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=t[e+r]-i;o+=Math.abs(a)}return o}function Wb(t,e,s,n,o){for(let r=0;r<s;r++){let i=e>0?t[e+r-s]:0,a=t[e+r]-i;n[o+r]=a}}function Hb(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++){let i=e>0?t[r-s]:0,a=t[r]-i;n+=Math.abs(a)}return n}function Yb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=t[e+i]-(a+l>>1);n[o+i]=c}}function Gb(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=t[e+r]-(i+a>>1);o+=Math.abs(l)}return o}function zb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=e>0&&i>=r?t[e+i-(s+r)]:0,u=t[e+i]-dp(a,l,c);n[o+i]=u}}function Kb(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=e>0&&r>=n?t[e+r-(s+n)]:0,c=t[e+r]-dp(i,a,l);o+=Math.abs(c)}return o}var Xb={0:qb,1:Bb,2:Wb,3:Yb,4:zb},Vb={0:Fb,1:Ub,2:Hb,3:Gb,4:Kb};fp.exports=function(t,e,s,n,o){let r;if(!("filterType"in n)||n.filterType===-1)r=[0,1,2,3,4];else if(typeof n.filterType=="number")r=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(o*=2);let i=e*o,a=0,l=0,c=Buffer.alloc((i+1)*s),u=r[0];for(let d=0;d<s;d++){if(r.length>1){let f=1/0;for(let p=0;p<r.length;p++){let m=Vb[r[p]](t,l,i,o);m<f&&(u=r[p],f=m)}}c[a]=u,a++,Xb[u](t,l,i,c,a,o),a+=i,l+=i}return c}});var Ol=V((O1,hp)=>{"use strict";var ct=Is(),Jb=vl(),Zb=up(),Qb=pp(),ek=require("zlib"),On=hp.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||ek.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:ct.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:ct.COLORTYPE_COLOR_ALPHA,[ct.COLORTYPE_GRAYSCALE,ct.COLORTYPE_COLOR,ct.COLORTYPE_COLOR_ALPHA,ct.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([ct.COLORTYPE_GRAYSCALE,ct.COLORTYPE_COLOR,ct.COLORTYPE_COLOR_ALPHA,ct.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};On.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};On.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};On.prototype.filterData=function(t,e,s){let n=Zb(t,e,s,this._options),o=ct.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Qb(n,e,s,this._options,o)};On.prototype._packChunk=function(t,e){let s=e?e.length:0,n=Buffer.alloc(s+12);return n.writeUInt32BE(s,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(Jb.crc32(n.slice(4,n.length-4)),n.length-4),n};On.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*ct.GAMMA_DIVISION),0),this._packChunk(ct.TYPE_gAMA,e)};On.prototype.packIHDR=function(t,e){let s=Buffer.alloc(13);return s.writeUInt32BE(t,0),s.writeUInt32BE(e,4),s[8]=this._options.bitDepth,s[9]=this._options.colorType,s[10]=0,s[11]=0,s[12]=0,this._packChunk(ct.TYPE_IHDR,s)};On.prototype.packIDAT=function(t){return this._packChunk(ct.TYPE_IDAT,t)};On.prototype.packIEND=function(){return this._packChunk(ct.TYPE_IEND,null)}});var wp=V((N1,yp)=>{"use strict";var tk=require("util"),mp=require("stream"),nk=Is(),sk=Ol(),gp=yp.exports=function(t){mp.call(this);let e=t||{};this._packer=new sk(e),this._deflate=this._packer.createDeflate(),this.readable=!0};tk.inherits(gp,mp);gp.prototype.pack=function(t,e,s,n){this.emit("data",Buffer.from(nk.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,s)),n&&this.emit("data",this._packer.packGAMA(n));let o=this._packer.filterData(t,e,s);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(o)}});var Sp=V((Eo,xp)=>{"use strict";var $p=require("assert").ok,js=require("zlib"),ok=require("util"),_p=require("buffer").kMaxLength;function Kn(t){if(!(this instanceof Kn))return new Kn(t);t&&t.chunkSize<js.Z_MIN_CHUNK&&(t.chunkSize=js.Z_MIN_CHUNK),js.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function rk(t){return new Kn(t)}function bp(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Kn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return js.Inflate._processChunk.call(this,t,e,s);let n=this,o=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(m){u=m});function d(m,g){if(n._hadError)return;let $=r-g;if($p($>=0,"have should not go down"),$>0){let k=n._buffer.slice(n._offset,n._offset+$);if(n._offset+=$,k.length>i&&(k=k.slice(0,i)),l.push(k),c+=k.length,i-=k.length,i===0)return!1}return(g===0||n._offset>=n._chunkSize)&&(r=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),g===0?(a+=o-m,o=m,!0):!1}$p(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,o,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=_p)throw bp(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+_p.toString(16)+" bytes");let p=Buffer.concat(l,c);return bp(this),p};ok.inherits(Kn,js.Inflate);function ik(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let s=t._finishFlushFlag;return s==null&&(s=js.Z_FINISH),t._processChunk(e,s)}function kp(t,e){return ik(new Kn(e),t)}xp.exports=Eo=kp;Eo.Inflate=Kn;Eo.createInflate=rk;Eo.inflateSync=kp});var Nl=V((M1,vp)=>{"use strict";var Ep=vp.exports=function(t){this._buffer=t,this._reads=[]};Ep.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Ep.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw new Error("unrecognised content at end of stream")}});var Rp=V(Tp=>{"use strict";var ak=Nl(),lk=xl();Tp.process=function(t,e){let s=[],n=new ak(t);return new lk(e,{read:n.read.bind(n),write:function(r){s.push(r)},complete:function(){}}).start(),n.process(),Buffer.concat(s)}});var Np=V((L1,Op)=>{"use strict";var Cp=!0,Ap=require("zlib"),ck=Sp();Ap.deflateSync||(Cp=!1);var uk=Nl(),dk=Rp(),fk=Tl(),pk=Rl(),hk=Cl();Op.exports=function(t,e){if(!Cp)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s;function n(v){s=v}let o;function r(v){o=v}function i(v){o.transColor=v}function a(v){o.palette=v}function l(){o.alpha=!0}let c;function u(v){c=v}let d=[];function f(v){d.push(v)}let p=new uk(t);if(new fk(e,{read:p.read.bind(p),error:n,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),p.process(),s)throw s;let g=Buffer.concat(d);d.length=0;let $;if(o.interlace)$=Ap.inflateSync(g);else{let E=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;$=ck(g,{chunkSize:E,maxLength:E})}if(g=null,!$||!$.length)throw new Error("bad png - invalid inflate data response");let k=dk.process($,o);g=null;let M=pk.dataToBitMap(k,o);k=null;let D=hk(M,o,e.skipRescale);return o.data=D,o.gamma=c||0,o}});var Ip=V((I1,Lp)=>{"use strict";var Mp=!0,Pp=require("zlib");Pp.deflateSync||(Mp=!1);var mk=Is(),gk=Ol();Lp.exports=function(t,e){if(!Mp)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s=e||{},n=new gk(s),o=[];o.push(Buffer.from(mk.PNG_SIGNATURE)),o.push(n.packIHDR(t.width,t.height)),t.gamma&&o.push(n.packGAMA(t.gamma));let r=n.filterData(t.data,t.width,t.height),i=Pp.deflateSync(r,n.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return o.push(n.packIDAT(i)),o.push(n.packIEND()),Buffer.concat(o)}});var jp=V(Ml=>{"use strict";var yk=Np(),wk=Ip();Ml.read=function(t,e){return yk(t,e||{})};Ml.write=function(t,e){return wk(t,e)}});var Fp=V(qp=>{"use strict";var $k=require("util"),Dp=require("stream"),_k=lp(),bk=wp(),kk=jp(),pt=qp.PNG=function(t){Dp.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new _k(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new bk(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};$k.inherits(pt,Dp);pt.sync=kk;pt.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};pt.prototype.parse=function(t,e){if(e){let s,n;s=function(o){this.removeListener("error",n),this.data=o,e(null,this)}.bind(this),n=function(o){this.removeListener("parsed",s),e(o,null)}.bind(this),this.once("parsed",s),this.once("error",n)}return this.end(t),this};pt.prototype.write=function(t){return this._parser.write(t),!0};pt.prototype.end=function(t){this._parser.end(t)};pt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};pt.prototype._gamma=function(t){this.gamma=t};pt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};pt.bitblt=function(t,e,s,n,o,r,i,a){if(s|=0,n|=0,o|=0,r|=0,i|=0,a|=0,s>t.width||n>t.height||s+o>t.width||n+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+o>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<r;l++)t.data.copy(e.data,(a+l)*e.width+i<<2,(n+l)*t.width+s<<2,(n+l)*t.width+s+o<<2)};pt.prototype.bitblt=function(t,e,s,n,o,r,i){return pt.bitblt(this,t,e,s,n,o,r,i),this};pt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let s=0;s<t.width;s++){let n=t.width*e+s<<2;for(let o=0;o<3;o++){let r=t.data[n+o]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[n+o]=Math.round(r*255)}}t.gamma=0}};pt.prototype.adjustGamma=function(){pt.adjustGamma(this)}});var Yp={};p0(Yp,{default:()=>Wp});function Wp(t,e,s,n,o,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:c=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=r;if(!Pl(t)||!Pl(e)||s&&!Pl(s))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||s&&s.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==n*o*4)throw new Error("Image data size does not match width/height.");let p=n*o,m=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),$=!0;for(let S=0;S<p;S++)if(m[S]!==g[S]){$=!1;break}if($){if(s&&!f)for(let S=0;S<p;S++)Up(t,4*S,a,s);return 0}let k=35215*i*i,[M,D,v]=l,[E,A,ee]=c,[se,ue,ae]=d||c,te=0;for(let S=0;S<o;S++)for(let ve=0;ve<n;ve++){let W=S*n+ve,z=W*4,me=m[W]===g[W]?0:Hp(t,e,z,z,!1);if(Math.abs(me)>k){let Ce=Bp(t,ve,S,n,o,m,g)||Bp(e,ve,S,n,o,g,m);!u&&Ce?s&&!f&&di(s,z,M,D,v):(s&&(me<0?di(s,z,se,ue,ae):di(s,z,E,A,ee)),te++)}else s&&!f&&Up(t,z,a,s)}return te}function Pl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Bp(t,e,s,n,o,r,i){let a=Math.max(e-1,0),l=Math.max(s-1,0),c=Math.min(e+1,n-1),u=Math.min(s+1,o-1),d=s*n+e,f=e===a||e===c||s===l||s===u?1:0,p=0,m=0,g=0,$=0,k=0,M=0;for(let D=a;D<=c;D++)for(let v=l;v<=u;v++){if(D===e&&v===s)continue;let E=Hp(t,t,d*4,(v*n+D)*4,!0);if(E===0){if(f++,f>2)return!1}else E<p?(p=E,g=D,$=v):E>m&&(m=E,k=D,M=v)}return p===0||m===0?!1:ui(r,g,$,n,o)&&ui(i,g,$,n,o)||ui(r,k,M,n,o)&&ui(i,k,M,n,o)}function ui(t,e,s,n,o){let r=Math.max(e-1,0),i=Math.max(s-1,0),a=Math.min(e+1,n-1),l=Math.min(s+1,o-1),c=t[s*n+e],u=e===r||e===a||s===i||s===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===s)&&(u+=+(c===t[f*n+d]),u>2))return!0;return!1}function Hp(t,e,s,n,o){let r=t[s],i=t[s+1],a=t[s+2],l=t[s+3],c=e[n],u=e[n+1],d=e[n+2],f=e[n+3],p=r-c,m=i-u,g=a-d,$=l-f;if(!p&&!m&&!g&&!$)return 0;if(l<255||f<255){let E=48+159*(s%2),A=48+159*((s/1.618033988749895|0)%2),ee=48+159*((s/2.618033988749895|0)%2);p=(r*l-c*f-E*$)/255,m=(i*l-u*f-A*$)/255,g=(a*l-d*f-ee*$)/255}let k=p*.29889531+m*.58662247+g*.11448223;if(o)return k;let M=p*.59597799-m*.2741761-g*.32180189,D=p*.21147017-m*.52261711+g*.31114694,v=.5053*k*k+.299*M*M+.1957*D*D;return k>0?-v:v}function di(t,e,s,n,o){t[e+0]=s,t[e+1]=n,t[e+2]=o,t[e+3]=255}function Up(t,e,s,n){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;di(n,e,o,o,o)}var Gp=f0(()=>{});var Xn=V((q1,Jp)=>{var wn=require("fs"),xk=require("path"),Sk=require("os"),Ek="nex-visual-";function Kp(t){return xk.join(Sk.tmpdir(),`${Ek}${Date.now()}-${t}`)}var Ll=null;function fi(){return Ll||(Ll=Fp().PNG),Ll}var Il=null;function vk(){if(!Il){let t=(Gp(),m0(Yp));Il=t.default||t}return Il}function ql(t,e,{threshold:s=.1}={}){let n=fi(),o=vk(),r=n.sync.read(wn.readFileSync(t)),i=n.sync.read(wn.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=zp(r,a,l),u=zp(i,a,l),d=new n({width:a,height:l}),f=o(c,u,d.data,a,l,{threshold:s,includeAA:!1}),p=a*l,m=(f/p*100).toFixed(1),g=Tk(d.data,a,l,3,3),$=Kp("diff.png");return wn.writeFileSync($,n.sync.write(d),{mode:384}),{diffPath:$,diffPercent:parseFloat(m),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function zp(t,e,s){if(t.width===e&&t.height===s)return t.data;let n=Buffer.alloc(e*s*4,0);for(let o=0;o<t.height;o++){let r=o*t.width*4,i=o*e*4;t.data.copy(n,i,r,r+t.width*4)}return n}function Tk(t,e,s,n,o){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/n),a=Math.ceil(s/o),l=[];for(let c=0;c<o;c++)for(let u=0;u<n;u++){let d=0,f=0,p=u*i,m=c*a,g=Math.min(p+i,e),$=Math.min(m+a,s);for(let k=m;k<$;k++)for(let M=p;M<g;M++){f++;let D=(k*e+M)*4;(t[D]>0||t[D+1]>0)&&d++}if(d>0){let k=(d/f*100).toFixed(1),M=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:M,changedPercent:parseFloat(k),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var Xp=[{width:320,label:"mobile-sm"},{width:768,label:"tablet"},{width:1024,label:"desktop-sm"},{width:1440,label:"desktop"},{width:1920,label:"desktop-lg"}];async function Rk(t,{viewports:e=Xp,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=yn(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:s,fullPage:n,timeout:o});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function Vp(t,e=[]){let s=fi(),n=s.sync.read(wn.readFileSync(t));for(let i of e){let a=Ck(i.color||"#FF0000");i.type==="box"?(Ak(n,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Dl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(Ok(n,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Dl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(Nk(n,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Dl(n,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=Kp("annotated.png");wn.writeFileSync(o,s.sync.write(n),{mode:384});let r=wn.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function Ck(t){let e=t.replace("#","");return{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16),a:255}}function sn(t,e,s,n){if(e<0||s<0||e>=t.width||s>=t.height)return;let o=(s*t.width+e)*4;t.data[o]=n.r,t.data[o+1]=n.g,t.data[o+2]=n.b,t.data[o+3]=n.a}function Ak(t,e,s,n,o,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<n;l++)sn(t,e+l,s+a,r),sn(t,e+l,s+o-1-a,r);for(let l=0;l<o;l++)sn(t,e+a,s+l,r),sn(t,e+n-1-a,s+l,r)}}function jl(t,e,s,n,o,r,i=3){let a=Math.abs(n-e),l=Math.abs(o-s),c=e<n?1:-1,u=s<o?1:-1,d=a-l,f=e,p=s;for(;;){let m=Math.floor(i/2);for(let $=-m;$<=m;$++)for(let k=-m;k<=m;k++)sn(t,f+$,p+k,r);if(f===n&&p===o)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,p+=u)}}function Ok(t,e,s,n,o,r,i=3){jl(t,e,s,n,o,r,i);let a=Math.atan2(o-s,n-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;jl(t,n,o,Math.round(n+l*Math.cos(c)),Math.round(o+l*Math.sin(c)),r,i),jl(t,n,o,Math.round(n+l*Math.cos(u)),Math.round(o+l*Math.sin(u)),r,i)}function Nk(t,e,s,n,o,r=3){for(let i=0;i<r;i++){let a=n-i;for(let l=0;l<360;l+=.5){let c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(s+a*Math.sin(c));sn(t,u,d,o)}}}function Dl(t,e,s,n,o){let i=n.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)sn(t,e+c,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)sn(t,e+l,s+a-1,o),sn(t,e+l,s+a-2,o);for(let l=0;l<n.length;l++){let c=e+2+l*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)sn(t,c+d,s+u,o)}}async function*Mk(t,e,{maxIterations:s=20,hmrDelay:n=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=yn(),l=Pk("chokidar"),c=await a(t,{width:o,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:c.path,base64:c.base64,media_type:c.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let u=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;u<s;){await Ik(()=>d,3e5),d=!1,u++,await Lk(n);let p=await a(t,{width:o,height:r,timeout:i}),m=null;try{m=ql(c.path,p.path)}catch{}c=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function Pk(t){try{return require(t)}catch{return null}}function Lk(t){return new Promise(e=>setTimeout(e,t))}function Ik(t,e=6e4){return new Promise((s,n)=>{let o=setInterval(()=>{t()&&(clearInterval(o),clearTimeout(r),s())},200),r=setTimeout(()=>{clearInterval(o),n(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function jk(t,{sampleRate:e=4}={}){let n=fi().sync.read(wn.readFileSync(t)),o=new Map;for(let c=0;c<n.height;c+=e)for(let u=0;u<n.width;u+=e){let d=(c*n.width+u)*4,f=n.data[d],p=n.data[d+1],m=n.data[d+2];if(n.data[d+3]<128)continue;let $=Math.round(f/8)*8,k=Math.round(p/8)*8,M=Math.round(m/8)*8,D=`${$},${k},${M}`;o.set(D,(o.get(D)||0)+1)}let r=[...o.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,p]=c.split(",").map(Number);return{hex:Dk(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:qk(d,f,p)}}),l=Fk(n);return{colors:a,spacing:l,dimensions:{width:n.width,height:n.height},imagePath:t}}function Dk(t,e,s){return"#"+[t,e,s].map(n=>Math.min(255,n).toString(16).padStart(2,"0")).join("")}function qk(t,e,s){let n=(t*299+e*587+s*114)/1e3;return n>240?"white/background":n<30?"black/text":n<80?"dark":t>200&&e<100&&s<100?"red/danger":t<100&&e>150&&s<100?"green/success":t<100&&e<100&&s>200?"blue/primary":t>200&&e>200&&s<100?"yellow/warning":t>200&&e>100&&s<50?"orange/accent":n>200?"light/subtle":"midtone"}function Fk(t){let e=[],s=!1,n=0,o=Bk(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let c=(i*t.width+l)*4;if(Math.abs(t.data[c]-o.r)>20||Math.abs(t.data[c+1]-o.g)>20||Math.abs(t.data[c+2]-o.b)>20){a=!1;break}}if(a&&s)s=!1,n=i;else if(!a&&!s&&(s=!0,n>0)){let l=i-n;l>=4&&l<=200&&e.push(l)}}let r=new Map;for(let i of e){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function Bk(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],s=0,n=0,o=0;for(let[r,i]of e){let a=(i*t.width+r)*4;s+=t.data[a],n+=t.data[a+1],o+=t.data[a+2]}return{r:Math.round(s/4),g:Math.round(n/4),b:Math.round(o/4)}}async function Uk(t,e,{width:s,height:n=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=yn(),c=fi().sync.read(wn.readFileSync(e)),u=s||c.width,d=n||c.height,f=await a(t,{width:u,height:d,fullPage:o,timeout:i}),p=ql(e,f.path,{threshold:r}),m=Vp(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,$)=>{let D=Math.ceil(p.width/3),v=Math.ceil(p.height/3),E=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],A=0,ee=0;for(let se=0;se<3;se++)for(let ue=0;ue<3;ue++)E[se][ue]===g.name&&(A=ue,ee=se);return{type:"box",x:A*D+2,y:ee*v+2,width:D-4,height:v-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:p.diffPath,annotatedPath:m.path,diffPercent:p.diffPercent,changedPixels:p.changedPixels,totalPixels:p.totalPixels,regions:p.regionSummary,liveBase64:f.base64,diffBase64:wn.readFileSync(p.diffPath).toString("base64"),annotatedBase64:m.base64}}Jp.exports={pixelDiff:ql,responsiveSweep:Rk,annotateImage:Vp,visualWatch:Mk,extractDesignTokens:jk,designCompare:Uk,DEFAULT_VIEWPORTS:Xp}});var Fl=V((F1,Zp)=>{var{C:Le}=tt(),To="",ht=[],vo=0,Vn=null;function Wk(t){Vn=t}function Hk(t,e){To=t,ht=[],vo=0;for(let n of e){vo++;let o=`t${vo}`;ht.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${vo}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=ht.map(n=>({...n}));return Vn&&Vn("create",{name:t,tasks:s}),s}function Yk(t,e,s){let n=ht.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Vn&&Vn("update",{id:t,status:e,result:s}),{...n}):null}function Gk(){return{name:To,tasks:ht.map(t=>({...t}))}}function zk(){To="",ht=[],vo=0,Vn&&Vn("clear",{})}function Kk(){return ht.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=ht.find(n=>n.id===e);return s&&s.status==="done"}))}function Xk(){if(ht.length===0)return`${Le.dim}No active tasks${Le.reset}`;let t=[];To&&(t.push(` ${Le.bold}${Le.cyan}Tasks: ${To}${Le.reset}`),t.push(` ${Le.dim}${"\u2500".repeat(40)}${Le.reset}`));for(let o of ht){let r,i;switch(o.status){case"done":r="\u2713",i=Le.green;break;case"in_progress":r="\u2192",i=Le.cyan;break;case"failed":r="\u2717",i=Le.red;break;default:r="\xB7",i=Le.dim}let a=o.dependsOn.length>0?` ${Le.dim}(after: ${o.dependsOn.join(", ")})${Le.reset}`:"",l=`[${o.status}]`,c=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Le.reset} ${Le.bold}${o.id}${Le.reset} ${c.padEnd(40)} ${i}${l}${Le.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Le.dim}\u2192 ${u}${Le.reset}`)}}let e=ht.filter(o=>o.status==="done").length,s=ht.filter(o=>o.status==="failed").length,n=ht.length;return t.push(` ${Le.dim}${"\u2500".repeat(40)}${Le.reset}`),t.push(` ${Le.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Le.reset}`),t.join(`
|
|
133
|
-
`)}function
|
|
142
|
+
Then restart nex-code.`;function lp(){if(Ao!==null)return Ao;try{require("playwright"),Ao=!0}catch{Ao=!1}return Ao}async function wi(){if(!lp())throw new Error(ap);return Tl||(Tl=require("playwright")),(!yn||!yn.isConnected())&&(yn=await Tl.chromium.launch({headless:!0})),yn}async function B_(){if(yn){try{await yn.close()}catch(t){console.error("closeBrowser failed:",t.message)}yn=null}}process.on("exit",()=>{if(yn)try{yn.close()}catch(t){console.error("Error closing browser on exit:",t.message)}});async function U_(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let n=await(await wi()).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?`
|
|
143
|
+
...(truncated)`:""),links:a.slice(0,20)}}finally{await n.close()}}async function W_(t,{width:e=1280,height:s=800,fullPage:o=!1,timeout:n=3e4}={}){let i=await(await wi()).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 H_(t,{selector:e,text:s,timeout:o=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await wi()).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 G_(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 wi()).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()}}cp.exports={isPlaywrightAvailable:lp,browserNavigate:U_,browserScreenshot:W_,browserClick:H_,browserFill:G_,closeBrowser:B_,INSTALL_MSG:ap}});var Rl=V((X1,dp)=>{"use strict";var Y_=require("util"),up=require("stream"),Gt=dp.exports=function(){up.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Y_.inherits(Gt,up);Gt.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))};Gt.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};Gt.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()))};Gt.prototype.destroySoon=Gt.prototype.end;Gt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Gt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Gt.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))};Gt.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)};Gt.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 Al=V(Cl=>{"use strict";var An=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];Cl.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<An.length;a++){let l=An[a],c=r*l.x.length,u=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<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};Cl.getInterlaceIterator=function(t){return function(e,s,o){let n=e%An[o].x.length,r=(e-n)/An[o].x.length*8+An[o].x[n],i=s%An[o].y.length,a=(s-i)/An[o].y.length*8+An[o].y[i];return r*4+a*t*4}}});var Ol=V((J1,fp)=>{"use strict";fp.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 Nl=V((Z1,hp)=>{"use strict";var z_=Al(),K_=Ol();function pp(t,e,s){let o=t*e;return s!==8&&(o=Math.ceil(o/(8/s))),o}var Is=hp.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=z_.getImagePasses(s,o);for(let l=0;l<a.length;l++)this._images.push({byteWidth:pp(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:pp(s,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Is.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Is.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}};Is.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}};Is.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}};Is.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=K_(c,l,u);e[i]=a+d}};Is.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 yp=V((Q1,gp)=>{"use strict";var X_=require("util"),mp=Rl(),V_=Nl(),J_=gp.exports=function(t){mp.call(this);let e=[],s=this;this._filter=new V_(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};X_.inherits(J_,mp)});var js=V((eC,wp)=>{"use strict";wp.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 Ll=V((tC,$p)=>{"use strict";var Ml=[];(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;Ml[t]=e}})();var Pl=$p.exports=function(){this._crc=-1};Pl.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Ml[(this._crc^t[e])&255]^this._crc>>>8;return!0};Pl.prototype.crc32=function(){return this._crc^-1};Pl.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=Ml[(e^t[s])&255]^e>>>8;return e^-1}});var Il=V((nC,bp)=>{"use strict";var Xe=js(),Z_=Ll(),Je=bp.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[Xe.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Xe.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Xe.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Xe.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Xe.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Xe.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(){}};Je.prototype.start=function(){this.read(Xe.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Je.prototype._parseSignature=function(t){let e=Xe.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))};Je.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!==Xe.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Z_,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))};Je.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Je.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Je.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))};Je.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Je.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 Xe.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=Xe.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:s,depth:o,interlace:!!a,palette:!!(n&Xe.COLORTYPE_PALETTE),color:!!(n&Xe.COLORTYPE_COLOR),alpha:!!(n&Xe.COLORTYPE_ALPHA),bpp:l,colorType:n}),this._handleChunkEnd()};Je.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Je.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()};Je.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Je.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Xe.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===Xe.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===Xe.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};Je.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Je.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Xe.GAMMA_DIVISION),this._handleChunkEnd()};Je.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};Je.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Xe.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()};Je.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Je.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var jl=V(kp=>{"use strict";var _p=Al(),Q_=[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]}],ek=[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 tk(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 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=s(u,c,l);Q_[o](e,n,d,r),r+=o}return r}function sk(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);ek[o](e,d,f,r)}n.resetAfterLine()}}kp.dataToBitMap=function(t,e){let s=e.width,o=e.height,n=e.depth,r=e.bpp,i=e.interlace,a;n!==8&&(a=tk(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=_p.getImagePasses(s,o),f=_p.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=nk(d[p],l,f,r,t,u):sk(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 Dl=V((oC,xp)=>{"use strict";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=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 rk(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 ik(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}}xp.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?ok(t,c,n,r,l):(a&&rk(t,c,n,r,a),o!==8&&!s&&(o===16&&(c=Buffer.alloc(n*r*4)),ik(t,c,n,r,o))),c}});var vp=V((rC,Ep)=>{"use strict";var ak=require("util"),ql=require("zlib"),Sp=Rl(),lk=yp(),ck=Il(),uk=jl(),dk=Dl(),rn=Ep.exports=function(t){Sp.call(this),this._parser=new ck(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()};ak.inherits(rn,Sp);rn.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};rn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=ql.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,ql.Z_MIN_CHUNK);this._inflate=ql.createInflate({chunkSize:o});let n=s,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){n&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){n&&(a.length>n&&(a=a.slice(0,n)),n-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};rn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new lk(this._bitmapInfo)};rn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};rn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};rn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};rn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};rn.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};rn.prototype._complete=function(t){if(this.errord)return;let e;try{let s=uk.dataToBitMap(t,this._bitmapInfo);e=dk(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var Rp=V((iC,Tp)=>{"use strict";var It=js();Tp.exports=function(t,e,s,o){let n=[It.COLORTYPE_COLOR_ALPHA,It.COLORTYPE_ALPHA].indexOf(o.colorType)!==-1;if(o.colorType===o.inputColorType){let m=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(o.bitDepth===8||o.bitDepth===16&&m)return t}let r=o.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=It.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let l=It.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,l*=2);let 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,$,x=i;switch(o.inputColorType){case It.COLORTYPE_COLOR_ALPHA:x=r[u+3],m=r[u],g=r[u+1],$=r[u+2];break;case It.COLORTYPE_COLOR:m=r[u],g=r[u+1],$=r[u+2];break;case It.COLORTYPE_ALPHA:x=r[u+1],m=r[u],g=m,$=m;break;case It.COLORTYPE_GRAYSCALE:m=r[u],g=m,$=m;break;default:throw new Error("input color type:"+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 $=p(r,u);switch(o.colorType){case It.COLORTYPE_COLOR_ALPHA:case It.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 It.COLORTYPE_ALPHA:case It.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 Op=V((aC,Ap)=>{"use strict";var Cp=Ol();function fk(t,e,s,o,n){for(let r=0;r<s;r++)o[n+r]=t[e+r]}function pk(t,e,s){let o=0,n=e+s;for(let r=e;r<n;r++)o+=Math.abs(t[r]);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=t[e+i]-a;o[n+i]=l}}function mk(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 gk(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 yk(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 wk(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 $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=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]-Cp(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]-Cp(i,a,l);n+=Math.abs(c)}return n}var kk={0:fk,1:hk,2:gk,3:wk,4:bk},xk={0:pk,1:mk,2:yk,3:$k,4:_k};Ap.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++,kk[u](t,l,i,c,a,n),a+=i,l+=i}return c}});var Fl=V((lC,Np)=>{"use strict";var ct=js(),Sk=Ll(),Ek=Rp(),vk=Op(),Tk=require("zlib"),On=Np.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||Tk.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:ct.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:ct.COLORTYPE_COLOR_ALPHA,[ct.COLORTYPE_GRAYSCALE,ct.COLORTYPE_COLOR,ct.COLORTYPE_COLOR_ALPHA,ct.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([ct.COLORTYPE_GRAYSCALE,ct.COLORTYPE_COLOR,ct.COLORTYPE_COLOR_ALPHA,ct.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};On.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};On.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};On.prototype.filterData=function(t,e,s){let o=Ek(t,e,s,this._options),n=ct.COLORTYPE_TO_BPP_MAP[this._options.colorType];return vk(o,e,s,this._options,n)};On.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(Sk.crc32(o.slice(4,o.length-4)),o.length-4),o};On.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*ct.GAMMA_DIVISION),0),this._packChunk(ct.TYPE_gAMA,e)};On.prototype.packIHDR=function(t,e){let s=Buffer.alloc(13);return s.writeUInt32BE(t,0),s.writeUInt32BE(e,4),s[8]=this._options.bitDepth,s[9]=this._options.colorType,s[10]=0,s[11]=0,s[12]=0,this._packChunk(ct.TYPE_IHDR,s)};On.prototype.packIDAT=function(t){return this._packChunk(ct.TYPE_IDAT,t)};On.prototype.packIEND=function(){return this._packChunk(ct.TYPE_IEND,null)}});var Ip=V((cC,Lp)=>{"use strict";var Rk=require("util"),Mp=require("stream"),Ck=js(),Ak=Fl(),Pp=Lp.exports=function(t){Mp.call(this);let e=t||{};this._packer=new Ak(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Rk.inherits(Pp,Mp);Pp.prototype.pack=function(t,e,s,o){this.emit("data",Buffer.from(Ck.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 Up=V((Oo,Bp)=>{"use strict";var jp=require("assert").ok,Ds=require("zlib"),Ok=require("util"),Dp=require("buffer").kMaxLength;function Vn(t){if(!(this instanceof Vn))return new Vn(t);t&&t.chunkSize<Ds.Z_MIN_CHUNK&&(t.chunkSize=Ds.Z_MIN_CHUNK),Ds.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 Nk(t){return new Vn(t)}function qp(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Vn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return Ds.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(jp($>=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}jp(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>=Dp)throw qp(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Dp.toString(16)+" bytes");let p=Buffer.concat(l,c);return qp(this),p};Ok.inherits(Vn,Ds.Inflate);function Mk(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=Ds.Z_FINISH),t._processChunk(e,s)}function Fp(t,e){return Mk(new Vn(e),t)}Bp.exports=Oo=Fp;Oo.Inflate=Vn;Oo.createInflate=Nk;Oo.inflateSync=Fp});var Bl=V((uC,Hp)=>{"use strict";var Wp=Hp.exports=function(t){this._buffer=t,this._reads=[]};Wp.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Wp.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw new Error("unrecognised content at end of stream")}});var Yp=V(Gp=>{"use strict";var Pk=Bl(),Lk=Nl();Gp.process=function(t,e){let s=[],o=new Pk(t);return new Lk(e,{read:o.read.bind(o),write:function(r){s.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(s)}});var Vp=V((fC,Xp)=>{"use strict";var zp=!0,Kp=require("zlib"),Ik=Up();Kp.deflateSync||(zp=!1);var jk=Bl(),Dk=Yp(),qk=Il(),Fk=jl(),Bk=Dl();Xp.exports=function(t,e){if(!zp)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(R){s=R}let n;function r(R){n=R}function i(R){n.transColor=R}function a(R){n.palette=R}function l(){n.alpha=!0}let c;function u(R){c=R}let d=[];function f(R){d.push(R)}let p=new jk(t);if(new qk(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 $;if(n.interlace)$=Kp.inflateSync(g);else{let v=((n.width*n.bpp*n.depth+7>>3)+1)*n.height;$=Ik(g,{chunkSize:v,maxLength:v})}if(g=null,!$||!$.length)throw new Error("bad png - invalid inflate data response");let x=Dk.process($,n);g=null;let T=Fk.dataToBitMap(x,n);x=null;let A=Bk(T,n,e.skipRescale);return n.data=A,n.gamma=c||0,n}});var eh=V((pC,Qp)=>{"use strict";var Jp=!0,Zp=require("zlib");Zp.deflateSync||(Jp=!1);var Uk=js(),Wk=Fl();Qp.exports=function(t,e){if(!Jp)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 Wk(s),n=[];n.push(Buffer.from(Uk.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=Zp.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 th=V(Ul=>{"use strict";var Hk=Vp(),Gk=eh();Ul.read=function(t,e){return Hk(t,e||{})};Ul.write=function(t,e){return Gk(t,e)}});var oh=V(sh=>{"use strict";var Yk=require("util"),nh=require("stream"),zk=vp(),Kk=Ip(),Xk=th(),pt=sh.PNG=function(t){nh.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 zk(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 Kk(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(pt,nh);pt.sync=Xk;pt.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};pt.prototype.parse=function(t,e){if(e){let s,o;s=function(n){this.removeListener("error",o),this.data=n,e(null,this)}.bind(this),o=function(n){this.removeListener("parsed",s),e(n,null)}.bind(this),this.once("parsed",s),this.once("error",o)}return this.end(t),this};pt.prototype.write=function(t){return this._parser.write(t),!0};pt.prototype.end=function(t){this._parser.end(t)};pt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};pt.prototype._gamma=function(t){this.gamma=t};pt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};pt.bitblt=function(t,e,s,o,n,r,i,a){if(s|=0,o|=0,n|=0,r|=0,i|=0,a|=0,s>t.width||o>t.height||s+n>t.width||o+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+n>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<r;l++)t.data.copy(e.data,(a+l)*e.width+i<<2,(o+l)*t.width+s<<2,(o+l)*t.width+s+n<<2)};pt.prototype.bitblt=function(t,e,s,o,n,r,i){return pt.bitblt(this,t,e,s,o,n,r,i),this};pt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let s=0;s<t.width;s++){let o=t.width*e+s<<2;for(let n=0;n<3;n++){let r=t.data[o+n]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[o+n]=Math.round(r*255)}}t.gamma=0}};pt.prototype.adjustGamma=function(){pt.adjustGamma(this)}});var ch={};O0(ch,{default:()=>ah});function ah(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(!Wl(t)||!Wl(e)||s&&!Wl(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),$=!0;for(let S=0;S<p;S++)if(m[S]!==g[S]){$=!1;break}if($){if(s&&!f)for(let S=0;S<p;S++)ih(t,4*S,a,s);return 0}let x=35215*i*i,[T,A,R]=l,[v,N,Q]=c,[se,re,le]=d||c,ne=0;for(let S=0;S<n;S++)for(let ve=0;ve<o;ve++){let W=S*o+ve,z=W*4,ge=m[W]===g[W]?0:lh(t,e,z,z,!1);if(Math.abs(ge)>x){let Ae=rh(t,ve,S,o,n,m,g)||rh(e,ve,S,o,n,g,m);!u&&Ae?s&&!f&&bi(s,z,T,A,R):(s&&(ge<0?bi(s,z,se,re,le):bi(s,z,v,N,Q)),ne++)}else s&&!f&&ih(t,z,a,s)}return ne}function Wl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function rh(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,$=0,x=0,T=0;for(let A=a;A<=c;A++)for(let R=l;R<=u;R++){if(A===e&&R===s)continue;let v=lh(t,t,d*4,(R*o+A)*4,!0);if(v===0){if(f++,f>2)return!1}else v<p?(p=v,g=A,$=R):v>m&&(m=v,x=A,T=R)}return p===0||m===0?!1:$i(r,g,$,o,n)&&$i(i,g,$,o,n)||$i(r,x,T,o,n)&&$i(i,x,T,o,n)}function $i(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 lh(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,$=l-f;if(!p&&!m&&!g&&!$)return 0;if(l<255||f<255){let v=48+159*(s%2),N=48+159*((s/1.618033988749895|0)%2),Q=48+159*((s/2.618033988749895|0)%2);p=(r*l-c*f-v*$)/255,m=(i*l-u*f-N*$)/255,g=(a*l-d*f-Q*$)/255}let x=p*.29889531+m*.58662247+g*.11448223;if(n)return x;let T=p*.59597799-m*.2741761-g*.32180189,A=p*.21147017-m*.52261711+g*.31114694,R=.5053*x*x+.299*T*T+.1957*A*A;return x>0?-R:R}function bi(t,e,s,o,n){t[e+0]=s,t[e+1]=o,t[e+2]=n,t[e+3]=255}function ih(t,e,s,o){let n=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;bi(o,e,n,n,n)}var uh=A0(()=>{});var Jn=V((gC,mh)=>{var $n=require("fs"),Vk=require("path"),Jk=require("os"),Zk="nex-visual-";function fh(t){return Vk.join(Jk.tmpdir(),`${Zk}${Date.now()}-${t}`)}var Hl=null;function _i(){return Hl||(Hl=oh().PNG),Hl}var Gl=null;function Qk(){if(!Gl){let t=(uh(),M0(ch));Gl=t.default||t}return Gl}function Kl(t,e,{threshold:s=.1}={}){let o=_i(),n=Qk(),r=o.sync.read($n.readFileSync(t)),i=o.sync.read($n.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=dh(r,a,l),u=dh(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=ex(d.data,a,l,3,3),$=fh("diff.png");return $n.writeFileSync($,o.sync.write(d),{mode:384}),{diffPath:$,diffPercent:parseFloat(m),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function dh(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 ex(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),$=Math.min(m+a,s);for(let x=m;x<$;x++)for(let T=p;T<g;T++){f++;let A=(x*e+T)*4;(t[A]>0||t[A+1]>0)&&d++}if(d>0){let x=(d/f*100).toFixed(1),T=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:T,changedPercent:parseFloat(x),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var ph=[{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 tx(t,{viewports:e=ph,height:s=800,fullPage:o=!1,timeout:n=3e4}={}){let{browserScreenshot:r}=wn(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:s,fullPage:o,timeout:n});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function hh(t,e=[]){let s=_i(),o=s.sync.read($n.readFileSync(t));for(let i of e){let a=nx(i.color||"#FF0000");i.type==="box"?(sx(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&zl(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(ox(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&zl(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(rx(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&zl(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let n=fh("annotated.png");$n.writeFileSync(n,s.sync.write(o),{mode:384});let r=$n.readFileSync(n).toString("base64");return{path:n,base64:r,media_type:"image/png"}}function nx(t){let e=t.replace("#","");return{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16),a:255}}function an(t,e,s,o){if(e<0||s<0||e>=t.width||s>=t.height)return;let n=(s*t.width+e)*4;t.data[n]=o.r,t.data[n+1]=o.g,t.data[n+2]=o.b,t.data[n+3]=o.a}function sx(t,e,s,o,n,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<o;l++)an(t,e+l,s+a,r),an(t,e+l,s+n-1-a,r);for(let l=0;l<n;l++)an(t,e+a,s+l,r),an(t,e+o-1-a,s+l,r)}}function Yl(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 $=-m;$<=m;$++)for(let x=-m;x<=m;x++)an(t,f+$,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 ox(t,e,s,o,n,r,i=3){Yl(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;Yl(t,o,n,Math.round(o+l*Math.cos(c)),Math.round(n+l*Math.sin(c)),r,i),Yl(t,o,n,Math.round(o+l*Math.cos(u)),Math.round(n+l*Math.sin(u)),r,i)}function rx(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));an(t,u,d,n)}}}function zl(t,e,s,o,n){let i=o.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)an(t,e+c,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)an(t,e+l,s+a-1,n),an(t,e+l,s+a-2,n);for(let l=0;l<o.length;l++){let c=e+2+l*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)an(t,c+d,s+u,n)}}async function*ix(t,e,{maxIterations:s=20,hmrDelay:o=1500,width:n=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=wn(),l=ax("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 cx(()=>d,3e5),d=!1,u++,await lx(o);let p=await a(t,{width:n,height:r,timeout:i}),m=null;try{m=Kl(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 ax(t){try{return require(t)}catch{return null}}function lx(t){return new Promise(e=>setTimeout(e,t))}function cx(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 ux(t,{sampleRate:e=4}={}){let o=_i().sync.read($n.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 $=Math.round(f/8)*8,x=Math.round(p/8)*8,T=Math.round(m/8)*8,A=`${$},${x},${T}`;n.set(A,(n.get(A)||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:dx(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:fx(d,f,p)}}),l=px(o);return{colors:a,spacing:l,dimensions:{width:o.width,height:o.height},imagePath:t}}function dx(t,e,s){return"#"+[t,e,s].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function fx(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 px(t){let e=[],s=!1,o=0,n=hx(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 hx(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 mx(t,e,{width:s,height:o=800,fullPage:n=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=wn(),c=_i().sync.read($n.readFileSync(e)),u=s||c.width,d=o||c.height,f=await a(t,{width:u,height:d,fullPage:n,timeout:i}),p=Kl(e,f.path,{threshold:r}),m=hh(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,$)=>{let A=Math.ceil(p.width/3),R=Math.ceil(p.height/3),v=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],N=0,Q=0;for(let se=0;se<3;se++)for(let re=0;re<3;re++)v[se][re]===g.name&&(N=re,Q=se);return{type:"box",x:N*A+2,y:Q*R+2,width:A-4,height:R-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:$n.readFileSync(p.diffPath).toString("base64"),annotatedBase64:m.base64}}mh.exports={pixelDiff:Kl,responsiveSweep:tx,annotateImage:hh,visualWatch:ix,extractDesignTokens:ux,designCompare:mx,DEFAULT_VIEWPORTS:ph}});var Xl=V((yC,gh)=>{var{C:Ie}=nt(),Mo="",ht=[],No=0,Zn=null;function gx(t){Zn=t}function yx(t,e){Mo=t,ht=[],No=0;for(let o of e){No++;let n=`t${No}`;ht.push({id:n,description:o.description||o.title||o.name||o.task||`Task ${No}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let s=ht.map(o=>({...o}));return Zn&&Zn("create",{name:t,tasks:s}),s}function wx(t,e,s){let o=ht.find(n=>n.id===t);return o?(o.status=e,s!==void 0&&(o.result=s),Zn&&Zn("update",{id:t,status:e,result:s}),{...o}):null}function $x(){return{name:Mo,tasks:ht.map(t=>({...t}))}}function bx(){Mo="",ht=[],No=0,Zn&&Zn("clear",{})}function _x(){return ht.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=ht.find(o=>o.id===e);return s&&s.status==="done"}))}function kx(){if(ht.length===0)return`${Ie.dim}No active tasks${Ie.reset}`;let t=[];Mo&&(t.push(` ${Ie.bold}${Ie.cyan}Tasks: ${Mo}${Ie.reset}`),t.push(` ${Ie.dim}${"\u2500".repeat(40)}${Ie.reset}`));for(let n of ht){let r,i;switch(n.status){case"done":r="\u2713",i=Ie.green;break;case"in_progress":r="\u2192",i=Ie.cyan;break;case"failed":r="\u2717",i=Ie.red;break;default:r="\xB7",i=Ie.dim}let a=n.dependsOn.length>0?` ${Ie.dim}(after: ${n.dependsOn.join(", ")})${Ie.reset}`:"",l=`[${n.status}]`,c=n.description.length>50?n.description.substring(0,47)+"...":n.description;if(t.push(` ${i}${r}${Ie.reset} ${Ie.bold}${n.id}${Ie.reset} ${c.padEnd(40)} ${i}${l}${Ie.reset}${a}`),n.result&&n.status==="done"){let u=n.result.length>60?n.result.substring(0,57)+"...":n.result;t.push(` ${Ie.dim}\u2192 ${u}${Ie.reset}`)}}let e=ht.filter(n=>n.status==="done").length,s=ht.filter(n=>n.status==="failed").length,o=ht.length;return t.push(` ${Ie.dim}${"\u2500".repeat(40)}${Ie.reset}`),t.push(` ${Ie.dim}${e}/${o} done${s>0?`, ${s} failed`:""}${Ie.reset}`),t.join(`
|
|
144
|
+
`)}function xx(){return ht.length>0&&ht.some(t=>t.status==="pending"||t.status==="in_progress")}gh.exports={createTasks:yx,updateTask:wx,getTaskList:$x,clearTasks:bx,getReadyTasks:_x,renderTaskList:kx,setOnChange:gx,hasActiveTasks:xx}});var Jl=V((wC,kh)=>{var{callChat:Sx}=lt(),{estimateTokens:Vl}=ln(),yh=process.env.NEX_COMPACTION!=="false",wh=6,$h=2e3,bh=3,Ex=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
134
145
|
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
135
146
|
|
|
136
147
|
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
@@ -162,46 +173,46 @@ Format your output as:
|
|
|
162
173
|
|
|
163
174
|
<summary>
|
|
164
175
|
[Sections 1-9 above]
|
|
165
|
-
</summary>`,
|
|
166
|
-
${
|
|
167
|
-
tools: ${
|
|
176
|
+
</summary>`,Qn=0;async function vx(t){if(!yh||t.length<wh||Qn>=bh)return null;let e=[{role:"system",content:Ex},{role:"user",content:_h(t)}];try{let o=((await Sx(e,[],{temperature:0,maxTokens:$h})).content||"").trim();if(!o)return Qn++,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 Qn++,null;let r=t.reduce((a,l)=>a+Vl(l.content||"")+(l.tool_calls?Vl(JSON.stringify(l.tool_calls)):0),0),i=Vl(o);return i>=r*.8?(Qn++,null):(Qn=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
177
|
+
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Qn++,null}}function Tx(){Qn=0}function _h(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let n=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${o}
|
|
178
|
+
tools: ${n}`}return`[${s}] ${o}`}).join(`
|
|
168
179
|
|
|
169
|
-
`)}
|
|
170
|
-
`);if(
|
|
180
|
+
`)}kh.exports={compactMessages:vx,formatMessagesForSummary:_h,resetCompactionFailures:Tx,COMPACTION_ENABLED:yh,COMPACTION_MIN_MESSAGES:wh,COMPACTION_SUMMARY_BUDGET:$h,MAX_CONSECUTIVE_FAILURES:bh}});var ln=V(($C,Nh)=>{var Rx=require("path");function Sh(){return lt().getActiveModel()}var Cx={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Ax={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},es=new Map,xh=1e3,Zl=new WeakMap,ts=null;function Ox(){if(ts!==null)return ts;try{let t=Sh(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[o,n]of Object.entries(Ax))if(s.startsWith(o))return ts=n,ts;return ts=Cx[e]||4,ts}catch{return 4}}function Nx(){ts=null}function ns(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=es.get(e);if(s!==void 0)return es.delete(e),es.set(e,s),s;let o=Math.ceil(t.length/Ox());if(es.size>=xh){let n=xh>>1,r=es.keys();for(let i=0;i<n;i++)es.delete(r.next().value)}return es.set(e,o),o}function Mx(t){if(Zl.has(t))return Zl.get(t);let e=JSON.stringify(t);return Zl.set(t,e),e}function ss(t){let s=4;if(t.content&&(s+=ns(t.content)),t.tool_calls)for(let o of t.tool_calls){s+=4,s+=ns(o.function?.name||"");let n=o.function?.arguments;typeof n=="string"?s+=ns(n):n&&(s+=ns(JSON.stringify(n)))}return s}function Yt(t){let e=0;for(let s of t)e+=ss(s);return e}function Px(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+=ss(e[r]);return n}var Ql=new WeakMap;function ki(t){if(!t||t.length===0)return 0;if(Ql.has(t))return Ql.get(t);let e=ns(JSON.stringify(t));return Ql.set(t,e),e}function xi(){return Sh()?.contextWindow||32768}var mt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function Lx(t,e){let s=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(mt.result&&t.length===mt.msgCount&&s===mt.lastMsgRef&&o===mt.toolCount)return mt.result;let n,r,i,a;if(mt.messagesRef===t&&t.length>mt.msgCount&&mt.msgCount>=0){n=mt.messageTokens,r=mt.systemTokens,i=mt.conversationTokens,a=mt.toolResultTokens;for(let p=mt.msgCount;p<t.length;p++){let m=ss(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=ss(p);n+=m,p.role==="system"?r+=m:p.role==="tool"?a+=m:i+=m}}let l=ki(e),c=n+l,u=xi(),d=u>0?c/u*100:0,f={used:c,limit:u,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return mt={msgCount:t.length,lastMsgRef:s,toolCount:o,result:f,messagesRef:t,messageTokens:n,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Po=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Eh=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,vh=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Th={essential:.6,standard:.65,full:Math.min(Po,.75)};function Rh(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Po;try{let{getActiveTier:t}=Co(),e=t();return Th[e]??Po}catch{return Po}}var Ix=200,jx=1e3;function Ch(t,e){if(!t||t.length<=e)return t;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=o)return t;let n=t.split(`
|
|
181
|
+
`);if(n.length<=10){let m=Math.floor(o*.6),g=Math.floor(o*.4),$=t.substring(0,m),x=t.substring(t.length-g);return $+`
|
|
171
182
|
...(${t.length} chars total)...
|
|
172
|
-
`+
|
|
183
|
+
`+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(`
|
|
173
184
|
`)+`
|
|
174
|
-
...(${p} lines omitted, ${
|
|
185
|
+
...(${p} lines omitted, ${n.length} total)...
|
|
175
186
|
`+u.join(`
|
|
176
|
-
`)}function
|
|
177
|
-
...(truncated)`),
|
|
178
|
-
`+
|
|
179
|
-
`)),
|
|
180
|
-
${
|
|
181
|
-
`)}`,_pinned:!0,_progressSnapshot:!0}}var
|
|
182
|
-
`),r=Math.floor(
|
|
183
|
-
`:"")+p,l++}let c="",u=0;for(let p=
|
|
187
|
+
`)}function Fs(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:jx,o=e==="aggressive"?50:e==="medium"?100:Ix;if(t.role==="tool"){let n=typeof t.content=="string"?t.content:JSON.stringify(t.content);return n.length>o?{...t,content:Ch(n,o)}:t}if(t.role==="assistant"){let n={...t};return n.content&&n.content.length>s&&(n.content=n.content.substring(0,s)+`
|
|
188
|
+
...(truncated)`),n.tool_calls&&e==="aggressive"&&(n.tool_calls=n.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),n}return t}function Ah(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(Rx.basename(l)))&&a++;n+=Math.min(30,a*10)}return Math.min(100,n)}function Oh(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 Dx(t,{filesModified:e=new Set,currentPhase:s=null}={}){let o=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");o.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}s&&o.push(`Current phase: ${s}`);let n=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return n.length>0&&o.push(`Recent progress:
|
|
189
|
+
`+n.map(r=>`- ${r}`).join(`
|
|
190
|
+
`)),o.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
|
|
191
|
+
${o.join(`
|
|
192
|
+
`)}`,_pinned:!0,_progressSnapshot:!0}}var qs={msgCount:-1,lastMsgRef:null,result:null};function qx(){qs={msgCount:-1,lastMsgRef:null,result:null},mt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function Fx(t,e,s={}){let o=t.length>0?t[t.length-1]:null;if(!s.force&&qs.result&&t.length===qs.msgCount&&o===qs.lastMsgRef)return qs.result;let n=s.threshold??Rh(),r=s.safetyMargin??Eh,i=s.keepRecent??vh,a=xi(),l=ki(e),c=Math.floor(a*(n-r)),u=c-l,d=Yt(t);if(d+l<=c){let ne={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return qs={msgCount:t.length,lastMsgRef:o,result:ne},ne}let p=d,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let $=Math.max(g,t.length-i),x=t.slice(g,$),T=t.slice($),A=x.map(ne=>Fs(ne,"light")),R=Nn(m,A,T),v=Yt(R);if(v+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-v};if(A=x.map(ne=>Fs(ne,"medium")),R=Nn(m,A,T),v=Yt(R),v+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-v};if(A=x.map(ne=>Fs(ne,"aggressive")),R=Nn(m,A,T),v=Yt(R),v+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-v};let N=process.env.NEX_SKIP_COMPACTOR==="1",Q=x.filter(ne=>ne._pinned),se=x.filter(ne=>!ne._compacted&&!ne._pinned);if(!N&&se.length>=6)try{let{compactMessages:ne}=Jl(),S=await ne(se);if(S){let ve=x.filter(Ae=>Ae._compacted&&!Ae._pinned),W=[...Q,...ve,S.message],z=Nn(m,W,T),ge=Yt(z);if(ge+l<=c)return{messages:z,compressed:!0,compacted:!0,tokensRemoved:p-ge};x=W}}catch(ne){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",ne.message)}let re=Oh([...A,...T]),le=A.map((ne,S)=>({msg:ne,score:ne._pinned?1/0:Ah(ne,S,A.length,re),tokens:ss(ne)}));for(;le.length>0&&v>u;){let ne=-1;for(let S=0;S<le.length;S++)le[S].score!==1/0&&(ne===-1||le[S].score<le[ne].score)&&(ne=S);if(ne===-1)break;v-=le[ne].tokens,le.splice(ne,1)}return A=le.map(ne=>ne.msg),R=Nn(m,A,T),v=Yt(R),{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-v}}function Nn(t,e,s){let o=[];return t&&o.push(t),o.push(...e,...s),o}function Bx(t,e){if(!t)return"";if(ns(t)<=e)return t;let o=e*4,n=t.split(`
|
|
193
|
+
`),r=Math.floor(o*.6),i=Math.floor(o*.4),a="",l=0;for(let p of n){if(a.length+p.length+1>r)break;a+=(a?`
|
|
194
|
+
`:"")+p,l++}let c="",u=0;for(let p=n.length-1;p>=l;p--){let m=n[p]+(c?`
|
|
184
195
|
`:"")+c;if(m.length>i)break;c=m,u++}let f=`
|
|
185
196
|
|
|
186
|
-
... (${
|
|
197
|
+
... (${n.length-l-u} lines omitted, ${n.length} total) ...
|
|
187
198
|
|
|
188
|
-
`;return a+f+c}var
|
|
189
|
-
`);for(let r of
|
|
190
|
-
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of
|
|
199
|
+
`;return a+f+c}var Ux=6;function Wx(t,e,s=!1){let o=xi(),n=ki(e),r=Math.floor(o*(s?.35:.5))-n,i=Yt(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:Ux,d=Math.max(c,t.length-u),f=t.slice(c,d),p=t.slice(d),m=f.map(v=>Fs(v,"aggressive"));s&&(p=p.map(v=>Fs(v,"aggressive")));let g=Nn(l,m,p),$=Yt(g);for(;m.length>0&&$>r;){let v=m.shift();$-=ss(v)}s&&$>r&&(p=p.filter(N=>N.role==="user").slice(-1),g=Nn(l,[],p),$=Yt(g)),g=Nn(l,m,p);let x=t.filter(v=>v.role==="user"),T=v=>{let N=typeof v.content=="string"?v.content:"";return N.startsWith("[SYSTEM WARNING]")||N.startsWith("[SYSTEM:")||N.startsWith("BLOCKED:")},A=x.find(v=>!T(v)),R=[...x].reverse().find(v=>!T(v));if(A&&!g.find(v=>v===A)){let v=g.findIndex(Q=>Q.role==="system"),N=v>=0?v+1:0;g.splice(N,0,A)}return R&&R!==A&&!g.find(v=>v===R)&&g.push(R),{messages:g,tokensRemoved:i-Yt(g)}}Nh.exports={estimateTokens:ns,estimateMessageTokens:ss,estimateMessagesTokens:Yt,estimateDeltaTokens:Px,estimateToolsTokens:ki,serializeMessage:Mx,getContextWindow:xi,getUsage:Lx,compressMessage:Fs,compressToolResult:Ch,scoreMessageRelevance:Ah,extractActiveFiles:Oh,buildProgressSnapshot:Dx,fitToContext:Fx,forceCompress:Wx,truncateFileContent:Bx,invalidateTokenRatioCache:Nx,invalidateFitToContextCache:qx,getEffectiveCompressionThreshold:Rh,COMPRESSION_THRESHOLD:Po,TIER_COMPRESSION_THRESHOLDS:Th,SAFETY_MARGIN:Eh,KEEP_RECENT:vh}});var ac=V((bC,Yh)=>{var Ge=require("fs"),bn=require("path"),{atomicWrite:Mh,withFileLockSync:Ph}=Hn(),Hx=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 Us(){let t=bn.join(process.cwd(),".nex","brain");return Ge.existsSync(t)||Ge.mkdirSync(t,{recursive:!0}),t}function Ei(){return bn.join(Us(),".brain-index.json")}function nc(){return bn.join(Us(),".embeddings.json")}function Lo(){let t=bn.join(process.cwd(),".nex","brain");if(!Ge.existsSync(t))return[];try{return Ge.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=bn.join(t,e),o=Ge.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 Io(t){let e={},s=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let n=o[1].split(`
|
|
200
|
+
`);for(let r of n){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[a]=l.slice(1,-1).split(",").map(c=>c.trim()).filter(Boolean):e[a]=l}s=o[2]}return{frontmatter:e,body:s}}function Lh(t){let e=bn.join(Us(),`${t}.md`);if(!Ge.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Ge.readFileSync(e,"utf-8"),{frontmatter:o,body:n}=Io(s);return{name:t,content:s,body:n,frontmatter:o}}function Gx(t,e){let s=bn.join(Us(),`${t}.md`);Mh(s,e),Kx(t,e),Yx()}function Yx(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=nc();Ge.existsSync(t)&&setImmediate(async()=>{try{await Uh()}catch{}})}function zx(t){let e=bn.join(Us(),`${t}.md`);return Ge.existsSync(e)?(Ge.unlinkSync(e),Xx(t),!0):!1}function Si(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Hx.has(e))}function sc(t){let e={},{frontmatter:s,body:o}=Io(t),n=Array.isArray(s.tags)?s.tags:[];for(let i of n){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(o||t).split(`
|
|
201
|
+
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of Si(a))e[l]=(e[l]||0)+3}for(let i of Si(o||t))e[i]=(e[i]||0)+1;return e}function oc(){let t=Ei();if(!Ge.existsSync(t))return{documents:{}};try{return JSON.parse(Ge.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function rc(t){Mh(Ei(),JSON.stringify(t,null,2))}function Kx(t,e){Ph(Ei(),()=>{let s=oc(),{frontmatter:o}=Io(e),n=Array.isArray(o.tags)?o.tags:[];s.documents[t]={keywords:sc(e),tags:n,modified:new Date().toISOString()},rc(s)})}function Xx(t){Ph(Ei(),()=>{let e=oc();delete e.documents[t],rc(e)})}function tc(){let t=Lo(),e={documents:{}};for(let s of t){let o=Ge.readFileSync(s.path,"utf-8"),{frontmatter:n}=Io(o),r=Array.isArray(n.tags)?n.tags:[];e.documents[s.name]={keywords:sc(o),tags:r,modified:s.modified.toISOString()}}return rc(e),e}function Ih(){let t=oc(),e=Lo();for(let s of e){let o=t.documents[s.name];if(!o||new Date(o.modified)<s.modified)return tc()}for(let s of Object.keys(t.documents))if(!e.some(o=>o.name===s))return tc();return t}function jh(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=Si(t);if(n.length===0)return[];let r=Ih(),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 Dh=process.env.NEX_EMBED_MODEL||"nomic-embed-text",ec=400,Vx=50;async function qh(){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(Dh.split(":")[0]))}catch{return!1}}async function ic(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:Dh,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 Fh(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 Bh(t){let e=t.split(/\s+/),s=[],o=0;for(;o<e.length;){let n=e.slice(o,o+ec).join(" ");if(s.push({text:n,offset:o}),o+ec>=e.length)break;o+=ec-Vx}return s}async function Uh(){let t=Lo(),e={documents:{}},s=nc();if(Ge.existsSync(s))try{e=JSON.parse(Ge.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=Ge.readFileSync(o.path,"utf-8"),i=Bh(r),a=[];for(let l of i){let c=await ic(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 Ge.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Wh(t,e={}){let{topK:s=3,minSimilarity:o=.3}=e,n=nc();if(!Ge.existsSync(n))return[];let r;try{r=JSON.parse(Ge.readFileSync(n,"utf-8"))}catch{return[]}let i=await ic(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let p=Fh(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 Hh(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 Gh(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=jh(t,{topK:s,minScore:o}),r=n;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await qh()){let a=await Wh(t,{topK:s});r=Hh(n,a,{topK:s})}}catch{}return r.map(i=>{let a=Lh(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 Bs={queryKey:null,result:null,ts:0},Jx=3e5;async function Zx(t){if(!t||!t.trim())return"";let e=bn.join(process.cwd(),".nex","brain");if(!Ge.existsSync(e)||Lo().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(Bs.result!==null&&Bs.queryKey===o&&Date.now()-Bs.ts<Jx)return Bs.result;let n;try{n=await Gh(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let r;try{r=ln().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))+`
|
|
191
202
|
...(truncated)`}let p=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${p}) ---
|
|
192
|
-
${d}`),l+=r(d),l>=i)break}if(a.length===0)return
|
|
203
|
+
${d}`),l+=r(d),l>=i)break}if(a.length===0)return Bs={queryKey:o,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
|
|
193
204
|
|
|
194
205
|
${a.join(`
|
|
195
206
|
|
|
196
|
-
`)}`;return
|
|
207
|
+
`)}`;return Bs={queryKey:o,result:c,ts:Date.now()},c}Yh.exports={getBrainDir:Us,listDocuments:Lo,readDocument:Lh,writeDocument:Gx,removeDocument:zx,buildIndex:tc,getIndex:Ih,query:Gh,getBrainContext:Zx,isEmbeddingAvailable:qh,generateEmbedding:ic,buildEmbeddingIndex:Uh,semanticQuery:Wh,cosineSimilarity:Fh,_keywordQuery:jh,_extractKeywords:sc,_chunkText:Bh,parseFrontmatter:Io,tokenize:Si,_fuseResults:Hh}});var qo=V((_C,om)=>{var je=require("fs"),vt=require("path"),Qx=require("os"),{atomicWrite:vi,withFileLockSync:zh}=Hn(),jo=["user","feedback","project","reference"],eS=50;function os(){return vt.join(process.cwd(),".nex","memory")}function Ws(){return vt.join(os(),"memory.json")}function Kh(){return vt.join(os(),"MEMORY.md")}function tS(){return vt.join(process.cwd(),"NEX.md")}function Xh(){return vt.join(Qx.homedir(),".nex","NEX.md")}function Ti(){let t=os();je.existsSync(t)||je.mkdirSync(t,{recursive:!0})}function Vh(t){let e=vt.join(os(),t);return je.existsSync(e)||je.mkdirSync(e,{recursive:!0}),e}function Do(){let t=Ws();if(!je.existsSync(t))return{};try{return JSON.parse(je.readFileSync(t,"utf-8"))}catch{return{}}}function Jh(t){Ti(),vi(Ws(),JSON.stringify(t,null,2))}function Zh(){let t=Ws();if(!je.existsSync(t))return;let e=Do(),s=Object.keys(e);if(s.length===0){try{je.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=Vh("project"),l=vt.join(a,`${i}.md`),c=r.split(`
|
|
197
208
|
`)[0].slice(0,100),u=`---
|
|
198
|
-
name: ${
|
|
209
|
+
name: ${o}
|
|
199
210
|
description: ${c}
|
|
200
211
|
type: project
|
|
201
212
|
---
|
|
202
213
|
|
|
203
214
|
${r}
|
|
204
|
-
`;
|
|
215
|
+
`;vi(l,u)}Ri();try{je.renameSync(t,t+".bak")}catch{}}function nS(t,e,s,o){if(!jo.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${jo.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=Vh(t),i=vt.join(r,`${n}.md`);if(je.existsSync(i))try{if(lc(je.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(`
|
|
205
216
|
`)[0].slice(0,100),l=`---
|
|
206
217
|
name: ${e}
|
|
207
218
|
description: ${a}
|
|
@@ -209,96 +220,100 @@ type: ${t}
|
|
|
209
220
|
---
|
|
210
221
|
|
|
211
222
|
${s}
|
|
212
|
-
`;return
|
|
223
|
+
`;return vi(i,l),Ri(),{ok:!0,path:i,updated:!0}}function sS(t,e){if(!jo.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=vt.join(os(),t,`${s}.md`);if(!je.existsSync(o))return!1;try{return je.unlinkSync(o),Ri(),!0}catch{return!1}}function lc(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 Qh(){let t=[],e=os();for(let s of jo){let o=vt.join(e,s);if(!je.existsSync(o))continue;let n;try{n=je.readdirSync(o).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of n){let i=vt.join(o,r);try{let a=je.readFileSync(i,"utf-8"),l=lc(a);t.push({type:s,name:l.name||vt.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function Ri(){let t=Qh(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=eS+2)break;let o=`${s.type}/${vt.basename(s.filePath)}`;e.push(`- [${s.name}](${o}) \u2014 ${s.description||"(no description)"}`)}Ti(),vi(Kh(),e.join(`
|
|
213
224
|
`)+`
|
|
214
|
-
`)}function
|
|
215
|
-
${e}`);let s=
|
|
216
|
-
${s}`);let
|
|
225
|
+
`)}function em(){let t=Kh();if(!je.existsSync(t))return"";try{return je.readFileSync(t,"utf-8").trim()}catch{return""}}function oS(t,e){Ti(),zh(Ws(),()=>{let s=Do();s[t]={value:e,updatedAt:new Date().toISOString()},Jh(s)})}function rS(t){let e=Do();return e[t]?e[t].value:null}function iS(t){return Ti(),zh(Ws(),()=>{let e=Do();return t in e?(delete e[t],Jh(e),!0):!1})}function tm(){let t=Do();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function nm(){let t=Xh();if(!je.existsSync(t))return"";try{return je.readFileSync(t,"utf-8").trim()}catch{return""}}function sm(){let t=tS();if(!je.existsSync(t))return"";try{return je.readFileSync(t,"utf-8").trim()}catch{return""}}function aS(){Zh();let t=[],e=nm();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
226
|
+
${e}`);let s=sm();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
227
|
+
${s}`);let o="",n=em();if(n)o=n;else{let d=tm();d.length>0&&(o=`PROJECT MEMORY:
|
|
217
228
|
${d.map(p=>` ${p.key}: ${p.value}`).join(`
|
|
218
229
|
`)}`)}let r=t.join(`
|
|
219
230
|
|
|
220
|
-
`),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(
|
|
231
|
+
`),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(`
|
|
221
232
|
`),f="";for(let p of d){if(f.length+p.length+1>c-60)break;f+=p+`
|
|
222
|
-
`}
|
|
223
|
-
[Memory index truncated \u2014 use delete_memory to prune old entries]`}else
|
|
233
|
+
`}o=f.trimEnd()+`
|
|
234
|
+
[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(`
|
|
224
235
|
|
|
225
|
-
`)}
|
|
226
|
-
`;
|
|
227
|
-
`).filter(l=>l.trim());for(let l of a)try{let c=JSON.parse(l);if(t.tool&&c.tool!==t.tool)continue;
|
|
236
|
+
`)}om.exports={saveMemory:nS,deleteMemory:sS,scanMemories:Qh,rebuildIndex:Ri,loadMemoryIndex:em,remember:oS,recall:rS,forget:iS,listMemories:tm,loadGlobalInstructions:nm,loadProjectInstructions:sm,getMemoryContext:aS,_getMemoryDir:os,_getMemoryFile:Ws,_getGlobalNexMdPath:Xh,_parseMemoryFile:lc,_migrateIfNeeded:Zh,VALID_TYPES:jo}});var um=V((kC,cm)=>{var Fo=require("fs"),cc=require("path"),uc=process.env.NEX_AUDIT!=="false",rs=null;function rm(){return rs||(rs=cc.join(process.cwd(),".nex","audit"),Fo.existsSync(rs)||Fo.mkdirSync(rs,{recursive:!0}),rs)}function im(){let t=new Date().toISOString().split("T")[0];return cc.join(rm(),`${t}.jsonl`)}function lS(t){if(uc)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:am(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},s=JSON.stringify(e)+`
|
|
237
|
+
`;Fo.appendFileSync(im(),s,"utf-8")}catch{}}function am(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 lm(t={}){let e=rm(),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=cc.join(e,`${r}.jsonl`);if(!Fo.existsSync(i))continue;let a=Fo.readFileSync(i,"utf-8").split(`
|
|
238
|
+
`).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 cS(t=1){let e=lm({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 uS(t){uc=t}function dS(){return uc}function fS(){rs=null}cm.exports={logToolExecution:lS,sanitizeArgs:am,readAuditLog:lm,getAuditSummary:cS,setAuditEnabled:uS,isAuditEnabled:dS,getAuditLogPath:im,_reset:fS}});var Cm=V((SC,Rm)=>{var Ye=require("fs").promises,Kt=require("fs"),oe=require("path"),Be=require("util").promisify(require("child_process").exec),is=require("util").promisify(require("child_process").execFile),{spawnSync:pS}=require("child_process"),dc=require("axios"),{isForbidden:hS,isSSHForbidden:mS,isDangerous:gS,isCritical:dm,isBashPathForbidden:yS,confirm:zt}=wo(),{showDiff:Ci,showNewFile:wS,showEditDiff:xC,confirmFileChange:Bo}=Zd(),{C:ce,Spinner:$S,getToolSpinnerText:bS}=nt(),{ToolProgress:Ai}=Gn(),{isGitRepo:fc,getCurrentBranch:fm,getStatus:_S,getDiff:kS}=Qr(),{recordChange:Oi}=uf(),{fuzzyFindText:pm,findMostSimilar:Yo}=Pf(),{runDiagnostics:Uo}=If(),{findFileInIndex:xS,getFileIndex:hm,searchContentIndex:SS,scorePathMatch:mm,refreshIndex:ES,isIndexValid:vS}=sn(),{resolveProfile:jt,sshExec:gt,scpUpload:TS,scpDownload:gm}=Ls(),{resolveDeployConfig:RS,loadDeployConfigs:CS}=sp(),{getEditMode:ym}=Co(),AS=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|telnet\s|screen|tmux|fzf|gum|dialog|whiptail|man\s|node\s*$|python3?\s*$|irb\s*$|rails\s*c|psql\s|mysql\s|redis-cli|mongosh?|sqlite3)\b/,OS=/^ssh\s/,NS=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Tt(t){return Ye.access(t).then(()=>!0).catch(()=>!1)}var Ni=null,wm=0,MS=12e4;function PS(){let t=Date.now();if(Ni&&t-wm<MS)return Ni;let e=oe.dirname(process.cwd());try{let s=Kt.readdirSync(e,{withFileTypes:!0}),o=oe.basename(process.cwd()),n=s.filter(r=>r.isDirectory()&&r.name!==o&&!r.name.startsWith(".")).map(r=>r.name).sort();return Ni=n.length>0?n:null,wm=t,Ni}catch{return null}}function pc(t){if(t&&oe.resolve(t)!==process.cwd())return"";let e=PS();if(!e)return"";let s=oe.dirname(process.cwd());return`
|
|
228
239
|
Hint: no matches in current project. Sibling directories in ${s}/:
|
|
229
240
|
${e.join(", ")}
|
|
230
|
-
You can search there with: grep pattern --path ${s}/<dir>`}async function
|
|
231
|
-
${i.map(l=>
|
|
232
|
-
`)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=
|
|
233
|
-
${l.map(u=>
|
|
234
|
-
`)}`}}catch{}try{let{smartSearch:i}=
|
|
235
|
-
${a.map(u=>
|
|
236
|
-
`)}`}}}catch{}return{fixedPath:null,message:""}}function
|
|
237
|
-
`).filter(
|
|
238
|
-
`).filter(
|
|
241
|
+
You can search there with: grep pattern --path ${s}/<dir>`}async function Mi(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=ot(e);if(s&&await Tt(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],n=oe.extname(t);if(!n)for(let i of o){let a=ot(t+i);if(a&&await Tt(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=ot(i+a);if(l&&await Tt(l))return{fixedPath:l,message:`(auto-fixed: ${n} \u2192 ${a})`}}}let r=oe.basename(t);if(r&&r.length>2)try{let i=xS(r).map(a=>ot(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${oe.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
242
|
+
${i.map(l=>oe.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
243
|
+
`)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=sn(),l=a().filter(c=>oe.basename(c).toLowerCase()===i).map(c=>ot(c));if(l.length===1)return{fixedPath:l[0],message:`(auto-fixed: case-insensitive match \u2192 ${oe.relative(process.cwd(),l[0])})`};if(l.length>1&&l.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
244
|
+
${l.map(u=>oe.relative(process.cwd(),u)).map(u=>` - ${u}`).join(`
|
|
245
|
+
`)}`}}catch{}try{let{smartSearch:i}=sn(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=ot(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 ${oe.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 ${oe.relative(process.cwd(),l)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
246
|
+
${a.map(u=>oe.relative(process.cwd(),ot(u.file))).map(u=>` - ${u}`).join(`
|
|
247
|
+
`)}`}}}catch{}return{fixedPath:null,message:""}}function LS(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":/\bsed\s+-n\s+['"]?\d+,\d+p/.test(t)?'sed -n line-range scrolling floods context with irrelevant lines. Use targeted grep instead: grep -n "ERROR\\|pattern" <logfile> | tail -20':""}function km(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 xm(t,e){let s=km(t);if(!s)return new Map;try{let o=await SS(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 $m(t,e){if(!t)return"";let s=e||process.cwd(),o=oe.isAbsolute(t)?t:oe.resolve(s,t),n=oe.relative(s,o);return n&&!n.startsWith("..")&&!oe.isAbsolute(n)?n:oe.relative(process.cwd(),o)}function Wo(t,e){let s=(t||"").trim();return s?e==="files_with_matches"||e==="count"?s.split(`
|
|
248
|
+
`).filter(o=>o.trim()):s.split(`
|
|
249
|
+
`).filter(o=>o.trim()):[]}function Sm(t,{query:e,basePath:s,definitionScores:o=new Map,mtimeByPath:n=new Map}={}){let r=km(e);return[...t].sort((i,a)=>{let l=$m(i,s),c=$m(a,s),u=0,d=0;if(r&&(u+=mm(l,r),d+=mm(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 hc(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 xm(e,s),a=Sm(r,{query:e,basePath:s,definitionScores:i}),l=[];for(let c of a)l.push(...n.get(c)||[]);return l}function Em(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+`
|
|
239
250
|
|
|
240
251
|
`+s.join(`
|
|
241
|
-
`)}function lm(t,e,s){let n=Fo(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var nm=!1,rs=null;function cS(){rs&&(rs(),rs=null)}var cc=null;function uS(t){cc=t}async function ic(){if(!nm){nm=!0;try{let{stdout:t}=await Fe("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Fe('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Fe("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Fe("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var dS=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function fS(){let t=process.cwd();try{return Kt.realpathSync(t)}catch{return ce.resolve(t)}}function pS(t,e){let s=ce.relative(e,t);return s===""||!s.startsWith("..")&&!ce.isAbsolute(s)}function hS(t){if(Kt.existsSync(t))return Kt.realpathSync(t);let e=ce.dirname(t);for(;e&&e!==ce.dirname(e);){if(Kt.existsSync(e)){let s=Kt.realpathSync(e),n=ce.relative(e,t);return ce.resolve(s,n)}e=ce.dirname(e)}return t}function st(t){let e=ce.isAbsolute(t)?ce.resolve(t):ce.resolve(process.cwd(),t);for(let n of dS)if(n.test(e))return null;let s=hS(e);return pS(s,fS())?s:null}function xe(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function cm(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function mS(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function gS(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function ac(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function yS(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Do(t,e="user"){return cm(t)?null:`ERROR: ${e} contains unsafe characters`}function lc(t,e="service"){return mS(t)?null:`ERROR: ${e} contains unsafe characters`}var wS=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Optionally use include to filter by file type (e.g. '*.js') but OMIT it when first searching \u2014 code may live in .html, .vue, .py or other unexpected file types. Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"visual_review",description:"Screenshot a URL, analyze the visual result, and return structured feedback about layout, design, and usability issues. Use this to visually inspect web pages, check CSS changes, or verify UI fixes. Returns the screenshot path + analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot and analyze"},focus:{type:"string",description:"What to focus on: layout, colors, typography, spacing, responsiveness, accessibility, or a custom description (e.g. 'check the navbar alignment')"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"},full_page:{type:"boolean",description:"Capture full scrollable page (default: false)"},compare_with:{type:"string",description:"Path to a previous screenshot to compare against (optional). Enables before/after analysis."}},required:["url"]}}},{type:"function",function:{name:"clipboard_image",description:"Grab the current image from the system clipboard (macOS). Returns the screenshot path for visual analysis. Use when the user says 'clipboard', 'pasteboard', or wants to analyze a copied screenshot.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"visual_diff",description:"Compare two screenshots pixel-by-pixel and compute a visual diff. Returns the percentage of changed pixels and which screen regions (top-left, center, bottom-right, etc.) were affected. Use after making CSS/HTML changes to quantify what changed. Example: take a before screenshot, make changes, take an after screenshot, then visual_diff both paths.",parameters:{type:"object",properties:{before:{type:"string",description:"Path to the 'before' screenshot (PNG)"},after:{type:"string",description:"Path to the 'after' screenshot (PNG)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1). Lower = more sensitive."}},required:["before","after"]}}},{type:"function",function:{name:"responsive_sweep",description:"Screenshot a URL at 5 viewport widths (320, 768, 1024, 1440, 1920) and return all screenshots for breakpoint analysis. Quickly identifies responsive layout issues across mobile, tablet, and desktop. Returns images for visual analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot at each viewport"},viewports:{type:"array",items:{type:"object",properties:{width:{type:"number"},label:{type:"string"}}},description:"Custom viewport list (default: 320/768/1024/1440/1920)"},full_page:{type:"boolean",description:"Capture full scrollable page at each viewport (default: false)"}},required:["url"]}}},{type:"function",function:{name:"visual_annotate",description:"Draw annotations (red boxes, arrows, circles) directly on a screenshot to mark problem areas. Returns the annotated image. Use instead of describing locations verbally \u2014 visual markers are unambiguous.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to the screenshot (PNG) to annotate"},annotations:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"box, arrow, or circle"},x:{type:"number",description:"X position (px)"},y:{type:"number",description:"Y position (px)"},width:{type:"number",description:"Width for box (px)"},height:{type:"number",description:"Height for box (px)"},toX:{type:"number",description:"Arrow end X (px)"},toY:{type:"number",description:"Arrow end Y (px)"},radius:{type:"number",description:"Circle radius (px)"},label:{type:"string",description:"Text label for the annotation"},color:{type:"string",description:"Hex color (default: #FF0000)"}},required:["type","x","y"]},description:"List of annotations to draw"}},required:["image","annotations"]}}},{type:"function",function:{name:"visual_watch",description:"Hot-reload visual feedback loop: watches source files for changes, waits for HMR to settle, takes a new screenshot, diffs it against the previous one, and reports what changed. Runs up to N iterations (default: 10). Requires a running dev server (Vite, Next, etc.) and chokidar. Use for autonomous visual polish loops.",parameters:{type:"object",properties:{url:{type:"string",description:"Dev server URL to screenshot (e.g. http://localhost:5173)"},watch:{type:"array",items:{type:"string"},description:"File paths or directories to watch for changes (e.g. ['src/components', 'src/styles'])"},max_iterations:{type:"number",description:"Max number of change\u2192screenshot\u2192diff cycles (default: 10)"},hmr_delay:{type:"number",description:"Milliseconds to wait after file change for HMR to settle (default: 1500)"}},required:["url","watch"]}}},{type:"function",function:{name:"design_tokens",description:"Extract design tokens from a screenshot: dominant colors (with hex/rgb/frequency/category), detected vertical spacing values, and image dimensions. Use to audit visual consistency, compare against a design system, or reverse-engineer CSS variables from a rendered page.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to screenshot (PNG) to analyze"},sample_rate:{type:"number",description:"Pixel sampling interval \u2014 lower = more accurate but slower (default: 4)"}},required:["image"]}}},{type:"function",function:{name:"design_compare",description:"Compare a live web page against a reference design (Figma export, mockup PNG). Screenshots the URL at the reference image's dimensions, computes pixel-level diff, and returns annotated images highlighting deviations. Use to verify implementation matches the design spec.",parameters:{type:"object",properties:{url:{type:"string",description:"Live URL to compare against the reference"},reference:{type:"string",description:"Path to reference design image (PNG)"},width:{type:"number",description:"Override viewport width (default: match reference image width)"},height:{type:"number",description:"Override viewport height (default: 800)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1)"}},required:["url","reference"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'},background:{type:"boolean",description:"Run this agent non-blocking in the background. The main session continues immediately; results are injected as [BACKGROUND AGENT COMPLETED] user messages when the agent finishes. Use for tasks that can run in parallel to your main work."}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl) that live on almalinux9. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/deploy/app). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "my-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "my-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function qo(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function sm(t,e,s={}){switch(t){case"bash":{let n=e.command,o=Bx(n);if(o){let d=lS(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
|
|
242
|
-
HINT: ${d}`:""}`}let r=
|
|
243
|
-
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?
|
|
244
|
-
${p}`}}case"read_file":{let n=
|
|
245
|
-
`+
|
|
246
|
-
`),
|
|
247
|
-
`),
|
|
248
|
-
|
|
249
|
-
[\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${
|
|
250
|
-
|
|
251
|
-
[\u{1F6A8} FILE CONTINUES: This is only lines ${
|
|
252
|
-
${
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
`),
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
`);return
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
`)
|
|
272
|
-
`)
|
|
273
|
-
|
|
274
|
-
|
|
252
|
+
`)}function vm(t,e,s){let o=Yo(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 bm=!1,as=null;function IS(){as&&(as(),as=null)}var wc=null;function jS(t){wc=t}async function mc(){if(!bm){bm=!0;try{let{stdout:t}=await Be("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Be('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Be("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Be("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var DS=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function qS(){let t=process.cwd();try{return Kt.realpathSync(t)}catch{return oe.resolve(t)}}function FS(t,e){let s=oe.relative(e,t);return s===""||!s.startsWith("..")&&!oe.isAbsolute(s)}function BS(t){if(Kt.existsSync(t))return Kt.realpathSync(t);let e=oe.dirname(t);for(;e&&e!==oe.dirname(e);){if(Kt.existsSync(e)){let s=Kt.realpathSync(e),o=oe.relative(e,t);return oe.resolve(s,o)}e=oe.dirname(e)}return t}function ot(t){let e=oe.isAbsolute(t)?oe.resolve(t):oe.resolve(process.cwd(),t);for(let o of DS)if(o.test(e))return null;let s=BS(e);return FS(s,qS())?s:null}function xe(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function Tm(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function US(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function WS(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function gc(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function HS(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Ho(t,e="user"){return Tm(t)?null:`ERROR: ${e} contains unsafe characters`}function yc(t,e="service"){return US(t)?null:`ERROR: ${e} contains unsafe characters`}var GS=[{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 Go(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 _m(t,e,s={}){switch(t){case"bash":{let o=e.command,n=hS(o);if(n){let d=LS(o);return`BLOCKED: Command matches forbidden pattern: ${n}${d?`
|
|
253
|
+
HINT: ${d}`:""}`}let r=yS(o);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
|
|
254
|
+
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?dm(o):gS(o)){let d=dm(o)?"\u26D4":"\u26A0";if(!await zt(` ${d} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Kt.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${ce.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${ce.reset}`)}let l=OS.test(o.trim())&&!NS.test(o.trim());if(AS.test(o.trim())||l){s.silent||console.log(`${ce.dim} \u25B6 interactive: ${o}${ce.reset}`);let d=pS("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}=Gn(),u=s.silent?null:new c("bash",o.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await Be(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=Em(f,o);return`EXIT ${d.code||1}
|
|
255
|
+
${p}`}}case"read_file":{let o=new Ai("read_file","Reading file...");o.start();try{let n=ot(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Tt(n)){let re=await Mi(e.path);if(re.fixedPath)n=re.fixedPath,console.log(`${ce.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${oe.relative(process.cwd(),n)}${ce.reset}`),o.update({message:"Resolved path",detail:oe.relative(process.cwd(),n)});else return`ERROR: File not found: ${e.path}${re.message?`
|
|
256
|
+
`+re.message:""}`}let i=oe.relative(process.cwd(),n);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),l=await Kt.promises.open(n,"r"),{bytesRead:c}=await l.read(a,0,8192,0);await l.close();for(let re=0;re<c;re++)if(a[re]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let u=await Ye.readFile(n,"utf-8");if(!u&&(await Ye.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let d=u.split(`
|
|
257
|
+
`),f=await Ye.stat(n),p=d.length,m=350,g=!e.line_start&&!e.line_end,$=g&&p>m,x=(e.line_start||1)-1,T=$?m:e.line_end||d.length,A=x+1,R=T;o.update({count:Math.max(0,T-x),total:p,detail:`${i} lines ${A}-${R}`,message:$?"Reading excerpt":"Reading"});let v=$?`showing lines 1-${m} of ${p}`:e.line_start||e.line_end?`lines ${x+1}-${T} of ${p}`:`${p} lines`,N=`File: ${i} (${v}, ${f.size} bytes)`,Q=d.slice(x,T).map((re,le)=>`${x+le+1}: ${re}`).join(`
|
|
258
|
+
`),se=$?`
|
|
259
|
+
|
|
260
|
+
[\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>T?`
|
|
261
|
+
|
|
262
|
+
[\u{1F6A8} FILE CONTINUES: This is only lines ${x+1} to ${T} of ${p} total. The rest is HIDDEN. Use line_start=${T+1} to read the next section, or grep_search for keywords.]`:"";return`${N}
|
|
263
|
+
${Q}${se}`}finally{o.stop()}}case"write_file":{let o=new Ai("write_file","Preparing write...");o.start();try{await mc();let n=ot(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await Tt(n),i=null,a=String(e.content||"").split(`
|
|
264
|
+
`).length;if(o.update({count:a,detail:`${oe.relative(process.cwd(),n)} ${a} lines`,message:r?"Overwriting":"Creating"}),s.autoConfirm)r&&(i=await Ye.readFile(n,"utf-8"));else if(r){i=await Ye.readFile(n,"utf-8");let f=await Uo(n,e.content);if(Ci(n,i,e.content,{annotations:f}),!await Bo("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let f=await Uo(n,e.content);if(wS(n,e.content,{annotations:f}),!await Bo("Create"))return"CANCELLED: User declined to create file."}let l=oe.dirname(n);await Tt(l)||await Ye.mkdir(l,{recursive:!0}),o.update({message:"Writing",detail:`${oe.relative(process.cwd(),n)} ${a} lines`}),await Ye.writeFile(n,e.content,"utf-8");let u=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");u&&(o.update({message:"Chmod",detail:oe.relative(process.cwd(),n)}),await Ye.chmod(n,493)),Oi("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 Ai("edit_file","Preparing edit...");o.start();try{await mc();let n=ot(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Tt(n)){let d=await Mi(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${ce.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${oe.relative(process.cwd(),n)}${ce.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
265
|
+
`+d.message:""}`}o.update({message:"Loading",detail:oe.relative(process.cwd(),n)});let i=await Ye.readFile(n,"utf-8"),a=e.old_text,l=!1,c=!1;if(!i.includes(e.old_text)){o.update({message:"Matching target",detail:`${oe.relative(process.cwd(),n)} ${String(e.old_text||"").trim().split(`
|
|
266
|
+
`)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=lt();if(ym(d(),f())==="strict"){let g=Yo(i,e.old_text);return g?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
|
|
267
|
+
Most similar text (line ${g.line}, distance ${g.distance}):
|
|
268
|
+
${g.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let m=pm(i,e.old_text);if(m)a=m,l=!0,o.update({message:"Matched target",detail:`${oe.relative(process.cwd(),n)} whitespace-normalized`}),console.log(`${ce.dim} \u2713 fuzzy whitespace match applied${ce.reset}`);else{let g=vm(i,e.old_text,e.new_text);if(g){if(!s.autoConfirm){let R=await Uo(n,g.content);if(Ci(n,i,g.content,{annotations:R}),!await Bo(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await Ye.writeFile(n,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||g.content.startsWith("#!"))&&await Ye.chmod(n,493),Oi("edit_file",n,i,g.content);let A=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${ce.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${ce.reset}`),`Edited: ${n} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${A}")`}let $=Yo(i,e.old_text);if($){let A=i.split(`
|
|
269
|
+
`),R=Math.max(0,$.line-6),v=Math.min(A.length,$.line+10),N=A.slice(R,v).map((se,re)=>`${R+re+1}: ${se}`).join(`
|
|
270
|
+
`),Q=`line_start=${Math.max(1,$.line-5)} line_end=${Math.min(A.length,$.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${$.line}, distance ${$.distance})
|
|
271
|
+
|
|
272
|
+
Actual file content around line ${$.line} \u2014 use this to correct old_text:
|
|
273
|
+
${N}
|
|
274
|
+
|
|
275
|
+
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${Q}`}let x=(e.old_text||"").trim().split(`
|
|
276
|
+
`)[0].slice(0,60),T=x?`
|
|
277
|
+
Recovery: grep -n "${x.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
|
|
278
|
+
Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${n}${T}`}}if(!s.autoConfirm){o.update({message:"Previewing edit",detail:`${oe.relative(process.cwd(),n)} ${String(e.new_text||"").trim().split(`
|
|
279
|
+
`)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await Uo(n,d);if(Ci(n,i,d,{annotations:f}),!await Bo(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:`${oe.relative(process.cwd(),n)} ${String(e.new_text||"").trim().split(`
|
|
280
|
+
`)[0].slice(0,40)}`}),await Ye.writeFile(n,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||u.startsWith("#!"))&&(o.update({message:"Chmod",detail:oe.relative(process.cwd(),n)}),await Ye.chmod(n,493)),Oi("edit_file",n,i,u),l?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}finally{o.stop()}}case"list_directory":{let o=ot(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Tt(o)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=ot(c),d=await Tt(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 Ye.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(oe.join(c,p.name),u+1,d+" ")}};return await l(o,1,""),a.join(`
|
|
281
|
+
`)||"(empty)"}case"search_files":{let o=ot(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 is("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=Wo(r).slice(0,50);return(await hc(i,{query:e.pattern,basePath:o})).join(`
|
|
282
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let n=process.cwd(),r=e.path?ot(e.path):n,i=e.pattern,a=v=>{let N=v.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${N}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=Gn(),f=new d("glob","Finding files...");f.start();let p=hm();vS(r)||(await ES(r),p=hm());let m=p.filter(v=>l.test(v)||u.test(oe.basename(v))).map(v=>oe.join(r,v));if(m.length===0)return f.stop(),"(no matches)"+pc(e.path);let g=await Promise.all(m.slice(0,210).map(async v=>{try{let N=await Ye.stat(v);return{path:v,mtime:N.mtimeMs}}catch{return{path:v,mtime:0}}})),$=new Map(g.map(v=>[v.path,v.mtime])),x=await xm(i,r),T=Sm(g.map(v=>v.path),{query:i,basePath:r,definitionScores:x,mtimeByPath:$}),A=m.length>200,R=T.slice(0,200).join(`
|
|
283
|
+
`);return f.update({count:m.length,detail:e.pattern}),f.stop(),A?`${R}
|
|
284
|
+
|
|
285
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:R}case"grep":{let o=e.path?ot(e.path):process.cwd();if(e.staged){let{getDiff:l}=Qr(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
|
|
286
|
+
`);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:p}=Gn(),m=new p("grep","Searching staged content...");m.start();let g=[];for(let $ of u)try{let x=oe.join(process.cwd(),$);if(await Tt(x)){let T=[...f];T.push(e.pattern,x);let{stdout:A}=await is("grep",T,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let R=Wo(A,e.output_mode);g=g.concat(R)}else g=g.concat(Wo(A))}}catch{}return g=await hc(g,{query:e.pattern,basePath:process.cwd(),outputMode:e.output_mode}),m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
|
|
287
|
+
`).trim()||"(no matches in staged files)"}let n=["-rn","-E","-H"];e.ignore_case&&n.push("-i"),e.include&&n.push(`--include=${e.include}`),e.type&&n.push(`--include=*.${e.type}`);let r=20;e.context?n.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&n.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&n.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?n.push("-l"):e.output_mode==="count"&&n.push("-c"),n.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),n.push(e.pattern,o);let{ToolProgress:i}=Gn(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await is("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;e.output_mode==="files_with_matches"||e.output_mode==="count"?c=Wo(l,e.output_mode):c=Wo(l);let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=await hc(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(`
|
|
288
|
+
`).trim()||"(no matches)"+pc(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)"+pc(e.path)}}case"patch_file":{let o=new Ai("patch_file","Preparing patches...");o.start();try{await mc();let n=ot(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Tt(n)){let T=await Mi(e.path);if(T.fixedPath)n=T.fixedPath,console.log(`${ce.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${oe.relative(process.cwd(),n)}${ce.reset}`);else return`ERROR: File not found: ${e.path}${T.message?`
|
|
289
|
+
`+T.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:`${oe.relative(process.cwd(),n)} ${i.length} patches`,message:"Validating patches"});let a=await Ye.readFile(n,"utf-8"),{getActiveModelId:l,getActiveProviderName:c}=lt(),u=ym(l(),c()),d=[],f=!1,p=!1;for(let T=0;T<i.length;T++){o.update({count:T+1,total:i.length,detail:`${oe.relative(process.cwd(),n)} patch ${T+1}/${i.length}`,message:"Matching patches"});let{old_text:A,new_text:R}=i[T];if(a.includes(A))d.push({old_text:A,new_text:R});else if(u==="strict"){let v=Yo(a,A);return v?`ERROR: Patch ${T+1} old_text not found in ${n} (strict mode \u2014 exact match required)
|
|
275
290
|
Most similar text (line ${v.line}, distance ${v.distance}):
|
|
276
|
-
${v.text}`:`ERROR: Patch ${
|
|
277
|
-
Most similar text (line ${
|
|
278
|
-
${
|
|
291
|
+
${v.text}`:`ERROR: Patch ${T+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let v=pm(a,A);if(v)d.push({old_text:v,new_text:R}),f=!0;else{let N=Yo(a,A);if(N){let Q=Math.max(3,Math.ceil(A.length*.05));if(N.distance<=Q)d.push({old_text:N.text,new_text:R}),p=!0;else return`ERROR: Patch ${T+1} old_text not found in ${n}
|
|
292
|
+
Most similar text (line ${N.line}, distance ${N.distance}):
|
|
293
|
+
${N.text}`}else return`ERROR: Patch ${T+1} old_text not found in ${n}`}}}let m=a;for(let{old_text:T,new_text:A}of d)m=m.split(T).join(A);if(!s.autoConfirm){o.update({message:"Previewing patch set",count:d.length,total:i.length,detail:`${oe.relative(process.cwd(),n)} ${d.length} matched`});let T=await Uo(n,m);if(Ci(n,a,m,{annotations:T}),!await Bo(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:`${oe.relative(process.cwd(),n)} ${d.length} matched`}),await Ye.writeFile(n,m,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||m.startsWith("#!");g&&(o.update({message:"Chmod",detail:oe.relative(process.cwd(),n)}),await Ye.chmod(n,493)),Oi("patch_file",n,a,m);let $=p?" (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 dc.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 dc.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]
|
|
279
294
|
|
|
280
295
|
${r}`;return i.length>0&&(a+=`
|
|
281
296
|
|
|
282
297
|
Sources:
|
|
283
|
-
`+i.slice(0,
|
|
284
|
-
`)),a}catch(
|
|
298
|
+
`+i.slice(0,o).map((l,c)=>`${c+1}. ${l}`).join(`
|
|
299
|
+
`)),a}catch(n){console.error(`${ce.dim} Perplexity search failed (${n.message}), falling back to DuckDuckGo${ce.reset}`)}try{let r=(await dc.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}
|
|
285
300
|
${c.url}`).join(`
|
|
286
301
|
|
|
287
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:
|
|
302
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=wn();try{let n=await o(e.url,{waitFor:e.wait_for}),r=n.links.length>0?`
|
|
288
303
|
|
|
289
304
|
Links:
|
|
290
|
-
`+
|
|
291
|
-
`):"";return`Title: ${
|
|
292
|
-
URL: ${
|
|
293
|
-
|
|
294
|
-
${
|
|
295
|
-
Title: ${
|
|
296
|
-
URL: ${
|
|
297
|
-
|
|
298
|
-
To analyze visually, paste the path into your next message: ${
|
|
299
|
-
URL: ${
|
|
300
|
-
Title: ${
|
|
301
|
-
Screenshot: ${
|
|
305
|
+
`+n.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
|
|
306
|
+
`):"";return`Title: ${n.title}
|
|
307
|
+
URL: ${n.url}
|
|
308
|
+
|
|
309
|
+
${n.text}${r}`}catch(n){return`ERROR: ${n.message}`}}case"browser_screenshot":{let{browserScreenshot:o}=wn();try{let n=await o(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${n.path}
|
|
310
|
+
Title: ${n.title}
|
|
311
|
+
URL: ${n.url}
|
|
312
|
+
|
|
313
|
+
To analyze visually, paste the path into your next message: ${n.path}`}catch(n){return`ERROR: ${n.message}`}}case"visual_review":{let{browserScreenshot:o}=wn();try{let n=await o(e.url,{width:e.width||1280,height:e.height||800,fullPage:e.full_page||!1}),r=e.focus||"general layout, spacing, typography, colors, and usability",i=`VISUAL REVIEW \u2014 Screenshot captured
|
|
314
|
+
URL: ${n.url}
|
|
315
|
+
Title: ${n.title}
|
|
316
|
+
Screenshot: ${n.path}
|
|
302
317
|
Viewport: ${e.width||1280}\xD7${e.height||800}${e.full_page?" (full page)":""}
|
|
303
318
|
|
|
304
319
|
Focus area: ${r}
|
|
@@ -312,44 +327,44 @@ Analyze the screenshot above and provide structured feedback:
|
|
|
312
327
|
4. Responsiveness concerns at this viewport
|
|
313
328
|
5. Specific issues related to: ${r}`;return e.compare_with&&Kt.existsSync(e.compare_with)&&(i+=`
|
|
314
329
|
|
|
315
|
-
COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:
|
|
316
|
-
Size: ${Math.round(Buffer.from(
|
|
330
|
+
COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:n.path,base64:n.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(n){return`ERROR: ${n.message}`}}case"clipboard_image":try{let{_grabClipboardImage:o}=$c(),n=o();return n?{text:`Clipboard image captured: ${n.path}
|
|
331
|
+
Size: ${Math.round(Buffer.from(n.data,"base64").length/1024)} KB
|
|
317
332
|
|
|
318
|
-
[Clipboard image is attached for visual analysis]`,images:[{path:
|
|
319
|
-
`):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${
|
|
320
|
-
Changed: ${
|
|
321
|
-
Canvas: ${
|
|
322
|
-
Diff image: ${
|
|
333
|
+
[Clipboard image is attached for visual analysis]`,images:[{path:n.path,base64:n.data,media_type:n.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(o){return`ERROR: ${o.message}`}case"browser_click":{let{browserClick:o}=wn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(n){return`ERROR: ${n.message}`}}case"browser_fill":{let{browserFill:o}=wn();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(n){return`ERROR: ${n.message}`}}case"visual_diff":try{let{pixelDiff:o}=Jn(),n=o(e.before,e.after,{threshold:e.threshold}),r=n.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
|
|
334
|
+
`):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${n.diffPercent}% of pixels changed
|
|
335
|
+
Changed: ${n.changedPixels.toLocaleString()} / ${n.totalPixels.toLocaleString()} pixels
|
|
336
|
+
Canvas: ${n.width}\xD7${n.height}
|
|
337
|
+
Diff image: ${n.diffPath}
|
|
323
338
|
|
|
324
339
|
Regional breakdown:
|
|
325
340
|
${i}
|
|
326
341
|
|
|
327
|
-
[Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:
|
|
328
|
-
`);return{text:`RESPONSIVE SWEEP \u2014 ${
|
|
342
|
+
[Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:n.diffPath,base64:Kt.readFileSync(n.diffPath).toString("base64"),media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"responsive_sweep":try{let{responsiveSweep:o}=Jn(),n=await o(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=n.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
|
|
343
|
+
`);return{text:`RESPONSIVE SWEEP \u2014 ${n.length} viewports captured
|
|
329
344
|
URL: ${e.url}
|
|
330
345
|
|
|
331
346
|
Screenshots:
|
|
332
347
|
${r}
|
|
333
348
|
|
|
334
|
-
[All ${
|
|
349
|
+
[All ${n.length} screenshots attached for breakpoint analysis]
|
|
335
350
|
|
|
336
351
|
Analyze these screenshots for:
|
|
337
352
|
1. Layout breakpoint issues (overflow, collapse, stacking)
|
|
338
353
|
2. Typography scaling (text too small on mobile, too large on desktop)
|
|
339
354
|
3. Navigation pattern changes across viewports
|
|
340
355
|
4. Image/media sizing and aspect ratio issues
|
|
341
|
-
5. Touch target sizes on mobile viewports`,images:
|
|
356
|
+
5. Touch target sizes on mobile viewports`,images:n.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(o){return`ERROR: ${o.message}`}case"visual_annotate":try{let{annotateImage:o}=Jn(),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})
|
|
342
357
|
Source: ${e.image}
|
|
343
|
-
Output: ${
|
|
358
|
+
Output: ${n.path}
|
|
344
359
|
|
|
345
|
-
[Annotated image attached with visual markers]`,images:[{path:
|
|
360
|
+
[Annotated image attached with visual markers]`,images:[{path:n.path,base64:n.base64,media_type:n.media_type}]}}catch(o){return`ERROR: ${o.message}`}case"visual_watch":try{let{visualWatch:o}=Jn(),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:Kt.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
|
|
346
361
|
`),images:c}}return{text:i.join(`
|
|
347
362
|
`)+`
|
|
348
363
|
|
|
349
|
-
No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(
|
|
350
|
-
`),i=
|
|
351
|
-
`):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${
|
|
352
|
-
Source: ${
|
|
364
|
+
No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(o){return`ERROR: ${o.message}`}case"design_tokens":try{let{extractDesignTokens:o}=Jn(),n=o(e.image,{sampleRate:e.sample_rate}),r=n.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
|
|
365
|
+
`),i=n.spacing.length?n.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
|
|
366
|
+
`):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${n.dimensions.width}\xD7${n.dimensions.height} image
|
|
367
|
+
Source: ${n.imagePath}
|
|
353
368
|
|
|
354
369
|
Dominant Colors:
|
|
355
370
|
${r}
|
|
@@ -360,102 +375,102 @@ ${i}
|
|
|
360
375
|
Use these values to:
|
|
361
376
|
- Compare against CSS variables / design system tokens
|
|
362
377
|
- Identify inconsistent colors or spacing
|
|
363
|
-
- Generate a color palette from the rendered output`}catch(
|
|
364
|
-
`)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${
|
|
365
|
-
Reference: ${
|
|
366
|
-
Live: ${
|
|
367
|
-
Diff: ${
|
|
368
|
-
Annotated: ${
|
|
378
|
+
- Generate a color palette from the rendered output`}catch(o){return`ERROR: ${o.message}`}case"design_compare":try{let{designCompare:o}=Jn(),n=await o(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=n.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
|
|
379
|
+
`)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${n.diffPercent}% deviation from reference
|
|
380
|
+
Reference: ${n.referencePath}
|
|
381
|
+
Live: ${n.livePath}
|
|
382
|
+
Diff: ${n.diffPath}
|
|
383
|
+
Annotated: ${n.annotatedPath}
|
|
369
384
|
|
|
370
|
-
Pixel deviation: ${
|
|
385
|
+
Pixel deviation: ${n.changedPixels.toLocaleString()} / ${n.totalPixels.toLocaleString()}
|
|
371
386
|
|
|
372
387
|
Regional breakdown:
|
|
373
388
|
${r}
|
|
374
389
|
|
|
375
|
-
[Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:
|
|
376
|
-
${
|
|
390
|
+
[Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:n.livePath,base64:n.liveBase64,media_type:"image/png"},{path:n.diffPath,base64:n.diffBase64,media_type:"image/png"},{path:n.annotatedPath,base64:n.annotatedBase64,media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"ask_user":{let{question:o,options:n=[]}=e;return wc?new Promise(r=>{as=()=>r("CANCELLED"),wc(o,n).then(i=>{as=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});as=()=>{i.close(),r("CANCELLED")};let a=n.length>0?`
|
|
391
|
+
${n.map((l,c)=>` ${c+1}. ${l}`).join(`
|
|
377
392
|
`)}
|
|
378
393
|
`:"";console.log(`
|
|
379
|
-
${
|
|
380
|
-
Clean working tree (no changes)`;let r=[`Branch: ${
|
|
381
|
-
`)}case"git_diff":{if(!await
|
|
394
|
+
${ce.cyan}${ce.bold} ? ${o}${ce.reset}${a}`),i.question(`${ce.cyan} > ${ce.reset}`,l=>{as=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await fc())return"ERROR: Not a git repository";let o=await fm()||"(detached)",n=await _S();if(n.length===0)return`Branch: ${o}
|
|
395
|
+
Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${n.length}):`];for(let i of n){let a=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${a}: ${i.file}`)}return r.join(`
|
|
396
|
+
`)}case"git_diff":{if(!await fc())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 kS(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await fc())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}=Xl(),{getActiveTaskProgress:l}=nt(),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(`
|
|
382
397
|
`+i()),`Created task list "${e.name}" with ${u.length} tasks:
|
|
383
398
|
`+u.map(d=>` ${d.id}: ${d.description}`).join(`
|
|
384
|
-
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":
|
|
399
|
+
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":n(e.task_id,e.status,e.result)?(c||console.log(`
|
|
385
400
|
`+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(`
|
|
386
|
-
`+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:
|
|
401
|
+
`+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}=Pi();return e.agents?.some(r=>r.background)?n(e):o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:n,getActiveModelId:r}=lt();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 is("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(`
|
|
387
402
|
`)}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(`
|
|
388
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";if(!/^\d+$/.test(String(e.run_id)))return"ERROR: run_id must be numeric";try{if(e.log){let{stdout:i}=await
|
|
389
|
-
...(truncated)`:"")}let{stdout:
|
|
390
|
-
`)}catch(
|
|
391
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";if(!/^[\w./-]+$/.test(e.workflow))return"ERROR: invalid workflow name";let{confirm:
|
|
392
|
-
${
|
|
393
|
-
`)[0]}`}}case"k8s_pods":{let
|
|
394
|
-
`)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let
|
|
403
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";if(!/^\d+$/.test(String(e.run_id)))return"ERROR: run_id must be numeric";try{if(e.log){let{stdout:i}=await is("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
404
|
+
...(truncated)`:"")}let{stdout:o}=await is("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(`
|
|
405
|
+
`)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
|
|
406
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";if(!/^[\w./-]+$/.test(e.workflow))return"ERROR: invalid workflow name";let{confirm:o}=wo(),n=e.branch||await fm()||"main";if(!/^[\w./-]+$/.test(n))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",n];if(e.inputs)for(let[a,l]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${l}`)}if(console.log(`
|
|
407
|
+
${ce.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${n}${ce.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await is("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${n}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
408
|
+
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",n=e.label?`-l ${e.label}`:"",r=Go(`get pods ${o} ${n} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await Be(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
|
|
409
|
+
`)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let o=e.namespace||"default",n=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${n}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Go(r,e);try{let{stdout:a,stderr:l}=await Be(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
|
|
395
410
|
...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
396
|
-
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let
|
|
397
|
-
${
|
|
398
|
-
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let
|
|
399
|
-
${
|
|
400
|
-
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let
|
|
401
|
-
${
|
|
402
|
-
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:
|
|
403
|
-
|
|
404
|
-
`+i:i;return
|
|
411
|
+
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let o=e.namespace||"default";if(console.log(`
|
|
412
|
+
${ce.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${ce.reset}`),console.log(`${ce.dim} Command: ${e.command}${ce.reset}`),!await zt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${o}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Go(r,e);try{let{stdout:a,stderr:l}=await Be(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
413
|
+
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let o=!!e.dry_run;if(!o){let i=e.file;if(console.log(`
|
|
414
|
+
${ce.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ce.reset}`),!await zt(" 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=Go(n,e);try{let{stdout:i,stderr:a}=await Be(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
415
|
+
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let o=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let a=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
416
|
+
${ce.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${ce.reset}`),!await zt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=Go(r,e);try{let{stdout:a,stderr:l}=await Be(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
417
|
+
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:o,readDocument:n}=ac(),{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+`
|
|
418
|
+
|
|
419
|
+
`+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=jt(e.server)}catch(N){return`ERROR: ${N.message}`}let n=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=mS(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:
|
|
405
420
|
grep -n "pattern" /path/to/file -A 50
|
|
406
421
|
or to read the whole file:
|
|
407
422
|
cat /path/to/file
|
|
408
423
|
NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
|
|
409
|
-
HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(
|
|
410
|
-
${
|
|
411
|
-
`).trim();if(d!==0){if(/no such file or directory/i.test(p)){let
|
|
424
|
+
HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(n=n.replace(/(-[BAC])\s*(\d+)/g,(N,Q,se)=>{let re=Math.min(Number(se),20);return`${Q} ${re}`}),n=n.replace(/(--(?:before|after|context)=)(\d+)/g,(N,Q,se)=>Q+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 N=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
425
|
+
${ce.yellow} \u26A0 Remote command on ${N}: ${n}${ce.reset}`),!await zt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await gt(o,n,{timeout:i,sudo:r}),p=[c,u].filter(Boolean).join(`
|
|
426
|
+
`).trim();if(d!==0){if(/no such file or directory/i.test(p)){let Q=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._-]+)['"]?/),re=Q&&Q[1]||se&&se[1];if(re)try{let{remoteAutoFixPath:le}=Ls(),ne=re.startsWith("/")?re.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(o.user||"root"),S=await le(o,ne,re);if(S.fixedPath){let ve=n.replace(re,S.fixedPath);console.log(`${ce.dim} \u2713 remote auto-fix: ${re} \u2192 ${S.fixedPath}${ce.reset}`);let W=await gt(o,ve,{timeout:i,sudo:r}),z=[W.stdout,W.stderr].filter(Boolean).join(`
|
|
412
427
|
`).trim();if(W.exitCode===0)return`${S.message}
|
|
413
428
|
${z}`||"(command completed, no output)"}else if(S.message)return`EXIT ${d}
|
|
414
429
|
${f||p}
|
|
415
430
|
|
|
416
431
|
${S.message}`}catch{}}return`EXIT ${d}
|
|
417
|
-
${f||p||"(no output)"}`}let m=/\bgrep\b/.test(
|
|
418
|
-
`).filter(
|
|
419
|
-
`));let $=m?60:100,
|
|
420
|
-
`);
|
|
421
|
-
`+
|
|
422
|
-
`));let
|
|
423
|
-
`),
|
|
424
|
-
`)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let
|
|
425
|
-
${
|
|
426
|
-
${l}`}if(a.message)return`ERROR: ${
|
|
427
|
-
|
|
428
|
-
${a.message}`}catch{}return`ERROR: ${
|
|
429
|
-
${p.slice(-2e3)}`:p.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let
|
|
430
|
-
${
|
|
432
|
+
${f||p||"(no output)"}`}let m=/\bgrep\b/.test(n),g=p;m&&(g=g.split(`
|
|
433
|
+
`).filter(N=>N!=="--").join(`
|
|
434
|
+
`));let $=m?60:100,x=g.split(`
|
|
435
|
+
`);x.length>$&&(g=`(${x.length-$} earlier lines omitted \u2014 showing last ${$})
|
|
436
|
+
`+x.slice(-$).join(`
|
|
437
|
+
`));let T=4,A=g.split(`
|
|
438
|
+
`),R=[],v=0;for(;v<A.length;){let N=v+1;for(;N<A.length&&A[N]===A[v];)N++;let Q=N-v;if(R.push(A[v]),Q>T)R.push(`... (${Q-1} identical lines omitted)`);else for(let se=1;se<Q;se++)R.push(A[v]);v=N}return R.join(`
|
|
439
|
+
`)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let o;try{o=jt(e.server)}catch(i){return`ERROR: ${i.message}`}let n=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
440
|
+
${ce.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${n}:${e.remote_path}${ce.reset}`),!await zt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await TS(o,e.local_path,e.remote_path);try{Ls().clearRemoteIndex()}catch{}return i}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let o;try{o=jt(e.server)}catch(n){return`ERROR: ${n.message}`}try{return await gm(o,e.remote_path,e.local_path)}catch(n){if(/no such file|not found/i.test(n.message))try{let{remoteAutoFixPath:r}=Ls(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(o,i,e.remote_path);if(a.fixedPath){console.log(`${ce.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${ce.reset}`);let l=await gm(o,a.fixedPath,e.local_path);return`${a.message}
|
|
441
|
+
${l}`}if(a.message)return`ERROR: ${n.message}
|
|
442
|
+
|
|
443
|
+
${a.message}`}catch{}return`ERROR: ${n.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),n=null;try{n=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=n?`${n.user||"root"}@${n.host}`:e.server,i=n?.key?["-i",n.key]:[],a=(e.project_path||n?.home||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),l=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),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}.
|
|
444
|
+
${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=yc(e.service);if(o)return o;let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let r=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",a=null;if(!r)try{a=jt(e.server)}catch(u){return`ERROR: ${u.message}`}if(!i){let u=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
|
|
445
|
+
${ce.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${u}${ce.reset}`),!await zt(" Execute?"))return"CANCELLED: User declined service action."}let l=e.service.includes(".")?e.service:`${e.service}.service`,c=`systemctl ${e.action} ${xe(l)}`;if(r){let d=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:f,stderr:p}=await Be(d,{timeout:15e3});return(f||p||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(f){let p=(f.stderr||f.message||"").toString().trim();return/not found|loaded.*not-found/i.test(p)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${f.code||1}
|
|
431
446
|
${p}`}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await gt(a,c,{timeout:15e3,sudo:!0}),m=[u,d].filter(Boolean).join(`
|
|
432
447
|
`).trim();return f!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${a.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${f}
|
|
433
|
-
${p||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let
|
|
448
|
+
${p||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=yc(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 ${xe(e.since)}`:"",l=e.follow?"-f":"",c=`journalctl -u ${xe(i)} -n ${r} ${a} ${l} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:$,stderr:x}=await Be(c,{timeout:15e3});return($||x||"(no log output)").trim()}catch($){return`EXIT ${$.code||1}
|
|
434
449
|
${($.stderr||$.message||"").toString().trim()}`}let u;try{u=jt(e.server)}catch($){return`ERROR: ${$.message}`}let{stdout:d,stderr:f,exitCode:p,error:m}=await gt(u,c,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
|
|
435
450
|
`).trim();return p!==0?`EXIT ${p}
|
|
436
|
-
${m||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let
|
|
451
|
+
${m||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let o=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(o)try{let{stdout:f,stderr:p}=await Be(r,{timeout:1e4});return(f||p||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
|
|
437
452
|
${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=jt(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await gt(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
|
|
438
453
|
`).trim();return c!==0?`EXIT ${c}
|
|
439
|
-
${u||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let
|
|
454
|
+
${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 Be(i,{timeout:15e3});return(p||m||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
440
455
|
${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=jt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await gt(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
|
|
441
456
|
`).trim();return u!==0?`EXIT ${u}
|
|
442
|
-
${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let
|
|
443
|
-
${
|
|
457
|
+
${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!n.test(e.command.trim())){let m=o?"local":e.server;if(console.log(`
|
|
458
|
+
${ce.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${ce.reset}`),!await zt(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let a=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(o)try{let{stdout:m,stderr:g}=await Be(a,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
444
459
|
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=jt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await gt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
|
|
445
460
|
`).trim();return d!==0?`EXIT ${d}
|
|
446
|
-
${f||p}`:p||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let
|
|
447
|
-
${
|
|
461
|
+
${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(`
|
|
462
|
+
${ce.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${ce.reset}`),!await zt(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(n)try{let{stdout:m,stderr:g}=await Be(a,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
|
|
448
463
|
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=jt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await gt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
|
|
449
464
|
`).trim();return d!==0?`EXIT ${d}
|
|
450
|
-
${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...
|
|
451
|
-
${
|
|
452
|
-
${
|
|
465
|
+
${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...RS(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=jt(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(`
|
|
466
|
+
${ce.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${ce.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
|
|
467
|
+
${ce.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ce.reset}`)}if(e.deploy_script&&console.log(`${ce.yellow} Then run: ${e.deploy_script}${ce.reset}`),e.health_check&&console.log(`${ce.yellow} Health check: ${e.health_check}${ce.reset}`),!await zt(" 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}:
|
|
453
468
|
${f}${e.deploy_script?`
|
|
454
|
-
${e.deploy_script}`:""}`;let{stdout:p,stderr:m,exitCode:g,error:$}=await gt(
|
|
469
|
+
${e.deploy_script}`:""}`;let{stdout:p,stderr:m,exitCode:g,error:$}=await gt(n,f,{timeout:12e4});if(i=[p,m].filter(Boolean).join(`
|
|
455
470
|
`).trim(),g!==0)return`ERROR (git pull, exit ${g}):
|
|
456
|
-
${$||i}`}else{let u=
|
|
457
|
-
${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await gt(
|
|
458
|
-
`).trim();if(f!==0)return`${
|
|
471
|
+
${$||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:$}=await Be(m,{timeout:12e4});i=(g||$||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
|
|
472
|
+
${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await gt(n,e.deploy_script,{timeout:12e4}),m=[u,d].filter(Boolean).join(`
|
|
473
|
+
`).trim();if(f!==0)return`${o==="git"?"git pull":"rsync"} OK
|
|
459
474
|
|
|
460
475
|
ERROR (deploy_script, exit ${f}):
|
|
461
476
|
${p||m}`;a=`
|
|
@@ -465,64 +480,64 @@ ${m||"(no output)"}`}let l="";if(e.health_check){let u=e.health_check.trim();if(
|
|
|
465
480
|
|
|
466
481
|
Health check: \u2713 ${u} \u2192 ${p.status}`;else return l=`
|
|
467
482
|
|
|
468
|
-
Health check FAILED: ${u} \u2192 HTTP ${p.status}`,(
|
|
483
|
+
Health check FAILED: ${u} \u2192 HTTP ${p.status}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l}catch(f){return l=`
|
|
469
484
|
|
|
470
|
-
Health check FAILED: ${u} \u2192 ${f.message}`,(
|
|
485
|
+
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 gt(n,u,{timeout:15e3}),g=[f,p].filter(Boolean).join(`
|
|
471
486
|
`).trim();if(m!==0)return l=`
|
|
472
487
|
|
|
473
|
-
Health check FAILED (exit ${m}): ${g}`,(
|
|
488
|
+
Health check FAILED (exit ${m}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
|
|
474
489
|
|
|
475
|
-
Health check: \u2713 ${g||"(exit 0)"}`}}let c=
|
|
476
|
-
${i}${a}${l}`.trim()}case"deployment_status":{let
|
|
490
|
+
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}
|
|
491
|
+
${i}${a}${l}`.trim()}case"deployment_status":{let o=CS(),n=e.config?[e.config]:Object.keys(o);if(n.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of n){let a=o[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let l=jt(a.server||i),u=(await gt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await gt(l,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let m=require("node-fetch"),g=await Promise.race([m(p),new Promise(($,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 gt(l,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
|
|
477
492
|
${r.join(`
|
|
478
|
-
`)}`}case"frontend_recon":{let
|
|
479
|
-
`),
|
|
480
|
-
`);return se.length>
|
|
481
|
-
... (${se.length-
|
|
482
|
-
`).filter(Boolean)}catch{return[]}},u=async(v
|
|
493
|
+
`)}`}case"frontend_recon":{let o=process.cwd(),n=(e.type||"").toLowerCase(),r=[],i=async(R,v=120)=>{try{let N=oe.isAbsolute(R)?R:oe.join(o,R),se=(await Ye.readFile(N,"utf8")).split(`
|
|
494
|
+
`),re=se.slice(0,v).join(`
|
|
495
|
+
`);return se.length>v?re+`
|
|
496
|
+
... (${se.length-v} more lines \u2014 use read_file for full content)`:re}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(R=>`-not -path "*/${R}/*"`).join(" "),c=async R=>{try{let{stdout:v}=await Be(`find "${o}" -type f -name "${R}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return v.trim().split(`
|
|
497
|
+
`).filter(Boolean)}catch{return[]}},u=async(R,v)=>{try{let{stdout:N}=await Be(`grep -rl "${R}" "${o}" --include="${v}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return N.trim().split(`
|
|
483
498
|
`).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
|
|
484
|
-
`);let d=[...await c("tailwind.config.js"),...await c("tailwind.config.ts"),...await c("tailwind.config.mjs")];if(d.length>0){let
|
|
499
|
+
`);let d=[...await c("tailwind.config.js"),...await c("tailwind.config.ts"),...await c("tailwind.config.mjs")];if(d.length>0){let R=await i(d[0],80);R&&r.push(`### Tailwind config (${oe.relative(o,d[0])})
|
|
485
500
|
\`\`\`js
|
|
486
|
-
${
|
|
487
|
-
\`\`\``)}else r.push("(no tailwind.config found)");let f=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],p=!1;for(let
|
|
501
|
+
${R}
|
|
502
|
+
\`\`\``)}else r.push("(no tailwind.config found)");let f=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],p=!1;for(let R of f){let v=await c(R);for(let N of v){let Q=await i(N,100);if(Q&&Q.includes(":root")){r.push(`### CSS Variables (${oe.relative(o,N)})
|
|
488
503
|
\`\`\`css
|
|
489
|
-
${
|
|
490
|
-
\`\`\``),p=!0;break}}if(p)break}if(!p){let
|
|
504
|
+
${Q}
|
|
505
|
+
\`\`\``),p=!0;break}}if(p)break}if(!p){let R=await u(":root","*.css");if(R.length>0){let v=await i(R[0],100);v&&r.push(`### CSS Variables (${oe.relative(o,R[0])})
|
|
491
506
|
\`\`\`css
|
|
492
|
-
${
|
|
507
|
+
${v}
|
|
493
508
|
\`\`\``),p=!0}}p||r.push("(no CSS custom properties / :root found)"),r.push(`
|
|
494
509
|
## STEP 2: Main Layout / Index Page
|
|
495
|
-
`);let m=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let
|
|
510
|
+
`);let m=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let R of m){let v=await c(R);if(v.length>0){let N=await i(v[0],150);if(N){r.push(`### Main layout: ${oe.relative(o,v[0])}
|
|
496
511
|
\`\`\`html
|
|
497
|
-
${
|
|
512
|
+
${N}
|
|
498
513
|
\`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
|
|
499
514
|
## STEP 3: Reference Component (same type)
|
|
500
|
-
`);let $=[];if(
|
|
501
|
-
`).filter(Boolean)}catch{$=[]}if($.length>0){let
|
|
515
|
+
`);let $=[];if(n){for(let R of["*.html","*.vue","*.jsx","*.tsx"])if($=await u(n,R),$.length>0)break}if($.length===0)try{let{stdout:R}=await Be(`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});$=R.trim().split(`
|
|
516
|
+
`).filter(Boolean)}catch{$=[]}if($.length>0){let R=$[0],v=await i(R,150);v?r.push(`### Reference: ${oe.relative(o,R)}
|
|
502
517
|
\`\`\`html
|
|
503
|
-
${
|
|
518
|
+
${v}
|
|
504
519
|
\`\`\``):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(`
|
|
505
520
|
## STEP 4: Framework Stack
|
|
506
|
-
`);let
|
|
521
|
+
`);let x=[],T=await i(oe.join(o,"package.json"),999);if(T){if((T.includes('"react"')||T.includes("'react'"))&&x.push("React"),T.includes('"vue"')||T.includes("'vue'")){let v=T.match(/"vue":\s*"[\^~]?(\d+)/);x.push(v?`Vue.js v${v[1]}`:"Vue.js")}let R=T.match(/"alpinejs":\s*"[\^~]?(\d+)/);R&&x.push(`Alpine.js v${R[1]} (\u26A0 v2 vs v3 API differs!)`),(T.includes('"htmx')||T.includes("'htmx"))&&x.push("HTMX"),T.includes('"tailwindcss"')&&x.push("Tailwind CSS"),T.includes('"bootstrap"')&&x.push("Bootstrap")}if((await Tt(oe.join(o,"manage.py"))||(await i(oe.join(o,"requirements.txt"),50)||"").includes("Django"))&&x.push("Django (server-rendered templates)"),!x.some(R=>R.includes("Alpine"))){let R=await u("alpinejs","*.html");if(R.length>0){let N=(await i(R[0],30)||"").match(/alpinejs[@/]v?(\d)/);x.push(N?`Alpine.js v${N[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return x.some(R=>R.includes("HTMX"))||(await u("htmx","*.html")).length>0&&x.push("HTMX (via CDN)"),x.length>0?(r.push(x.map(R=>`- ${R}`).join(`
|
|
507
522
|
`)),r.push(`
|
|
508
523
|
\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(`
|
|
509
524
|
---
|
|
510
525
|
\u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
|
|
511
|
-
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let
|
|
526
|
+
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",n;if(!o)try{n=jt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(o)try{let{stdout:u,stderr:d}=await Be(l,{timeout:c});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await gt(n,l,{timeout:c}),m=[u,d].filter(Boolean).join(`
|
|
512
527
|
`).trim();return{out:p&&f!==0&&!u.trim()?(p+`
|
|
513
|
-
`+m).trim():m,exitCode:f}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!s.autoConfirm){let l=
|
|
528
|
+
`+m).trim():m,exitCode:f}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!s.autoConfirm){let l=o?"local":e.server;if(!await zt(`sysadmin [${e.action}] on ${l} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let l=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:c,exitCode:u}=await r(l,45e3);return c||`EXIT ${u}
|
|
514
529
|
(no output)`}case"disk_usage":{let l=e.path||"/",c=xe(l),u=`df -h ${c}; echo '--- Top subdirs ---'; du -d1 -x -h ${c} 2>/dev/null | sort -rh | head -20`,{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
|
|
515
530
|
${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}
|
|
516
531
|
${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}
|
|
517
|
-
${c}`:c}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:l}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),c=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!c)return"ERROR: No supported package manager found (dnf/apt)";let u=e.packages||[];if(!u.every(
|
|
532
|
+
${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(WS))return"ERROR: package names contain unsafe characters";let d=u.map(xe).join(" "),f;switch(e.package_action){case"list":f=c==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=c==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:$}=await r(g,6e4);return $||"(no output from package check)"}case"install":if(!d)return"ERROR: packages required for install";f=c==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=c==="dnf"?`dnf remove -y ${d}`:`apt-get remove -y ${d}`;break;case"update":if(!d)return"ERROR: packages required for update (use upgrade for full system upgrade)";f=c==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=c==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:p,exitCode:m}=await r(f,12e4);return m!==0?`EXIT ${m}
|
|
518
533
|
${p}`:p||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let l=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:c,exitCode:u}=await r(l,1e4);return u!==0?`EXIT ${u}
|
|
519
|
-
${c}`:c||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=
|
|
520
|
-
${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=
|
|
521
|
-
${f}`:f}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=
|
|
522
|
-
${d}`:d}case"add_ssh_key":{if(!e.user)return"ERROR: user is required for user_action=add_ssh_key";if(!e.ssh_key)return"ERROR: ssh_key is required for user_action=add_ssh_key";let l=
|
|
534
|
+
${c}`:c||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=Ho(e.user);if(l)return l;let c=xe(e.user),u=`id ${c} && echo '--- Groups ---' && groups ${c} && echo '--- Last login ---' && lastlog -u ${c} 2>/dev/null`,{out:d,exitCode:f}=await r(u,1e4);return f!==0?`EXIT ${f}
|
|
535
|
+
${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=Ho(e.user);if(l)return l;if(!(e.groups||[]).every(Tm))return"ERROR: groups contain unsafe characters";let c=(e.groups||[]).map(m=>`-G ${xe(m)}`).join(" "),u=xe(e.user),d=`useradd -m ${c} ${u} && echo "User ${e.user} created"`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
|
|
536
|
+
${f}`:f}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=Ho(e.user);if(l)return l;let u=`userdel -r ${xe(e.user)} && echo "User ${e.user} deleted"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
537
|
+
${d}`:d}case"add_ssh_key":{if(!e.user)return"ERROR: user is required for user_action=add_ssh_key";if(!e.ssh_key)return"ERROR: ssh_key is required for user_action=add_ssh_key";let l=Ho(e.user);if(l)return l;let u=`${`/home/${e.user}`}/.ssh`,d=`${u}/authorized_keys`,f=xe(e.user),p=`mkdir -p ${xe(u)} && chmod 700 ${xe(u)} && printf '%s
|
|
523
538
|
' ${xe(e.ssh_key)} >> ${xe(d)} && chmod 600 ${xe(d)} && chown -R ${xe(`${e.user}:${e.user}`)} ${xe(u)} && echo "SSH key added for ${e.user}"`,{out:m,exitCode:g}=await r(p,15e3);return g!==0?`EXIT ${g}
|
|
524
|
-
${m}`:m}default:return`ERROR: Unknown user_action: ${e.user_action}`}}case"firewall":{if(!e.firewall_action)return"ERROR: firewall_action is required for action=firewall";let{out:l}=await r("which firewall-cmd 2>/dev/null && echo firewalld || (which ufw 2>/dev/null && echo ufw) || echo iptables",1e4),c=l.includes("firewalld")?"firewalld":l.includes("ufw")?"ufw":"iptables",u;switch(e.firewall_action){case"status":u=c==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":c==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';if(!
|
|
525
|
-
${d}`:d||`firewall ${e.firewall_action} OK`}case"cron":{if(!e.cron_action)return"ERROR: cron_action is required for action=cron";if(e.user){let c=
|
|
539
|
+
${m}`:m}default:return`ERROR: Unknown user_action: ${e.user_action}`}}case"firewall":{if(!e.firewall_action)return"ERROR: firewall_action is required for action=firewall";let{out:l}=await r("which firewall-cmd 2>/dev/null && echo firewalld || (which ufw 2>/dev/null && echo ufw) || echo iptables",1e4),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(!gc(e.port))return"ERROR: port contains unsafe characters";u=c==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw allow ${xe(e.port)}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT`;break;case"deny":if(!e.port)return"ERROR: port is required for firewall deny";if(!gc(e.port))return"ERROR: port contains unsafe characters";u=c==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw deny ${xe(e.port)}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j DROP`;break;case"remove":if(!e.port)return"ERROR: port is required for firewall remove";if(!gc(e.port))return"ERROR: port contains unsafe characters";u=c==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:c==="ufw"?`ufw delete allow ${xe(e.port)}`:`iptables -D INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT 2>/dev/null || true`;break;case"reload":u=c==="firewalld"?"firewall-cmd --reload":c==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
|
|
540
|
+
${d}`:d||`firewall ${e.firewall_action} OK`}case"cron":{if(!e.cron_action)return"ERROR: cron_action is required for action=cron";if(e.user){let c=Ho(e.user);if(c)return c}let l=e.user?`-u ${xe(e.user)}`:"";switch(e.cron_action){case"list":{let c=`crontab ${l} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:u}=await r(c,1e4);return u||"(empty crontab)"}case"add":{if(!e.schedule)return"ERROR: schedule is required for cron add";if(!e.command)return"ERROR: command is required for cron add";let c=`${e.schedule} ${e.command}`,u=`(crontab ${l} -l 2>/dev/null; printf '%s
|
|
526
541
|
' ${xe(c)}) | crontab ${l} - && echo "Cron entry added: ${c}"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
527
542
|
${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}
|
|
528
543
|
${d}`:d}default:return`ERROR: Unknown cron_action: ${e.cron_action}`}}case"ssl_check":{if(!e.domain&&!e.cert_path)return"ERROR: domain or cert_path is required for ssl_check";let l;e.cert_path?l=`
|
|
@@ -551,12 +566,12 @@ fi
|
|
|
551
566
|
`.trim();let{out:c,exitCode:u}=await r(l,25e3),d=/notAfter=|Days until expiry:/i.test(c);return u!==0&&!d?`EXIT ${u}
|
|
552
567
|
${c}`:c||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let c=`tail -n ${e.lines||100} ${xe(e.path)} 2>&1`,{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
|
|
553
568
|
${u}`:u||"(empty log)"}case"find_large":{let l=e.path||"/",c=e.limit||20,u=e.min_size||"100M",d=`find ${xe(l)} -xdev -type f -size +${xe(u)} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${c}`,{out:f,exitCode:p}=await r(d,6e4);return p!==0?`EXIT ${p}
|
|
554
|
-
${f}`:f||`(no files larger than ${u} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";if(e.service_name){let p=
|
|
555
|
-
${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let l=e.signal||"SIGTERM";if(!
|
|
569
|
+
${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=yc(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}
|
|
570
|
+
${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(!HS(l))return"ERROR: signal contains unsafe characters";let c;if(e.pid){if(!/^\d+$/.test(String(e.pid)))return"ERROR: pid must be numeric";c=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${l} ${e.pid} && echo "Sent ${l} to PID ${e.pid}"`}else c=`pgrep -a ${xe(e.process_name)} 2>/dev/null | head -5 && pkill -${l} ${xe(e.process_name)} && echo "Sent ${l} to all '${e.process_name}' processes"`;let{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
|
|
556
571
|
${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}
|
|
557
|
-
${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:
|
|
558
|
-
`)}function
|
|
559
|
-
`),u=r.map(f=>
|
|
572
|
+
${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=qo(),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}=qo();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=oi(),n=await o(t,e,s);return n!==null?n:`ERROR: Unknown tool: ${t}`}}}async function YS(t,e,s={}){let{emit:o}=oi(),{logToolExecution:n}=um(),r=Date.now(),i=s.silent?null:bS(t,e);if(!i){let l=await _m(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 $S(i);a.start();try{let l=await _m(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}}Rm.exports={TOOL_DEFINITIONS:GS,executeTool:YS,resolvePath:ot,autoFixPath:Mi,autoFixEdit:vm,enrichBashError:Em,cancelPendingAskUser:IS,setAskUserHandler:jS,fileExists:Tt}});var xo=V((EC,Am)=>{Am.exports=Cm()});var _c=V((TC,Om)=>{var{loadServerProfiles:zo,resolveProfile:vC,sshExec:zS}=Ls(),bc={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 KS(){let t=zo();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&&bc[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 bc[n])s.push(`- ${i}`)}}return s.join(`
|
|
573
|
+
`)}function XS(t){let e=zo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function VS(){return Object.keys(zo())}function JS(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(s,"utf-8")}catch{}let n=zo(),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(`
|
|
574
|
+
`),u=r.map(f=>n[f].log_path).filter(Boolean),d=u.length>0?`
|
|
560
575
|
- Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
|
|
561
576
|
|
|
562
577
|
This project is deployed on a **remote server**. The application runs as a service there \u2014 NOT locally.
|
|
@@ -573,7 +588,7 @@ ${c}
|
|
|
573
588
|
- \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
|
|
574
589
|
- \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
|
|
575
590
|
|
|
576
|
-
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${
|
|
591
|
+
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${ZS(n)}`}function ZS(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
|
|
577
592
|
|
|
578
593
|
## Server Debugging Rules
|
|
579
594
|
|
|
@@ -584,51 +599,51 @@ ${c}
|
|
|
584
599
|
- 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.
|
|
585
600
|
- 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.
|
|
586
601
|
- 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.
|
|
587
|
-
- READING REMOTE FILES: NEVER use sed -n (always blocked). To read a specific function in a remote file: ssh_exec 'grep -n "functionName" /path/file -A 50'. To read the whole file: ssh_exec 'cat /path/file'. These are the only two options.`:""}async function
|
|
588
|
-
`+i.trim()}catch{return null}}
|
|
589
|
-
`)}catch{return""}}function
|
|
590
|
-
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function
|
|
591
|
-
`)}var
|
|
602
|
+
- 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 QS(t){if(typeof t!="string")return null;let e=[...t.matchAll(/https?:\/\/([a-zA-Z0-9._-]+)/g)];if(e.length===0)return null;let s=zo();if(Object.keys(s).length===0)return null;let o=null,n=null;for(let[,i]of e){let a=i.toLowerCase().split(".");for(let[l,c]of Object.entries(s))if(a.includes(l.toLowerCase())){o=c,n=l;break}if(o)break;for(let[l,c]of Object.entries(s))if(c.host===i){o=c,n=l;break}if(o)break}if(!o||!n)return null;let r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await zS(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]
|
|
603
|
+
`+i.trim()}catch{return null}}Om.exports={getServerContext:KS,getDeploymentContextBlock:JS,hasServerOS:XS,getProfileNames:VS,probeUrlServer:QS,OS_HINTS:bc}});var Lm=V((RC,Pm)=>{var yt=require("fs").promises,Ii=require("fs"),Ue=require("path"),Li=require("util").promisify(require("child_process").exec),{C:Hs}=nt(),{getMergeConflicts:Mm}=Qr(),{getServerContext:eE}=_c(),{refreshIndex:tE,getFileIndex:nE,buildContentIndex:sE,summarizeModuleHubs:oE}=sn(),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=Ue.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=Ue.join(t,"package.json");if(Ii.existsSync(d)){let f=JSON.parse(Ii.readFileSync(d,"utf-8"));a=dE(f)}}catch{}let l="",c="";try{let d=await sE(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 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(`
|
|
604
|
+
`)}catch{return""}}function pE(t){try{return Ii.readFileSync(t,"utf-8").split(`
|
|
605
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function hE(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=Ue.join(t,".gitignore"),r=[...o,...pE(n)],i=0,a=[Ue.basename(t)+"/"];function l(c,u,d){if(d>e||i>=s)return;let f;try{f=Ii.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=>!(rE.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||hE(m.name,r)));for(let m=0;m<p.length;m++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=p[m],$=m===p.length-1,x=$?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",T=u+($?" ":"\u2502 "),A=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${x}${A}`),i++,g.isDirectory()&&l(Ue.join(c,g.name),T,d+1)}}return l(t,"",1),a.join(`
|
|
606
|
+
`)}var kc=new Map,Ys=new Map,ji=null,Nm=3e4,Gs={result:null,expiry:0,cwd:null};async function cn(t){try{return await t()}catch{return null}}async function gE(){if(!ji||Date.now()>ji)return!1;let t=[Ue.join(process.cwd(),"package.json"),Ue.join(process.cwd(),"README.md"),Ue.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await yt.stat(e),o=Ys.get(e);if(!o||s.mtimeMs!==o)return!1}catch{if(Ys.has(e))return!1}try{let e=Ue.join(process.cwd(),".git","HEAD"),s=await yt.stat(e),o=Ys.get(e);if(!o||s.mtimeMs!==o)return!1}catch{}return!0}async function yE(){let t=[Ue.join(process.cwd(),"package.json"),Ue.join(process.cwd(),"README.md"),Ue.join(process.cwd(),".gitignore"),Ue.join(process.cwd(),".git","HEAD"),Ue.join(process.cwd(),"CLAUDE.md"),Ue.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let s=await yt.stat(e);Ys.set(e,s.mtimeMs)}catch{Ys.delete(e)}}async function wE(t){let e="fileContext",s=kc.get(e),o=!1;if(s&&await gE()&&(o=!0),!o){let c=[],u=Ue.join(t,"package.json");if(await cn(()=>yt.access(u).then(()=>!0).catch(()=>!1)))try{let v=await yt.readFile(u,"utf-8"),N=JSON.parse(v),Q={name:N.name,version:N.version};N.scripts&&(Q.scripts=Object.keys(N.scripts).slice(0,15)),N.dependencies&&(Q.deps=Object.keys(N.dependencies).length),N.devDependencies&&(Q.devDeps=Object.keys(N.devDependencies).length),c.push(`PACKAGE: ${JSON.stringify(Q)}`)}catch{}let f=Ue.join(t,"README.md");if(await cn(()=>yt.access(f).then(()=>!0).catch(()=>!1))){let N=(await yt.readFile(f,"utf-8")).split(`
|
|
592
607
|
`).slice(0,50);c.push(`README (first 50 lines):
|
|
593
|
-
${
|
|
594
|
-
`)}`)}let m=
|
|
595
|
-
${
|
|
596
|
-
${
|
|
597
|
-
${
|
|
598
|
-
|
|
599
|
-
`),
|
|
600
|
-
${i}`),a&&
|
|
608
|
+
${N.join(`
|
|
609
|
+
`)}`)}let m=Ue.join(t,".gitignore");if(await cn(()=>yt.access(m).then(()=>!0).catch(()=>!1))){let v=await yt.readFile(m,"utf-8");c.push(`GITIGNORE:
|
|
610
|
+
${v.trim()}`)}let $=Ue.join(t,"CLAUDE.md");if(await cn(()=>yt.access($).then(()=>!0).catch(()=>!1))){let v=await yt.readFile($,"utf-8");v.trim()&&c.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
|
|
611
|
+
${v.trim()}`)}let T=Ue.join(t,".nex","CLAUDE.md");if(await cn(()=>yt.access(T).then(()=>!0).catch(()=>!1))){let v=await yt.readFile(T,"utf-8");v.trim()&&c.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
|
|
612
|
+
${v.trim()}`)}let R=await fE(t);R&&c.push(R),s=c.join(`
|
|
613
|
+
|
|
614
|
+
`),kc.set(e,s),ji=Date.now()+Nm,await yE()}let n=[s],r,i,a,l;if(Gs.result&&Date.now()<Gs.expiry&&Gs.cwd===t?{branch:r,status:i,log:a,conflicts:l}=Gs.result:([r,i,a,l]=await Promise.all([cn(async()=>{let{stdout:c}=await Li("git branch --show-current",{cwd:t,timeout:5e3});return c.trim()}),cn(async()=>{let{stdout:c}=await Li("git status --short",{cwd:t,timeout:5e3});return c.trim()}),cn(async()=>{let{stdout:c}=await Li("git log --oneline -5",{cwd:t,timeout:5e3});return c.trim()}),Mm()]),Gs={result:{branch:r,status:i,log:a,conflicts:l},expiry:Date.now()+Nm,cwd:t}),r&&n.push(`GIT BRANCH: ${r}`),i&&n.push(`GIT STATUS:
|
|
615
|
+
${i}`),a&&n.push(`RECENT COMMITS:
|
|
601
616
|
${a}`),l&&l.length>0){let c=l.map(u=>` ${u.file}`).join(`
|
|
602
|
-
`);
|
|
603
|
-
${c}`)}try{let c=
|
|
604
|
-
|
|
605
|
-
`)}async function GS(t){let e=Be.join(t,"package.json"),s="";if(await rn(()=>yt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await yt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([rn(async()=>{let{stdout:i}=await Ei("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),mm()]);if(r&&r.length>0){console.log(`${Ws.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ws.reset}`);for(let i of r)console.log(`${Ws.red} ${i.file}${Ws.reset}`);console.log(`${Ws.yellow} \u2192 Resolve conflicts before starting tasks${Ws.reset}`)}console.log()}gm.exports={gatherProjectContext:YS,printContext:GS,generateFileTree:US,_clearContextCache:()=>{pc.clear(),Ys.clear(),Ti=null,Hs={result:null,expiry:0,cwd:null}}}});var Ci=V((Z1,_m)=>{var Xt=require("fs"),Ri=require("path"),{atomicWrite:zS}=Hn();function Wo(){return Ri.join(process.cwd(),".nex","sessions")}function hc(){let t=Wo();Xt.existsSync(t)||Xt.mkdirSync(t,{recursive:!0,mode:448})}function mc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ri.join(Wo(),`${e}.json`)}function gc(t,e,s={}){hc();let n=mc(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return zS(n,JSON.stringify(o,null,2)),{path:n,name:t}}function wm(t){let e=mc(t);if(!Xt.existsSync(e))return null;try{return JSON.parse(Xt.readFileSync(e,"utf-8"))}catch{return null}}function $m(){hc();let t=Wo(),e=Xt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Xt.readFileSync(Ri.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function KS(t){let e=mc(t);return Xt.existsSync(e)?(Xt.unlinkSync(e),!0):!1}function XS(){let t=$m();return t.length===0?null:wm(t[0].name)}var is=null,_n=null,Uo=null;function VS(t,e={}){t.length!==0&&(is&&clearTimeout(is),_n=t,Uo=e||{},is=setTimeout(()=>{_n&&_n.length>0&&gc("_autosave",_n,Uo),is=null,_n=null,Uo=null},5e3))}function JS(){is&&(clearTimeout(is),is=null),_n&&_n.length>0&&(gc("_autosave",_n,Uo),_n=null,Uo=null)}function ZS(){hc();let t=Wo(),e=Xt.readdirSync(t).filter(r=>r.endsWith(".json")),s=new Date,n=new Date(s.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Ri.join(t,r);try{let a=Xt.statSync(i);new Date(a.mtime)<n&&(Xt.unlinkSync(i),o++)}catch{}}return o}_m.exports={saveSession:gc,loadSession:wm,listSessions:$m,deleteSession:KS,getLastSession:XS,autoSave:VS,flushAutoSave:JS,clearOldSessions:ZS,_getSessionsDir:Wo}});var Cm=V((Q1,Rm)=>{"use strict";var Ho=require("fs"),bm=require("path");function km(t){let e=[];return t.forEach((s,n)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:n,id:o.id||null})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:n,id:o.id||null})}))}),e}function QS(t){let e=new Set;return t.forEach(s=>{s.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&s.tool_call_id&&e.add(s.tool_call_id),s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_result"&&n.tool_use_id&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&e.add(n.tool_use_id)})}),e}function xm(t){let e=[];return t.forEach((s,n)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:n})}}),s.role==="tool"){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:o,index:n})}}),e}function Sm(t){for(let e=t.length-1;e>=0;e--){let s=t[e];if(s.role==="assistant"){if(typeof s.content=="string")return s.content.trim();if(Array.isArray(s.content)){let n=s.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(n)return n}}}return""}function Em(t,e){let s=[];for(let n=t.length-1;n>=0&&s.length<e;n--){let o=t[n];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&s.push(r)}return s}function vm(t){let e=new Map;for(let s of t){let n;try{n=JSON.stringify(s.input)}catch{n=String(s.input)}let o=`${s.name}|${n}`;e.set(o,(e.get(o)||0)+1)}return e}function Tm(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,s=[],n=km(t),o=xm(t),r=n.length,i=QS(t),a=n.filter(b=>!b.id||!i.has(b.id));t.some(b=>b.role==="user"&&typeof b.content=="string"&&b.content.startsWith("[SYSTEM WARNING]")&&(b.content.includes("edited")||b.content.includes("bash command")||b.content.includes("grep pattern")||b.content.includes("re-read")||b.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let c=n.find(b=>{let I=b.input?.command||b.input?.cmd||"";return/\bsed\s+-n\b/.test(I)});if(c){let b=(c.input?.command||c.input?.cmd||"").slice(0,80);o.some(H=>H.content.includes("BLOCKED: sed -n is forbidden")||H.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${b}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${b}`))}n.find(b=>{if(b.name!=="grep"&&b.name!=="bash"&&b.name!=="ssh_exec")return!1;let I=b.input?.command||b.input?.cmd||"",H=b.input?.pattern||"",N=`${I} ${H}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(N)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(N)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(b=>b.role==="assistant"),f=Sm(t),m=Em(t,3).some(b=>b.length>100&&!/^[^.!]{0,40}\?$/.test(b));if(d&&!m&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let b=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";s.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${b}`)}r>40?(e-=1.5,s.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,s.push(`High tool call count: ${r} (>25 threshold)`)),t.some(b=>{let I=typeof b.content=="string"?b.content:Array.isArray(b.content)?b.content.map(H=>typeof H=="string"?H:H.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(I)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let k=vm(a),M=0,D="";for(let[b,I]of k)I>M&&(M=I,D=b);if(M>=3){let[b]=D.split("|");e-=1,s.push(`Same tool call repeated ${M}\xD7 (tool: ${b})`)}let v=!1,E=t.findIndex(b=>b.role==="user"&&typeof b.content=="string"&&b.content.includes("[SYSTEM STOP]")&&b.content.includes('"valid":true'));E>=0&&n.filter(I=>I.index>E).length>0&&(v=!0),v&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let A=n.filter(b=>b.name==="ssh_exec");if(A.length>=8){let b=0,I=1;for(let H=1;H<A.length;H++)A[H].index<=A[H-1].index+2?I++:(b=Math.max(b,I),I=1);b=Math.max(b,I),b>=8&&(e-=.5,s.push(`SSH reconnect storm: ${b} consecutive SSH calls`))}d&&A.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,s.push("Surrender: model asked user to manually provide server output instead of gathering it"));let ee=new Map;for(let b of a)if(b.name==="read_file"&&b.input?.path){let I=b.input.path;ee.has(I)||ee.set(I,{count:0,ranges:[]});let H=ee.get(I);if(H.count++,b.input.line_start!=null){let N=b.input.line_start||1,L=b.input.line_end||N+350;H.ranges.push([N,L])}}function se(b,I,H){for(let[N,L]of H){let _=Math.max(b,N),J=Math.min(I,L);if(J>_){let de=J-_,fe=I-b||1;if(de/fe>=.7)return!0}}return!1}let ue=0,ae="";for(let[b,I]of ee){if(I.count<3)continue;if(I.ranges.length===I.count){let L=!1,_=[];for(let[J,de]of I.ranges){if(_.length>0&&se(J,de,_)){L=!0;break}_.push([J,de])}if(!L)continue}if(I.count-I.ranges.length<=2&&I.ranges.length>=1){let L=!1,_=[];for(let[J,de]of I.ranges){if(_.length>0&&se(J,de,_)){L=!0;break}_.push([J,de])}if(!L)continue}I.count>ue&&(ue=I.count,ae=b)}if(ue>=3){e-=1;let b=ae.split("/").slice(-2).join("/");s.push(`read_file loop: "${b}" read ${ue}\xD7 (file already in context)`)}let te=0,S="";for(let[b,I]of ee){if(I.ranges.length<4)continue;let H=[],N=!1;for(let[L,_]of I.ranges){if(H.length>0&&se(L,_,H)){N=!0;break}H.push([L,_])}!N&&I.ranges.length>te&&(te=I.ranges.length,S=b)}if(te>=4){e-=.5;let b=S.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${b}" read in ${te} sequential sections \u2014 use grep instead`)}let ve=new Map;for(let b of a)if(b.name==="grep"&&b.input?.path&&b.input?.pattern){let I=b.input.path;ve.has(I)||ve.set(I,new Set),ve.get(I).add(b.input.pattern)}let W=0,z="";for(let[b,I]of ve)b.split("/").pop().includes(".")&&I.size>W&&(W=I.size,z=b);if(W>=3){e-=.75;let b=z.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${b}" searched ${W}\xD7 with different patterns (file already in context)`)}{let b=new Set,I=new Set,H=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let L of n){if(L.name==="write_file"&&L.input?.path){let _=L.input.path.split("/").pop(),J=L.input.path.includes("/tests/");H.test(_)&&!J&&b.add(L.input.path)}if((L.name==="bash"||L.name==="ssh_exec")&&L.input?.command){let _=L.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(_)for(let J of _){let de=J.split(/\s+/),fe=de[de.length-1];for(let Je of b)(Je.endsWith(fe)||fe.endsWith(Je.split("/").pop()))&&I.add(Je)}}}let N=I.size;if(N>=1){let L=Math.min(N*.25,.5);e-=L;let _=[...I].map(J=>J.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${_} \u2014 write inline logic or use tests/ instead`)}}let me=o.filter(b=>b.content.startsWith("EXIT")).length;me>=10?(e-=1,s.push(`Bash exit-error storm: ${me} tool results started with EXIT (repeated failing commands)`)):me>=5&&(e-=.5,s.push(`Repeated bash errors: ${me} tool results with non-zero exit code`));for(let b of t){if(b.role!=="assistant")continue;let I="";if(typeof b.content=="string"?I=b.content:Array.isArray(b.content)&&(I=b.content.filter(fe=>fe&&(fe.type==="text"||typeof fe=="string")).map(fe=>typeof fe=="string"?fe:fe.text||"").join("")),I.length<=5e3)continue;let H=I.split(/(?<=\. )/).filter(fe=>fe.trim().length>0);if(H.length<6)continue;let N=new Map;for(let fe=0;fe<=H.length-3;fe++){let Je=H.slice(fe,fe+3).join("").trim();Je.length>30&&N.set(Je,(N.get(Je)||0)+1)}let L=0,_="";for(let[fe,Je]of N)Je>L&&(L=Je,_=fe);if(L<3)continue;let de=_.length*L/I.length;if(de>=.4||L>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${L}\xD7 same paragraph, ${Math.round(de*100)}% repeated)`);break}}{let b=new Set(["read_file","list_directory","search_files","glob","grep"]),I=t.some(N=>Array.isArray(N.tool_calls)?N.tool_calls.some(L=>b.has(L.function?.name)):Array.isArray(N.content)?N.content.some(L=>L.type==="tool_use"&&b.has(L.name)):!1);t.some(N=>N.role==="assistant"&&typeof N.content=="string"&&(N.content.includes("## Steps")||N.content.includes("/plan approve")))&&!I&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Ce=o.filter(b=>b.content.startsWith("BLOCKED:")&&!b.content.includes("BLOCKED: sed -n")&&!b.content.includes("SSH paused")&&!b.content.includes("SSH temporarily paused"));if(Ce.length>0){let b=Math.min(Ce.length*.5,1.5);e-=b,s.push(`${Ce.length} tool call${Ce.length===1?"":"s"} blocked (agent attempted denied actions)`)}let De=t.filter(b=>{let I=typeof b.content=="string"?b.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(I)}).length;if(De>0){let b=Math.min(De*1,2);e-=b,s.push(`Super-nuclear context wipe fired ${De}\xD7 (context collapse \u2014 task too large or read loops)`)}{let b=!1,I=!1,H=!1;for(let L of n){if(L.name!=="bash")continue;let _=(L.input?.command||L.input?.cmd||"").trim();!(/cat\s*>/.test(_)||/<</.test(_))&&/\bcat\s+\S/.test(_)&&(b=!0),/^\s*ls(\s|$)/.test(_)&&!/npm|yarn|pnpm|make|git\b/.test(_)&&(I=!0),/\bfind\s+\S/.test(_)&&!/git\b|npm\b|-exec\b/.test(_)&&(H=!0)}let N=[b,I,H].filter(Boolean).length;if(N>0){let L=Math.min(N*.25,.75);e-=L;let _=[];b&&_.push("cat (use read_file)"),I&&_.push("ls (use list_directory)"),H&&_.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${_.join(", ")}`)}}{let b=n.some(_=>(_.name==="write_file"||_.name==="Write")&&_.input?.path&&(_.input.path.endsWith("requirements.txt")||_.input.path.endsWith("Pipfile")||_.input.path.endsWith("pyproject.toml"))),I=n.some(_=>(_.name==="write_file"||_.name==="Write")&&_.input?.path&&_.input.path.endsWith("package.json")),H=n.filter(_=>(_.name==="bash"||_.name==="Bash")&&_.input?.command).map(_=>_.input.command),N=H.some(_=>/pip\s+install|python\s+-m\s+venv/.test(_)),L=H.some(_=>/npm\s+install/.test(_));b&&!N?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):I&&!L&&n.some(J=>(J.name==="write_file"||J.name==="Write")&&J.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(J.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let b=t.find(_=>_.role==="assistant"),I="";b&&(typeof b.content=="string"?I=b.content:Array.isArray(b.content)&&(I=b.content.filter(_=>_&&(_.type==="text"||typeof _=="string")).map(_=>typeof _=="string"?_:_.text||"").join("")));let H=I.slice(0,400),N=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,L=H.split(`
|
|
606
|
-
`).find(_=>{let
|
|
607
|
-
`)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${_}"`)}}if(d&&r>0){let
|
|
608
|
-
`).filter(_=>_.trim()).length<5&&/^\s*\[/.test(
|
|
609
|
-
${
|
|
610
|
-
${i}\u26A0${r} ${
|
|
611
|
-
${
|
|
617
|
+
`);n.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
618
|
+
${c}`)}try{let c=eE();c&&n.push(c)}catch{}return n.join(`
|
|
619
|
+
|
|
620
|
+
`)}async function $E(t){let e=Ue.join(t,"package.json"),s="";if(await cn(()=>yt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await yt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[n,r]=await Promise.all([cn(async()=>{let{stdout:i}=await Li("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Mm()]);if(r&&r.length>0){console.log(`${Hs.red} \u26A0 ${r.length} unresolved merge conflict(s):${Hs.reset}`);for(let i of r)console.log(`${Hs.red} ${i.file}${Hs.reset}`);console.log(`${Hs.yellow} \u2192 Resolve conflicts before starting tasks${Hs.reset}`)}console.log()}Pm.exports={gatherProjectContext:wE,printContext:$E,generateFileTree:mE,_clearContextCache:()=>{kc.clear(),Ys.clear(),ji=null,Gs={result:null,expiry:0,cwd:null}}}});var qi=V((CC,Dm)=>{var Xt=require("fs"),Di=require("path"),{atomicWrite:bE}=Hn();function Xo(){return Di.join(process.cwd(),".nex","sessions")}function xc(){let t=Xo();Xt.existsSync(t)||Xt.mkdirSync(t,{recursive:!0,mode:448})}function Sc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Di.join(Xo(),`${e}.json`)}function Ec(t,e,s={}){xc();let o=Sc(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 Im(t){let e=Sc(t);if(!Xt.existsSync(e))return null;try{return JSON.parse(Xt.readFileSync(e,"utf-8"))}catch{return null}}function jm(){xc();let t=Xo(),e=Xt.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(Xt.readFileSync(Di.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=Sc(t);return Xt.existsSync(e)?(Xt.unlinkSync(e),!0):!1}function kE(){let t=jm();return t.length===0?null:Im(t[0].name)}var ls=null,_n=null,Ko=null;function xE(t,e={}){t.length!==0&&(ls&&clearTimeout(ls),_n=t,Ko=e||{},ls=setTimeout(()=>{_n&&_n.length>0&&Ec("_autosave",_n,Ko),ls=null,_n=null,Ko=null},5e3))}function SE(){ls&&(clearTimeout(ls),ls=null),_n&&_n.length>0&&(Ec("_autosave",_n,Ko),_n=null,Ko=null)}function EE(){xc();let t=Xo(),e=Xt.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=Di.join(t,r);try{let a=Xt.statSync(i);new Date(a.mtime)<o&&(Xt.unlinkSync(i),n++)}catch{}}return n}Dm.exports={saveSession:Ec,loadSession:Im,listSessions:jm,deleteSession:_E,getLastSession:kE,autoSave:xE,flushAutoSave:SE,clearOldSessions:EE,_getSessionsDir:Xo}});var zm=V((AC,Ym)=>{"use strict";var Vo=require("fs"),qm=require("path");function Fm(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 vE(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 Bm(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 Um(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 Wm(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 Hm(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 Gm(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=Fm(t),n=Bm(t),r=o.length,i=vE(t),a=o.filter(k=>!k.id||!i.has(k.id));t.some(k=>k.role==="user"&&typeof k.content=="string"&&k.content.startsWith("[SYSTEM WARNING]")&&(k.content.includes("edited")||k.content.includes("bash command")||k.content.includes("grep pattern")||k.content.includes("re-read")||k.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(k=>{let D=k.input?.command||k.input?.cmd||"";return/\bsed\s+-n\b/.test(D)});if(c){let k=(c.input?.command||c.input?.cmd||"").slice(0,80);n.some(H=>H.content.includes("BLOCKED: sed -n is forbidden")||H.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${k}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${k}`))}o.find(k=>{if(k.name!=="grep"&&k.name!=="bash"&&k.name!=="ssh_exec")return!1;let D=k.input?.command||k.input?.cmd||"",H=k.input?.pattern||"",M=`${D} ${H}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(M)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(M)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(k=>k.role==="assistant"),f=Um(t),m=Wm(t,3).some(k=>k.length>100&&!/^[^.!]{0,40}\?$/.test(k));if(d&&!m&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let k=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: ${k}`)}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(k=>{let D=typeof k.content=="string"?k.content:Array.isArray(k.content)?k.content.map(H=>typeof H=="string"?H:H.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(D)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let x=Hm(a),T=0,A="";for(let[k,D]of x)D>T&&(T=D,A=k);if(T>=3){let[k]=A.split("|");e-=1,s.push(`Same tool call repeated ${T}\xD7 (tool: ${k})`)}let R=!1,v=t.findIndex(k=>k.role==="user"&&typeof k.content=="string"&&k.content.includes("[SYSTEM STOP]")&&k.content.includes('"valid":true'));v>=0&&o.filter(D=>D.index>v).length>0&&(R=!0),R&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let N=o.filter(k=>k.name==="ssh_exec");if(N.length>=8){let k=0,D=1;for(let H=1;H<N.length;H++)N[H].index<=N[H-1].index+2?D++:(k=Math.max(k,D),D=1);k=Math.max(k,D),k>=8&&(e-=.5,s.push(`SSH reconnect storm: ${k} consecutive SSH calls`))}d&&N.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,s.push("Surrender: model asked user to manually provide server output instead of gathering it"));let Q=new Map;for(let k of a)if(k.name==="read_file"&&k.input?.path){let D=k.input.path;Q.has(D)||Q.set(D,{count:0,ranges:[]});let H=Q.get(D);if(H.count++,k.input.line_start!=null){let M=k.input.line_start||1,I=k.input.line_end||M+350;H.ranges.push([M,I])}}function se(k,D,H){for(let[M,I]of H){let _=Math.max(k,M),Z=Math.min(D,I);if(Z>_){let de=Z-_,fe=D-k||1;if(de/fe>=.7)return!0}}return!1}let re=0,le="";for(let[k,D]of Q){if(D.count<3)continue;if(D.ranges.length===D.count){let I=!1,_=[];for(let[Z,de]of D.ranges){if(_.length>0&&se(Z,de,_)){I=!0;break}_.push([Z,de])}if(!I)continue}if(D.count-D.ranges.length<=2&&D.ranges.length>=1){let I=!1,_=[];for(let[Z,de]of D.ranges){if(_.length>0&&se(Z,de,_)){I=!0;break}_.push([Z,de])}if(!I)continue}D.count>re&&(re=D.count,le=k)}if(re>=3){e-=1;let k=le.split("/").slice(-2).join("/");s.push(`read_file loop: "${k}" read ${re}\xD7 (file already in context)`)}let ne=0,S="";for(let[k,D]of Q){if(D.ranges.length<4)continue;let H=[],M=!1;for(let[I,_]of D.ranges){if(H.length>0&&se(I,_,H)){M=!0;break}H.push([I,_])}!M&&D.ranges.length>ne&&(ne=D.ranges.length,S=k)}if(ne>=4){e-=.5;let k=S.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${k}" read in ${ne} sequential sections \u2014 use grep instead`)}let ve=new Map;for(let k of a)if(k.name==="grep"&&k.input?.path&&k.input?.pattern){let D=k.input.path;ve.has(D)||ve.set(D,new Set),ve.get(D).add(k.input.pattern)}let W=0,z="";for(let[k,D]of ve)k.split("/").pop().includes(".")&&D.size>W&&(W=D.size,z=k);if(W>=3){e-=.75;let k=z.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${k}" searched ${W}\xD7 with different patterns (file already in context)`)}{let k=new Set,D=new Set,H=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let I of o){if(I.name==="write_file"&&I.input?.path){let _=I.input.path.split("/").pop(),Z=I.input.path.includes("/tests/");H.test(_)&&!Z&&k.add(I.input.path)}if((I.name==="bash"||I.name==="ssh_exec")&&I.input?.command){let _=I.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(_)for(let Z of _){let de=Z.split(/\s+/),fe=de[de.length-1];for(let Ze of k)(Ze.endsWith(fe)||fe.endsWith(Ze.split("/").pop()))&&D.add(Ze)}}}let M=D.size;if(M>=1){let I=Math.min(M*.25,.5);e-=I;let _=[...D].map(Z=>Z.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${_} \u2014 write inline logic or use tests/ instead`)}}let ge=n.filter(k=>k.content.startsWith("EXIT")).length;ge>=10?(e-=1,s.push(`Bash exit-error storm: ${ge} tool results started with EXIT (repeated failing commands)`)):ge>=5&&(e-=.5,s.push(`Repeated bash errors: ${ge} tool results with non-zero exit code`));for(let k of t){if(k.role!=="assistant")continue;let D="";if(typeof k.content=="string"?D=k.content:Array.isArray(k.content)&&(D=k.content.filter(fe=>fe&&(fe.type==="text"||typeof fe=="string")).map(fe=>typeof fe=="string"?fe:fe.text||"").join("")),D.length<=5e3)continue;let H=D.split(/(?<=\. )/).filter(fe=>fe.trim().length>0);if(H.length<6)continue;let M=new Map;for(let fe=0;fe<=H.length-3;fe++){let Ze=H.slice(fe,fe+3).join("").trim();Ze.length>30&&M.set(Ze,(M.get(Ze)||0)+1)}let I=0,_="";for(let[fe,Ze]of M)Ze>I&&(I=Ze,_=fe);if(I<3)continue;let de=_.length*I/D.length;if(de>=.4||I>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${I}\xD7 same paragraph, ${Math.round(de*100)}% repeated)`);break}}{let k=new Set(["read_file","list_directory","search_files","glob","grep"]),D=t.some(M=>Array.isArray(M.tool_calls)?M.tool_calls.some(I=>k.has(I.function?.name)):Array.isArray(M.content)?M.content.some(I=>I.type==="tool_use"&&k.has(I.name)):!1);t.some(M=>M.role==="assistant"&&typeof M.content=="string"&&(M.content.includes("## Steps")||M.content.includes("/plan approve")))&&!D&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Ae=n.filter(k=>k.content.startsWith("BLOCKED:")&&!k.content.includes("BLOCKED: sed -n")&&!k.content.includes("SSH paused")&&!k.content.includes("SSH temporarily paused"));if(Ae.length>0){let k=Math.min(Ae.length*.5,1.5);e-=k,s.push(`${Ae.length} tool call${Ae.length===1?"":"s"} blocked (agent attempted denied actions)`)}let qe=t.filter(k=>{let D=typeof k.content=="string"?k.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(D)}).length;if(qe>0){let k=Math.min(qe*1,2);e-=k,s.push(`Super-nuclear context wipe fired ${qe}\xD7 (context collapse \u2014 task too large or read loops)`)}{let k=!1,D=!1,H=!1;for(let I of o){if(I.name!=="bash")continue;let _=(I.input?.command||I.input?.cmd||"").trim();!(/cat\s*>/.test(_)||/<</.test(_))&&/\bcat\s+\S/.test(_)&&(k=!0),/^\s*ls(\s|$)/.test(_)&&!/npm|yarn|pnpm|make|git\b/.test(_)&&(D=!0),/\bfind\s+\S/.test(_)&&!/git\b|npm\b|-exec\b/.test(_)&&(H=!0)}let M=[k,D,H].filter(Boolean).length;if(M>0){let I=Math.min(M*.25,.75);e-=I;let _=[];k&&_.push("cat (use read_file)"),D&&_.push("ls (use list_directory)"),H&&_.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${_.join(", ")}`)}}{let k=o.some(_=>(_.name==="write_file"||_.name==="Write")&&_.input?.path&&(_.input.path.endsWith("requirements.txt")||_.input.path.endsWith("Pipfile")||_.input.path.endsWith("pyproject.toml"))),D=o.some(_=>(_.name==="write_file"||_.name==="Write")&&_.input?.path&&_.input.path.endsWith("package.json")),H=o.filter(_=>(_.name==="bash"||_.name==="Bash")&&_.input?.command).map(_=>_.input.command),M=H.some(_=>/pip\s+install|python\s+-m\s+venv/.test(_)),I=H.some(_=>/npm\s+install/.test(_));k&&!M?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):D&&!I&&o.some(Z=>(Z.name==="write_file"||Z.name==="Write")&&Z.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(Z.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let k=t.find(_=>_.role==="assistant"),D="";k&&(typeof k.content=="string"?D=k.content:Array.isArray(k.content)&&(D=k.content.filter(_=>_&&(_.type==="text"||typeof _=="string")).map(_=>typeof _=="string"?_:_.text||"").join("")));let H=D.slice(0,400),M=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,I=H.split(`
|
|
621
|
+
`).find(_=>{let Z=_.trim();return Z.length>0&&Z.length<=30&&/^\d/.test(Z)&&/=/.test(Z)&&!/[a-zA-Z]/.test(Z)});if(M.test(H)||I){e-=1.5;let _=(I||H.split(`
|
|
622
|
+
`)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${_}"`)}}if(d&&r>0){let k=t.findIndex(H=>H.role==="assistant"),D=t.findIndex(H=>!!(Array.isArray(H.tool_calls)&&H.tool_calls.length>0||Array.isArray(H.content)&&H.content.some(M=>M&&M.type==="tool_use")));if(k!==-1&&D!==-1&&k<D){let H=t[k],M="";typeof H.content=="string"?M=H.content:Array.isArray(H.content)&&(M=H.content.filter(Z=>Z&&(Z.type==="text"||typeof Z=="string")).map(Z=>typeof Z=="string"?Z:Z.text||"").join(""));let I=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(M),_=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(M);(I||_)&&(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 k=f;if(k.length>100){let H=(k.match(/^```/gm)||[]).length%2!==0,M=/"\s*:\s*$/.test(k.trimEnd()),I=/[,\[{]\s*$/.test(k.trimEnd());(H||M||I)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let k=[];t.forEach((H,M)=>{let I=[];Array.isArray(H.tool_calls)&&H.tool_calls.forEach(_=>{if((_.function?.name||_.name||"")==="read_file"){let de={};try{de=typeof _.function?.arguments=="string"?JSON.parse(_.function.arguments):_.function?.arguments||{}}catch{}(de.path||"").endsWith(".json")&&I.push({id:_.id,path:de.path})}}),Array.isArray(H.content)&&H.content.forEach(_=>{_&&_.type==="tool_use"&&_.name==="read_file"&&(_.input?.path||"").endsWith(".json")&&I.push({id:_.id,path:_.input.path})}),I.forEach(_=>k.push({..._,msgIdx:M}))});let D=0;for(let H of k){let M=null;for(let _ of t){if(_.role==="tool"&&_.tool_call_id===H.id&&typeof _.content=="string"){M=_.content;break}if(_.role==="user"&&Array.isArray(_.content)){let Z=_.content.find(de=>de&&de.type==="tool_result"&&de.tool_use_id===H.id);if(Z){M=typeof Z.content=="string"?Z.content:"";break}}}if(!M)continue;M.split(`
|
|
623
|
+
`).filter(_=>_.trim()).length<5&&/^\s*\[/.test(M)&&!/\]\s*$/.test(M.trimEnd())&&D++}D>=1&&(e-=.75,s.push(`Shallow JSON read: ${D} .json file${D>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let k=n.filter(D=>/argument errors?/i.test(D.content)||/missing required (argument|parameter)/i.test(D.content)||/invalid argument/i.test(D.content));k.length>=3?(e-=.75,s.push(`Repeated tool argument errors: ${k.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):k.length>=2&&(e-=.25,s.push(`Tool argument errors: ${k.length} tool calls returned argument errors`))}{let k=!1,D=0,H=0;for(let M of a){if((M.name==="bash"||M.name==="Bash")&&M.input?.command&&/git\s+commit\b/.test(M.input.command)){k&&(H=Math.max(H,D)),k=!0,D=0;continue}k&&(M.name==="bash"||M.name==="Bash")&&M.input?.command&&/git\s+(status|diff|log|show)\b/.test(M.input.command)&&D++}H=Math.max(H,D),H>=3&&(e-=.75,s.push(`Post-commit verification waste: ${H} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let ke=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",_e=s.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${s.length} issue${s.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:ke,issues:s,summary:_e}}function TE(t){try{let{loadSession:e}=qi(),s=e(t);return s?Gm(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})`),`
|
|
624
|
+
${n}${f}${r}`}let l="";for(let u of a.slice(0,4))l+=`
|
|
625
|
+
${i}\u26A0${r} ${n}${u}${r}`;let c=a.length-4;return c>0&&(l+=`
|
|
626
|
+
${n}(+${c} more)${r}`),l}function CE(t,e={}){try{let s=qm.join(process.cwd(),".nex");Vo.existsSync(s)||Vo.mkdirSync(s,{recursive:!0});let o=qm.join(s,"benchmark-history.json"),n=[];if(Vo.existsSync(o))try{n=JSON.parse(Vo.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)),Vo.writeFileSync(o,JSON.stringify(n,null,2))}catch{}}Ym.exports={scoreMessages:Gm,scoreSession:TE,formatScore:RE,appendScoreHistory:CE,_extractToolCalls:Fm,_extractToolResults:Bm,_getLastAssistantText:Um,_getLastNAssistantTexts:Wm,_countDuplicateToolCalls:Hm}});var Qo=V((OC,Zm)=>{"use strict";var AE=require("os"),vc=require("path"),Mn=require("fs"),Jo=vc.join(AE.homedir(),".nex-code","model-routing.json"),Fi={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}},Km=["agentic","frontend","sysadmin","data","coding"];function OE(t){if(!t||t.length<8)return null;for(let e of Km){let s=Fi[e];if(!s.pattern||s.pattern.test(t))return s}return Fi.coding}function Zo(){try{if(Mn.existsSync(Jo))return JSON.parse(Mn.readFileSync(Jo,"utf-8"))}catch{}return{}}function Xm(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=Fi[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Zo()[t]||null}var Vm={explore:10,plan:10,implement:35,verify:8},Tc={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Jm(){let t=Zo();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=lt();if(e()==="ollama")return Tc}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Tc:null}function NE(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let s=Jm();return s?.[t]?s[t]:e?Xm(e):null}function ME(t){return Zo().phaseBudgets?.[t]||Vm[t]||20}function PE(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:Jm()!==null}function LE(t){let e=vc.dirname(Jo);Mn.existsSync(e)||Mn.mkdirSync(e,{recursive:!0});let s=Zo(),o={...s,...t};!t.phases&&s.phases&&(o.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(o.phaseBudgets=s.phaseBudgets),Mn.writeFileSync(Jo,JSON.stringify(o,null,2));try{let n=vc.join(e,".env"),r="";Mn.existsSync(n)&&(r=Mn.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)),Mn.writeFileSync(n,i.filter(l=>l.trim()!=="").join(`
|
|
612
627
|
`)+`
|
|
613
|
-
`)}catch{}}
|
|
628
|
+
`)}catch{}}Zm.exports={CATEGORIES:Fi,DETECTION_ORDER:Km,detectCategory:OE,getModelForCategory:Xm,getModelForPhase:NE,getPhaseBudget:ME,isPhaseRoutingEnabled:PE,DEFAULT_PHASE_BUDGETS:Vm,BUILTIN_PHASE_DEFAULTS:Tc,saveRoutingConfig:LE,loadRoutingConfig:Zo,ROUTING_CONFIG_PATH:Jo}});var ng=V((NC,tg)=>{"use strict";var cs=require("fs"),er=require("path"),IE=require("os"),{detectCategory:jE}=Qo(),zs=er.join(IE.homedir(),".nex-code","examples"),Rc=er.join(__dirname,"..","examples");function Qm(t){try{let s=cs.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(`
|
|
614
629
|
A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],l=0;for(let u of i.split(`
|
|
615
630
|
`))if(u.startsWith(" ")){for(;l>0;)a.push(""),l--;a.push(u.slice(2))}else if(u.trim()==="")a.length>0&&l++;else break;if(a.length===0)return null;let c=a.join(`
|
|
616
|
-
`).trim();return{user:
|
|
631
|
+
`).trim();return{user:n,assistant:c}}catch{return null}}function eg(t){let e=`${t}.md`,s=er.join(zs,e);if(cs.existsSync(s)){let n=Qm(s);if(n)return n}let o=er.join(Rc,e);return cs.existsSync(o)?Qm(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:eg(e.id)}function qE(){let t=new Set;for(let e of[zs,Rc])try{for(let s of cs.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function FE(t,e){cs.existsSync(zs)||cs.mkdirSync(zs,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
|
|
617
632
|
|
|
618
633
|
user: ${e.user}
|
|
619
634
|
|
|
620
635
|
A: |
|
|
621
636
|
${e.assistant.split(`
|
|
622
|
-
`).map(
|
|
637
|
+
`).map(o=>` ${o}`).join(`
|
|
623
638
|
`)}
|
|
624
|
-
`;
|
|
639
|
+
`;cs.writeFileSync(er.join(zs,`${t}.md`),s,"utf-8")}tg.exports={getFewShotForInput:DE,loadExampleForCategory:eg,listAvailableExamples:qE,savePrivateExample:FE,PRIVATE_EXAMPLES_DIR:zs,BUNDLED_EXAMPLES_DIR:Rc}});var lg=V((PC,ag)=>{var Rt=require("fs"),Ks=require("path"),{C:MC}=nt(),{atomicWrite:BE,withFileLockSync:UE}=Hn(),Bi={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"},Xs={...Bi};function sg(){let t=Ks.join(process.cwd(),".nex","config.json");if(Rt.existsSync(t))try{let e=JSON.parse(Rt.readFileSync(t,"utf-8"));e.permissions&&(Xs={...Bi,...e.permissions})}catch{}}function WE(){let t=Ks.join(process.cwd(),".nex"),e=Ks.join(t,"config.json");Rt.existsSync(t)||Rt.mkdirSync(t,{recursive:!0}),UE(e,()=>{let s={};if(Rt.existsSync(e))try{s=JSON.parse(Rt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Xs,BE(e,JSON.stringify(s,null,2))})}function og(t){return Xs[t]||"ask"}function HE(t,e){return["allow","ask","deny"].includes(e)?(Xs[t]=e,!0):!1}function GE(t){return og(t)}function YE(){return Object.entries(Xs).map(([t,e])=>({tool:t,mode:e}))}function zE(){Xs={...Bi}}var tr={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 rg(){let t=Ks.join(process.cwd(),".nex","config.json");try{return Rt.existsSync(t)&&JSON.parse(Rt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function KE(t){let e=Ks.join(process.cwd(),".nex"),s=Ks.join(e,"config.json");Rt.existsSync(e)||Rt.mkdirSync(e,{recursive:!0});let o={};try{Rt.existsSync(s)&&(o=JSON.parse(Rt.readFileSync(s,"utf-8")))}catch{o={}}o.teamPermissions=t,Rt.writeFileSync(s,JSON.stringify(o,null,2),"utf-8")}function ig(){let t=rg();if(!t)return tr.admin;let e=t.role||"admin",s=tr[e]||tr.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function XE(t){let e=ig();return e.blockedTools&&e.blockedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is blocked by permission preset "${e.description||"custom"}"`}:e.allowedTools&&!e.allowedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is not in the allowed list for this permission level`}:{allowed:!0}}function VE(){return Object.entries(tr).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}sg();ag.exports={getPermission:og,setPermission:HE,checkPermission:GE,listPermissions:YE,loadPermissions:sg,savePermissions:WE,resetPermissions:zE,DEFAULT_PERMISSIONS:Bi,PERMISSION_PRESETS:tr,loadPresetConfig:rg,savePresetConfig:KE,getEffectivePreset:ig,isToolAllowed:XE,listPresets:VE}});var Hi=V((IC,pg)=>{var ds=require("fs"),Ui=require("path"),LC=require("readline"),{C:Re}=nt(),Ee=null,Ac=!1,Oc=null,cg=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Wi(){return Ui.join(process.cwd(),".nex","plans")}function ug(){let t=Wi();ds.existsSync(t)||ds.mkdirSync(t,{recursive:!0})}function JE(t,e=[]){return Ee={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Ee}function ZE(){return Ee}function QE(t){Ac=t}function ev(){return Ac}function tv(){return!Ee||Ee.status!=="draft"?!1:(Ee.status="approved",Ee.updatedAt=new Date().toISOString(),!0)}function nv(){return!Ee||Ee.status!=="approved"?!1:(Ee.status="executing",!0)}function Cc(t,e){return!Ee||t<0||t>=Ee.steps.length?!1:(Ee.steps[t].status=e,Ee.updatedAt=new Date().toISOString(),Ee.steps.every(s=>s.status==="done"||s.status==="skipped")&&(Ee.status="completed"),!0)}function sv(t){if(!t)return`${Re.dim}No active plan${Re.reset}`;let e={draft:`${Re.yellow}DRAFT${Re.reset}`,approved:`${Re.green}APPROVED${Re.reset}`,executing:`${Re.blue}EXECUTING${Re.reset}`,completed:`${Re.green}COMPLETED${Re.reset}`},s=[];s.push(`
|
|
625
640
|
${Re.bold}${Re.cyan}Plan: ${t.task}${Re.reset}`),s.push(`${Re.dim}Status: ${e[t.status]||t.status}${Re.reset}
|
|
626
|
-
`);for(let
|
|
627
|
-
`)}function
|
|
641
|
+
`);for(let o=0;o<t.steps.length;o++){let n=t.steps[o],r;switch(n.status){case"done":r=`${Re.green}\u2713${Re.reset}`;break;case"in_progress":r=`${Re.blue}\u2192${Re.reset}`;break;case"skipped":r=`${Re.dim}\u25CB${Re.reset}`;break;default:r=`${Re.dim} ${Re.reset}`}s.push(` ${r} ${Re.bold}Step ${o+1}:${Re.reset} ${n.description}`),n.files.length>0&&s.push(` ${Re.dim}Files: ${n.files.join(", ")}${Re.reset}`)}return s.push(""),s.join(`
|
|
642
|
+
`)}function ov(t){if(t||(t=Ee),!t)return null;ug();let e=Ui.join(Wi(),`${t.name}.json`);return ds.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function rv(t){let e=Ui.join(Wi(),`${t}.json`);if(!ds.existsSync(e))return null;try{let s=JSON.parse(ds.readFileSync(e,"utf-8"));return Ee=s,s}catch{return null}}function iv(){ug();let t=Wi(),e=ds.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(ds.readFileSync(Ui.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 av(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 lv(t){Oc=t}function cv(){return Oc}function uv(){Ee=null,Ac=!1,Oc=null,hv()}function dv(){return`
|
|
628
643
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
629
644
|
|
|
630
645
|
# Allowed Tools (read-only)
|
|
631
|
-
You may ONLY use these tools: ${[...
|
|
646
|
+
You may ONLY use these tools: ${[...cg].join(", ")}
|
|
632
647
|
Any other tool call will be blocked and returned with an error.
|
|
633
648
|
|
|
634
649
|
# MANDATORY: Read Before You Plan
|
|
@@ -680,26 +695,26 @@ Bullet list of potential issues and mitigations.
|
|
|
680
695
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
681
696
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
682
697
|
- Do NOT make any file changes \u2014 your role is analysis and planning only.
|
|
683
|
-
- Do NOT call ask_user. If anything is ambiguous, add an "## Assumptions" section to the plan and state your assumption. The user approves or rejects the whole plan \u2014 that is the only gate.`}var
|
|
684
|
-
`),s=[],
|
|
685
|
-
`)}function Ct(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function
|
|
686
|
-
`+s,a=r+1,i=a,
|
|
687
|
-
`+s,a=i,
|
|
688
|
-
`)}function
|
|
689
|
-
`))!==-1;){let
|
|
690
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=
|
|
691
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let
|
|
692
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
693
|
-
`);return}if(e.startsWith("###### ")){this._safeWrite(`${
|
|
694
|
-
`);return}if(e.startsWith("##### ")){this._safeWrite(`${
|
|
695
|
-
`);return}if(e.startsWith("#### ")){this._safeWrite(`${
|
|
696
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${
|
|
697
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${
|
|
698
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${
|
|
699
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let
|
|
700
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let
|
|
701
|
-
`);return}}let
|
|
702
|
-
`)}};
|
|
698
|
+
- 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 us=0;function fv(){!Ee||Ee.status!=="executing"||(us>0&&Cc(us-1,"done"),us<Ee.steps.length&&(Cc(us,"in_progress"),us++))}function pv(){if(!Ee||Ee.status!=="executing"||Ee.steps.length===0)return null;let t=Math.min(us,Ee.steps.length),e=Ee.steps.length,s=Math.max(0,t-1),o=Ee.steps[s]?.description||"";return{current:t,total:e,description:o}}function hv(){us=0}var dg=["interactive","semi-auto","autonomous"],fg="interactive";function mv(t){return dg.includes(t)?(fg=t,!0):!1}function gv(){return fg}pg.exports={createPlan:JE,getActivePlan:ZE,setPlanMode:QE,isPlanMode:ev,approvePlan:tv,startExecution:nv,updateStep:Cc,formatPlan:sv,savePlan:ov,loadPlan:rv,listPlans:iv,clearPlan:uv,getPlanModePrompt:dv,setPlanContent:lv,getPlanContent:cv,extractStepsFromText:av,advancePlanStep:fv,getPlanStepInfo:pv,PLAN_MODE_ALLOWED_TOOLS:cg,setAutonomyLevel:mv,getAutonomyLevel:gv,AUTONOMY_LEVELS:dg}});var Sg=V((jC,xg)=>{var{C:E}=nt();function hg(){return Math.max(10,(process.stdout.columns||80)-2)}function yv(t){if(!t)return"";let e=t.split(`
|
|
699
|
+
`),s=[],o=!1,n="";for(let r of e){let i=hg();if(r.trim().startsWith("```")){if(o)s.push(`${E.dim}${"\u2500".repeat(40)}${E.reset}`),o=!1,n="";else{o=!0,n=r.trim().substring(3).trim();let a=n?` ${n} `:"";s.push(`${E.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${E.reset}`)}continue}if(o){s.push(` ${Mc(r,n)}`);continue}if(r.startsWith("###### ")){s.push(`${E.bold}${E.cyan} ${Ct(r.substring(7))}${E.reset}`);continue}if(r.startsWith("##### ")){s.push(`${E.bold}${E.cyan} ${Ct(r.substring(6))}${E.reset}`);continue}if(r.startsWith("#### ")){s.push(`${E.bold}${E.cyan} ${Ct(r.substring(5))}${E.reset}`);continue}if(r.startsWith("### ")){s.push(`${E.bold}${E.cyan} ${Ct(r.substring(4))}${E.reset}`);continue}if(r.startsWith("## ")){s.push(`${E.bold}${E.cyan} ${Ct(r.substring(3))}${E.reset}`);continue}if(r.startsWith("# ")){s.push(`${E.bold}${E.cyan}${Ct(r.substring(2))}${E.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${E.cyan}\u2022${E.reset} ${fs(l)}`;s.push(ps(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}${E.cyan}${c}.${E.reset} ${fs(u)}`,f=l+" ".repeat(c.length+2);s.push(ps(d,i,f));continue}}s.push(ps(fs(r),i))}return s.join(`
|
|
700
|
+
`)}function Ct(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function fs(t){return t?t.replace(/`([^`]+)`/g,`${E.cyan}$1${E.reset}`).replace(/\*\*([^*]+)\*\*/g,`${E.bold}$1${E.reset}`).replace(/\*([^*]+)\*/g,`${E.dim}$1${E.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${E.cyan}$1${E.reset} ${E.dim}($2)${E.reset}`):""}function Mc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?mg(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?gg(t):e==="json"||e==="jsonc"?yg(t):e==="python"||e==="py"?wg(t):e==="go"||e==="golang"?$g(t):e==="rust"||e==="rs"?bg(t):e==="css"||e==="scss"||e==="less"?_g(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?kg(t):t:""}function mg(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,`${E.yellow}$1${E.reset}`),r=r.replace(e,`${E.magenta}$1${E.reset}`),r=r.replace(s,`${E.green}$&${E.reset}`),r=r.replace(o,`${E.dim}$1${E.reset}`),r}function gg(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(#.*$)/,r=t;return r=r.replace(s,`${E.cyan}$1${E.reset}`),r=r.replace(e,`$1${E.green}$2${E.reset}`),r=r.replace(o,`${E.yellow}$&${E.reset}`),r=r.replace(n,`${E.dim}$1${E.reset}`),r}function yg(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,`${E.cyan}$1${E.reset}:`),r=r.replace(s,`: ${E.green}$1${E.reset}`),r=r.replace(o,`: ${E.yellow}$1${E.reset}`),r=r.replace(n,`: ${E.magenta}$1${E.reset}`),r}function wg(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,`${E.yellow}$1${E.reset}`),i=i.replace(e,`${E.magenta}$1${E.reset}`),i=i.replace(r,`${E.cyan}$1${E.reset}`),i=i.replace(s,`${E.green}$&${E.reset}`),i=i.replace(o,`${E.dim}$1${E.reset}`),i}function $g(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,`${E.yellow}$1${E.reset}`),i=i.replace(s,`${E.cyan}$1${E.reset}`),i=i.replace(e,`${E.magenta}$1${E.reset}`),i=i.replace(o,`${E.green}$&${E.reset}`),i=i.replace(n,`${E.dim}$1${E.reset}`),i}function bg(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,`${E.yellow}$1${E.reset}`),a=a.replace(s,`${E.cyan}$1${E.reset}`),a=a.replace(e,`${E.magenta}$1${E.reset}`),a=a.replace(i,`${E.yellow}$1${E.reset}`),a=a.replace(o,`${E.green}$&${E.reset}`),a=a.replace(n,`${E.dim}$1${E.reset}`),a}function _g(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,`${E.yellow}$1${E.reset}`),a=a.replace(n,`${E.yellow}$1${E.reset}`),a=a.replace(e,`$1${E.cyan}$2${E.reset}:`),a=a.replace(o,`$1${E.magenta}$&${E.reset}`),a=a.replace(r,`${E.dim}$1${E.reset}`),a}function kg(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,`${E.dim}$1${E.reset}`),i=i.replace(o,`${E.green}$&${E.reset}`),i=i.replace(e,`<${E.magenta}$1${E.reset}`),i=i.replace(s,` ${E.cyan}$1${E.reset}=`),i=i.replace(r,`${E.yellow}$1${E.reset}`),i}function ps(t,e,s=""){if(!e||e<10)return t;let o="",n=0,r=-1,i=0,a=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let 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)+`
|
|
701
|
+
`+s,a=r+1,i=a,n=s.length,r=-1;continue}n>e&&r===-1&&(o+=t.slice(a,i)+`
|
|
702
|
+
`+s,a=i,n=s.length+1),i++}return o+=t.slice(a),o}function wv(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)=>` ${E.bold}${i.padEnd(s[a])}${E.reset} `).join("\u2502"),r=[];r.push(`${E.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${E.reset}`),r.push(`${E.dim}\u2502${E.reset}${n}${E.dim}\u2502${E.reset}`),r.push(`${E.dim}\u251C${o}\u2524${E.reset}`);for(let i of e){let a=t.map((l,c)=>` ${(i[c]||"").padEnd(s[c])} `).join(`${E.dim}\u2502${E.reset}`);r.push(`${E.dim}\u2502${E.reset}${a}${E.dim}\u2502${E.reset}`)}return r.push(`${E.dim}\u2514${o.replace(/┼/g,"\u2534")}\u2518${E.reset}`),r.join(`
|
|
703
|
+
`)}function $v(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?E.green:n>50?E.yellow:E.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${E.dim}${"\u2591".repeat(i)}${E.reset} ${n}% (${e}/${s})`}var Nc=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?`${Ht().T.cyan}\u25CF${Ht().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(`
|
|
704
|
+
`))!==-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(`${E.dim}${"\u2500".repeat(40)}${E.reset}
|
|
705
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=hg();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${E.dim}${"\u2500".repeat(40)}${E.reset}
|
|
706
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let n=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${E.dim}${"\u2500".repeat(3)}${n}${"\u2500".repeat(Math.max(0,37-n.length))}${E.reset}
|
|
707
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Mc(e,this.codeBlockLang)}
|
|
708
|
+
`);return}if(e.startsWith("###### ")){this._safeWrite(`${E.bold}${E.cyan} ${Ct(e.substring(7))}${E.reset}
|
|
709
|
+
`);return}if(e.startsWith("##### ")){this._safeWrite(`${E.bold}${E.cyan} ${Ct(e.substring(6))}${E.reset}
|
|
710
|
+
`);return}if(e.startsWith("#### ")){this._safeWrite(`${E.bold}${E.cyan} ${Ct(e.substring(5))}${E.reset}
|
|
711
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${E.bold}${E.cyan} ${Ct(e.substring(4))}${E.reset}
|
|
712
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${E.bold}${E.cyan} ${Ct(e.substring(3))}${E.reset}
|
|
713
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${E.bold}${E.cyan}${Ct(e.substring(2))}${E.reset}
|
|
714
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let n=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${n}${E.cyan}\u2022${E.reset} ${fs(r)}`,a=ps(i,s,n+" ");this._safeWrite(`${a}
|
|
715
|
+
`);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}${E.cyan}${i}.${E.reset} ${fs(a)}`,c=r+" ".repeat(i.length+2),u=ps(l,s,c);this._safeWrite(`${u}
|
|
716
|
+
`);return}}let o=ps(fs(e),s);this._safeWrite(`${o}
|
|
717
|
+
`)}};xg.exports={renderMarkdown:yv,renderInline:fs,stripHeadingMarkers:Ct,highlightCode:Mc,highlightJS:mg,highlightBash:gg,highlightJSON:yg,highlightPython:wg,highlightGo:$g,highlightRust:bg,highlightCSS:_g,highlightHTML:kg,renderTable:wv,renderProgress:$v,wrapAnsi:ps,StreamRenderer:Nc}});var Cg=V((DC,Rg)=>{var{execSync:bv}=require("child_process"),Pc=require("path"),nr=require("fs"),Lc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Eg(){return Pc.join(process.cwd(),".nex","hooks")}function _v(){return Pc.join(process.cwd(),".nex","config.json")}function vg(){let t=_v();if(!nr.existsSync(t))return{};try{return JSON.parse(nr.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Gi(t){if(!Lc.includes(t))return[];let e=[],s=Eg(),o=Pc.join(s,t);nr.existsSync(o)&&e.push(o);let n=vg();if(n[t]){let r=Array.isArray(n[t])?n[t]:[n[t]];e.push(...r)}return e}function Tg(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:bv(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 kv(t,e={}){let s=Gi(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=Tg(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 xv(t){return Gi(t).length>0}function Sv(){let t=[];for(let e of Lc){let s=Gi(e);s.length>0&&t.push({event:e,commands:s})}return t}function Ev(){let t=Eg();return nr.existsSync(t)||nr.mkdirSync(t,{recursive:!0}),t}Rg.exports={HOOK_EVENTS:Lc,loadHookConfig:vg,getHooksForEvent:Gi,executeHook:Tg,runHooks:kv,hasHooks:xv,listHooks:Sv,initHooksDir:Ev}});var Yi=V((qC,Og)=>{var sr={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
|
|
703
718
|
Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
|
|
704
719
|
You excel at sysadmin, frontend, and multi-step coding tasks.
|
|
705
720
|
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.
|
|
@@ -712,7 +727,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
|
|
|
712
727
|
Prioritize decisive, targeted edits. Read only what you need, then fix.
|
|
713
728
|
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.
|
|
714
729
|
Trust your reasoning. Use tools thoroughly when the task demands it.
|
|
715
|
-
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},
|
|
730
|
+
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Ag={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function vv(t){let e=(t||"").toLowerCase(),s=null,o=0;for(let r of Object.keys(sr))e.startsWith(r)&&r.length>o&&(s=r,o=r.length);let n=s?{...sr[s]}:{...Ag};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 Tv(t){let e=(t||"").toLowerCase(),s=null,o=0;for(let n of Object.keys(sr))e.startsWith(n)&&n.length>o&&(s=n,o=n.length);return s&&sr[s].briefing||""}Og.exports={getModelProfile:vv,getModelBriefing:Tv,PROFILES:sr,DEFAULTS:Ag}});var Js=V((FC,Ng)=>{var{fork:Rv}=require("child_process"),Cv=require("path"),Av=Cv.join(__dirname,"background-worker.js"),hs=new Map,Vs=new Map;function Ov(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function Nv(t){let e=Ov(),s=Rv(Av,[],{silent:!0,env:process.env,cwd:process.cwd()});return s.send({jobId:e,agentDef:t}),s.on("message",o=>{o.type==="result"?Ic(e,t,o.payload):o.type==="error"&&Ic(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(hs.has(e)){let r=n?`killed (${n})`:`exit code ${o}`;Ic(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),hs.set(e,{process:s,agentDef:t,startedAt:Date.now()}),e}function Ic(t,e,s){hs.delete(t),Vs.set(t,{jobId:t,agentDef:e,result:s,finishedAt:Date.now()})}function Mv(){if(Vs.size===0)return[];let t=[...Vs.values()];return Vs.clear(),t}function Pv(){return hs.size>0||Vs.size>0}function Lv(){let t=hs.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function Iv(){for(let[t,e]of hs){try{e.process.kill("SIGTERM")}catch{}hs.delete(t)}Vs.clear()}Ng.exports={createJob:Nv,getCompletedJobs:Mv,getPendingJobSummary:Lv,hasPendingOrCompletedJobs:Pv,cancelAllJobs:Iv}});var Vg=V((HC,Xg)=>{"use strict";var{callWithRetry:Lg,runSubAgent:Mg,clearAllLocks:jv}=Pi(),{parseModelSpec:Ig,getActiveProviderName:BC,getActiveModelId:UC}=lt(),{detectCategory:Dv,getModelForCategory:Pg}=Qo(),{MultiProgress:qv,C:pe}=nt(),{getModelBriefing:WC}=Yi(),jg=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),zi=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Dg="devstral-2:123b",qg="kimi-k2.5",Fg=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
716
731
|
|
|
717
732
|
RULES:
|
|
718
733
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -727,7 +742,7 @@ RULES:
|
|
|
727
742
|
- If the request is simple (single goal), return an array with exactly 1 item.
|
|
728
743
|
|
|
729
744
|
USER REQUEST:
|
|
730
|
-
{prompt}`,
|
|
745
|
+
{prompt}`,Bg=`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.
|
|
731
746
|
|
|
732
747
|
RULES:
|
|
733
748
|
- Output ONLY a JSON object with these fields:
|
|
@@ -741,16 +756,16 @@ ORIGINAL REQUEST:
|
|
|
741
756
|
{prompt}
|
|
742
757
|
|
|
743
758
|
SUB-AGENT RESULTS:
|
|
744
|
-
{results}`;async function
|
|
745
|
-
${e.slice(0,200)}`)}async function
|
|
759
|
+
{results}`;async function Ug(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 Wg(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 Fv(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 jc(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:
|
|
760
|
+
${e.slice(0,200)}`)}async function Hg(t,e,s={}){let o=s.maxSubTasks||zi,r=[{role:"system",content:Fg.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Ig(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await Lg(r,[],i)).content||"",c=jc(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),p=f.reduce((g,$)=>g+$.estimatedCalls,0),m=zi*u;if(p>m){let{debugLog:g}=Xa();g(`${Ht().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${m} \u2014 consider raising maxSubTasks${Ht().T.reset}`)}return f}async function Gg(t,e,s){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((u,d)=>{let f=u.status==="done"?"SUCCESS":u.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
|
|
746
761
|
Task: ${u.task}
|
|
747
762
|
Result: ${u.result}
|
|
748
763
|
Tools: ${(u.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
749
764
|
|
|
750
|
-
`),r=[{role:"system",content:
|
|
751
|
-
${pe.bold}Orchestrator${pe.reset} ${pe.dim}model: ${s} | workers: ${
|
|
752
|
-
`),i("decomposing"),console.log(`${pe.dim}Phase 1: Decomposing prompt into sub-tasks...${pe.reset}`);let l;try{l=await
|
|
753
|
-
`);let u=Date.now(),d=
|
|
765
|
+
`),r=[{role:"system",content:Bg.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=Ig(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let l=(await Lg(r,[],i)).content||"",c=jc(l);return{summary:String(c.summary||""),conflicts:Array.isArray(c.conflicts)?c.conflicts:[],commitMessage:String(c.commitMessage||""),filesChanged:Array.isArray(c.filesChanged)?c.filesChanged:[]}}async function Bv(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||qg,o=e.workerModel||Dg,n=e.maxParallel||jg,r=e.maxSubTasks||zi,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
|
|
766
|
+
${pe.bold}Orchestrator${pe.reset} ${pe.dim}model: ${s} | workers: ${o} | max parallel: ${n}${pe.reset}
|
|
767
|
+
`),i("decomposing"),console.log(`${pe.dim}Phase 1: Decomposing prompt into sub-tasks...${pe.reset}`);let l;try{l=await Hg(t,s,{maxSubTasks:r})}catch(W){return console.log(`${pe.red}Decompose failed: ${W.message}${pe.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${W.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${pe.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${pe.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${pe.green}Decomposed into ${l.length} sub-tasks:${pe.reset}`);for(let W of l){console.log(` ${pe.dim}${W.id}:${pe.reset} ${W.task}`);let z=W.scope.filter(Boolean);z.length>0&&console.log(` ${pe.dim}scope: ${z.join(", ")}${pe.reset}`)}console.log("");let c=new Map;for(let W=0;W<l.length;W++)for(let z of l[W].scope)z&&!c.has(z)&&c.set(z,W);i("executing"),console.log(`${pe.dim}Phase 2: Running ${l.length} sub-agents (max ${n} parallel)...${pe.reset}
|
|
768
|
+
`);let u=Date.now(),d=Wg(n),f={findings:[],_lock:!1},p=l.map(W=>{let z=Dv(W.task);return(z?Pg(z.id):null)||o}),m=l.map((W,z)=>{let ge=`Agent ${z+1} [${p[z]}]: `,Ae=Math.max(20,60-ge.length),qe=W.task.substring(0,Ae)+(W.task.length>Ae?"...":"");return ge+qe}),g=new qv(m);g.start();let $=`
|
|
754
769
|
You are a focused coding agent executing ONE specific sub-task.
|
|
755
770
|
Your scope is limited to the files listed in your task definition.
|
|
756
771
|
|
|
@@ -775,77 +790,78 @@ RULES:
|
|
|
775
790
|
- Start with symbol-aware reads inside your scope: locate the target function/class/module, then read the exact section instead of scanning broadly.
|
|
776
791
|
- Before finishing, run the smallest relevant verification for your scope and report any residual risk explicitly.
|
|
777
792
|
- If your sub-task is review/audit/verify-oriented, output findings first with severity, file, and impact. If nothing is wrong, say so explicitly and mention remaining risk.
|
|
778
|
-
`,
|
|
779
|
-
`),
|
|
780
|
-
${
|
|
781
|
-
`:"",W.scope.length>0?`Focus on files: ${W.scope.join(", ")}`:"",
|
|
782
|
-
`)),
|
|
783
|
-
`):void 0,max_iterations:Math.min(W.estimatedCalls||10,15),model:fe,_skipLog:!0,_systemPrompt:$,_readOnlyFiles:ke},{onUpdate:
|
|
793
|
+
`,x=new Map;for(let W=0;W<l.length;W++){let z=l[W].priority||1;x.has(z)||x.set(z,[]),x.get(z).push({st:l[W],idx:W})}let T=[...x.keys()].sort((W,z)=>W-z),A=new Array(l.length);for(let W of T){let ge=x.get(W).map(async({st:Ae,idx:qe})=>{let ke=await d();try{let _e=await R(Ae,qe,{acquire:d,subTaskModels:p,labels:m,progress:g,sharedContext:f,_fileOwnership:c,workerModel:o,WORKER_SYSTEM_PROMPT:$});return A[qe]=_e,_e}finally{ke()}});await Promise.all(ge)}async function R(W,z,ge){try{let Ae=f.findings.filter(de=>de.agentId!==W.id).map(de=>`Agent ${de.agentId} found: ${de.summary}`).join(`
|
|
794
|
+
`),qe=[...c.entries()].filter(([,de])=>de===z).map(([de])=>de),ke=[...c.entries()].filter(([,de])=>de!==z).map(([de])=>de),_e=[Ae?`Prior agent findings:
|
|
795
|
+
${Ae}
|
|
796
|
+
`:"",W.scope.length>0?`Focus on files: ${W.scope.join(", ")}`:"",qe.length>0?`You OWN these files (may read+write): ${qe.join(", ")}`:"",ke.length>0?`READ ONLY (owned by other agents, do NOT write): ${ke.join(", ")}`:""].filter(Boolean),k=Kg(W.task),D=p[z],H=process.env.NEX_FALLBACK_MODEL||Pg("agentic")||o,M=0,I=await Ug(async()=>{let de=M>0;de&&(g.update(z,"retry"),process.stderr.write(` ${pe.dim}[Agent ${z+1}] retrying after error...${pe.reset}
|
|
797
|
+
`)),M++;let fe=de&&D!==H?H:D;return Mg({task:W.task,type:k,context:_e.length>0?_e.join(`
|
|
798
|
+
`):void 0,max_iterations:Math.min(W.estimatedCalls||10,15),model:fe,_skipLog:!0,_systemPrompt:$,_readOnlyFiles:ke},{onUpdate:Ze=>{if(Ze&&Ze.type==="tool_call"&&process.stderr.isTTY){let uo=`Agent ${z+1} [${fe}]`,Sn=Ze.tool||"...";g.labels[z]=`${uo}: ${Sn}`}}})},1,2e3),_="";if(zg(k,I,W,qe)){let de=[...new Set([...qe,...Array.isArray(I.filesModified)?I.filesModified:[],...Array.isArray(W.scope)?W.scope:[]])].filter(Boolean);try{g.labels[z]=`Agent ${z+1} [${D}] review`,g.update(z,"retry");let fe=await Mg({task:`Review the completed changes for: ${W.task}`,type:"review",context:Gv(W,I,de),max_iterations:4,model:D,_skipLog:!0,_systemPrompt:$},{onUpdate:()=>{}},1);Yg(fe.result)?(_=`
|
|
784
799
|
|
|
785
800
|
Reviewer findings:
|
|
786
801
|
${fe.result}`,f.findings.push({agentId:`${W.id}-review`,summary:String(fe.result||"").slice(0,200),files:de})):fe.result&&(_=`
|
|
787
802
|
|
|
788
803
|
Reviewer: ${fe.result}`)}catch(fe){_=`
|
|
789
804
|
|
|
790
|
-
Reviewer note: review pass failed (${fe.message})`}}let
|
|
791
|
-
`),conflicts:[],commitMessage:"",resourcesChanged:[]}}let
|
|
805
|
+
Reviewer note: review pass failed (${fe.message})`}}let Z=typeof I.result=="string"?`${I.result}${_}`.slice(0,200):`${String(I.result||"")}${_}`.slice(0,200);return f.findings.push({agentId:W.id,summary:Z,files:Array.isArray(W.scope)?W.scope:[]}),g.labels[z]=m[z],g.update(z,I.status==="failed"?"error":"done"),a.input+=I.tokensUsed?.input||0,a.output+=I.tokensUsed?.output||0,I.tokensUsed?._estimated&&(a._estimated=!0),{...I,result:`${String(I.result||"")}${_}`,_scope:W.scope,_idx:z}}catch(Ae){return g.labels[z]=m[z],g.update(z,"error"),{task:W.task,status:"failed",result:`Error: ${Ae.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let v;try{v=A}finally{g.stop({silent:!0}),jv()}console.log("");let N=Math.round((Date.now()-u)/1e3),Q=N>=60?`${Math.floor(N/60)}m ${N%60}s`:`${N}s`;for(let W=0;W<v.length;W++){let z=v[W],Ae=z.status==="done"||z.status==="truncated"&&z.result&&!z.result.startsWith("Error")?`${pe.green}\u2713${pe.reset}`:`${pe.red}\u2717${pe.reset}`,qe=z._scope&&z._scope.length>0?z._scope.map(k=>k.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],ke=qe.length>0?qe.join(", "):z.task.substring(0,35)+(z.task.length>35?"...":""),_e=W===v.length-1;console.log(` ${Ae} Agent ${W+1} ${pe.dim}${ke}${pe.reset}${_e?` ${pe.dim}${Q}${pe.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${pe.dim}Phase 3: Synthesizing results...${pe.reset}`);let se;try{se=await Gg(v,t,s)}catch(W){console.log(`${pe.yellow}Synthesize failed: ${W.message} \u2014 using raw results.${pe.reset}`),se={summary:v.map(z=>z.result).join(`
|
|
806
|
+
`),conflicts:[],commitMessage:"",resourcesChanged:[]}}let re=f.findings.flatMap(W=>W.files),le=new Map;for(let W of re)le.set(W,(le.get(W)||0)+1);let ne=[...le.values()].some(W=>W>1),S=f.findings.length>1&&ne?` ${pe.dim}(agents shared context)${pe.reset}`:"";if(console.log(`
|
|
792
807
|
${pe.bold}Summary:${pe.reset} ${se.summary}${S}`),se.conflicts.length>0){console.log(`${pe.yellow}Conflicts:${pe.reset}`);for(let W of se.conflicts)console.log(` - ${W}`)}se.commitMessage&&console.log(`${pe.dim}Suggested commit: ${se.commitMessage}${pe.reset}`);let ve=a.input===0&&a.output===0?"n/a (provider does not report token counts)":a._estimated?`~${a.input} input / ~${a.output} output (est.)`:`${a.input} input + ${a.output} output`;return console.log(`${pe.dim}Tokens: ${ve}${pe.reset}
|
|
793
|
-
`),{results:
|
|
794
|
-
`)}function
|
|
795
|
-
`)}var
|
|
808
|
+
`),{results:v,synthesis:se,totalTokens:a}}var Uv=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,Wv=/\b(review|audit|verify|validate|inspect|critique)\b/i,Hv=/\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 Gv(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(`
|
|
809
|
+
`)}function Yg(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function zg(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 Kg(t){if(!t)return"implement";let e=Uv.test(t),s=Wv.test(t);return Hv.test(t)?"implement":s?"review":e?"explore":"implement"}Xg.exports={runOrchestrated:Bv,decompose:Hg,synthesize:Gg,detectComplexPrompt:Fv,extractJSON:jc,createSemaphore:Wg,DECOMPOSE_PROMPT:Fg,SYNTHESIZE_PROMPT:Bg,DEFAULT_ORCHESTRATOR_MODEL:qg,DEFAULT_WORKER_MODEL:Dg,DEFAULT_MAX_PARALLEL:jg,DEFAULT_MAX_SUBTASKS:zi,withRetry:Ug,_classifyWorkerType:Kg,_hasMaterialReviewFindings:Yg,_shouldRunFollowUpReview:zg}});var $c=V((VC,Ry)=>{var{C:h,Spinner:Qs,TaskProgress:Yv,formatToolCall:zv,formatToolSummary:Jc,formatSectionHeader:or,formatMilestone:Kv,setActiveTaskProgress:GC,getThinkingVerb:Dc,setActiveModelForSpinner:Jg}=nt(),{debugLog:j,warnLog:YC}=Xa(),{MilestoneTracker:Xv}=Ud(),{callStream:Zg}=lt(),{parseToolArgs:Vv}=Kr(),{executeTool:Jv}=xo(),{gatherProjectContext:Zv}=Lm(),{fitToContext:Qv,forceCompress:un,getUsage:Vt,estimateTokens:eT,buildProgressSnapshot:tT}=ln(),{autoSave:nT,flushAutoSave:sT}=qi(),{scoreMessages:oT,formatScore:rT,appendScoreHistory:iT}=zm(),{detectCategory:aT,getModelForPhase:Zc,getPhaseBudget:ms,isPhaseRoutingEnabled:lT}=Qo();function Ne(t){nT(t),sT()}function cT(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 Ki(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=oT(t);if(!s)return;console.log(rT(s,h));try{let{_getSessionsDir:o}=qi(),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}=Kr(),n=Ba();iT(s.score,{version:n.version,model:o?o():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:uT}=qo(),{getDeploymentContextBlock:dT,probeUrlServer:fT}=_c(),{getFewShotForInput:pT}=ng(),{checkPermission:hT,setPermission:mT,savePermissions:gT}=lg(),{confirm:dy,setAllowAlwaysHandler:yT,getAutoConfirm:pr}=wo(),{isPlanMode:hr,getPlanModePrompt:wT,PLAN_MODE_ALLOWED_TOOLS:fy,setPlanContent:$T,extractStepsFromText:bT,createPlan:_T,getActivePlan:zC,startExecution:KC,advancePlanStep:kT,getPlanStepInfo:xT}=Hi(),{StreamRenderer:ST}=Sg(),{runHooks:Qg}=Cg(),{routeMCPCall:ET,getMCPToolDefinitions:vT}=pl(),{getSkillInstructions:TT,getSkillToolDefinitions:RT,routeSkillCall:CT,matchSkillTriggers:AT}=dl(),{trackUsage:ey,estimateTokens:ty}=Br();function ny(t){return!t||typeof t!="string"?0:typeof ty=="function"?ty(t):Math.ceil(t.length/4)}var{validateToolArgs:OT}=gl(),{filterToolsForModel:sy,getModelTier:NT,PROVIDER_DEFAULT_TIER:XC}=Co(),{getConfiguredProviders:MT,getActiveProviderName:eo,getActiveModelId:Qt,setActiveModel:qc,MODEL_EQUIVALENTS:ua}=lt(),{getModelProfile:PT,getModelBriefing:LT}=Yi(),De=require("fs"),We=require("path"),IT=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function jT(t){let e=Kv(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
810
|
+
`)}var oy=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,ry=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,DT=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function qT(t){let e=[],s;for(oy.lastIndex=0;(s=oy.exec(t))!==null;){let o=s[1].trim(),n=o.startsWith("~")?o.replace("~",process.env.HOME||""):We.resolve(o);De.existsSync(n)&&e.push({raw:o,abs:n})}return e}function py(t){let e=[],s;for(ry.lastIndex=0;(s=ry.exec(t))!==null;)e.push(s[1].trim());return e}async function hy(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]:FT(t);return{data:Buffer.from(s.data).toString("base64"),media_type:n}}catch{return null}}function FT(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 my(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=We.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&De.existsSync(e)){let n=De.readFileSync(e);if(n.length>100)return{data:n.toString("base64"),media_type:"image/png",path:e};try{De.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let o=t("osascript",["-e",`try
|
|
796
811
|
set imgData to the clipboard as \xABclass PNGf\xBB
|
|
797
812
|
return "has_image"
|
|
798
813
|
on error
|
|
799
814
|
return "no_image"
|
|
800
|
-
end try`],{timeout:3e3});if(
|
|
815
|
+
end try`],{timeout:3e3});if(o.stdout&&o.stdout.toString().trim()==="has_image"){let n=`
|
|
801
816
|
set imgData to the clipboard as \xABclass PNGf\xBB
|
|
802
817
|
set filePath to POSIX file "${e}"
|
|
803
818
|
set fRef to open for access filePath with write permission
|
|
804
819
|
write imgData to fRef
|
|
805
820
|
close access fRef
|
|
806
|
-
`;if(t("osascript",["-e",
|
|
821
|
+
`;if(t("osascript",["-e",n],{timeout:5e3}).status===0&&De.existsSync(e)){let i=De.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function iy(t){let e=De.readFileSync(t),s=We.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 gy(t){let e=qT(t),s=py(t),o=DT.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}=iy(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}=iy(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){j(`${h.yellow} \u26A0 Path resolution failed: ${a.message}${h.reset}`)}if(s.length>0){let i=await Promise.all(s.map(hy));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=my();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
|
|
807
822
|
[Clipboard image attached: ${i.path}]`):r[0].text+=`
|
|
808
|
-
[No image found in clipboard]`}return r.length>1?r:t})()}var
|
|
823
|
+
[No image found in clipboard]`}return r.length>1?r:t})()}var BT=[/\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 yy(t){return typeof t!="string"||!t?!1:BT.some(e=>e.test(t))}function UT(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=`
|
|
809
824
|
|
|
810
|
-
[SYSTEM: Output repetition detected \u2014 response truncated (${
|
|
811
|
-
`),
|
|
825
|
+
[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 Qc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
|
|
826
|
+
`),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=`
|
|
812
827
|
|
|
813
|
-
\u26A0 [Response truncated: repeated paragraph detected (${
|
|
828
|
+
\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 Fc=null,Bc=null,Uc=null;function ut(){if(Fc===null){let{TOOL_DEFINITIONS:t}=xo();Fc=t}return Bc===null&&(Bc=RT()),Uc===null&&(Uc=vT()),[...Fc,...Bc,...Uc]}var eu=50;function WT(t){Number.isFinite(t)&&t>0&&(eu=t)}var Zi=()=>null;function HT(t){Zi=t}var lr=null,tu=null,to=null,no="",so=0,nu="",su=0,Qi=new Map,GT=1e4,YT=6e3,zT=/\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 KT(t){return!t||typeof t!="string"?t:t.replace(zT,(e,s)=>`${s}=***REDACTED***`)}var XT=7e3,VT=4e3;function JT(t,e=null){let s=KT(t),o=eT(s),n=e==="read_file"?XT:GT,r=e==="read_file"?VT:YT;if(o>n)try{let{compressToolResult:i}=ln();return i(s,r)}catch{return s}return s}function wy(t){try{let{getActiveModel:e}=lt(),s=e(),o=s?`${s.provider}:${s.id}`:"default";if(Qi.has(o))return Qi.get(o);let n=sy(t);return Qi.set(o,n),n}catch{return sy(t)}}function ZT(){Qi.clear()}var cr={hash:null,ts:0},QT=3e4;async function $y(){if(cr.hash&&Date.now()-cr.ts<QT)return cr.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}=qo(),a=i();a&&n.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(De.existsSync(i)){let a=await t.stat(i);n.push(`brain:${a.mtimeMs}`)}}catch{}let r=n.join("|");return cr={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function ou(){lr=null,tu=null,cr={hash:null,ts:0},to=null}var eR=new Set(["spawn_agents"]),Wc=10,Hc=10,Xi=5,ay=6e4,Gc=12e4,tR=process.env.NEX_STALE_AUTO_SWITCH!=="0";function nR(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{}}yT(t=>{mT(t,"allow"),gT(),console.log(`${h.green} \u2713 ${t}: always allow${h.reset}`)});async function sR(t){let e=t.function.name,s=Vv(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let d=ut().find(p=>p.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return j(`${h.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${h.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
814
829
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
815
830
|
|
|
816
831
|
Expected JSON schema for "${e}":
|
|
817
832
|
${f}
|
|
818
833
|
|
|
819
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:
|
|
820
|
-
`)[0]}${h.reset}`);let u=(
|
|
834
|
+
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=We.resolve(process.cwd(),s.path.replace(/^~/,u.homedir())),f=s.path;s.path=We.relative(process.cwd(),d)||".",Object.defineProperty(s,"_originalPath",{value:f,enumerable:!1})}catch(u){console.error("path resolution failed:",u.message)}let n=OT(e,s);if(!n.valid){j(`${h.yellow} \u26A0 ${e}: ${n.error.split(`
|
|
835
|
+
`)[0]}${h.reset}`);let u=(cy.get(e)||0)+1;cy.set(e,u);let d=u>=2?`${n.error}
|
|
821
836
|
|
|
822
|
-
[SYSTEM: This is argument error #${u} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:
|
|
837
|
+
[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(hr()&&!fy.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(me&&Ce==="plan"&&!i.has(e)&&!e.startsWith("skill_")&&!l)return In++,j(`${h.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${In})${h.reset}`),{callId: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(me&&Ce==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return j(`${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=hT(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 dy(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 oR(t,e,s={}){let o=await CT(t,e);if(o!==null)return o;let n=await ET(t,e);return n!==null?n:Jv(t,e,s)}function rR(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 Yc(t,e=!1){e||console.log(zv(t.fnName,t.args));let s=Qg("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(`${h.yellow} [hook pre-tool] BLOCKED: ${s.blockReason}${h.reset}`);let x=Jc(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(`${h.dim} [hook pre-tool] ${$.command} \u2192 ${$.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook pre-tool] ${$.command} \u2192 ERROR: ${$.error}${h.reset}`);pn?.onToolStart&&pn.onToolStart(t.fnName,t.args);let n=await oR(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)+`
|
|
823
838
|
...(truncated ${i.length-5e4} chars)`:i,l=a.split(`
|
|
824
|
-
`)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=
|
|
839
|
+
`)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=Jc(t.fnName,t.args,a,c);e||console.log(u),pn?.onToolEnd&&pn.onToolEnd(t.fnName,u,!c);let f=Qg("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let $ of f)$.success?console.log(`${h.dim} [hook post-tool] ${$.command} \u2192 ${$.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook post-tool] ${$.command} \u2192 ERROR: ${$.error}${h.reset}`);let m=JT(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let $=t.args.command.trim();!/cat\s*>|<</.test($)&&/\bcat\s+\S/.test($)?m+=`
|
|
825
840
|
HINT: use read_file instead of bash cat \u2014 it is faster, context-efficient, and the preferred tool for reading files.`:/^\s*ls(\s|$)/.test($)&&!/npm|yarn|pnpm|make|git\b/.test($)?m+=`
|
|
826
841
|
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test($)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test($)&&(m+=`
|
|
827
|
-
HINT: use glob instead of bash find for file discovery \u2014 it is faster and the preferred tool (e.g. glob('**/*.jsx')).`)}return{msg:{role:"tool",content:r?[{type:"text",text:m},...r.map($=>({type:"image",media_type:$.media_type,data:$.base64}))]:m,tool_call_id:t.callId},summary:u}}var
|
|
828
|
-
`)):(
|
|
829
|
-
`)}function
|
|
830
|
-
Duration: ${e}s`:"",
|
|
842
|
+
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 iR=[{re:/TypeError:\s*([^\n]{0,120})/i,label:"TypeError"},{re:/SyntaxError:\s*([^\n]{0,120})/i,label:"SyntaxError"},{re:/ReferenceError:\s*([^\n]{0,120})/i,label:"ReferenceError"},{re:/Cannot find module\s*'([^']+)'/i,label:"Cannot find module"},{re:/Error:\s*ENOENT[^\n]{0,120}/i,label:"ENOENT"},{re:/Error:\s*EACCES[^\n]{0,120}/i,label:"EACCES"},{re:/Error:\s*EADDRINUSE[^\n]{0,120}/i,label:"EADDRINUSE"},{re:/ImportError:\s*([^\n]{0,120})/i,label:"ImportError"},{re:/ModuleNotFoundError:\s*([^\n]{0,120})/i,label:"ModuleNotFoundError"},{re:/NameError:\s*([^\n]{0,120})/i,label:"NameError"},{re:/AttributeError:\s*([^\n]{0,120})/i,label:"AttributeError"},{re:/KeyError:\s*([^\n]{0,120})/i,label:"KeyError"},{re:/ValueError:\s*([^\n]{0,120})/i,label:"ValueError"},{re:/panic:\s*([^\n]{0,120})/i,label:"Go panic"},{re:/java\.lang\.\w+Exception[^\n]{0,80}/i,label:"Java exception"}];function zc(t){for(let{re:e,label:s}of iR){let o=t.match(e);if(o){let n=(o[1]||"").trim();return n?`${s}: ${n}`:s}}return null}async function aR(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=rR(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 Qs(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await Yc(t[l],e);o[l]=c,n.push(u)}else{let l=r.map(u=>Yc(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(Jc(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(eR.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await Yc(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 L=[],ly=300,by=900*1e3;function dn(t,e){let s=t.get(e);return s?Date.now()-s.ts>by?(t.delete(e),0):s.count:0}function gs(t,e){let s=t.get(e),o=s&&Date.now()-s.ts<=by?s.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function Kc(t,e,s){t.set(e,{count:s,ts:Date.now()})}var pu=new Map,_y=new Map,ea=new Map,mr=new Set,ky=new Map,ta=new Map,gr=new Set,kn=new Map,Ln=new Map,yr=new Map,Dt=new Map,bs=new Map,cy=new Map,da=new Map,ru=new Map,qt=0,ur=0,na=0,iu="",sa=0,At=!1,Vi=0,oa=0,ys=-1,au=!1,ra=0,ia=!1,Bt=0,Ut=!1,Jt=0,Zt=0,rt=!1,kt="",dr=0,Pn=0,aa="",ws=0,$s=0,la="",rr=0,Ft=!1,lu=!1,$r=new Map,br=new Set,fr=null,Xc=!1,ir=0,uy=!1,Ce="plan",fa=0,me=!1,In=0,xn=null,cu=null,uu=null,oo=0,wr=0,ro=0,io=!1,ao=0,lo=null,_s=[];function Zs(t,e){t===iu?(sa++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${sa})${h.reset}
|
|
843
|
+
`)):(iu=t,sa=1,j(`${e} \u26A0 ${t}${h.reset}`))}var ca=[];function lR(t){ca.push(t.trim())}function cR(){return ca.length===0?null:ca.splice(0,ca.length).join(`
|
|
844
|
+
`)}function uR(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,s=e!==null?`
|
|
845
|
+
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?`
|
|
831
846
|
Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
|
|
832
847
|
Job: ${t.jobId}
|
|
833
848
|
Task: "${t.agentDef.task}"`+s+`
|
|
834
|
-
Status: ${t.result.status||"done"}`+
|
|
835
|
-
Result: ${
|
|
836
|
-
`)}}function
|
|
837
|
-
`).find(l=>l.includes(r)||l.includes(
|
|
849
|
+
Status: ${t.result.status||"done"}`+n+`
|
|
850
|
+
Result: ${o}`}function Ji(t,e){let{getCompletedJobs:s}=Js(),o=s();for(let n of o){let r={role:"user",content:uR(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}
|
|
851
|
+
`)}}function xy(t,e){let s=[],o=new Set([...e.keys(),...mr,...gr]);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(`
|
|
852
|
+
`).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 dR(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 fR(){return De.existsSync(We.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":De.existsSync(We.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function fn(t){let e=fR();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 pR(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(`
|
|
853
|
+
`)}function hR(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 Sy(t){let e=dR(t);if(e.length===0)return[];let{searchContentIndex:s}=sn(),o=[],n=new Set;for(let r of e)try{let i=await s(r,void 0,process.cwd());for(let a of i.slice(0,3)){let l=`${a.file}:${a.name}:${a.line}`;if(!n.has(l)&&(n.add(l),o.push(a),o.length>=5))return o}}catch{}return o}async function Ey(t){let e=await Sy(t);if(e.length===0)return"";let{getRelatedFiles:s,findSymbolReferences:o}=sn(),n=["Likely symbol targets:"];for(let r=0;r<e.length;r++){let i=e[r],a=Math.max(1,i.line-20),l=i.line+40;n.push(`${r+1}. ${i.name} (${i.type}) in ${i.file}:${i.line} -> read_file(path='${i.file}', line_start=${a}, line_end=${l})`);try{let 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(`
|
|
838
854
|
`)}
|
|
839
855
|
Use these exact targeted reads before broader searching.
|
|
840
856
|
|
|
841
|
-
`}function
|
|
857
|
+
`}async function pa(t){let{getFileIndex:e}=sn(),{buildContentIndex:s,findSymbolReferences:o,getRelatedFiles:n}=sn(),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=We.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 $=We.basename(g).replace(/\.[^.]+$/,"");if(!($.length<3)){for(let x of i)if(x.includes($)&&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,$)=>m&&$.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 $ of g)if(i.includes($.file)&&a.add($.file),a.size>=4)return[...a]}catch{}}return[...a]}function mR(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)||De.existsSync(We.join(process.cwd(),"vitest.config.ts"))||De.existsSync(We.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${s}`):(/jest/.test(n)||De.existsSync(We.join(process.cwd(),"jest.config.js"))||De.existsSync(We.join(process.cwd(),"jest.config.cjs"))||De.existsSync(We.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${s}`),(De.existsSync(We.join(process.cwd(),"pytest.ini"))||De.existsSync(We.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 ar(t,e,s,o){if(!me)return null;let n=Ce;Ce=t,fa=0,xn=Zc(t,lo),t==="verify"&&(wr=0,ro=0,io=!1,ao=0),Bt=0,Ut=!1,Jt=0,Zt=0,bs.clear(),da.clear(),pu.clear(),yr.clear(),t==="implement"&&(_s=xy(e||"",kn));let r=_s.length>0?`
|
|
842
858
|
|
|
843
859
|
ACTION ITEMS (execute these in order, do NOT re-read these files):
|
|
844
|
-
|
|
845
|
-
`):"",i=await
|
|
846
|
-
${
|
|
860
|
+
`+_s.map((l,c)=>`${c+1}. ${l.file} \u2014 ${l.action}`).join(`
|
|
861
|
+
`):"",i=await Ey(t==="verify"?o:e||o||""),a;if(t==="implement")cu=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
|
|
862
|
+
${cu}
|
|
847
863
|
|
|
848
|
-
${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){
|
|
864
|
+
${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){uu=e?.slice(0,500)||"";let l=s?[...s].join(", "):"none",c=await hu(s),u=await pa(s),d=c.length>0?`Suggested checks (run the narrowest ones that fit the change):
|
|
849
865
|
${c.map((p,m)=>`${m+1}. ${p}`).join(`
|
|
850
866
|
`)}
|
|
851
867
|
|
|
@@ -858,22 +874,25 @@ Prefer these before broader suites when a targeted run is possible.
|
|
|
858
874
|
1. Read only the modified sections/files and confirm the final code matches intent
|
|
859
875
|
2. Run the smallest relevant verification command(s)
|
|
860
876
|
3. If one check fails, explain the failure precisely and loop back with a focused fix
|
|
861
|
-
4. Does the implementation address: "${(
|
|
877
|
+
4. Does the implementation address: "${(o||"").slice(0,200)}"?
|
|
862
878
|
Report PASS (all good) or FAIL (list specific issues).
|
|
863
879
|
|
|
864
880
|
Files modified: ${l}
|
|
865
|
-
${i}${d}${f}Summary: ${
|
|
866
|
-
`];n?
|
|
867
|
-
This is a hard requirement. Always respond in ${n}. Do NOT switch to any other language \u2014 even if the user writes to you in German, French, or any other language, your reply MUST be in ${n}.`),
|
|
881
|
+
${i}${d}${f}Summary: ${uu}`}return j(`${h.cyan} \u21B3 Phase transition: ${n} \u2192 ${t} (model: ${xn||"default"})${h.reset}`),a?{role:"user",content:a}:null}async function hu(t){let e=[],o=[...t||[]].map(l=>String(l).toLowerCase()),n={};try{let l=We.join(process.cwd(),"package.json");if(De.existsSync(l)){n=JSON.parse(De.readFileSync(l,"utf-8")).scripts||{};let u=[["test",fn("test")],["lint",fn("lint")],["typecheck",fn("typecheck")],["check",fn("check")],["build",fn("build")]];for(let[d,f]of u)n[d]&&e.push(f)}}catch{}e.length===0&&(De.existsSync(We.join(process.cwd(),"package.json"))&&e.push(fn("test")),(De.existsSync(We.join(process.cwd(),"pytest.ini"))||De.existsSync(We.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await pa(t);e.unshift(...mR(r,n));let i=o.some(l=>/\.(ts|tsx)$/.test(l)),a=o.some(l=>/\.(js|jsx|ts|tsx)$/.test(l));return i&&!e.includes(fn("typecheck"))&&e.push(fn("typecheck")),a&&!e.includes(fn("lint"))&&e.push(fn("lint")),[...new Set(e)].slice(0,4)}function gR(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(Ty())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 yR(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,o=Ty(),n=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
882
|
+
`];n?r.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o?r.push("RESPONSE LANGUAGE: This project requires English. Always respond in English, even if the user writes in another language."):r.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),r.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),r.push("COMPLETENESS RULES:"),r.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),pr()?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(`
|
|
883
|
+
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(`
|
|
868
884
|
`)+`
|
|
869
885
|
|
|
870
|
-
`}function
|
|
886
|
+
`}function wR(t){let e=gR(t);return`# Current Turn Language (CRITICAL \u2014 enforce strictly)
|
|
887
|
+
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.
|
|
888
|
+
|
|
889
|
+
`}function $R(){if(to!==null)return to;try{let e=MT().flatMap(n=>n.models.map(r=>({spec:`${n.name}:${r.id}`,tier:NT(r.id,n.name),name:r.name})));if(e.length<2)return to="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
|
|
871
890
|
# Sub-Agent Model Routing
|
|
872
891
|
|
|
873
|
-
`;
|
|
892
|
+
`;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 |
|
|
874
893
|
|---|---|---|
|
|
875
|
-
`;for(let
|
|
876
|
-
`;return
|
|
894
|
+
`;for(let n of e)o+=`| ${n.spec} | ${n.tier} | ${s[n.tier]||n.tier} |
|
|
895
|
+
`;return to=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),to="",""}}var du="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function bR(t){let e=t.indexOf(du);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+du.length).trimStart()}}async function fu(){let t=await $y()+":"+Qt();if(lr!==null&&t===tu)return lr;let e=await Zv(process.cwd()),s=uT(),o=TT(),n=hr()?wT():"",r=yR(),i=dT(),a=LT(Qt());return lr=`${a?`## Model Briefing
|
|
877
896
|
${a}
|
|
878
897
|
|
|
879
898
|
---
|
|
@@ -886,15 +905,15 @@ PROJECT CONTEXT:
|
|
|
886
905
|
${e}
|
|
887
906
|
${s?`
|
|
888
907
|
${s}
|
|
889
|
-
`:""}${n?`
|
|
890
|
-
${n}
|
|
891
908
|
`:""}${o?`
|
|
892
909
|
${o}
|
|
910
|
+
`:""}${n?`
|
|
911
|
+
${n}
|
|
893
912
|
`:""}
|
|
894
913
|
${r?`${r}
|
|
895
914
|
`:""}${i?`${i}
|
|
896
915
|
|
|
897
|
-
`:""}${
|
|
916
|
+
`:""}${pr()?`# YOLO Mode \u2014 Auto-Execute
|
|
898
917
|
|
|
899
918
|
You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
|
|
900
919
|
- NEVER ask for confirmation \u2014 just execute tasks directly
|
|
@@ -1134,7 +1153,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
|
|
|
1134
1153
|
- Instead: use bash with inline node -e '...' for quick one-off checks.
|
|
1135
1154
|
- If the test is worth keeping, write it to tests/ with a proper name.
|
|
1136
1155
|
- Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
|
|
1137
|
-
${
|
|
1156
|
+
${$R()}
|
|
1138
1157
|
|
|
1139
1158
|
# Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
|
|
1140
1159
|
|
|
@@ -1326,86 +1345,89 @@ class ErrorBoundary extends React.Component {
|
|
|
1326
1345
|
- Use migrations for schema changes, never manual ALTER TABLE
|
|
1327
1346
|
- Add database-level constraints (unique, foreign key, check) not just app-level
|
|
1328
1347
|
|
|
1329
|
-
`,
|
|
1330
|
-
`):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let c=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=
|
|
1331
|
-
\u{1F4E6} ${p}${m}`}}catch{}return c}function
|
|
1332
|
-
${h.dim} ${a}${h.reset}`),l>=30&&process.stdout.isTTY){let c=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;
|
|
1333
|
-
`),f==="")return a({action:"quit"});let m=i.find(g=>g.key===p);!m||m.key==="q"||!m.model&&m.key!=="r"?a({action:"quit"}):m.key==="r"?a({action:"retry"}):a({action:"switch",model:m.model,provider:t})};l.on("data",d)})}function
|
|
1348
|
+
`,tu=t,lr}function vy(){pu.clear(),_y.clear(),ea.clear(),mr.clear(),ky.clear(),ta.clear(),gr.clear(),kn.clear(),Ln.clear(),yr.clear(),Dt.clear(),bs.clear(),da.clear(),ru.clear(),qt=0,ur=0,na=0,At=!1,oa=0,ys=-1,au=!1,ra=0,ia=!1,Bt=0,Ut=!1,Jt=0,Zt=0,rt=!1,kt="",dr=0,aa="",ws=0,la="",$s=0,Ft=!1,lu=!1,Ce="plan",fa=0,me=!1,xn=null,cu=null,uu=null,_s=[],oo=0,wr=0,ro=0,io=!1,ao=0,In=0,lo=null,$r.clear(),br.clear(),iu="",sa=0}function _R(){L=[],fr=null,no="",so=0,nu="",su=0,vy();try{let{resetCompactionFailures:t}=Jl();t()}catch{}try{let{cancelAllJobs:t}=Js();t()}catch{}}function kR(){L.length>ly&&L.splice(0,L.length-ly)}function Ty(){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 Vc(t,e,s,o=1500){return!t||!e?!1:t===e&&Date.now()-s<o}function xR(){return L.length}function SR(){return L}function ER(t){L=t}async function vR(){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(`
|
|
1349
|
+
`):[]).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=We.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+=`
|
|
1350
|
+
\u{1F4E6} ${p}${m}`}}catch{}return c}function TR(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 Pe(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(`
|
|
1351
|
+
${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`;TR(c)}if(br.size>0&&$r.size>0)for(let c of br){let u=$r.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 RR(){if(!process.stdout.isTTY)return{action:"quit"};let t=eo(),e=Qt(),s=ua.fast?.[t],o=ua.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}
|
|
1352
|
+
`),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 CR(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 AR(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 pn=null;async function OR(t,e=null,s={}){let o=PT(Qt());ay=o.staleWarn,Gc=o.staleAbort,pn=e;let n=t;if(fr&&typeof t=="string"&&(n=`${fr}
|
|
1334
1353
|
|
|
1335
|
-
${t}`,
|
|
1354
|
+
${t}`,fr=null),typeof n=="string"){let we=CR(n),$e=AR(n);(we.length>0||$e.length>0)&&(n+=`
|
|
1336
1355
|
|
|
1337
1356
|
[System Note for Assistant: To resolve this task faster, consider these hints:
|
|
1338
|
-
`,
|
|
1339
|
-
`)
|
|
1340
|
-
`}),
|
|
1357
|
+
`,we.length>0&&(n+=`- The user mentioned URLs containing the paths/folders: ${we.join(", ")}. Prioritize searching these folder names using glob or grep first.
|
|
1358
|
+
`),$e.length>0&&$e.forEach(Se=>{n+=`- ${Se}
|
|
1359
|
+
`}),n+="Always prefer parallel search execution if unsure.]")}typeof n=="string"&&yy(n)&&(n+=`
|
|
1341
1360
|
|
|
1342
|
-
[Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=
|
|
1361
|
+
[Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=gy(n);r&&typeof r.then=="function"&&(r=await r),L.push({role:"user",content:r}),kR();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:we,runOrchestrated:$e}=Vg(),Se=we(typeof t=="string"?t:"");if(i&&Se.isComplex&&Se.estimatedGoals>=a){console.log(`${h.yellow}\u26A1 Auto-orchestrate: ${Se.estimatedGoals} goals \u2192 parallel agents${h.reset}`);let Qe=await $e(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});if(Qe&&Qe.synthesis){let dt=Qe.synthesis.summary||"",En=Qe.synthesis.filesChanged?.length?`
|
|
1343
1362
|
|
|
1344
|
-
Files changed: ${
|
|
1363
|
+
Files changed: ${Qe.synthesis.filesChanged.join(", ")}`:"",Ve=Qe.synthesis.conflicts?.length?`
|
|
1345
1364
|
|
|
1346
1365
|
Conflicts:
|
|
1347
|
-
${
|
|
1348
|
-
`)}`:"";
|
|
1349
|
-
|
|
1350
|
-
`)}catch(
|
|
1351
|
-
${
|
|
1366
|
+
${Qe.synthesis.conflicts.map(Ot=>`- ${Ot}`).join(`
|
|
1367
|
+
`)}`:"";L.push({role:"assistant",content:dt+En+Ve}),Ne(L),Ki(L)}return Qe}Se.isComplex&&process.stdout.isTTY&&console.log(`${h.dim}Hint: ~${Se.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${h.reset}`)}catch{}let{setOnChange:l}=Xl(),c=null,u=0;l((we,$e)=>{we==="create"?(c&&c.stop(),c=new Yv($e.name,$e.tasks),c.setStats({tokens:u}),c.start()):we==="update"&&c?c.updateTask($e.id,$e.status):we==="clear"&&c&&(c.stop(),c=null)});let d=await fu(),f=d;try{let{getBrainContext:we}=ac(),$e=await we(t);$e&&(f=d+`
|
|
1368
|
+
`+$e+`
|
|
1369
|
+
`)}catch(we){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",we.message)}let m=AT(typeof t=="string"?t:"");if(m.length>0){let we=m.map($e=>`[Triggered: ${$e.name}]
|
|
1370
|
+
${$e.instructions}`).join(`
|
|
1352
1371
|
`);f+=`
|
|
1353
|
-
`+
|
|
1354
|
-
`}
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
`)
|
|
1360
|
-
|
|
1361
|
-
|
|
1372
|
+
`+we+`
|
|
1373
|
+
`}f+=`
|
|
1374
|
+
`+wR(t);let g=[{role:"system",content:f},...L];Jg(Qt());let $=new Qs(Dc());$.start();let x=L.length===1,T=x?vR().catch(()=>null):Promise.resolve(null),A=x?fT(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),R=ut(),[{messages:v,compressed:N,compacted:Q,tokensRemoved:se},re,le]=await Promise.all([Qv(g,R),T,A]),ne=Vt(g,R);if($.stop(),re&&console.log(`${h.dim}${re}${h.reset}`),Q)console.log(`${h.dim} [context compacted \u2014 summary (~${se} tokens freed)]${h.reset}`);else if(N){let we=ne.limit>0?Math.round(se/ne.limit*100):0;j(`${h.dim} [context compressed \u2014 ~${se} tokens freed (${we}%)]${h.reset}`)}ne.percentage>85&&j(`${h.yellow} \u26A0 Context ${Math.round(ne.percentage)}% used (${Math.round(100-ne.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${h.reset}`);let S=v;if(le&&x&&(S=[S[0],{role:"user",content:`[Server probe at task start]
|
|
1375
|
+
${le}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...S.slice(1)]),x){let we=pT(typeof t=="string"?t:"");we&&(S=[S[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
|
|
1376
|
+
`+we.user},{role:"assistant",content:we.assistant+`
|
|
1377
|
+
[END EXAMPLE \u2014 wait for the real user request below]`},...S.slice(1)])}if(Vt(S,ut()).percentage>=65){let{messages:$e,tokensRemoved:Se}=un(S,ut());Se>0&&(S=$e,console.log(`${h.dim} [pre-flight compress \u2014 ${Se} tokens freed, now ${Math.round(Vt(S,ut()).percentage)}% used]${h.reset}`))}let ve=0,W=0,z=0,ge=0,Ae=0,qe=9,ke=0,_e=new Set,k=(()=>{let we=L.find($e=>$e.role==="user");return typeof we?.content=="string"?we.content:""})(),D=/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(k),H=0;if(!rt){let we=L.filter(Se=>Se.role==="user"||Se.role==="tool").map(Se=>typeof Se.content=="string"?Se.content:"").join(`
|
|
1378
|
+
`),$e=zc(we);$e&&(rt=!0,kt=$e.slice(0,120),j(`${h.yellow} \u26A1 Root cause in briefing: ${kt} \u2014 fix phase active from start (read budget: 3)${h.reset}`))}!rt&&!Ft&&/\b(create|build|generate|implement|write|make|develop|set\s*up|scaffold|add)\b.{0,80}\b(app|component|page|game|api|backend|frontend|server|service|module|class|function|feature|project|system|bot|script|tool)\b/i.test(k)&&(Ft=!0,j(`${h.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${h.reset}`)),L.length<=1&&!s.skipPhaseRouting&&(me=lT(),me&&(lo=aT(k)?.id||"coding",Ce="plan",xn=Zc("plan",lo),fa=0,oo=0,In=0,process.stdout.isTTY&&console.log(`${h.dim} \u21B3 Phase routing: plan(${xn||"default"}) \u2192 implement \u2192 verify${h.reset}`),j(`${h.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${xn||"default model"} (category: ${lo})${h.reset}`)));let M=0,I=new Map,_=new Set,Z=new Set,de=new Set,fe=0,Ze=0,uo=0,Sn=0,Me=Date.now(),e0=new Xv(IT),t0=yr,Ke=s.skillLoop?10:1,n0=3*Ke,s0=5*Ke,xu=pu,o0=5*Ke,r0=8*Ke,i0=_y,a0=(me?6:4)*Ke,l0=(me?10:7)*Ke,$a=ea,c0=(me?5:3)*Ke,xr=(me?8:5)*Ke,u0=ky,d0=(me?4:3)*Ke,f0=(me?6:4)*Ke,p0=3*Ke,h0=4*Ke,ks=kn,m0=(me?6:4)*Ke,g0=(me?10:8)*Ke,xs=(me?12:10)*Ke,y0=25,jn=0,w0=10*Ke,$0=15*Ke,Dn=0,Su=5*Ke,qn=0,b0=2*Ke,_0=3,ba=0,fo=10,k0=16,Eu=s.skillLoop?999:o.investigationCap,vu=async()=>{let{hasPendingOrCompletedJobs:we,getPendingJobSummary:$e}=Js();if(we()){if($e()){let Se=Date.now()+45e3;for(process.stderr.write(`${h.cyan} \u23F3 Waiting for background agents to finish\u2026${h.reset}
|
|
1379
|
+
`);$e()&&Date.now()<Se;)await new Promise(Qe=>setTimeout(Qe,500).unref()),Ji(L,S)}Ji(L,S),L.length>0&&Ne(L)}},_a=typeof t=="string"?t.trim():"",Tu=_a.length>0&&/^\s*(analyze|analyse|analysiere|explain|erkläre|describe|beschreib|review|audit|summari[sz]e|zusammenfass|list|liste|what is|what does|wie funktioniert|wie geht|how does|show me|zeig|show the|show all|tell me about|erzähl)/i.test(_a)&&!/\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(_a),He,St=s.maxIterations||(me?ms(Ce):eu);Tu&&(St=Math.min(St,4),j(`${h.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${St}${h.reset}`));let ka=0,Ru=3,xa=!1,Sr=0;e:for(;;){for(xa=!1,He=0;He<St&&!Zi()?.aborted;He++){Ji(L,S);{let w=ut(),y=Vt(S,w),G=M===0?65:78;if(y.percentage>=G){if(_.size>0||me&&Ce!=="plan"){let ee=tT(L,{filesModified:_,currentPhase:me?Ce:null});if(ee){let B=S.findIndex(O=>O._progressSnapshot);B!==-1&&S.splice(B,1);let ie=S.findIndex(O=>O.role==="system");S.splice(ie+1,0,ee)}}let{messages:C,tokensRemoved:P}=un(S,w,M===0);if(P>0&&(S=C,P>50&&console.log(`${h.dim} [auto-compressed \u2014 ~${P} tokens freed, now ${Math.round(Vt(S,w).percentage)}%]${h.reset}`),Ft&&_.size>=3)){let ee=[..._].map(ie=>ie.split("/").pop()).slice(0,10).join(", "),B={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${_.size} files: ${ee}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};S.push(B)}}}if(At&&!rt&&dr<2){dr++;let w={role:"user",content:"[SYSTEM] SSH paused \u2014 you have made many consecutive SSH calls. Synthesize your findings so far: summarize what you learned and what the likely issue is. After your synthesis, SSH will be available again for targeted follow-up commands."};S.push(w),L.push(w),j(`${h.yellow} \u26A0 Pre-call SSH-blocked nudge #${dr} injected \u2014 model told to synthesize${h.reset}`)}At||(dr=0);let $e=!0;M>0&&kT();let Se=null;if(c&&c.isActive())c._paused&&c.resume();else if(!c){let w,y=xT();if(y&&y.total>1){let P=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;w=`Plan step ${y.current}/${y.total}: ${P}`}else w=M>0?`${Dc()} (step ${M+1})`:Dc();let{getPendingJobSummary:G}=Js(),C=G();C&&(w+=` [${C}]`),Se=new Qs(w),Se.start()}let Qe=!0,dt="",En=!1,Ve=new ST,Ot,Sa=Date.now(),Er=!1,Ea=new AbortController,Cu=setInterval(()=>{let w=Date.now()-Sa;if(w>=Gc)Ve._clearCursorLine(),j(`${h.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${h.reset}`),Ea.abort();else if(w>=ay&&!Er){Er=!0,Ve._clearCursorLine();let y=ua.fast?.[eo()],G=z>0?` (retry ${z+1}/${Xi})`:"",C=Math.round((Gc-w)/1e3);j(`${h.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${G}${h.reset}`),y&&y!==Qt()?console.log(`${h.dim} \u{1F4A1} Will auto-switch to ${y} in ~${C}s if no tokens arrive${h.reset}`):console.log(`${h.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${C}s${h.reset}`)}},5e3),Nt="",hn=null;try{let w=wy(ut()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),G=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),C;hr()?C=w.filter(B=>fy.has(B.function.name)):me&&Ce==="plan"?C=w.filter(B=>y.has(B.function.name)):me&&Ce==="verify"?C=w.filter(B=>G.has(B.function.name)):C=w;let P=Zi(),ee=new AbortController;P&&P.addEventListener("abort",()=>ee.abort(),{once:!0}),Ea.signal.addEventListener("abort",()=>ee.abort(),{once:!0}),Ot=await Zg(S,C,{signal:ee.signal,...xn?{model:xn}:{},onThinkingToken:()=>{Sa=Date.now(),Er=!1,pn?.onThinkingToken&&pn.onThinkingToken()},onToken:B=>{if(Sa=Date.now(),Er=!1,pn?.onToken){pn.onToken(B),dt+=B;return}if(dt+=B,!En&&dt.length>400&&dt.length%250<B.length+1){let ie=Qc(dt,3);ie.truncated&&(En=!0,Ve._clearCursorLine?.(),j(`${h.yellow} \u26A0 LLM stream loop detected (${ie.repeatCount}\xD7 repeated) \u2014 suppressing display${h.reset}`))}En||(Nt+=B,process.stdout.isTTY?hn||(hn=setTimeout(()=>{Nt&&Ve&&Ve.push(Nt),Nt="",hn=null},50)):(Ve.push(Nt),Nt=""),Qe&&(c&&!c._paused?c.pause():Se&&Se.stop(),$e||($e=!0),Ve.startCursor(),Qe=!1))}})}catch(w){if(clearInterval(Cu),hn&&(clearTimeout(hn),hn=null),Nt&&Ve&&(Ve.push(Nt),Nt=""),c&&!c._paused&&c.pause(),Se&&Se.stop(),Ve.stopCursor(),Ea.signal.aborted&&!Zi()?.aborted){if(z++,z>Xi){if(ge<1){ge++,Zs("Stale retries exhausted \u2014 last-resort force-compress...",h.yellow);let ie=ut(),{messages:O,tokensRemoved:q}=un(S,ie);S=O,q>50&&j(`${h.dim} [force-compressed \u2014 ~${q} tokens freed]${h.reset}`),z=0,He--;continue}c&&(c.stop(),c=null);let B=await RR();if(B.action==="quit"){l(null),Pe(M,I,_,Z,Me),Ne(L);break}B.action==="switch"&&(qc(`${B.provider}:${B.model}`),console.log(`${h.green} \u2713 Switched to ${B.provider}:${B.model}${h.reset}`)),z=0,He--;continue}let P=z===1?3e3:5e3;if(z>=1&&ke<1){ke++,Zs(`Stale retry ${z}/${Xi} \u2014 force-compressing before retry...`,h.yellow);let B=ut(),{messages:ie,tokensRemoved:O}=un(S,B,!0);if(S=ie,O>0&&O>50&&j(`${h.dim} [force-compressed \u2014 ~${O} tokens freed]${h.reset}`),tR){let q=ua.fast?.[eo()];q&&q!==Qt()&&(qc(`${eo()}:${q}`),console.log(`${h.cyan} \u26A1 Auto-switched to ${q} to avoid further stale timeouts${h.reset}`),console.log(`${h.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${h.reset}`))}}else j(`${h.yellow} \u26A0 Stale retry ${z}/${Xi} \u2014 retrying in ${P/1e3}s...${h.reset}`);let ee=new Qs(`Waiting ${P/1e3}s before retry...`);ee.start(),await new Promise(B=>setTimeout(B,P)),ee.stop(),He--;continue}if(w.name==="AbortError"||w.name==="CanceledError"||w.message?.includes("canceled")||w.message?.includes("aborted")){c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me),Ne(L);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 P=Qt?Qt():"unknown",ee=O=>O.includes(":")&&O.split(":")[0].match(/^[a-z]+$/)&&!O.split(":")[1].includes(":")?O.split(":").slice(1).join(":"):O;_e.add(ee(P));let ie=(()=>{let O=[];process.env.NEX_FALLBACK_MODEL&&O.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:q}=Qo(),F=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let X of F){let K=q(X);K&&!O.includes(K)&&O.push(K)}}catch{}return O.filter(q=>!_e.has(ee(q)))})()[0];if(ie){console.log(`${h.yellow} \u26A0 Model ${P} unavailable (404) \u2014 switching to ${ie}${h.reset}`),qc(ie),Jg(ie),He--;continue}y=`Model not found (404): ${P} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${h.red} \u2717 ${y}${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me),Ne(L);break}else if(w.message.includes("400")){if(ge<3&&Ae<qe){ge++,Ae++;let P=M===0&&ge===1,ee=P||ge===3||ke>0;if(P){ge=3;let q=w.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);Zs(`Bad request (400) \u2014 ${q||"system prompt too large"}, compressing...`,h.yellow)}else Zs(ee?`Bad request (400) \u2014 nuclear compression (attempt ${ge}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${ge}/3)`,h.yellow);let B=ut(),{messages:ie,tokensRemoved:O}=un(S,B,ee);S=ie,O>50&&j(`${h.dim} [force-compressed \u2014 ~${O} tokens freed]${h.reset}`),He--;continue}{let P=S.find(F=>F.role==="system"),ee=S.find(F=>F.role==="user"&&!String(F.content).startsWith("[SYSTEM")&&!String(F.content).startsWith("BLOCKED:")),B=[P,ee].filter(Boolean),{getUsage:ie}=ln(),O=ln().estimateMessagesTokens(B),q=ln().estimateMessagesTokens(S);if(O<q){let F=[],X=L.filter(te=>te.role==="assistant"&&typeof te.content=="string"&&te.content.trim().length>30).slice(-5).map(te=>te.content.trim().slice(0,300).replace(/\n+/g," "));X.length>0&&F.push(`Key findings:
|
|
1380
|
+
`+X.map(te=>`- ${te}`).join(`
|
|
1381
|
+
`));let K=L.filter(te=>te.role==="tool"&&typeof te.content=="string"&&!te.content.startsWith("BLOCKED:")&&te.content.trim().length>10).slice(-5).map(te=>te.content.trim().split(`
|
|
1362
1382
|
`).slice(0,8).join(`
|
|
1363
1383
|
`).slice(0,500));if(K.length>0&&F.push(`Tool results summary:
|
|
1364
|
-
`+K.map(
|
|
1365
|
-
`)),_.size>0){let
|
|
1366
|
-
${JSON.stringify(Pt,null,2)}`)}if(F.length>0){let
|
|
1384
|
+
`+K.map(te=>`- ${te}`).join(`
|
|
1385
|
+
`)),_.size>0){let te=[..._].map(be=>be.split("/").slice(-2).join("/")).join(", ");F.unshift(`Already modified: ${te} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(Z.size>0){let te=[...Z].map(be=>be.split("/").slice(-2).join("/")).join(", ");F.push(`Files already investigated: ${te}`)}let ae=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(ae,JSON.stringify({filesWritten:[..._].map(te=>te.split("/").slice(-2).join("/")),filesRead:[...Z].map(te=>te.split("/").slice(-2).join("/")),isCreationTask:Ft,wipeNumber:ur+1,timestamp:Date.now()},null,2)),F.push(`Session checkpoint: ${ae} \u2014 read it for exact file list`)}catch{}let he=0;{let be=((typeof ee?.content=="string"?ee.content:Array.isArray(ee?.content)?ee.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),Te=[..._],wt=be.filter(tt=>!Te.some(Ca=>Ca.endsWith(tt)||tt.endsWith(Ca.split("/").pop())));he=wt.length;let et=[...L].reverse().find(tt=>tt.role==="tool"&&typeof tt.content=="string"&&!tt.content.startsWith("BLOCKED:")&&tt.content.length>5),Pt={completed:Te.map(tt=>tt.split("/").slice(-2).join("/")),pending:wt.length>0?wt:Te.length===0?["(task files not yet identified)"]:[],lastEdit:et?et.content.trim().slice(0,120):null};(Pt.completed.length>0||Pt.pending.length>0)&&F.unshift(`Work manifest:
|
|
1386
|
+
${JSON.stringify(Pt,null,2)}`)}if(F.length>0){let te={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
1367
1387
|
${F.join(`
|
|
1368
1388
|
`)}
|
|
1369
|
-
Continue implementing the fixes based on these findings.`};B.push(
|
|
1370
|
-
Files modified so far: ${[..._].map(
|
|
1389
|
+
Continue implementing the fixes based on these findings.`};B.push(te)}if(ur>=3){let te=_.size>0?`
|
|
1390
|
+
Files modified so far: ${[..._].map(be=>be.split("/").slice(-1)[0]).join(", ")}`:"";j(`${h.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${h.reset}`),console.log(`${h.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${te?h.dim+te:""}${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me,{suppressHint:!0}),Ne(L);break}S=B,ur++,ys=10+Math.min(he*3,7),au=!0,ra=_.size,ia=!1,qt=0,H=0;for(let[te,be]of kn){let Te=be?.count??be??0;Kc(kn,te,Te>=2?Te:1)}for(let[te]of Ln)dn(kn,te)<2&&Ln.delete(te);Dt.clear(),bs.clear(),Ft&&Zt>0&&(Ut=!0,j(`${h.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Zt} edits already made)${h.reset}`));for(let[te]of ea)Kc(ea,te,xr-1);if(Zs(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${q-O} tokens freed)`,h.yellow),ur>=1){let te=[...kn.entries()].filter(([,et])=>et>=xs).map(([et])=>et.split("/").slice(-1)[0]),be=te.length>0?`
|
|
1371
1391
|
|
|
1372
|
-
Files already at read cap \u2014 use grep_search instead: ${
|
|
1373
|
-
Use /undo to revert changes made during this session.${h.reset}`),c&&(c.stop(),c=null),l(null),
|
|
1374
|
-
`),
|
|
1375
|
-
${
|
|
1392
|
+
Files already at read cap \u2014 use grep_search instead: ${te.join(", ")}`:"",wt={role:"user",content:At&&!rt?"[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}`};L.push(wt),S.push(wt)}ge=0,He--;continue}}y="Context too large to compress \u2014 use /clear to start fresh"}else w.message.includes("500")||w.message.includes("502")||w.message.includes("503")||w.message.includes("504")?y="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(w.message.includes("fetch failed")||w.message.includes("fetch"))&&(y="Network request failed \u2014 please check your internet connection");if(console.log(`${h.red} \u2717 ${y}${h.reset}`),w.message.includes("429")){if(ve++,ve>Wc){console.log(`${h.red} Rate limit: max retries (${Wc}) exceeded. Try again later or use /budget to check your limits.${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me),Ne(L);break e}let P=Math.min(1e4*Math.pow(2,ve-1),12e4),ee=new Qs(`Rate limit \u2014 waiting ${Math.round(P/1e3)}s (retry ${ve}/${Wc})`);ee.start(),await new Promise(B=>setTimeout(B,P)),ee.stop();continue}let G=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return lt().getActiveProviderName()==="ollama"}catch{return!1}})();if(w.message.includes("socket disconnected")||w.message.includes("TLS")||w.message.includes("ECONNRESET")||w.message.includes("ECONNABORTED")||w.message.includes("ETIMEDOUT")||G&&(w.message.includes("500")||w.message.includes("502")||w.message.includes("503")||w.message.includes("504")||w.message.includes("401")||w.message.includes("Unauthorized"))||w.code==="ECONNRESET"||w.code==="ECONNABORTED"){if(W++,W>Hc){console.log(`${h.red} Network error: max retries (${Hc}) exceeded. Check your connection and try again.
|
|
1393
|
+
Use /undo to revert changes made during this session.${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me),Ne(L);break e}let P=Math.min(2e3*Math.pow(2,W-1),3e4),ee=new Qs(`API temporarily unavailable \u2014 retrying in ${Math.round(P/1e3)}s (${W}/${Hc}). Your changes are safe.`);ee.start(),await new Promise(B=>setTimeout(B,P)),ee.stop(),He--;continue}c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me),Ne(L);break}if(clearInterval(Cu),ve=0,W=0,Qe&&(c&&!c._paused&&c.pause(),Se&&Se.stop()),hn&&(clearTimeout(hn),hn=null),Nt&&Ve&&(Ve.push(Nt),Nt=""),dt&&Ve.flush(),W=0,z=0,Ot&&Ot.usage){let w=Ot.usage.prompt_tokens||0,y=Ot.usage.completion_tokens||0;ey(eo(),Qt(),w,y),u+=w+y,c&&c.setStats({tokens:u})}else if(Ot&&!Ot.usage){let w=S.map(C=>typeof C.content=="string"?C.content:Array.isArray(C.content)?C.content.map(P=>typeof P=="string"?P:P.text||"").join(""):"").join(" "),y=ny(w),G=ny(Ot.content||dt||"");ey(eo(),Qt(),y,G),u+=y+G,c&&c.setStats({tokens:u})}let{content:Au,tool_calls:Ss}=Ot,en=Ss,va=!1;if(Array.isArray(Ss)&&Ss.length>0){let w=Ss.filter(y=>y?.function?.name==="ask_user");w.length>0&&(en=[w[0]],va=Ss.length!==1,va&&j(`${h.yellow} \u26A0 ask_user must run alone \u2014 deferring ${Ss.length-1} other tool call(s) until the user replies${h.reset}`))}let vr=Qc(Au||""),Ou=vr.truncated?vr.text:Au;vr.truncated&&j(`${h.yellow} \u26A0 LLM output loop detected (${vr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${h.reset}`);let Tr=UT(Ou||""),Mt=Tr.truncated?Tr.text:Ou;Tr.truncated&&j(`${h.yellow} \u26A0 LLM output loop detected (${Tr.repeatCount}\xD7 repeated window) \u2014 response truncated${h.reset}`);let po={role:"assistant",content:Mt||""};if(en&&en.length>0&&(po.tool_calls=en),L.push(po),S.push(po),Tu&&(Mt||"").trim().length>1500&&_.size===0&&Sn===0){j(`${h.green} \u2713 Analysis-only early exit: ${(Mt||"").length} chars produced, no file changes${h.reset}`),po.tool_calls&&delete po.tool_calls,Pe(M,I,_,Z,Me),Ne(L);break e}if(!rt&&Mt&&en&&en.length>0){let w=zc(Mt);if(w){rt=!0,kt=w.slice(0,120),Bt=0,Ut=!1,Jt=0,j(`${h.yellow} \u26A1 Root cause in model analysis: ${kt} \u2014 fix phase (read budget: 3)${h.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${kt}. Read only the file that needs fixing, then edit it. Do not read other files.`};L.push(y),S.push(y)}}if(!en||en.length===0){let w=(Mt||"").trim().length>0||dt.trim().length>0,y=!1;if(At&&w&&(Vi>=2?j(`${h.yellow} \u26A0 SSH permanently blocked after ${Vi} storm warnings \u2014 no further SSH calls allowed${h.reset}`):(At=!1,qt=fo-4,y=!0)),y&&w){let C=(Mt||"").trim();if(C.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(C.slice(-200))){let ee={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};S.push(ee),L.push(ee);continue}}if(!w&&M>0&&He<eu-1){let C={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};S.push(C),L.push(C);continue}let G=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(w&&He<3&&G.test((Mt||"").slice(0,600)))if(au&&ys<=0||At){j(`${h.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${h.reset}`);let P={role:"user",content:"[SYSTEM] Correct \u2014 remote access is currently limited. Summarize what you have found so far and tell the user exactly what specific information (logs, process list, error output) you need from the server to continue."};S.push(P),L.push(P);continue}else{j(`${h.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${h.reset}`);let P={role:"user",content:"[SYSTEM] You have full tool access. Use your tools to investigate and implement the fix directly \u2014 do not say you cannot use tools. If SSH is needed, use a single targeted command that captures the most relevant information rather than multiple sequential calls."};S.push(P),L.push(P);continue}if(s.skillLoop&&w&&M>3&&Sr<5){let C=(Mt||dt||"").toLowerCase();if(/\b(i.ll stop|stop the|stopped|done with|complet|summar|conclud|no more|finish|end of|that.s all|final|wrapped up|no further|mindful of|reached.*limit|tool call limit|at this point|recommend keep)/.test(C.slice(-600))){Sr=(Sr||0)+1,j(`${h.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Sr}${h.reset}`);let ee={role:"user",content:"[SYSTEM] Do NOT stop. You are in an autonomous experiment loop. The user is away and expects you to keep running experiments indefinitely until they interrupt with Ctrl+C. Start the next experiment NOW: hypothesize a new change, checkpoint, edit, run, measure, keep or revert. Think harder \u2014 try a completely different optimization approach."};S.push(ee),L.push(ee);continue}}if(pr()&&!s.skillLoop&&!me&&(_.size>0||Sn>0)&&w&&M>=2){j(`${h.green} \u2713 Headless early exit: ${_.size} file(s) modified (+ ${Sn} bash writes), text response received${h.reset}`),Pe(M,I,_,Z,Me),Ne(L);break e}if(me&&Ce==="plan"&&In>=2){j(`${h.cyan} \u21B3 Plan phase: ${In} consecutive blocks \u2014 auto-advancing to implement${h.reset}`),In=0;let C=await ar("implement","[auto-advance: task only requires direct action]");if(C){L.push(C),S.push(C),He=0,St=ms("implement");continue}}if(me&&w){let C=(Mt||dt||"").trim();if(Ce==="plan"){let P=/\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,ee=xy(C,kn).length===0,B=mr.size>0,ie=gr.size>0,O=C.length>1500;if(pr()&&ee&&!B&&!ie&&!O&&P.test(C)){j(`${h.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${h.reset}
|
|
1394
|
+
`),Pe(M,I,_,Z,Me),Ne(L);break e}let q=await ar("implement",C);if(q){L.push(q),S.push(q),He=0,St=ms("implement");continue}}else if(Ce==="implement"&&(_.size>0||Sn>0)){let P=L.find(ie=>ie.role==="user"),ee=typeof P?.content=="string"?P.content:"",B=await ar("verify",C,_,ee);if(B){L.push(B),S.push(B),He=0,St=Math.min(ms("verify")+Math.max(0,(_.size-2)*2),20);continue}}else if(Ce==="verify"){let P=/\bPASS\b/i.test(C.slice(0,500)),B=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(C.slice(0,500));if(B&&oo<3){oo++;let ie={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
|
|
1395
|
+
${C.slice(0,400)}
|
|
1376
1396
|
|
|
1377
|
-
Fix the identified issues. This is attempt ${
|
|
1397
|
+
Fix the identified issues. This is attempt ${oo}/3.`};Ce="implement",xn=Zc("implement",lo),L.push(ie),S.push(ie),He=0,St=ms("implement"),j(`${h.yellow} \u21B3 Verify \u2192 implement loop-back #${oo} (issues found)${h.reset}`);continue}if(!B&&(!P||wr===0)){if(ro<2){ro++;let ie=[];wr===0&&ie.push("run at least one verification tool"),P||ie.push("end your report with PASS or FAIL");let O={role:"user",content:`[SYSTEM] Verification is incomplete: ${ie.join(" and ")}. Do not stop yet. Re-read the modified files and/or run tests or linters, then respond with PASS or FAIL.`};L.push(O),S.push(O),j(`${h.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${ro}/2)${h.reset}`);continue}j(`${h.yellow} \u26A0 Verify phase completion accepted without full markers after ${ro} nudges${h.reset}`)}if(j(`${h.green} \u2713 Verification phase complete${B?" (loop-back exhausted)":" (PASS)"}${h.reset}`),!B){Pe(M,I,_,Z,Me),Ne(L),Ki(L);break e}}}if(hr()&&w&&M===0)if(na++,na>2)j(`${h.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${h.reset}`);else{let C={role:"user",content:`[SYSTEM] You wrote a plan without reading any files. This plan may be based on incorrect assumptions (wrong database type, wrong file structure, etc.).
|
|
1378
1398
|
|
|
1379
|
-
MANDATORY: Use read_file, glob, or grep to investigate the actual codebase first. Read at least the relevant module file and route file before writing the plan.`};
|
|
1380
|
-
${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${
|
|
1381
|
-
`),
|
|
1399
|
+
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.`};L.push(C),S.push(C),j(`${h.yellow} \u26A0 Plan rejected (${na}/2): no files read \u2014 forcing investigation${h.reset}`);continue}if(hr()&&w){let C=(Mt||dt||"").trim();$T(C),nR(C);let P=bT(C);if(P.length>0){let ee=L.find(q=>q.role==="user"),B=typeof ee?.content=="string"?ee.content.slice(0,120):"Task";_T(B,P);let ie=P.length===1?"step":"steps",O=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:q,startExecution:F,setPlanMode:X}=Hi();process.stdout.write(`
|
|
1400
|
+
${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${P.length} ${ie})${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.yellow}[E]${h.reset}${h.dim}dit${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let K=process.stdin.isRaw,ae=await new Promise(he=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",te=>{try{process.stdin.setRawMode(K||!1)}catch{}let be=te.toString().toLowerCase()[0]||"\r";he(be)})});if(process.stdout.write(`
|
|
1401
|
+
`),ae==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(ae==="e")console.log(`${h.yellow}Type /plan edit to open in editor, or give feedback.${h.reset}`);else if(q()){F(),X(!1),ou(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing ${P.length} ${ie}...`);let he=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1382
1402
|
|
|
1383
1403
|
Implement the following plan step by step. All tools are now available.
|
|
1384
1404
|
|
|
1385
|
-
${
|
|
1386
|
-
${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${
|
|
1405
|
+
${C}`;L.push({role:"user",content:he}),S.push({role:"user",content:he}),O=!0}}else console.log(`
|
|
1406
|
+
${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${P.length} ${ie} extracted).${h.reset} Type ${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ${h.reset}${h.cyan}/plan edit${h.reset}${h.dim} to review.${h.reset}`);if(O){c&&(c.stop(),c=null),He--;continue}}else{let ee=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:B,startExecution:ie,setPlanMode:O}=Hi();process.stdout.write(`
|
|
1387
1407
|
${h.cyan}${h.bold}Plan ready.${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let q=process.stdin.isRaw,F=await new Promise(X=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",K=>{try{process.stdin.setRawMode(q||!1)}catch{}X(K.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
|
|
1388
|
-
`),F==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(B()){
|
|
1408
|
+
`),F==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(B()){ie(),O(!1),ou(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing...`);let K=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1389
1409
|
|
|
1390
1410
|
Implement the following plan step by step. All tools are now available.
|
|
1391
1411
|
|
|
1392
|
-
${getPlanContent()||Ot.content}`;
|
|
1393
|
-
${h.cyan}${h.bold}Plan ready.${h.reset} ${h.dim}Type ${h.reset}${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ask follow-up questions to refine.${h.reset}`);if(
|
|
1394
|
-
${B}`),P.push({role:"user",content:T},{role:"assistant",content:B}))}catch{}Ae(P),qi(P),await hu();return}N++,sa++,N>=1&&(ye=!1);for(let w of fn){let y=w.function.name;L.set(y,(L.get(y)||0)+1)}if(N>=30&&!Gg){Gg=!0,j(`${h.yellow} \u26A0 Tool budget warning: ${N} tool calls used \u2014 nudging model to wrap up${h.reset}`);let w={role:"user",content:"[SYSTEM] \u26A0 You have used "+N+" tool calls. This is approaching the quality threshold (40). Wrap up NOW: write your final summary and stop. Do NOT run additional verification commands (git status, git diff, git log) \u2014 your changes are already committed and verified. Further tool calls will hurt session quality."};P.push(w),S.push(w)}let we=await Promise.all(fn.map(w=>AT(w)));{let w=Vt(S,ut()),y=w.percentage,G=we.some(B=>B.canExecute&&B.fnName==="read_file"&&!B.args?.line_end),T=we.filter(B=>B.canExecute&&B.fnName==="read_file"&&B.args?.path&&ln(_s,B.args.path)>=1&&!B.args?.line_start).map(B=>B.args.path.split("/").slice(-2).join("/")),O=T.length>0;if(y>=70&&G&&ua<70||y>=85&&ua<85||O){ua=y;let B=y>=85?"URGENT":"WARNING",oe;O?(B="WARNING",oe=`Full-file read of ${T.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):G?oe=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:oe="Use targeted reads (line_start/line_end) to save space.";let R={role:"user",content:`[SYSTEM ${B}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${oe}`};if(P.push(R),S.push(R),y>=85){let q=O?` (re-read of: ${T.join(", ")})`:"";j(`${h.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${q}${h.reset}`)}}}let ga=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let G=ln(_s,y),T=ga.get(y)||0,O=G+T,Z=w.args?.line_start!=null,B=Dt.get(y)||0,oe=B>0,R=2;if(O>=bs){let q=y.split("/").slice(-2).join("/"),F=(ws.get(y)||0)+1;if(ws.set(y,F),F===1)j(`${h.red} \u2716 Blocked: "${q}" read ${O}\xD7 \u2014 hard cap (${bs}) reached${h.reset}`);else if(F===2){j(`${h.red} \u2716 Escalated block: "${q}" \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${y}") and tried again anyway. This file has reached its read cap (${bs}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};P.push(X),S.push(X)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${O}\xD7 (hard cap: ${bs}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:w.callId}}else if(O>=1&&Z)if(oe&&B<=R){let q=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Targeted re-read: "${q}" (line_start=${w.args.line_start}) \u2014 edit recovery #${B}${h.reset}`),Dt.set(y,B-1)}else if(oe&&B>R){let q=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Edit recovery blocked: "${q}" \u2014 ${R} recovery reads already used. Use grep to find the exact line numbers, then retry.${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${R} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:w.callId}}else{let q=parseInt(w.args.line_start,10)||1,F=parseInt(w.args.line_end,10)||q+350,X=Ln.get(y)||[],K=!1;for(let[re,he]of X){let Q=Math.max(q,re),_e=Math.min(F,he);if(_e>Q){let Te=_e-Q,wt=F-q||1,Qe=he-re||1,Pt=Te/Qe>=.7&&Te/wt<.7,et=F-q<=Qy;if(Te>=wt||!et&&(Te/wt>=.7||Te/Qe>=.7)){let wa=y.split("/").slice(-2).join("/"),Su=`${y}:${q}-${F}`,xs=(na.get(Su)||0)+1;if(na.set(Su,xs),j(Pt?`${h.red} \u2716 Blocked superread: "${wa}" lines ${q}-${F} subsumes already-read ${re}-${he} \u2014 use line_start=${he+1} to skip known content (block #${xs})${h.reset}`:`${h.red} \u2716 Blocked duplicate read: "${wa}" lines ${q}-${F} (\u226570% overlap with lines ${re}-${he} already in context, block #${xs})${h.reset}`),xs>=2){j(`${h.red} \u2716 Escalated range-block: "${wa}" lines ${q}-${F} \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let Eu={role:"user",content:Pt?`[SYSTEM] Read blocked ${xs}\xD7 for read_file("${y}", lines ${q}-${F}). Lines ${re}-${he} were already read. Use line_start=${he+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${xs}\xD7 for read_file("${y}", lines ${q}-${F}). Lines ${re}-${he} were already read and will NOT change. Use grep_search to find specific content instead.`};P.push(Eu),S.push(Eu)}w.canExecute=!1,w.errorResult={role:"tool",content:Pt?`BLOCKED: read_file("${y}", lines ${q}-${F}) re-reads lines ${re}-${he} already in context. Use line_start=${he+1} to read only the new content beyond line ${he}.`:`BLOCKED: read_file("${y}", lines ${q}-${F}) is a duplicate \u2014 lines ${re}-${he} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:w.callId},K=!0;break}}}if(!K){let re=X.length,he=2;if(re>=3){let _e=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked file-scroll: "${_e}" \u2014 ${re} sections already read. Use grep to find specific content.${h.reset}`);let Te=ln(ca,y)>=gr;w.canExecute=!1,w.errorResult={role:"tool",content:Te?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${re} different sections of this file (file-scroll pattern). Grep is also exhausted. The content you need is already in your context \u2014 work with what you have.`:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${re} different sections of this file (file-scroll pattern). You have seen most of this file. Use grep_search to find the exact lines you need instead of continuing to scroll.`,tool_call_id:w.callId}}else re>=he&&(w._scrollWarn={sectionCount:re+1,path:y})}}else if(O>=1){let q=Dt.get(y)||0;if(q>0){let F=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Full re-read: "${F}" \u2014 test-failure recovery (${q} remaining)${h.reset}`);let X=q-1;X<=0?Dt.delete(y):Dt.set(y,X)}else{let F=y.split("/").slice(-2).join("/"),X=(ws.get(y)||0)+1;if(ws.set(y,X),X===1)j(`${h.red} \u2716 Blocked unbounded re-read: "${F}" \u2014 already in context. Use line_start/line_end for specific sections.${h.reset}`);else if(X===2){j(`${h.red} \u2716 Escalated block: "${F}" \u2014 model ignored unbounded re-read block, injecting system warning${h.reset}`);let K={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};P.push(K),S.push(K)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${O}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:w.callId}}}w.canExecute&&ga.set(y,(ga.get(y)||0)+1)}if(Pn>=3)for(let w of we)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(j(`${h.red} \u2716 Blocked ${w.fnName} \u2014 ${Pn} consecutive file-not-found errors, must search first${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${Pn} consecutive "File not found" errors. You must call search_files or glob_files to locate the correct path before reading or editing. Do not guess file paths.`,tool_call_id:w.callId}));for(let w of we){if(!w.canExecute||w.fnName!=="bash")continue;let y=(w.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){j(`${h.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:w.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(j(`${h.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:w.callId})}for(let w of we)w.canExecute&&(w.fnName!=="ssh_exec"&&w.fnName!=="bash"||/\bsed\s+-n\b/.test(w.args?.command||"")&&(j(`${h.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:w.callId}));for(let w of we){if(!w.canExecute||w.fnName!=="write_file")continue;let y=w.args?.path,G=w.args?.content||"";if(y)try{let T=require("fs"),O=require("path").resolve(process.cwd(),y);if(T.existsSync(O)){let Z=T.statSync(O).size,B=Buffer.byteLength(G,"utf8"),oe=Z>0?B/Z:1;if(oe<.6&&Z>200){let R=y.split("/").slice(-2).join("/");console.log(`${h.red} \u2716 write_file shrink guard: "${R}" would shrink to ${Math.round(oe*100)}% of original \u2014 likely context loss${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(oe*100)}% of current file size (${Z} \u2192 ${B} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:w.callId}}}}catch{}}let _u=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let G=_u.get(y)||0,T=ln(ca,y)+G,O=ln(_s,y)>=1,Z=O?Math.min(3,gr):gr;if(T>=Z){let B=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked grep: "${B}" grepped ${T}\xD7 with different patterns \u2014 flood threshold exceeded${h.reset}`);let oe=ln(_s,y),R=oe>=bs;if(R){let q={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${oe} sections and tried ${T} grep patterns. Do NOT attempt to read or grep this file again. The content you need is already in your conversation context \u2014 scroll back to find it, or proceed with what you know.`};P.push(q),S.push(q),j(`${h.red} \u2716 Deadlock detected: "${B}" \u2014 both read and grep blocked, injecting deadlock-break${h.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:R?`BLOCKED: grep("${y}") denied \u2014 ${T} patterns already tried AND reads are also exhausted. The content is already in your context. Do not attempt to read or grep this file again.`:O?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${T} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${T} patterns already tried. Work with the grep results already in your context.`,tool_call_id:w.callId}}w.canExecute&&_u.set(y,G+1)}let r0=5,bu=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let G=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),T=bu.get(G)||0,O=ln(du,G)+T;O>=r0&&(j(`${h.yellow} \u26A0 Blocked ssh_exec: same command run ${O}\xD7 \u2014 result already in context${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${O} times and the output is in your context. Use existing results, try a different command, or run it as a local bash call: bash("ssh user@host 'your command'").`,tool_call_id:w.callId}),w.canExecute&&bu.set(G,T+1)}if(At){let w=we.filter(T=>T.canExecute&&T.fnName==="ssh_exec"),y=we.some(T=>T.canExecute&&T.fnName!=="ssh_exec"),G=I&&H<3;if(w.length>0&&!y&&G&&Xi<1)At=!1,Xi++,qt=Math.max(0,io-2),j(`${h.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Xi}/1)]${h.reset}`);else for(let T of w)T.canExecute=!1,T.errorResult={role:"tool",content:ot?`BLOCKED: ssh_exec denied \u2014 SSH paused (${io}+ calls). Root cause is known (${bt}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${io}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary. For one-off lookups use bash("ssh user@host 'cmd'") instead.`,tool_call_id:T.callId}}if(I&&H<3&&!At){for(let w of we)if(w.canExecute&&["bash","read_file","find_files"].includes(w.fnName)){H++;{let y=ut(),{messages:G}=an(S,y);S=G}j(`${h.yellow} \u26A0 Server-local guard: blocking local ${w.fnName} \u2014 use ssh_exec on 94.130.37.43${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:w.callId};break}}if(!$e&&Ut&&Ft&&Zt>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of we)y.canExecute&&w.includes(y.fnName)&&(j(`${h.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(ms>=0){let w=we.filter(y=>y.canExecute).length;if(w>0&&(ms-=w,ms<0))if(!Ji&&_.size>Vi){Ji=!0,ms=5,j(`${h.green} \u2713 Post-wipe progress detected (${_.size-Vi} files modified) \u2014 granting 5 bonus tool calls${h.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};P.push(y),S.push(y)}else{j(`${h.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${h.reset}`);for(let G of we)G.canExecute&&(G.canExecute=!1,G.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:G.callId});let y={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};P.push(y),S.push(y)}}let i0=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open","skill_ar_run_experiment","skill_ar_run_benchmark","skill_ar_checkpoint","skill_ar_revert","skill_ar_log_experiment","skill_ar_extract_metric"]);for(let w of we){if(!w.canExecute||i0.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),G=`${w.fnName}|${y}`,T=ln(zc,G);T>=2?(j(`${h.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${T+1}\xD7 with identical args${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName}() with these exact arguments has already been called ${T}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:w.callId}):T===1&&j(`${h.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${h.reset}`),hs(zc,G)}{let w=new Set;for(let y of we){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let G=y.args?.path;G&&(de.has(G)||w.has(G)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${G}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:y.callId},j(`${h.yellow} \u26A0 Map-first gate: blocked re-edit of "${G.split("/").slice(-1)[0]}" \u2014 re-read required${h.reset}`)):w.add(G))}}let lo=c?{skipSpinner:!0,skipSummaries:!0}:{},a0=we.some(w=>w.fnName==="ask_user"),ku=!lo.skipSummaries&&!ye,br=null,ks=null;ku&&!a0?(ye=!0,lo.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(ks=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Di(we,N,!1,"blink")),br=!0):un||process.stdout.write(Di(we,N,!1)+`
|
|
1395
|
-
`)
|
|
1412
|
+
${getPlanContent()||Ot.content}`;L.push({role:"user",content:K}),S.push({role:"user",content:K}),ee=!0}}else console.log(`
|
|
1413
|
+
${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(ee){c&&(c.stop(),c=null),He--;continue}}}if(c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me),Ft&&_.size>=3){let C=[..._].map(O=>O.split("/").pop()).slice(0,8).join(", "),P=[..._].some(O=>O.endsWith("package.json")),ee=[..._].some(O=>O.endsWith("requirements.txt")),B=[..._].some(O=>O.endsWith("package-lock.json")||O.endsWith("yarn.lock")||O.endsWith("pnpm-lock.yaml")),ie=P&&!B?"npm install not yet run":ee?"pip install not yet run":null;fr=`[Previous session created ${_.size} files: ${C}`+(ie?` \u2014 ${ie}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Ft&&!lu&&M>0){let C=[..._].some(K=>K.endsWith("package.json")),P=[..._].some(K=>K.endsWith("requirements.txt")||K.endsWith("Pipfile")||K.endsWith("pyproject.toml")),ee=[..._].some(K=>K.endsWith("package-lock.json")||K.endsWith("yarn.lock")||K.endsWith("pnpm-lock.yaml")),B=L.flatMap(K=>{let ae=Array.isArray(K.tool_calls)?K.tool_calls:[],he=Array.isArray(K.content)?K.content.filter(te=>te?.type==="tool_use"):[];return[...ae,...he]}).filter(K=>{let ae=K.function?.name||K.name||"";return ae==="bash"||ae==="Bash"}).map(K=>{try{let ae=K.function?.arguments??K.input??{};return(typeof ae=="string"?JSON.parse(ae):ae)?.command||""}catch{return""}}),ie=B.some(K=>/pip\s+install|python\s+-m\s+venv/.test(K)),O=B.some(K=>/npm\s+install/.test(K)),F=[..._].some(K=>/\/App\.(js|ts|jsx|tsx)$/.test(K))&&!C&&!O;if(P&&!ie||C&&!ee&&!O||F){lu=!0;let K=[];P&&!ie&&K.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),F?K.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):C&&!ee&&!O&&K.push("npm install");let ae=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${K.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;j(`${h.dim} [post-creation] bootstrapping environment (${K.join(", ")})${h.reset}`),L.push({role:"user",content:ae}),S.push({role:"user",content:ae});continue}}if(M>0&&!s._isSummaryTurn&&cT(Mt))try{j(`${h.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${h.reset}`);let C=_.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.",P=[...S,{role:"user",content:C}],B=((await Zg(P,[],{}))?.content||"").trim();B&&(console.log(`
|
|
1414
|
+
${B}`),L.push({role:"user",content:C},{role:"assistant",content:B}))}catch{}Ne(L),Ki(L),await vu();return}M++,fa++,M>=1&&($e=!1);for(let w of en){let y=w.function.name;I.set(y,(I.get(y)||0)+1)}if(M>=30&&!uy){uy=!0,j(`${h.yellow} \u26A0 Tool budget warning: ${M} tool calls used \u2014 nudging model to wrap up${h.reset}`);let w={role:"user",content:"[SYSTEM] \u26A0 You have used "+M+" 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."};L.push(w),S.push(w)}let ye=await Promise.all(en.map(w=>sR(w)));{let w=Vt(S,ut()),y=w.percentage,G=ye.some(B=>B.canExecute&&B.fnName==="read_file"&&!B.args?.line_end),C=ye.filter(B=>B.canExecute&&B.fnName==="read_file"&&B.args?.path&&dn(ks,B.args.path)>=1&&!B.args?.line_start).map(B=>B.args.path.split("/").slice(-2).join("/")),P=C.length>0;if(y>=70&&G&&ba<70||y>=85&&ba<85||P){ba=y;let B=y>=85?"URGENT":"WARNING",ie;P?(B="WARNING",ie=`Full-file read of ${C.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):G?ie=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:ie="Use targeted reads (line_start/line_end) to save space.";let O={role:"user",content:`[SYSTEM ${B}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${ie}`};if(L.push(O),S.push(O),y>=85){let q=P?` (re-read of: ${C.join(", ")})`:"";j(`${h.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${q}${h.reset}`)}}}let Ta=new Map;for(let w of ye){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let G=dn(ks,y),C=Ta.get(y)||0,P=G+C,ee=w.args?.line_start!=null,B=Dt.get(y)||0,ie=B>0,O=2;if(P>=xs){let q=y.split("/").slice(-2).join("/"),F=(bs.get(y)||0)+1;if(bs.set(y,F),F===1)j(`${h.red} \u2716 Blocked: "${q}" read ${P}\xD7 \u2014 hard cap (${xs}) reached${h.reset}`);else if(F===2){j(`${h.red} \u2716 Escalated block: "${q}" \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${y}") and tried again anyway. This file has reached its read cap (${xs}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};L.push(X),S.push(X)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${P}\xD7 (hard cap: ${xs}). 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(P>=1&&ee)if(ie&&B<=O){let q=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Targeted re-read: "${q}" (line_start=${w.args.line_start}) \u2014 edit recovery #${B}${h.reset}`),Dt.set(y,B-1)}else if(ie&&B>O){let q=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Edit recovery blocked: "${q}" \u2014 ${O} 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 (${O} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:w.callId}}else{let q=parseInt(w.args.line_start,10)||1,F=parseInt(w.args.line_end,10)||q+350,X=Ln.get(y)||[],K=!1;for(let[ae,he]of X){let te=Math.max(q,ae),be=Math.min(F,he);if(be>te){let Te=be-te,wt=F-q||1,et=he-ae||1,Pt=Te/et>=.7&&Te/wt<.7,tt=F-q<=y0;if(Te>=wt||!tt&&(Te/wt>=.7||Te/et>=.7)){let Aa=y.split("/").slice(-2).join("/"),Iu=`${y}:${q}-${F}`,vs=(da.get(Iu)||0)+1;if(da.set(Iu,vs),j(Pt?`${h.red} \u2716 Blocked superread: "${Aa}" lines ${q}-${F} subsumes already-read ${ae}-${he} \u2014 use line_start=${he+1} to skip known content (block #${vs})${h.reset}`:`${h.red} \u2716 Blocked duplicate read: "${Aa}" lines ${q}-${F} (\u226570% overlap with lines ${ae}-${he} already in context, block #${vs})${h.reset}`),vs>=2){j(`${h.red} \u2716 Escalated range-block: "${Aa}" lines ${q}-${F} \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let ju={role:"user",content:Pt?`[SYSTEM] Read blocked ${vs}\xD7 for read_file("${y}", lines ${q}-${F}). Lines ${ae}-${he} were already read. Use line_start=${he+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${vs}\xD7 for read_file("${y}", lines ${q}-${F}). Lines ${ae}-${he} were already read and will NOT change. Use grep_search to find specific content instead.`};L.push(ju),S.push(ju)}w.canExecute=!1,w.errorResult={role:"tool",content:Pt?`BLOCKED: read_file("${y}", lines ${q}-${F}) re-reads lines ${ae}-${he} already in context. Use line_start=${he+1} to read only the new content beyond line ${he}.`:`BLOCKED: read_file("${y}", lines ${q}-${F}) is a duplicate \u2014 lines ${ae}-${he} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:w.callId},K=!0;break}}}if(!K){let ae=X.length,he=2;if(ae>=3){let be=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked file-scroll: "${be}" \u2014 ${ae} sections already read. Use grep to find specific content.${h.reset}`);let Te=dn($a,y)>=xr;w.canExecute=!1,w.errorResult={role:"tool",content:Te?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${ae} 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 ${ae} 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 ae>=he&&(w._scrollWarn={sectionCount:ae+1,path:y})}}else if(P>=1){let q=Dt.get(y)||0;if(q>0){let F=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Full re-read: "${F}" \u2014 test-failure recovery (${q} remaining)${h.reset}`);let X=q-1;X<=0?Dt.delete(y):Dt.set(y,X)}else{let F=y.split("/").slice(-2).join("/"),X=(bs.get(y)||0)+1;if(bs.set(y,X),X===1)j(`${h.red} \u2716 Blocked unbounded re-read: "${F}" \u2014 already in context. Use line_start/line_end for specific sections.${h.reset}`);else if(X===2){j(`${h.red} \u2716 Escalated block: "${F}" \u2014 model ignored unbounded re-read block, injecting system warning${h.reset}`);let K={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};L.push(K),S.push(K)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${P}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:w.callId}}}w.canExecute&&Ta.set(y,(Ta.get(y)||0)+1)}if(Pn>=3)for(let w of ye)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(j(`${h.red} \u2716 Blocked ${w.fnName} \u2014 ${Pn} consecutive file-not-found errors, must search first${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${Pn} consecutive "File not found" errors. You must call search_files or glob_files to locate the correct path before reading or editing. Do not guess file paths.`,tool_call_id:w.callId}));for(let w of ye){if(!w.canExecute||w.fnName!=="bash")continue;let y=(w.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){j(`${h.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:w.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(j(`${h.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:w.callId})}for(let w of ye)w.canExecute&&(w.fnName!=="ssh_exec"&&w.fnName!=="bash"||/\bsed\s+-n\b/.test(w.args?.command||"")&&(j(`${h.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:w.callId}));for(let w of ye){if(!w.canExecute||w.fnName!=="write_file")continue;let y=w.args?.path,G=w.args?.content||"";if(y)try{let C=require("fs"),P=require("path").resolve(process.cwd(),y);if(C.existsSync(P)){let ee=C.statSync(P).size,B=Buffer.byteLength(G,"utf8"),ie=ee>0?B/ee:1;if(ie<.6&&ee>200){let O=y.split("/").slice(-2).join("/");console.log(`${h.red} \u2716 write_file shrink guard: "${O}" would shrink to ${Math.round(ie*100)}% of original \u2014 likely context loss${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(ie*100)}% of current file size (${ee} \u2192 ${B} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:w.callId}}}}catch{}}let Nu=new Map;for(let w of ye){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let G=Nu.get(y)||0,C=dn($a,y)+G,P=dn(ks,y)>=1,ee=P?Math.min(3,xr):xr;if(C>=ee){let B=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked grep: "${B}" grepped ${C}\xD7 with different patterns \u2014 flood threshold exceeded${h.reset}`);let ie=dn(ks,y),O=ie>=xs;if(O){let q={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${ie} sections and tried ${C} 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.`};L.push(q),S.push(q),j(`${h.red} \u2716 Deadlock detected: "${B}" \u2014 both read and grep blocked, injecting deadlock-break${h.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:O?`BLOCKED: grep("${y}") denied \u2014 ${C} 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.`:P?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${C} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${C} patterns already tried. Work with the grep results already in your context.`,tool_call_id:w.callId}}w.canExecute&&Nu.set(y,G+1)}let x0=5,Mu=new Map;for(let w of ye){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let G=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),C=Mu.get(G)||0,P=dn(xu,G)+C;P>=x0&&(j(`${h.yellow} \u26A0 Blocked ssh_exec: same command run ${P}\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 ${P} 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&&Mu.set(G,C+1)}if(At){let w=ye.filter(C=>C.canExecute&&C.fnName==="ssh_exec"),y=ye.some(C=>C.canExecute&&C.fnName!=="ssh_exec"),G=D&&H<3;if(w.length>0&&!y&&G&&oa<1)At=!1,oa++,qt=Math.max(0,fo-2),j(`${h.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${oa}/1)]${h.reset}`);else for(let C of w)C.canExecute=!1,C.errorResult={role:"tool",content:rt?`BLOCKED: ssh_exec denied \u2014 SSH paused (${fo}+ calls). Root cause is known (${kt}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${fo}+ 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:C.callId}}if(D&&H<3&&!At){for(let w of ye)if(w.canExecute&&["bash","read_file","find_files"].includes(w.fnName)){H++;{let y=ut(),{messages:G}=un(S,y);S=G}j(`${h.yellow} \u26A0 Server-local guard: blocking local ${w.fnName} \u2014 use ssh_exec on 94.130.37.43${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:w.callId};break}}if(!me&&Ut&&Ft&&Zt>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of ye)y.canExecute&&w.includes(y.fnName)&&(j(`${h.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(ys>=0){let w=ye.filter(y=>y.canExecute).length;if(w>0&&(ys-=w,ys<0))if(!ia&&_.size>ra){ia=!0,ys=5,j(`${h.green} \u2713 Post-wipe progress detected (${_.size-ra} 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."};L.push(y),S.push(y)}else{j(`${h.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${h.reset}`);for(let G of ye)G.canExecute&&(G.canExecute=!1,G.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:G.callId});let y={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};L.push(y),S.push(y)}}let S0=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open","skill_ar_run_experiment","skill_ar_run_benchmark","skill_ar_checkpoint","skill_ar_revert","skill_ar_log_experiment","skill_ar_extract_metric"]);for(let w of ye){if(!w.canExecute||S0.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),G=`${w.fnName}|${y}`,C=dn(ru,G);C>=2?(j(`${h.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${C+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 ${C}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:w.callId}):C===1&&j(`${h.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${h.reset}`),gs(ru,G)}{let w=new Set;for(let y of ye){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let G=y.args?.path;G&&(de.has(G)||w.has(G)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${G}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:y.callId},j(`${h.yellow} \u26A0 Map-first gate: blocked re-edit of "${G.split("/").slice(-1)[0]}" \u2014 re-read required${h.reset}`)):w.add(G))}}let ho=c?{skipSpinner:!0,skipSummaries:!0}:{},E0=ye.some(w=>w.fnName==="ask_user"),Pu=!ho.skipSummaries&&!$e,Rr=null,Es=null;if(Pu&&!E0){if($e=!0,ho.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(Es=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let w=or(ye,M,!1,"blink"),y=or(ye,M,!1);process.stdout.write(`${M>1?`
|
|
1415
|
+
`:""}${w}`),no=y,so=Date.now(),Rr=!0}else if(!pn){let w=or(ye,M,!1);Vc(w,no,so)||(process.stdout.write(`${M>1?`
|
|
1416
|
+
`:""}${w}
|
|
1417
|
+
`),no=w,so=Date.now())}}else Pu&&($e=!0,ho.skipSpinner=!0);c&&c._paused&&c.resume();let Cr=null;if(Rr&&process.stdout.isTTY&&ye.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();Cr=setInterval(()=>{let G=Math.round((Date.now()-y)/1e3);if(G>=3){let C=`${or(ye,M,!1,"blink")} ${h.dim}[${G}s]${h.reset}`;Es!==null?process.stdout.write(`\x1B[${Es};1H\x1B[2K${C}`):process.stdout.write(`\r\x1B[2K${C}`)}},1e3)}let{results:at,summaries:v0}=await aR(ye,!0,{...ho,skipSummaries:!0});if(va){let w={role:"user",content:"[SYSTEM] ask_user is exclusive. Wait for the user's answer before making any other tool calls."};L.push(w),S.push(w)}if(Cr&&(clearInterval(Cr),Cr=null),Rr){Rr=null;let w=or(ye,M,!1);Vc(w,no,so)||(Es!==null?process.stdout.write(`\x1B[${Es};1H\x1B[2K${w}
|
|
1396
1418
|
`):process.stdout.write(`\r\x1B[2K${w}
|
|
1397
|
-
`),
|
|
1398
|
-
`)[0],
|
|
1399
|
-
Do NOT re-read \u2014 apply the edit directly with edit_file.`};
|
|
1400
|
-
`).map(X=>X.trim()).find(X=>X.length>0&&!X.startsWith("**")&&(X.startsWith("EXIT")||/^[\w./-]+:\s/.test(X)||X.startsWith("bash:")||X.startsWith("sh:")))??"";if(F){if(F===
|
|
1401
|
-
`).map(X=>X.trim()).find(X=>X.length>0&&(X.startsWith("EXIT")||/^[\w./-]+:\s/.test(X)||X.startsWith("bash:")||X.startsWith("sh:")))??"";if(F){if(F===
|
|
1402
|
-
`);for(let q of
|
|
1403
|
-
`);for(let K of X)(K.startsWith("/")&&!K.includes(" ")||!K.includes(":")&&!K.startsWith("["))&&
|
|
1404
|
-
...(truncated ${
|
|
1405
|
-
`),c&&(c.stop(),c=null),l(null),
|
|
1406
|
-
${h.yellow}\u26A0 Max iterations reached.${h.reset}`),await
|
|
1407
|
-
`),await t(a,i,u)}catch(c){if(s=c,!
|
|
1408
|
-
`),await t(a,i,d)}catch(f){if(s=f,!
|
|
1419
|
+
`),no=w,so=Date.now()),Es=null}if(!ho.skipSummaries){let w=v0.filter((C,P)=>!(ye[P]&&ye[P].fnName==="ask_user"));for(let C of w)Vc(C,nu,su)||(console.log(C),nu=C,su=Date.now());let y=ye.filter(C=>C&&C.fnName!=="ask_user").map(C=>C.fnName),G=e0.record(0,y,Z,_);G&&jT(G)}for(let w of ye){if(w.canExecute||!w.errorResult)continue;let y=typeof w.errorResult.content=="string"?w.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:")||y.startsWith("PLAN PHASE:"))&&(Dn++,Dn>=Su)){j(`${h.red} \u2716 Loop abort: ${Dn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me,{suppressHint:!0}),Ne(L);return}}let Ra=!1;for(let w=0;w<ye.length;w++){let y=ye[w];if(!y.canExecute)continue;let G=at[w].content,C=G.split(`
|
|
1420
|
+
`)[0],P=!C.startsWith("ERROR")&&!C.startsWith("CANCELLED")&&!C.startsWith("Command failed")&&!C.startsWith("EXIT");if(!P&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&C.includes("old_text not found")){let O=Dt.get(y.args.path)||0;Dt.set(y.args.path,O+1)}if(!P&&y.fnName==="bash"&&yr.size>0){let O=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(O))for(let[F]of yr)Dt.has(F)||(Dt.set(F,1),j(`${h.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${F.split("/").pop()}"${h.reset}`))}if(!P&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(C)){if(Pn++,Pn>=2){j(`${h.yellow} \u26A0 File-not-found streak: ${Pn} consecutive misses \u2014 forcing search${h.reset}`);let O={role:"user",content:`[SYSTEM] ${Pn} consecutive "File not found" errors. STOP guessing paths. Use search_files or glob_files to locate the correct file first, then read/edit the path returned by the search.`};L.push(O),S.push(O)}}else P&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(Pn=0);if(P&&y.fnName==="write_file"&&y.args?.path){let O=y.args.path.split("/").pop(),q=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(O)&&!q){j(`${h.yellow} \u26A0 Temp file: "${O}" \u2014 delete with bash rm when done to keep the workspace clean${h.reset}`);let X={role:"user",content:`[HINT] "${y.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${y.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};L.push(X),S.push(X)}}if(P&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Dt.delete(y.args.path),_.add(y.args.path);for(let F of _s)!F.done&&y.args.path.endsWith(F.file.split("/").pop())&&(F.done=!0,j(`${h.green} \u2713 TODO done: ${F.file}${h.reset}`));let O=gs(t0,y.args.path),q=y.args.path.split("/").slice(-2).join("/");if(O===n0){j(`${h.yellow} \u26A0 Loop warning: "${q}" edited ${O}\xD7 \u2014 possible edit loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${O}\xD7. One more edit max, then move on.`};L.push(F),S.push(F)}else if(O>=s0){j(`${h.red} \u2716 Loop abort: "${q}" edited ${O}\xD7 \u2014 aborting to prevent runaway loop${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me,{suppressHint:!0}),Ne(L);return}me&&Ce==="verify"||(io=!0,ao=0,Ra=!0)}if(P&&y.canExecute&&me&&(In=0),P&&y.canExecute&&!(me&&Ce==="plan")){let O=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){Bt=0,Ut=!1,Jt=0,Zt++;let te=y.args?.path||y.args?.file_path;te&&(Kc(kn,te,1),Ln.delete(te),de.add(te))}else if(O.includes(y.fnName)){if(Bt++,Ut&&Jt++,me&&Ce==="implement"&&y.fnName==="read_file"&&_s.length>0){let te=y.args?.path||y.args?.file_path||"",be=_s.find(Te=>!Te.done&&te.endsWith(Te.file.split("/").pop()));if(be){let Te={role:"user",content:`[TODO OBSERVER] You already analyzed "${be.file}" in the plan phase. Action: ${be.action}
|
|
1421
|
+
Do NOT re-read \u2014 apply the edit directly with edit_file.`};L.push(Te),S.push(Te),j(`${h.yellow} \u26A0 TODO nudge: ${be.file} \u2014 already analyzed, edit directly${h.reset}`)}}me&&Ce==="implement"&&io&&ao<1&&(ao++,Ra=!0)}me&&Ce==="verify"&&wr++,P&&hR(y)&&(io=!1,ao=0);let F=o.postEditCap,X=me&&Ce==="implement"?Math.min(Eu,10):Eu,K=rt?8:Ft?Zt>0?6:10:Zt>0?F:X,ae=6,he=!me&&Ut&&(rt&&Jt>=ae||Ft&&Zt>=3&&Jt>=ae||Jt>=ae);if(rr<2&&!Ut&&Bt>=3&&_.size===0){let te=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,be=Date.now()-Me,Te=rr===0?.4:.65;if(te>0&&be>te*Te){rr++;let wt=Math.round(be/6e4),et=Math.round(be/te*100);j(`${h.yellow} \u26A0 Time nudge #${rr}: ${wt}m elapsed (${et}%), ${Bt} reads, 0 edits${h.reset}`);let Pt={role:"user",content:rr===1?`[SYSTEM] ${et}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${et}% 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.`};L.push(Pt),S.push(Pt)}}if(he&&O.includes(y.fnName)){let te=rt?`root cause already identified (${kt})`:Jt>=ae?`${Bt} consecutive reads without an edit`:`${Zt} file edit(s) already made`;j(`${h.red} \u2716 Blocked read-only tool: cap fired, ${te}${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:rt?`BLOCKED: root cause already identified (${kt}). Use edit_file to fix the issue \u2014 do not read more files.`:Ft?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Jt>=ae?`BLOCKED: You have read ${Bt} files without making any edits. Stop investigating and either implement a fix with edit_file/write_file, or write your diagnosis as text output. Do not read more files.`:`BLOCKED: ${Zt} file edit(s) already made and post-edit investigation cap reached. The fix is in place. Do not read more files \u2014 proceed with the task.`,tool_call_id:y.callId}}else if(Bt>=K&&!Ut){if(Ut=!0,j(`${h.yellow} \u26A0 Investigation cap: ${Bt} read-only calls without an edit \u2014 forcing implementation${h.reset}`),me&&Ce==="plan"){let Te=[...S].reverse().find(Pt=>Pt.role==="assistant"),wt=typeof Te?.content=="string"?Te.content:"",et=await ar("implement",wt);et&&(L.push(et),S.push(et),He=0,St=ms("implement"))}let te;rt?te=`[SYSTEM] Root cause was already identified (${kt}). Edit the file now \u2014 do not read more files.`:At?te="[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.":te="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let be={role:"user",content:te};L.push(be),S.push(be)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let O=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),q=gs(xu,O);if(q===o0){j(`${h.yellow} \u26A0 Loop warning: same bash command run ${q}\xD7 \u2014 possible debug loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same bash command ${q}\xD7. Debug loop detected \u2014 try a different approach.`};L.push(F),S.push(F)}else if(q>=r0){j(`${h.red} \u2716 Loop abort: same bash command run ${q}\xD7 \u2014 aborting runaway debug loop${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me,{suppressHint:!0}),Ne(L);return}}if(y.fnName==="ssh_exec"){qt++;{let F=(at[w]?.content??"").split(`
|
|
1422
|
+
`).map(X=>X.trim()).find(X=>X.length>0&&!X.startsWith("**")&&(X.startsWith("EXIT")||/^[\w./-]+:\s/.test(X)||X.startsWith("bash:")||X.startsWith("sh:")))??"";if(F){if(F===aa?ws++:(aa=F,ws=1),ws===3&&!At){j(`${h.yellow} \u26A0 SSH repeated-error: "${F.slice(0,60)}" returned ${ws}\xD7 \u2014 nudging to change approach${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] The last ${ws} SSH commands all failed with the same error: "${F}". Retrying variants of the same command will not help. Switch to a different approach to accomplish the task (e.g. use a different tool, read a local file, or change the command syntax entirely).`};L.push(X),S.push(X)}}else aa="",ws=0}if(qt>=k0){j(`${h.red} \u2716 SSH storm abort: ${qt} consecutive ssh_exec calls \u2014 aborting${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me,{suppressHint:!0}),Ne(L);return}else if(qt===fo){{let F=ut(),{messages:X}=un(S,F);S=X}At=!0,Vi++,j(`${h.yellow} \u26A0 SSH storm warning (#${Vi}): ${qt} consecutive ssh_exec calls \u2014 blocking further SSH${h.reset}`);let q={role:"user",content:rt?`[SYSTEM WARNING] ${qt} consecutive SSH calls. Root cause identified (${kt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${qt} consecutive SSH calls \u2014 SSH temporarily paused for synthesis. Summarize what you found and state the likely diagnosis. Do NOT ask the user to run commands or provide logs. SSH will be re-enabled after your summary so you can continue.`};L.push(q),S.push(q)}}else y.canExecute&&(qt=0);if(y.fnName==="bash"&&y.canExecute){let F=(at[w]?.content??"").split(`
|
|
1423
|
+
`).map(X=>X.trim()).find(X=>X.length>0&&(X.startsWith("EXIT")||/^[\w./-]+:\s/.test(X)||X.startsWith("bash:")||X.startsWith("sh:")))??"";if(F){if(F===la?$s++:(la=F,$s=1),$s===3){j(`${h.yellow} \u26A0 Bash repeated-error: "${F.slice(0,60)}" returned ${$s}\xD7 \u2014 nudging to change approach${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] The last ${$s} bash commands all failed with the same error: "${F}". Retrying variants of the same command will not help. Switch to a completely different approach (e.g. use a different tool, change the command syntax, or use ssh_exec to run the command on the remote server instead).`};L.push(X),S.push(X)}}else la="",$s=0}if(y.fnName==="bash"&&y.canExecute&&!Xc&&y.args?.command){let O=at[w]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!O.startsWith("EXIT")&&!O.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(O)||O.includes("files changed")||O.includes("file changed")||O.includes("insertions(+)")||O.includes("create mode"))){Xc=!0,ir=0,j(`${h.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${h.reset}`);let X={role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. Your changes are committed. Do NOT run further git status / git diff / git log calls \u2014 the commit is done. Write your final summary and stop. Running extra verification commands wastes tool calls and hurts session quality."};L.push(X),S.push(X)}}if(Xc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(ir++,ir>2)){j(`${h.yellow} \u26A0 Post-commit git verification blocked (call ${ir})${h.reset}`);let q={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(ir-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};L.push(q),S.push(q)}if(P&&y.fnName==="grep"&&G&&!G.startsWith("(no matches)")){let O=G.split(`
|
|
1424
|
+
`);for(let q of O){let F=q.indexOf(":");if(F>0){let X=q.substring(0,F);X.startsWith("/")&&!X.includes(" ")&&mr.add(X)}else q.startsWith("/")&&!q.includes(" ")&&mr.add(q.trim())}}{let O=["grep","search_files","glob","glob_files"].includes(y.fnName);if(O&&P&&G&&(G.startsWith("(no matches)")||G.trim()===""||/^No matches found/.test(G.trim())||/^\(0 results\)/.test(G.trim()))){if(uo++,uo===3){j(`${h.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${h.reset}`);let F={role:"user",content:"[SYSTEM NOTE] 3 consecutive local searches returned no results. The target files may be on a remote server. If you have an SSH profile configured for this project's server, use ssh_exec to search there (e.g. ssh_exec with grep). Do not keep searching locally if the code does not exist on this machine."};L.push(F),S.push(F)}}else O&&P&&G&&G.trim().length>0&&(uo=0)}if(P&&y.fnName==="grep"&&y.args&&y.args.pattern){let O=`${y.args.pattern}|${y.args.path||""}`,q=gs(i0,O);if(q===a0){j(`${h.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};L.push(F),S.push(F)}else if(q>=l0){j(`${h.red} \u2716 Loop abort: grep pattern run ${q}\xD7 \u2014 aborting runaway search loop${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me,{suppressHint:!0}),Ne(L);return}if(y.args.path){let F=gs($a,y.args.path),X=dn(ks,y.args.path)>=1;if(F===(X?1:c0)){let ae=y.args.path.split("/").slice(-2).join("/");j(`${h.yellow} \u26A0 Loop warning: "${ae}" grepped ${F}\xD7 with different patterns \u2014 context flood risk${h.reset}`);let he={role:"user",content:X?`[SYSTEM NOTE] "${y.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${y.args.path}" grepped ${F}\xD7 \u2014 use the search results already in context instead of searching again.`};L.push(he),S.push(he)}}}if(P&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(G&&!G.startsWith("(no matches)")){let X=G.split(`
|
|
1425
|
+
`);for(let K of X)(K.startsWith("/")&&!K.includes(" ")||!K.includes(":")&&!K.startsWith("["))&&gr.add(K.trim())}let O=y.args.pattern||y.args.query||y.args.path||"",q=gs(u0,O);if(q===d0){j(`${h.yellow} \u26A0 Loop warning: glob pattern "${O.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};L.push(X),S.push(X)}else if(q>=f0){j(`${h.red} \u2716 Loop abort: glob pattern run ${q}\xD7 \u2014 aborting runaway search loop${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me,{suppressHint:!0}),Ne(L);return}let F=O.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(X=>X.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(X));for(let X of F){let K=X.toLowerCase();ta.has(K)||ta.set(K,new Set);let ae=ta.get(K);if(ae.add(O),ae.size===h0){j(`${h.red} \u2716 Glob core-term block: ${ae.size} different patterns all searching for "${K}" \u2014 search loop${h.reset}`);let he={role:"user",content:`[SYSTEM WARNING] You have searched for "${K}" using ${ae.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.`};L.push(he),S.push(he)}else if(ae.size===p0){j(`${h.yellow} \u26A0 Glob core-term warning: ${ae.size} different patterns searching for "${K}"${h.reset}`);let he={role:"user",content:`[SYSTEM WARNING] ${ae.size} different glob patterns all target "${K}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};L.push(he),S.push(he)}}}let ee=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),B=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(ee)||/\/(health|status|ping|ready|alive)\b/.test(ee);if(P&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&B&&G.includes('"valid":true')){{let q=ut();if(Vt(S,q).percentage>=60){let{messages:X,tokensRemoved:K}=un(S,q);K>0&&(S=X,console.log(`${h.dim} [pre-stop-compress \u2014 ~${K} tokens freed before STOP injection, now ${Math.round(Vt(S,q).percentage)}%]${h.reset}`))}}let O={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.'};L.push(O),S.push(O),console.log(`${h.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${h.reset}`)}if(P&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&ee&&/\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(ee)&&(Sn++,j(`${h.dim} [bash write detected: _bashModifiedFiles=${Sn}]${h.reset}`)),G.startsWith("BLOCKED:")){if(Dn++,Dn>=Su){j(`${h.red} \u2716 Loop abort: ${Dn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me,{suppressHint:!0}),Ne(L);return}}else Dn=0;if(P)jn=0,xa=!0;else if(jn++,jn===w0){j(`${h.yellow} \u26A0 Loop warning: ${jn} consecutive tool errors \u2014 possible stuck loop${h.reset}`);let O={role:"user",content:`[SYSTEM WARNING] ${jn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};L.push(O),S.push(O)}else if(jn>=$0){j(`${h.red} \u2716 Loop abort: ${jn} consecutive errors \u2014 aborting stuck loop${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me,{suppressHint:!0}),Ne(L);return}if(P&&y.fnName==="read_file"&&y.args&&y.args.path){Z.add(y.args.path),de.delete(y.args.path);let O=gs(ks,y.args.path);{let K=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,ae=y.args.line_start!=null?parseInt(y.args.line_end,10)||K+350:350;Ln.has(y.args.path)||Ln.set(y.args.path,[]),Ln.get(y.args.path).push([K,ae])}if(y._scrollWarn){let{sectionCount:K,path:ae}=y._scrollWarn,he={role:"user",content:`[SYSTEM WARNING] "${ae}" \u2014 you have now read ${K} different sections of this file. This is a file-scroll pattern. Stop reading sections and use grep_search to find the specific lines you need instead.`};L.push(he),S.push(he),j(`${h.yellow} \u26A0 Scroll warning: "${ae.split("/").slice(-2).join("/")}" \u2014 ${K} sections read \u2014 use grep instead${h.reset}`)}let q=y.args.path.split("/").slice(-2).join("/"),F=!y.args?.line_start&&!y.args?.line_end,X=me&&Ce==="plan";if(!X&&F&&O===m0){{let ae=ut();if(Vt(S,ae).percentage>=60){let{messages:te}=un(S,ae);S=te}}j(`${h.yellow} \u26A0 Loop warning: "${q}" read unbounded ${O}\xD7 \u2014 use line_start/line_end${h.reset}`);let K={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${O}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};L.push(K),S.push(K)}else if(!X&&F&&O>=g0){j(`${h.red} \u2716 Loop abort: "${q}" read unbounded ${O}\xD7 \u2014 aborting runaway read loop${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me,{suppressHint:!0}),Ne(L);return}}if(y.fnName==="spawn_agents"){let O=(G.match(/\bStatus: done\b/g)||[]).length;if((G.match(/\bStatus: truncated\b/g)||[]).length>0&&O===0){if(qn++,qn===b0){j(`${h.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${qn}\xD7 in a row${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${qn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};L.push(F),S.push(F)}else if(qn>=_0){console.log(`${h.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${qn}\xD7 \u2014 aborting stuck swarm${h.reset}`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me,{suppressHint:!0}),Ne(L);return}}else O>0&&(qn=0)}}if(Ra&&io&&!(me&&Ce==="verify")){let w=await hu(_),y=await pa(_),G={role:"user",content:pR(_,w,y)};L.push(G),S.push(G),j(`${h.cyan} \u21B3 Post-edit verify prompt injected (${w.length} checks, ${y.length} tests)${h.reset}`)}{let y=at.reduce((G,C)=>G+(typeof C.content=="string"?C.content.length:0),0);if(y>2e5){let G=at.map((C,P)=>({i:P,len:typeof C.content=="string"?C.content.length:0})).sort((C,P)=>P.len-C.len);for(let{i:C,len:P}of G){if(y<=2e5)break;let ee=y-2e5,B=Math.max(P-ee,500);B<P&&typeof at[C].content=="string"&&(at[C]={...at[C],content:at[C].content.substring(0,B)+`
|
|
1426
|
+
...(truncated ${P-B} chars \u2014 per-message budget)`},y-=P-B)}}}for(let w of at)L.push(w),S.push(w);if(Ji(L,S),!rt)for(let w=0;w<at.length;w++){if(!ye[w]||ye[w].fnName!=="ssh_exec")continue;let y=at[w];if(!y||typeof y.content!="string")continue;let G=zc(y.content);if(G){rt=!0,kt=G.slice(0,120),Bt=0,Ut=!1,Jt=0,j(`${h.yellow} \u26A1 Root cause detected: ${kt} \u2014 fix phase (read budget: 3)${h.reset}`);let C={role:"user",content:`[SYSTEM] Root cause identified: ${kt}. Read only the file that needs fixing, then edit it. Do not read other files.`};L.push(C),S.push(C);break}}for(let w=0;w<at.length;w++){let y=ye[w];if(!y)continue;let G=typeof at[w]?.content=="string"?at[w].content:"";if(y.fnName==="create_task"){let C=G.match(/Task #(\d+) created/),P=typeof y.args?.subject=="string"?y.args.subject:"";C&&P&&$r.set(C[1],P)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!G.startsWith("BLOCKED:")&&G.trim().length>0){let P=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),ee=P.split(/[._\-/]/).filter(B=>B.length>2);for(let[B,ie]of $r){if(br.has(B))continue;let O=ie.toLowerCase().split(/\W+/).filter(F=>F.length>3);ee.filter(F=>O.some(X=>X.includes(F)||F.includes(X))).length>=1&&(br.add(B),j(`${h.green} \u2714 Auto-matched task #${B} to ${P}: ${ie.slice(0,60)}${h.reset}`))}}}{let w=ut();if(Vt(S,w).percentage>=78){let{messages:G,tokensRemoved:C}=un(S,w);C>0&&(S=G,console.log(`${h.dim} [auto-compressed \u2014 ~${C} tokens freed, now ${Math.round(Vt(S,w).percentage)}%]${h.reset}`))}}if(pr()&&!s.skillLoop&&(ye.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?fe=0:(fe===0&&(Ze=_.size),fe++),fe>=9&&M>=4&&_.size===Ze)){j(`${h.green} \u2713 Stagnation exit: ${fe} read-only iterations, no new file changes${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Stagnation detected: ${fe} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${h.reset}
|
|
1427
|
+
`),c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me),Ne(L);break e}let Lu=cR();if(Lu){let w={role:"user",content:`[User note mid-run]: ${Lu}`};L.push(w),S.push(w),console.log(`${h.cyan} \u270E Context added${h.reset}`)}}if(He>=St){if(c&&(c.stop(),c=null),l(null),Pe(M,I,_,Z,Me),Ne(L),Ki(L),me&&Ce==="plan"){let Qe=[...L].reverse().find(Ve=>Ve.role==="assistant"),dt=typeof Qe?.content=="string"?Qe.content:"",En=await ar("implement",dt);if(En){L.push(En),S=[{role:"system",content:await fu()},...L],St=ms("implement"),j(`${h.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${h.reset}`);continue e}}else if(me&&Ce==="verify"){j(`${h.yellow} \u26A0 Verify budget exhausted \u2014 completing session${h.reset}`);break e}let{getActiveProviderName:we}=lt();if(we()==="ollama"&&ka<Ru){if(_.size===0&&!xa){console.log(`${h.yellow} \u26A0 Max iterations reached with no progress. Stopping.${h.reset}`);break e}ka++,St=20,console.log(`${h.dim} \u2500\u2500 auto-extending (+20 turns, ext ${ka}/${Ru}) \u2500\u2500${h.reset}`);continue e}if(console.log(`
|
|
1428
|
+
${h.yellow}\u26A0 Max iterations reached.${h.reset}`),await dy(" Continue for 20 more turns?")){St=20;continue e}console.log(`${h.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${h.reset}`)}break e}await vu()}Ry.exports={processInput:OR,clearConversation:_R,getConversationLength:xR,getConversationMessages:SR,setConversationMessages:ER,setAbortSignalGetter:HT,setMaxIterations:WT,invalidateSystemPromptCache:ou,clearToolFilterCache:ZT,getCachedFilteredTools:wy,buildSystemPrompt:fu,splitSystemPrompt:bR,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:du,getProjectContextHash:$y,_inferVerificationCommands:hu,_inferRelevantTests:pa,_inferSymbolTargets:Sy,_buildSymbolHintBlock:Ey,buildUserContent:gy,_detectImageURLs:py,_downloadImageURL:hy,_grabClipboardImage:my,detectFrustration:yy,detectAndTruncateLoop:Qc,injectMidRunNote:lR,resetSessionTracking:vy}});var lt=V((JC,Ny)=>{var{OllamaProvider:NR}=Wu(),{OpenAIProvider:MR}=zu(),{AnthropicProvider:PR}=Ju(),{GeminiProvider:LR}=td(),{LocalProvider:IR}=od(),{checkBudget:jR}=Br(),yu={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"}},mu=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Ay={};for(let[t,e]of Object.entries(yu))for(let s of Object.values(e))Ay[s]=t;function gu(t,e){let s=Ay[t];return s&&yu[s][e]||t}var it={},xt=null,ze=null,_r=[];function Wt(){if(Object.keys(it).length>0)return;co("ollama",new NR),co("openai",new MR),co("anthropic",new PR),co("gemini",new LR),co("local",new IR);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;it[t]?(xt=t,ze=e||it[t].defaultModel):(xt="ollama",ze="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(_r=s.split(",").map(o=>o.trim()).filter(Boolean))}function co(t,e){it[t]=e}function DR(t){return Wt(),it[t]||null}function wu(){return Wt(),it[xt]||null}function qR(){return Wt(),xt}function FR(){return Wt(),ze}function BR(){Wt();let t=wu();if(!t)return{id:ze,name:ze,provider:xt};let e=t.getModel(ze);return e?{...e,provider:xt}:{id:ze,name:ze,provider:xt}}function $u(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(it[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function UR(t){Wt();let{provider:e,model:s}=$u(t);if(e){let n=it[e];return n&&(n.getModel(s)||e==="local"||e==="ollama")?(xt=e,ze=s,ha(),!0):!1}let o=wu();if(o&&o.getModel(s))return ze=s,ha(),!0;for(let[n,r]of Object.entries(it))if(r.getModel(s))return xt=n,ze=s,ha(),!0;return!1}function ha(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=$c();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=ln();t()}catch{}}function WR(){Wt();let t=new Set;for(let e of Object.values(it))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function HR(){return Wt(),Object.entries(it).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===xt&&s.id===ze}))}))}function GR(){Wt();let t=[];for(let[e,s]of Object.entries(it)){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 YR(t){_r=Array.isArray(t)?t:[]}function zR(){return[..._r]}function Cy(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 Oy(t){let e=[xt,..._r.filter(r=>r!==xt)],s,o=0,n=0;for(let r=0;r<e.length;r++){let i=e[r],a=it[i];if(!a||!a.isConfigured())continue;n++;let l=jR(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?gu(ze,i):ze;return c&&u!==ze&&process.stderr.write(` [fallback: ${i}:${u}]
|
|
1429
|
+
`),await t(a,i,u)}catch(c){if(s=c,!Cy(c)||r>=e.length-1)throw c;if(i==="ollama"&&mu.length>0){let u=isFallback?gu(ze,i):ze;for(let d of mu)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
|
|
1430
|
+
`),await t(a,i,d)}catch(f){if(s=f,!Cy(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 KR(t,e,s={}){Wt();let o=s.model,n=o?(()=>{let{model:i}=$u(o);return i||o})():void 0,r=n!==o?{...s,model:n}:s;return Oy((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function XR(t,e,s={}){if(Wt(),s.provider){let o=it[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 Oy(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 VR(){Wt();let t=[];for(let[e,s]of Object.entries(it))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function JR(){for(let t of Object.keys(it))delete it[t];xt=null,ze=null,_r=[]}Ny.exports={registerProvider:co,getProvider:DR,getActiveProvider:wu,getActiveProviderName:qR,getActiveModelId:FR,getActiveModel:BR,setActiveModel:UR,getModelNames:WR,parseModelSpec:$u,listProviders:HR,listAllModels:GR,callStream:KR,callChat:XR,getConfiguredProviders:VR,setFallbackChain:YR,getFallbackChain:zR,resolveModelForProvider:gu,MODEL_EQUIVALENTS:yu,OLLAMA_FALLBACK_MODELS:mu,_reset:JR}});var Pi=V((QC,Qy)=>{var{callStream:ZR,getActiveProviderName:ga,getActiveModelId:My,getConfiguredProviders:QR,getProvider:Py,getActiveProvider:Ly,parseModelSpec:Iy}=lt(),{parseToolArgs:jy}=Kr(),{filterToolsForModel:e1,getModelTier:ma}=Co(),{getModelBriefing:t1}=Yi(),{trackUsage:Dy,estimateTokens:qy}=Br(),{MultiProgress:n1,C:ZC}=nt();function Fy(t){return!t||typeof t!="string"?0:typeof qy=="function"?qy(t):Math.ceil(t.length/4)}var Wy=15,s1=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),By=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Hy=8,o1=2,ya=new Map,Gy=600*1e3;function r1(t,e){let s=ya.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Gy?!1:(ya.set(t,{agentId:e,timestamp:Date.now()}),!0)}function kr(t){ya.delete(t)}function bu(){ya.clear()}function _u(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 Yy(t){let e=_u(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function zy(t,e,s){let o;for(let n=0;n<=By;n++)try{return await ZR(t,e,s)}catch(r){o=r;let i=_u(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<By&&Yy(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 Uy=new Set(["ask_user","task_list"]);function Ky(t){return t>=2?new Set([...Uy,"spawn_agents"]):Uy}var i1=new Set(["write_file","edit_file","patch_file"]),Xy={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:""}},a1=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,l1=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Vy(t){return l1.test(t)?"full":a1.test(t)?"essential":t.length>300?"full":"standard"}function Jy(t){let e=QR(),s=ga(),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(ma(r.id,n.name)===t)return{provider:n.name,model:r.id};return null}var c1={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function wa(t){if(t.model){let{provider:n,model:r}=Iy(t.model),i=n?Py(n):Ly(),a=n||ga();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=ma(r,a);return{provider:a,model:r,tier:l}}}let e=Vy(t.task),s=c1[e];if(s){let{provider:n,model:r}=Iy(s),i=n?Py(n):Ly(),a=n||ga();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=ma(r,a);return{provider:a,model:r,tier:l}}}let o=Jy(e);if(o){let n=ma(o.model,o.provider);return{provider:o.provider,model:o.model,tier:n}}return{provider:null,model:null,tier:null}}async function Zy(t,e={},s=0){let o=s===0?Wy:Hy,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.
|
|
1409
1431
|
|
|
1410
1432
|
TASK: ${t.task}
|
|
1411
1433
|
${t.context?`
|
|
@@ -1431,19 +1453,19 @@ TOOL STRATEGY:
|
|
|
1431
1453
|
ERROR RECOVERY:
|
|
1432
1454
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
1433
1455
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
1434
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&
|
|
1456
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Xy[t.type],f=d&&d.systemSuffix?`
|
|
1435
1457
|
|
|
1436
|
-
${d.systemSuffix}`:"",p=
|
|
1437
|
-
${
|
|
1458
|
+
${d.systemSuffix}`:"",p=wa(t),m=p.provider,g=p.model,$=p.tier,x=t1(g||My()),A=[{role:"system",content:(x?`## Model Briefing
|
|
1459
|
+
${x}
|
|
1438
1460
|
|
|
1439
1461
|
---
|
|
1440
1462
|
|
|
1441
|
-
`:"")+u+f}];
|
|
1442
|
-
`)}let se={};m&&(se.provider=m),g&&(se.model=g);let
|
|
1443
|
-
...(truncated)`:_,tool_call_id:
|
|
1444
|
-
`)}catch(u){return c.stop(),
|
|
1445
|
-
`+s.map((i,a)=>` ${
|
|
1463
|
+
`:"")+u+f}];A.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:R,executeTool:v}=xo(),N=Ky(s),Q=e1(R.filter(le=>!N.has(le.function.name)),$);if(d&&d.allowedTools&&(Q=Q.filter(le=>d.allowedTools.has(le.function.name))),g&&!t._skipLog){let le=$?` (${$})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${le}]
|
|
1464
|
+
`)}let se={};m&&(se.provider=m),g&&(se.model=g);let re=new Set;try{for(let ne=0;ne<n;ne++){let S=await zy(A,Q,se);if(!S||typeof S!="object")throw new Error("Empty or invalid response from provider");{let ke=m||ga(),_e=g||My();if(S.usage){let k=S.usage.prompt_tokens||0,D=S.usage.completion_tokens||0;a.input+=k,a.output+=D,Dy(ke,_e,k,D)}else{let k=S.content||"",D=A.map(I=>typeof I.content=="string"?I.content:Array.isArray(I.content)?I.content.map(_=>typeof _=="string"?_:_.text||"").join(""):"").join(" "),H=Fy(D),M=Fy(k);a.input+=H,a.output+=M,a._estimated=!0,Dy(ke,_e,H,M)}}let ve=S.content||"",W=S.tool_calls,z={role:"assistant",content:ve||""};if(W&&W.length>0&&(z.tool_calls=W),A.push(z),!W||W.length===0){for(let ke of l)kr(ke);return{task:t.task,status:"done",result:ve||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let ge=new Set,Ae=W.map(ke=>{let _e=ke.function.name,k=jy(ke.function.arguments),D=ke.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!k)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${_e}`,tool_call_id:D});if(["edit_file","patch_file"].includes(_e)&&k.path){if(re.has(k.path)||ge.has(k.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${k.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:D});ge.add(k.path)}let H=null;if(i1.has(_e)&&k.path){let I=require("path"),_=I.isAbsolute(k.path)?k.path:I.resolve(process.cwd(),k.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let Z=I.relative(process.cwd(),_);if(t._readOnlyFiles.some(fe=>Z===fe||Z.startsWith(fe+"/")||_===fe||_.startsWith(fe+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${k.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:D})}if(l.has(_)||!r1(_,r))return Promise.resolve({role:"tool",content:`ERROR: File '${k.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:D});l.add(_),H=_}return i.push(_e),e.onUpdate&&e.onUpdate({type:"tool_call",tool:_e,agentId:r}),(_e==="spawn_agents"?ku(k,s+1):v(_e,k,{autoConfirm:!0,silent:!0})).then(I=>{H&&(kr(H),l.delete(H));let _=String(I??"");return k&&k.path&&(["edit_file","patch_file","write_file"].includes(_e)&&_.startsWith("Edited:")?re.add(k.path):_e==="read_file"&&!_.startsWith("ERROR")&&re.delete(k.path)),{role:"tool",content:_.length>2e4?_.substring(0,2e4)+`
|
|
1465
|
+
...(truncated)`:_,tool_call_id:D}}).catch(I=>(H&&(kr(H),l.delete(H)),{role:"tool",content:`ERROR: ${I.message}`,tool_call_id:D}))}),qe=await Promise.all(Ae);if(A.push(...qe),ne>=7&&A.length>12)try{let{compressMessage:ke}=ln(),_e=A.length-6;for(let k=1;k<_e;k++)A[k]._subAgentCompressed||(A[k]={...ke(A[k],"light"),_subAgentCompressed:!0})}catch{}for(let ke=0;ke<W.length;ke++){let _e=W[ke];if(_e.function.name==="bash_exec"){let k=jy(_e.function.arguments);if((qe[ke]?.content||"").startsWith("ERROR")&&k&&k.command){let H=k.command.replace(/\s+/g," ").trim().slice(0,100);c.set(H,(c.get(H)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${ne+1}/${n}`)}for(let ne of l)kr(ne);let le=[...c.entries()].filter(([,ne])=>ne>=3).sort((ne,S)=>S[1]-ne[1]).slice(0,3).map(([ne,S])=>`"${ne}" (failed ${S}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:le,result:A[A.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(le){for(let ne of l)kr(ne);return{task:t.task,status:"failed",result:`Error: ${le.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function ku(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?s1:o1,o=e===0?Wy:Hy,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=>wa(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 n1(l);c.start();try{let u=n.map((g,$)=>{let x=a[$],T=Math.min(g.max_iterations||o,o),A=x.model?{...g,model:`${x.provider}:${x.model}`,_skipLog:!0,max_iterations:T}:{...g,_skipLog:!0,max_iterations:T};return Zy(A,{onUpdate:()=>{}},e).then(R=>(c.update($,R.status==="failed"?"error":"done"),R)).catch(R=>(c.update($,"error"),{task:g.task,status:"failed",result:`Error: ${R.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),bu();let f=["Sub-agent results:",""],p=0,m=0;for(let g=0;g<d.length;g++){let $=d[g],x=$.status==="done"?"\u2713":$.status==="truncated"?"\u26A0":"\u2717",T=$.modelSpec?` [${$.modelSpec}]`:"";f.push(`${x} Agent ${g+1}${T}: ${$.task}`),f.push(` Status: ${$.status}`),f.push(` Tools used: ${$.toolsUsed.length>0?$.toolsUsed.join(", "):"none"}`),f.push(` Result: ${$.result}`),$.repeatedFailures&&$.repeatedFailures.length>0&&f.push(` Repeated failures: ${$.repeatedFailures.join("; ")}`),f.push(""),p+=$.tokensUsed.input,m+=$.tokensUsed.output}return f.push(`Total sub-agent tokens: ${p} input + ${m} output`),f.join(`
|
|
1466
|
+
`)}catch(u){return c.stop(),bu(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function u1(t){let{createJob:e}=Js(),s=(t.agents||[]).filter(i=>i.background),o=(t.agents||[]).filter(i=>!i.background),n=s.map(i=>{let a=wa(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(", ")}]
|
|
1467
|
+
`+s.map((i,a)=>` ${n[a]}: ${i.task}`).join(`
|
|
1446
1468
|
`)+`
|
|
1447
|
-
Results will be injected into the conversation when each agent completes.`),
|
|
1469
|
+
Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await ku({agents:o});r.push(i)}return r.join(`
|
|
1448
1470
|
|
|
1449
|
-
`)||"No agents specified."}
|
|
1471
|
+
`)||"No agents specified."}Qy.exports={runSubAgent:Zy,executeSpawnAgents:ku,executeSpawnAgentsBackground:u1,clearAllLocks:bu,classifyTask:Vy,pickModelForTier:Jy,resolveSubAgentModel:wa,classifyError:_u,isRetryableError:Yy,callWithRetry:zy,getExcludedTools:Ky,LOCK_TIMEOUT_MS:Gy,SUB_AGENT_TYPES:Xy}});var{runSubAgent:d1}=Pi();process.on("message",async({jobId:t,agentDef:e})=>{try{let s=await d1({...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)}});
|