nex-code 0.5.20 → 0.5.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,17 @@
1
- var jl=Object.defineProperty;var G0=Object.getOwnPropertyDescriptor;var Y0=Object.getOwnPropertyNames;var z0=Object.prototype.hasOwnProperty;var K0=(t,e)=>()=>(t&&(e=t(t=0)),e);var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),V0=(t,e)=>{for(var n in e)jl(t,n,{get:e[n],enumerable:!0})},X0=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Y0(e))!z0.call(t,s)&&s!==n&&jl(t,s,{get:()=>e[s],enumerable:!(o=G0(e,s))||o.enumerable});return t};var J0=t=>X0(jl({},"__esModule",{value:!0}),t);var ws=J((DO,df)=>{async function Z0(t,e){if(!t.response?.data)return t.message;let n=t.response.data;if(typeof n=="object"&&n!==null&&typeof n.pipe!="function")return e(n)||t.message;try{let o=await new Promise((r,i)=>{let a=[];n.on("data",l=>a.push(l)),n.on("end",()=>r(Buffer.concat(a).toString("utf8"))),n.on("error",i)}),s=JSON.parse(o);return e(s)||o||t.message}catch{return t.message}}var Dl=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,n,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,o={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};df.exports={BaseProvider:Dl,readStreamErrorBody:Z0}});var go=J((qO,pf)=>{var ho=class{buildRequestBody(e){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(e){return e}normalizeResponse(e){throw new Error("normalizeResponse() not implemented")}createStreamParser(e,n={}){throw new Error("createStreamParser() not implemented")}},mo=class{constructor(e,n={}){this.onToken=e,this.callbacks=n,this.content="",this.buffer=""}feed(e){this.buffer+=e;let n=this.buffer.split(`
2
- `);this.buffer=n.pop()||"";for(let o of n){let s=this.parseLine(o);if(s?.done)return s}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},Si=class extends mo{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let o=n.slice(6);if(o==="[DONE]")return{done:!0,result:this.getResult()};let s;try{s=JSON.parse(o)}catch{return{done:!1}}let r=s.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},vi=class extends ho{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i}){let a={model:e,messages:n,max_tokens:s,temperature:r};return i&&(a.stream=!0),o&&o.length>0&&(a.tools=o),a}normalizeResponse(e){let n=e.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}createStreamParser(e,n={}){return new Si(e,n)}},Ei=class extends mo{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let o=n.slice(6),s;try{s=JSON.parse(o)}catch{return{done:!1}}switch(s.type){case"content_block_start":{let r=s.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=s.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},ql="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Ti=class extends ho{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let l={model:e,messages:n,max_tokens:s,temperature:r};if(i&&(l.stream=!0),a?.system){let c=a.system,u=c.indexOf(ql);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+ql.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(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let n="",o=[];for(let s of e.content||[])s.type==="text"?n+=s.text:s.type==="tool_use"&&o.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:n,tool_calls:o}}createStreamParser(e,n={}){return new Ei(e,n)}};function ff(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 Ri=class extends mo{constructor(e,n={}){super(e,n),this.toolCalls=[],this.onThinkingToken=n.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let n;try{n=JSON.parse(e)}catch{return{done:!1}}return n.message?.thinking&&this.onThinkingToken(n.message.thinking),n.message?.content&&(this.onToken(n.message.content),this.content+=n.message.content),n.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(n.message.tool_calls)),n.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,n)=>({id:e.id||`ollama-${Date.now()}-${n}`,function:{name:e.function?.name||e.name||"unknown",arguments:ff(e.function?.arguments??e.arguments)}}))}}},Ci=class extends ho{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let l={model:e,messages:n,stream:i,options:{temperature:r,num_predict:s,repeat_penalty:a?.repeat_penalty??1.05}};return o&&o.length>0&&(l.tools=o),l}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((o,s)=>({id:o.id||`ollama-${Date.now()}-${s}`,function:{name:o.function?.name||o.name||"unknown",arguments:ff(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,n={}){return new Ri(e,n)}},Q0=new vi,e_=new Ti,t_=new Ci;pf.exports={ANTHROPIC_CACHE_BOUNDARY:ql,WireProtocol:ho,StreamParser:mo,OpenAICompatibleProtocol:vi,AnthropicProtocol:Ti,OllamaChatProtocol:Ci,OpenAIStreamParser:Si,AnthropicStreamParser:Ei,OllamaStreamParser:Ri,openaiProtocol:Q0,anthropicProtocol:e_,ollamaProtocol:t_}});var mf=J((FO,hf)=>{var Ai=require("axios"),n_=require("http"),s_=require("https"),{BaseProvider:o_,readStreamErrorBody:r_}=ws(),{ollamaProtocol:_s}=go(),Oi=new n_.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Pi=new s_.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Ni={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072,capability:"agentic",speed:"balanced",quality:98,recommendedFor:["coding","agentic","refactor"]},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144,capability:"agentic",speed:"balanced",quality:97,recommendedFor:["coding","agentic","large-context"]},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072,capability:"agentic",speed:"balanced",quality:94,recommendedFor:["coding","sysadmin","agentic"]},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072,capability:"fast-coding",speed:"fast",quality:82,recommendedFor:["quick-fix","sysadmin","fallback"]},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072,capability:"general",speed:"balanced",quality:90,recommendedFor:["coding","reasoning"]},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"balanced",quality:96,recommendedFor:["reasoning","large-context","review"]},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"deliberate",quality:99,recommendedFor:["reasoning","architecture","review"]},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"deliberate",quality:98,recommendedFor:["reasoning","debugging","review"]},"deepseek-v4-pro:cloud":{id:"deepseek-v4-pro:cloud",name:"DeepSeek V4 Pro",maxTokens:16384,contextWindow:1048576,capability:"general",speed:"balanced",quality:96,recommendedFor:["coding","reasoning","review"]},"deepseek-v4-flash:cloud":{id:"deepseek-v4-flash:cloud",name:"DeepSeek V4 Flash",maxTokens:16384,contextWindow:1048576,capability:"general",speed:"fast",quality:90,recommendedFor:["coding","quick-fix","fallback"]},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072,capability:"general",speed:"balanced",quality:94,recommendedFor:["coding","reasoning","fallback"]},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144,capability:"vision-language",speed:"balanced",quality:95,recommendedFor:["frontend","vision","large-context"]},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144,capability:"fast-coding",speed:"fast",quality:84,recommendedFor:["quick-fix","coding","fallback"]},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072,capability:"fast-coding",speed:"fast",quality:86,recommendedFor:["quick-fix","coding"]},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072,capability:"open-reasoning",speed:"balanced",quality:88,recommendedFor:["open-source","reasoning","coding"]},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072,capability:"fast-coding",speed:"fast",quality:78,recommendedFor:["quick-fix","fallback"]},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072,capability:"fast",speed:"very-fast",quality:72,recommendedFor:["quick-fix","fallback"]},"gemma4:e2b":{id:"gemma4:e2b",name:"Gemma 4 E2B",maxTokens:8192,contextWindow:131072},"gemma4:e4b":{id:"gemma4:e4b",name:"Gemma 4 E4B",maxTokens:8192,contextWindow:131072},"gemma4:26b-a4b":{id:"gemma4:26b-a4b",name:"Gemma 4 26B A4B",maxTokens:16384,contextWindow:262144},"gemma4:31b":{id:"gemma4:31b",name:"Gemma 4 31B",maxTokens:16384,contextWindow:262144},"gemma4:31b-cloud":{id:"gemma4:31b-cloud",name:"Gemma 4 31B Cloud",maxTokens:16384,contextWindow:262144},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},Fl={coding:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b","deepseek-v4-pro:cloud"],agentic:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b","deepseek-v4-pro:cloud"],reasoning:["kimi-k2:1t","kimi-k2-thinking","kimi-k2.5"],"large-context":["qwen3-coder-next","qwen3.5:397b-cloud","kimi-k2.5"],frontend:["qwen3.5:397b-cloud","qwen3-coder-next","qwen3-coder:480b"],"quick-fix":["devstral-small-2:24b","qwen3-next:80b","ministral-3:14b","deepseek-v4-flash:cloud"],fallback:["devstral-small-2:24b","deepseek-v4-flash:cloud","deepseek-v3.2","qwen3.5:35b-a3b"],"open-source":["qwen3-coder:480b","devstral-2:123b","gpt-oss:120b"]};function i_(t="coding",e=5){let n=Fl[t]||Fl.coding;return n.map(s=>Ni[s]).filter(Boolean).concat(Object.values(Ni).filter(s=>!n.includes(s.id)).filter(s=>(s.recommendedFor||[]).includes(t))).sort((s,r)=>(r.quality||0)-(s.quality||0)).slice(0,e)}var Bl=class extends o_{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Ni,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){Ai.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Oi,httpsAgent:Pi}).then(e=>{let n=e.data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await Ai.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Oi,httpsAgent:Pi})).data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:n.role,content:o.join(`
3
- `)};return s.length>0&&(r.images=s),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=_s.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),l;try{l=await Ai.post(`${this.baseUrl}${_s.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Oi,httpsAgent:Pi})}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 _s.normalizeResponse(l.data)}async stream(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),c=_s.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),u;try{u=await Ai.post(`${this.baseUrl}${_s.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:Oi,httpsAgent:Pi})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await r_(f,_=>_?.error),g=new Error(`API Error${h}: ${m}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=_s.createStreamParser(a,{onThinkingToken:l});return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{if(o.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,h(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return _s.normalizeResponse(e)}};hf.exports={OllamaProvider:Bl,OLLAMA_MODELS:Ni,OLLAMA_USE_CASES:Fl,getOllamaRecommendations:i_}});var Wl=J((BO,bf)=>{var gf=require("axios"),{BaseProvider:a_,readStreamErrorBody:l_}=ws(),{openaiProtocol:$s}=go(),yf={"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}},Ul=class extends a_{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||yf,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool"){let n;return Array.isArray(e.content)?n=e.content.filter(s=>s.type==="text").map(s=>s.text).join(`
4
- `)||JSON.stringify(e.content):n=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:n,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}prepareRequestBody(e,n={}){return e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),l=this.prepareRequestBody($s.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),o),c;try{c=await gf.post(`${this.baseUrl}${$s.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 $s.normalizeResponse(c.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=this.prepareRequestBody($s.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),o),u;try{u=await gf.post(`${this.baseUrl}${$s.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await l_(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=$s.createStreamParser(a);return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return $s.normalizeResponse(e)}};bf.exports={OpenAIProvider:Ul,OPENAI_MODELS:yf}});var $f=J((UO,_f)=>{var{OpenAIProvider:c_}=Wl(),wf={"deepseek-v4-flash":{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",maxTokens:16384,contextWindow:1048576,capability:"fast-coding",speed:"fast",quality:90,recommendedFor:["coding","quick-fix","fallback"]},"deepseek-v4-pro":{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",maxTokens:16384,contextWindow:1048576,capability:"agentic",speed:"balanced",quality:96,recommendedFor:["coding","agentic","reasoning","review"]}},Hl=class extends c_{constructor(e={}){super({name:"deepseek",baseUrl:e.baseUrl||process.env.DEEPSEEK_BASE_URL||"https://api.deepseek.com",models:e.models||wf,defaultModel:e.defaultModel||"deepseek-v4-flash",...e})}getApiKey(){return process.env.DEEPSEEK_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("DEEPSEEK_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}prepareRequestBody(e,n={}){let o=n.thinking||process.env.DEEPSEEK_THINKING;return{...e,thinking:o!==void 0?{type:o}:{type:"disabled"}}}};_f.exports={DeepSeekProvider:Hl,DEEPSEEK_MODELS:wf}});var vf=J((WO,Sf)=>{var kf=require("axios"),{BaseProvider:u_,readStreamErrorBody:d_}=ws(),{anthropicProtocol:Qn}=go(),xf={"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}},f_="2023-06-01",Gl=class extends u_{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||xf,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||f_}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n="",o=[];for(let s of e){if(s.role==="system"){n+=(n?`
1
+ var ql=Object.defineProperty;var K0=Object.getOwnPropertyDescriptor;var V0=Object.getOwnPropertyNames;var X0=Object.prototype.hasOwnProperty;var J0=(t,e)=>()=>(t&&(e=t(t=0)),e);var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Z0=(t,e)=>{for(var n in e)ql(t,n,{get:e[n],enumerable:!0})},Q0=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of V0(e))!X0.call(t,s)&&s!==n&&ql(t,s,{get:()=>e[s],enumerable:!(o=K0(e,s))||o.enumerable});return t};var e_=t=>Q0(ql({},"__esModule",{value:!0}),t);var _s=J((UO,pf)=>{async function t_(t,e){if(!t.response?.data)return t.message;let n=t.response.data;if(typeof n=="object"&&n!==null&&typeof n.pipe!="function")return e(n)||t.message;try{let o=await new Promise((r,i)=>{let a=[];n.on("data",l=>a.push(l)),n.on("end",()=>r(Buffer.concat(a).toString("utf8"))),n.on("error",i)}),s=JSON.parse(o);return e(s)||o||t.message}catch{return t.message}}var Fl=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,n,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,o={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};pf.exports={BaseProvider:Fl,readStreamErrorBody:t_}});var yo=J((WO,mf)=>{var mo=class{buildRequestBody(e){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(e){return e}normalizeResponse(e){throw new Error("normalizeResponse() not implemented")}createStreamParser(e,n={}){throw new Error("createStreamParser() not implemented")}},go=class{constructor(e,n={}){this.onToken=e,this.callbacks=n,this.content="",this.buffer=""}feed(e){this.buffer+=e;let n=this.buffer.split(`
2
+ `);this.buffer=n.pop()||"";for(let o of n){let s=this.parseLine(o);if(s?.done)return s}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},vi=class extends go{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let o=n.slice(6);if(o==="[DONE]")return{done:!0,result:this.getResult()};let s;try{s=JSON.parse(o)}catch{return{done:!1}}let r=s.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Ei=class extends mo{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i}){let a={model:e,messages:n,max_tokens:s,temperature:r};return i&&(a.stream=!0),o&&o.length>0&&(a.tools=o),a}normalizeResponse(e){let n=e.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}createStreamParser(e,n={}){return new vi(e,n)}},Ti=class extends go{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let o=n.slice(6),s;try{s=JSON.parse(o)}catch{return{done:!1}}switch(s.type){case"content_block_start":{let r=s.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=s.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},Bl="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Ri=class extends mo{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let l={model:e,messages:n,max_tokens:s,temperature:r};if(i&&(l.stream=!0),a?.system){let c=a.system,u=c.indexOf(Bl);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+Bl.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(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let n="",o=[];for(let s of e.content||[])s.type==="text"?n+=s.text:s.type==="tool_use"&&o.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:n,tool_calls:o}}createStreamParser(e,n={}){return new Ti(e,n)}};function hf(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 Ci=class extends go{constructor(e,n={}){super(e,n),this.toolCalls=[],this.onThinkingToken=n.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let n;try{n=JSON.parse(e)}catch{return{done:!1}}return n.message?.thinking&&this.onThinkingToken(n.message.thinking),n.message?.content&&(this.onToken(n.message.content),this.content+=n.message.content),n.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(n.message.tool_calls)),n.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,n)=>({id:e.id||`ollama-${Date.now()}-${n}`,function:{name:e.function?.name||e.name||"unknown",arguments:hf(e.function?.arguments??e.arguments)}}))}}},Ai=class extends mo{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let l={model:e,messages:n,stream:i,options:{temperature:r,num_predict:s,repeat_penalty:a?.repeat_penalty??1.05}};return o&&o.length>0&&(l.tools=o),l}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((o,s)=>({id:o.id||`ollama-${Date.now()}-${s}`,function:{name:o.function?.name||o.name||"unknown",arguments:hf(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,n={}){return new Ci(e,n)}},n_=new Ei,s_=new Ri,o_=new Ai;mf.exports={ANTHROPIC_CACHE_BOUNDARY:Bl,WireProtocol:mo,StreamParser:go,OpenAICompatibleProtocol:Ei,AnthropicProtocol:Ri,OllamaChatProtocol:Ai,OpenAIStreamParser:vi,AnthropicStreamParser:Ti,OllamaStreamParser:Ci,openaiProtocol:n_,anthropicProtocol:s_,ollamaProtocol:o_}});var yf=J((HO,gf)=>{var Oi=require("axios"),r_=require("http"),i_=require("https"),{BaseProvider:a_,readStreamErrorBody:l_}=_s(),{ollamaProtocol:$s}=yo(),Pi=new r_.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Ni=new i_.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Mi={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072,capability:"agentic",speed:"balanced",quality:98,recommendedFor:["coding","agentic","refactor"]},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144,capability:"agentic",speed:"balanced",quality:97,recommendedFor:["coding","agentic","large-context"]},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072,capability:"agentic",speed:"balanced",quality:94,recommendedFor:["coding","sysadmin","agentic"]},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072,capability:"fast-coding",speed:"fast",quality:82,recommendedFor:["quick-fix","sysadmin","fallback"]},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072,capability:"general",speed:"balanced",quality:90,recommendedFor:["coding","reasoning"]},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"balanced",quality:96,recommendedFor:["reasoning","large-context","review"]},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"deliberate",quality:99,recommendedFor:["reasoning","architecture","review"]},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"deliberate",quality:98,recommendedFor:["reasoning","debugging","review"]},"deepseek-v4-pro:cloud":{id:"deepseek-v4-pro:cloud",name:"DeepSeek V4 Pro",maxTokens:16384,contextWindow:1048576,capability:"general",speed:"balanced",quality:96,recommendedFor:["coding","reasoning","review"]},"deepseek-v4-flash:cloud":{id:"deepseek-v4-flash:cloud",name:"DeepSeek V4 Flash",maxTokens:16384,contextWindow:1048576,capability:"general",speed:"fast",quality:90,recommendedFor:["coding","quick-fix","fallback"]},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072,capability:"general",speed:"balanced",quality:94,recommendedFor:["coding","reasoning","fallback"]},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144,capability:"vision-language",speed:"balanced",quality:95,recommendedFor:["frontend","vision","large-context"]},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144,capability:"fast-coding",speed:"fast",quality:84,recommendedFor:["quick-fix","coding","fallback"]},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072,capability:"fast-coding",speed:"fast",quality:86,recommendedFor:["quick-fix","coding"]},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072,capability:"open-reasoning",speed:"balanced",quality:88,recommendedFor:["open-source","reasoning","coding"]},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072,capability:"fast-coding",speed:"fast",quality:78,recommendedFor:["quick-fix","fallback"]},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072,capability:"fast",speed:"very-fast",quality:72,recommendedFor:["quick-fix","fallback"]},"gemma4:e2b":{id:"gemma4:e2b",name:"Gemma 4 E2B",maxTokens:8192,contextWindow:131072},"gemma4:e4b":{id:"gemma4:e4b",name:"Gemma 4 E4B",maxTokens:8192,contextWindow:131072},"gemma4:26b-a4b":{id:"gemma4:26b-a4b",name:"Gemma 4 26B A4B",maxTokens:16384,contextWindow:262144},"gemma4:31b":{id:"gemma4:31b",name:"Gemma 4 31B",maxTokens:16384,contextWindow:262144},"gemma4:31b-cloud":{id:"gemma4:31b-cloud",name:"Gemma 4 31B Cloud",maxTokens:16384,contextWindow:262144},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},Ul={coding:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b","deepseek-v4-pro:cloud"],agentic:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b","deepseek-v4-pro:cloud"],reasoning:["kimi-k2:1t","kimi-k2-thinking","kimi-k2.5"],"large-context":["qwen3-coder-next","qwen3.5:397b-cloud","kimi-k2.5"],frontend:["qwen3.5:397b-cloud","qwen3-coder-next","qwen3-coder:480b"],"quick-fix":["devstral-small-2:24b","qwen3-next:80b","ministral-3:14b","deepseek-v4-flash:cloud"],fallback:["devstral-small-2:24b","deepseek-v4-flash:cloud","deepseek-v3.2","qwen3.5:35b-a3b"],"open-source":["qwen3-coder:480b","devstral-2:123b","gpt-oss:120b"]};function c_(t="coding",e=5){let n=Ul[t]||Ul.coding;return n.map(s=>Mi[s]).filter(Boolean).concat(Object.values(Mi).filter(s=>!n.includes(s.id)).filter(s=>(s.recommendedFor||[]).includes(t))).sort((s,r)=>(r.quality||0)-(s.quality||0)).slice(0,e)}var Wl=class extends a_{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Mi,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){Oi.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Pi,httpsAgent:Ni}).then(e=>{let n=e.data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await Oi.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Pi,httpsAgent:Ni})).data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:n.role,content:o.join(`
3
+ `)};return s.length>0&&(r.images=s),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=$s.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),l;try{l=await Oi.post(`${this.baseUrl}${$s.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Pi,httpsAgent:Ni})}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 $s.normalizeResponse(l.data)}async stream(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),c=$s.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),u;try{u=await Oi.post(`${this.baseUrl}${$s.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:Pi,httpsAgent:Ni})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await l_(f,_=>_?.error),g=new Error(`API Error${h}: ${m}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=$s.createStreamParser(a,{onThinkingToken:l});return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{if(o.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,h(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return $s.normalizeResponse(e)}};gf.exports={OllamaProvider:Wl,OLLAMA_MODELS:Mi,OLLAMA_USE_CASES:Ul,getOllamaRecommendations:c_}});var Gl=J((GO,_f)=>{var bf=require("axios"),{BaseProvider:u_,readStreamErrorBody:d_}=_s(),{openaiProtocol:ks}=yo(),wf={"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}},Hl=class extends u_{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||wf,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool"){let n;return Array.isArray(e.content)?n=e.content.filter(s=>s.type==="text").map(s=>s.text).join(`
4
+ `)||JSON.stringify(e.content):n=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:n,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}prepareRequestBody(e,n={}){return e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),l=this.prepareRequestBody(ks.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),o),c;try{c=await bf.post(`${this.baseUrl}${ks.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 ks.normalizeResponse(c.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=this.prepareRequestBody(ks.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),o),u;try{u=await bf.post(`${this.baseUrl}${ks.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await d_(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=ks.createStreamParser(a);return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return ks.normalizeResponse(e)}};_f.exports={OpenAIProvider:Hl,OPENAI_MODELS:wf}});var xf=J((YO,kf)=>{var{OpenAIProvider:f_}=Gl(),$f={"deepseek-v4-flash":{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",maxTokens:16384,contextWindow:1048576,capability:"fast-coding",speed:"fast",quality:90,recommendedFor:["coding","quick-fix","fallback"]},"deepseek-v4-pro":{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",maxTokens:16384,contextWindow:1048576,capability:"agentic",speed:"balanced",quality:96,recommendedFor:["coding","agentic","reasoning","review"]}},Yl=class extends f_{constructor(e={}){super({name:"deepseek",baseUrl:e.baseUrl||process.env.DEEPSEEK_BASE_URL||"https://api.deepseek.com",models:e.models||$f,defaultModel:e.defaultModel||"deepseek-v4-flash",...e})}getApiKey(){return process.env.DEEPSEEK_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("DEEPSEEK_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}prepareRequestBody(e,n={}){let o=n.thinking||process.env.DEEPSEEK_THINKING;return{...e,thinking:o!==void 0?{type:o}:{type:"disabled"}}}};kf.exports={DeepSeekProvider:Yl,DEEPSEEK_MODELS:$f}});var Tf=J((zO,Ef)=>{var Sf=require("axios"),{BaseProvider:p_,readStreamErrorBody:h_}=_s(),{anthropicProtocol:Qn}=yo(),vf={"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}},m_="2023-06-01",zl=class extends p_{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||vf,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||m_}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n="",o=[];for(let s of e){if(s.role==="system"){n+=(n?`
5
5
 
6
- `:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=n[n.length-1],s;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});s=i}else s=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:s};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let o=[];for(let s of e.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return Qn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,{messages:l,system:c}=this.formatMessages(e),u=this.formatTools(n),d=Qn.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await kf.post(`${this.baseUrl}${Qn.getEndpoint()}`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let m=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${m}: ${g}`)}return Qn.normalizeResponse(f.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(n),f=Qn.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:u}}),h;try{h=await kf.post(`${this.baseUrl}${Qn.getEndpoint()}`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let _=g.response?.status?` [HTTP ${g.response.status}]`:"",k=await d_(g,$=>$?.error?.message||$?.error);throw new Error(`API Error${_}: ${k}`)}let m=Qn.createStreamParser(l);return new Promise((g,_)=>{o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),_(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{let{done:$,result:O}=m.feed(k.toString());$&&g(O)}),h.data.on("error",k=>{o.signal?.aborted||_(new Error(`Stream error: ${k.message}`))}),h.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return Qn.normalizeResponse(e)}};Sf.exports={AnthropicProvider:Gl,ANTHROPIC_MODELS:xf}});var Cf=J((HO,Rf)=>{var Ef=require("axios"),{BaseProvider:p_,readStreamErrorBody:h_}=ws(),{openaiProtocol:ks}=go(),Tf={"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}},Yl=class extends p_{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Tf,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),l=ks.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),c;try{c=await Ef.post(`${this.baseUrl}${ks.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 ks.normalizeResponse(c.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,a=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=ks.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),u;try{u=await Ef.post(`${this.baseUrl}${ks.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await h_(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=ks.createStreamParser(a);return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return ks.normalizeResponse(e)}};Rf.exports={GeminiProvider:Yl,GEMINI_MODELS:Tf}});var Pf=J((GO,Of)=>{var Mi=require("axios"),{BaseProvider:m_,readStreamErrorBody:g_}=ws(),{ollamaProtocol:xs}=go(),Af="http://localhost:11434",zl=class extends m_{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Af,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let n=(await Mi.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let a=await Mi.post(`${this.baseUrl}/api/show`,{name:s},{timeout:5e3}),l=a.data?.model_info||a.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
7
- `)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=xs.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await Mi.post(`${this.baseUrl}${xs.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 xs.normalizeResponse(i.data)}async stream(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i=xs.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await Mi.post(`${this.baseUrl}${xs.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 g_(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=xs.createStreamParser(r);return new Promise((c,u)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:h}=l.feed(d.toString());f&&c(h)}),a.data.on("error",d=>{o.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{c(l.flush())})})}normalizeResponse(e){return xs.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}};Of.exports={LocalProvider:zl,DEFAULT_LOCAL_URL:Af}});var pn=J((YO,qf)=>{"use strict";var Nf="\x1B[0m",Mf="\x1B[1m",yo="\x1B[2m";function Y(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function y_(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
8
- `),s=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),a=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function Lf(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function b_(t){try{let n=require("fs").readFileSync(Lf(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch(e){console.error("readThemeCache failed:",e.message)}return null}function w_(t,e){try{let n=require("fs"),o=require("path"),s=Lf(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"utf8"))}catch(l){console.error("theme cache failed:",l.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(s,JSON.stringify(i),"utf8")}catch{}}function __(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let n=process.env.TERM_SESSION_ID||"default",o=b_(n);if(o!==null)return o;let s=y_(),r=s!==null?s:!0;return w_(n,r),r}var If=__(),jf={reset:Nf,bold:Mf,dim:yo,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:yo,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:yo,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:yo,banner_model:yo,banner_yolo:Y(245,175,50),banner_gemini:Y(138,180,248),footer_sep:yo,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)},Df={reset:Nf,bold:Mf,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)},$_=If?jf:Df;qf.exports={T:$_,isDark:If,DARK:jf,LIGHT:Df}});var Ss=J((zO,Bf)=>{"use strict";var Ht=require("fs"),Ff=require("path");function k_(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function x_(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function S_(t,e){let n=Ff.dirname(t),o=Ff.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Ht.existsSync(n)||Ht.mkdirSync(n,{recursive:!0,mode:448}),Ht.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Ht.renameSync(o,t)}catch(s){try{Ht.unlinkSync(o)}catch{}throw s}}function v_(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Ht.openSync(s,"wx"),Ht.writeSync(i,Buffer.from(String(process.pid))),Ht.closeSync(i),i=-1;try{return e()}finally{try{Ht.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{Ht.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=Ht.readFileSync(s,"utf-8").trim(),c=parseInt(l,10);if(!k_(c)){try{Ht.unlinkSync(s)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Ht.unlinkSync(s)}catch{}return e()}x_(o)}}}Bf.exports={atomicWrite:S_,withFileLockSync:v_}});var Di=J((KO,Kf)=>{var bo=require("fs"),Kl=require("path"),{T:Li}=pn(),{atomicWrite:E_,withFileLockSync:T_}=Ss(),Uf={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}},deepseek:{"deepseek-v4-flash":{input:.14,output:.28},"deepseek-v4-pro":{input:.435,output:.87}},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-v4-pro:cloud":{input:0,output:0},"deepseek-v4-flash:cloud":{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:{}},R_=new Set(["ollama","local"]),C_=new Set(["openai","deepseek","anthropic","gemini"]),ji=[],es={},Ii=new Set;function tr(t){let e=String(t||"").toLowerCase();return R_.has(e)?{provider:e,tier:"affordable",paid:!1,label:e==="local"?"local open model":"open-model path",detail:e==="local"?"runs through a local Ollama server with no per-token API charge":"recommended affordable path for open coding models"}:C_.has(e)?{provider:e,tier:"premium",paid:!0,label:"premium paid provider",detail:"may incur per-token API charges; use /budget to cap spend"}:{provider:e,tier:"unknown",paid:null,label:"cost unknown",detail:"pricing is not known to nex-code"}}function A_(t){return tr(t).tier==="affordable"}function O_(t){return tr(t).tier==="premium"}function P_(t){let e=tr(t);return`${e.label} \u2014 ${e.detail}`}function N_(t,e,n,o,s=0){if(ji.push({provider:t,model:e,input:n,output:o,cacheRead:s}),es[t]!==void 0){let r=Yf(t);if(!r.allowed)process.stderr.write(`${Li.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${Li.reset}
9
- `);else if(r.limit>0&&r.spent>=r.limit*.8){let i=`${t}:${r.limit}:80`;Ii.has(i)||(Ii.add(i),process.stderr.write(`${Li.yellow}Budget warning for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)} used. Use /budget ${t} <amount> to raise the cap or /model ollama:<model> for the affordable path.${Li.reset}
10
- `))}}}function Vl(t,e){let n=Uf[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function Wf(t){let e=Vl(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Hf(){let t={};for(let i of ji){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:Wf(i)})),n=e.reduce((i,a)=>i+a.cost,0),o=e.reduce((i,a)=>i+a.input,0),s=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:n,totalInput:o,totalOutput:s,totalCacheRead:r,breakdown:e}}function M_(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=Hf();if(o.length===0)return"No token usage recorded this session.";let s=[];s.push("Session Token Usage:"),s.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free",a=tr(r.provider);s.push(` ${r.provider}:${r.model}`),s.push(` Path: ${a.label}`),s.push(` Input: ${r.input.toLocaleString()} tokens`),s.push(` Output: ${r.output.toLocaleString()} tokens`),s.push(` Cost: ${i}`)}return s.push(""),s.push(` Total: ${e.toLocaleString()} in + ${n.toLocaleString()} out = $${t.toFixed(4)}`),s.join(`
11
- `)}function L_(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function I_(t,e,n,o){let s=Vl(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function j_(){ji=[],Ii=new Set}function D_(t,e){es[t]=e}function q_(t){delete es[t]}function F_(){return{...es}}function Gf(t){let e=0;for(let n of ji)n.provider===t&&(e+=Wf(n));return e}function Yf(t){let e=Gf(t),n=es[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let o=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:o}}function zf(){let t=Kl.join(process.cwd(),".nex","config.json");if(bo.existsSync(t))try{let e=JSON.parse(bo.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(es={...e.costLimits})}catch{}}function B_(){let t=Kl.join(process.cwd(),".nex"),e=Kl.join(t,"config.json");bo.existsSync(t)||bo.mkdirSync(t,{recursive:!0}),T_(e,()=>{let n={};if(bo.existsSync(e))try{n=JSON.parse(bo.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=es,E_(e,JSON.stringify(n,null,2))})}function U_(){es={},Ii=new Set}zf();Kf.exports={PRICING:Uf,trackUsage:N_,getSessionCosts:Hf,formatCosts:M_,formatCostHint:I_,resetCosts:j_,getPricing:Vl,setCostLimit:D_,removeCostLimit:q_,getCostLimits:F_,getProviderSpend:Gf,checkBudget:Yf,getProviderCostMode:tr,formatProviderCostMode:P_,isAffordableProvider:A_,isPremiumProvider:O_,loadCostLimits:zf,saveCostLimits:B_,resetCostLimits:U_,estimateTokens:L_}});var Jl=J((VO,Jf)=>{var{BaseProvider:W_}=ws();function Ie(t,e,n){return{id:n||`mock-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:t,arguments:typeof e=="string"?e:JSON.stringify(e||{})}}}function Ye(t,e){return Array.isArray(t)&&t.some(n=>n?.role==="tool"&&n?.tool_call_id===e)}function H_(t){let e=Array.isArray(t)?[...t].reverse().find(n=>n?.role==="user"):null;return e?Xf(e):""}function Xf(t){return t?typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(e=>e?.type==="text"?e.text:"").filter(Boolean).join(`
12
- `):String(t.content||""):""}function G_(t){return Array.isArray(t)?t.filter(e=>e?.role==="user").map(e=>Xf(e)).filter(Boolean).join(`
6
+ `:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=n[n.length-1],s;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});s=i}else s=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:s};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let o=[];for(let s of e.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return Qn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,{messages:l,system:c}=this.formatMessages(e),u=this.formatTools(n),d=Qn.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Sf.post(`${this.baseUrl}${Qn.getEndpoint()}`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let m=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${m}: ${g}`)}return Qn.normalizeResponse(f.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(n),f=Qn.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:u}}),h;try{h=await Sf.post(`${this.baseUrl}${Qn.getEndpoint()}`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let _=g.response?.status?` [HTTP ${g.response.status}]`:"",k=await h_(g,$=>$?.error?.message||$?.error);throw new Error(`API Error${_}: ${k}`)}let m=Qn.createStreamParser(l);return new Promise((g,_)=>{o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),_(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{let{done:$,result:O}=m.feed(k.toString());$&&g(O)}),h.data.on("error",k=>{o.signal?.aborted||_(new Error(`Stream error: ${k.message}`))}),h.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return Qn.normalizeResponse(e)}};Ef.exports={AnthropicProvider:zl,ANTHROPIC_MODELS:vf}});var Of=J((KO,Af)=>{var Rf=require("axios"),{BaseProvider:g_,readStreamErrorBody:y_}=_s(),{openaiProtocol:xs}=yo(),Cf={"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}},Kl=class extends g_{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Cf,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),l=xs.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),c;try{c=await Rf.post(`${this.baseUrl}${xs.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 xs.normalizeResponse(c.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,a=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=xs.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),u;try{u=await Rf.post(`${this.baseUrl}${xs.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await y_(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=xs.createStreamParser(a);return new Promise((f,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return xs.normalizeResponse(e)}};Af.exports={GeminiProvider:Kl,GEMINI_MODELS:Cf}});var Mf=J((VO,Nf)=>{var Li=require("axios"),{BaseProvider:b_,readStreamErrorBody:w_}=_s(),{ollamaProtocol:Ss}=yo(),Pf="http://localhost:11434",Vl=class extends b_{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Pf,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let n=(await Li.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let a=await Li.post(`${this.baseUrl}/api/show`,{name:s},{timeout:5e3}),l=a.data?.model_info||a.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
7
+ `)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=Ss.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await Li.post(`${this.baseUrl}${Ss.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 Ss.normalizeResponse(i.data)}async stream(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i=Ss.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await Li.post(`${this.baseUrl}${Ss.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 w_(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=Ss.createStreamParser(r);return new Promise((c,u)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:h}=l.feed(d.toString());f&&c(h)}),a.data.on("error",d=>{o.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{c(l.flush())})})}normalizeResponse(e){return Ss.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}};Nf.exports={LocalProvider:Vl,DEFAULT_LOCAL_URL:Pf}});var pn=J((XO,Bf)=>{"use strict";var Lf="\x1B[0m",If="\x1B[1m",bo="\x1B[2m";function Y(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function __(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
8
+ `),s=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),a=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function jf(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function $_(t){try{let n=require("fs").readFileSync(jf(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch(e){console.error("readThemeCache failed:",e.message)}return null}function k_(t,e){try{let n=require("fs"),o=require("path"),s=jf(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"utf8"))}catch(l){console.error("theme cache failed:",l.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(s,JSON.stringify(i),"utf8")}catch{}}function x_(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let n=process.env.TERM_SESSION_ID||"default",o=$_(n);if(o!==null)return o;let s=__(),r=s!==null?s:!0;return k_(n,r),r}var Df=x_(),qf={reset:Lf,bold:If,dim:bo,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:bo,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:bo,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:bo,banner_model:bo,banner_yolo:Y(245,175,50),banner_gemini:Y(138,180,248),footer_sep:bo,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)},Ff={reset:Lf,bold:If,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)},S_=Df?qf:Ff;Bf.exports={T:S_,isDark:Df,DARK:qf,LIGHT:Ff}});var vs=J((JO,Wf)=>{"use strict";var Yt=require("fs"),Uf=require("path");function v_(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function E_(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function T_(t,e){let n=Uf.dirname(t),o=Uf.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Yt.existsSync(n)||Yt.mkdirSync(n,{recursive:!0,mode:448}),Yt.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Yt.renameSync(o,t)}catch(s){try{Yt.unlinkSync(o)}catch{}throw s}}function R_(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Yt.openSync(s,"wx"),Yt.writeSync(i,Buffer.from(String(process.pid))),Yt.closeSync(i),i=-1;try{return e()}finally{try{Yt.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{Yt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=Yt.readFileSync(s,"utf-8").trim(),c=parseInt(l,10);if(!v_(c)){try{Yt.unlinkSync(s)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Yt.unlinkSync(s)}catch{}return e()}E_(o)}}}Wf.exports={atomicWrite:T_,withFileLockSync:R_}});var qi=J((ZO,Xf)=>{var wo=require("fs"),Xl=require("path"),{T:Ii}=pn(),{atomicWrite:C_,withFileLockSync:A_}=vs(),Hf={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}},deepseek:{"deepseek-v4-flash":{input:.14,output:.28},"deepseek-v4-pro":{input:.435,output:.87}},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-v4-pro:cloud":{input:0,output:0},"deepseek-v4-flash:cloud":{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:{}},O_=new Set(["ollama","local"]),P_=new Set(["openai","deepseek","anthropic","gemini"]),Di=[],es={},ji=new Set;function nr(t){let e=String(t||"").toLowerCase();return O_.has(e)?{provider:e,tier:"affordable",paid:!1,label:e==="local"?"local open model":"open-model path",detail:e==="local"?"runs through a local Ollama server with no per-token API charge":"recommended affordable path for open coding models"}:P_.has(e)?{provider:e,tier:"premium",paid:!0,label:"premium paid provider",detail:"may incur per-token API charges; use /budget to cap spend"}:{provider:e,tier:"unknown",paid:null,label:"cost unknown",detail:"pricing is not known to nex-code"}}function N_(t){return nr(t).tier==="affordable"}function M_(t){return nr(t).tier==="premium"}function L_(t){let e=nr(t);return`${e.label} \u2014 ${e.detail}`}function I_(t,e,n,o,s=0){if(Di.push({provider:t,model:e,input:n,output:o,cacheRead:s}),es[t]!==void 0){let r=Kf(t);if(!r.allowed)process.stderr.write(`${Ii.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${Ii.reset}
9
+ `);else if(r.limit>0&&r.spent>=r.limit*.8){let i=`${t}:${r.limit}:80`;ji.has(i)||(ji.add(i),process.stderr.write(`${Ii.yellow}Budget warning for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)} used. Use /budget ${t} <amount> to raise the cap or /model ollama:<model> for the affordable path.${Ii.reset}
10
+ `))}}}function Jl(t,e){let n=Hf[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function Gf(t){let e=Jl(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Yf(){let t={};for(let i of Di){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:Gf(i)})),n=e.reduce((i,a)=>i+a.cost,0),o=e.reduce((i,a)=>i+a.input,0),s=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:n,totalInput:o,totalOutput:s,totalCacheRead:r,breakdown:e}}function j_(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=Yf();if(o.length===0)return"No token usage recorded this session.";let s=[];s.push("Session Token Usage:"),s.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free",a=nr(r.provider);s.push(` ${r.provider}:${r.model}`),s.push(` Path: ${a.label}`),s.push(` Input: ${r.input.toLocaleString()} tokens`),s.push(` Output: ${r.output.toLocaleString()} tokens`),s.push(` Cost: ${i}`)}return s.push(""),s.push(` Total: ${e.toLocaleString()} in + ${n.toLocaleString()} out = $${t.toFixed(4)}`),s.join(`
11
+ `)}function D_(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function q_(t,e,n,o){let s=Jl(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function F_(){Di=[],ji=new Set}function B_(t,e){es[t]=e}function U_(t){delete es[t]}function W_(){return{...es}}function zf(t){let e=0;for(let n of Di)n.provider===t&&(e+=Gf(n));return e}function Kf(t){let e=zf(t),n=es[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let o=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:o}}function Vf(){let t=Xl.join(process.cwd(),".nex","config.json");if(wo.existsSync(t))try{let e=JSON.parse(wo.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(es={...e.costLimits})}catch{}}function H_(){let t=Xl.join(process.cwd(),".nex"),e=Xl.join(t,"config.json");wo.existsSync(t)||wo.mkdirSync(t,{recursive:!0}),A_(e,()=>{let n={};if(wo.existsSync(e))try{n=JSON.parse(wo.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=es,C_(e,JSON.stringify(n,null,2))})}function G_(){es={},ji=new Set}Vf();Xf.exports={PRICING:Hf,trackUsage:I_,getSessionCosts:Yf,formatCosts:j_,formatCostHint:q_,resetCosts:F_,getPricing:Jl,setCostLimit:B_,removeCostLimit:U_,getCostLimits:W_,getProviderSpend:zf,checkBudget:Kf,getProviderCostMode:nr,formatProviderCostMode:L_,isAffordableProvider:N_,isPremiumProvider:M_,loadCostLimits:Vf,saveCostLimits:H_,resetCostLimits:G_,estimateTokens:D_}});var Ql=J((QO,Qf)=>{var{BaseProvider:Y_}=_s();function je(t,e,n){return{id:n||`mock-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:t,arguments:typeof e=="string"?e:JSON.stringify(e||{})}}}function ze(t,e){return Array.isArray(t)&&t.some(n=>n?.role==="tool"&&n?.tool_call_id===e)}function z_(t){let e=Array.isArray(t)?[...t].reverse().find(n=>n?.role==="user"):null;return e?Zf(e):""}function Zf(t){return t?typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(e=>e?.type==="text"?e.text:"").filter(Boolean).join(`
12
+ `):String(t.content||""):""}function K_(t){return Array.isArray(t)?t.filter(e=>e?.role==="user").map(e=>Zf(e)).filter(Boolean).join(`
13
13
 
14
- `):""}var qi=null;function Y_(){return qi||(qi={scenario:null,lastStep:0},qi)}var z_=`// Scenario A fixture: refactor callback-based flow to async/await.
14
+ `):""}var Fi=null;function V_(){return Fi||(Fi={scenario:null,lastStep:0},Fi)}var X_=`// Scenario A fixture: refactor callback-based flow to async/await.
15
15
 
16
16
  function fakeApiGet(path, cb) {
17
17
  setTimeout(() => {
@@ -45,7 +45,7 @@ async function getUserAndPosts(userId) {
45
45
  process.exitCode = 1;
46
46
  }
47
47
  })();
48
- `,K_=`// Applies a percentage discount to a price in cents.
48
+ `,J_=`// Applies a percentage discount to a price in cents.
49
49
 
50
50
  function applyPercentDiscount(totalCents, percent) {
51
51
  // percent is a whole number (e.g. 10 for 10%).
@@ -55,9 +55,9 @@ function applyPercentDiscount(totalCents, percent) {
55
55
  }
56
56
 
57
57
  module.exports = { applyPercentDiscount };
58
- `;function V_(){return["# Scenario C fixture: nginx config with a deliberate syntax error.","","worker_processes 1;","","events {"," worker_connections 1024;","}","","http {"," server {"," listen 8080;",""," location / {"," proxy_pass http://127.0.0.1:3000;"," }"," }","}",""].join(`
59
- `)}function X_(){return["#!/usr/bin/env bash","set -euo pipefail","","# Dry-run nginx restart helper for the sandbox mock environment.","# This prepends the sandbox's fake binaries to PATH, validates the config,","# then performs a fake systemctl restart.","",'ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"','export PATH="$ROOT/bin:$PATH"',"","# Safety check: refuse to run unless we are using the sandboxed binaries.",'sysctl_path="$(command -v systemctl || true)"','nginx_path="$(command -v nginx || true)"','if [[ "$sysctl_path" != "$ROOT/bin/systemctl" ]]; then',' echo "Refusing to run: systemctl is not sandboxed ($sysctl_path)" >&2'," exit 2","fi",'if [[ "$nginx_path" != "$ROOT/bin/nginx" ]]; then',' echo "Refusing to run: nginx is not sandboxed ($nginx_path)" >&2'," exit 2","fi","",'CONF="$ROOT/sandbox-local/etc/nginx/nginx.conf"',"",'nginx -t -c "$CONF"',"","# Fake systemctl prints a dry-run message and exits 0.","systemctl restart nginx",""].join(`
60
- `)}var J_=`// Scenario E fixture: nested callback flow with a simulated missing dependency.
58
+ `;function Z_(){return["# Scenario C fixture: nginx config with a deliberate syntax error.","","worker_processes 1;","","events {"," worker_connections 1024;","}","","http {"," server {"," listen 8080;",""," location / {"," proxy_pass http://127.0.0.1:3000;"," }"," }","}",""].join(`
59
+ `)}function Q_(){return["#!/usr/bin/env bash","set -euo pipefail","","# Dry-run nginx restart helper for the sandbox mock environment.","# This prepends the sandbox's fake binaries to PATH, validates the config,","# then performs a fake systemctl restart.","",'ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"','export PATH="$ROOT/bin:$PATH"',"","# Safety check: refuse to run unless we are using the sandboxed binaries.",'sysctl_path="$(command -v systemctl || true)"','nginx_path="$(command -v nginx || true)"','if [[ "$sysctl_path" != "$ROOT/bin/systemctl" ]]; then',' echo "Refusing to run: systemctl is not sandboxed ($sysctl_path)" >&2'," exit 2","fi",'if [[ "$nginx_path" != "$ROOT/bin/nginx" ]]; then',' echo "Refusing to run: nginx is not sandboxed ($nginx_path)" >&2'," exit 2","fi","",'CONF="$ROOT/sandbox-local/etc/nginx/nginx.conf"',"",'nginx -t -c "$CONF"',"","# Fake systemctl prints a dry-run message and exits 0.","systemctl restart nginx",""].join(`
60
+ `)}var e$=`// Scenario E fixture: nested callback flow with a simulated missing dependency.
61
61
 
62
62
  function loadJson(file, cb) {
63
63
  setTimeout(() => {
@@ -100,57 +100,57 @@ run()
100
100
  console.error(err.message);
101
101
  process.exitCode = 1;
102
102
  });
103
- `;function Z_(){return["# Scenario F fixture: subtle nginx typo in a sandboxed mock root.","events { worker_connections 128; }","http {"," upstream app_backend {"," server 127.0.0.1:3000;"," }"," server {"," listen 8081;"," location /api {"," proxy_pass http://app_backend;"," }"," }","}",""].join(`
104
- `)}function Q_(t){let e=String(t||"");return/malformed tool call/i.test(e)?"malformed":/Scenario G|merge conflicts/i.test(e)?"g":/Scenario F|dummy systemctl|sandboxed nginx config typo/i.test(e)?"f":/Scenario E|legacy callback processor|nested callback/i.test(e)?"e":/mocked server environment|nginx/i.test(e)?"c":/discount|node\s+src\/main\.js/i.test(e)?"b":/async\s*\/\s*await|Refactor\s+app\.js/i.test(e)?"a":/tool budget|budget stop/i.test(e)?"d":null}function Vf(t){let e=G_(t),n=Q_(e||H_(t)),o=Y_();!o.scenario&&n&&(o.scenario=n);let s=o.scenario||n;if(process.env.NEX_MOCK_MALFORMED_TOOL_CALL==="1"||s==="malformed"){let r=Ye(t,"m1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Simulating a malformed tool call to test CLI error handling.",tool_calls:[Ie("read_file","}{","m1")]}):{content:"Final report: the CLI handled a malformed tool call without hanging. The tool arguments were not valid JSON, so execution was blocked and the session concluded safely.",tool_calls:[]}}if(s==="a"){let r=Ye(t,"a3")?3:Ye(t,"a2")?2:Ye(t,"a1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Inspecting current implementation.",tool_calls:[Ie("read_file",{path:"app.js"},"a1")]}):o.lastStep<2?(o.lastStep=2,{content:"Applying async/await refactor.",tool_calls:[Ie("write_file",{path:"app.js",content:z_},"a2")]}):o.lastStep<3?(o.lastStep=3,{content:"Verifying behavior.",tool_calls:[Ie("bash",{command:"node app.js"},"a3")]}):{content:"Refactored the callback-based flow to Promises + async/await and verified the script still runs successfully.",tool_calls:[]}}if(s==="b"){let r=Ye(t,"b4")?4:Ye(t,"b3")?3:Ye(t,"b2")?2:Ye(t,"b1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Reading the failing entry point.",tool_calls:[Ie("read_file",{path:"src/main.js"},"b1")]}):o.lastStep<2?(o.lastStep=2,{content:"Locating the bug in discount calculation.",tool_calls:[Ie("read_file",{path:"src/discount.js"},"b2")]}):o.lastStep<3?(o.lastStep=3,{content:"Fixing discount logic.",tool_calls:[Ie("write_file",{path:"src/discount.js",content:K_},"b3")]}):o.lastStep<4?(o.lastStep=4,{content:"Verifying the fix.",tool_calls:[Ie("bash",{command:"node src/main.js"},"b4")]}):{content:"Fixed the percent discount bug (10 now correctly means 10%) and verified the script runs without throwing.",tool_calls:[]}}if(s==="c"){let r=Ye(t,"c5")?5:Ye(t,"c4")?4:Ye(t,"c3")||Ye(t,"c2")?3:Ye(t,"c1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Inspecting nginx configuration.",tool_calls:[Ie("read_file",{path:"sandbox-local/etc/nginx/nginx.conf"},"c1")]}):o.lastStep<3?(o.lastStep=3,{content:"Fixing nginx config syntax error and adding dry-run restart helper.",tool_calls:[Ie("write_file",{path:"sandbox-local/etc/nginx/nginx.conf",content:V_()},"c2"),Ie("write_file",{path:"restart-nginx-dry-run.sh",content:X_()},"c3")]}):o.lastStep<4?(o.lastStep=4,{content:"Making the restart helper executable.",tool_calls:[Ie("bash",{command:"chmod +x restart-nginx-dry-run.sh"},"c4")]}):o.lastStep<5?(o.lastStep=5,{content:"Verifying dry-run restart in the sandbox.",tool_calls:[Ie("bash",{command:"./restart-nginx-dry-run.sh"},"c5")]}):{content:"Fixed the nginx syntax error (missing semicolon) and added a sandbox-only dry-run restart script that validates the config then performs a fake systemctl restart.",tool_calls:[]}}if(s==="d"){let r=Ye(t,"d1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Investigating.",tool_calls:[Ie("list_directory",{path:".",max_depth:2},"d1"),Ie("glob",{pattern:"**/*.js"},"d2"),Ie("grep",{pattern:"fakeApiGet",path:"."},"d3"),Ie("read_file",{path:"README.md"},"d4"),Ie("read_file",{path:"app.js"},"d5"),Ie("search_files",{path:".",pattern:"getUserAndPosts"},"d6")]}):{content:"Final summary: tool budget enforcement worked; no further tool calls were executed.",tool_calls:[]}}if(s==="e"){let r=Ye(t,"e3")?3:Ye(t,"e2")?2:Ye(t,"e1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Reading the legacy callback processor.",tool_calls:[Ie("read_file",{path:"processor.js"},"e1")]}):o.lastStep<2?(o.lastStep=2,{content:"Refactoring nested callbacks to async helpers without adding dependencies.",tool_calls:[Ie("write_file",{path:"processor.js",content:J_},"e2")]}):o.lastStep<3?(o.lastStep=3,{content:"Verifying the refactored processor.",tool_calls:[Ie("bash",{command:"node processor.js"},"e3")]}):{content:"Refactored the nested callback processor to async/await without adding dependencies and verified the output.",tool_calls:[]}}if(s==="f"){let r=Ye(t,"f3")?3:Ye(t,"f2")?2:Ye(t,"f1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Reading the sandboxed nginx config.",tool_calls:[Ie("read_file",{path:"mock-root/etc/nginx/nginx.conf"},"f1")]}):o.lastStep<2?(o.lastStep=2,{content:"Fixing the upstream name typo.",tool_calls:[Ie("write_file",{path:"mock-root/etc/nginx/nginx.conf",content:Z_()},"f2")]}):o.lastStep<3?(o.lastStep=3,{content:"Checking the dummy service command stays sandboxed.",tool_calls:[Ie("bash",{command:'PATH="$PWD/bin:$PATH" systemctl reload nginx'},"f3")]}):{content:"Fixed the sandboxed nginx upstream typo and verified only the dummy systemctl executable was invoked.",tool_calls:[]}}if(s==="g"){let r=Ye(t,"g5")?5:Ye(t,"g4")?4:Ye(t,"g3")||Ye(t,"g2")?3:Ye(t,"g1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Inspecting simulated conflict markers.",tool_calls:[Ie("grep",{pattern:"<<<<<<<|=======|>>>>>>>",path:"."},"g1")]}):o.lastStep<3?(o.lastStep=3,{content:"Reading conflicted files.",tool_calls:[Ie("read_file",{path:"service.js"},"g2"),Ie("read_file",{path:"README.md"},"g3")]}):o.lastStep<5?(o.lastStep=5,{content:"Resolving conflicts by preserving configurable behavior.",tool_calls:[Ie("write_file",{path:"service.js",content:`function port() { return Number(process.env.PORT || 3000); }
103
+ `;function t$(){return["# Scenario F fixture: subtle nginx typo in a sandboxed mock root.","events { worker_connections 128; }","http {"," upstream app_backend {"," server 127.0.0.1:3000;"," }"," server {"," listen 8081;"," location /api {"," proxy_pass http://app_backend;"," }"," }","}",""].join(`
104
+ `)}function n$(t){let e=String(t||"");return/malformed tool call/i.test(e)?"malformed":/Scenario G|merge conflicts/i.test(e)?"g":/Scenario F|dummy systemctl|sandboxed nginx config typo/i.test(e)?"f":/Scenario E|legacy callback processor|nested callback/i.test(e)?"e":/mocked server environment|nginx/i.test(e)?"c":/discount|node\s+src\/main\.js/i.test(e)?"b":/async\s*\/\s*await|Refactor\s+app\.js/i.test(e)?"a":/tool budget|budget stop/i.test(e)?"d":null}function Jf(t){let e=K_(t),n=n$(e||z_(t)),o=V_();!o.scenario&&n&&(o.scenario=n);let s=o.scenario||n;if(process.env.NEX_MOCK_MALFORMED_TOOL_CALL==="1"||s==="malformed"){let r=ze(t,"m1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Simulating a malformed tool call to test CLI error handling.",tool_calls:[je("read_file","}{","m1")]}):{content:"Final report: the CLI handled a malformed tool call without hanging. The tool arguments were not valid JSON, so execution was blocked and the session concluded safely.",tool_calls:[]}}if(s==="a"){let r=ze(t,"a3")?3:ze(t,"a2")?2:ze(t,"a1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Inspecting current implementation.",tool_calls:[je("read_file",{path:"app.js"},"a1")]}):o.lastStep<2?(o.lastStep=2,{content:"Applying async/await refactor.",tool_calls:[je("write_file",{path:"app.js",content:X_},"a2")]}):o.lastStep<3?(o.lastStep=3,{content:"Verifying behavior.",tool_calls:[je("bash",{command:"node app.js"},"a3")]}):{content:"Refactored the callback-based flow to Promises + async/await and verified the script still runs successfully.",tool_calls:[]}}if(s==="b"){let r=ze(t,"b4")?4:ze(t,"b3")?3:ze(t,"b2")?2:ze(t,"b1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Reading the failing entry point.",tool_calls:[je("read_file",{path:"src/main.js"},"b1")]}):o.lastStep<2?(o.lastStep=2,{content:"Locating the bug in discount calculation.",tool_calls:[je("read_file",{path:"src/discount.js"},"b2")]}):o.lastStep<3?(o.lastStep=3,{content:"Fixing discount logic.",tool_calls:[je("write_file",{path:"src/discount.js",content:J_},"b3")]}):o.lastStep<4?(o.lastStep=4,{content:"Verifying the fix.",tool_calls:[je("bash",{command:"node src/main.js"},"b4")]}):{content:"Fixed the percent discount bug (10 now correctly means 10%) and verified the script runs without throwing.",tool_calls:[]}}if(s==="c"){let r=ze(t,"c5")?5:ze(t,"c4")?4:ze(t,"c3")||ze(t,"c2")?3:ze(t,"c1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Inspecting nginx configuration.",tool_calls:[je("read_file",{path:"sandbox-local/etc/nginx/nginx.conf"},"c1")]}):o.lastStep<3?(o.lastStep=3,{content:"Fixing nginx config syntax error and adding dry-run restart helper.",tool_calls:[je("write_file",{path:"sandbox-local/etc/nginx/nginx.conf",content:Z_()},"c2"),je("write_file",{path:"restart-nginx-dry-run.sh",content:Q_()},"c3")]}):o.lastStep<4?(o.lastStep=4,{content:"Making the restart helper executable.",tool_calls:[je("bash",{command:"chmod +x restart-nginx-dry-run.sh"},"c4")]}):o.lastStep<5?(o.lastStep=5,{content:"Verifying dry-run restart in the sandbox.",tool_calls:[je("bash",{command:"./restart-nginx-dry-run.sh"},"c5")]}):{content:"Fixed the nginx syntax error (missing semicolon) and added a sandbox-only dry-run restart script that validates the config then performs a fake systemctl restart.",tool_calls:[]}}if(s==="d"){let r=ze(t,"d1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Investigating.",tool_calls:[je("list_directory",{path:".",max_depth:2},"d1"),je("glob",{pattern:"**/*.js"},"d2"),je("grep",{pattern:"fakeApiGet",path:"."},"d3"),je("read_file",{path:"README.md"},"d4"),je("read_file",{path:"app.js"},"d5"),je("search_files",{path:".",pattern:"getUserAndPosts"},"d6")]}):{content:"Final summary: tool budget enforcement worked; no further tool calls were executed.",tool_calls:[]}}if(s==="e"){let r=ze(t,"e3")?3:ze(t,"e2")?2:ze(t,"e1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Reading the legacy callback processor.",tool_calls:[je("read_file",{path:"processor.js"},"e1")]}):o.lastStep<2?(o.lastStep=2,{content:"Refactoring nested callbacks to async helpers without adding dependencies.",tool_calls:[je("write_file",{path:"processor.js",content:e$},"e2")]}):o.lastStep<3?(o.lastStep=3,{content:"Verifying the refactored processor.",tool_calls:[je("bash",{command:"node processor.js"},"e3")]}):{content:"Refactored the nested callback processor to async/await without adding dependencies and verified the output.",tool_calls:[]}}if(s==="f"){let r=ze(t,"f3")?3:ze(t,"f2")?2:ze(t,"f1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Reading the sandboxed nginx config.",tool_calls:[je("read_file",{path:"mock-root/etc/nginx/nginx.conf"},"f1")]}):o.lastStep<2?(o.lastStep=2,{content:"Fixing the upstream name typo.",tool_calls:[je("write_file",{path:"mock-root/etc/nginx/nginx.conf",content:t$()},"f2")]}):o.lastStep<3?(o.lastStep=3,{content:"Checking the dummy service command stays sandboxed.",tool_calls:[je("bash",{command:'PATH="$PWD/bin:$PATH" systemctl reload nginx'},"f3")]}):{content:"Fixed the sandboxed nginx upstream typo and verified only the dummy systemctl executable was invoked.",tool_calls:[]}}if(s==="g"){let r=ze(t,"g5")?5:ze(t,"g4")?4:ze(t,"g3")||ze(t,"g2")?3:ze(t,"g1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Inspecting simulated conflict markers.",tool_calls:[je("grep",{pattern:"<<<<<<<|=======|>>>>>>>",path:"."},"g1")]}):o.lastStep<3?(o.lastStep=3,{content:"Reading conflicted files.",tool_calls:[je("read_file",{path:"service.js"},"g2"),je("read_file",{path:"README.md"},"g3")]}):o.lastStep<5?(o.lastStep=5,{content:"Resolving conflicts by preserving configurable behavior.",tool_calls:[je("write_file",{path:"service.js",content:`function port() { return Number(process.env.PORT || 3000); }
105
105
 
106
106
  module.exports = { port };
107
- `},"g4"),Ie("write_file",{path:"README.md",content:`Run the service with PORT=3001 node service.js.
108
- `},"g5")]}):{content:"Resolved the simulated multi-file git conflict while preserving the configurable port behavior.",tool_calls:[]}}return{content:"No mock scenario matched this prompt. Set a Scenario A\u2013G prompt (or enable malformed mode) to run deterministic E2E flows.",tool_calls:[]}}var Xl=class extends W_{constructor(e={}){super({name:"mock",baseUrl:"mock://",models:{"mock-model":{id:"mock-model",name:"Mock Model",maxTokens:4096,contextWindow:8192}},defaultModel:"mock-model",...e})}isConfigured(){return process.env.NEX_MOCK_PROVIDER==="1"}async chat(e,n,o={}){return Vf(e)}async stream(e,n,o={}){let s=typeof o.onToken=="function"?o.onToken:()=>{},r=Vf(e),i=String(r.content||""),a=Math.min(i.length,Math.max(1,Math.floor(i.length/2)));return i&&(s(i.slice(0,a)),s(i.slice(a))),r}normalizeResponse(e){return e}};Jf.exports={MockProvider:Xl}});var Zl=J((XO,e$)=>{e$.exports={name:"nex-code",version:"0.5.20",description:"Run 400B+ open coding models on your codebase without the hardware bill. Ollama Cloud first \u2014 OpenAI, Anthropic, and Gemini when you need them.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","examples/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --runInBand","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",format:"prettier --write .","scan:secrets":"node scripts/secret-scan.js --staged","install-hooks":"ln -sf ../../hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-commit, pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0",prettier:"^3.8.1",typescript:"^5.9.3"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var vs=J((JO,sp)=>{var{T:z}=pn(),Ql=5,wo=(()=>{let t=[];for(let e=0;e<Ql;e++)t.push(e);for(let e=Ql-2;e>=1;e--)t.push(e);return t})(),Zf=["\u273D","\u2726","\u2727","\u2726"],Qf=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function ep(t=""){let e=String(t).toLowerCase();return e.includes("search")||e.includes("read")||e.includes("list")||e.includes("inspect")?{glyph:"\u25CC",color:z.cyan,accent:"scan"}:e.includes("write")||e.includes("edit")||e.includes("patch")||e.includes("build")?{glyph:"\u2726",color:z.yellow,accent:"shape"}:e.includes("test")||e.includes("diff")||e.includes("check")||e.includes("verify")?{glyph:"\u25A3",color:z.green,accent:"verify"}:e.includes("wait")||e.includes("github")||e.includes("fetch")||e.includes("browser")?{glyph:"\u25CD",color:z.blue,accent:"wait"}:{glyph:"\u25CF",color:z.cyan,accent:"think"}}function tp(t,e,n){let o="";for(let s=0;s<Ql;s++)s===t?o+=`${n}${e}${z.reset}`:s===t-1||s===t+1?o+=`${z.dim}\xB7${z.reset}`:o+=`${z.dim}\xB7${z.reset}`;return o}function np(t){return`${z.dim}${Qf[t%Qf.length]}${z.reset}`}var ec=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=wo[this.frame%wo.length],n=ep(this.text),o=tp(e,n.glyph,n.color),s=np(this.frame),r="";if(this.startTime){let i=Math.floor((Date.now()-this.startTime)/1e3);if(i>=60){let a=Math.floor(i/60),l=i%60;r=` ${z.dim}${a}m ${String(l).padStart(2,"0")}s${z.reset}`}else i>=1&&(r=` ${z.dim}${i}s${z.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${z.reset}${s} ${o} ${z.dim}${this.text}${z.reset}${r}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},tc=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let e=wo[this.frame%wo.length],n=`${z.cyan}\u25CC${z.reset}`,o=this._formatElapsed(),s=o?` ${z.dim}${o}${z.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=`${z.green}\u2713${z.reset}`,c=z.dim;break;case"error":l=`${z.red}\u2717${z.reset}`,c=z.dim;break;case"retry":l=`${z.yellow}\u21BB${z.reset}`,c=z.yellow;break;default:l=a===e?n:`${z.dim}\xB7${z.reset}`,c=""}let u=a===this.labels.length-1?s:"",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}${z.reset}${u}
107
+ `},"g4"),je("write_file",{path:"README.md",content:`Run the service with PORT=3001 node service.js.
108
+ `},"g5")]}):{content:"Resolved the simulated multi-file git conflict while preserving the configurable port behavior.",tool_calls:[]}}return{content:"No mock scenario matched this prompt. Set a Scenario A\u2013G prompt (or enable malformed mode) to run deterministic E2E flows.",tool_calls:[]}}var Zl=class extends Y_{constructor(e={}){super({name:"mock",baseUrl:"mock://",models:{"mock-model":{id:"mock-model",name:"Mock Model",maxTokens:4096,contextWindow:8192}},defaultModel:"mock-model",...e})}isConfigured(){return process.env.NEX_MOCK_PROVIDER==="1"}async chat(e,n,o={}){return Jf(e)}async stream(e,n,o={}){let s=typeof o.onToken=="function"?o.onToken:()=>{},r=Jf(e),i=String(r.content||""),a=Math.min(i.length,Math.max(1,Math.floor(i.length/2)));return i&&(s(i.slice(0,a)),s(i.slice(a))),r}normalizeResponse(e){return e}};Qf.exports={MockProvider:Zl}});var ec=J((eP,s$)=>{s$.exports={name:"nex-code",version:"0.5.22",description:"Run 400B+ open coding models on your codebase without the hardware bill. Ollama Cloud first \u2014 OpenAI, Anthropic, and Gemini when you need them.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","examples/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --runInBand","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",format:"prettier --write .","scan:secrets":"node scripts/secret-scan.js --staged","install-hooks":"ln -sf ../../hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-commit, pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0",prettier:"^3.8.1",typescript:"^5.9.3"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var Es=J((tP,rp)=>{var{T:z}=pn(),tc=5,_o=(()=>{let t=[];for(let e=0;e<tc;e++)t.push(e);for(let e=tc-2;e>=1;e--)t.push(e);return t})(),ep=["\u273D","\u2726","\u2727","\u2726"],tp=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function np(t=""){let e=String(t).toLowerCase();return e.includes("search")||e.includes("read")||e.includes("list")||e.includes("inspect")?{glyph:"\u25CC",color:z.cyan,accent:"scan"}:e.includes("write")||e.includes("edit")||e.includes("patch")||e.includes("build")?{glyph:"\u2726",color:z.yellow,accent:"shape"}:e.includes("test")||e.includes("diff")||e.includes("check")||e.includes("verify")?{glyph:"\u25A3",color:z.green,accent:"verify"}:e.includes("wait")||e.includes("github")||e.includes("fetch")||e.includes("browser")?{glyph:"\u25CD",color:z.blue,accent:"wait"}:{glyph:"\u25CF",color:z.cyan,accent:"think"}}function sp(t,e,n){let o="";for(let s=0;s<tc;s++)s===t?o+=`${n}${e}${z.reset}`:s===t-1||s===t+1?o+=`${z.dim}\xB7${z.reset}`:o+=`${z.dim}\xB7${z.reset}`;return o}function op(t){return`${z.dim}${tp[t%tp.length]}${z.reset}`}var nc=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=_o[this.frame%_o.length],n=np(this.text),o=sp(e,n.glyph,n.color),s=op(this.frame),r="";if(this.startTime){let i=Math.floor((Date.now()-this.startTime)/1e3);if(i>=60){let a=Math.floor(i/60),l=i%60;r=` ${z.dim}${a}m ${String(l).padStart(2,"0")}s${z.reset}`}else i>=1&&(r=` ${z.dim}${i}s${z.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${z.reset}${s} ${o} ${z.dim}${this.text}${z.reset}${r}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},sc=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let e=_o[this.frame%_o.length],n=`${z.cyan}\u25CC${z.reset}`,o=this._formatElapsed(),s=o?` ${z.dim}${o}${z.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=`${z.green}\u2713${z.reset}`,c=z.dim;break;case"error":l=`${z.red}\u2717${z.reset}`,c=z.dim;break;case"retry":l=`${z.yellow}\u21BB${z.reset}`,c=z.yellow;break;default:l=a===e?n:`${z.dim}\xB7${z.reset}`,c=""}let u=a===this.labels.length-1?s:"",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}${z.reset}${u}
109
109
  `}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
110
110
  `;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,n){e>=0&&e<this.statuses.length&&(this.statuses[e]=n)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let n="";for(let o=0;o<this.lineCount;o++)n+=`\x1B[2K
111
111
  `;this.lineCount>0&&(n+=`\x1B[${this.lineCount}A`),process.stderr.write(n)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),n=e?` ${z.dim}${e}${z.reset}`:"",o=process.stderr.columns||80,s="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${z.green}\u2713${z.reset}`;break;case"error":i=`${z.red}\u2717${z.reset}`;break;case"retry":i=`${z.yellow}\u21BB${z.reset}`;break;default:i=`${z.yellow}\u25CB${z.reset}`}let a=r===this.labels.length-1?n:"",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];s+=`\x1B[2K ${i} ${z.dim}${c}${z.reset}${a}
112
- `}process.stderr.write(s)}},Fi={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Bi={done:z.green,in_progress:z.cyan,pending:z.dim,failed:z.red},ts=null,nc=class{constructor(e,n){this.name=e,this.tasks=n.map(o=>({id:o.id,description:o.description,status:o.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=Zf[this.frame%Zf.length],n=this._formatElapsed(),o=this._formatTokens(),s=[n,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=s?` ${z.dim}(${s})${z.reset}`:"",i=`\x1B[2K${z.cyan}${z.bold}${e}${z.reset} ${z.bold}${this.name}${z.reset}${z.dim}\u2026${z.reset}${r}
113
- `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=Fi[l.status]||Fi.pending,d=Bi[l.status]||Bi.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${z.dim}${c}${z.reset} ${d}${u}${z.reset} ${f}
112
+ `}process.stderr.write(s)}},Bi={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Ui={done:z.green,in_progress:z.cyan,pending:z.dim,failed:z.red},ts=null,oc=class{constructor(e,n){this.name=e,this.tasks=n.map(o=>({id:o.id,description:o.description,status:o.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=ep[this.frame%ep.length],n=this._formatElapsed(),o=this._formatTokens(),s=[n,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=s?` ${z.dim}(${s})${z.reset}`:"",i=`\x1B[2K${z.cyan}${z.bold}${e}${z.reset} ${z.bold}${this.name}${z.reset}${z.dim}\u2026${z.reset}${r}
113
+ `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=Bi[l.status]||Bi.pending,d=Ui[l.status]||Ui.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${z.dim}${c}${z.reset} ${d}${u}${z.reset} ${f}
114
114
  `}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
115
115
  `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),ts=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,ts===this&&(ts=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let n=0;n<this.lineCount;n++)e+=`\x1B[2K
116
116
  `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
117
117
  `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,n){let o=this.tasks.find(s=>s.id===e);o&&(o.status=n)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),n=this.tasks.filter(a=>a.status==="done").length,o=this.tasks.filter(a=>a.status==="failed").length,s=this.tasks.length,r=o>0?`${n}/${s} done, ${o} failed`:`${n}/${s} done`,i=`\x1B[2K${z.green}${z.bold}\u2714${z.reset} ${z.bold}${this.name}${z.reset} ${z.dim}(${e} \xB7 ${r})${z.reset}
118
- `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=Fi[l.status]||Fi.pending,d=Bi[l.status]||Bi.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${z.dim}${c}${z.reset} ${d}${u}${z.reset} ${z.dim}${f}${z.reset}
119
- `}process.stderr.write(i)}},sc=class{constructor(e,n){this.toolName=e,this.message=n||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=wo[this.frame%wo.length],n=ep(this.message),o=tp(e,n.glyph,n.color),s=np(this.frame),r=this.message;this.count>0&&(r+=` ${z.cyan}${this.count}${z.reset}`,this.total&&(r+=`/${this.total}`)),this.detail&&(r+=` ${z.dim}${this.detail}${z.reset}`);let i="";if(this.startTime){let a=Math.floor((Date.now()-this.startTime)/1e3);a>=1&&(i=` ${z.dim}${a}s${z.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${z.reset}${s} ${o} ${z.dim}${r}${z.reset}${i}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function t$(t){ts=t}function n$(){return ts}function s$(){ts&&(ts.stop(),ts=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}sp.exports={C:z,Spinner:ec,MultiProgress:tc,TaskProgress:nc,ToolProgress:sc,setActiveTaskProgress:t$,getActiveTaskProgress:n$,cleanupTerminal:s$}});var Ui=J((ZO,lp)=>{"use strict";var{T:Es}=pn(),me={kw:Es.syn_keyword,str:Es.syn_string,cmt:Es.syn_comment,num:Es.syn_number,type:Es.cyan,punct:Es.magenta,reset:Es.reset},op={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"])},o$={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 ip(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return o$[e]||null}var rp=/\x1b\[[0-9;]*m/g;function qn(t,e,n){let o=t.split(rp),s=t.match(rp)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,n),i<s.length&&(r+=s[i]);return r}function r$(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,n=>me.type+n+me.reset),e=qn(e,/"([^"\\]|\\.)*"/g,n=>me.str+n+me.reset),e=qn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,n=>me.num+n+me.reset),e=qn(e,/\b(true|false|null)\b/g,n=>me.kw+n+me.reset),e}function i$(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,n=>me.cmt+n+me.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(n,o,s)=>o+me.type+s+me.reset),e=qn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(n,o)=>" "+me.kw+o+me.reset+"="),e=qn(e,/"([^"]*)"/g,n=>me.str+n+me.reset),e}function a$(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,n=>me.cmt+n+me.reset),e=qn(e,/#[0-9a-fA-F]{3,8}\b/g,n=>me.num+n+me.reset),e=qn(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(n,o,s)=>me.num+o+me.reset+s),e=qn(e,/([a-z][a-z-]*)(\s*:)/g,(n,o,s)=>me.type+o+me.reset+s),e=qn(e,/"[^"]*"|'[^']*'/g,n=>me.str+n+me.reset),e}function ap(t,e,n){if(e==="json")return r$(t);if(e==="html"||e==="xml")return i$(t);if(e==="css")return a$(t);if(e==="md")return t;let o=op[e]||op.js,s="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return me.cmt+t+me.reset;if(s+=me.cmt+t.slice(0,i+2)+me.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return s}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return me.str+t+me.reset;if(s+=me.str+t.slice(0,i+1)+me.reset,n.inString=null,r=i+1,r>=t.length)return s}for(;r<t.length;){let i=t[r];if(!n.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return s+=me.cmt+t.slice(r)+me.reset,n.inBlockComment=!0,s;s+=me.cmt+t.slice(r,a+2)+me.reset,r=a+2;continue}if(!n.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return s+=me.cmt+t.slice(r)+me.reset,s;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,s+=me.str+i,r++;continue}if(n.inString){if(i==="\\"&&r+1<t.length){s+=i+t[r+1],r+=2;continue}if(i===n.inString){s+=i+me.reset,n.inString=null,r++;continue}s+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];s+=me.num+a+me.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];s+=me.punct+a+me.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];o.has(a)?s+=me.kw+a+me.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?s+=me.type+a+me.reset:s+=a;continue}s+=i,r++}return n.inString&&n.inString!=="`"&&(s+=me.reset,n.inString=null),s}function l$(t,e){let n=ip(e);if(!n)return t.split(`
118
+ `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=Bi[l.status]||Bi.pending,d=Ui[l.status]||Ui.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${z.dim}${c}${z.reset} ${d}${u}${z.reset} ${z.dim}${f}${z.reset}
119
+ `}process.stderr.write(i)}},rc=class{constructor(e,n){this.toolName=e,this.message=n||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=_o[this.frame%_o.length],n=np(this.message),o=sp(e,n.glyph,n.color),s=op(this.frame),r=this.message;this.count>0&&(r+=` ${z.cyan}${this.count}${z.reset}`,this.total&&(r+=`/${this.total}`)),this.detail&&(r+=` ${z.dim}${this.detail}${z.reset}`);let i="";if(this.startTime){let a=Math.floor((Date.now()-this.startTime)/1e3);a>=1&&(i=` ${z.dim}${a}s${z.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${z.reset}${s} ${o} ${z.dim}${r}${z.reset}${i}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function o$(t){ts=t}function r$(){return ts}function i$(){ts&&(ts.stop(),ts=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}rp.exports={C:z,Spinner:nc,MultiProgress:sc,TaskProgress:oc,ToolProgress:rc,setActiveTaskProgress:o$,getActiveTaskProgress:r$,cleanupTerminal:i$}});var Wi=J((nP,up)=>{"use strict";var{T:Ts}=pn(),ge={kw:Ts.syn_keyword,str:Ts.syn_string,cmt:Ts.syn_comment,num:Ts.syn_number,type:Ts.cyan,punct:Ts.magenta,reset:Ts.reset},ip={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"])},a$={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 lp(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return a$[e]||null}var ap=/\x1b\[[0-9;]*m/g;function qn(t,e,n){let o=t.split(ap),s=t.match(ap)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,n),i<s.length&&(r+=s[i]);return r}function l$(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,n=>ge.type+n+ge.reset),e=qn(e,/"([^"\\]|\\.)*"/g,n=>ge.str+n+ge.reset),e=qn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,n=>ge.num+n+ge.reset),e=qn(e,/\b(true|false|null)\b/g,n=>ge.kw+n+ge.reset),e}function c$(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,n=>ge.cmt+n+ge.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(n,o,s)=>o+ge.type+s+ge.reset),e=qn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(n,o)=>" "+ge.kw+o+ge.reset+"="),e=qn(e,/"([^"]*)"/g,n=>ge.str+n+ge.reset),e}function u$(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,n=>ge.cmt+n+ge.reset),e=qn(e,/#[0-9a-fA-F]{3,8}\b/g,n=>ge.num+n+ge.reset),e=qn(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(n,o,s)=>ge.num+o+ge.reset+s),e=qn(e,/([a-z][a-z-]*)(\s*:)/g,(n,o,s)=>ge.type+o+ge.reset+s),e=qn(e,/"[^"]*"|'[^']*'/g,n=>ge.str+n+ge.reset),e}function cp(t,e,n){if(e==="json")return l$(t);if(e==="html"||e==="xml")return c$(t);if(e==="css")return u$(t);if(e==="md")return t;let o=ip[e]||ip.js,s="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ge.cmt+t+ge.reset;if(s+=ge.cmt+t.slice(0,i+2)+ge.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return s}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return ge.str+t+ge.reset;if(s+=ge.str+t.slice(0,i+1)+ge.reset,n.inString=null,r=i+1,r>=t.length)return s}for(;r<t.length;){let i=t[r];if(!n.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return s+=ge.cmt+t.slice(r)+ge.reset,n.inBlockComment=!0,s;s+=ge.cmt+t.slice(r,a+2)+ge.reset,r=a+2;continue}if(!n.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return s+=ge.cmt+t.slice(r)+ge.reset,s;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,s+=ge.str+i,r++;continue}if(n.inString){if(i==="\\"&&r+1<t.length){s+=i+t[r+1],r+=2;continue}if(i===n.inString){s+=i+ge.reset,n.inString=null,r++;continue}s+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];s+=ge.num+a+ge.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];s+=ge.punct+a+ge.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];o.has(a)?s+=ge.kw+a+ge.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?s+=ge.type+a+ge.reset:s+=a;continue}s+=i,r++}return n.inString&&n.inString!=="`"&&(s+=ge.reset,n.inString=null),s}function d$(t,e){let n=lp(e);if(!n)return t.split(`
120
120
  `);let o=t.split(`
121
- `),s={inString:null,inBlockComment:!1};return o.map(r=>ap(r,n,s))}function c$(t,e){return e?ap(t,e,{inString:null,inBlockComment:!1}):t}lp.exports={detectLang:ip,highlightLine:c$,highlightLines:l$}});var wp=J((QO,bp)=>{var{T:x}=pn(),Ge=x,cp=require("path"),up=["\u23FA","\u25C9","\u25CE","\u25C9"];function Hi(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var u$={read_file:x.tool_read,list_directory:x.tool_read,write_file:x.tool_write,edit_file:x.tool_write,patch_file:x.tool_write,bash:x.tool_exec,grep:x.tool_search,search_files:x.tool_search,glob:x.tool_search,git_commit:x.tool_git,git_push:x.tool_git,git_pull:x.tool_git,git_status:x.tool_git,git_diff:x.tool_git,git_log:x.tool_git,git_branch:x.tool_git,git_stash:x.tool_git,web_fetch:x.tool_web,web_search:x.tool_web,sysadmin:x.tool_sysadmin,ssh_exec:x.tool_sysadmin,ssh_upload:x.tool_sysadmin,ssh_download:x.tool_sysadmin,deploy:x.tool_sysadmin},hp={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"},d$={read_file:{label:"Inspect",accent:x.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:x.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:x.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:x.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:x.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:x.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:x.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:x.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:x.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:x.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:x.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:x.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:x.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:x.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:x.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:x.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:x.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:x.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:x.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:x.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:x.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:x.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:x.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:x.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:x.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:x.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:x.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:x.tool_git,icon:"\u2713"}};function mp(t){return String(t||"").replace(/\x1B(?:\][^\x07]*(?:\x07|\x1B\\)|[PX^_][\s\S]*?\x1B\\)/g,"").replace(/[\x1B\x9B][[\]()#;?]*(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nq-uy=><]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}function f$(t){let e=t.trim();if(!e)return!1;let n=e.replace(/^[│┃┆┊>↩✓✗⚠◆●◉◎⏺◌✦▣•\-\s]+/,"").trim();return!!(/^(INSPECT|SHAPE|EXECUTE|EXPLORE|VERIFY|OPERATE|SHIP|SYNC|COMMIT|RUN|CAPTURE|INTERACT)\b/i.test(n)||/^Step\s+\d+\b/i.test(n)||/^(Read|Write|Edit|Patch|Bash|Grep|Search|Glob|WebFetch|WebSearch|TaskList|Agent|AskUser)\b.*\s→\s/i.test(n)||/^(Reading|Writing|Editing|Patching|Running|Searching|Listing|Fetching|Delegating|Switching)\b/i.test(n)||/^\[(?:context|auto|pre-flight|pre-stop|debug|system)\b/i.test(n)||/\b(?:auto-abort|Ctrl\+C to abort|Headless early exit|Phase transition|tool budget|model metadata|orchestration log)\b/i.test(n)||/^(?:Thinking|Analyzing|Planning|Implementing|Verifying|Working)(?:[.\s]|$)/i.test(n)||/^(?:Model|Provider|Tokens|Cost|Usage):\s/i.test(n))}function p$(t){let e=mp(t),n=[],o=!1;for(let s of e.split(/\r?\n/)){if(/^\s*```/.test(s)){o=!o,n.push(s.replace(/[ \t]+$/g,""));continue}!o&&f$(s)||n.push(s.replace(/[ \t]+$/g,""))}return n.join(`
121
+ `),s={inString:null,inBlockComment:!1};return o.map(r=>cp(r,n,s))}function f$(t,e){return e?cp(t,e,{inString:null,inBlockComment:!1}):t}up.exports={detectLang:lp,highlightLine:f$,highlightLines:d$}});var $p=J((sP,_p)=>{var{T:x}=pn(),Ye=x,dp=require("path"),fp=["\u23FA","\u25C9","\u25CE","\u25C9"];function Gi(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var p$={read_file:x.tool_read,list_directory:x.tool_read,write_file:x.tool_write,edit_file:x.tool_write,patch_file:x.tool_write,bash:x.tool_exec,grep:x.tool_search,search_files:x.tool_search,glob:x.tool_search,git_commit:x.tool_git,git_push:x.tool_git,git_pull:x.tool_git,git_status:x.tool_git,git_diff:x.tool_git,git_log:x.tool_git,git_branch:x.tool_git,git_stash:x.tool_git,web_fetch:x.tool_web,web_search:x.tool_web,sysadmin:x.tool_sysadmin,ssh_exec:x.tool_sysadmin,ssh_upload:x.tool_sysadmin,ssh_download:x.tool_sysadmin,deploy:x.tool_sysadmin},gp={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"},h$={read_file:{label:"Inspect",accent:x.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:x.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:x.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:x.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:x.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:x.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:x.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:x.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:x.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:x.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:x.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:x.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:x.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:x.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:x.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:x.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:x.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:x.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:x.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:x.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:x.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:x.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:x.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:x.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:x.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:x.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:x.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:x.tool_git,icon:"\u2713"}};function yp(t){return String(t||"").replace(/\x1B(?:\][^\x07]*(?:\x07|\x1B\\)|[PX^_][\s\S]*?\x1B\\)/g,"").replace(/[\x1B\x9B][[\]()#;?]*(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nq-uy=><]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}function m$(t){let e=t.trim();if(!e)return!1;let n=e.replace(/^[│┃┆┊>↩✓✗⚠◆●◉◎⏺◌✦▣•\-\s]+/,"").trim();return!!(/^(INSPECT|SHAPE|EXECUTE|EXPLORE|VERIFY|OPERATE|SHIP|SYNC|COMMIT|RUN|CAPTURE|INTERACT)\b/i.test(n)||/^Step\s+\d+\b/i.test(n)||/^(Read|Write|Edit|Patch|Bash|Grep|Search|Glob|WebFetch|WebSearch|TaskList|Agent|AskUser)\b.*\s→\s/i.test(n)||/^(Reading|Writing|Editing|Patching|Running|Searching|Listing|Fetching|Delegating|Switching)\b/i.test(n)||/^\[(?:context|auto|pre-flight|pre-stop|debug|system)\b/i.test(n)||/\b(?:auto-abort|Ctrl\+C to abort|Headless early exit|Phase transition|tool budget|model metadata|orchestration log)\b/i.test(n)||/^(?:Thinking|Analyzing|Planning|Implementing|Verifying|Working)(?:[.\s]|$)/i.test(n)||/^(?:Model|Provider|Tokens|Cost|Usage):\s/i.test(n))}function g$(t){let e=yp(t),n=[],o=!1;for(let s of e.split(/\r?\n/)){if(/^\s*```/.test(s)){o=!o,n.push(s.replace(/[ \t]+$/g,""));continue}!o&&m$(s)||n.push(s.replace(/[ \t]+$/g,""))}return n.join(`
122
122
  `).replace(/\n{3,}/g,`
123
123
 
124
- `).trim()}function rc(t){return d$[t]||{label:"Run",accent:x.tool_default,icon:"\u2022"}}function dp(t){let e=rc(t);return`${e.accent}${Ge.bold}${e.icon} ${e.label.toUpperCase()}${x.reset}`}function h$(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function fp(t,e={}){return e.path?Hi(e.path):e.file?Hi(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):hp[t]||h$(t)}function m$(t){return String(t||"").split(`
125
- `).map(e=>{let n=e.match(/^(\d+):\s?(.*)$/s);return n?{lineNumber:n[1],content:n[2]||""}:null}).filter(Boolean)}function g$(t,e,n={}){let{maxLines:o=4,indent:s=" ",maxContent:r=110,includeOverflow:i=!0}=n;if(!Array.isArray(e)||e.length===0)return"";let{highlightLine:a,detectLang:l}=Ui(),c=l(t||null),u=e.slice(0,o),d=u.map(({lineNumber:f,content:h})=>{let m=h.length>r?h.substring(0,r-1)+"\u2026":h;return`${s}${x.subtle}${f}:${x.reset} ${a(m,c)}${x.reset}`});return i&&e.length>u.length&&d.push(`${s}${x.subtle}\u2026 +${e.length-u.length} more line${e.length-u.length!==1?"s":""}${x.reset}`),d.join(`
126
- `)}function y$(t,e=96){let n=String(t||"").replace(/\t/g," ").trimEnd();return n.length>e?n.substring(0,Math.max(1,e-1))+"\u2026":n}function oc(t,e={}){let{maxLines:n=3,maxContent:o=96}=e,r=String(t||"").split(`
127
- `).filter((a,l,c)=>a.trim()||c.length===1||l===0),i=r.slice(0,n).map(a=>y$(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function gp(t,e={}){let{indent:n=" ",maxLines:o=2,maxContent:s=100}=e;if(!t)return"";let{shown:r,more:i}=oc(t,{maxLines:o,maxContent:s});if(r.length===0)return"";let a=r.map((l,c)=>`${n}${x.subtle}${c===0?"$":">"}${x.reset} ${x.muted}${l}${x.reset}`);return i>0&&a.push(`${n}${x.subtle}\u2026 +${i} more command line${i!==1?"s":""}${x.reset}`),a.join(`
128
- `)}function ic(t,e,n,o={}){let{indent:s=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=o,{highlightLine:l,detectLang:c}=Ui(),u=c(t||null),{shown:d,more:f}=oc(e,{maxLines:r,maxContent:i}),{shown:h,more:m}=oc(n,{maxLines:r,maxContent:i}),g=[];return d.length>0&&a&&g.push(`${s}${x.subtle}before${x.reset}`),d.forEach(_=>{g.push(`${s}${x.diff_rem}- ${x.reset}${l(_,u)}${x.reset}`)}),f>0&&g.push(`${s}${x.subtle}\u2026 ${f} more removed line${f!==1?"s":""}${x.reset}`),h.length>0&&a&&g.push(`${s}${x.subtle}after${x.reset}`),h.forEach(_=>{g.push(`${s}${x.diff_add}+ ${x.reset}${l(_,u)}${x.reset}`)}),m>0&&g.push(`${s}${x.subtle}\u2026 ${m} more added line${m!==1?"s":""}${x.reset}`),g.join(`
129
- `)}function yp(t,e,n={}){let{indent:o=" ",maxPatches:s=2,maxLinesPerSide:r=2,maxContent:i=92}=n;if(!Array.isArray(e)||e.length===0)return"";let a=[];return e.slice(0,s).forEach((l,c)=>{a.push(`${o}${x.subtle}patch ${c+1}${x.reset}`);let u=ic(t,l.old_text,l.new_text,{indent:o+" ",maxLines:r,maxContent:i,includeLabels:!1});u&&a.push(u)}),e.length>s&&a.push(`${o}${x.subtle}\u2026 +${e.length-s} more patches${x.reset}`),a.join(`
130
- `)}function b$(t){let e=new Set,n=[];for(let o of t){let s=rc(o.fnName).label;e.has(s)||(e.add(s),n.push(s))}return n.length===0?"":n.length<=3?n.join(`${Ge.dim} \u2192 ${Ge.reset}`):`${n.slice(0,3).join(`${Ge.dim} \u2192 ${Ge.reset}`)}${Ge.dim} \u2192 +${n.length-3}${Ge.reset}`}function Wi(t,e=!1,n=null){if(e)return`${x.error}\u23FA${x.reset}`;let o=u$[t]||x.tool_default;if(n==="blink")return`${o}\x1B[5m\u23FA\x1B[25m${x.reset}`;let s=typeof n=="number"?up[n%up.length]:n!==null?n:"\u23FA";return`${o}${s}${x.reset}`}function w$(t,e,n=!1,o=null){let s=(t||[]).filter(c=>c&&c.canExecute!==!1);if(s.length===0)return`${Wi("",n,o)} Step ${e}`;if(s.length===1){let c=s[0],u=c.args||{},d=fp(c.fnName,{...u,path:u._originalPath||u.path});return`${Wi(c.fnName,n,o)} ${dp(c.fnName)} ${Ge.bold}${d}${Ge.reset}`}let r=s[0].fnName,i=b$(s)||`${s.length} tools`,a=s.slice(0,2).map(c=>fp(c.fnName,c.args||{})).filter(Boolean).join(`${Ge.dim} \xB7 ${Ge.reset}`),l=a?` ${x.subtle}\xB7${x.reset} ${Ge.dim}${a}${Ge.reset}`:"";return`${Wi(r,n,o)} ${dp(r)} ${Ge.bold}${i}${Ge.reset}${l}`}function _$(t,e){let n;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":n=e.path||"";break;case"bash":case"ssh_exec":n=(e.command||"").substring(0,44);break;case"grep":case"search_files":n=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":n=e.pattern||"";break;case"web_fetch":n=(e.url||"").substring(0,60);break;case"web_search":n=(e.query||"").substring(0,50);break;default:n=JSON.stringify(e).substring(0,80)}let o=hp[t]||t.replace(/_/g," "),s=n?`(${Ge.dim}${n}${Ge.reset})`:"",r=`${Wi(t)} ${Ge.bold}${o}${Ge.reset}${s}`;if(t==="bash"||t==="ssh_exec"){let i=gp(e.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
131
- ${i}`:r}if(t==="edit_file"){let i=ic(e.path,e.old_text,e.new_text,{indent:" ",maxLines:2,maxContent:92});return i?`${r}
132
- ${i}`:r}if(t==="patch_file"){let i=yp(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
133
- ${i}`:r}return r}function $$(t,e=8){let n=t.split(`
124
+ `).trim()}function ac(t){return h$[t]||{label:"Run",accent:x.tool_default,icon:"\u2022"}}function pp(t){let e=ac(t);return`${e.accent}${Ye.bold}${e.icon} ${e.label.toUpperCase()}${x.reset}`}function y$(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function hp(t,e={}){return e.path?Gi(e.path):e.file?Gi(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):gp[t]||y$(t)}function b$(t){return String(t||"").split(`
125
+ `).map(e=>{let n=e.match(/^(\d+):\s?(.*)$/s);return n?{lineNumber:n[1],content:n[2]||""}:null}).filter(Boolean)}function w$(t,e,n={}){let{maxLines:o=4,indent:s=" ",maxContent:r=110,includeOverflow:i=!0}=n;if(!Array.isArray(e)||e.length===0)return"";let{highlightLine:a,detectLang:l}=Wi(),c=l(t||null),u=e.slice(0,o),d=u.map(({lineNumber:f,content:h})=>{let m=h.length>r?h.substring(0,r-1)+"\u2026":h;return`${s}${x.subtle}${f}:${x.reset} ${a(m,c)}${x.reset}`});return i&&e.length>u.length&&d.push(`${s}${x.subtle}\u2026 +${e.length-u.length} more line${e.length-u.length!==1?"s":""}${x.reset}`),d.join(`
126
+ `)}function _$(t,e=96){let n=String(t||"").replace(/\t/g," ").trimEnd();return n.length>e?n.substring(0,Math.max(1,e-1))+"\u2026":n}function ic(t,e={}){let{maxLines:n=3,maxContent:o=96}=e,r=String(t||"").split(`
127
+ `).filter((a,l,c)=>a.trim()||c.length===1||l===0),i=r.slice(0,n).map(a=>_$(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function bp(t,e={}){let{indent:n=" ",maxLines:o=2,maxContent:s=100}=e;if(!t)return"";let{shown:r,more:i}=ic(t,{maxLines:o,maxContent:s});if(r.length===0)return"";let a=r.map((l,c)=>`${n}${x.subtle}${c===0?"$":">"}${x.reset} ${x.muted}${l}${x.reset}`);return i>0&&a.push(`${n}${x.subtle}\u2026 +${i} more command line${i!==1?"s":""}${x.reset}`),a.join(`
128
+ `)}function lc(t,e,n,o={}){let{indent:s=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=o,{highlightLine:l,detectLang:c}=Wi(),u=c(t||null),{shown:d,more:f}=ic(e,{maxLines:r,maxContent:i}),{shown:h,more:m}=ic(n,{maxLines:r,maxContent:i}),g=[];return d.length>0&&a&&g.push(`${s}${x.subtle}before${x.reset}`),d.forEach(_=>{g.push(`${s}${x.diff_rem}- ${x.reset}${l(_,u)}${x.reset}`)}),f>0&&g.push(`${s}${x.subtle}\u2026 ${f} more removed line${f!==1?"s":""}${x.reset}`),h.length>0&&a&&g.push(`${s}${x.subtle}after${x.reset}`),h.forEach(_=>{g.push(`${s}${x.diff_add}+ ${x.reset}${l(_,u)}${x.reset}`)}),m>0&&g.push(`${s}${x.subtle}\u2026 ${m} more added line${m!==1?"s":""}${x.reset}`),g.join(`
129
+ `)}function wp(t,e,n={}){let{indent:o=" ",maxPatches:s=2,maxLinesPerSide:r=2,maxContent:i=92}=n;if(!Array.isArray(e)||e.length===0)return"";let a=[];return e.slice(0,s).forEach((l,c)=>{a.push(`${o}${x.subtle}patch ${c+1}${x.reset}`);let u=lc(t,l.old_text,l.new_text,{indent:o+" ",maxLines:r,maxContent:i,includeLabels:!1});u&&a.push(u)}),e.length>s&&a.push(`${o}${x.subtle}\u2026 +${e.length-s} more patches${x.reset}`),a.join(`
130
+ `)}function $$(t){let e=new Set,n=[];for(let o of t){let s=ac(o.fnName).label;e.has(s)||(e.add(s),n.push(s))}return n.length===0?"":n.length<=3?n.join(`${Ye.dim} \u2192 ${Ye.reset}`):`${n.slice(0,3).join(`${Ye.dim} \u2192 ${Ye.reset}`)}${Ye.dim} \u2192 +${n.length-3}${Ye.reset}`}function Hi(t,e=!1,n=null){if(e)return`${x.error}\u23FA${x.reset}`;let o=p$[t]||x.tool_default;if(n==="blink")return`${o}\x1B[5m\u23FA\x1B[25m${x.reset}`;let s=typeof n=="number"?fp[n%fp.length]:n!==null?n:"\u23FA";return`${o}${s}${x.reset}`}function k$(t,e,n=!1,o=null){let s=(t||[]).filter(c=>c&&c.canExecute!==!1);if(s.length===0)return`${Hi("",n,o)} Step ${e}`;if(s.length===1){let c=s[0],u=c.args||{},d=hp(c.fnName,{...u,path:u._originalPath||u.path});return`${Hi(c.fnName,n,o)} ${pp(c.fnName)} ${Ye.bold}${d}${Ye.reset}`}let r=s[0].fnName,i=$$(s)||`${s.length} tools`,a=s.slice(0,2).map(c=>hp(c.fnName,c.args||{})).filter(Boolean).join(`${Ye.dim} \xB7 ${Ye.reset}`),l=a?` ${x.subtle}\xB7${x.reset} ${Ye.dim}${a}${Ye.reset}`:"";return`${Hi(r,n,o)} ${pp(r)} ${Ye.bold}${i}${Ye.reset}${l}`}function x$(t,e){let n;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":n=e.path||"";break;case"bash":case"ssh_exec":n=(e.command||"").substring(0,44);break;case"grep":case"search_files":n=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":n=e.pattern||"";break;case"web_fetch":n=(e.url||"").substring(0,60);break;case"web_search":n=(e.query||"").substring(0,50);break;default:n=JSON.stringify(e).substring(0,80)}let o=gp[t]||t.replace(/_/g," "),s=n?`(${Ye.dim}${n}${Ye.reset})`:"",r=`${Hi(t)} ${Ye.bold}${o}${Ye.reset}${s}`;if(t==="bash"||t==="ssh_exec"){let i=bp(e.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
131
+ ${i}`:r}if(t==="edit_file"){let i=lc(e.path,e.old_text,e.new_text,{indent:" ",maxLines:2,maxContent:92});return i?`${r}
132
+ ${i}`:r}if(t==="patch_file"){let i=wp(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
133
+ ${i}`:r}return r}function S$(t,e=8){let n=t.split(`
134
134
  `),o=n.slice(0,e),s=n.length-e,r=`${x.muted} \u23BF ${x.reset}`,i=" ",a=o.map((l,c)=>`${c===0?r:i}${x.success}${l}${x.reset}`).join(`
135
135
  `);return s>0&&(a+=`
136
- ${x.subtle} \u2026 +${s} lines${x.reset}`),a}var Gi=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],pp=Math.floor(Math.random()*Gi.length),k$=null;function x$(t){k$=t}function S$(){let t=Gi[pp%Gi.length];return pp++,t}function v$(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading ${e.path||"file"}`;case"list_directory":return`Listing ${e.path||"."}`;case"search_files":return`Searching ${e.pattern||"..."}`;case"glob":return`Searching ${e.pattern||"..."}`;case"grep":return`Searching ${e.pattern||"..."}`;case"web_fetch":return`Fetching ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Analyzing repository status";case"git_diff":return`Diffing${e.file?` ${e.file}`:""}`;case"git_log":return`Reading git log${e.file?` (${e.file})`:""}`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let n=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${n}: full audit...`;case"disk_usage":return`Sysadmin${n}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${n}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${n}: network status...`;case"ssl_check":return`Sysadmin${n}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${n}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${n}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${n}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${n}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${n}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${n}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${n}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${n}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${n}: cron ${e.cron_action||""}...`;default:return`Sysadmin${n}: ${e.action}...`}}case"visual_diff":return"Comparing screenshots (pixel diff)...";case"responsive_sweep":return`Responsive sweep: ${(e.url||"").substring(0,50)}...`;case"visual_annotate":return`Annotating screenshot (${(e.annotations||[]).length} markers)...`;case"visual_watch":return`Visual watch: ${(e.url||"").substring(0,50)}...`;case"design_tokens":return"Extracting design tokens...";case"design_compare":return"Comparing against reference design...";default:return`Running: ${t}`}}function E$(t,e,n,o){let s=String(n||""),r=rc(t),i=` ${x.subtle}\u2502${x.reset} ${r.accent}${Ge.bold}${r.label}${x.reset} ${x.subtle}\xB7${x.reset} `;if(o){let c=s.split(`
136
+ ${x.subtle} \u2026 +${s} lines${x.reset}`),a}var Yi=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],mp=Math.floor(Math.random()*Yi.length),v$=null;function E$(t){v$=t}function T$(){let t=Yi[mp%Yi.length];return mp++,t}function R$(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading ${e.path||"file"}`;case"list_directory":return`Listing ${e.path||"."}`;case"search_files":return`Searching ${e.pattern||"..."}`;case"glob":return`Searching ${e.pattern||"..."}`;case"grep":return`Searching ${e.pattern||"..."}`;case"web_fetch":return`Fetching ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Analyzing repository status";case"git_diff":return`Diffing${e.file?` ${e.file}`:""}`;case"git_log":return`Reading git log${e.file?` (${e.file})`:""}`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let n=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${n}: full audit...`;case"disk_usage":return`Sysadmin${n}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${n}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${n}: network status...`;case"ssl_check":return`Sysadmin${n}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${n}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${n}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${n}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${n}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${n}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${n}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${n}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${n}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${n}: cron ${e.cron_action||""}...`;default:return`Sysadmin${n}: ${e.action}...`}}case"visual_diff":return"Comparing screenshots (pixel diff)...";case"responsive_sweep":return`Responsive sweep: ${(e.url||"").substring(0,50)}...`;case"visual_annotate":return`Annotating screenshot (${(e.annotations||[]).length} markers)...`;case"visual_watch":return`Visual watch: ${(e.url||"").substring(0,50)}...`;case"design_tokens":return"Extracting design tokens...";case"design_compare":return"Comparing against reference design...";default:return`Running: ${t}`}}function C$(t,e,n,o){let s=String(n||""),r=ac(t),i=` ${x.subtle}\u2502${x.reset} ${r.accent}${Ye.bold}${r.label}${x.reset} ${x.subtle}\xB7${x.reset} `;if(o){let c=s.split(`
137
137
  `)[0];if(c.startsWith("BLOCKED:")){let h=c.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${x.muted}blocked: ${h}${x.reset}`}let u=c.replace(/^ERROR:\s*/i,"").substring(0,80),d=s.match(/\nHINT: (.+)/),f=d?`
138
- ${x.muted}${d[1].substring(0,100)}${x.reset}`:"";return`${i}${x.error}${u}${x.reset}${f}`}let a;switch(t){case"read_file":{let c=m$(s),u=c.length,d=c[c.length-1],f=d?parseInt(d.lineNumber||"0"):0,h=e.line_start||e.line_end,m=e.path?cp.basename(e.path):null,g=m?` ${x.muted}from ${m}${x.reset}`:"";h&&f>u?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${u} line${u!==1?"s":""}${g}`;let _=g$(e.path,c,{maxLines:4,maxContent:120});_&&(a+=`
138
+ ${x.muted}${d[1].substring(0,100)}${x.reset}`:"";return`${i}${x.error}${u}${x.reset}${f}`}let a;switch(t){case"read_file":{let c=b$(s),u=c.length,d=c[c.length-1],f=d?parseInt(d.lineNumber||"0"):0,h=e.line_start||e.line_end,m=e.path?dp.basename(e.path):null,g=m?` ${x.muted}from ${m}${x.reset}`:"";h&&f>u?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${u} line${u!==1?"s":""}${g}`;let _=w$(e.path,c,{maxLines:4,maxContent:120});_&&(a+=`
139
139
  ${_}`);break}case"write_file":{let u=(e.content||"").split(`
140
- `).length,d=e.path?cp.basename(e.path):null,f=d?`Wrote ${d} \xB7 ${u} line${u!==1?"s":""}`:`Wrote ${u} line${u!==1?"s":""}`,{highlightLines:h}=Ui(),m=h(e.content||"",e.path||null),g=40,_=8;if(u<=g){let k=m.map($=>` ${$}`).join(`
140
+ `).length,d=e.path?dp.basename(e.path):null,f=d?`Wrote ${d} \xB7 ${u} line${u!==1?"s":""}`:`Wrote ${u} line${u!==1?"s":""}`,{highlightLines:h}=Wi(),m=h(e.content||"",e.path||null),g=40,_=8;if(u<=g){let k=m.map($=>` ${$}`).join(`
141
141
  `);a=`${f}
142
142
  ${k}`}else{let k=m.slice(0,_).map($=>` ${$}`).join(`
143
143
  `);a=`${f}
144
144
  ${k}
145
145
  ${x.subtle}\u2026 +${u-_} lines${x.reset}`}break}case"edit_file":{let c=(e.old_text||"").split(`
146
146
  `),u=(e.new_text||"").split(`
147
- `),d=c.length,f=u.length,h=e.path?Hi(e.path):null,m=h?` ${x.muted}${h}${x.reset}`:"",g=ic(e.path,e.old_text,e.new_text,{indent:" ",maxLines:4,maxContent:96});a=`${x.diff_rem}\u2212${d}${x.reset} ${x.diff_add}+${f}${x.reset}${m}`+(g?`
147
+ `),d=c.length,f=u.length,h=e.path?Gi(e.path):null,m=h?` ${x.muted}${h}${x.reset}`:"",g=lc(e.path,e.old_text,e.new_text,{indent:" ",maxLines:4,maxContent:96});a=`${x.diff_rem}\u2212${d}${x.reset} ${x.diff_add}+${f}${x.reset}${m}`+(g?`
148
148
  `+g:"");break}case"patch_file":{let c=e.patches||[],u=c.reduce((g,_)=>g+(_.old_text||"").split(`
149
149
  `).length,0),d=c.reduce((g,_)=>g+(_.new_text||"").split(`
150
- `).length,0),f=e.path?Hi(e.path):null,h=f?` ${x.muted}${f}${x.reset}`:"";a=`${c.length} patch${c.length!==1?"es":""} ${x.diff_rem}\u2212${u}${x.reset} ${x.diff_add}+${d}${x.reset}${h}`;let m=yp(e.path,c,{indent:" ",maxPatches:3,maxLinesPerSide:2,maxContent:92});m&&(a+=`
150
+ `).length,0),f=e.path?Gi(e.path):null,h=f?` ${x.muted}${f}${x.reset}`:"";a=`${c.length} patch${c.length!==1?"es":""} ${x.diff_rem}\u2212${u}${x.reset} ${x.diff_add}+${d}${x.reset}${h}`;let m=wp(e.path,c,{indent:" ",maxPatches:3,maxLinesPerSide:2,maxContent:92});m&&(a+=`
151
151
  ${m}`);break}case"bash":{let u=s.match(/^EXIT (\d+)/),d=s.split(`
152
152
  `).filter(g=>g&&!g.startsWith("EXIT ")&&!g.startsWith("HINT:")&&g.trim()),f=u?u[1]==="0"?`${x.success}\u2713${x.reset}`:`${x.error}\u2717 Exit ${u[1]}${x.reset}`:`${x.success}\u2713${x.reset}`,h=s.match(/\nHINT: (.+)/);if(h)a=`${f} ${x.muted}\u2014 ${h[1].substring(0,100)}${x.reset}`;else if(d.length===0)a=f;else{let g=u&&u[1]!=="0",_=g?d.slice(-3):d.slice(0,3),k=d.length-3,$=_.map((O,E)=>E===0?`${f} ${x.muted}${O.substring(0,120)}${x.reset}`:` ${x.muted}${O.substring(0,120)}${x.reset}`);if(k>0){let O=g?` ${x.subtle}${k} lines above\u2026${x.reset}`:` ${x.subtle}\u2026 +${k} lines${x.reset}`;g?$.unshift(O):$.push(O)}a=$.join(`
153
- `)}let m=gp(e.command,{indent:" ",maxLines:2,maxContent:108});m&&(a=`${m}
153
+ `)}let m=bp(e.command,{indent:" ",maxLines:2,maxContent:108});m&&(a=`${m}
154
154
  ${a}`);break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")a=`No matches${e.pattern?` ${x.muted}"${String(e.pattern).substring(0,40)}"${x.reset}`:""}`;else{let _=function(E){let T=E.indexOf(":");if(T===-1)return`${x.muted}${E.substring(0,90)}${x.reset}`;let q=E.substring(0,T),ee=E.substring(T+1),te=ee.match(/^(\d+)[:-](.*)/s),K=te?`:${te[1]}`:"",ae=(te?te[2]:ee).trim(),se=`${x.subtle}${c.basename(q)}${K}${x.reset}`,ie=`${x.muted}${ae.substring(0,80)}${ae.length>80?"\u2026":""}${x.reset}`;return`${se} ${ie}`};var l=_;let c=require("path"),u=s.split(`
155
155
  `).filter(Boolean),d=u.length,h=new Set(u.map(E=>E.split(":")[0]).filter(Boolean)).size,m=e.pattern?` ${x.muted}"${String(e.pattern).substring(0,40)}"${x.reset}`:"",g=h>1?`${d} match${d!==1?"es":""} in ${h} files${m}`:`${d} match${d!==1?"es":""}${m}`,k=e.path?`
156
156
  ${x.subtle}path:${x.reset} ${x.muted}${String(e.path).substring(0,70)}${x.reset}`:"",$=u.slice(0,5).map((E,T)=>T===0?`${g}${k}
@@ -169,88 +169,88 @@ ${g.join(`
169
169
  `)[0].replace(/^\d+\.\s*/,"").trim():null,f=d?` ${x.muted}\u2014 ${d.substring(0,70)}${x.reset}`:"";a=`${u} result${u!==1?"s":""}${f}`;break}case"task_list":a="Done";break;case"spawn_agents":{if(s.includes("Background agents started")){let d=s.match(/\bbg-[\w-]+/g),f=d?d.length:0;a=`${f} bg agent${f!==1?"s":""} started`;break}let c=(s.match(/✓ Agent/g)||[]).length,u=(s.match(/✗ Agent/g)||[]).length;a=u>0?`${c} done, ${u} failed`:`${c} agent${c!==1?"s":""} done`;break}case"switch_model":{let c=s.match(/Switched to (.+)/);a=c?`\u2192 ${c[1]}`:"Done";break}case"ssh_exec":{let u=s.startsWith("EXIT ")||s.startsWith("Command failed"),d=s.split(`
170
170
  `).filter(h=>h.trim()&&!h.startsWith("EXIT ")),f=u?`${x.error}\u2717${x.reset}`:`${x.success}\u2713${x.reset}`;if(d.length===0)a=f;else{if(d.length>2&&d.every(k=>/^\[/.test(k.trim()))){a=`${f} ${d.length} log lines`;break}let m=u?d.slice(-3):d.slice(0,3),g=d.length-3,_=m.map((k,$)=>$===0?`${f} ${x.muted}${k.substring(0,120)}${x.reset}`:` ${x.muted}${k.substring(0,120)}${x.reset}`);if(g>0){let k=u?` ${x.subtle}${g} lines above\u2026${x.reset}`:` ${x.subtle}\u2026 +${g} lines${x.reset}`;u?_.unshift(k):_.push(k)}a=_.join(`
171
171
  `)}break}default:{let c=s.split(`
172
- `).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?` ${x.subtle}\u2026 +${c.length-1} lines${x.reset}`:"";a=`${x.muted}${u}${x.reset}${d}`}else a=`${r.label} complete`}}return`${i}${a}${x.reset}`}function T$(t,e,n,o,s,r){let i=Math.round(o/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,l=`
173
- ${x.success}\u25C6${Ge.reset} ${Ge.bold}${t}${Ge.reset}`;return l+=` ${x.subtle}\u2501\u2501${x.reset} ${Ge.dim}${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),s.size>0&&(l+=` \xB7 ${s.size} scanned`),l+=Ge.reset,l}bp.exports={C:Ge,formatToolCall:_$,formatResult:$$,getToolSpinnerText:v$,formatToolSummary:E$,formatSectionHeader:w$,formatMilestone:T$,stripAnsiControlSequences:mp,sanitizeFinalAnswer:p$,getThinkingVerb:S$,setActiveModelForSpinner:x$,THINKING_VERBS:Gi}});var _t=J((eP,$p)=>{var{T:En}=pn(),ac=En,R$=require("path"),_p=["01100110","01111110","01111110","01011010","01111110","00111100"];function C$(t,e){let n=[];for(let o=0;o<t.length;o+=2){let s="";for(let r=0;r<t[0].length;r++){let i=t[o][r]==="1",a=o+1<t.length&&t[o+1][r]==="1";i&&a?s+=`${e}\u2588\x1B[0m`:i&&!a?s+=`${e}\u2580\x1B[0m`:!i&&a?s+=`${e}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function A$(t,e,n={}){let o=ac.bold,s=ac.reset,r=C$(_p,En.banner_logo),i=n.yolo?` ${o}${En.banner_yolo}\u26A1 YOLO${s}`:"",a=n.gemini?` ${o}${En.banner_gemini}\u2726 GEMINI${s}`:"",l=Zl().version,c=e?R$.basename(e):null,u=`${En.banner_model}[${t||"model"}]${s}`,d=`${En.banner_version}[${c||"workspace"}]${s}`,f=[` ${En.banner_name}${o}nex-code${s} ${En.banner_version}v${l}${s}`,` ${u} ${d}`,` ${En.banner_logo}${o}terminal workbench${s} ${En.muted}\xB7 /help${s}${a}${i}`,""],h=Math.max(r.length,f.length),m=Math.floor((h-r.length)/2),g=Math.floor((h-f.length)/2),_=_p[0].length,k=[];for(let $=0;$<h;$++){let O=r[$-m]??" ".repeat(_),E=f[$-g]??"";k.push(O+E)}console.log(`
172
+ `).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?` ${x.subtle}\u2026 +${c.length-1} lines${x.reset}`:"";a=`${x.muted}${u}${x.reset}${d}`}else a=`${r.label} complete`}}return`${i}${a}${x.reset}`}function A$(t,e,n,o,s,r){let i=Math.round(o/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,l=`
173
+ ${x.success}\u25C6${Ye.reset} ${Ye.bold}${t}${Ye.reset}`;return l+=` ${x.subtle}\u2501\u2501${x.reset} ${Ye.dim}${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),s.size>0&&(l+=` \xB7 ${s.size} scanned`),l+=Ye.reset,l}_p.exports={C:Ye,formatToolCall:x$,formatResult:S$,getToolSpinnerText:R$,formatToolSummary:C$,formatSectionHeader:k$,formatMilestone:A$,stripAnsiControlSequences:yp,sanitizeFinalAnswer:g$,getThinkingVerb:T$,setActiveModelForSpinner:E$,THINKING_VERBS:Yi}});var $t=J((oP,xp)=>{var{T:En}=pn(),cc=En,O$=require("path"),kp=["01100110","01111110","01111110","01011010","01111110","00111100"];function P$(t,e){let n=[];for(let o=0;o<t.length;o+=2){let s="";for(let r=0;r<t[0].length;r++){let i=t[o][r]==="1",a=o+1<t.length&&t[o+1][r]==="1";i&&a?s+=`${e}\u2588\x1B[0m`:i&&!a?s+=`${e}\u2580\x1B[0m`:!i&&a?s+=`${e}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function N$(t,e,n={}){let o=cc.bold,s=cc.reset,r=P$(kp,En.banner_logo),i=n.yolo?` ${o}${En.banner_yolo}\u26A1 YOLO${s}`:"",a=n.gemini?` ${o}${En.banner_gemini}\u2726 GEMINI${s}`:"",l=ec().version,c=e?O$.basename(e):null,u=`${En.banner_model}[${t||"model"}]${s}`,d=`${En.banner_version}[${c||"workspace"}]${s}`,f=[` ${En.banner_name}${o}nex-code${s} ${En.banner_version}v${l}${s}`,` ${u} ${d}`,` ${En.banner_logo}${o}terminal workbench${s} ${En.muted}\xB7 /help${s}${a}${i}`,""],h=Math.max(r.length,f.length),m=Math.floor((h-r.length)/2),g=Math.floor((h-f.length)/2),_=kp[0].length,k=[];for(let $=0;$<h;$++){let O=r[$-m]??" ".repeat(_),E=f[$-g]??"";k.push(O+E)}console.log(`
174
174
  `+k.join(`
175
175
  `)+`
176
- `)}var{Spinner:O$,MultiProgress:P$,TaskProgress:N$,ToolProgress:M$,setActiveTaskProgress:L$,getActiveTaskProgress:I$,cleanupTerminal:j$}=vs(),{formatToolCall:D$,formatResult:q$,getToolSpinnerText:F$,formatToolSummary:B$,formatSectionHeader:U$,formatMilestone:W$,getThinkingVerb:H$,setActiveModelForSpinner:G$}=wp();$p.exports={C:ac,banner:A$,Spinner:O$,MultiProgress:P$,TaskProgress:N$,ToolProgress:M$,setActiveTaskProgress:L$,getActiveTaskProgress:I$,cleanupTerminal:j$,formatToolCall:D$,formatResult:q$,getToolSpinnerText:F$,formatToolSummary:B$,formatSectionHeader:U$,formatMilestone:W$,getThinkingVerb:H$,setActiveModelForSpinner:G$}});var cc=J((tP,kp)=>{function lc(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var Y$=lc();function z$(...t){lc()&&console.log(...t)}function K$(...t){lc()&&console.warn(...t)}kp.exports={DEBUG:Y$,debugLog:z$,warnLog:K$}});var vp=J((nP,Sp)=>{"use strict";var V$=new Set(["read_file","grep","glob","search_files","list_directory"]),X$=new Set(["write_file","edit_file","patch_file"]),J$=new Set(["bash"]),Z$=new Set(["web_search","web_fetch","perplexity_search"]);function xp(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[a,l]of t)i+=l,V$.has(a)&&(n+=l),X$.has(a)&&(o+=l),J$.has(a)&&(s+=l),Z$.has(a)&&(r+=l);return i===0?`Phase ${e}`:r/i>.5?"Research":n/i>.5?"Exploration":o/i>.3?"Implementation":s/i>.3&&o/i<.15?"Verification":`Phase ${e}`}var uc=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,n,o,s){if(this._disabled)return null;this._stepsThisPhase++;for(let i of n)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:xp(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(o),filesModified:new Set(s)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};Sp.exports={MilestoneTracker:uc,_phaseName:xp}});var Yi=J((sP,Ep)=>{var nr=$t(),Q$={"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 ek(){return nr.getActiveModel()}function tk(t){return nr.setActiveModel(t)}function nk(){return nr.getModelNames()}function sk(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let o=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(o)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let o=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(o)}catch{}let n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function ok(t,e){let{C:n}=_t(),{Spinner:o}=_t(),s=new o("Thinking...");s.start();let r=!0,i="";try{let a=await nr.callStream(t,e,{onToken:l=>{r&&(s.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?s.stop():process.stdout.write(`${n.reset}
177
- `),a}catch(a){throw s.stop(),a}}async function rk(t,e){return nr.callChat(t,e)}Ep.exports={MODELS:Q$,getActiveModel:ek,setActiveModel:tk,getModelNames:nk,callOllamaStream:ok,callOllama:rk,parseToolArgs:sk}});var or=J((oP,Pp)=>{var ik=require("readline"),{C:Tn}=_t(),ak=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,lk=/^=([\w-]+)/;function sr(t){return typeof t!="string"?t:t.replace(ak,"").replace(lk,"$1")}var pc=[/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/],Tp=[...pc,/\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 ck(t){for(let e of Tp)if(e.test(t))return e;return null}var Rp=[/\.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)/],uk=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,dc=[/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 Cp(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let o=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(o.length===0)return!1;let s=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(c=>c.trim()).filter(Boolean).every(c=>s(c)):dc.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:dc.some(a=>a.test(i))};return o.every(s)}var hc=[/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/],Ap=[/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/],Op=[...hc,...Ap],mc=!1,Fn=null,fc=null;function dk(t){mc=t}function fk(t){fc=t}function pk(){return mc}function hk(t){Fn=t}function mk(t){let e=sr(t);for(let n of pc)if(n.test(e))return n;return null}function gk(t){let e=sr(t);if(/ssh\s/.test(e)&&Cp(e))return!1;for(let n of Op)if(n.test(e))return!0;return!1}function yk(t){let e=sr(t);for(let n of hc)if(n.test(e))return!0;return!1}function bk(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=sr(t);if(!uk.test(e))return null;for(let n of Rp)if(n.test(e))return n;return null}function wk(t,e={}){if(mc)return Promise.resolve(!0);if(fc)return fc(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY||process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID||typeof process.stdin.setRawMode!="function")return _k(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Fn&&typeof Fn.pause=="function"&&Fn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-n.length-2)},a=()=>{let d=i();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${Tn.yellow}${t}${Tn.reset}`;for(let h=0;h<n.length;h++){let m=h===s,g=m?`${Tn.yellow}\u276F${Tn.reset}`:" ",_=m?`${Tn.yellow}${n[h]}${Tn.reset}`:n[h];f+=`\x1B[${d+1+h};1H\x1B[2K ${g} ${_}`}r(f)},l=d=>{typeof process.stdin.setRawMode=="function"&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),m="";for(let g=0;g<n.length+1;g++)m+=`\x1B[${h+g};1H\x1B[2K`;f(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Fn&&typeof Fn.resume=="function"&&Fn.resume(),o(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&zi(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
178
- `){c(s);return}if(f==="\x1B[A"){s=(s-1+n.length)%n.length,a();return}if(f==="\x1B[B"){s=(s+1)%n.length,a();return}let h=f.toLowerCase().trim();if(h==="y"){l(!0);return}if(h==="n"){l(!1);return}if(h==="a"&&e.toolName){zi(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function _k(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let s=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(zi(e.toolName),o(!0)):o(i!=="n")};if(Fn)Fn.question(`${Tn.yellow}${t} ${n}${Tn.reset}`,s);else{let r=ik.createInterface({input:process.stdin,output:process.stdout});r.question(`${Tn.yellow}${t} ${n}${Tn.reset}`,i=>{r.close(),s(i)})}})}var zi=()=>{};function $k(t){zi=t}Pp.exports={sanitizeBashCommand:sr,FORBIDDEN_PATTERNS:pc,SSH_FORBIDDEN_PATTERNS:Tp,BASH_PROTECTED_PATHS:Rp,SSH_SAFE_PATTERNS:dc,isSSHReadOnly:Cp,DANGEROUS_BASH:Op,CRITICAL_BASH:hc,NOTABLE_BASH:Ap,isForbidden:mk,isSSHForbidden:ck,isDangerous:gk,isCritical:yk,isBashPathForbidden:bk,confirm:wk,setAutoConfirm:dk,getAutoConfirm:pk,setConfirmHook:fk,setReadlineInterface:hk,setAllowAlwaysHandler:$k}});var Lp=J((iP,Mp)=>{var Ki=require("path"),{C:B}=_t(),{T:gc,isDark:rP}=pn(),{confirm:kk,getAutoConfirm:xk}=or(),Np=2e3;function rr(t,e){let n=t.split(`
176
+ `)}var{Spinner:M$,MultiProgress:L$,TaskProgress:I$,ToolProgress:j$,setActiveTaskProgress:D$,getActiveTaskProgress:q$,cleanupTerminal:F$}=Es(),{formatToolCall:B$,formatResult:U$,getToolSpinnerText:W$,formatToolSummary:H$,formatSectionHeader:G$,formatMilestone:Y$,getThinkingVerb:z$,setActiveModelForSpinner:K$}=$p();xp.exports={C:cc,banner:N$,Spinner:M$,MultiProgress:L$,TaskProgress:I$,ToolProgress:j$,setActiveTaskProgress:D$,getActiveTaskProgress:q$,cleanupTerminal:F$,formatToolCall:B$,formatResult:U$,getToolSpinnerText:W$,formatToolSummary:H$,formatSectionHeader:G$,formatMilestone:Y$,getThinkingVerb:z$,setActiveModelForSpinner:K$}});var dc=J((rP,Sp)=>{function uc(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var V$=uc();function X$(...t){uc()&&console.log(...t)}function J$(...t){uc()&&console.warn(...t)}Sp.exports={DEBUG:V$,debugLog:X$,warnLog:J$}});var Tp=J((iP,Ep)=>{"use strict";var Z$=new Set(["read_file","grep","glob","search_files","list_directory"]),Q$=new Set(["write_file","edit_file","patch_file"]),ek=new Set(["bash"]),tk=new Set(["web_search","web_fetch","perplexity_search"]);function vp(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[a,l]of t)i+=l,Z$.has(a)&&(n+=l),Q$.has(a)&&(o+=l),ek.has(a)&&(s+=l),tk.has(a)&&(r+=l);return i===0?`Phase ${e}`:r/i>.5?"Research":n/i>.5?"Exploration":o/i>.3?"Implementation":s/i>.3&&o/i<.15?"Verification":`Phase ${e}`}var fc=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,n,o,s){if(this._disabled)return null;this._stepsThisPhase++;for(let i of n)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:vp(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(o),filesModified:new Set(s)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};Ep.exports={MilestoneTracker:fc,_phaseName:vp}});var zi=J((aP,Rp)=>{var sr=kt(),nk={"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 sk(){return sr.getActiveModel()}function ok(t){return sr.setActiveModel(t)}function rk(){return sr.getModelNames()}function ik(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let o=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(o)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let o=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(o)}catch{}let n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function ak(t,e){let{C:n}=$t(),{Spinner:o}=$t(),s=new o("Thinking...");s.start();let r=!0,i="";try{let a=await sr.callStream(t,e,{onToken:l=>{r&&(s.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?s.stop():process.stdout.write(`${n.reset}
177
+ `),a}catch(a){throw s.stop(),a}}async function lk(t,e){return sr.callChat(t,e)}Rp.exports={MODELS:nk,getActiveModel:sk,setActiveModel:ok,getModelNames:rk,callOllamaStream:ak,callOllama:lk,parseToolArgs:ik}});var rr=J((lP,Mp)=>{var ck=require("readline"),{C:Tn}=$t(),uk=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,dk=/^=([\w-]+)/;function or(t){return typeof t!="string"?t:t.replace(uk,"").replace(dk,"$1")}var mc=[/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/],Cp=[...mc,/\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 fk(t){for(let e of Cp)if(e.test(t))return e;return null}var Ap=[/\.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)/],pk=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,pc=[/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 Op(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let o=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(o.length===0)return!1;let s=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(c=>c.trim()).filter(Boolean).every(c=>s(c)):pc.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:pc.some(a=>a.test(i))};return o.every(s)}var gc=[/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/],Pp=[/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/],Np=[...gc,...Pp],yc=!1,Fn=null,hc=null;function hk(t){yc=t}function mk(t){hc=t}function gk(){return yc}function yk(t){Fn=t}function bk(t){let e=or(t);for(let n of mc)if(n.test(e))return n;return null}function wk(t){let e=or(t);if(/ssh\s/.test(e)&&Op(e))return!1;for(let n of Np)if(n.test(e))return!0;return!1}function _k(t){let e=or(t);for(let n of gc)if(n.test(e))return!0;return!1}function $k(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=or(t);if(!pk.test(e))return null;for(let n of Ap)if(n.test(e))return n;return null}function kk(t,e={}){if(yc)return Promise.resolve(!0);if(hc)return hc(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY||process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID||typeof process.stdin.setRawMode!="function")return xk(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Fn&&typeof Fn.pause=="function"&&Fn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-n.length-2)},a=()=>{let d=i();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${Tn.yellow}${t}${Tn.reset}`;for(let h=0;h<n.length;h++){let m=h===s,g=m?`${Tn.yellow}\u276F${Tn.reset}`:" ",_=m?`${Tn.yellow}${n[h]}${Tn.reset}`:n[h];f+=`\x1B[${d+1+h};1H\x1B[2K ${g} ${_}`}r(f)},l=d=>{typeof process.stdin.setRawMode=="function"&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),m="";for(let g=0;g<n.length+1;g++)m+=`\x1B[${h+g};1H\x1B[2K`;f(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Fn&&typeof Fn.resume=="function"&&Fn.resume(),o(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&Ki(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
178
+ `){c(s);return}if(f==="\x1B[A"){s=(s-1+n.length)%n.length,a();return}if(f==="\x1B[B"){s=(s+1)%n.length,a();return}let h=f.toLowerCase().trim();if(h==="y"){l(!0);return}if(h==="n"){l(!1);return}if(h==="a"&&e.toolName){Ki(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function xk(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let s=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Ki(e.toolName),o(!0)):o(i!=="n")};if(Fn)Fn.question(`${Tn.yellow}${t} ${n}${Tn.reset}`,s);else{let r=ck.createInterface({input:process.stdin,output:process.stdout});r.question(`${Tn.yellow}${t} ${n}${Tn.reset}`,i=>{r.close(),s(i)})}})}var Ki=()=>{};function Sk(t){Ki=t}Mp.exports={sanitizeBashCommand:or,FORBIDDEN_PATTERNS:mc,SSH_FORBIDDEN_PATTERNS:Cp,BASH_PROTECTED_PATHS:Ap,SSH_SAFE_PATTERNS:pc,isSSHReadOnly:Op,DANGEROUS_BASH:Np,CRITICAL_BASH:gc,NOTABLE_BASH:Pp,isForbidden:bk,isSSHForbidden:fk,isDangerous:wk,isCritical:_k,isBashPathForbidden:$k,confirm:kk,setAutoConfirm:hk,getAutoConfirm:gk,setConfirmHook:mk,setReadlineInterface:yk,setAllowAlwaysHandler:Sk}});var jp=J((uP,Ip)=>{var Vi=require("path"),{C:B}=$t(),{T:bc,isDark:cP}=pn(),{confirm:vk,getAutoConfirm:Ek}=rr(),Lp=2e3;function ir(t,e){let n=t.split(`
179
179
  `),o=e.split(`
180
- `),s=[],r=n.length,i=o.length;if(r>Np||i>Np){for(let d of n)s.push({type:"remove",line:d});for(let d of o)s.push({type:"add",line:d});return s}let a=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let d=1;d<=r;d++)for(let f=1;f<=i;f++)n[d-1]===o[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let l=r,c=i,u=[];for(;l>0||c>0;)l>0&&c>0&&n[l-1]===o[c-1]?(u.unshift({type:"same",line:n[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:n[l-1]}),l--);return u}function Sk(t,e,n,o=3){console.log(`
181
- ${B.bold}${B.cyan} Diff: ${t}${B.reset}`);let s=rr(e,n),r=[];if(s.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${B.gray} (no changes)${B.reset}`);return}let i=Math.max(0,r[0]-o),a=Math.min(s.length,r[r.length-1]+o+1);i>0&&console.log(`${B.gray} ...${B.reset}`);for(let l=i;l<a;l++){let c=s[l];switch(c.type){case"remove":console.log(`${B.red} - ${c.line}${B.reset}`);break;case"add":console.log(`${B.green} + ${c.line}${B.reset}`);break;default:console.log(`${B.gray} ${c.line}${B.reset}`)}}a<s.length&&console.log(`${B.gray} ...${B.reset}`),console.log()}function vk(t,e,n){console.log(`
182
- ${B.bold}${B.cyan} File exists \u2014 showing changes: ${t}${B.reset}`);let o=rr(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${B.gray} (identical content)${B.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${B.gray} ...(${s-r} more changes)${B.reset}`);break}switch(i.type){case"remove":console.log(`${B.red} - ${i.line}${B.reset}`),r++;break;case"add":console.log(`${B.green} + ${i.line}${B.reset}`),r++;break;default:r>0&&console.log(`${B.gray} ${i.line}${B.reset}`)}}console.log()}function Ek(t,e){console.log(`
180
+ `),s=[],r=n.length,i=o.length;if(r>Lp||i>Lp){for(let d of n)s.push({type:"remove",line:d});for(let d of o)s.push({type:"add",line:d});return s}let a=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let d=1;d<=r;d++)for(let f=1;f<=i;f++)n[d-1]===o[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let l=r,c=i,u=[];for(;l>0||c>0;)l>0&&c>0&&n[l-1]===o[c-1]?(u.unshift({type:"same",line:n[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:n[l-1]}),l--);return u}function Tk(t,e,n,o=3){console.log(`
181
+ ${B.bold}${B.cyan} Diff: ${t}${B.reset}`);let s=ir(e,n),r=[];if(s.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${B.gray} (no changes)${B.reset}`);return}let i=Math.max(0,r[0]-o),a=Math.min(s.length,r[r.length-1]+o+1);i>0&&console.log(`${B.gray} ...${B.reset}`);for(let l=i;l<a;l++){let c=s[l];switch(c.type){case"remove":console.log(`${B.red} - ${c.line}${B.reset}`);break;case"add":console.log(`${B.green} + ${c.line}${B.reset}`);break;default:console.log(`${B.gray} ${c.line}${B.reset}`)}}a<s.length&&console.log(`${B.gray} ...${B.reset}`),console.log()}function Rk(t,e,n){console.log(`
182
+ ${B.bold}${B.cyan} File exists \u2014 showing changes: ${t}${B.reset}`);let o=ir(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${B.gray} (identical content)${B.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${B.gray} ...(${s-r} more changes)${B.reset}`);break}switch(i.type){case"remove":console.log(`${B.red} - ${i.line}${B.reset}`),r++;break;case"add":console.log(`${B.green} + ${i.line}${B.reset}`),r++;break;default:r>0&&console.log(`${B.gray} ${i.line}${B.reset}`)}}console.log()}function Ck(t,e){console.log(`
183
183
  ${B.bold}${B.cyan} New file: ${t}${B.reset}`);let n=e.split(`
184
- `),o=n.slice(0,20);for(let s of o)console.log(`${B.green} + ${s}${B.reset}`);n.length>20&&console.log(`${B.gray} ...+${n.length-20} more lines${B.reset}`),console.log()}async function Tk(t){return xk()?!0:kk(` ${t}?`)}function Rk(t,e,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
185
- ${B.bold}${B.cyan} Side-by-side: ${t}${B.reset}`),console.log(` ${B.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${B.reset}`);let i=rr(e,n),a=[],l=0;for(;l<i.length;)if(i[l].type==="same")a.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let h=[];for(;l<i.length&&i[l].type==="remove";)h.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(h.length,m.length);for(let _=0;_<g;_++)a.push({left:_<h.length?h[_]:"",right:_<m.length?m[_]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let c=a.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(c.length===0){console.log(` ${B.gray}(no changes)${B.reset}`);return}let u=Math.max(0,c[0]-2),d=Math.min(a.length,c[c.length-1]+3),f=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};u>0&&console.log(` ${B.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${B.reset}`);for(let h=u;h<d;h++){let m=a[h];if(m.type==="same")console.log(` ${B.gray}${f(m.left,r)}${B.reset}\u2502${B.gray}${f(m.right,r)}${B.reset}`);else{let g=m.left?`${B.red}${f(m.left,r)}${B.reset}`:`${f("",r)}`,_=m.right?`${B.green}${f(m.right,r)}${B.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${_}`)}}d<a.length&&console.log(` ${B.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${B.reset}`),console.log(` ${B.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${B.reset}
186
- `)}function Ck(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],a=Ki.isAbsolute(t)?Ki.relative(process.cwd(),t):t,l=rr(e,n),c=1,u=1;for(let q of l)q.type==="same"?(q.oldLine=c++,q.newLine=u++):q.type==="remove"?(q.oldLine=c++,q.newLine=null):(q.oldLine=null,q.newLine=u++);let d=0,f=0;for(let q of l)q.type==="add"?d++:q.type==="remove"&&f++;if(console.log(`
184
+ `),o=n.slice(0,20);for(let s of o)console.log(`${B.green} + ${s}${B.reset}`);n.length>20&&console.log(`${B.gray} ...+${n.length-20} more lines${B.reset}`),console.log()}async function Ak(t){return Ek()?!0:vk(` ${t}?`)}function Ok(t,e,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
185
+ ${B.bold}${B.cyan} Side-by-side: ${t}${B.reset}`),console.log(` ${B.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${B.reset}`);let i=ir(e,n),a=[],l=0;for(;l<i.length;)if(i[l].type==="same")a.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let h=[];for(;l<i.length&&i[l].type==="remove";)h.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(h.length,m.length);for(let _=0;_<g;_++)a.push({left:_<h.length?h[_]:"",right:_<m.length?m[_]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let c=a.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(c.length===0){console.log(` ${B.gray}(no changes)${B.reset}`);return}let u=Math.max(0,c[0]-2),d=Math.min(a.length,c[c.length-1]+3),f=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};u>0&&console.log(` ${B.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${B.reset}`);for(let h=u;h<d;h++){let m=a[h];if(m.type==="same")console.log(` ${B.gray}${f(m.left,r)}${B.reset}\u2502${B.gray}${f(m.right,r)}${B.reset}`);else{let g=m.left?`${B.red}${f(m.left,r)}${B.reset}`:`${f("",r)}`,_=m.right?`${B.green}${f(m.right,r)}${B.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${_}`)}}d<a.length&&console.log(` ${B.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${B.reset}`),console.log(` ${B.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${B.reset}
186
+ `)}function Pk(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],a=Vi.isAbsolute(t)?Vi.relative(process.cwd(),t):t,l=ir(e,n),c=1,u=1;for(let q of l)q.type==="same"?(q.oldLine=c++,q.newLine=u++):q.type==="remove"?(q.oldLine=c++,q.newLine=null):(q.oldLine=null,q.newLine=u++);let d=0,f=0;for(let q of l)q.type==="add"?d++:q.type==="remove"&&f++;if(console.log(`
187
187
  ${B.green}\u23FA${B.reset} ${B.bold}${s}(${a})${B.reset}`),d===0&&f===0){console.log(` ${B.dim}\u23BF (no changes)${B.reset}
188
- `);return}let h=[];if(d>0&&h.push(`Added ${d} line${d!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let q=i.filter(ae=>ae.severity==="error").length,ee=i.filter(ae=>ae.severity==="warn").length,te=i.filter(ae=>ae.severity==="info").length,K=[];q>0&&K.push(`${B.red}${q} error${q!==1?"s":""}${B.dim}`),ee>0&&K.push(`${B.yellow}${ee} warning${ee!==1?"s":""}${B.dim}`),te>0&&K.push(`${B.cyan}${te} info${te!==1?"s":""}${B.dim}`),h.push(`found ${K.join(", ")}`)}console.log(` ${B.dim}\u23BF ${h.join(", ")}${B.reset}`);let g=[];l.forEach((q,ee)=>{q.type!=="same"&&g.push(ee)});let _=[],k=null,$=null;for(let q of g){let ee=Math.max(0,q-r),te=Math.min(l.length-1,q+r);k===null?(k=ee,$=te):(ee<=$+1||(_.push([k,$]),k=ee),$=te)}k!==null&&_.push([k,$]);let O=" ",E=process.stdout.columns||120;function T(q,ee,te){let K=te.replace(/\x1b\[[0-9;]*m/g,""),ae=te+" ".repeat(Math.max(0,E-K.length));return`${q}${ee}${ae}${B.reset}`}for(let q=0;q<_.length;q++){q>0&&console.log(`${O}${B.dim}\xB7\xB7\xB7${B.reset}`);let[ee,te]=_[q];for(let K=ee;K<=te;K++){let ae=l[K],se=ae.newLine!=null?ae.newLine:ae.oldLine,ie=String(se).padStart(4),Be=ae.type!=="remove"?i.filter(Re=>Re.line===ae.newLine):[];ae.type==="remove"?console.log(T(gc.diff_rem_bg,B.red,`${O}${ie} - ${ae.line}`)):ae.type==="add"?console.log(T(gc.diff_add_bg,B.green,`${O}${ie} + ${ae.line}`)):console.log(`${O}${B.dim}${ie} ${B.reset}${ae.line}`);for(let Re of Be){let W=B.cyan,ne="\u2139";Re.severity==="error"?(W=B.red,ne="\u2716"):Re.severity==="warn"&&(W=B.yellow,ne="\u26A0"),console.log(`${O} ${W}${ne} ${Re.message}${B.reset}`)}}}console.log()}function Ak(t,e,n={}){let o=Ki.isAbsolute(t)?Ki.relative(process.cwd(),t):t,s=e.split(`
188
+ `);return}let h=[];if(d>0&&h.push(`Added ${d} line${d!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let q=i.filter(ae=>ae.severity==="error").length,ee=i.filter(ae=>ae.severity==="warn").length,te=i.filter(ae=>ae.severity==="info").length,K=[];q>0&&K.push(`${B.red}${q} error${q!==1?"s":""}${B.dim}`),ee>0&&K.push(`${B.yellow}${ee} warning${ee!==1?"s":""}${B.dim}`),te>0&&K.push(`${B.cyan}${te} info${te!==1?"s":""}${B.dim}`),h.push(`found ${K.join(", ")}`)}console.log(` ${B.dim}\u23BF ${h.join(", ")}${B.reset}`);let g=[];l.forEach((q,ee)=>{q.type!=="same"&&g.push(ee)});let _=[],k=null,$=null;for(let q of g){let ee=Math.max(0,q-r),te=Math.min(l.length-1,q+r);k===null?(k=ee,$=te):(ee<=$+1||(_.push([k,$]),k=ee),$=te)}k!==null&&_.push([k,$]);let O=" ",E=process.stdout.columns||120;function T(q,ee,te){let K=te.replace(/\x1b\[[0-9;]*m/g,""),ae=te+" ".repeat(Math.max(0,E-K.length));return`${q}${ee}${ae}${B.reset}`}for(let q=0;q<_.length;q++){q>0&&console.log(`${O}${B.dim}\xB7\xB7\xB7${B.reset}`);let[ee,te]=_[q];for(let K=ee;K<=te;K++){let ae=l[K],se=ae.newLine!=null?ae.newLine:ae.oldLine,ie=String(se).padStart(4),Be=ae.type!=="remove"?i.filter(Ce=>Ce.line===ae.newLine):[];ae.type==="remove"?console.log(T(bc.diff_rem_bg,B.red,`${O}${ie} - ${ae.line}`)):ae.type==="add"?console.log(T(bc.diff_add_bg,B.green,`${O}${ie} + ${ae.line}`)):console.log(`${O}${B.dim}${ie} ${B.reset}${ae.line}`);for(let Ce of Be){let H=B.cyan,ne="\u2139";Ce.severity==="error"?(H=B.red,ne="\u2716"):Ce.severity==="warn"&&(H=B.yellow,ne="\u26A0"),console.log(`${O} ${H}${ne} ${Ce.message}${B.reset}`)}}}console.log()}function Nk(t,e,n={}){let o=Vi.isAbsolute(t)?Vi.relative(process.cwd(),t):t,s=e.split(`
189
189
  `),r=n.annotations||[];console.log(`
190
- ${B.green}\u23FA${B.reset} ${B.bold}Create(${o})${B.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let d=r.filter(g=>g.severity==="error").length,f=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,m=[];d>0&&m.push(`${B.red}${d} error${d!==1?"s":""}${B.dim}`),f>0&&m.push(`${B.yellow}${f} warning${f!==1?"s":""}${B.dim}`),h>0&&m.push(`${B.cyan}${h} info${h!==1?"s":""}${B.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${B.dim}\u23BF ${i.join(", ")}${B.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(s.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),h=d+1,m=r.filter($=>$.line===h),g=`${l}${f} + ${s[d]}`,_=g.replace(/\x1b\[[0-9;]*m/g,""),k=g+" ".repeat(Math.max(0,c-_.length));console.log(`${gc.diff_add_bg}${B.green}${k}${B.reset}`);for(let $ of m){let O=B.cyan,E="\u2139";$.severity==="error"?(O=B.red,E="\u2716"):$.severity==="warn"&&(O=B.yellow,E="\u26A0"),console.log(`${l} ${O}${E} ${$.message}${B.reset}`)}}s.length>20&&console.log(`${l}${B.dim} ...+${s.length-20} more lines${B.reset}`),console.log()}Mp.exports={diffLines:rr,showEditDiff:Sk,showWriteDiff:vk,showNewFilePreview:Ek,confirmFileChange:Tk,showSideBySideDiff:Rk,showDiff:Ck,showNewFile:Ak}});var Ji=J((aP,Dp)=>{var Ip=require("util").promisify(require("child_process").exec),Ok=require("util").promisify(require("child_process").execFile),{C:at}=_t();async function yc(t){try{let{stdout:e}=await Ip(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Vi(...t){try{let{stdout:e}=await Ok("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Pk(){return await yc("git rev-parse --is-inside-work-tree")==="true"}async function Nk(){return await yc("git branch --show-current")}async function bc(){try{let{stdout:t}=await Ip("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
191
- `).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function Xi(t=!1){return await yc(`git diff ${t?"--cached":""}`)||""}async function wc(){return(await bc()).map(e=>e.file)}async function jp(){let t=await wc();if(t.length===0)return null;let e=await Xi(),o=await Xi(!0)||e,s=0,r=0;if(o){let u=o.split(`
192
- `);for(let d of u)d.startsWith("+")&&!d.startsWith("+++")&&s++,d.startsWith("-")&&!d.startsWith("---")&&r++}else s=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":s>r*2?i="feat":r>s?i="refactor":i="fix";let l=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:s,deletions:r}}}async function Mk(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Vi("checkout","-b",n)!==null?n:null}async function Lk(t){return await Vi("add","-A"),await Vi("commit","-m",t)?await Vi("rev-parse","--short","HEAD"):null}async function Ik(){let t=await jp();if(!t)return`${at.dim}No changes${at.reset}`;let e=[];e.push(`
190
+ ${B.green}\u23FA${B.reset} ${B.bold}Create(${o})${B.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let d=r.filter(g=>g.severity==="error").length,f=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,m=[];d>0&&m.push(`${B.red}${d} error${d!==1?"s":""}${B.dim}`),f>0&&m.push(`${B.yellow}${f} warning${f!==1?"s":""}${B.dim}`),h>0&&m.push(`${B.cyan}${h} info${h!==1?"s":""}${B.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${B.dim}\u23BF ${i.join(", ")}${B.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(s.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),h=d+1,m=r.filter($=>$.line===h),g=`${l}${f} + ${s[d]}`,_=g.replace(/\x1b\[[0-9;]*m/g,""),k=g+" ".repeat(Math.max(0,c-_.length));console.log(`${bc.diff_add_bg}${B.green}${k}${B.reset}`);for(let $ of m){let O=B.cyan,E="\u2139";$.severity==="error"?(O=B.red,E="\u2716"):$.severity==="warn"&&(O=B.yellow,E="\u26A0"),console.log(`${l} ${O}${E} ${$.message}${B.reset}`)}}s.length>20&&console.log(`${l}${B.dim} ...+${s.length-20} more lines${B.reset}`),console.log()}Ip.exports={diffLines:ir,showEditDiff:Tk,showWriteDiff:Rk,showNewFilePreview:Ck,confirmFileChange:Ak,showSideBySideDiff:Ok,showDiff:Pk,showNewFile:Nk}});var Zi=J((dP,Fp)=>{var Dp=require("util").promisify(require("child_process").exec),Mk=require("util").promisify(require("child_process").execFile),{C:at}=$t();async function wc(t){try{let{stdout:e}=await Dp(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Xi(...t){try{let{stdout:e}=await Mk("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Lk(){return await wc("git rev-parse --is-inside-work-tree")==="true"}async function Ik(){return await wc("git branch --show-current")}async function _c(){try{let{stdout:t}=await Dp("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
191
+ `).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function Ji(t=!1){return await wc(`git diff ${t?"--cached":""}`)||""}async function $c(){return(await _c()).map(e=>e.file)}async function qp(){let t=await $c();if(t.length===0)return null;let e=await Ji(),o=await Ji(!0)||e,s=0,r=0;if(o){let u=o.split(`
192
+ `);for(let d of u)d.startsWith("+")&&!d.startsWith("+++")&&s++,d.startsWith("-")&&!d.startsWith("---")&&r++}else s=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":s>r*2?i="feat":r>s?i="refactor":i="fix";let l=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:s,deletions:r}}}async function jk(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Xi("checkout","-b",n)!==null?n:null}async function Dk(t){return await Xi("add","-A"),await Xi("commit","-m",t)?await Xi("rev-parse","--short","HEAD"):null}async function qk(){let t=await qp();if(!t)return`${at.dim}No changes${at.reset}`;let e=[];e.push(`
193
193
  ${at.bold}${at.cyan}Git Diff Summary:${at.reset}`),e.push(` ${at.green}+${t.stats.additions}${at.reset} ${at.red}-${t.stats.deletions}${at.reset} in ${t.files.length} file(s)`),e.push(`
194
194
  ${at.bold}${at.cyan}Files:${at.reset}`);for(let n of t.files.slice(0,20))e.push(` ${at.dim}${n}${at.reset}`);return t.files.length>20&&e.push(` ${at.dim}...+${t.files.length-20} more${at.reset}`),e.push(`
195
195
  ${at.bold}${at.cyan}Suggested message:${at.reset}`),e.push(` ${at.cyan}${t.summary}${at.reset}
196
196
  `),e.join(`
197
- `)}async function jk(){return(await bc()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Dk(){let t=await wc();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let o of t.slice(0,10))e.push(` ${o}`);let n=await Xi();if(n){let o=n.length>5e3?n.substring(0,5e3)+`
197
+ `)}async function Fk(){return(await _c()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Bk(){let t=await $c();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let o of t.slice(0,10))e.push(` ${o}`);let n=await Ji();if(n){let o=n.length>5e3?n.substring(0,5e3)+`
198
198
  ...(truncated)`:n;e.push(`
199
199
  DIFF:
200
200
  ${o}`)}return e.join(`
201
- `)}Dp.exports={isGitRepo:Pk,getCurrentBranch:Nk,getStatus:bc,getDiff:Xi,getChangedFiles:wc,analyzeDiff:jp,createBranch:Mk,commit:Lk,formatDiffSummary:Ik,getDiffContext:Dk,getMergeConflicts:jk}});var Yp=J((cP,Gp)=>{var kt=require("fs").promises,lP=require("fs"),en=require("path"),qk=require("crypto"),{execSync:_c,execFileSync:Bp}=require("child_process"),Fk=100*1024,Up=50,It=[],_o=[];function Bk(t,e,n,o){for(It.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});It.length>Up;)It.shift();_o.length=0,Wp(It[It.length-1]).catch(()=>{})}async function Uk(){if(It.length===0)return null;let t=It.pop();if(t.oldContent===null)try{await kt.unlink(t.filePath)}catch{}else await kt.writeFile(t.filePath,t.oldContent,"utf-8");return _o.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Wk(){if(_o.length===0)return null;let t=_o.pop();return await kt.writeFile(t.filePath,t.newContent,"utf-8"),It.push(t),{tool:t.tool,filePath:t.filePath}}function Hk(t=10){return It.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Gk(){return It.length}function Yk(){return _o.length}function zk({diskToo:t=!0}={}){if(It.length=0,_o.length=0,t){let e=Qi();kt.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&kt.unlink(en.join(e,o)).catch(()=>{})}).catch(()=>{})}}function Qi(){return en.join(process.cwd(),".nex","history")}async function qp(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Fk)return{inline:!0,content:t};let n=qk.createHash("sha256").update(t,"utf-8").digest("hex"),o=en.join(e,"blobs");return await kt.mkdir(o,{recursive:!0}),await kt.writeFile(en.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function Wp(t){let e=Qi();await kt.mkdir(e,{recursive:!0});let n=en.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await qp(t.oldContent,e),r=await qp(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:s.inline?{inline:!0,content:s.content}:{inline:!1,hash:s.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await kt.writeFile(en.join(e,o),JSON.stringify(i),"utf-8")}async function Fp(t,e){if(!t)return null;if(t.inline)return t.content;let n=en.join(e,"blobs",t.hash);return kt.readFile(n,"utf-8")}async function Kk(){let t=Qi(),e;try{e=await kt.readdir(t)}catch{return 0}let n=e.filter(s=>s.endsWith(".json")).sort(),o=0;for(let s of n)try{let r=await kt.readFile(en.join(t,s),"utf-8"),i=JSON.parse(r),a=await Fp(i.oldContent,t),l=await Fp(i.newContent,t);It.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),o++}catch{}for(;It.length>Up;)It.shift();return o}async function Vk(t=7){let e=Qi(),n;try{n=await kt.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,s=n.filter(c=>c.endsWith(".json")),r=0,i=new Set,a=[];for(let c of s)try{let u=await kt.readFile(en.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 kt.unlink(en.join(e,c))}catch{}let l=en.join(e,"blobs");try{let c=await kt.readdir(l);for(let u of c)if(!i.has(u))try{await kt.unlink(en.join(l,u))}catch{}}catch{}return r}var Zi="nex-snapshot";function Xk(t,e=process.cwd()){let n=t?`${Zi}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Zi}-${Date.now()}`;try{return _c("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Bp("git",["stash","push","-u","-m",n],{cwd:e,timeout:15e3}),_c("git stash pop",{cwd:e,timeout:1e4}),{name:n,label:n,ok:!0}):{name:n,label:n,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(o){return{name:n,label:n,ok:!1,error:o.message}}}function Hp(t=process.cwd()){try{let e=_c("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
202
- `).map(n=>{let o=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let s=o[2].trim();return s.startsWith(Zi)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${Zi}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function Jk(t,e=process.cwd()){try{let n=Hp(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let o;return t===void 0||t==="last"?o=n[0]:typeof t=="number"?o=n.find(s=>s.index===t):o=n.find(s=>s.label===t||s.shortName===t||s.shortName.includes(String(t))),o?(Bp("git",["stash","apply",`stash@{${o.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:o.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}Gp.exports={recordChange:Bk,undo:Uk,redo:Wk,getHistory:Hk,getUndoCount:Gk,getRedoCount:Yk,clearHistory:zk,persistEntry:Wp,loadPersistedHistory:Kk,pruneHistory:Vk,createSnapshot:Xk,listSnapshots:Hp,restoreSnapshot:Jk}});var vc=J((uP,Zp)=>{var Ze=require("fs"),jt=require("path"),{atomicWrite:Zk,withFileLockSync:Qk}=Ss(),Ct=[];function ir(){return jt.join(process.cwd(),".nex","skills")}function zp(){return jt.join(process.cwd(),".nex","config.json")}function Kp(){let t=ir();return Ze.existsSync(t)||Ze.mkdirSync(t,{recursive:!0}),t}function xc(){let t=zp();if(!Ze.existsSync(t))return[];try{let e=JSON.parse(Ze.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Vp(t){let e=zp(),n=jt.dirname(e);Ze.existsSync(n)||Ze.mkdirSync(n,{recursive:!0}),Qk(e,()=>{let o={};if(Ze.existsSync(e))try{o=JSON.parse(Ze.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,Zk(e,JSON.stringify(o,null,2))})}function Xp(t,e){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&n.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&n.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&n.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))n.push("commands must be an array");else for(let o=0;o<t.commands.length;o++){let s=t.commands[o];(!s.cmd||typeof s.cmd!="string")&&n.push(`commands[${o}].cmd must be a non-empty string`),s.handler!==void 0&&typeof s.handler!="function"&&n.push(`commands[${o}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))n.push("tools must be an array");else for(let o=0;o<t.tools.length;o++){let s=t.tools[o];(!s.function||!s.function.name||typeof s.function.name!="string")&&n.push(`tools[${o}].function.name must be a non-empty string`),s.execute!==void 0&&typeof s.execute!="function"&&n.push(`tools[${o}].execute must be a function`)}return{valid:n.length===0,errors:n}}function Jp(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let n=e[1],o=e[2].trim(),s=[],r=!1;for(let i of n.split(`
203
- `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?s.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:s,body:o}}function $c(t){try{let e=Ze.readFileSync(t,"utf-8").trim();if(!e)return null;let n=jt.basename(t,".md"),{triggers:o,body:s}=Jp(e);return{name:n,type:"prompt",filePath:t,instructions:s||e,triggers:o,commands:[],tools:[]}}catch{return null}}function kc(t){try{let e=require(t),{valid:n,errors:o}=Xp(e,t);return n?{name:e.name||jt.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}
201
+ `)}Fp.exports={isGitRepo:Lk,getCurrentBranch:Ik,getStatus:_c,getDiff:Ji,getChangedFiles:$c,analyzeDiff:qp,createBranch:jk,commit:Dk,formatDiffSummary:qk,getDiffContext:Bk,getMergeConflicts:Fk}});var Kp=J((pP,zp)=>{var xt=require("fs").promises,fP=require("fs"),tn=require("path"),Uk=require("crypto"),{execSync:kc,execFileSync:Wp}=require("child_process"),Wk=100*1024,Hp=50,It=[],$o=[];function Hk(t,e,n,o){for(It.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});It.length>Hp;)It.shift();$o.length=0,Gp(It[It.length-1]).catch(()=>{})}async function Gk(){if(It.length===0)return null;let t=It.pop();if(t.oldContent===null)try{await xt.unlink(t.filePath)}catch{}else await xt.writeFile(t.filePath,t.oldContent,"utf-8");return $o.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Yk(){if($o.length===0)return null;let t=$o.pop();return await xt.writeFile(t.filePath,t.newContent,"utf-8"),It.push(t),{tool:t.tool,filePath:t.filePath}}function zk(t=10){return It.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Kk(){return It.length}function Vk(){return $o.length}function Xk({diskToo:t=!0}={}){if(It.length=0,$o.length=0,t){let e=ea();xt.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&xt.unlink(tn.join(e,o)).catch(()=>{})}).catch(()=>{})}}function ea(){return tn.join(process.cwd(),".nex","history")}async function Bp(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Wk)return{inline:!0,content:t};let n=Uk.createHash("sha256").update(t,"utf-8").digest("hex"),o=tn.join(e,"blobs");return await xt.mkdir(o,{recursive:!0}),await xt.writeFile(tn.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function Gp(t){let e=ea();await xt.mkdir(e,{recursive:!0});let n=tn.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await Bp(t.oldContent,e),r=await Bp(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:s.inline?{inline:!0,content:s.content}:{inline:!1,hash:s.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await xt.writeFile(tn.join(e,o),JSON.stringify(i),"utf-8")}async function Up(t,e){if(!t)return null;if(t.inline)return t.content;let n=tn.join(e,"blobs",t.hash);return xt.readFile(n,"utf-8")}async function Jk(){let t=ea(),e;try{e=await xt.readdir(t)}catch{return 0}let n=e.filter(s=>s.endsWith(".json")).sort(),o=0;for(let s of n)try{let r=await xt.readFile(tn.join(t,s),"utf-8"),i=JSON.parse(r),a=await Up(i.oldContent,t),l=await Up(i.newContent,t);It.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),o++}catch{}for(;It.length>Hp;)It.shift();return o}async function Zk(t=7){let e=ea(),n;try{n=await xt.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,s=n.filter(c=>c.endsWith(".json")),r=0,i=new Set,a=[];for(let c of s)try{let u=await xt.readFile(tn.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 xt.unlink(tn.join(e,c))}catch{}let l=tn.join(e,"blobs");try{let c=await xt.readdir(l);for(let u of c)if(!i.has(u))try{await xt.unlink(tn.join(l,u))}catch{}}catch{}return r}var Qi="nex-snapshot";function Qk(t,e=process.cwd()){let n=t?`${Qi}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Qi}-${Date.now()}`;try{return kc("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Wp("git",["stash","push","-u","-m",n],{cwd:e,timeout:15e3}),kc("git stash pop",{cwd:e,timeout:1e4}),{name:n,label:n,ok:!0}):{name:n,label:n,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(o){return{name:n,label:n,ok:!1,error:o.message}}}function Yp(t=process.cwd()){try{let e=kc("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
202
+ `).map(n=>{let o=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let s=o[2].trim();return s.startsWith(Qi)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${Qi}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function ex(t,e=process.cwd()){try{let n=Yp(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let o;return t===void 0||t==="last"?o=n[0]:typeof t=="number"?o=n.find(s=>s.index===t):o=n.find(s=>s.label===t||s.shortName===t||s.shortName.includes(String(t))),o?(Wp("git",["stash","apply",`stash@{${o.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:o.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}zp.exports={recordChange:Hk,undo:Gk,redo:Yk,getHistory:zk,getUndoCount:Kk,getRedoCount:Vk,clearHistory:Xk,persistEntry:Gp,loadPersistedHistory:Jk,pruneHistory:Zk,createSnapshot:Qk,listSnapshots:Yp,restoreSnapshot:ex}});var Tc=J((hP,eh)=>{var Ze=require("fs"),jt=require("path"),{atomicWrite:tx,withFileLockSync:nx}=vs(),Ct=[];function ar(){return jt.join(process.cwd(),".nex","skills")}function Vp(){return jt.join(process.cwd(),".nex","config.json")}function Xp(){let t=ar();return Ze.existsSync(t)||Ze.mkdirSync(t,{recursive:!0}),t}function vc(){let t=Vp();if(!Ze.existsSync(t))return[];try{let e=JSON.parse(Ze.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Jp(t){let e=Vp(),n=jt.dirname(e);Ze.existsSync(n)||Ze.mkdirSync(n,{recursive:!0}),nx(e,()=>{let o={};if(Ze.existsSync(e))try{o=JSON.parse(Ze.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,tx(e,JSON.stringify(o,null,2))})}function Zp(t,e){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&n.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&n.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&n.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))n.push("commands must be an array");else for(let o=0;o<t.commands.length;o++){let s=t.commands[o];(!s.cmd||typeof s.cmd!="string")&&n.push(`commands[${o}].cmd must be a non-empty string`),s.handler!==void 0&&typeof s.handler!="function"&&n.push(`commands[${o}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))n.push("tools must be an array");else for(let o=0;o<t.tools.length;o++){let s=t.tools[o];(!s.function||!s.function.name||typeof s.function.name!="string")&&n.push(`tools[${o}].function.name must be a non-empty string`),s.execute!==void 0&&typeof s.execute!="function"&&n.push(`tools[${o}].execute must be a function`)}return{valid:n.length===0,errors:n}}function Qp(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let n=e[1],o=e[2].trim(),s=[],r=!1;for(let i of n.split(`
203
+ `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?s.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:s,body:o}}function xc(t){try{let e=Ze.readFileSync(t,"utf-8").trim();if(!e)return null;let n=jt.basename(t,".md"),{triggers:o,body:s}=Qp(e);return{name:n,type:"prompt",filePath:t,instructions:s||e,triggers:o,commands:[],tools:[]}}catch{return null}}function Sc(t){try{let e=require(t),{valid:n,errors:o}=Zp(e,t);return n?{name:e.name||jt.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}
204
204
  ${o.join(`
205
- `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Sc(){Ct=[];let t=xc(),e=ir(),n=[];if(Ze.existsSync(e))try{n=Ze.readdirSync(e)}catch{n=[]}for(let s of n){let r=jt.join(e,s),i;try{i=Ze.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;s.endsWith(".md")?a=$c(r):s.endsWith(".js")&&(a=kc(r)),a&&(a.enabled=!t.includes(a.name),Ct.push(a))}let o=jt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ze.existsSync(o)){let s;try{s=Ze.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{s=[]}for(let r of s){let i=jt.join(o,r),a=jt.basename(r,jt.extname(r));if(Ct.some(u=>u.name===a))continue;let l;try{l=Ze.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?$c(i):kc(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),Ct.push(c))}}return Ct}function ex(){let t=[];for(let e of Ct)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
205
+ `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Ec(){Ct=[];let t=vc(),e=ar(),n=[];if(Ze.existsSync(e))try{n=Ze.readdirSync(e)}catch{n=[]}for(let s of n){let r=jt.join(e,s),i;try{i=Ze.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;s.endsWith(".md")?a=xc(r):s.endsWith(".js")&&(a=Sc(r)),a&&(a.enabled=!t.includes(a.name),Ct.push(a))}let o=jt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ze.existsSync(o)){let s;try{s=Ze.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{s=[]}for(let r of s){let i=jt.join(o,r),a=jt.basename(r,jt.extname(r));if(Ct.some(u=>u.name===a))continue;let l;try{l=Ze.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?xc(i):Sc(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),Ct.push(c))}}return Ct}function sx(){let t=[];for(let e of Ct)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
206
206
  ${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
207
207
  ${t.join(`
208
208
 
209
- `)}`}function tx(){let t=[];for(let e of Ct)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function nx(){let t=[];for(let e of Ct)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function sx(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let o of Ct)if(o.enabled){for(let s of o.tools)if(s.function.name===n&&s.execute)try{let r=await s.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function ox(t){let[e,...n]=t.split(/\s+/),o=n.join(" ").trim();for(let s of Ct)if(s.enabled){for(let r of s.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(o);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function rx(){return Ct.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function ix(t){let e=Ct.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=xc().filter(o=>o!==t);return Vp(n),!0}function ax(t){let e=Ct.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=xc();return n.includes(t)||(n.push(t),Vp(n)),!0}function lx(){return Ct}async function cx(t,e={}){let{execFileSync:n}=require("child_process"),o=Kp(),s=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(s=`https://github.com/${t}.git`);let r=e.name||jt.basename(s,".git").replace(/^nex-skill-/,""),i=jt.join(o,r);if(Ze.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(s))throw new Error(`Invalid git URL: ${s}`);n("git",["clone","--depth","1",s,i],{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=jt.join(i,"skill.json"),l=Ze.existsSync(a),c=Ze.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{Ze.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(Ze.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Ze.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Sc(),{ok:!0,name:r}}async function ux(t){let e=require("axios");try{let n=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(s=>({name:s.name.replace(/^nex-skill-/,""),description:s.description||"(no description)",url:s.clone_url,stars:s.stargazers_count,owner:s.owner.login}))}catch(n){return[{name:"error",description:`Search failed: ${n.message}`,url:"",stars:0,owner:""}]}}function dx(t){let e=jt.join(ir(),t);if(!Ze.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${ir()}`};try{return Ze.rmSync(e,{recursive:!0,force:!0}),Sc(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function fx(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let o of Ct){if(!o.enabled||!o.triggers||o.triggers.length===0)continue;if(o.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(o.instructions||"").split(`
209
+ `)}`}function ox(){let t=[];for(let e of Ct)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function rx(){let t=[];for(let e of Ct)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function ix(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let o of Ct)if(o.enabled){for(let s of o.tools)if(s.function.name===n&&s.execute)try{let r=await s.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function ax(t){let[e,...n]=t.split(/\s+/),o=n.join(" ").trim();for(let s of Ct)if(s.enabled){for(let r of s.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(o);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function lx(){return Ct.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function cx(t){let e=Ct.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=vc().filter(o=>o!==t);return Jp(n),!0}function ux(t){let e=Ct.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=vc();return n.includes(t)||(n.push(t),Jp(n)),!0}function dx(){return Ct}async function fx(t,e={}){let{execFileSync:n}=require("child_process"),o=Xp(),s=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(s=`https://github.com/${t}.git`);let r=e.name||jt.basename(s,".git").replace(/^nex-skill-/,""),i=jt.join(o,r);if(Ze.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(s))throw new Error(`Invalid git URL: ${s}`);n("git",["clone","--depth","1",s,i],{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=jt.join(i,"skill.json"),l=Ze.existsSync(a),c=Ze.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{Ze.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(Ze.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Ze.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Ec(),{ok:!0,name:r}}async function px(t){let e=require("axios");try{let n=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(s=>({name:s.name.replace(/^nex-skill-/,""),description:s.description||"(no description)",url:s.clone_url,stars:s.stargazers_count,owner:s.owner.login}))}catch(n){return[{name:"error",description:`Search failed: ${n.message}`,url:"",stars:0,owner:""}]}}function hx(t){let e=jt.join(ar(),t);if(!Ze.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${ar()}`};try{return Ze.rmSync(e,{recursive:!0,force:!0}),Ec(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function mx(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let o of Ct){if(!o.enabled||!o.triggers||o.triggers.length===0)continue;if(o.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(o.instructions||"").split(`
210
210
  `).slice(0,3).join(`
211
- `);n.push({name:o.name,instructions:r})}}return n}Zp.exports={initSkillsDir:Kp,loadAllSkills:Sc,getSkillInstructions:ex,getSkillCommands:tx,getSkillToolDefinitions:nx,routeSkillCall:sx,handleSkillCommand:ox,listSkills:rx,enableSkill:ix,disableSkill:ax,getLoadedSkills:lx,installSkill:cx,searchSkills:ux,removeSkill:dx,matchSkillTriggers:fx,_getSkillsDir:ir,_validateScriptSkill:Xp,_loadMarkdownSkill:$c,_loadScriptSkill:kc,_parseFrontmatter:Jp}});var Tc=J((dP,oh)=>{var{spawn:px}=require("child_process"),hx=require("path"),Qp=require("fs"),Bn=new Map;function mx(){return hx.join(process.cwd(),".nex","config.json")}function Ec(){let t=mx();if(!Qp.existsSync(t))return{};try{return JSON.parse(Qp.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function ea(t,e,n={},o=1e4){return new Promise((s,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
211
+ `);n.push({name:o.name,instructions:r})}}return n}eh.exports={initSkillsDir:Xp,loadAllSkills:Ec,getSkillInstructions:sx,getSkillCommands:ox,getSkillToolDefinitions:rx,routeSkillCall:ix,handleSkillCommand:ax,listSkills:lx,enableSkill:cx,disableSkill:ux,getLoadedSkills:dx,installSkill:fx,searchSkills:px,removeSkill:hx,matchSkillTriggers:mx,_getSkillsDir:ar,_validateScriptSkill:Zp,_loadMarkdownSkill:xc,_loadScriptSkill:Sc,_parseFrontmatter:Qp}});var Cc=J((mP,ih)=>{var{spawn:gx}=require("child_process"),yx=require("path"),th=require("fs"),Bn=new Map;function bx(){return yx.join(process.cwd(),".nex","config.json")}function Rc(){let t=bx();if(!th.existsSync(t))return{};try{return JSON.parse(th.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function ta(t,e,n={},o=1e4){return new Promise((s,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
212
212
  `,l="",c=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},o);function u(f){l+=f.toString();let h=l.split(`
213
- `);for(let m of h)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=h[h.length-1]||""}function d(){clearTimeout(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 eh(t,e){if(Bn.has(t))return Bn.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of n)process.env[i]&&(o[i]=process.env[i]);let s=px(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await ea(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await ea(s,"tools/list",{});return r.tools=i&&i.tools||[],Bn.set(t,r),r}catch(i){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function th(t){let e=Bn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Bn.delete(t),!0}function gx(){for(let[t]of Bn)th(t)}async function nh(t,e,n={}){let o=Bn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await ea(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
214
- `):JSON.stringify(s)}function sh(){let t=[];for(let[e,n]of Bn)for(let o of n.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function yx(){return sh().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function bx(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let o=n[0],s=n.slice(1).join("_");return nh(o,s,e)}function wx(){let t=Ec();return Object.entries(t).map(([e,n])=>{let o=Bn.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function _x(){let t=Ec(),e=[];for(let[n,o]of Object.entries(t))try{let s=await eh(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}oh.exports={loadMCPConfig:Ec,sendRequest:ea,connectServer:eh,disconnectServer:th,disconnectAll:gx,callTool:nh,getAllTools:sh,getMCPToolDefinitions:yx,routeMCPCall:bx,listServers:wx,connectAll:_x}});var na=J((fP,lh)=>{var rh=require("fs"),Rc=require("path"),ta=[],ar=[],Ts={},lr=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function ih(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let n=t.function.name;return ar.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(ar.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function ah(t,e){return lr.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Ts[t]||(Ts[t]=[]),Ts[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${lr.join(", ")}`}}async function Cc(t,e){let n=Ts[t]||[],o=e;for(let s of n)try{let r=await s(o);r!==void 0&&(o=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return o}function $x(){let t=Rc.join(process.cwd(),".nex","plugins"),e=[];if(!rh.existsSync(t))return{loaded:0,errors:[]};let n=rh.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:ih,registerHook:ah,EVENTS:lr};for(let s of n){let r=Rc.join(t,s);try{let i=require(r);if(typeof i=="function")i(o);else if(typeof i.setup=="function")i.setup(o);else{e.push(`${s}: Plugin must export a function or { setup: function }`);continue}ta.push({name:i.name||Rc.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:ta.length,errors:e}}function kx(){return ar.map(t=>t.definition)}async function xx(t,e,n={}){let o=ar.find(a=>a.definition.function.name===t);if(!o)return null;let s=await Cc("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await Cc("afterToolExec",{name:t,args:e,result:r})).result||r}function Sx(){return[...ta]}function vx(){let t={};for(let e of lr)t[e]=(Ts[e]||[]).length;return t}function Ex(){ta.length=0,ar.length=0;for(let t of Object.keys(Ts))delete Ts[t]}lh.exports={registerTool:ih,registerHook:ah,emit:Cc,loadPlugins:$x,getPluginToolDefinitions:kx,executePluginTool:xx,getLoadedPlugins:Sx,getHookCounts:vx,clearPlugins:Ex,EVENTS:lr}});var Ac=J((pP,fh)=>{var{getSkillToolDefinitions:Tx}=vc(),{getMCPToolDefinitions:Rx}=Tc(),{getPluginToolDefinitions:Cx}=na(),sa=new Map;function ch(){let{TOOL_DEFINITIONS:t}=cr();return[...t,...Tx(),...Rx(),...Cx()]}function uh(t){if(sa.has(t))return sa.get(t);let n=ch().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return sa.set(t,o),o}function Ax(){sa.clear()}function oa(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=dh(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function dh(t,e){let n=t.length,o=e.length,s=Array.from({length:n+1},()=>Array(o+1).fill(0));for(let r=0;r<=n;r++)s[r][0]=r;for(let r=0;r<=o;r++)s[0][r]=r;for(let r=1;r<=n;r++)for(let i=1;i<=o;i++)s[r][i]=t[r-1]===e[i-1]?s[r-1][i-1]:1+Math.min(s[r-1][i],s[r][i-1],s[r-1][i-1]);return s[n][o]}function Ox(t,e){let n=uh(t);if(n===null){let d=ch().map(h=>h.function.name),f=oa(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
215
- Available tools: ${d.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let o=n.required||[],s=Object.keys(n.properties),r=Object.keys(e),i=[],a={...e},l=!1;for(let u of o)if(!(u in e)||e[u]===void 0||e[u]===null){let d=oa(u,r);d&&!s.includes(d)?(a[u]=e[d],delete a[d],l=!0):i.push(`Missing required parameter "${u}" (${n.properties[u]?.description||n.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!s.includes("-n")&&(delete a["-n"],delete a.n,l=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(n.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],l=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],l=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,l=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,l=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,l=!0));for(let u of Object.keys(a))if(!s.includes(u)){let d=oa(u,s);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(!n.properties[u])continue;let d=n.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:
213
+ `);for(let m of h)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=h[h.length-1]||""}function d(){clearTimeout(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 nh(t,e){if(Bn.has(t))return Bn.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of n)process.env[i]&&(o[i]=process.env[i]);let s=gx(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await ta(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await ta(s,"tools/list",{});return r.tools=i&&i.tools||[],Bn.set(t,r),r}catch(i){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function sh(t){let e=Bn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Bn.delete(t),!0}function wx(){for(let[t]of Bn)sh(t)}async function oh(t,e,n={}){let o=Bn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await ta(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
214
+ `):JSON.stringify(s)}function rh(){let t=[];for(let[e,n]of Bn)for(let o of n.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function _x(){return rh().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function $x(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let o=n[0],s=n.slice(1).join("_");return oh(o,s,e)}function kx(){let t=Rc();return Object.entries(t).map(([e,n])=>{let o=Bn.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function xx(){let t=Rc(),e=[];for(let[n,o]of Object.entries(t))try{let s=await nh(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}ih.exports={loadMCPConfig:Rc,sendRequest:ta,connectServer:nh,disconnectServer:sh,disconnectAll:wx,callTool:oh,getAllTools:rh,getMCPToolDefinitions:_x,routeMCPCall:$x,listServers:kx,connectAll:xx}});var sa=J((gP,uh)=>{var ah=require("fs"),Ac=require("path"),na=[],lr=[],Rs={},cr=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function lh(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let n=t.function.name;return lr.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(lr.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function ch(t,e){return cr.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Rs[t]||(Rs[t]=[]),Rs[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${cr.join(", ")}`}}async function Oc(t,e){let n=Rs[t]||[],o=e;for(let s of n)try{let r=await s(o);r!==void 0&&(o=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return o}function Sx(){let t=Ac.join(process.cwd(),".nex","plugins"),e=[];if(!ah.existsSync(t))return{loaded:0,errors:[]};let n=ah.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:lh,registerHook:ch,EVENTS:cr};for(let s of n){let r=Ac.join(t,s);try{let i=require(r);if(typeof i=="function")i(o);else if(typeof i.setup=="function")i.setup(o);else{e.push(`${s}: Plugin must export a function or { setup: function }`);continue}na.push({name:i.name||Ac.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:na.length,errors:e}}function vx(){return lr.map(t=>t.definition)}async function Ex(t,e,n={}){let o=lr.find(a=>a.definition.function.name===t);if(!o)return null;let s=await Oc("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await Oc("afterToolExec",{name:t,args:e,result:r})).result||r}function Tx(){return[...na]}function Rx(){let t={};for(let e of cr)t[e]=(Rs[e]||[]).length;return t}function Cx(){na.length=0,lr.length=0;for(let t of Object.keys(Rs))delete Rs[t]}uh.exports={registerTool:lh,registerHook:ch,emit:Oc,loadPlugins:Sx,getPluginToolDefinitions:vx,executePluginTool:Ex,getLoadedPlugins:Tx,getHookCounts:Rx,clearPlugins:Cx,EVENTS:cr}});var Pc=J((yP,hh)=>{var{getSkillToolDefinitions:Ax}=Tc(),{getMCPToolDefinitions:Ox}=Cc(),{getPluginToolDefinitions:Px}=sa(),oa=new Map;function dh(){let{TOOL_DEFINITIONS:t}=ur();return[...t,...Ax(),...Ox(),...Px()]}function fh(t){if(oa.has(t))return oa.get(t);let n=dh().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return oa.set(t,o),o}function Nx(){oa.clear()}function ra(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=ph(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function ph(t,e){let n=t.length,o=e.length,s=Array.from({length:n+1},()=>Array(o+1).fill(0));for(let r=0;r<=n;r++)s[r][0]=r;for(let r=0;r<=o;r++)s[0][r]=r;for(let r=1;r<=n;r++)for(let i=1;i<=o;i++)s[r][i]=t[r-1]===e[i-1]?s[r-1][i-1]:1+Math.min(s[r-1][i],s[r][i-1],s[r-1][i-1]);return s[n][o]}function Mx(t,e){let n=fh(t);if(n===null){let d=dh().map(h=>h.function.name),f=ra(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
215
+ Available tools: ${d.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let o=n.required||[],s=Object.keys(n.properties),r=Object.keys(e),i=[],a={...e},l=!1;for(let u of o)if(!(u in e)||e[u]===void 0||e[u]===null){let d=ra(u,r);d&&!s.includes(d)?(a[u]=e[d],delete a[d],l=!0):i.push(`Missing required parameter "${u}" (${n.properties[u]?.description||n.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!s.includes("-n")&&(delete a["-n"],delete a.n,l=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(n.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],l=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],l=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,l=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,l=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,l=!0));for(let u of Object.keys(a))if(!s.includes(u)){let d=ra(u,s);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(!n.properties[u])continue;let d=n.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:
216
216
  `+i.map(u=>` - ${u}`).join(`
217
217
  `)+`
218
218
 
219
- Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function Px(t,e){let n=[],o={...t};if(!o.function&&!o.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:n};if(!o.function&&o.name&&(o.function={name:o.name,arguments:o.arguments||o.args||{}},delete o.name,delete o.args),o.function&&o.function.args!==void 0&&o.function.arguments===void 0&&(o.function.arguments=o.function.args,delete o.function.args),o.function&&(o.function.arguments===void 0||o.function.arguments===null)&&(o.function.arguments={}),o.function&&typeof o.function.arguments=="string"){let s=o.function.arguments;if(s.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(s)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:n}}}return o.function&&typeof o.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:n}):!o.function.name||typeof o.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:n}):{valid:n.length===0,normalized:o,errors:n}}fh.exports={validateToolArgs:Ox,validateToolCallFormat:Px,closestMatch:oa,levenshtein:dh,getCachedSchema:uh,clearSchemaCache:Ax}});var gh=J((hP,mh)=>{var{levenshtein:ra}=Ac(),Nx=200,Mx=.3,Lx=2;function Oc(t){return t.replace(/\r\n/g,`
219
+ Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function Lx(t,e){let n=[],o={...t};if(!o.function&&!o.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:n};if(!o.function&&o.name&&(o.function={name:o.name,arguments:o.arguments||o.args||{}},delete o.name,delete o.args),o.function&&o.function.args!==void 0&&o.function.arguments===void 0&&(o.function.arguments=o.function.args,delete o.function.args),o.function&&(o.function.arguments===void 0||o.function.arguments===null)&&(o.function.arguments={}),o.function&&typeof o.function.arguments=="string"){let s=o.function.arguments;if(s.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(s)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:n}}}return o.function&&typeof o.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:n}):!o.function.name||typeof o.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:n}):{valid:n.length===0,normalized:o,errors:n}}hh.exports={validateToolArgs:Mx,validateToolCallFormat:Lx,closestMatch:ra,levenshtein:ph,getCachedSchema:fh,clearSchemaCache:Nx}});var bh=J((bP,yh)=>{var{levenshtein:ia}=Pc(),Ix=200,jx=.3,Dx=2;function Nc(t){return t.replace(/\r\n/g,`
220
220
  `).replace(/\r/g,`
221
- `).replace(/\t/g," ".repeat(Lx)).split(`
221
+ `).replace(/\t/g," ".repeat(Dx)).split(`
222
222
  `).map(e=>{let n=e.replace(/\s+$/,""),o=n.match(/^(\s*)(.*)/);if(!o)return n;let[,s,r]=o;return s+r.replace(/ {2,}/g," ")}).join(`
223
- `)}function Ix(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=Oc(t),o=Oc(e);if(!n.includes(o))return null;let s=t.split(`
223
+ `)}function qx(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=Nc(t),o=Nc(e);if(!n.includes(o))return null;let s=t.split(`
224
224
  `),r=n.split(`
225
225
  `),i=o.split(`
226
226
  `),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 s.slice(c,c+i.length).join(`
227
- `)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(o)!==-1)return s[c]}return null}function jx(t,e){if(!t||!e)return null;let n=t.split(`
227
+ `)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(o)!==-1)return s[c]}return null}function Fx(t,e){if(!t||!e)return null;let n=t.split(`
228
228
  `),s=e.split(`
229
- `).length;return n.length===0||s===0?null:s===1?Dx(n,e):Fx(n,e,s)}function ph(t){return Math.max(1,Math.floor(t/Nx))}function hh(t,e){return t<=Math.ceil(e*Mx)}function Dx(t,e){let n=e.trim(),o=ph(t.length),s=null,r=1/0;for(let i=0;i<t.length;i+=o){let a=t[i];if(!a.trim())continue;let l=ra(a.trim(),n);l<r&&(r=l,s={text:a,distance:l,line:i+1})}return s&&o>1&&(s=qx(t,n,s,o)||s,r=s.distance),hh(r,e.length)?s:null}function qx(t,e,n,o){let s=n.line-1,r=Math.max(0,s-o),i=Math.min(t.length-1,s+o),a=n.distance,l=null;for(let c=r;c<=i;c++){let u=t[c];if(!u.trim())continue;let d=ra(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function Fx(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=ph(o),r=null,i=1/0;for(let a=0;a<o;a+=s){let l=t.slice(a,a+n).join(`
230
- `),c=ra(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&s>1&&(r=Bx(t,e,r,s,n,o)||r,i=r.distance),hh(i,e.length)?r:null}function Bx(t,e,n,o,s,r){let i=n.line-1,a=Math.max(0,i-o),l=Math.min(r-1,i+o),c=n.distance,u=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+s).join(`
231
- `),h=ra(f,e);h<c&&(c=h,u={text:f,distance:h,line:d+1})}return u}mh.exports={normalizeWhitespace:Oc,fuzzyFindText:Ix,findMostSimilar:jx}});var vh=J((mP,Nc)=>{var yh=require("fs"),Ux=require("path"),{execFileSync:Wx}=require("child_process"),bh=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],Hx=/(^|\/)(tests\/.*\.test\.(js|ts|jsx|tsx)|__tests__\/.*\.(js|ts|jsx|tsx))$/i,wh=[{category:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{category:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{category:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{category:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{category:"GitHub Token (ghp_)",regex:/ghp_[a-zA-Z0-9]{36}/i},{category:"GitHub OAuth (gho_)",regex:/gho_[a-zA-Z0-9]{36}/i},{category:"GitHub App Token (ghs_)",regex:/ghs_[a-zA-Z0-9]{36}/i},{category:"GitHub Fine-Grained Token",regex:/github_pat_[a-zA-Z0-9_]{20,}/i},{category:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{category:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{category:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{category:"Credential URL",regex:/\b[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@[^/\s]+/i},{category:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"][^'"]{8,}/i},{category:"SSH + IP",regex:/\bssh\s+.*@[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"SSH Config HostName",regex:/\bHostName\s+[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"Server IP Assignment",regex:/\b(host|hostname|server|server_ip|public_ip|private_ip|vps_ip|ssh_host|remote_host|db_host)\b\s*[:=]\s*['"]?[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+['"]?/i},{category:".env Secret Assignment",regex:/\b(API_KEY|SECRET_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY|ACCESS_KEY|AUTH_TOKEN|DB_PASSWORD|DATABASE_URL)\s*=/i}],Gx=/(^|\/)\.env(?:\.[^/]+)?\.(example|sample|template)$/i,_h=[{category:"Sensitive Env File",regex:/(^|\/)\.env(?:\.[^/]+)?$/i},{category:"Private Key File",regex:/(^|\/)(id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|.*\.key)$/i},{category:"Certificate Bundle",regex:/(^|\/).*\.(p12|pfx|mobileprovision)$/i},{category:"Terraform Secrets",regex:/(^|\/).*\.(tfvars|tfstate)(\..+)?$/i},{category:"Credential File",regex:/(^|\/)(\.npmrc|\.netrc)$/i},{category:"Cloud Credentials",regex:/(^|\/)\.(aws\/credentials|kube\/config)$/i}];function ia(t,e=process.cwd()){return Wx("git",t,{cwd:e,encoding:"utf8"})}function Yx(t=process.cwd()){return ia(["rev-parse","--show-toplevel"],t).trim()}function zx(t){let e=Ux.join(t,".nex","push-allowlist");return yh.existsSync(e)?yh.readFileSync(e,"utf8").split(`
232
- `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function Pc(t,e){return e.some(n=>t.includes(n))}function $h(t){return Gx.test(t)}function kh(t,e){let n=[];for(let o of t)if(!$h(o))for(let s of _h)s.regex.test(o)&&(Pc(o,e)||n.push({category:s.category,location:o,preview:o}));return n}function Kx(t){let e=t.split(`
233
- `),n=[],o="";for(let s=0;s<e.length;s++){let r=e[s];if(r.startsWith("+++ b/")){o=r.slice(6);continue}!r.startsWith("+")||r.startsWith("+++")||n.push({filePath:o,lineNumber:s+1,text:r.slice(1),raw:r})}return n}function xh(t,e){let n=[];for(let o of Kx(t))if(!Hx.test(o.filePath||""))for(let s of wh)s.regex.test(o.text)&&(Pc(o.raw,e)||Pc(o.text,e)||n.push({category:s.category,location:`${o.lineNumber}:${o.raw}`,preview:o.raw}));return n}function Vx(t){return ia(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function Xx(t,e){return ia(["diff",e,...bh],t)}function Jx(t){return ia(["diff","--cached",...bh],t)}function Sh({repoRoot:t,mode:e,range:n}){let o=zx(t),s=e==="staged"?Vx(t):[],r=kh(s,o),i=e==="range"?Xx(t,n):Jx(t),a=xh(i,o);return[...r,...a]}function Zx(t){return t.map(e=>` [${e.category}]
229
+ `).length;return n.length===0||s===0?null:s===1?Bx(n,e):Wx(n,e,s)}function mh(t){return Math.max(1,Math.floor(t/Ix))}function gh(t,e){return t<=Math.ceil(e*jx)}function Bx(t,e){let n=e.trim(),o=mh(t.length),s=null,r=1/0;for(let i=0;i<t.length;i+=o){let a=t[i];if(!a.trim())continue;let l=ia(a.trim(),n);l<r&&(r=l,s={text:a,distance:l,line:i+1})}return s&&o>1&&(s=Ux(t,n,s,o)||s,r=s.distance),gh(r,e.length)?s:null}function Ux(t,e,n,o){let s=n.line-1,r=Math.max(0,s-o),i=Math.min(t.length-1,s+o),a=n.distance,l=null;for(let c=r;c<=i;c++){let u=t[c];if(!u.trim())continue;let d=ia(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function Wx(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=mh(o),r=null,i=1/0;for(let a=0;a<o;a+=s){let l=t.slice(a,a+n).join(`
230
+ `),c=ia(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&s>1&&(r=Hx(t,e,r,s,n,o)||r,i=r.distance),gh(i,e.length)?r:null}function Hx(t,e,n,o,s,r){let i=n.line-1,a=Math.max(0,i-o),l=Math.min(r-1,i+o),c=n.distance,u=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+s).join(`
231
+ `),h=ia(f,e);h<c&&(c=h,u={text:f,distance:h,line:d+1})}return u}yh.exports={normalizeWhitespace:Nc,fuzzyFindText:qx,findMostSimilar:Fx}});var Th=J((wP,Lc)=>{var wh=require("fs"),Gx=require("path"),{execFileSync:Yx}=require("child_process"),_h=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],zx=/(^|\/)(tests\/.*\.test\.(js|ts|jsx|tsx)|__tests__\/.*\.(js|ts|jsx|tsx))$/i,$h=[{category:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{category:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{category:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{category:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{category:"GitHub Token (ghp_)",regex:/ghp_[a-zA-Z0-9]{36}/i},{category:"GitHub OAuth (gho_)",regex:/gho_[a-zA-Z0-9]{36}/i},{category:"GitHub App Token (ghs_)",regex:/ghs_[a-zA-Z0-9]{36}/i},{category:"GitHub Fine-Grained Token",regex:/github_pat_[a-zA-Z0-9_]{20,}/i},{category:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{category:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{category:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{category:"Credential URL",regex:/\b[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@[^/\s]+/i},{category:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"][^'"]{8,}/i},{category:"SSH + IP",regex:/\bssh\s+.*@[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"SSH Config HostName",regex:/\bHostName\s+[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"Server IP Assignment",regex:/\b(host|hostname|server|server_ip|public_ip|private_ip|vps_ip|ssh_host|remote_host|db_host)\b\s*[:=]\s*['"]?[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+['"]?/i},{category:".env Secret Assignment",regex:/\b(API_KEY|SECRET_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY|ACCESS_KEY|AUTH_TOKEN|DB_PASSWORD|DATABASE_URL)\s*=/i}],Kx=/(^|\/)\.env(?:\.[^/]+)?\.(example|sample|template)$/i,kh=[{category:"Sensitive Env File",regex:/(^|\/)\.env(?:\.[^/]+)?$/i},{category:"Private Key File",regex:/(^|\/)(id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|.*\.key)$/i},{category:"Certificate Bundle",regex:/(^|\/).*\.(p12|pfx|mobileprovision)$/i},{category:"Terraform Secrets",regex:/(^|\/).*\.(tfvars|tfstate)(\..+)?$/i},{category:"Credential File",regex:/(^|\/)(\.npmrc|\.netrc)$/i},{category:"Cloud Credentials",regex:/(^|\/)\.(aws\/credentials|kube\/config)$/i}];function aa(t,e=process.cwd()){return Yx("git",t,{cwd:e,encoding:"utf8"})}function Vx(t=process.cwd()){return aa(["rev-parse","--show-toplevel"],t).trim()}function Xx(t){let e=Gx.join(t,".nex","push-allowlist");return wh.existsSync(e)?wh.readFileSync(e,"utf8").split(`
232
+ `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function Mc(t,e){return e.some(n=>t.includes(n))}function xh(t){return Kx.test(t)}function Sh(t,e){let n=[];for(let o of t)if(!xh(o))for(let s of kh)s.regex.test(o)&&(Mc(o,e)||n.push({category:s.category,location:o,preview:o}));return n}function Jx(t){let e=t.split(`
233
+ `),n=[],o="";for(let s=0;s<e.length;s++){let r=e[s];if(r.startsWith("+++ b/")){o=r.slice(6);continue}!r.startsWith("+")||r.startsWith("+++")||n.push({filePath:o,lineNumber:s+1,text:r.slice(1),raw:r})}return n}function vh(t,e){let n=[];for(let o of Jx(t))if(!zx.test(o.filePath||""))for(let s of $h)s.regex.test(o.text)&&(Mc(o.raw,e)||Mc(o.text,e)||n.push({category:s.category,location:`${o.lineNumber}:${o.raw}`,preview:o.raw}));return n}function Zx(t){return aa(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function Qx(t,e){return aa(["diff",e,..._h],t)}function eS(t){return aa(["diff","--cached",..._h],t)}function Eh({repoRoot:t,mode:e,range:n}){let o=Xx(t),s=e==="staged"?Zx(t):[],r=Sh(s,o),i=e==="range"?Qx(t,n):eS(t),a=vh(i,o);return[...r,...a]}function tS(t){return t.map(e=>` [${e.category}]
234
234
  ${e.location}`).join(`
235
- `)}function Qx(t){let e={mode:"staged",range:""};for(let n=0;n<t.length;n++)t[n]==="--staged"&&(e.mode="staged"),t[n]==="--range"&&(e.mode="range",e.range=t[n+1]||"",n++);return e}function eS(){let t=Qx(process.argv.slice(2)),e=Yx(),n=Sh({repoRoot:e,mode:t.mode,range:t.range});if(n.length===0)return;let o=t.mode==="range"?"pushed commits":"staged changes";console.log(""),console.log("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log("\u2551 SECRET DETECTED \u2014 operation blocked \u2551"),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(`\u2551 Found ${n.length} potential secret(s) in ${o}:`),console.log(Zx(n)),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log("\u2551 Remove secrets or move them to local-only config. \u2551"),console.log("\u2551 To allowlist: add a specific pattern to .nex/push-allowlist"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(""),process.exit(1)}require.main===Nc&&eS();Nc.exports={SECRET_PATTERNS:wh,SENSITIVE_FILE_RULES:_h,scanDiffText:xh,scanFileNames:kh,scanRepo:Sh,isSafeExampleFile:$h}});var Th=J((yP,Eh)=>{var{C:gP}=_t(),{SECRET_PATTERNS:tS}=vh(),nS=[{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 sS(t,e){let n=e.split(`
236
- `),o=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let l of tS)l.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${l.category}`,severity:"error"});for(let l of nS)l.ext&&!l.ext.includes(s)||l.regex.test(i)&&o.push({line:a,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return n.length>500&&o.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),o}function oS(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Eh.exports={runDiagnostics:sS,getMemoryUsage:oS}});var Rn=J((bP,qh)=>{var Rs=require("fs").promises,Dt=require("path"),{exec:rS}=require("util").promisify(require("child_process").exec),ns=[],Ic=null,aa=!1,Lc=0,iS=6e4;function jc(t){return!(ns.length===0||Ic!==t||Date.now()-Lc>iS)}async function Ph(t){if(!aa&&!jc(t)){aa=!0,Ic=t;try{try{let{stdout:o}=await rS("rg --files",{cwd:t,timeout:5e3});ns=o.split(`
237
- `).filter(Boolean),Lc=Date.now(),aa=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await Rs.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=s?`${s}/${i.name}`:i.name;i.isDirectory()?await n(Dt.join(o,i.name),a):e.push(a)}};await n(t,""),ns=e,Lc=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{aa=!1}}}function ur(){return ns}function aS(){return Ic}function lS(t){return ns.filter(e=>Dt.basename(e)===t)}function cS(t){let e=t.toLowerCase();return ns.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}function Nh(t,e){let n=t.length,o=e.length;if(n===0)return o;if(o===0)return n;let s=Array.from({length:o+1},(r,i)=>i);for(let r=1;r<=n;r++){let i=r-1;s[0]=r;for(let a=1;a<=o;a++){let l=t[r-1]===e[a-1]?i:1+Math.min(s[a],s[a-1],i);i=s[a],s[a]=l}}return s[o]}function Mh(t,e){let n=t.toLowerCase(),o=e.toLowerCase();if(n===o)return 1e3;let s=n.split("/").filter(Boolean),r=o.split("/").filter(Boolean),i=0;for(let u=1;u<=Math.min(s.length,r.length)&&s[s.length-u]===r[r.length-u];u++)i=u;if(i>0&&i===r.length)return 500+i*100;let a=Dt.basename(t).toLowerCase(),l=Dt.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-Nh(a,l)/u;f>=.6&&(c+=Math.round(f*50))}}if((n.includes(o)||o.includes(n))&&(c+=20),r.length>1){let u=new Set(s),d=0;for(let f of r)u.has(f)&&d++;c+=d*10}return i>0&&(c+=i*30),c}function uS(t,{limit:e=10,minScore:n=15}={}){if(!t||ns.length===0)return[];let o=[];for(let s of ns){let r=Mh(s,t);r>=n&&o.push({file:s,score:r})}return o.sort((s,r)=>r.score-s.score),o.slice(0,e)}var Mc=null,Rh=0,Ch=null,Lh=12e4,la=null,Ah=0,Oh=null,Ih=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function jh(t,e){let n=[],o=t.split(`
238
- `);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let c=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);c&&n.push({type:"function",name:c[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of f)/^\w+$/.test(h)&&n.push({type:"export",name:h,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];n.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let c=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);c&&n.push({type:"import",name:c[1]||c[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&n.push({type:"class",name:l[1],line:i})}}return n}async function ca(t){t=t||process.cwd();let e=Dt.join(t,".nex","index","content-index.json"),n={};if(Mc&&Ch===t&&Date.now()-Rh<Lh)return Mc;try{let i=await Rs.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}let o=ur();(!jc(t)||o.length===0)&&(await Ph(t),o=ur());let s={files:{}},r=!1;for(let i of ur()){let a=Dt.extname(i);if(!Ih.has(a))continue;let l=Dt.join(t,i);try{let u=(await Rs.stat(l)).mtimeMs;if(n.files[i]&&n.files[i].mtime===u){s.files[i]=n.files[i];continue}let d=await Rs.readFile(l,"utf-8"),f=jh(d,a);s.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=Dt.join(t,".nex","index");await Rs.mkdir(i,{recursive:!0}),await Rs.writeFile(e,JSON.stringify(s),"utf-8")}return Mc=s,Rh=Date.now(),Ch=t,s}async function dS(t,e,n){let o=await ca(n),s=[],r=t.toLowerCase();for(let[i,a]of Object.entries(o.files))for(let l of a.defs)e&&l.type!==e||l.name.toLowerCase().includes(r)&&s.push({file:i,type:l.type,name:l.name,line:l.line});return s.sort((i,a)=>{let l=i.name.toLowerCase()===r?0:1,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}),s.slice(0,50)}function fS(t,e,n){if(!e||!e.startsWith("."))return null;let o=Dt.posix.dirname(t.replace(/\\/g,"/")),s=Dt.posix.normalize(Dt.posix.join(o==="."?"":o,e)),r=[];if(Dt.posix.extname(s))r.push(s);else for(let a of Ih)r.push(`${s}${a}`),r.push(Dt.posix.join(s,`index${a}`));for(let a of r)if(n.has(a))return a;return null}async function Dc(t){if(t=t||process.cwd(),la&&Oh===t&&Date.now()-Ah<Lh)return la;let e=await ca(t),n=ur(),o=new Set(n.map(i=>i.replace(/\\/g,"/"))),s={},r={};for(let i of Object.keys(e.files||{})){let a=i.replace(/\\/g,"/"),l=Array.isArray(e.files[i]?.defs)?e.files[i].defs:[],c=[],u=new Set;for(let d of l){if(d.type!=="import")continue;let f=fS(a,d.name,o);!f||f===a||u.has(f)||(u.add(f),c.push(f),r[f]||(r[f]=[]),r[f].push(a))}s[a]=c}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return la={importsByFile:s,importedByFile:r},Ah=Date.now(),Oh=t,la}async function pS(t,e,n=6){if(!t)return[];let o=await Dc(e),s=String(t).replace(/\\/g,"/"),r=[...o.importsByFile[s]||[],...o.importedByFile[s]||[]];return[...new Set(r)].filter(i=>i!==s).slice(0,n)}async function hS(t,e=4){let n=await Dc(t),o=new Map;for(let[s,r]of Object.entries(n.importsByFile||{}))o.set(s,(o.get(s)||0)+r.length);for(let[s,r]of Object.entries(n.importedByFile||{}))o.set(s,(o.get(s)||0)+r.length);return[...o.entries()].filter(([,s])=>s>0).sort((s,r)=>r[1]-s[1]||s[0].localeCompare(r[0])).slice(0,e).map(([s,r])=>`${s} (${r} links)`)}function Dh(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mS(t,e){let n=Dh(e);return[new RegExp(`\\bfunction\\s+${n}\\b`),new RegExp(`\\bclass\\s+${n}\\b`),new RegExp(`\\b(?:const|let|var)\\s+${n}\\b\\s*=`),new RegExp(`\\bdef\\s+${n}\\b`),new RegExp(`\\btype\\s+${n}\\b\\s+struct\\b`),new RegExp(`\\bmodule\\.exports\\b[^\\n]*\\b${n}\\b`),new RegExp(`\\bexport\\b[^\\n]*\\b${n}\\b`)].some(s=>s.test(t))}async function gS(t,e,n={}){e=e||process.cwd();let{excludeFile:o=null,excludeLine:s=null,limit:r=6}=n;if(!t||typeof t!="string")return[];let i=await ca(e),a=Dh(t),l=new RegExp(`\\b${a}\\s*\\(`),c=new RegExp(`\\b${a}\\b`),u=[];for(let d of Object.keys(i.files||{})){let f=d.replace(/\\/g,"/");try{let h=Dt.join(e,f),g=(await Rs.readFile(h,"utf-8")).split(`
239
- `);for(let _=0;_<g.length;_++){let k=g[_],$=_+1;if(!c.test(k)||o&&f===o&&s===$||mS(k,t))continue;let O=(f===o?0:4)+(l.test(k)?3:1);u.push({file:f,line:$,context:k.trim(),score:O})}}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)}qh.exports={refreshIndex:Ph,getFileIndex:ur,getIndexedCwd:aS,findFileInIndex:lS,searchIndex:cS,isIndexValid:jc,buildContentIndex:ca,searchContentIndex:dS,extractDefinitions:jh,buildImportGraph:Dc,getRelatedFiles:pS,summarizeModuleHubs:hS,findSymbolReferences:gS,smartSearch:uS,scorePathMatch:Mh,pathLevenshtein:Nh}});var $o=J((wP,Gh)=>{var ua=require("fs"),ha=require("path"),ma=require("os"),{execFile:yS}=require("child_process"),{promisify:bS}=require("util"),qc=bS(yS),wS=ha.join(ma.homedir(),".nex","servers.json"),da=ha.join(ma.tmpdir(),"nex-ssh-sockets");function _S(){return ha.join(process.cwd(),".nex","servers.json")}function Fh(){let t=o=>{if(!ua.existsSync(o))return{};try{return JSON.parse(ua.readFileSync(o,"utf-8"))}catch{return{}}},e=t(wS),n=t(_S());return{...e,...n}}function $S(t){let e=Fh();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[s,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:s}}let n=Object.keys(e),o=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${o}`)}function kS(){ua.existsSync(da)||ua.mkdirSync(da,{recursive:!0})}function Bh(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,ma.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),kS();let n=t.user?`${t.user}@${t.host}`:t.host,o=ha.join(da,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function Uh(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,ma.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function fa(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=Bh(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await qc("ssh",[...s,r],{timeout:n,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:a,error:ga(l,t)}}}async function xS(t,e,n,{timeout:o=12e4}={}){let s=Uh(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:a}=await qc("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(ga(a,t)||a)}}async function SS(t,e,n,{timeout:o=12e4}={}){let s=Uh(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:a}=await qc("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(ga(a,t)||a)}}function ga(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
235
+ `)}function nS(t){let e={mode:"staged",range:""};for(let n=0;n<t.length;n++)t[n]==="--staged"&&(e.mode="staged"),t[n]==="--range"&&(e.mode="range",e.range=t[n+1]||"",n++);return e}function sS(){let t=nS(process.argv.slice(2)),e=Vx(),n=Eh({repoRoot:e,mode:t.mode,range:t.range});if(n.length===0)return;let o=t.mode==="range"?"pushed commits":"staged changes";console.log(""),console.log("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log("\u2551 SECRET DETECTED \u2014 operation blocked \u2551"),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(`\u2551 Found ${n.length} potential secret(s) in ${o}:`),console.log(tS(n)),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log("\u2551 Remove secrets or move them to local-only config. \u2551"),console.log("\u2551 To allowlist: add a specific pattern to .nex/push-allowlist"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(""),process.exit(1)}require.main===Lc&&sS();Lc.exports={SECRET_PATTERNS:$h,SENSITIVE_FILE_RULES:kh,scanDiffText:vh,scanFileNames:Sh,scanRepo:Eh,isSafeExampleFile:xh}});var Ch=J(($P,Rh)=>{var{C:_P}=$t(),{SECRET_PATTERNS:oS}=Th(),rS=[{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 iS(t,e){let n=e.split(`
236
+ `),o=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let l of oS)l.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${l.category}`,severity:"error"});for(let l of rS)l.ext&&!l.ext.includes(s)||l.regex.test(i)&&o.push({line:a,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return n.length>500&&o.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),o}function aS(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Rh.exports={runDiagnostics:iS,getMemoryUsage:aS}});var Rn=J((kP,Bh)=>{var Cs=require("fs").promises,Dt=require("path"),{exec:lS}=require("util").promisify(require("child_process").exec),ns=[],Dc=null,la=!1,jc=0,cS=6e4;function qc(t){return!(ns.length===0||Dc!==t||Date.now()-jc>cS)}async function Mh(t){if(!la&&!qc(t)){la=!0,Dc=t;try{try{let{stdout:o}=await lS("rg --files",{cwd:t,timeout:5e3});ns=o.split(`
237
+ `).filter(Boolean),jc=Date.now(),la=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await Cs.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=s?`${s}/${i.name}`:i.name;i.isDirectory()?await n(Dt.join(o,i.name),a):e.push(a)}};await n(t,""),ns=e,jc=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{la=!1}}}function dr(){return ns}function uS(){return Dc}function dS(t){return ns.filter(e=>Dt.basename(e)===t)}function fS(t){let e=t.toLowerCase();return ns.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}function Lh(t,e){let n=t.length,o=e.length;if(n===0)return o;if(o===0)return n;let s=Array.from({length:o+1},(r,i)=>i);for(let r=1;r<=n;r++){let i=r-1;s[0]=r;for(let a=1;a<=o;a++){let l=t[r-1]===e[a-1]?i:1+Math.min(s[a],s[a-1],i);i=s[a],s[a]=l}}return s[o]}function Ih(t,e){let n=t.toLowerCase(),o=e.toLowerCase();if(n===o)return 1e3;let s=n.split("/").filter(Boolean),r=o.split("/").filter(Boolean),i=0;for(let u=1;u<=Math.min(s.length,r.length)&&s[s.length-u]===r[r.length-u];u++)i=u;if(i>0&&i===r.length)return 500+i*100;let a=Dt.basename(t).toLowerCase(),l=Dt.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-Lh(a,l)/u;f>=.6&&(c+=Math.round(f*50))}}if((n.includes(o)||o.includes(n))&&(c+=20),r.length>1){let u=new Set(s),d=0;for(let f of r)u.has(f)&&d++;c+=d*10}return i>0&&(c+=i*30),c}function pS(t,{limit:e=10,minScore:n=15}={}){if(!t||ns.length===0)return[];let o=[];for(let s of ns){let r=Ih(s,t);r>=n&&o.push({file:s,score:r})}return o.sort((s,r)=>r.score-s.score),o.slice(0,e)}var Ic=null,Ah=0,Oh=null,jh=12e4,ca=null,Ph=0,Nh=null,Dh=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function qh(t,e){let n=[],o=t.split(`
238
+ `);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let c=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);c&&n.push({type:"function",name:c[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of f)/^\w+$/.test(h)&&n.push({type:"export",name:h,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];n.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let c=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);c&&n.push({type:"import",name:c[1]||c[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&n.push({type:"class",name:l[1],line:i})}}return n}async function ua(t){t=t||process.cwd();let e=Dt.join(t,".nex","index","content-index.json"),n={};if(Ic&&Oh===t&&Date.now()-Ah<jh)return Ic;try{let i=await Cs.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}let o=dr();(!qc(t)||o.length===0)&&(await Mh(t),o=dr());let s={files:{}},r=!1;for(let i of dr()){let a=Dt.extname(i);if(!Dh.has(a))continue;let l=Dt.join(t,i);try{let u=(await Cs.stat(l)).mtimeMs;if(n.files[i]&&n.files[i].mtime===u){s.files[i]=n.files[i];continue}let d=await Cs.readFile(l,"utf-8"),f=qh(d,a);s.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=Dt.join(t,".nex","index");await Cs.mkdir(i,{recursive:!0}),await Cs.writeFile(e,JSON.stringify(s),"utf-8")}return Ic=s,Ah=Date.now(),Oh=t,s}async function hS(t,e,n){let o=await ua(n),s=[],r=t.toLowerCase();for(let[i,a]of Object.entries(o.files))for(let l of a.defs)e&&l.type!==e||l.name.toLowerCase().includes(r)&&s.push({file:i,type:l.type,name:l.name,line:l.line});return s.sort((i,a)=>{let l=i.name.toLowerCase()===r?0:1,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}),s.slice(0,50)}function mS(t,e,n){if(!e||!e.startsWith("."))return null;let o=Dt.posix.dirname(t.replace(/\\/g,"/")),s=Dt.posix.normalize(Dt.posix.join(o==="."?"":o,e)),r=[];if(Dt.posix.extname(s))r.push(s);else for(let a of Dh)r.push(`${s}${a}`),r.push(Dt.posix.join(s,`index${a}`));for(let a of r)if(n.has(a))return a;return null}async function Fc(t){if(t=t||process.cwd(),ca&&Nh===t&&Date.now()-Ph<jh)return ca;let e=await ua(t),n=dr(),o=new Set(n.map(i=>i.replace(/\\/g,"/"))),s={},r={};for(let i of Object.keys(e.files||{})){let a=i.replace(/\\/g,"/"),l=Array.isArray(e.files[i]?.defs)?e.files[i].defs:[],c=[],u=new Set;for(let d of l){if(d.type!=="import")continue;let f=mS(a,d.name,o);!f||f===a||u.has(f)||(u.add(f),c.push(f),r[f]||(r[f]=[]),r[f].push(a))}s[a]=c}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return ca={importsByFile:s,importedByFile:r},Ph=Date.now(),Nh=t,ca}async function gS(t,e,n=6){if(!t)return[];let o=await Fc(e),s=String(t).replace(/\\/g,"/"),r=[...o.importsByFile[s]||[],...o.importedByFile[s]||[]];return[...new Set(r)].filter(i=>i!==s).slice(0,n)}async function yS(t,e=4){let n=await Fc(t),o=new Map;for(let[s,r]of Object.entries(n.importsByFile||{}))o.set(s,(o.get(s)||0)+r.length);for(let[s,r]of Object.entries(n.importedByFile||{}))o.set(s,(o.get(s)||0)+r.length);return[...o.entries()].filter(([,s])=>s>0).sort((s,r)=>r[1]-s[1]||s[0].localeCompare(r[0])).slice(0,e).map(([s,r])=>`${s} (${r} links)`)}function Fh(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bS(t,e){let n=Fh(e);return[new RegExp(`\\bfunction\\s+${n}\\b`),new RegExp(`\\bclass\\s+${n}\\b`),new RegExp(`\\b(?:const|let|var)\\s+${n}\\b\\s*=`),new RegExp(`\\bdef\\s+${n}\\b`),new RegExp(`\\btype\\s+${n}\\b\\s+struct\\b`),new RegExp(`\\bmodule\\.exports\\b[^\\n]*\\b${n}\\b`),new RegExp(`\\bexport\\b[^\\n]*\\b${n}\\b`)].some(s=>s.test(t))}async function wS(t,e,n={}){e=e||process.cwd();let{excludeFile:o=null,excludeLine:s=null,limit:r=6}=n;if(!t||typeof t!="string")return[];let i=await ua(e),a=Fh(t),l=new RegExp(`\\b${a}\\s*\\(`),c=new RegExp(`\\b${a}\\b`),u=[];for(let d of Object.keys(i.files||{})){let f=d.replace(/\\/g,"/");try{let h=Dt.join(e,f),g=(await Cs.readFile(h,"utf-8")).split(`
239
+ `);for(let _=0;_<g.length;_++){let k=g[_],$=_+1;if(!c.test(k)||o&&f===o&&s===$||bS(k,t))continue;let O=(f===o?0:4)+(l.test(k)?3:1);u.push({file:f,line:$,context:k.trim(),score:O})}}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)}Bh.exports={refreshIndex:Mh,getFileIndex:dr,getIndexedCwd:uS,findFileInIndex:dS,searchIndex:fS,isIndexValid:qc,buildContentIndex:ua,searchContentIndex:hS,extractDefinitions:qh,buildImportGraph:Fc,getRelatedFiles:gS,summarizeModuleHubs:yS,findSymbolReferences:wS,smartSearch:pS,scorePathMatch:Ih,pathLevenshtein:Lh}});var ko=J((xP,zh)=>{var da=require("fs"),ma=require("path"),ga=require("os"),{execFile:_S}=require("child_process"),{promisify:$S}=require("util"),Bc=$S(_S),kS=ma.join(ga.homedir(),".nex","servers.json"),fa=ma.join(ga.tmpdir(),"nex-ssh-sockets");function xS(){return ma.join(process.cwd(),".nex","servers.json")}function Uh(){let t=o=>{if(!da.existsSync(o))return{};try{return JSON.parse(da.readFileSync(o,"utf-8"))}catch{return{}}},e=t(kS),n=t(xS());return{...e,...n}}function SS(t){let e=Uh();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[s,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:s}}let n=Object.keys(e),o=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${o}`)}function vS(){da.existsSync(fa)||da.mkdirSync(fa,{recursive:!0})}function Wh(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,ga.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),vS();let n=t.user?`${t.user}@${t.host}`:t.host,o=ma.join(fa,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function Hh(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,ga.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function pa(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=Wh(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await Bc("ssh",[...s,r],{timeout:n,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:a,error:ya(l,t)}}}async function ES(t,e,n,{timeout:o=12e4}={}){let s=Hh(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:a}=await Bc("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(ya(a,t)||a)}}async function TS(t,e,n,{timeout:o=12e4}={}){let s=Hh(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:a}=await Bc("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(ya(a,t)||a)}}function ya(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
240
240
  HINT: Connection refused on ${e.host}:${n}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${n} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let n=e.key?`key: ${e.key}`:"SSH agent";return`${t}
241
241
  HINT: Auth failed using ${n} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
242
242
  HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
243
243
  HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
244
244
  HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
245
- HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function vS(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",s=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${o}${s}${r}${i}`}var pa=new Map,ES=12e4;async function Wh(t,e,{force:n=!1}={}){let s=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=pa.get(s);if(!n&&r&&Date.now()-r.time<ES)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 fa(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let c=e.endsWith("/")?e:e+"/",u=a.split(`
246
- `).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return pa.set(s,{files:u,time:Date.now()}),u}async function Hh(t,e,n,{limit:o=5,minScore:s=15}={}){let r=await Wh(t,e);if(r.length===0)return[];let{scorePathMatch:i}=Rn(),a=[];for(let l of r){let c=i(l,n);c>=s&&a.push({file:l,score:c})}return a.sort((l,c)=>c.score-l.score),a.slice(0,o)}async function TS(t,e,n){if(!n)return{fixedPath:null,message:""};let o=n.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await fa(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await fa(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let s=await Hh(t,e,n,{limit:5,minScore:15});if(s.length>0){let i=(e.endsWith("/")?e:e+"/")+s[0].file;if(s[0].score>=200||s.length===1&&s[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${s[0].file})`};if(s.length>=2&&s[0].score>=80&&s[0].score>=s[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${s[0].file})`};if(s.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
245
+ HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function RS(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",s=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${o}${s}${r}${i}`}var ha=new Map,CS=12e4;async function Gh(t,e,{force:n=!1}={}){let s=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=ha.get(s);if(!n&&r&&Date.now()-r.time<CS)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 pa(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let c=e.endsWith("/")?e:e+"/",u=a.split(`
246
+ `).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return ha.set(s,{files:u,time:Date.now()}),u}async function Yh(t,e,n,{limit:o=5,minScore:s=15}={}){let r=await Gh(t,e);if(r.length===0)return[];let{scorePathMatch:i}=Rn(),a=[];for(let l of r){let c=i(l,n);c>=s&&a.push({file:l,score:c})}return a.sort((l,c)=>c.score-l.score),a.slice(0,o)}async function AS(t,e,n){if(!n)return{fixedPath:null,message:""};let o=n.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await pa(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await pa(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let s=await Yh(t,e,n,{limit:5,minScore:15});if(s.length>0){let i=(e.endsWith("/")?e:e+"/")+s[0].file;if(s[0].score>=200||s.length===1&&s[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${s[0].file})`};if(s.length>=2&&s[0].score>=80&&s[0].score>=s[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${s[0].file})`};if(s.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
247
247
  ${s.map(a=>` - ${a.file}`).join(`
248
- `)}`}}return{fixedPath:null,message:""}}function RS(t){t?pa.delete(t):pa.clear()}Gh.exports={loadServerProfiles:Fh,resolveProfile:$S,buildSSHArgs:Bh,sshExec:fa,scpUpload:xS,scpDownload:SS,enrichSSHError:ga,formatProfile:vS,SSH_SOCKET_DIR:da,getRemoteIndex:Wh,remoteSmartSearch:Hh,remoteAutoFixPath:TS,clearRemoteIndex:RS}});var Kh=J((_P,zh)=>{var dr=require("fs"),Fc=require("path"),CS=Fc.join(".nex","deploy.json");function Bc(){return Fc.join(process.cwd(),CS)}function Yh(){let t=Bc();if(!dr.existsSync(t))return{};try{return JSON.parse(dr.readFileSync(t,"utf-8"))}catch{return{}}}function AS(t){let e=Yh();if(e[t])return{...e[t],_name:t};let n=Object.keys(e),o=n.length?`Available: ${n.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${o}`)}function OS(t){let e=Fc.join(process.cwd(),".nex");dr.existsSync(e)||dr.mkdirSync(e,{recursive:!0}),dr.writeFileSync(Bc(),JSON.stringify(t,null,2)+`
249
- `,"utf-8")}zh.exports={loadDeployConfigs:Yh,resolveDeployConfig:AS,saveDeployConfigs:OS,getDeployConfigPath:Bc}});var mr=J(($P,Jh)=>{var{getActiveModel:PS,getActiveProviderName:NS}=$t(),fr={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},pr={"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"},hr={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Cn={};function Xh(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(Cn=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{Cn={}}}Xh();function Uc(){let e=PS()?.id,n=NS();return e&&Cn[e]?Cn[e]:n&&Cn[`${n}:*`]?Cn[`${n}:*`]:e&&pr[e]?pr[e]:n&&hr[n]?hr[n]:"full"}var MS=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"]),Vh={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function LS(t,e){return t&&(MS.has(t)||t.startsWith("claude-"))?"strict":e&&Vh[e]?Vh[e]:"fuzzy"}function IS(t,e){return t&&Cn[t]?Cn[t]:e&&Cn[`${e}:*`]?Cn[`${e}:*`]:t&&pr[t]?pr[t]:e&&hr[e]?hr[e]:"full"}function jS(t,e){let n=e||Uc();if(n==="full"||!fr[n])return t;let o=new Set(fr[n]);return t.filter(s=>o.has(s.function.name))}function DS(){let t=Uc(),e=fr[t]?fr[t].length:"all";return{tier:t,toolCount:e}}Jh.exports={filterToolsForModel:jS,getActiveTier:Uc,getModelTier:IS,getEditMode:LS,getTierInfo:DS,TIERS:fr,MODEL_TIERS:pr,PROVIDER_DEFAULT_TIER:hr,loadConfigOverrides:Xh}});var Wn=J((kP,tm)=>{var Wc=null,Un=null,gr=null,Hc=Symbol.for("nex-code.browserExitCleanup"),Zh=`Playwright is not installed. Install with:
248
+ `)}`}}return{fixedPath:null,message:""}}function OS(t){t?ha.delete(t):ha.clear()}zh.exports={loadServerProfiles:Uh,resolveProfile:SS,buildSSHArgs:Wh,sshExec:pa,scpUpload:ES,scpDownload:TS,enrichSSHError:ya,formatProfile:RS,SSH_SOCKET_DIR:fa,getRemoteIndex:Gh,remoteSmartSearch:Yh,remoteAutoFixPath:AS,clearRemoteIndex:OS}});var Xh=J((SP,Vh)=>{var fr=require("fs"),Uc=require("path"),PS=Uc.join(".nex","deploy.json");function Wc(){return Uc.join(process.cwd(),PS)}function Kh(){let t=Wc();if(!fr.existsSync(t))return{};try{return JSON.parse(fr.readFileSync(t,"utf-8"))}catch{return{}}}function NS(t){let e=Kh();if(e[t])return{...e[t],_name:t};let n=Object.keys(e),o=n.length?`Available: ${n.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${o}`)}function MS(t){let e=Uc.join(process.cwd(),".nex");fr.existsSync(e)||fr.mkdirSync(e,{recursive:!0}),fr.writeFileSync(Wc(),JSON.stringify(t,null,2)+`
249
+ `,"utf-8")}Vh.exports={loadDeployConfigs:Kh,resolveDeployConfig:NS,saveDeployConfigs:MS,getDeployConfigPath:Wc}});var gr=J((vP,Qh)=>{var{getActiveModel:LS,getActiveProviderName:IS}=kt(),pr={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},hr={"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"},mr={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Cn={};function Zh(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(Cn=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{Cn={}}}Zh();function Hc(){let e=LS()?.id,n=IS();return e&&Cn[e]?Cn[e]:n&&Cn[`${n}:*`]?Cn[`${n}:*`]:e&&hr[e]?hr[e]:n&&mr[n]?mr[n]:"full"}var jS=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"]),Jh={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function DS(t,e){return t&&(jS.has(t)||t.startsWith("claude-"))?"strict":e&&Jh[e]?Jh[e]:"fuzzy"}function qS(t,e){return t&&Cn[t]?Cn[t]:e&&Cn[`${e}:*`]?Cn[`${e}:*`]:t&&hr[t]?hr[t]:e&&mr[e]?mr[e]:"full"}function FS(t,e){let n=e||Hc();if(n==="full"||!pr[n])return t;let o=new Set(pr[n]);return t.filter(s=>o.has(s.function.name))}function BS(){let t=Hc(),e=pr[t]?pr[t].length:"all";return{tier:t,toolCount:e}}Qh.exports={filterToolsForModel:FS,getActiveTier:Hc,getModelTier:qS,getEditMode:DS,getTierInfo:BS,TIERS:pr,MODEL_TIERS:hr,PROVIDER_DEFAULT_TIER:mr,loadConfigOverrides:Zh}});var Wn=J((EP,sm)=>{var Gc=null,Un=null,yr=null,Yc=Symbol.for("nex-code.browserExitCleanup"),em=`Playwright is not installed. Install with:
250
250
  npm install playwright && npx playwright install chromium
251
- Then restart nex-code.`;function Qh(){if(gr!==null)return gr;try{require("playwright"),gr=!0}catch{gr=!1}return gr}async function ya(){if(!Qh())throw new Error(Zh);return Wc||(Wc=require("playwright")),(!Un||!Un.isConnected())&&(Un=await Wc.chromium.launch({headless:!0})),Un}async function qS(){if(Un){try{await Un.close()}catch(t){console.error("closeBrowser failed:",t.message)}Un=null}}globalThis[Hc]&&process.off("exit",globalThis[Hc]);var em=()=>{if(Un)try{Un.close()}catch(t){console.error("Error closing browser on exit:",t.message)}};globalThis[Hc]=em;process.on("exit",em);async function FS(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await ya()).newPage();try{await s.goto(t,{waitUntil:n,timeout:e});let r=await s.title(),i=await s.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(c=>c.remove()),document.body?.innerText||"")),a=await s.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:s.url(),text:i.substring(0,8e3)+(i.length>8e3?`
252
- ...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function BS(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await ya()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:s});let a=await i.screenshot({type:"png",fullPage:o}),l=require("os"),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 US(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await ya()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function WS(t,{selector:e,value:n,submit:o=!1,timeout:s=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await ya()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:s}),await i.fill(e,String(n)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}tm.exports={isPlaywrightAvailable:Qh,browserNavigate:FS,browserScreenshot:BS,browserClick:US,browserFill:WS,closeBrowser:qS,INSTALL_MSG:Zh}});var Gc=J((xP,sm)=>{"use strict";var HS=require("util"),nm=require("stream"),hn=sm.exports=function(){nm.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};HS.inherits(hn,nm);hn.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))};hn.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};hn.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()))};hn.prototype.destroySoon=hn.prototype.end;hn.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};hn.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};hn.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))};hn.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,o=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],r=Math.min(s.length,t.length-e);s.copy(o,e,0,r),e+=r,r!==s.length&&(this._buffers[--n]=s.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,o)};hn.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 zc=J(Yc=>{"use strict";var ss=[{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]}];Yc.getImagePasses=function(t,e){let n=[],o=t%8,s=e%8,r=(t-o)/8,i=(e-s)/8;for(let a=0;a<ss.length;a++){let l=ss[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]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};Yc.getInterlaceIterator=function(t){return function(e,n,o){let s=e%ss[o].x.length,r=(e-s)/ss[o].x.length*8+ss[o].x[s],i=n%ss[o].y.length,a=(n-i)/ss[o].y.length*8+ss[o].y[i];return r*4+a*t*4}}});var Kc=J((vP,om)=>{"use strict";om.exports=function(e,n,o){let s=e+n-o,r=Math.abs(s-e),i=Math.abs(s-n),a=Math.abs(s-o);return r<=i&&r<=a?e:i<=a?n:o}});var Vc=J((EP,im)=>{"use strict";var GS=zc(),YS=Kc();function rm(t,e,n){let o=t*e;return n!==8&&(o=Math.ceil(o/(8/n))),o}var ko=im.exports=function(t,e){let n=t.width,o=t.height,s=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=GS.getImagePasses(n,o);for(let l=0;l<a.length;l++)this._images.push({byteWidth:rm(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:rm(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};ko.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ko.prototype._unFilterType1=function(t,e,n){let o=this._xComparison,s=o-1;for(let r=0;r<n;r++){let i=t[1+r],a=r>s?e[r-o]:0;e[r]=i+a}};ko.prototype._unFilterType2=function(t,e,n){let o=this._lastLine;for(let s=0;s<n;s++){let r=t[1+s],i=o?o[s]:0;e[s]=r+i}};ko.prototype._unFilterType3=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],l=r?r[i]:0,c=i>s?e[i-o]:0,u=Math.floor((c+l)/2);e[i]=a+u}};ko.prototype._unFilterType4=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],l=r?r[i]:0,c=i>s?e[i-o]:0,u=i>s&&r?r[i-o]:0,d=YS(c,l,u);e[i]=a+d}};ko.prototype._reverseFilterLine=function(t){let e=t[0],n,o=this._images[this._imageIndex],s=o.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),o.lineIndex++,o.lineIndex>=o.height?(this._lastLine=null,this._imageIndex++,o=this._images[this._imageIndex]):this._lastLine=n,o?this.read(o.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var cm=J((TP,lm)=>{"use strict";var zS=require("util"),am=Gc(),KS=Vc(),VS=lm.exports=function(t){am.call(this);let e=[],n=this;this._filter=new KS(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};zS.inherits(VS,am)});var xo=J((RP,um)=>{"use strict";um.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 Zc=J((CP,dm)=>{"use strict";var Xc=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;Xc[t]=e}})();var Jc=dm.exports=function(){this._crc=-1};Jc.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Xc[(this._crc^t[e])&255]^this._crc>>>8;return!0};Jc.prototype.crc32=function(){return this._crc^-1};Jc.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Xc[(e^t[n])&255]^e>>>8;return e^-1}});var Qc=J((AP,fm)=>{"use strict";var yt=xo(),XS=Zc(),wt=fm.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[yt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[yt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[yt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[yt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[yt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[yt.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(){}};wt.prototype.start=function(){this.read(yt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};wt.prototype._parseSignature=function(t){let e=yt.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};wt.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o="";for(let r=4;r<8;r++)o+=String.fromCharCode(t[r]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==yt.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new XS,this._crc.write(Buffer.from(o)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+o));return}this.read(e+4,this._skipChunk.bind(this))};wt.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};wt.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};wt.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};wt.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};wt.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o=t[8],s=t[9],r=t[10],i=t[11],a=t[12];if(o!==8&&o!==4&&o!==2&&o!==1&&o!==16){this.error(new Error("Unsupported bit depth "+o));return}if(!(s in yt.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=yt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:o,interlace:!!a,palette:!!(s&yt.COLORTYPE_PALETTE),color:!!(s&yt.COLORTYPE_COLOR),alpha:!!(s&yt.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};wt.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};wt.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};wt.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};wt.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===yt.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===yt.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===yt.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};wt.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};wt.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/yt.GAMMA_DIVISION),this._handleChunkEnd()};wt.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};wt.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===yt.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};wt.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};wt.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var eu=J(hm=>{"use strict";var pm=zc(),JS=[function(){},function(t,e,n,o){if(o===e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,o){if(o+1>=e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[o+1]},function(t,e,n,o){if(o+2>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=255},function(t,e,n,o){if(o+3>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=e[o+3]}],ZS=[function(){},function(t,e,n,o){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=o},function(t,e,n){let o=e[0];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=e[1]},function(t,e,n,o){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=o},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function QS(t,e){let n=[],o=0;function s(){if(o===t.length)throw new Error("Ran out of data");let r=t[o];o++;let i,a,l,c,u,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[o],o++,n.push((r<<8)+f);break;case 4:f=r&15,h=r>>4,n.push(h,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,h=r>>6&3,n.push(h,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,h=r>>7&1,n.push(h,f,d,u,c,l,a,i);break}}return{get:function(r){for(;n.length<r;)s();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(o!==t.length)throw new Error("extra data found")}}}function ev(t,e,n,o,s,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(u,c,l);JS[o](e,s,d,r),r+=o}return r}function tv(t,e,n,o,s,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.get(o),f=n(u,c,l);ZS[o](e,d,f,r)}s.resetAfterLine()}}hm.dataToBitMap=function(t,e){let n=e.width,o=e.height,s=e.depth,r=e.bpp,i=e.interlace,a;s!==8&&(a=QS(t,s));let l;s<=8?l=Buffer.alloc(n*o*4):l=new Uint16Array(n*o*4);let c=Math.pow(2,s)-1,u=0,d,f;if(i)d=pm.getImagePasses(n,o),f=pm.getInterlaceIterator(n,o);else{let h=0;f=function(){let m=h;return h+=4,m},d=[{width:n,height:o}]}for(let h=0;h<d.length;h++)s===8?u=ev(d[h],l,f,r,t,u):tv(d[h],l,f,r,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var tu=J((PP,mm)=>{"use strict";function nv(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let l=s[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let c=0;c<4;c++)e[r+c]=l[c];r+=4}}function sv(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[r]&&(l=!0):s[0]===t[r]&&s[1]===t[r+1]&&s[2]===t[r+2]&&(l=!0),l)for(let c=0;c<4;c++)e[r+c]=0;r+=4}}function ov(t,e,n,o,s){let r=255,i=Math.pow(2,s)-1,a=0;for(let l=0;l<o;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}mm.exports=function(t,e,n=!1){let o=e.depth,s=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,c=t;return i===3?nv(t,c,s,r,l):(a&&sv(t,c,s,r,a),o!==8&&!n&&(o===16&&(c=Buffer.alloc(s*r*4)),ov(t,c,s,r,o))),c}});var bm=J((NP,ym)=>{"use strict";var rv=require("util"),nu=require("zlib"),gm=Gc(),iv=cm(),av=Qc(),lv=eu(),cv=tu(),An=ym.exports=function(t){gm.call(this),this._parser=new av(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()};rv.inherits(An,gm);An.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};An.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=nu.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,o=Math.max(n,nu.Z_MIN_CHUNK);this._inflate=nu.createInflate({chunkSize:o});let s=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};An.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new iv(this._bitmapInfo)};An.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};An.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};An.prototype._simpleTransparency=function(){this._metaData.alpha=!0};An.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};An.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};An.prototype._complete=function(t){if(this.errord)return;let e;try{let n=lv.dataToBitMap(t,this._bitmapInfo);e=cv(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var _m=J((MP,wm)=>{"use strict";var tn=xo();wm.exports=function(t,e,n,o){let s=[tn.COLORTYPE_COLOR_ALPHA,tn.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=tn.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let l=tn.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=o.bgColor||{};f.red===void 0&&(f.red=i),f.green===void 0&&(f.green=i),f.blue===void 0&&(f.blue=i);function h(){let m,g,_,k=i;switch(o.inputColorType){case tn.COLORTYPE_COLOR_ALPHA:k=r[u+3],m=r[u],g=r[u+1],_=r[u+2];break;case tn.COLORTYPE_COLOR:m=r[u],g=r[u+1],_=r[u+2];break;case tn.COLORTYPE_ALPHA:k=r[u+1],m=r[u],g=m,_=m;break;case tn.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&&(s||(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<n;m++)for(let g=0;g<e;g++){let _=h(r,u);switch(o.colorType){case tn.COLORTYPE_COLOR_ALPHA:case tn.COLORTYPE_COLOR:o.bitDepth===8?(c[d]=_.red,c[d+1]=_.green,c[d+2]=_.blue,s&&(c[d+3]=_.alpha)):(c.writeUInt16BE(_.red,d),c.writeUInt16BE(_.green,d+2),c.writeUInt16BE(_.blue,d+4),s&&c.writeUInt16BE(_.alpha,d+6));break;case tn.COLORTYPE_ALPHA:case tn.COLORTYPE_GRAYSCALE:{let k=(_.red+_.green+_.blue)/3;o.bitDepth===8?(c[d]=k,s&&(c[d+1]=_.alpha)):(c.writeUInt16BE(k,d),s&&c.writeUInt16BE(_.alpha,d+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}u+=a,d+=l}return c}});var xm=J((LP,km)=>{"use strict";var $m=Kc();function uv(t,e,n,o,s){for(let r=0;r<n;r++)o[s+r]=t[e+r]}function dv(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++)o+=Math.abs(t[r]);return o}function fv(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;o[s+i]=l}}function pv(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=t[e+r]-i;s+=Math.abs(a)}return s}function hv(t,e,n,o,s){for(let r=0;r<n;r++){let i=e>0?t[e+r-n]:0,a=t[e+r]-i;o[s+r]=a}}function mv(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++){let i=e>0?t[r-n]:0,a=t[r]-i;o+=Math.abs(a)}return o}function gv(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-n]:0,c=t[e+i]-(a+l>>1);o[s+i]=c}}function yv(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,l=t[e+r]-(i+a>>1);s+=Math.abs(l)}return s}function bv(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-n]:0,c=e>0&&i>=r?t[e+i-(n+r)]:0,u=t[e+i]-$m(a,l,c);o[s+i]=u}}function wv(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,l=e>0&&r>=o?t[e+r-(n+o)]:0,c=t[e+r]-$m(i,a,l);s+=Math.abs(c)}return s}var _v={0:uv,1:fv,2:hv,3:gv,4:bv},$v={0:dv,1:pv,2:mv,3:yv,4:wv};km.exports=function(t,e,n,o,s){let r;if(!("filterType"in o)||o.filterType===-1)r=[0,1,2,3,4];else if(typeof o.filterType=="number")r=[o.filterType];else throw new Error("unrecognised filter types");o.bitDepth===16&&(s*=2);let i=e*s,a=0,l=0,c=Buffer.alloc((i+1)*n),u=r[0];for(let d=0;d<n;d++){if(r.length>1){let f=1/0;for(let h=0;h<r.length;h++){let m=$v[r[h]](t,l,i,s);m<f&&(u=r[h],f=m)}}c[a]=u,a++,_v[u](t,l,i,c,a,s),a+=i,l+=i}return c}});var su=J((IP,Sm)=>{"use strict";var Rt=xo(),kv=Zc(),xv=_m(),Sv=xm(),vv=require("zlib"),os=Sm.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||vv.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:Rt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:Rt.COLORTYPE_COLOR_ALPHA,[Rt.COLORTYPE_GRAYSCALE,Rt.COLORTYPE_COLOR,Rt.COLORTYPE_COLOR_ALPHA,Rt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([Rt.COLORTYPE_GRAYSCALE,Rt.COLORTYPE_COLOR,Rt.COLORTYPE_COLOR_ALPHA,Rt.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};os.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};os.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};os.prototype.filterData=function(t,e,n){let o=xv(t,e,n,this._options),s=Rt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Sv(o,e,n,this._options,s)};os.prototype._packChunk=function(t,e){let n=e?e.length:0,o=Buffer.alloc(n+12);return o.writeUInt32BE(n,0),o.writeUInt32BE(t,4),e&&e.copy(o,8),o.writeInt32BE(kv.crc32(o.slice(4,o.length-4)),o.length-4),o};os.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Rt.GAMMA_DIVISION),0),this._packChunk(Rt.TYPE_gAMA,e)};os.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(Rt.TYPE_IHDR,n)};os.prototype.packIDAT=function(t){return this._packChunk(Rt.TYPE_IDAT,t)};os.prototype.packIEND=function(){return this._packChunk(Rt.TYPE_IEND,null)}});var Rm=J((jP,Tm)=>{"use strict";var Ev=require("util"),vm=require("stream"),Tv=xo(),Rv=su(),Em=Tm.exports=function(t){vm.call(this);let e=t||{};this._packer=new Rv(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Ev.inherits(Em,vm);Em.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(Tv.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),o&&this.emit("data",this._packer.packGAMA(o));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var Mm=J((yr,Nm)=>{"use strict";var Cm=require("assert").ok,So=require("zlib"),Cv=require("util"),Am=require("buffer").kMaxLength;function Cs(t){if(!(this instanceof Cs))return new Cs(t);t&&t.chunkSize<So.Z_MIN_CHUNK&&(t.chunkSize=So.Z_MIN_CHUNK),So.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 Av(t){return new Cs(t)}function Om(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Cs.prototype._processChunk=function(t,e,n){if(typeof n=="function")return So.Inflate._processChunk.call(this,t,e,n);let o=this,s=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(m){u=m});function d(m,g){if(o._hadError)return;let _=r-g;if(Cm(_>=0,"have should not go down"),_>0){let k=o._buffer.slice(o._offset,o._offset+_);if(o._offset+=_,k.length>i&&(k=k.slice(0,i)),l.push(k),c+=k.length,i-=k.length,i===0)return!1}return(g===0||o._offset>=o._chunkSize)&&(r=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),g===0?(a+=s-m,s=m,!0):!1}Cm(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=Am)throw Om(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Am.toString(16)+" bytes");let h=Buffer.concat(l,c);return Om(this),h};Cv.inherits(Cs,So.Inflate);function Ov(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=So.Z_FINISH),t._processChunk(e,n)}function Pm(t,e){return Ov(new Cs(e),t)}Nm.exports=yr=Pm;yr.Inflate=Cs;yr.createInflate=Av;yr.inflateSync=Pm});var ou=J((DP,Im)=>{"use strict";var Lm=Im.exports=function(t){this._buffer=t,this._reads=[]};Lm.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Lm.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 Dm=J(jm=>{"use strict";var Pv=ou(),Nv=Vc();jm.process=function(t,e){let n=[],o=new Pv(t);return new Nv(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var Um=J((FP,Bm)=>{"use strict";var qm=!0,Fm=require("zlib"),Mv=Mm();Fm.deflateSync||(qm=!1);var Lv=ou(),Iv=Dm(),jv=Qc(),Dv=eu(),qv=tu();Bm.exports=function(t,e){if(!qm)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function o(E){n=E}let s;function r(E){s=E}function i(E){s.transColor=E}function a(E){s.palette=E}function l(){s.alpha=!0}let c;function u(E){c=E}let d=[];function f(E){d.push(E)}let h=new Lv(t);if(new jv(e,{read:h.read.bind(h),error:o,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let g=Buffer.concat(d);d.length=0;let _;if(s.interlace)_=Fm.inflateSync(g);else{let T=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;_=Mv(g,{chunkSize:T,maxLength:T})}if(g=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let k=Iv.process(_,s);g=null;let $=Dv.dataToBitMap(k,s);k=null;let O=qv($,s,e.skipRescale);return s.data=O,s.gamma=c||0,s}});var Ym=J((BP,Gm)=>{"use strict";var Wm=!0,Hm=require("zlib");Hm.deflateSync||(Wm=!1);var Fv=xo(),Bv=su();Gm.exports=function(t,e){if(!Wm)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},o=new Bv(n),s=[];s.push(Buffer.from(Fv.PNG_SIGNATURE)),s.push(o.packIHDR(t.width,t.height)),t.gamma&&s.push(o.packGAMA(t.gamma));let r=o.filterData(t.data,t.width,t.height),i=Hm.deflateSync(r,o.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return s.push(o.packIDAT(i)),s.push(o.packIEND()),Buffer.concat(s)}});var zm=J(ru=>{"use strict";var Uv=Um(),Wv=Ym();ru.read=function(t,e){return Uv(t,e||{})};ru.write=function(t,e){return Wv(t,e)}});var Xm=J(Vm=>{"use strict";var Hv=require("util"),Km=require("stream"),Gv=bm(),Yv=Rm(),zv=zm(),At=Vm.PNG=function(t){Km.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 Gv(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 Yv(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"))};Hv.inherits(At,Km);At.sync=zv;At.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)};At.prototype.parse=function(t,e){if(e){let n,o;n=function(s){this.removeListener("error",o),this.data=s,e(null,this)}.bind(this),o=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",o)}return this.end(t),this};At.prototype.write=function(t){return this._parser.write(t),!0};At.prototype.end=function(t){this._parser.end(t)};At.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};At.prototype._gamma=function(t){this.gamma=t};At.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};At.bitblt=function(t,e,n,o,s,r,i,a){if(n|=0,o|=0,s|=0,r|=0,i|=0,a|=0,n>t.width||o>t.height||n+s>t.width||o+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+s>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<r;l++)t.data.copy(e.data,(a+l)*e.width+i<<2,(o+l)*t.width+n<<2,(o+l)*t.width+n+s<<2)};At.prototype.bitblt=function(t,e,n,o,s,r,i){return At.bitblt(this,t,e,n,o,s,r,i),this};At.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let o=t.width*e+n<<2;for(let s=0;s<3;s++){let r=t.data[o+s]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[o+s]=Math.round(r*255)}}t.gamma=0}};At.prototype.adjustGamma=function(){At.adjustGamma(this)}});var tg={};V0(tg,{default:()=>Qm});function Qm(t,e,n,o,s,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(!iu(t)||!iu(e)||n&&!iu(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||n&&n.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==o*s*4)throw new Error("Image data size does not match width/height.");let h=o*s,m=new Uint32Array(t.buffer,t.byteOffset,h),g=new Uint32Array(e.buffer,e.byteOffset,h),_=!0;for(let ie=0;ie<h;ie++)if(m[ie]!==g[ie]){_=!1;break}if(_){if(n&&!f)for(let ie=0;ie<h;ie++)Zm(t,4*ie,a,n);return 0}let k=35215*i*i,[$,O,E]=l,[T,q,ee]=c,[te,K,ae]=d||c,se=0;for(let ie=0;ie<s;ie++)for(let Be=0;Be<o;Be++){let Re=ie*o+Be,W=Re*4,ne=m[Re]===g[Re]?0:eg(t,e,W,W,!1);if(Math.abs(ne)>k){let Ke=Jm(t,Be,ie,o,s,m,g)||Jm(e,Be,ie,o,s,g,m);!u&&Ke?n&&!f&&wa(n,W,$,O,E):(n&&(ne<0?wa(n,W,te,K,ae):wa(n,W,T,q,ee)),se++)}else n&&!f&&Zm(t,W,a,n)}return se}function iu(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Jm(t,e,n,o,s,r,i){let a=Math.max(e-1,0),l=Math.max(n-1,0),c=Math.min(e+1,o-1),u=Math.min(n+1,s-1),d=n*o+e,f=e===a||e===c||n===l||n===u?1:0,h=0,m=0,g=0,_=0,k=0,$=0;for(let O=a;O<=c;O++)for(let E=l;E<=u;E++){if(O===e&&E===n)continue;let T=eg(t,t,d*4,(E*o+O)*4,!0);if(T===0){if(f++,f>2)return!1}else T<h?(h=T,g=O,_=E):T>m&&(m=T,k=O,$=E)}return h===0||m===0?!1:ba(r,g,_,o,s)&&ba(i,g,_,o,s)||ba(r,k,$,o,s)&&ba(i,k,$,o,s)}function ba(t,e,n,o,s){let r=Math.max(e-1,0),i=Math.max(n-1,0),a=Math.min(e+1,o-1),l=Math.min(n+1,s-1),c=t[n*o+e],u=e===r||e===a||n===i||n===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===n)&&(u+=+(c===t[f*o+d]),u>2))return!0;return!1}function eg(t,e,n,o,s){let r=t[n],i=t[n+1],a=t[n+2],l=t[n+3],c=e[o],u=e[o+1],d=e[o+2],f=e[o+3],h=r-c,m=i-u,g=a-d,_=l-f;if(!h&&!m&&!g&&!_)return 0;if(l<255||f<255){let T=48+159*(n%2),q=48+159*((n/1.618033988749895|0)%2),ee=48+159*((n/2.618033988749895|0)%2);h=(r*l-c*f-T*_)/255,m=(i*l-u*f-q*_)/255,g=(a*l-d*f-ee*_)/255}let k=h*.29889531+m*.58662247+g*.11448223;if(s)return k;let $=h*.59597799-m*.2741761-g*.32180189,O=h*.21147017-m*.52261711+g*.31114694,E=.5053*k*k+.299*$*$+.1957*O*O;return k>0?-E:E}function wa(t,e,n,o,s){t[e+0]=n,t[e+1]=o,t[e+2]=s,t[e+3]=255}function Zm(t,e,n,o){let s=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;wa(o,e,s,s,s)}var ng=K0(()=>{});var As=J((HP,ag)=>{var Hn=require("fs"),Kv=require("path"),Vv=require("os"),Xv="nex-visual-";function og(t){return Kv.join(Vv.tmpdir(),`${Xv}${Date.now()}-${t}`)}var au=null;function _a(){return au||(au=Xm().PNG),au}var lu=null;function Jv(){if(!lu){let t=(ng(),J0(tg));lu=t.default||t}return lu}function du(t,e,{threshold:n=.1}={}){let o=_a(),s=Jv(),r=o.sync.read(Hn.readFileSync(t)),i=o.sync.read(Hn.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=sg(r,a,l),u=sg(i,a,l),d=new o({width:a,height:l}),f=s(c,u,d.data,a,l,{threshold:n,includeAA:!1}),h=a*l,m=(f/h*100).toFixed(1),g=Zv(d.data,a,l,3,3),_=og("diff.png");return Hn.writeFileSync(_,o.sync.write(d),{mode:384}),{diffPath:_,diffPercent:parseFloat(m),totalPixels:h,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function sg(t,e,n){if(t.width===e&&t.height===n)return t.data;let o=Buffer.alloc(e*n*4,0);for(let s=0;s<t.height;s++){let r=s*t.width*4,i=s*e*4;t.data.copy(o,i,r,r+t.width*4)}return o}function Zv(t,e,n,o,s){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/o),a=Math.ceil(n/s),l=[];for(let c=0;c<s;c++)for(let u=0;u<o;u++){let d=0,f=0,h=u*i,m=c*a,g=Math.min(h+i,e),_=Math.min(m+a,n);for(let k=m;k<_;k++)for(let $=h;$<g;$++){f++;let O=(k*e+$)*4;(t[O]>0||t[O+1]>0)&&d++}if(d>0){let k=(d/f*100).toFixed(1),$=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:$,changedPercent:parseFloat(k),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var rg=[{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 Qv(t,{viewports:e=rg,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=Wn(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:n,fullPage:o,timeout:s});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function ig(t,e=[]){let n=_a(),o=n.sync.read(Hn.readFileSync(t));for(let i of e){let a=eE(i.color||"#FF0000");i.type==="box"?(tE(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&uu(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(nE(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&uu(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(sE(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&uu(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=og("annotated.png");Hn.writeFileSync(s,n.sync.write(o),{mode:384});let r=Hn.readFileSync(s).toString("base64");return{path:s,base64:r,media_type:"image/png"}}function eE(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 On(t,e,n,o){if(e<0||n<0||e>=t.width||n>=t.height)return;let s=(n*t.width+e)*4;t.data[s]=o.r,t.data[s+1]=o.g,t.data[s+2]=o.b,t.data[s+3]=o.a}function tE(t,e,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<o;l++)On(t,e+l,n+a,r),On(t,e+l,n+s-1-a,r);for(let l=0;l<s;l++)On(t,e+a,n+l,r),On(t,e+o-1-a,n+l,r)}}function cu(t,e,n,o,s,r,i=3){let a=Math.abs(o-e),l=Math.abs(s-n),c=e<o?1:-1,u=n<s?1:-1,d=a-l,f=e,h=n;for(;;){let m=Math.floor(i/2);for(let _=-m;_<=m;_++)for(let k=-m;k<=m;k++)On(t,f+_,h+k,r);if(f===o&&h===s)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,h+=u)}}function nE(t,e,n,o,s,r,i=3){cu(t,e,n,o,s,r,i);let a=Math.atan2(s-n,o-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;cu(t,o,s,Math.round(o+l*Math.cos(c)),Math.round(s+l*Math.sin(c)),r,i),cu(t,o,s,Math.round(o+l*Math.cos(u)),Math.round(s+l*Math.sin(u)),r,i)}function sE(t,e,n,o,s,r=3){for(let i=0;i<r;i++){let a=o-i;for(let l=0;l<360;l+=.5){let c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(n+a*Math.sin(c));On(t,u,d,s)}}}function uu(t,e,n,o,s){let i=o.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)On(t,e+c,n+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)On(t,e+l,n+a-1,s),On(t,e+l,n+a-2,s);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++)On(t,c+d,n+u,s)}}async function*oE(t,e,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=Wn(),l=rE("chokidar"),c=await a(t,{width:s,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<n;){await aE(()=>d,3e5),d=!1,u++,await iE(o);let h=await a(t,{width:s,height:r,timeout:i}),m=null;try{m=du(c.path,h.path)}catch{}c=h,yield{iteration:u,type:"change",path:h.path,base64:h.base64,media_type:h.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function rE(t){try{return require(t)}catch{return null}}function iE(t){return new Promise(e=>setTimeout(e,t))}function aE(t,e=6e4){return new Promise((n,o)=>{let s=setInterval(()=>{t()&&(clearInterval(s),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(s),o(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function lE(t,{sampleRate:e=4}={}){let o=_a().sync.read(Hn.readFileSync(t)),s=new Map;for(let c=0;c<o.height;c+=e)for(let u=0;u<o.width;u+=e){let d=(c*o.width+u)*4,f=o.data[d],h=o.data[d+1],m=o.data[d+2];if(o.data[d+3]<128)continue;let _=Math.round(f/8)*8,k=Math.round(h/8)*8,$=Math.round(m/8)*8,O=`${_},${k},${$}`;s.set(O,(s.get(O)||0)+1)}let r=[...s.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,h]=c.split(",").map(Number);return{hex:cE(d,f,h),rgb:`rgb(${d}, ${f}, ${h})`,frequency:parseFloat((u/i*100).toFixed(1)),category:uE(d,f,h)}}),l=dE(o);return{colors:a,spacing:l,dimensions:{width:o.width,height:o.height},imagePath:t}}function cE(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function uE(t,e,n){let o=(t*299+e*587+n*114)/1e3;return o>240?"white/background":o<30?"black/text":o<80?"dark":t>200&&e<100&&n<100?"red/danger":t<100&&e>150&&n<100?"green/success":t<100&&e<100&&n>200?"blue/primary":t>200&&e>200&&n<100?"yellow/warning":t>200&&e>100&&n<50?"orange/accent":o>200?"light/subtle":"midtone"}function dE(t){let e=[],n=!1,o=0,s=fE(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]-s.r)>20||Math.abs(t.data[c+1]-s.g)>20||Math.abs(t.data[c+2]-s.b)>20){a=!1;break}}if(a&&n)n=!1,o=i;else if(!a&&!n&&(n=!0,o>0)){let l=i-o;l>=4&&l<=200&&e.push(l)}}let r=new Map;for(let i of e){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function fE(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],n=0,o=0,s=0;for(let[r,i]of e){let a=(i*t.width+r)*4;n+=t.data[a],o+=t.data[a+1],s+=t.data[a+2]}return{r:Math.round(n/4),g:Math.round(o/4),b:Math.round(s/4)}}async function pE(t,e,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=Wn(),c=_a().sync.read(Hn.readFileSync(e)),u=n||c.width,d=o||c.height,f=await a(t,{width:u,height:d,fullPage:s,timeout:i}),h=du(e,f.path,{threshold:r}),m=ig(f.path,h.regionSummary.filter(g=>g.changedPercent>1).map((g,_)=>{let O=Math.ceil(h.width/3),E=Math.ceil(h.height/3),T=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],q=0,ee=0;for(let te=0;te<3;te++)for(let K=0;K<3;K++)T[te][K]===g.name&&(q=K,ee=te);return{type:"box",x:q*O+2,y:ee*E+2,width:O-4,height:E-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:h.diffPath,annotatedPath:m.path,diffPercent:h.diffPercent,changedPixels:h.changedPixels,totalPixels:h.totalPixels,regions:h.regionSummary,liveBase64:f.base64,diffBase64:Hn.readFileSync(h.diffPath).toString("base64"),annotatedBase64:m.base64}}ag.exports={pixelDiff:du,responsiveSweep:Qv,annotateImage:ig,visualWatch:oE,extractDesignTokens:lE,designCompare:pE,DEFAULT_VIEWPORTS:rg}});var fu=J((GP,lg)=>{var{C:Qe}=_t(),wr="",Ot=[],br=0,Os=null;function hE(t){Os=t}function mE(t,e){wr=t,Ot=[],br=0;for(let o of e){br++;let s=`t${br}`;Ot.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${br}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=Ot.map(o=>({...o}));return Os&&Os("create",{name:t,tasks:n}),n}function gE(t,e,n){let o=Ot.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),Os&&Os("update",{id:t,status:e,result:n}),{...o}):null}function yE(){return{name:wr,tasks:Ot.map(t=>({...t}))}}function bE(){wr="",Ot=[],br=0,Os&&Os("clear",{})}function wE(){return Ot.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=Ot.find(o=>o.id===e);return n&&n.status==="done"}))}function _E(){if(Ot.length===0)return`${Qe.dim}No active tasks${Qe.reset}`;let t=[];wr&&(t.push(` ${Qe.bold}${Qe.cyan}Tasks: ${wr}${Qe.reset}`),t.push(` ${Qe.dim}${"\u2500".repeat(40)}${Qe.reset}`));for(let s of Ot){let r,i;switch(s.status){case"done":r="\u2713",i=Qe.green;break;case"in_progress":r="\u2192",i=Qe.cyan;break;case"failed":r="\u2717",i=Qe.red;break;default:r="\xB7",i=Qe.dim}let a=s.dependsOn.length>0?` ${Qe.dim}(after: ${s.dependsOn.join(", ")})${Qe.reset}`:"",l=`[${s.status}]`,c=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${Qe.reset} ${Qe.bold}${s.id}${Qe.reset} ${c.padEnd(40)} ${i}${l}${Qe.reset}${a}`),s.result&&s.status==="done"){let u=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${Qe.dim}\u2192 ${u}${Qe.reset}`)}}let e=Ot.filter(s=>s.status==="done").length,n=Ot.filter(s=>s.status==="failed").length,o=Ot.length;return t.push(` ${Qe.dim}${"\u2500".repeat(40)}${Qe.reset}`),t.push(` ${Qe.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${Qe.reset}`),t.join(`
253
- `)}function $E(){return Ot.length>0&&Ot.some(t=>t.status==="pending"||t.status==="in_progress")}lg.exports={createTasks:mE,updateTask:gE,getTaskList:yE,clearTasks:bE,getReadyTasks:wE,renderTaskList:_E,setOnChange:hE,hasActiveTasks:$E}});var hu=J((YP,hg)=>{var{callChat:kE}=$t(),{estimateTokens:pu}=Pn(),cg=process.env.NEX_COMPACTION!=="false",ug=6,dg=2e3,fg=3,xE=`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.
251
+ Then restart nex-code.`;function tm(){if(yr!==null)return yr;try{require("playwright"),yr=!0}catch{yr=!1}return yr}async function ba(){if(!tm())throw new Error(em);return Gc||(Gc=require("playwright")),(!Un||!Un.isConnected())&&(Un=await Gc.chromium.launch({headless:!0})),Un}async function US(){if(Un){try{await Un.close()}catch(t){console.error("closeBrowser failed:",t.message)}Un=null}}globalThis[Yc]&&process.off("exit",globalThis[Yc]);var nm=()=>{if(Un)try{Un.close()}catch(t){console.error("Error closing browser on exit:",t.message)}};globalThis[Yc]=nm;process.on("exit",nm);async function WS(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await ba()).newPage();try{await s.goto(t,{waitUntil:n,timeout:e});let r=await s.title(),i=await s.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(c=>c.remove()),document.body?.innerText||"")),a=await s.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:s.url(),text:i.substring(0,8e3)+(i.length>8e3?`
252
+ ...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function HS(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await ba()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:s});let a=await i.screenshot({type:"png",fullPage:o}),l=require("os"),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 GS(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await ba()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function YS(t,{selector:e,value:n,submit:o=!1,timeout:s=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await ba()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:s}),await i.fill(e,String(n)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}sm.exports={isPlaywrightAvailable:tm,browserNavigate:WS,browserScreenshot:HS,browserClick:GS,browserFill:YS,closeBrowser:US,INSTALL_MSG:em}});var zc=J((TP,rm)=>{"use strict";var zS=require("util"),om=require("stream"),hn=rm.exports=function(){om.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};zS.inherits(hn,om);hn.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))};hn.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};hn.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()))};hn.prototype.destroySoon=hn.prototype.end;hn.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};hn.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};hn.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))};hn.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,o=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],r=Math.min(s.length,t.length-e);s.copy(o,e,0,r),e+=r,r!==s.length&&(this._buffers[--n]=s.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,o)};hn.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 Vc=J(Kc=>{"use strict";var ss=[{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]}];Kc.getImagePasses=function(t,e){let n=[],o=t%8,s=e%8,r=(t-o)/8,i=(e-s)/8;for(let a=0;a<ss.length;a++){let l=ss[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]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};Kc.getInterlaceIterator=function(t){return function(e,n,o){let s=e%ss[o].x.length,r=(e-s)/ss[o].x.length*8+ss[o].x[s],i=n%ss[o].y.length,a=(n-i)/ss[o].y.length*8+ss[o].y[i];return r*4+a*t*4}}});var Xc=J((CP,im)=>{"use strict";im.exports=function(e,n,o){let s=e+n-o,r=Math.abs(s-e),i=Math.abs(s-n),a=Math.abs(s-o);return r<=i&&r<=a?e:i<=a?n:o}});var Jc=J((AP,lm)=>{"use strict";var KS=Vc(),VS=Xc();function am(t,e,n){let o=t*e;return n!==8&&(o=Math.ceil(o/(8/n))),o}var xo=lm.exports=function(t,e){let n=t.width,o=t.height,s=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=KS.getImagePasses(n,o);for(let l=0;l<a.length;l++)this._images.push({byteWidth:am(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:am(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};xo.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};xo.prototype._unFilterType1=function(t,e,n){let o=this._xComparison,s=o-1;for(let r=0;r<n;r++){let i=t[1+r],a=r>s?e[r-o]:0;e[r]=i+a}};xo.prototype._unFilterType2=function(t,e,n){let o=this._lastLine;for(let s=0;s<n;s++){let r=t[1+s],i=o?o[s]:0;e[s]=r+i}};xo.prototype._unFilterType3=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],l=r?r[i]:0,c=i>s?e[i-o]:0,u=Math.floor((c+l)/2);e[i]=a+u}};xo.prototype._unFilterType4=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],l=r?r[i]:0,c=i>s?e[i-o]:0,u=i>s&&r?r[i-o]:0,d=VS(c,l,u);e[i]=a+d}};xo.prototype._reverseFilterLine=function(t){let e=t[0],n,o=this._images[this._imageIndex],s=o.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),o.lineIndex++,o.lineIndex>=o.height?(this._lastLine=null,this._imageIndex++,o=this._images[this._imageIndex]):this._lastLine=n,o?this.read(o.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var dm=J((OP,um)=>{"use strict";var XS=require("util"),cm=zc(),JS=Jc(),ZS=um.exports=function(t){cm.call(this);let e=[],n=this;this._filter=new JS(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};XS.inherits(ZS,cm)});var So=J((PP,fm)=>{"use strict";fm.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 eu=J((NP,pm)=>{"use strict";var Zc=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;Zc[t]=e}})();var Qc=pm.exports=function(){this._crc=-1};Qc.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Zc[(this._crc^t[e])&255]^this._crc>>>8;return!0};Qc.prototype.crc32=function(){return this._crc^-1};Qc.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Zc[(e^t[n])&255]^e>>>8;return e^-1}});var tu=J((MP,hm)=>{"use strict";var yt=So(),QS=eu(),_t=hm.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[yt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[yt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[yt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[yt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[yt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[yt.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(){}};_t.prototype.start=function(){this.read(yt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};_t.prototype._parseSignature=function(t){let e=yt.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};_t.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o="";for(let r=4;r<8;r++)o+=String.fromCharCode(t[r]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==yt.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new QS,this._crc.write(Buffer.from(o)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+o));return}this.read(e+4,this._skipChunk.bind(this))};_t.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};_t.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};_t.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};_t.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};_t.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o=t[8],s=t[9],r=t[10],i=t[11],a=t[12];if(o!==8&&o!==4&&o!==2&&o!==1&&o!==16){this.error(new Error("Unsupported bit depth "+o));return}if(!(s in yt.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=yt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:o,interlace:!!a,palette:!!(s&yt.COLORTYPE_PALETTE),color:!!(s&yt.COLORTYPE_COLOR),alpha:!!(s&yt.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};_t.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};_t.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};_t.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};_t.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===yt.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===yt.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===yt.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};_t.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};_t.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/yt.GAMMA_DIVISION),this._handleChunkEnd()};_t.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};_t.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===yt.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};_t.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};_t.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var nu=J(gm=>{"use strict";var mm=Vc(),ev=[function(){},function(t,e,n,o){if(o===e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,o){if(o+1>=e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[o+1]},function(t,e,n,o){if(o+2>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=255},function(t,e,n,o){if(o+3>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=e[o+3]}],tv=[function(){},function(t,e,n,o){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=o},function(t,e,n){let o=e[0];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=e[1]},function(t,e,n,o){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=o},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function nv(t,e){let n=[],o=0;function s(){if(o===t.length)throw new Error("Ran out of data");let r=t[o];o++;let i,a,l,c,u,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[o],o++,n.push((r<<8)+f);break;case 4:f=r&15,h=r>>4,n.push(h,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,h=r>>6&3,n.push(h,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,h=r>>7&1,n.push(h,f,d,u,c,l,a,i);break}}return{get:function(r){for(;n.length<r;)s();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(o!==t.length)throw new Error("extra data found")}}}function sv(t,e,n,o,s,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(u,c,l);ev[o](e,s,d,r),r+=o}return r}function ov(t,e,n,o,s,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.get(o),f=n(u,c,l);tv[o](e,d,f,r)}s.resetAfterLine()}}gm.dataToBitMap=function(t,e){let n=e.width,o=e.height,s=e.depth,r=e.bpp,i=e.interlace,a;s!==8&&(a=nv(t,s));let l;s<=8?l=Buffer.alloc(n*o*4):l=new Uint16Array(n*o*4);let c=Math.pow(2,s)-1,u=0,d,f;if(i)d=mm.getImagePasses(n,o),f=mm.getInterlaceIterator(n,o);else{let h=0;f=function(){let m=h;return h+=4,m},d=[{width:n,height:o}]}for(let h=0;h<d.length;h++)s===8?u=sv(d[h],l,f,r,t,u):ov(d[h],l,f,r,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var su=J((IP,ym)=>{"use strict";function rv(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let l=s[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let c=0;c<4;c++)e[r+c]=l[c];r+=4}}function iv(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[r]&&(l=!0):s[0]===t[r]&&s[1]===t[r+1]&&s[2]===t[r+2]&&(l=!0),l)for(let c=0;c<4;c++)e[r+c]=0;r+=4}}function av(t,e,n,o,s){let r=255,i=Math.pow(2,s)-1,a=0;for(let l=0;l<o;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}ym.exports=function(t,e,n=!1){let o=e.depth,s=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,c=t;return i===3?rv(t,c,s,r,l):(a&&iv(t,c,s,r,a),o!==8&&!n&&(o===16&&(c=Buffer.alloc(s*r*4)),av(t,c,s,r,o))),c}});var _m=J((jP,wm)=>{"use strict";var lv=require("util"),ou=require("zlib"),bm=zc(),cv=dm(),uv=tu(),dv=nu(),fv=su(),An=wm.exports=function(t){bm.call(this),this._parser=new uv(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()};lv.inherits(An,bm);An.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};An.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=ou.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,o=Math.max(n,ou.Z_MIN_CHUNK);this._inflate=ou.createInflate({chunkSize:o});let s=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};An.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new cv(this._bitmapInfo)};An.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};An.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};An.prototype._simpleTransparency=function(){this._metaData.alpha=!0};An.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};An.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};An.prototype._complete=function(t){if(this.errord)return;let e;try{let n=dv.dataToBitMap(t,this._bitmapInfo);e=fv(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var km=J((DP,$m)=>{"use strict";var nn=So();$m.exports=function(t,e,n,o){let s=[nn.COLORTYPE_COLOR_ALPHA,nn.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=nn.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let l=nn.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=o.bgColor||{};f.red===void 0&&(f.red=i),f.green===void 0&&(f.green=i),f.blue===void 0&&(f.blue=i);function h(){let m,g,_,k=i;switch(o.inputColorType){case nn.COLORTYPE_COLOR_ALPHA:k=r[u+3],m=r[u],g=r[u+1],_=r[u+2];break;case nn.COLORTYPE_COLOR:m=r[u],g=r[u+1],_=r[u+2];break;case nn.COLORTYPE_ALPHA:k=r[u+1],m=r[u],g=m,_=m;break;case nn.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&&(s||(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<n;m++)for(let g=0;g<e;g++){let _=h(r,u);switch(o.colorType){case nn.COLORTYPE_COLOR_ALPHA:case nn.COLORTYPE_COLOR:o.bitDepth===8?(c[d]=_.red,c[d+1]=_.green,c[d+2]=_.blue,s&&(c[d+3]=_.alpha)):(c.writeUInt16BE(_.red,d),c.writeUInt16BE(_.green,d+2),c.writeUInt16BE(_.blue,d+4),s&&c.writeUInt16BE(_.alpha,d+6));break;case nn.COLORTYPE_ALPHA:case nn.COLORTYPE_GRAYSCALE:{let k=(_.red+_.green+_.blue)/3;o.bitDepth===8?(c[d]=k,s&&(c[d+1]=_.alpha)):(c.writeUInt16BE(k,d),s&&c.writeUInt16BE(_.alpha,d+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}u+=a,d+=l}return c}});var vm=J((qP,Sm)=>{"use strict";var xm=Xc();function pv(t,e,n,o,s){for(let r=0;r<n;r++)o[s+r]=t[e+r]}function hv(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++)o+=Math.abs(t[r]);return o}function mv(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;o[s+i]=l}}function gv(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=t[e+r]-i;s+=Math.abs(a)}return s}function yv(t,e,n,o,s){for(let r=0;r<n;r++){let i=e>0?t[e+r-n]:0,a=t[e+r]-i;o[s+r]=a}}function bv(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++){let i=e>0?t[r-n]:0,a=t[r]-i;o+=Math.abs(a)}return o}function wv(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-n]:0,c=t[e+i]-(a+l>>1);o[s+i]=c}}function _v(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,l=t[e+r]-(i+a>>1);s+=Math.abs(l)}return s}function $v(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-n]:0,c=e>0&&i>=r?t[e+i-(n+r)]:0,u=t[e+i]-xm(a,l,c);o[s+i]=u}}function kv(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,l=e>0&&r>=o?t[e+r-(n+o)]:0,c=t[e+r]-xm(i,a,l);s+=Math.abs(c)}return s}var xv={0:pv,1:mv,2:yv,3:wv,4:$v},Sv={0:hv,1:gv,2:bv,3:_v,4:kv};Sm.exports=function(t,e,n,o,s){let r;if(!("filterType"in o)||o.filterType===-1)r=[0,1,2,3,4];else if(typeof o.filterType=="number")r=[o.filterType];else throw new Error("unrecognised filter types");o.bitDepth===16&&(s*=2);let i=e*s,a=0,l=0,c=Buffer.alloc((i+1)*n),u=r[0];for(let d=0;d<n;d++){if(r.length>1){let f=1/0;for(let h=0;h<r.length;h++){let m=Sv[r[h]](t,l,i,s);m<f&&(u=r[h],f=m)}}c[a]=u,a++,xv[u](t,l,i,c,a,s),a+=i,l+=i}return c}});var ru=J((FP,Em)=>{"use strict";var Rt=So(),vv=eu(),Ev=km(),Tv=vm(),Rv=require("zlib"),os=Em.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||Rv.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:Rt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:Rt.COLORTYPE_COLOR_ALPHA,[Rt.COLORTYPE_GRAYSCALE,Rt.COLORTYPE_COLOR,Rt.COLORTYPE_COLOR_ALPHA,Rt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([Rt.COLORTYPE_GRAYSCALE,Rt.COLORTYPE_COLOR,Rt.COLORTYPE_COLOR_ALPHA,Rt.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};os.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};os.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};os.prototype.filterData=function(t,e,n){let o=Ev(t,e,n,this._options),s=Rt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Tv(o,e,n,this._options,s)};os.prototype._packChunk=function(t,e){let n=e?e.length:0,o=Buffer.alloc(n+12);return o.writeUInt32BE(n,0),o.writeUInt32BE(t,4),e&&e.copy(o,8),o.writeInt32BE(vv.crc32(o.slice(4,o.length-4)),o.length-4),o};os.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Rt.GAMMA_DIVISION),0),this._packChunk(Rt.TYPE_gAMA,e)};os.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(Rt.TYPE_IHDR,n)};os.prototype.packIDAT=function(t){return this._packChunk(Rt.TYPE_IDAT,t)};os.prototype.packIEND=function(){return this._packChunk(Rt.TYPE_IEND,null)}});var Am=J((BP,Cm)=>{"use strict";var Cv=require("util"),Tm=require("stream"),Av=So(),Ov=ru(),Rm=Cm.exports=function(t){Tm.call(this);let e=t||{};this._packer=new Ov(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Cv.inherits(Rm,Tm);Rm.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(Av.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),o&&this.emit("data",this._packer.packGAMA(o));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var Im=J((br,Lm)=>{"use strict";var Om=require("assert").ok,vo=require("zlib"),Pv=require("util"),Pm=require("buffer").kMaxLength;function As(t){if(!(this instanceof As))return new As(t);t&&t.chunkSize<vo.Z_MIN_CHUNK&&(t.chunkSize=vo.Z_MIN_CHUNK),vo.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 Nv(t){return new As(t)}function Nm(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}As.prototype._processChunk=function(t,e,n){if(typeof n=="function")return vo.Inflate._processChunk.call(this,t,e,n);let o=this,s=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(m){u=m});function d(m,g){if(o._hadError)return;let _=r-g;if(Om(_>=0,"have should not go down"),_>0){let k=o._buffer.slice(o._offset,o._offset+_);if(o._offset+=_,k.length>i&&(k=k.slice(0,i)),l.push(k),c+=k.length,i-=k.length,i===0)return!1}return(g===0||o._offset>=o._chunkSize)&&(r=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),g===0?(a+=s-m,s=m,!0):!1}Om(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=Pm)throw Nm(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Pm.toString(16)+" bytes");let h=Buffer.concat(l,c);return Nm(this),h};Pv.inherits(As,vo.Inflate);function Mv(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=vo.Z_FINISH),t._processChunk(e,n)}function Mm(t,e){return Mv(new As(e),t)}Lm.exports=br=Mm;br.Inflate=As;br.createInflate=Nv;br.inflateSync=Mm});var iu=J((UP,Dm)=>{"use strict";var jm=Dm.exports=function(t){this._buffer=t,this._reads=[]};jm.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};jm.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 Fm=J(qm=>{"use strict";var Lv=iu(),Iv=Jc();qm.process=function(t,e){let n=[],o=new Lv(t);return new Iv(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var Hm=J((HP,Wm)=>{"use strict";var Bm=!0,Um=require("zlib"),jv=Im();Um.deflateSync||(Bm=!1);var Dv=iu(),qv=Fm(),Fv=tu(),Bv=nu(),Uv=su();Wm.exports=function(t,e){if(!Bm)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function o(E){n=E}let s;function r(E){s=E}function i(E){s.transColor=E}function a(E){s.palette=E}function l(){s.alpha=!0}let c;function u(E){c=E}let d=[];function f(E){d.push(E)}let h=new Dv(t);if(new Fv(e,{read:h.read.bind(h),error:o,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let g=Buffer.concat(d);d.length=0;let _;if(s.interlace)_=Um.inflateSync(g);else{let T=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;_=jv(g,{chunkSize:T,maxLength:T})}if(g=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let k=qv.process(_,s);g=null;let $=Bv.dataToBitMap(k,s);k=null;let O=Uv($,s,e.skipRescale);return s.data=O,s.gamma=c||0,s}});var Km=J((GP,zm)=>{"use strict";var Gm=!0,Ym=require("zlib");Ym.deflateSync||(Gm=!1);var Wv=So(),Hv=ru();zm.exports=function(t,e){if(!Gm)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},o=new Hv(n),s=[];s.push(Buffer.from(Wv.PNG_SIGNATURE)),s.push(o.packIHDR(t.width,t.height)),t.gamma&&s.push(o.packGAMA(t.gamma));let r=o.filterData(t.data,t.width,t.height),i=Ym.deflateSync(r,o.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return s.push(o.packIDAT(i)),s.push(o.packIEND()),Buffer.concat(s)}});var Vm=J(au=>{"use strict";var Gv=Hm(),Yv=Km();au.read=function(t,e){return Gv(t,e||{})};au.write=function(t,e){return Yv(t,e)}});var Zm=J(Jm=>{"use strict";var zv=require("util"),Xm=require("stream"),Kv=_m(),Vv=Am(),Xv=Vm(),At=Jm.PNG=function(t){Xm.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 Kv(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 Vv(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"))};zv.inherits(At,Xm);At.sync=Xv;At.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)};At.prototype.parse=function(t,e){if(e){let n,o;n=function(s){this.removeListener("error",o),this.data=s,e(null,this)}.bind(this),o=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",o)}return this.end(t),this};At.prototype.write=function(t){return this._parser.write(t),!0};At.prototype.end=function(t){this._parser.end(t)};At.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};At.prototype._gamma=function(t){this.gamma=t};At.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};At.bitblt=function(t,e,n,o,s,r,i,a){if(n|=0,o|=0,s|=0,r|=0,i|=0,a|=0,n>t.width||o>t.height||n+s>t.width||o+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+s>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<r;l++)t.data.copy(e.data,(a+l)*e.width+i<<2,(o+l)*t.width+n<<2,(o+l)*t.width+n+s<<2)};At.prototype.bitblt=function(t,e,n,o,s,r,i){return At.bitblt(this,t,e,n,o,s,r,i),this};At.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let o=t.width*e+n<<2;for(let s=0;s<3;s++){let r=t.data[o+s]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[o+s]=Math.round(r*255)}}t.gamma=0}};At.prototype.adjustGamma=function(){At.adjustGamma(this)}});var sg={};Z0(sg,{default:()=>tg});function tg(t,e,n,o,s,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(!lu(t)||!lu(e)||n&&!lu(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||n&&n.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==o*s*4)throw new Error("Image data size does not match width/height.");let h=o*s,m=new Uint32Array(t.buffer,t.byteOffset,h),g=new Uint32Array(e.buffer,e.byteOffset,h),_=!0;for(let ie=0;ie<h;ie++)if(m[ie]!==g[ie]){_=!1;break}if(_){if(n&&!f)for(let ie=0;ie<h;ie++)eg(t,4*ie,a,n);return 0}let k=35215*i*i,[$,O,E]=l,[T,q,ee]=c,[te,K,ae]=d||c,se=0;for(let ie=0;ie<s;ie++)for(let Be=0;Be<o;Be++){let Ce=ie*o+Be,H=Ce*4,ne=m[Ce]===g[Ce]?0:ng(t,e,H,H,!1);if(Math.abs(ne)>k){let Ve=Qm(t,Be,ie,o,s,m,g)||Qm(e,Be,ie,o,s,g,m);!u&&Ve?n&&!f&&_a(n,H,$,O,E):(n&&(ne<0?_a(n,H,te,K,ae):_a(n,H,T,q,ee)),se++)}else n&&!f&&eg(t,H,a,n)}return se}function lu(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Qm(t,e,n,o,s,r,i){let a=Math.max(e-1,0),l=Math.max(n-1,0),c=Math.min(e+1,o-1),u=Math.min(n+1,s-1),d=n*o+e,f=e===a||e===c||n===l||n===u?1:0,h=0,m=0,g=0,_=0,k=0,$=0;for(let O=a;O<=c;O++)for(let E=l;E<=u;E++){if(O===e&&E===n)continue;let T=ng(t,t,d*4,(E*o+O)*4,!0);if(T===0){if(f++,f>2)return!1}else T<h?(h=T,g=O,_=E):T>m&&(m=T,k=O,$=E)}return h===0||m===0?!1:wa(r,g,_,o,s)&&wa(i,g,_,o,s)||wa(r,k,$,o,s)&&wa(i,k,$,o,s)}function wa(t,e,n,o,s){let r=Math.max(e-1,0),i=Math.max(n-1,0),a=Math.min(e+1,o-1),l=Math.min(n+1,s-1),c=t[n*o+e],u=e===r||e===a||n===i||n===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===n)&&(u+=+(c===t[f*o+d]),u>2))return!0;return!1}function ng(t,e,n,o,s){let r=t[n],i=t[n+1],a=t[n+2],l=t[n+3],c=e[o],u=e[o+1],d=e[o+2],f=e[o+3],h=r-c,m=i-u,g=a-d,_=l-f;if(!h&&!m&&!g&&!_)return 0;if(l<255||f<255){let T=48+159*(n%2),q=48+159*((n/1.618033988749895|0)%2),ee=48+159*((n/2.618033988749895|0)%2);h=(r*l-c*f-T*_)/255,m=(i*l-u*f-q*_)/255,g=(a*l-d*f-ee*_)/255}let k=h*.29889531+m*.58662247+g*.11448223;if(s)return k;let $=h*.59597799-m*.2741761-g*.32180189,O=h*.21147017-m*.52261711+g*.31114694,E=.5053*k*k+.299*$*$+.1957*O*O;return k>0?-E:E}function _a(t,e,n,o,s){t[e+0]=n,t[e+1]=o,t[e+2]=s,t[e+3]=255}function eg(t,e,n,o){let s=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;_a(o,e,s,s,s)}var og=J0(()=>{});var Os=J((KP,cg)=>{var Hn=require("fs"),Jv=require("path"),Zv=require("os"),Qv="nex-visual-";function ig(t){return Jv.join(Zv.tmpdir(),`${Qv}${Date.now()}-${t}`)}var cu=null;function $a(){return cu||(cu=Zm().PNG),cu}var uu=null;function eE(){if(!uu){let t=(og(),e_(sg));uu=t.default||t}return uu}function pu(t,e,{threshold:n=.1}={}){let o=$a(),s=eE(),r=o.sync.read(Hn.readFileSync(t)),i=o.sync.read(Hn.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=rg(r,a,l),u=rg(i,a,l),d=new o({width:a,height:l}),f=s(c,u,d.data,a,l,{threshold:n,includeAA:!1}),h=a*l,m=(f/h*100).toFixed(1),g=tE(d.data,a,l,3,3),_=ig("diff.png");return Hn.writeFileSync(_,o.sync.write(d),{mode:384}),{diffPath:_,diffPercent:parseFloat(m),totalPixels:h,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function rg(t,e,n){if(t.width===e&&t.height===n)return t.data;let o=Buffer.alloc(e*n*4,0);for(let s=0;s<t.height;s++){let r=s*t.width*4,i=s*e*4;t.data.copy(o,i,r,r+t.width*4)}return o}function tE(t,e,n,o,s){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/o),a=Math.ceil(n/s),l=[];for(let c=0;c<s;c++)for(let u=0;u<o;u++){let d=0,f=0,h=u*i,m=c*a,g=Math.min(h+i,e),_=Math.min(m+a,n);for(let k=m;k<_;k++)for(let $=h;$<g;$++){f++;let O=(k*e+$)*4;(t[O]>0||t[O+1]>0)&&d++}if(d>0){let k=(d/f*100).toFixed(1),$=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:$,changedPercent:parseFloat(k),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var ag=[{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 nE(t,{viewports:e=ag,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=Wn(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:n,fullPage:o,timeout:s});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function lg(t,e=[]){let n=$a(),o=n.sync.read(Hn.readFileSync(t));for(let i of e){let a=sE(i.color||"#FF0000");i.type==="box"?(oE(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&fu(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(rE(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&fu(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(iE(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&fu(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=ig("annotated.png");Hn.writeFileSync(s,n.sync.write(o),{mode:384});let r=Hn.readFileSync(s).toString("base64");return{path:s,base64:r,media_type:"image/png"}}function sE(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 On(t,e,n,o){if(e<0||n<0||e>=t.width||n>=t.height)return;let s=(n*t.width+e)*4;t.data[s]=o.r,t.data[s+1]=o.g,t.data[s+2]=o.b,t.data[s+3]=o.a}function oE(t,e,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<o;l++)On(t,e+l,n+a,r),On(t,e+l,n+s-1-a,r);for(let l=0;l<s;l++)On(t,e+a,n+l,r),On(t,e+o-1-a,n+l,r)}}function du(t,e,n,o,s,r,i=3){let a=Math.abs(o-e),l=Math.abs(s-n),c=e<o?1:-1,u=n<s?1:-1,d=a-l,f=e,h=n;for(;;){let m=Math.floor(i/2);for(let _=-m;_<=m;_++)for(let k=-m;k<=m;k++)On(t,f+_,h+k,r);if(f===o&&h===s)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,h+=u)}}function rE(t,e,n,o,s,r,i=3){du(t,e,n,o,s,r,i);let a=Math.atan2(s-n,o-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;du(t,o,s,Math.round(o+l*Math.cos(c)),Math.round(s+l*Math.sin(c)),r,i),du(t,o,s,Math.round(o+l*Math.cos(u)),Math.round(s+l*Math.sin(u)),r,i)}function iE(t,e,n,o,s,r=3){for(let i=0;i<r;i++){let a=o-i;for(let l=0;l<360;l+=.5){let c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(n+a*Math.sin(c));On(t,u,d,s)}}}function fu(t,e,n,o,s){let i=o.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)On(t,e+c,n+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)On(t,e+l,n+a-1,s),On(t,e+l,n+a-2,s);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++)On(t,c+d,n+u,s)}}async function*aE(t,e,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=Wn(),l=lE("chokidar"),c=await a(t,{width:s,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<n;){await uE(()=>d,3e5),d=!1,u++,await cE(o);let h=await a(t,{width:s,height:r,timeout:i}),m=null;try{m=pu(c.path,h.path)}catch{}c=h,yield{iteration:u,type:"change",path:h.path,base64:h.base64,media_type:h.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function lE(t){try{return require(t)}catch{return null}}function cE(t){return new Promise(e=>setTimeout(e,t))}function uE(t,e=6e4){return new Promise((n,o)=>{let s=setInterval(()=>{t()&&(clearInterval(s),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(s),o(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function dE(t,{sampleRate:e=4}={}){let o=$a().sync.read(Hn.readFileSync(t)),s=new Map;for(let c=0;c<o.height;c+=e)for(let u=0;u<o.width;u+=e){let d=(c*o.width+u)*4,f=o.data[d],h=o.data[d+1],m=o.data[d+2];if(o.data[d+3]<128)continue;let _=Math.round(f/8)*8,k=Math.round(h/8)*8,$=Math.round(m/8)*8,O=`${_},${k},${$}`;s.set(O,(s.get(O)||0)+1)}let r=[...s.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,h]=c.split(",").map(Number);return{hex:fE(d,f,h),rgb:`rgb(${d}, ${f}, ${h})`,frequency:parseFloat((u/i*100).toFixed(1)),category:pE(d,f,h)}}),l=hE(o);return{colors:a,spacing:l,dimensions:{width:o.width,height:o.height},imagePath:t}}function fE(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function pE(t,e,n){let o=(t*299+e*587+n*114)/1e3;return o>240?"white/background":o<30?"black/text":o<80?"dark":t>200&&e<100&&n<100?"red/danger":t<100&&e>150&&n<100?"green/success":t<100&&e<100&&n>200?"blue/primary":t>200&&e>200&&n<100?"yellow/warning":t>200&&e>100&&n<50?"orange/accent":o>200?"light/subtle":"midtone"}function hE(t){let e=[],n=!1,o=0,s=mE(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]-s.r)>20||Math.abs(t.data[c+1]-s.g)>20||Math.abs(t.data[c+2]-s.b)>20){a=!1;break}}if(a&&n)n=!1,o=i;else if(!a&&!n&&(n=!0,o>0)){let l=i-o;l>=4&&l<=200&&e.push(l)}}let r=new Map;for(let i of e){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function mE(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],n=0,o=0,s=0;for(let[r,i]of e){let a=(i*t.width+r)*4;n+=t.data[a],o+=t.data[a+1],s+=t.data[a+2]}return{r:Math.round(n/4),g:Math.round(o/4),b:Math.round(s/4)}}async function gE(t,e,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=Wn(),c=$a().sync.read(Hn.readFileSync(e)),u=n||c.width,d=o||c.height,f=await a(t,{width:u,height:d,fullPage:s,timeout:i}),h=pu(e,f.path,{threshold:r}),m=lg(f.path,h.regionSummary.filter(g=>g.changedPercent>1).map((g,_)=>{let O=Math.ceil(h.width/3),E=Math.ceil(h.height/3),T=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],q=0,ee=0;for(let te=0;te<3;te++)for(let K=0;K<3;K++)T[te][K]===g.name&&(q=K,ee=te);return{type:"box",x:q*O+2,y:ee*E+2,width:O-4,height:E-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:h.diffPath,annotatedPath:m.path,diffPercent:h.diffPercent,changedPixels:h.changedPixels,totalPixels:h.totalPixels,regions:h.regionSummary,liveBase64:f.base64,diffBase64:Hn.readFileSync(h.diffPath).toString("base64"),annotatedBase64:m.base64}}cg.exports={pixelDiff:pu,responsiveSweep:nE,annotateImage:lg,visualWatch:aE,extractDesignTokens:dE,designCompare:gE,DEFAULT_VIEWPORTS:ag}});var hu=J((VP,ug)=>{var{C:Qe}=$t(),_r="",Ot=[],wr=0,Ps=null;function yE(t){Ps=t}function bE(t,e){_r=t,Ot=[],wr=0;for(let o of e){wr++;let s=`t${wr}`;Ot.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${wr}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=Ot.map(o=>({...o}));return Ps&&Ps("create",{name:t,tasks:n}),n}function wE(t,e,n){let o=Ot.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),Ps&&Ps("update",{id:t,status:e,result:n}),{...o}):null}function _E(){return{name:_r,tasks:Ot.map(t=>({...t}))}}function $E(){_r="",Ot=[],wr=0,Ps&&Ps("clear",{})}function kE(){return Ot.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=Ot.find(o=>o.id===e);return n&&n.status==="done"}))}function xE(){if(Ot.length===0)return`${Qe.dim}No active tasks${Qe.reset}`;let t=[];_r&&(t.push(` ${Qe.bold}${Qe.cyan}Tasks: ${_r}${Qe.reset}`),t.push(` ${Qe.dim}${"\u2500".repeat(40)}${Qe.reset}`));for(let s of Ot){let r,i;switch(s.status){case"done":r="\u2713",i=Qe.green;break;case"in_progress":r="\u2192",i=Qe.cyan;break;case"failed":r="\u2717",i=Qe.red;break;default:r="\xB7",i=Qe.dim}let a=s.dependsOn.length>0?` ${Qe.dim}(after: ${s.dependsOn.join(", ")})${Qe.reset}`:"",l=`[${s.status}]`,c=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${Qe.reset} ${Qe.bold}${s.id}${Qe.reset} ${c.padEnd(40)} ${i}${l}${Qe.reset}${a}`),s.result&&s.status==="done"){let u=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${Qe.dim}\u2192 ${u}${Qe.reset}`)}}let e=Ot.filter(s=>s.status==="done").length,n=Ot.filter(s=>s.status==="failed").length,o=Ot.length;return t.push(` ${Qe.dim}${"\u2500".repeat(40)}${Qe.reset}`),t.push(` ${Qe.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${Qe.reset}`),t.join(`
253
+ `)}function SE(){return Ot.length>0&&Ot.some(t=>t.status==="pending"||t.status==="in_progress")}ug.exports={createTasks:bE,updateTask:wE,getTaskList:_E,clearTasks:$E,getReadyTasks:kE,renderTaskList:xE,setOnChange:yE,hasActiveTasks:SE}});var gu=J((XP,gg)=>{var{callChat:vE}=kt(),{estimateTokens:mu}=Pn(),dg=process.env.NEX_COMPACTION!=="false",fg=6,pg=2e3,hg=3,EE=`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.
254
254
  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.
255
255
 
256
256
  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:
@@ -282,38 +282,38 @@ Format your output as:
282
282
 
283
283
  <summary>
284
284
  [Sections 1-9 above]
285
- </summary>`,Ps=0;async function SE(t){if(!cg||t.length<ug||Ps>=fg)return null;let e=[{role:"system",content:xE},{role:"user",content:pg(t)}];try{let o=((await kE(e,[],{temperature:0,maxTokens:dg})).content||"").trim();if(!o)return Ps++,null;let s=o.match(/<summary>([\s\S]*?)<\/summary>/);if(s?o=s[1].trim():o=o.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!o)return Ps++,null;let r=t.reduce((a,l)=>a+pu(l.content||"")+(l.tool_calls?pu(JSON.stringify(l.tool_calls)):0),0),i=pu(o);return i>=r*.8?(Ps++,null):(Ps=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
286
- ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Ps++,null}}function vE(){Ps=0}function pg(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let s=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${o}
285
+ </summary>`,Ns=0;async function TE(t){if(!dg||t.length<fg||Ns>=hg)return null;let e=[{role:"system",content:EE},{role:"user",content:mg(t)}];try{let o=((await vE(e,[],{temperature:0,maxTokens:pg})).content||"").trim();if(!o)return Ns++,null;let s=o.match(/<summary>([\s\S]*?)<\/summary>/);if(s?o=s[1].trim():o=o.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!o)return Ns++,null;let r=t.reduce((a,l)=>a+mu(l.content||"")+(l.tool_calls?mu(JSON.stringify(l.tool_calls)):0),0),i=mu(o);return i>=r*.8?(Ns++,null):(Ns=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
286
+ ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Ns++,null}}function RE(){Ns=0}function mg(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let s=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${o}
287
287
  tools: ${s}`}return`[${n}] ${o}`}).join(`
288
288
 
289
- `)}hg.exports={compactMessages:SE,formatMessagesForSummary:pg,resetCompactionFailures:vE,COMPACTION_ENABLED:cg,COMPACTION_MIN_MESSAGES:ug,COMPACTION_SUMMARY_BUDGET:dg,MAX_CONSECUTIVE_FAILURES:fg}});var Pn=J((zP,Sg)=>{var EE=require("path");function gg(){return $t().getActiveModel()}var TE={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},RE={devstral:3.8,mistral:3.8,ministral:3.8,codestral:3.8,qwen:3.5,deepseek:3.6,kimi:3.7,gemma:4,llama:3.8,cogito:3.6,phi:4},Ns=new Map,mg=1e3,mu=new WeakMap,Ms=null;function CE(){if(Ms!==null)return Ms;try{let t=gg(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(RE))if(n.startsWith(o))return Ms=s,Ms;return Ms=TE[e]||4,Ms}catch{return 4}}function AE(){Ms=null}function Ls(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,n=Ns.get(e);if(n!==void 0)return Ns.delete(e),Ns.set(e,n),n;let o=Math.ceil(t.length/CE());if(Ns.size>=mg){let s=mg>>1,r=Ns.keys();for(let i=0;i<s;i++)Ns.delete(r.next().value)}return Ns.set(e,o),o}function OE(t){if(mu.has(t))return mu.get(t);let e=JSON.stringify(t);return mu.set(t,e),e}function Is(t){let n=4;if(t.content&&(n+=Ls(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=Ls(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=Ls(s):s&&(n+=Ls(JSON.stringify(s)))}return n}function mn(t){let e=0;for(let n of t)e+=Is(n);return e}function PE(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let n=t?t.length:0,o=e.length,s=0;for(let r=n;r<o;r++)s+=Is(e[r]);return s}var gu=new WeakMap;function $a(t){if(!t||t.length===0)return 0;if(gu.has(t))return gu.get(t);let e=Ls(JSON.stringify(t));return gu.set(t,e),e}function ka(){return gg()?.contextWindow||32768}var Pt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function NE(t,e){let n=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(Pt.result&&t.length===Pt.msgCount&&n===Pt.lastMsgRef&&o===Pt.toolCount)return Pt.result;let s,r,i,a;if(Pt.messagesRef===t&&t.length>Pt.msgCount&&Pt.msgCount>=0){s=Pt.messageTokens,r=Pt.systemTokens,i=Pt.conversationTokens,a=Pt.toolResultTokens;for(let h=Pt.msgCount;h<t.length;h++){let m=Is(t[h]);s+=m,t[h].role==="system"?r+=m:t[h].role==="tool"?a+=m:i+=m}}else{s=0,r=0,i=0,a=0;for(let h of t){let m=Is(h);s+=m,h.role==="system"?r+=m:h.role==="tool"?a+=m:i+=m}}let l=$a(e),c=s+l,u=ka(),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 Pt={msgCount:t.length,lastMsgRef:n,toolCount:o,result:f,messagesRef:t,messageTokens:s,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var _r=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,yg=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,bg=parseInt(process.env.NEX_KEEP_RECENT,10)||10,wg={essential:.6,standard:.65,full:Math.min(_r,.75)};function _g(){if(process.env.NEX_COMPRESSION_THRESHOLD)return _r;try{let{getActiveTier:t}=mr(),e=t();return wg[e]??_r}catch{return _r}}var ME=200,LE=1e3;function $g(t,e){if(!t||t.length<=e)return t;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=o)return t;let s=t.split(`
289
+ `)}gg.exports={compactMessages:TE,formatMessagesForSummary:mg,resetCompactionFailures:RE,COMPACTION_ENABLED:dg,COMPACTION_MIN_MESSAGES:fg,COMPACTION_SUMMARY_BUDGET:pg,MAX_CONSECUTIVE_FAILURES:hg}});var Pn=J((JP,Eg)=>{var CE=require("path");function bg(){return kt().getActiveModel()}var AE={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},OE={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},Ms=new Map,yg=1e3,yu=new WeakMap,Ls=null;function PE(){if(Ls!==null)return Ls;try{let t=bg(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(OE))if(n.startsWith(o))return Ls=s,Ls;return Ls=AE[e]||4,Ls}catch{return 4}}function NE(){Ls=null}function Is(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,n=Ms.get(e);if(n!==void 0)return Ms.delete(e),Ms.set(e,n),n;let o=Math.ceil(t.length/PE());if(Ms.size>=yg){let s=yg>>1,r=Ms.keys();for(let i=0;i<s;i++)Ms.delete(r.next().value)}return Ms.set(e,o),o}function ME(t){if(yu.has(t))return yu.get(t);let e=JSON.stringify(t);return yu.set(t,e),e}function js(t){let n=4;if(t.content&&(n+=Is(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=Is(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=Is(s):s&&(n+=Is(JSON.stringify(s)))}return n}function mn(t){let e=0;for(let n of t)e+=js(n);return e}function LE(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let n=t?t.length:0,o=e.length,s=0;for(let r=n;r<o;r++)s+=js(e[r]);return s}var bu=new WeakMap;function ka(t){if(!t||t.length===0)return 0;if(bu.has(t))return bu.get(t);let e=Is(JSON.stringify(t));return bu.set(t,e),e}function xa(){return bg()?.contextWindow||32768}var Pt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function IE(t,e){let n=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(Pt.result&&t.length===Pt.msgCount&&n===Pt.lastMsgRef&&o===Pt.toolCount)return Pt.result;let s,r,i,a;if(Pt.messagesRef===t&&t.length>Pt.msgCount&&Pt.msgCount>=0){s=Pt.messageTokens,r=Pt.systemTokens,i=Pt.conversationTokens,a=Pt.toolResultTokens;for(let h=Pt.msgCount;h<t.length;h++){let m=js(t[h]);s+=m,t[h].role==="system"?r+=m:t[h].role==="tool"?a+=m:i+=m}}else{s=0,r=0,i=0,a=0;for(let h of t){let m=js(h);s+=m,h.role==="system"?r+=m:h.role==="tool"?a+=m:i+=m}}let l=ka(e),c=s+l,u=xa(),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 Pt={msgCount:t.length,lastMsgRef:n,toolCount:o,result:f,messagesRef:t,messageTokens:s,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var $r=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,wg=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,_g=parseInt(process.env.NEX_KEEP_RECENT,10)||10,$g={essential:.6,standard:.65,full:Math.min($r,.75)};function kg(){if(process.env.NEX_COMPRESSION_THRESHOLD)return $r;try{let{getActiveTier:t}=gr(),e=t();return $g[e]??$r}catch{return $r}}var jE=200,DE=1e3;function xg(t,e){if(!t||t.length<=e)return t;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=o)return t;let s=t.split(`
290
290
  `);if(s.length<=10){let m=Math.floor(o*.6),g=Math.floor(o*.4),_=t.substring(0,m),k=t.substring(t.length-g);return _+`
291
291
  ...(${t.length} chars total)...
292
292
  `+k}let r=Math.floor(s.length*.4),i=Math.floor(s.length*.4),a=[],l=0,c=Math.floor(o*.4);for(let m=0;m<r&&l<c;m++)if(l+s[m].length+1>c&&s[m].trim().startsWith("```")){a.push(s[m]),l+=s[m].length+1;let g=m+1;for(;g<s.length&&l<c*1.5&&!s[g].trim().startsWith("```");)a.push(s[g]),l+=s[g].length+1,g++;g<s.length&&s[g].trim().startsWith("```")&&(a.push(s[g]),l+=s[g].length+1),m=g}else a.push(s[m]),l+=s[m].length+1;let u=[],d=0,f=Math.floor(o*.4);for(let m=s.length-1;m>=s.length-i&&d<f;m--)if(d+s[m].length+1>f&&s[m].trim().startsWith("```")){u.push(s[m]),d+=s[m].length+1;let g=m-1;for(;g>=0&&d<f*1.5&&!s[g].trim().startsWith("```");)u.push(s[g]),d+=s[g].length+1,g--;g>=0&&s[g].trim().startsWith("```")&&(u.push(s[g]),d+=s[g].length+1),m=g}else u.push(s[m]),d+=s[m].length+1;u.reverse();let h=s.length-a.length-u.length;return a.join(`
293
293
  `)+`
294
294
  ...(${h} lines omitted, ${s.length} total)...
295
295
  `+u.join(`
296
- `)}function Eo(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:LE,o=e==="aggressive"?50:e==="medium"?100:ME;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:$g(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
297
- ...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),s}return t}function kg(t,e,n,o){let s=0;if(t.role==="system")return 100;if(t.role==="user")s+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?s+=30:s+=15}else t.role==="assistant"&&(s+=t.tool_calls?20:10);let r=n>1?e/(n-1):1;if(s+=Math.round(r*30),o&&o.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let l of o)(i.includes(l)||i.includes(EE.basename(l)))&&a++;s+=Math.min(30,a*10)}return Math.min(100,s)}function xg(t,e=10){let n=new Set,o=t.slice(-e),s=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(s);a&&a.forEach(l=>n.add(l))}return n}function IE(t,{filesModified:e=new Set,currentPhase:n=null}={}){let o=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");o.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}n&&o.push(`Current phase: ${n}`);let s=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return s.length>0&&o.push(`Recent progress:
296
+ `)}function To(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:DE,o=e==="aggressive"?50:e==="medium"?100:jE;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:xg(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
297
+ ...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),s}return t}function Sg(t,e,n,o){let s=0;if(t.role==="system")return 100;if(t.role==="user")s+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?s+=30:s+=15}else t.role==="assistant"&&(s+=t.tool_calls?20:10);let r=n>1?e/(n-1):1;if(s+=Math.round(r*30),o&&o.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let l of o)(i.includes(l)||i.includes(CE.basename(l)))&&a++;s+=Math.min(30,a*10)}return Math.min(100,s)}function vg(t,e=10){let n=new Set,o=t.slice(-e),s=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(s);a&&a.forEach(l=>n.add(l))}return n}function qE(t,{filesModified:e=new Set,currentPhase:n=null}={}){let o=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");o.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}n&&o.push(`Current phase: ${n}`);let s=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return s.length>0&&o.push(`Recent progress:
298
298
  `+s.map(r=>`- ${r}`).join(`
299
299
  `)),o.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
300
300
  ${o.join(`
301
- `)}`,_pinned:!0,_progressSnapshot:!0}}var vo={msgCount:-1,lastMsgRef:null,result:null};function jE(){vo={msgCount:-1,lastMsgRef:null,result:null},Pt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function DE(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&vo.result&&t.length===vo.msgCount&&o===vo.lastMsgRef)return vo.result;let s=n.threshold??_g(),r=n.safetyMargin??yg,i=n.keepRecent??bg,a=ka(),l=$a(e),c=Math.floor(a*(s-r)),u=c-l,d=mn(t);if(d+l<=c){let se={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return vo={msgCount:t.length,lastMsgRef:o,result:se},se}let h=d,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let _=Math.max(g,t.length-i),k=t.slice(g,_),$=t.slice(_),O=k.map(se=>Eo(se,"light")),E=rs(m,O,$),T=mn(E);if(T+l<=c)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-T};if(O=k.map(se=>Eo(se,"medium")),E=rs(m,O,$),T=mn(E),T+l<=c)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-T};if(O=k.map(se=>Eo(se,"aggressive")),E=rs(m,O,$),T=mn(E),T+l<=c)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-T};let q=process.env.NEX_SKIP_COMPACTOR==="1",ee=k.filter(se=>se._pinned),te=k.filter(se=>!se._compacted&&!se._pinned);if(!q&&te.length>=6)try{let{compactMessages:se}=hu(),ie=await se(te);if(ie){let Be=k.filter(Ke=>Ke._compacted&&!Ke._pinned),Re=[...ee,...Be,ie.message],W=rs(m,Re,$),ne=mn(W);if(ne+l<=c)return{messages:W,compressed:!0,compacted:!0,tokensRemoved:h-ne};k=Re}}catch(se){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",se.message)}let K=xg([...O,...$]),ae=O.map((se,ie)=>({msg:se,score:se._pinned?1/0:kg(se,ie,O.length,K),tokens:Is(se)}));for(;ae.length>0&&T>u;){let se=-1;for(let ie=0;ie<ae.length;ie++)ae[ie].score!==1/0&&(se===-1||ae[ie].score<ae[se].score)&&(se=ie);if(se===-1)break;T-=ae[se].tokens,ae.splice(se,1)}return O=ae.map(se=>se.msg),E=rs(m,O,$),T=mn(E),{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-T}}function rs(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function qE(t,e){if(!t)return"";if(Ls(t)<=e)return t;let o=e*4,s=t.split(`
301
+ `)}`,_pinned:!0,_progressSnapshot:!0}}var Eo={msgCount:-1,lastMsgRef:null,result:null};function FE(){Eo={msgCount:-1,lastMsgRef:null,result:null},Pt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function BE(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&Eo.result&&t.length===Eo.msgCount&&o===Eo.lastMsgRef)return Eo.result;let s=n.threshold??kg(),r=n.safetyMargin??wg,i=n.keepRecent??_g,a=xa(),l=ka(e),c=Math.floor(a*(s-r)),u=c-l,d=mn(t);if(d+l<=c){let se={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Eo={msgCount:t.length,lastMsgRef:o,result:se},se}let h=d,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let _=Math.max(g,t.length-i),k=t.slice(g,_),$=t.slice(_),O=k.map(se=>To(se,"light")),E=rs(m,O,$),T=mn(E);if(T+l<=c)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-T};if(O=k.map(se=>To(se,"medium")),E=rs(m,O,$),T=mn(E),T+l<=c)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-T};if(O=k.map(se=>To(se,"aggressive")),E=rs(m,O,$),T=mn(E),T+l<=c)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-T};let q=process.env.NEX_SKIP_COMPACTOR==="1",ee=k.filter(se=>se._pinned),te=k.filter(se=>!se._compacted&&!se._pinned);if(!q&&te.length>=6)try{let{compactMessages:se}=gu(),ie=await se(te);if(ie){let Be=k.filter(Ve=>Ve._compacted&&!Ve._pinned),Ce=[...ee,...Be,ie.message],H=rs(m,Ce,$),ne=mn(H);if(ne+l<=c)return{messages:H,compressed:!0,compacted:!0,tokensRemoved:h-ne};k=Ce}}catch(se){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",se.message)}let K=vg([...O,...$]),ae=O.map((se,ie)=>({msg:se,score:se._pinned?1/0:Sg(se,ie,O.length,K),tokens:js(se)}));for(;ae.length>0&&T>u;){let se=-1;for(let ie=0;ie<ae.length;ie++)ae[ie].score!==1/0&&(se===-1||ae[ie].score<ae[se].score)&&(se=ie);if(se===-1)break;T-=ae[se].tokens,ae.splice(se,1)}return O=ae.map(se=>se.msg),E=rs(m,O,$),T=mn(E),{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-T}}function rs(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function UE(t,e){if(!t)return"";if(Is(t)<=e)return t;let o=e*4,s=t.split(`
302
302
  `),r=Math.floor(o*.6),i=Math.floor(o*.4),a="",l=0;for(let h of s){if(a.length+h.length+1>r)break;a+=(a?`
303
303
  `:"")+h,l++}let c="",u=0;for(let h=s.length-1;h>=l;h--){let m=s[h]+(c?`
304
304
  `:"")+c;if(m.length>i)break;c=m,u++}let f=`
305
305
 
306
306
  ... (${s.length-l-u} lines omitted, ${s.length} total) ...
307
307
 
308
- `;return a+f+c}var FE=6;function BE(t,e,n=!1){let o=ka(),s=$a(e),r=Math.floor(o*(n?.35:.5))-s,i=mn(t),a=Math.floor(i*(n?.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=n?2:FE,d=Math.max(c,t.length-u),f=t.slice(c,d),h=t.slice(d),m=f.map(T=>Eo(T,"aggressive"));n&&(h=h.map(T=>Eo(T,"aggressive")));let g=rs(l,m,h),_=mn(g);for(;m.length>0&&_>r;){let T=m.shift();_-=Is(T)}n&&_>r&&(h=h.filter(q=>q.role==="user").slice(-1),g=rs(l,[],h),_=mn(g)),g=rs(l,m,h);let k=t.filter(T=>T.role==="user"),$=T=>{let q=typeof T.content=="string"?T.content:"";return q.startsWith("[SYSTEM WARNING]")||q.startsWith("[SYSTEM:")||q.startsWith("BLOCKED:")},O=k.find(T=>!$(T)),E=[...k].reverse().find(T=>!$(T));if(O&&!g.find(T=>T===O)){let T=g.findIndex(ee=>ee.role==="system"),q=T>=0?T+1:0;g.splice(q,0,O)}return E&&E!==O&&!g.find(T=>T===E)&&g.push(E),{messages:g,tokensRemoved:i-mn(g)}}Sg.exports={estimateTokens:Ls,estimateMessageTokens:Is,estimateMessagesTokens:mn,estimateDeltaTokens:PE,estimateToolsTokens:$a,serializeMessage:OE,getContextWindow:ka,getUsage:NE,compressMessage:Eo,compressToolResult:$g,scoreMessageRelevance:kg,extractActiveFiles:xg,buildProgressSnapshot:IE,fitToContext:DE,forceCompress:BE,truncateFileContent:qE,invalidateTokenRatioCache:AE,invalidateFitToContextCache:jE,getEffectiveCompressionThreshold:_g,COMPRESSION_THRESHOLD:_r,TIER_COMPRESSION_THRESHOLDS:wg,SAFETY_MARGIN:yg,KEEP_RECENT:bg}});var Su=J((KP,Dg)=>{var dt=require("fs"),Gn=require("path"),{atomicWrite:vg,withFileLockSync:Eg}=Ss(),UE=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 Ro(){let t=Gn.join(process.cwd(),".nex","brain");return dt.existsSync(t)||dt.mkdirSync(t,{recursive:!0}),t}function Sa(){return Gn.join(Ro(),".brain-index.json")}function wu(){return Gn.join(Ro(),".embeddings.json")}function $r(){let t=Gn.join(process.cwd(),".nex","brain");if(!dt.existsSync(t))return[];try{return dt.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=Gn.join(t,e),o=dt.statSync(n);return{name:e.replace(/\.md$/,""),path:n,size:o.size,modified:new Date(o.mtimeMs)}}).sort((e,n)=>n.modified-e.modified)}catch{return[]}}function kr(t){let e={},n=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let s=o[1].split(`
309
- `);for(let r of s){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[a]=l.slice(1,-1).split(",").map(c=>c.trim()).filter(Boolean):e[a]=l}n=o[2]}return{frontmatter:e,body:n}}function Tg(t){let e=Gn.join(Ro(),`${t}.md`);if(!dt.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=dt.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=kr(n);return{name:t,content:n,body:s,frontmatter:o}}function WE(t,e){let n=Gn.join(Ro(),`${t}.md`);vg(n,e),YE(t,e),HE()}function HE(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=wu();dt.existsSync(t)&&setImmediate(async()=>{try{await Mg()}catch{}})}function GE(t){let e=Gn.join(Ro(),`${t}.md`);return dt.existsSync(e)?(dt.unlinkSync(e),zE(t),!0):!1}function xa(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!UE.has(e))}function _u(t){let e={},{frontmatter:n,body:o}=kr(t),s=Array.isArray(n.tags)?n.tags:[];for(let i of s){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(o||t).split(`
310
- `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of xa(a))e[l]=(e[l]||0)+3}for(let i of xa(o||t))e[i]=(e[i]||0)+1;return e}function $u(){let t=Sa();if(!dt.existsSync(t))return{documents:{}};try{return JSON.parse(dt.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function ku(t){vg(Sa(),JSON.stringify(t,null,2))}function YE(t,e){Eg(Sa(),()=>{let n=$u(),{frontmatter:o}=kr(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:_u(e),tags:s,modified:new Date().toISOString()},ku(n)})}function zE(t){Eg(Sa(),()=>{let e=$u();delete e.documents[t],ku(e)})}function bu(){let t=$r(),e={documents:{}};for(let n of t){let o=dt.readFileSync(n.path,"utf-8"),{frontmatter:s}=kr(o),r=Array.isArray(s.tags)?s.tags:[];e.documents[n.name]={keywords:_u(o),tags:r,modified:n.modified.toISOString()}}return ku(e),e}function Rg(){let t=$u(),e=$r();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return bu()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return bu();return t}function Cg(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=xa(t);if(s.length===0)return[];let r=Rg(),i=[];for(let[a,l]of Object.entries(r.documents)){let c=0;for(let u of s){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,n)}var Ag=process.env.NEX_EMBED_MODEL||"nomic-embed-text",yu=400,KE=50;async function Og(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),n=require("https"),o=new URL(`${t}/api/tags`),s=o.protocol==="https:"?n:e;return((await new Promise((a,l)=>{let c=s.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(Ag.split(":")[0]))}catch{return!1}}async function xu(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",n=require("http"),o=require("https"),s=new URL(`${e}/api/embeddings`),r=s.protocol==="https:"?o:n,i=JSON.stringify({model:Ag,prompt:t});return new Promise((a,l)=>{let c=r.request(s,{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 Pg(t,e){if(!t||!e||t.length!==e.length)return 0;let n=0,o=0,s=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],o+=t[i]*t[i],s+=e[i]*e[i];let r=Math.sqrt(o)*Math.sqrt(s);return r===0?0:n/r}function Ng(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+yu).join(" ");if(n.push({text:s,offset:o}),o+yu>=e.length)break;o+=yu-KE}return n}async function Mg(){let t=$r(),e={documents:{}},n=wu();if(dt.existsSync(n))try{e=JSON.parse(dt.readFileSync(n,"utf-8"))}catch{}for(let o of t){let s=e.documents[o.name];if(s&&new Date(s.modified)>=o.modified)continue;let r=dt.readFileSync(o.path,"utf-8"),i=Ng(r),a=[];for(let l of i){let c=await xu(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(s=>s.name===o)||delete e.documents[o];return dt.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function Lg(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=wu();if(!dt.existsSync(s))return[];let r;try{r=JSON.parse(dt.readFileSync(s,"utf-8"))}catch{return[]}let i=await xu(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let h=Pg(i,f.embedding);h>u&&(u=h,d=f.text)}u>=o&&a.push({name:l,score:u,bestChunk:d})}return a.sort((l,c)=>c.score-l.score),a.slice(0,n)}function Ig(t,e,n={}){let{k:o=60,topK:s=3}=n,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,s)}async function jg(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=Cg(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Og()){let a=await Lg(t,{topK:n});r=Ig(s,a,{topK:n})}}catch{}return r.map(i=>{let a=Tg(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 To={queryKey:null,result:null,ts:0},VE=3e5;async function XE(t){if(!t||!t.trim())return"";let e=Gn.join(process.cwd(),".nex","brain");if(!dt.existsSync(e)||$r().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(To.result!==null&&To.queryKey===o&&Date.now()-To.ts<VE)return To.result;let s;try{s=await jg(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=Pn().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],l=0;for(let u of s){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))+`
308
+ `;return a+f+c}var WE=6;function HE(t,e,n=!1){let o=xa(),s=ka(e),r=Math.floor(o*(n?.35:.5))-s,i=mn(t),a=Math.floor(i*(n?.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=n?2:WE,d=Math.max(c,t.length-u),f=t.slice(c,d),h=t.slice(d),m=f.map(T=>To(T,"aggressive"));n&&(h=h.map(T=>To(T,"aggressive")));let g=rs(l,m,h),_=mn(g);for(;m.length>0&&_>r;){let T=m.shift();_-=js(T)}n&&_>r&&(h=h.filter(q=>q.role==="user").slice(-1),g=rs(l,[],h),_=mn(g)),g=rs(l,m,h);let k=t.filter(T=>T.role==="user"),$=T=>{let q=typeof T.content=="string"?T.content:"";return q.startsWith("[SYSTEM WARNING]")||q.startsWith("[SYSTEM:")||q.startsWith("BLOCKED:")},O=k.find(T=>!$(T)),E=[...k].reverse().find(T=>!$(T));if(O&&!g.find(T=>T===O)){let T=g.findIndex(ee=>ee.role==="system"),q=T>=0?T+1:0;g.splice(q,0,O)}return E&&E!==O&&!g.find(T=>T===E)&&g.push(E),{messages:g,tokensRemoved:i-mn(g)}}Eg.exports={estimateTokens:Is,estimateMessageTokens:js,estimateMessagesTokens:mn,estimateDeltaTokens:LE,estimateToolsTokens:ka,serializeMessage:ME,getContextWindow:xa,getUsage:IE,compressMessage:To,compressToolResult:xg,scoreMessageRelevance:Sg,extractActiveFiles:vg,buildProgressSnapshot:qE,fitToContext:BE,forceCompress:HE,truncateFileContent:UE,invalidateTokenRatioCache:NE,invalidateFitToContextCache:FE,getEffectiveCompressionThreshold:kg,COMPRESSION_THRESHOLD:$r,TIER_COMPRESSION_THRESHOLDS:$g,SAFETY_MARGIN:wg,KEEP_RECENT:_g}});var Eu=J((ZP,Fg)=>{var ft=require("fs"),Gn=require("path"),{atomicWrite:Tg,withFileLockSync:Rg}=vs(),GE=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 Co(){let t=Gn.join(process.cwd(),".nex","brain");return ft.existsSync(t)||ft.mkdirSync(t,{recursive:!0}),t}function va(){return Gn.join(Co(),".brain-index.json")}function $u(){return Gn.join(Co(),".embeddings.json")}function kr(){let t=Gn.join(process.cwd(),".nex","brain");if(!ft.existsSync(t))return[];try{return ft.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=Gn.join(t,e),o=ft.statSync(n);return{name:e.replace(/\.md$/,""),path:n,size:o.size,modified:new Date(o.mtimeMs)}}).sort((e,n)=>n.modified-e.modified)}catch{return[]}}function xr(t){let e={},n=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let s=o[1].split(`
309
+ `);for(let r of s){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[a]=l.slice(1,-1).split(",").map(c=>c.trim()).filter(Boolean):e[a]=l}n=o[2]}return{frontmatter:e,body:n}}function Cg(t){let e=Gn.join(Co(),`${t}.md`);if(!ft.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=ft.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=xr(n);return{name:t,content:n,body:s,frontmatter:o}}function YE(t,e){let n=Gn.join(Co(),`${t}.md`);Tg(n,e),VE(t,e),zE()}function zE(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=$u();ft.existsSync(t)&&setImmediate(async()=>{try{await Ig()}catch{}})}function KE(t){let e=Gn.join(Co(),`${t}.md`);return ft.existsSync(e)?(ft.unlinkSync(e),XE(t),!0):!1}function Sa(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!GE.has(e))}function ku(t){let e={},{frontmatter:n,body:o}=xr(t),s=Array.isArray(n.tags)?n.tags:[];for(let i of s){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(o||t).split(`
310
+ `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of Sa(a))e[l]=(e[l]||0)+3}for(let i of Sa(o||t))e[i]=(e[i]||0)+1;return e}function xu(){let t=va();if(!ft.existsSync(t))return{documents:{}};try{return JSON.parse(ft.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Su(t){Tg(va(),JSON.stringify(t,null,2))}function VE(t,e){Rg(va(),()=>{let n=xu(),{frontmatter:o}=xr(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:ku(e),tags:s,modified:new Date().toISOString()},Su(n)})}function XE(t){Rg(va(),()=>{let e=xu();delete e.documents[t],Su(e)})}function _u(){let t=kr(),e={documents:{}};for(let n of t){let o=ft.readFileSync(n.path,"utf-8"),{frontmatter:s}=xr(o),r=Array.isArray(s.tags)?s.tags:[];e.documents[n.name]={keywords:ku(o),tags:r,modified:n.modified.toISOString()}}return Su(e),e}function Ag(){let t=xu(),e=kr();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return _u()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return _u();return t}function Og(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=Sa(t);if(s.length===0)return[];let r=Ag(),i=[];for(let[a,l]of Object.entries(r.documents)){let c=0;for(let u of s){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,n)}var Pg=process.env.NEX_EMBED_MODEL||"nomic-embed-text",wu=400,JE=50;async function Ng(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),n=require("https"),o=new URL(`${t}/api/tags`),s=o.protocol==="https:"?n:e;return((await new Promise((a,l)=>{let c=s.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(Pg.split(":")[0]))}catch{return!1}}async function vu(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",n=require("http"),o=require("https"),s=new URL(`${e}/api/embeddings`),r=s.protocol==="https:"?o:n,i=JSON.stringify({model:Pg,prompt:t});return new Promise((a,l)=>{let c=r.request(s,{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 Mg(t,e){if(!t||!e||t.length!==e.length)return 0;let n=0,o=0,s=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],o+=t[i]*t[i],s+=e[i]*e[i];let r=Math.sqrt(o)*Math.sqrt(s);return r===0?0:n/r}function Lg(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+wu).join(" ");if(n.push({text:s,offset:o}),o+wu>=e.length)break;o+=wu-JE}return n}async function Ig(){let t=kr(),e={documents:{}},n=$u();if(ft.existsSync(n))try{e=JSON.parse(ft.readFileSync(n,"utf-8"))}catch{}for(let o of t){let s=e.documents[o.name];if(s&&new Date(s.modified)>=o.modified)continue;let r=ft.readFileSync(o.path,"utf-8"),i=Lg(r),a=[];for(let l of i){let c=await vu(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(s=>s.name===o)||delete e.documents[o];return ft.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function jg(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=$u();if(!ft.existsSync(s))return[];let r;try{r=JSON.parse(ft.readFileSync(s,"utf-8"))}catch{return[]}let i=await vu(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let h=Mg(i,f.embedding);h>u&&(u=h,d=f.text)}u>=o&&a.push({name:l,score:u,bestChunk:d})}return a.sort((l,c)=>c.score-l.score),a.slice(0,n)}function Dg(t,e,n={}){let{k:o=60,topK:s=3}=n,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,s)}async function qg(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=Og(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Ng()){let a=await jg(t,{topK:n});r=Dg(s,a,{topK:n})}}catch{}return r.map(i=>{let a=Cg(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 Ro={queryKey:null,result:null,ts:0},ZE=3e5;async function QE(t){if(!t||!t.trim())return"";let e=Gn.join(process.cwd(),".nex","brain");if(!ft.existsSync(e)||kr().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(Ro.result!==null&&Ro.queryKey===o&&Date.now()-Ro.ts<ZE)return Ro.result;let s;try{s=await qg(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=Pn().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],l=0;for(let u of s){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))+`
311
311
  ...(truncated)`}let h=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${h}) ---
312
- ${d}`),l+=r(d),l>=i)break}if(a.length===0)return To={queryKey:o,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
312
+ ${d}`),l+=r(d),l>=i)break}if(a.length===0)return Ro={queryKey:o,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
313
313
 
314
314
  ${a.join(`
315
315
 
316
- `)}`;return To={queryKey:o,result:c,ts:Date.now()},c}Dg.exports={getBrainDir:Ro,listDocuments:$r,readDocument:Tg,writeDocument:WE,removeDocument:GE,buildIndex:bu,getIndex:Rg,query:jg,getBrainContext:XE,isEmbeddingAvailable:Og,generateEmbedding:xu,buildEmbeddingIndex:Mg,semanticQuery:Lg,cosineSimilarity:Pg,_keywordQuery:Cg,_extractKeywords:_u,_chunkText:Ng,parseFrontmatter:kr,tokenize:xa,_fuseResults:Ig}});var Sr=J((VP,Qg)=>{var et=require("fs"),qt=require("path"),JE=require("os"),{atomicWrite:va,withFileLockSync:qg}=Ss(),js=["user","feedback","project","reference"],ZE=50;function Ds(){return qt.join(process.cwd(),".nex","memory")}function Co(){return qt.join(Ds(),"memory.json")}function Fg(){return qt.join(Ds(),"MEMORY.md")}function QE(){return qt.join(process.cwd(),"NEX.md")}function Bg(){return qt.join(JE.homedir(),".nex","NEX.md")}function Ea(){let t=Ds();et.existsSync(t)||et.mkdirSync(t,{recursive:!0})}function Ug(t){let e=qt.join(Ds(),t);return et.existsSync(e)||et.mkdirSync(e,{recursive:!0}),e}function xr(){let t=Co();if(!et.existsSync(t))return{};try{return JSON.parse(et.readFileSync(t,"utf-8"))}catch{return{}}}function Wg(t){Ea(),va(Co(),JSON.stringify(t,null,2))}function Hg(){let t=Co();if(!et.existsSync(t))return;let e=xr(),n=Object.keys(e);if(n.length===0){try{et.renameSync(t,t+".bak")}catch{}return}for(let o of n){let s=e[o],r=s.value||String(s),i=o.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=Ug("project"),l=qt.join(a,`${i}.md`),c=r.split(`
316
+ `)}`;return Ro={queryKey:o,result:c,ts:Date.now()},c}Fg.exports={getBrainDir:Co,listDocuments:kr,readDocument:Cg,writeDocument:YE,removeDocument:KE,buildIndex:_u,getIndex:Ag,query:qg,getBrainContext:QE,isEmbeddingAvailable:Ng,generateEmbedding:vu,buildEmbeddingIndex:Ig,semanticQuery:jg,cosineSimilarity:Mg,_keywordQuery:Og,_extractKeywords:ku,_chunkText:Lg,parseFrontmatter:xr,tokenize:Sa,_fuseResults:Dg}});var vr=J((QP,ty)=>{var et=require("fs"),qt=require("path"),eT=require("os"),{atomicWrite:Ea,withFileLockSync:Bg}=vs(),Ds=["user","feedback","project","reference"],tT=50;function qs(){return qt.join(process.cwd(),".nex","memory")}function Ao(){return qt.join(qs(),"memory.json")}function Ug(){return qt.join(qs(),"MEMORY.md")}function nT(){return qt.join(process.cwd(),"NEX.md")}function Wg(){return qt.join(eT.homedir(),".nex","NEX.md")}function Ta(){let t=qs();et.existsSync(t)||et.mkdirSync(t,{recursive:!0})}function Hg(t){let e=qt.join(qs(),t);return et.existsSync(e)||et.mkdirSync(e,{recursive:!0}),e}function Sr(){let t=Ao();if(!et.existsSync(t))return{};try{return JSON.parse(et.readFileSync(t,"utf-8"))}catch{return{}}}function Gg(t){Ta(),Ea(Ao(),JSON.stringify(t,null,2))}function Yg(){let t=Ao();if(!et.existsSync(t))return;let e=Sr(),n=Object.keys(e);if(n.length===0){try{et.renameSync(t,t+".bak")}catch{}return}for(let o of n){let s=e[o],r=s.value||String(s),i=o.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=Hg("project"),l=qt.join(a,`${i}.md`),c=r.split(`
317
317
  `)[0].slice(0,100),u=`---
318
318
  name: ${o}
319
319
  description: ${c}
@@ -321,7 +321,7 @@ type: project
321
321
  ---
322
322
 
323
323
  ${r}
324
- `;va(l,u)}Ta();try{et.renameSync(t,t+".bak")}catch{}}function eT(t,e,n,o){if(!js.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${js.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!n||typeof n!="string"||n.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!s)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=Ug(t),i=qt.join(r,`${s}.md`);if(et.existsSync(i))try{if(Eu(et.readFileSync(i,"utf-8")).body.slice(0,200)===n.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=o||n.split(`
324
+ `;Ea(l,u)}Ra();try{et.renameSync(t,t+".bak")}catch{}}function sT(t,e,n,o){if(!Ds.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Ds.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!n||typeof n!="string"||n.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!s)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=Hg(t),i=qt.join(r,`${s}.md`);if(et.existsSync(i))try{if(Ru(et.readFileSync(i,"utf-8")).body.slice(0,200)===n.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=o||n.split(`
325
325
  `)[0].slice(0,100),l=`---
326
326
  name: ${e}
327
327
  description: ${a}
@@ -329,53 +329,53 @@ type: ${t}
329
329
  ---
330
330
 
331
331
  ${n}
332
- `;return va(i,l),Ta(),{ok:!0,path:i,updated:!0}}function tT(t,e){if(!js.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=qt.join(Ds(),t,`${n}.md`);if(!et.existsSync(o))return!1;try{return et.unlinkSync(o),Ta(),!0}catch{return!1}}function Eu(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let n=e[1],o=(e[2]||"").trim(),s=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:s("name"),description:s("description"),type:s("type"),body:o}}function Gg({includeBody:t=!1}={}){let e=[],n=Ds();for(let o of js){let s=qt.join(n,o);if(!et.existsSync(s))continue;let r;try{r=et.readdirSync(s).filter(i=>i.endsWith(".md"))}catch{continue}for(let i of r){let a=qt.join(s,i);try{let l=et.readFileSync(a,"utf-8"),c=Eu(l),u=null;try{u=et.statSync(a)}catch{u=null}let d={type:o,name:c.name||qt.basename(i,".md"),description:c.description,filePath:a,updatedAt:u?u.mtimeMs:0};t&&(d.body=c.body),e.push(d)}catch{}}}return e}function Yg(){return Gg()}function zg(t){return String(t||"").replace(/\s+/g," ").trim()}function nT(t,e){let n=zg(t);return n.length<=e?n:n.slice(0,Math.max(0,e-15)).trimEnd()+" [truncated]"}function vu(t,e,n){return t.join(`
333
- `).length+e.length+1>n?!1:(t.push(e),!0)}function Kg(t){if(t<=200)return"";let e=Vg(),n=Gg({includeBody:!0});if(!e&&n.length===0){let r=Xg();if(r.length===0)return"";let i=["PROJECT MEMORY:"];for(let a of r)if(!vu(i,` ${a.key}: ${a.value}`,t)){i.push("[Memory truncated - use delete_memory to prune old entries]");break}return i.join(`
332
+ `;return Ea(i,l),Ra(),{ok:!0,path:i,updated:!0}}function oT(t,e){if(!Ds.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=qt.join(qs(),t,`${n}.md`);if(!et.existsSync(o))return!1;try{return et.unlinkSync(o),Ra(),!0}catch{return!1}}function Ru(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let n=e[1],o=(e[2]||"").trim(),s=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:s("name"),description:s("description"),type:s("type"),body:o}}function zg({includeBody:t=!1}={}){let e=[],n=qs();for(let o of Ds){let s=qt.join(n,o);if(!et.existsSync(s))continue;let r;try{r=et.readdirSync(s).filter(i=>i.endsWith(".md"))}catch{continue}for(let i of r){let a=qt.join(s,i);try{let l=et.readFileSync(a,"utf-8"),c=Ru(l),u=null;try{u=et.statSync(a)}catch{u=null}let d={type:o,name:c.name||qt.basename(i,".md"),description:c.description,filePath:a,updatedAt:u?u.mtimeMs:0};t&&(d.body=c.body),e.push(d)}catch{}}}return e}function Kg(){return zg()}function Vg(t){return String(t||"").replace(/\s+/g," ").trim()}function rT(t,e){let n=Vg(t);return n.length<=e?n:n.slice(0,Math.max(0,e-15)).trimEnd()+" [truncated]"}function Tu(t,e,n){return t.join(`
333
+ `).length+e.length+1>n?!1:(t.push(e),!0)}function Xg(t){if(t<=200)return"";let e=Jg(),n=zg({includeBody:!0});if(!e&&n.length===0){let r=Zg();if(r.length===0)return"";let i=["PROJECT MEMORY:"];for(let a of r)if(!Tu(i,` ${a.key}: ${a.value}`,t)){i.push("[Memory truncated - use delete_memory to prune old entries]");break}return i.join(`
334
334
  `)}let o=[];if(e){let r=Math.max(350,Math.floor(t*.45)),i=e.split(`
335
- `);for(let a of i)if(!vu(o,a,r)){o.push("[Memory index truncated - use delete_memory to prune old entries]");break}}let s=n.filter(r=>zg(r.body).length>0).sort((r,i)=>{let a=js.indexOf(r.type)-js.indexOf(i.type);return a!==0?a:(i.updatedAt||0)-(r.updatedAt||0)});if(s.length>0&&o.join(`
335
+ `);for(let a of i)if(!Tu(o,a,r)){o.push("[Memory index truncated - use delete_memory to prune old entries]");break}}let s=n.filter(r=>Vg(r.body).length>0).sort((r,i)=>{let a=Ds.indexOf(r.type)-Ds.indexOf(i.type);return a!==0?a:(i.updatedAt||0)-(r.updatedAt||0)});if(s.length>0&&o.join(`
336
336
  `).length<t-220){o.length>0&&o.push(""),o.push("ACTIVE MEMORY EXCERPTS:");for(let r of s){let i=t-o.join(`
337
- `).length-1;if(i<180)break;let a=Math.min(520,Math.max(120,i-90)),l=`${r.type}/${qt.basename(r.filePath)}`,c=r.description?` - ${r.description}`:"",u=nT(r.body,a),d=`- ${r.name} (${l})${c}: ${u}`;if(!vu(o,d,t))break}}return o.length===0?"":o.join(`
338
- `)}function Ta(){let t=Yg(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=ZE+2)break;let o=`${n.type}/${qt.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Ea(),va(Fg(),e.join(`
337
+ `).length-1;if(i<180)break;let a=Math.min(520,Math.max(120,i-90)),l=`${r.type}/${qt.basename(r.filePath)}`,c=r.description?` - ${r.description}`:"",u=rT(r.body,a),d=`- ${r.name} (${l})${c}: ${u}`;if(!Tu(o,d,t))break}}return o.length===0?"":o.join(`
338
+ `)}function Ra(){let t=Kg(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=tT+2)break;let o=`${n.type}/${qt.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Ta(),Ea(Ug(),e.join(`
339
339
  `)+`
340
- `)}function Vg(){let t=Fg();if(!et.existsSync(t))return"";try{return et.readFileSync(t,"utf-8").trim()}catch{return""}}function sT(t,e){Ea(),qg(Co(),()=>{let n=xr();n[t]={value:e,updatedAt:new Date().toISOString()},Wg(n)})}function oT(t){let e=xr();return e[t]?e[t].value:null}function rT(t){return Ea(),qg(Co(),()=>{let e=xr();return t in e?(delete e[t],Wg(e),!0):!1})}function Xg(){let t=xr();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function Jg(){let t=Bg();if(!et.existsSync(t))return"";try{return et.readFileSync(t,"utf-8").trim()}catch{return""}}function Zg(){let t=QE();if(!et.existsSync(t))return"";try{return et.readFileSync(t,"utf-8").trim()}catch{return""}}function iT(){Hg();let t=[],e=Jg();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
341
- ${e}`);let n=Zg();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
340
+ `)}function Jg(){let t=Ug();if(!et.existsSync(t))return"";try{return et.readFileSync(t,"utf-8").trim()}catch{return""}}function iT(t,e){Ta(),Bg(Ao(),()=>{let n=Sr();n[t]={value:e,updatedAt:new Date().toISOString()},Gg(n)})}function aT(t){let e=Sr();return e[t]?e[t].value:null}function lT(t){return Ta(),Bg(Ao(),()=>{let e=Sr();return t in e?(delete e[t],Gg(e),!0):!1})}function Zg(){let t=Sr();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function Qg(){let t=Wg();if(!et.existsSync(t))return"";try{return et.readFileSync(t,"utf-8").trim()}catch{return""}}function ey(){let t=nT();if(!et.existsSync(t))return"";try{return et.readFileSync(t,"utf-8").trim()}catch{return""}}function cT(){Yg();let t=[],e=Qg();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
341
+ ${e}`);let n=ey();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
342
342
  ${n}`);let o=t.join(`
343
343
 
344
- `),s="You can save insights with save_memory(type, name, content) and remove them with delete_memory(type, name).",a=Math.max(1500,16e3-o.length-s.length-10),l=Kg(a),c=[...t];return l&&c.push(l),c.length>0&&c.push(s),c.join(`
344
+ `),s="You can save insights with save_memory(type, name, content) and remove them with delete_memory(type, name).",a=Math.max(1500,16e3-o.length-s.length-10),l=Xg(a),c=[...t];return l&&c.push(l),c.length>0&&c.push(s),c.join(`
345
345
 
346
- `)}Qg.exports={saveMemory:eT,deleteMemory:tT,scanMemories:Yg,rebuildIndex:Ta,loadMemoryIndex:Vg,remember:sT,recall:oT,forget:rT,listMemories:Xg,loadGlobalInstructions:Jg,loadProjectInstructions:Zg,getMemoryContext:iT,_getMemoryDir:Ds,_getMemoryFile:Co,_getGlobalNexMdPath:Bg,_parseMemoryFile:Eu,_buildMemoryPromptSection:Kg,_migrateIfNeeded:Hg,VALID_TYPES:js}});var ry=J((XP,oy)=>{var vr=require("fs"),Tu=require("path"),Ru=process.env.NEX_AUDIT!=="false",qs=null;function ey(){return qs||(qs=Tu.join(process.cwd(),".nex","audit"),vr.existsSync(qs)||vr.mkdirSync(qs,{recursive:!0}),qs)}function ty(){let t=new Date().toISOString().split("T")[0];return Tu.join(ey(),`${t}.jsonl`)}function aT(t){if(Ru)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:ny(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},n=JSON.stringify(e)+`
347
- `;vr.appendFileSync(ty(),n,"utf-8")}catch{}}function ny(t){if(!t||typeof t!="object")return{};let e={};for(let[n,o]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof o=="string"&&o.length>500?e[n]=o.substring(0,500)+`... (${o.length} chars)`:e[n]=o;return e}function sy(t={}){let e=ey(),n=t.days||1,o=[];for(let s=0;s<n;s++){let r=t.date||new Date(Date.now()-s*864e5).toISOString().split("T")[0],i=Tu.join(e,`${r}.jsonl`);if(!vr.existsSync(i))continue;let a=vr.readFileSync(i,"utf-8").split(`
348
- `).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 lT(t=1){let e=sy({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},o=0,s=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,o+=r.duration||0,r.success&&s++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(o/e.length),successRate:s/e.length}}function cT(t){Ru=t}function uT(){return Ru}function dT(){qs=null}oy.exports={logToolExecution:aT,sanitizeArgs:ny,readAuditLog:sy,getAuditSummary:lT,setAuditEnabled:cT,isAuditEnabled:uT,getAuditLogPath:ty,_reset:dT}});var vy=J((ZP,Sy)=>{var ft=require("fs").promises,yn=require("fs"),re=require("path"),lt=require("util").promisify(require("child_process").exec),Fs=require("util").promisify(require("child_process").execFile),{spawnSync:fT}=require("child_process"),Cu=require("axios"),{isForbidden:pT,isSSHForbidden:hT,isDangerous:mT,isCritical:iy,isBashPathForbidden:gT,confirm:gn}=or(),{showDiff:Ra,showNewFile:yT,showEditDiff:JP,confirmFileChange:Er}=Lp(),{C:fe,Spinner:bT,getToolSpinnerText:wT}=_t(),{ToolProgress:Ca}=vs(),{isGitRepo:Au,getCurrentBranch:ay,getStatus:_T,getDiff:$T}=Ji(),{recordChange:Aa}=Yp(),{fuzzyFindText:ly,findMostSimilar:Or}=gh(),{runDiagnostics:Tr}=Th(),{findFileInIndex:kT,getFileIndex:cy,searchContentIndex:xT,scorePathMatch:uy,refreshIndex:ST,isIndexValid:vT}=Rn(),{resolveProfile:nn,sshExec:Nt,scpUpload:ET,scpDownload:dy}=$o(),{resolveDeployConfig:TT,loadDeployConfigs:RT}=Kh(),{getEditMode:fy}=mr(),CT=/^(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/,AT=/^ssh\s/,OT=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/,PT=new Set(["assert","buffer","child_process","cluster","crypto","dns","events","fs","http","https","module","net","os","path","perf_hooks","process","querystring","readline","stream","timers","tls","tty","url","util","vm","zlib"]);function yy(t){let n=String(t||"").match(/\b(?:npm\s+(?:install|i|add)|yarn\s+add|pnpm\s+(?:add|install))\s+([^;&|]+)/i);return n&&n[1].split(/\s+/).map(s=>s.trim()).filter(s=>s&&!s.startsWith("-")&&!s.includes("=")&&s!=="."&&s!=="./").map(s=>s.replace(/^node:/,"").replace(/@[^/]+$/,"")).find(s=>PT.has(s))||null}async function Gt(t){return ft.access(t).then(()=>!0).catch(()=>!1)}var Oa=null,py=0,NT=12e4;function MT(){let t=Date.now();if(Oa&&t-py<NT)return Oa;let e=re.dirname(process.cwd());try{let n=yn.readdirSync(e,{withFileTypes:!0}),o=re.basename(process.cwd()),s=n.filter(r=>r.isDirectory()&&r.name!==o&&!r.name.startsWith(".")).map(r=>r.name).sort();return Oa=s.length>0?s:null,py=t,Oa}catch{return null}}function Ou(t){if(t&&re.resolve(t)!==process.cwd())return"";let e=MT();if(!e)return"";let n=re.dirname(process.cwd());return`
346
+ `)}ty.exports={saveMemory:sT,deleteMemory:oT,scanMemories:Kg,rebuildIndex:Ra,loadMemoryIndex:Jg,remember:iT,recall:aT,forget:lT,listMemories:Zg,loadGlobalInstructions:Qg,loadProjectInstructions:ey,getMemoryContext:cT,_getMemoryDir:qs,_getMemoryFile:Ao,_getGlobalNexMdPath:Wg,_parseMemoryFile:Ru,_buildMemoryPromptSection:Xg,_migrateIfNeeded:Yg,VALID_TYPES:Ds}});var ay=J((eN,iy)=>{var Er=require("fs"),Cu=require("path"),Au=process.env.NEX_AUDIT!=="false",Fs=null;function ny(){return Fs||(Fs=Cu.join(process.cwd(),".nex","audit"),Er.existsSync(Fs)||Er.mkdirSync(Fs,{recursive:!0}),Fs)}function sy(){let t=new Date().toISOString().split("T")[0];return Cu.join(ny(),`${t}.jsonl`)}function uT(t){if(Au)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:oy(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},n=JSON.stringify(e)+`
347
+ `;Er.appendFileSync(sy(),n,"utf-8")}catch{}}function oy(t){if(!t||typeof t!="object")return{};let e={};for(let[n,o]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof o=="string"&&o.length>500?e[n]=o.substring(0,500)+`... (${o.length} chars)`:e[n]=o;return e}function ry(t={}){let e=ny(),n=t.days||1,o=[];for(let s=0;s<n;s++){let r=t.date||new Date(Date.now()-s*864e5).toISOString().split("T")[0],i=Cu.join(e,`${r}.jsonl`);if(!Er.existsSync(i))continue;let a=Er.readFileSync(i,"utf-8").split(`
348
+ `).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 dT(t=1){let e=ry({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},o=0,s=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,o+=r.duration||0,r.success&&s++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(o/e.length),successRate:s/e.length}}function fT(t){Au=t}function pT(){return Au}function hT(){Fs=null}iy.exports={logToolExecution:uT,sanitizeArgs:oy,readAuditLog:ry,getAuditSummary:dT,setAuditEnabled:fT,isAuditEnabled:pT,getAuditLogPath:sy,_reset:hT}});var Ty=J((nN,Ey)=>{var pt=require("fs").promises,yn=require("fs"),re=require("path"),lt=require("util").promisify(require("child_process").exec),Bs=require("util").promisify(require("child_process").execFile),{spawnSync:mT}=require("child_process"),Ou=require("axios"),{isForbidden:gT,isSSHForbidden:yT,isDangerous:bT,isCritical:ly,isBashPathForbidden:wT,confirm:gn}=rr(),{showDiff:Ca,showNewFile:_T,showEditDiff:tN,confirmFileChange:Tr}=jp(),{C:pe,Spinner:$T,getToolSpinnerText:kT}=$t(),{ToolProgress:Aa}=Es(),{isGitRepo:Pu,getCurrentBranch:cy,getStatus:xT,getDiff:ST}=Zi(),{recordChange:Oa}=Kp(),{fuzzyFindText:uy,findMostSimilar:Pr}=bh(),{runDiagnostics:Rr}=Ch(),{findFileInIndex:vT,getFileIndex:dy,searchContentIndex:ET,scorePathMatch:fy,refreshIndex:TT,isIndexValid:RT}=Rn(),{resolveProfile:sn,sshExec:Nt,scpUpload:CT,scpDownload:py}=ko(),{resolveDeployConfig:AT,loadDeployConfigs:OT}=Xh(),{getEditMode:hy}=gr(),PT=/^(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/,NT=/^ssh\s/,MT=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/,LT=new Set(["assert","buffer","child_process","cluster","crypto","dns","events","fs","http","https","module","net","os","path","perf_hooks","process","querystring","readline","stream","timers","tls","tty","url","util","vm","zlib"]);function wy(t){let n=String(t||"").match(/\b(?:npm\s+(?:install|i|add)|yarn\s+add|pnpm\s+(?:add|install))\s+([^;&|]+)/i);return n&&n[1].split(/\s+/).map(s=>s.trim()).filter(s=>s&&!s.startsWith("-")&&!s.includes("=")&&s!=="."&&s!=="./").map(s=>s.replace(/^node:/,"").replace(/@[^/]+$/,"")).find(s=>LT.has(s))||null}async function zt(t){return pt.access(t).then(()=>!0).catch(()=>!1)}var Pa=null,my=0,IT=12e4;function jT(){let t=Date.now();if(Pa&&t-my<IT)return Pa;let e=re.dirname(process.cwd());try{let n=yn.readdirSync(e,{withFileTypes:!0}),o=re.basename(process.cwd()),s=n.filter(r=>r.isDirectory()&&r.name!==o&&!r.name.startsWith(".")).map(r=>r.name).sort();return Pa=s.length>0?s:null,my=t,Pa}catch{return null}}function Nu(t){if(t&&re.resolve(t)!==process.cwd())return"";let e=jT();if(!e)return"";let n=re.dirname(process.cwd());return`
349
349
  Hint: no matches in current project. Sibling directories in ${n}/:
350
350
  ${e.join(", ")}
351
- You can search there with: grep pattern --path ${n}/<dir>`}async function Pa(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=xt(e);if(n&&await Gt(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=re.extname(t);if(!s)for(let i of o){let a=xt(t+i);if(a&&await Gt(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(s){let i=t.replace(/\.[^.]+$/,"");for(let a of o){if(a===s)continue;let l=xt(i+a);if(l&&await Gt(l))return{fixedPath:l,message:`(auto-fixed: ${s} \u2192 ${a})`}}}let r=re.basename(t);if(r&&r.length>2)try{let i=kT(r).map(a=>xt(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${re.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
351
+ You can search there with: grep pattern --path ${n}/<dir>`}async function Na(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=St(e);if(n&&await zt(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=re.extname(t);if(!s)for(let i of o){let a=St(t+i);if(a&&await zt(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(s){let i=t.replace(/\.[^.]+$/,"");for(let a of o){if(a===s)continue;let l=St(i+a);if(l&&await zt(l))return{fixedPath:l,message:`(auto-fixed: ${s} \u2192 ${a})`}}}let r=re.basename(t);if(r&&r.length>2)try{let i=vT(r).map(a=>St(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${re.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
352
352
  ${i.map(l=>re.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
353
- `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=Rn(),l=a().filter(c=>re.basename(c).toLowerCase()===i).map(c=>xt(c));if(l.length===1)return{fixedPath:l[0],message:`(auto-fixed: case-insensitive match \u2192 ${re.relative(process.cwd(),l[0])})`};if(l.length>1&&l.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
353
+ `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=Rn(),l=a().filter(c=>re.basename(c).toLowerCase()===i).map(c=>St(c));if(l.length===1)return{fixedPath:l[0],message:`(auto-fixed: case-insensitive match \u2192 ${re.relative(process.cwd(),l[0])})`};if(l.length>1&&l.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
354
354
  ${l.map(u=>re.relative(process.cwd(),u)).map(u=>` - ${u}`).join(`
355
- `)}`}}catch{}try{let{smartSearch:i}=Rn(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=xt(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 ${re.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 ${re.relative(process.cwd(),l)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
356
- ${a.map(u=>re.relative(process.cwd(),xt(u.file))).map(u=>` - ${u}`).join(`
357
- `)}`}}}catch{}return{fixedPath:null,message:""}}function LT(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 by(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e||/[()[\]{}|^$\\]/.test(e))return null;let n=e.replace(/\*\*/g," ").replace(/[*?]/g," ").replace(/[:=><!]+/g," ").replace(/\s+/g," ").trim();if(!n)return null;let o=n.split(/[\/\s,]+/).map(s=>s.trim()).filter(Boolean).filter(s=>s!=="."&&s!=="..").filter(s=>!/^\.[a-z0-9]+$/i.test(s)).filter(s=>s.length>=3);return o.length===0?null:(o.sort((s,r)=>r.length-s.length),o[0])}async function wy(t,e){let n=by(t);if(!n)return new Map;try{let o=await xT(n,void 0,e||process.cwd()),s=new Map;for(let r of o){let a=r.name.toLowerCase()===n.toLowerCase()?140:90;s.set(r.file,(s.get(r.file)||0)+a)}return s}catch{return new Map}}function hy(t,e){if(!t)return"";let n=e||process.cwd(),o=re.isAbsolute(t)?t:re.resolve(n,t),s=re.relative(n,o);return s&&!s.startsWith("..")&&!re.isAbsolute(s)?s:re.relative(process.cwd(),o)}function Rr(t,e){let n=(t||"").trim();return n?e==="files_with_matches"||e==="count"?n.split(`
355
+ `)}`}}catch{}try{let{smartSearch:i}=Rn(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=St(a[0].file);if(a[0].score>=200||a.length===1&&a[0].score>=50)return{fixedPath:l,message:`(auto-fixed: smart matched ${t} \u2192 ${re.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 ${re.relative(process.cwd(),l)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
356
+ ${a.map(u=>re.relative(process.cwd(),St(u.file))).map(u=>` - ${u}`).join(`
357
+ `)}`}}}catch{}return{fixedPath:null,message:""}}function DT(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 _y(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e||/[()[\]{}|^$\\]/.test(e))return null;let n=e.replace(/\*\*/g," ").replace(/[*?]/g," ").replace(/[:=><!]+/g," ").replace(/\s+/g," ").trim();if(!n)return null;let o=n.split(/[\/\s,]+/).map(s=>s.trim()).filter(Boolean).filter(s=>s!=="."&&s!=="..").filter(s=>!/^\.[a-z0-9]+$/i.test(s)).filter(s=>s.length>=3);return o.length===0?null:(o.sort((s,r)=>r.length-s.length),o[0])}async function $y(t,e){let n=_y(t);if(!n)return new Map;try{let o=await ET(n,void 0,e||process.cwd()),s=new Map;for(let r of o){let a=r.name.toLowerCase()===n.toLowerCase()?140:90;s.set(r.file,(s.get(r.file)||0)+a)}return s}catch{return new Map}}function gy(t,e){if(!t)return"";let n=e||process.cwd(),o=re.isAbsolute(t)?t:re.resolve(n,t),s=re.relative(n,o);return s&&!s.startsWith("..")&&!re.isAbsolute(s)?s:re.relative(process.cwd(),o)}function Cr(t,e){let n=(t||"").trim();return n?e==="files_with_matches"||e==="count"?n.split(`
358
358
  `).filter(o=>o.trim()):n.split(`
359
- `).filter(o=>o.trim()):[]}function _y(t,{query:e,basePath:n,definitionScores:o=new Map,mtimeByPath:s=new Map}={}){let r=by(e);return[...t].sort((i,a)=>{let l=hy(i,n),c=hy(a,n),u=0,d=0;if(r&&(u+=uy(l,r),d+=uy(c,r)),u+=o.get(l)||0,d+=o.get(c)||0,u!==d)return d-u;let f=s.get(i)||0,h=s.get(a)||0;return f!==h?h-f:l.localeCompare(c)})}async function Pu(t,{query:e,basePath:n,outputMode:o}={}){if(!Array.isArray(t)||t.length<=1)return t;let s=new Map,r=[];for(let c of t){if(!c)continue;let u=c;(o==="count"||o!=="files_with_matches")&&(u=c.split(":")[0]),s.has(u)||(s.set(u,[]),r.push(u)),s.get(u).push(c)}let i=await wy(e,n),a=_y(r,{query:e,basePath:n,definitionScores:i}),l=[];for(let c of a)l.push(...s.get(c)||[]);return l}function $y(t,e){let n=[];if(/command not found|: not found|not recognized/i.test(t)){let o=e.match(/^(\S+)/),s=o?o[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(s)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(s)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${s}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let o=t.match(/Cannot find module '([^']+)'/),s=o?o[1]:"";s&&!s.startsWith(".")&&!s.startsWith("/")?n.push(`HINT: Missing npm package "${s}". Run: npm install ${s}`):n.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&n.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let o=t.match(/port (\d+)|:(\d+)/),s=o?o[1]||o[2]:"";n.push(`HINT: Port ${s||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&n.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&n.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&n.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&n.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let o=t.match(/curl:\s*\((\d+)\)/),s=o?parseInt(o[1],10):null;s===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):s===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):s===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):s===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(s===35||/SSL.*error/i.test(t))&&n.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let o=t.match(/port (\d+)/),s=o?o[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${s}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${s}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&n.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&n.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&n.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&n.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),n.length===0?t:t+`
359
+ `).filter(o=>o.trim()):[]}function ky(t,{query:e,basePath:n,definitionScores:o=new Map,mtimeByPath:s=new Map}={}){let r=_y(e);return[...t].sort((i,a)=>{let l=gy(i,n),c=gy(a,n),u=0,d=0;if(r&&(u+=fy(l,r),d+=fy(c,r)),u+=o.get(l)||0,d+=o.get(c)||0,u!==d)return d-u;let f=s.get(i)||0,h=s.get(a)||0;return f!==h?h-f:l.localeCompare(c)})}async function Mu(t,{query:e,basePath:n,outputMode:o}={}){if(!Array.isArray(t)||t.length<=1)return t;let s=new Map,r=[];for(let c of t){if(!c)continue;let u=c;(o==="count"||o!=="files_with_matches")&&(u=c.split(":")[0]),s.has(u)||(s.set(u,[]),r.push(u)),s.get(u).push(c)}let i=await $y(e,n),a=ky(r,{query:e,basePath:n,definitionScores:i}),l=[];for(let c of a)l.push(...s.get(c)||[]);return l}function xy(t,e){let n=[];if(/command not found|: not found|not recognized/i.test(t)){let o=e.match(/^(\S+)/),s=o?o[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(s)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(s)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${s}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let o=t.match(/Cannot find module '([^']+)'/),s=o?o[1]:"";s&&!s.startsWith(".")&&!s.startsWith("/")?n.push(`HINT: Missing npm package "${s}". Run: npm install ${s}`):n.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&n.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let o=t.match(/port (\d+)|:(\d+)/),s=o?o[1]||o[2]:"";n.push(`HINT: Port ${s||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&n.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&n.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&n.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&n.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let o=t.match(/curl:\s*\((\d+)\)/),s=o?parseInt(o[1],10):null;s===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):s===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):s===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):s===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(s===35||/SSL.*error/i.test(t))&&n.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let o=t.match(/port (\d+)/),s=o?o[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${s}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${s}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&n.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&n.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&n.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&n.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),n.length===0?t:t+`
360
360
 
361
361
  `+n.join(`
362
- `)}function ky(t,e,n){let o=Or(t,e);if(!o)return null;let s=Math.max(2,Math.ceil(e.length*.03));return o.distance>s?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(n),distance:o.distance,line:o.line}}var my=!1,Bs=null;function IT(){Bs&&(Bs(),Bs=null)}var Iu=null;function jT(t){Iu=t}async function Nu(){if(!my){my=!0;try{let{stdout:t}=await lt("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await lt('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await lt("git stash pop",{cwd:process.cwd(),timeout:1e4}),await lt("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var DT=[/\.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 qT(){let t=process.cwd();try{return yn.realpathSync(t)}catch{return re.resolve(t)}}function FT(t,e){let n=re.relative(e,t);return n===""||!n.startsWith("..")&&!re.isAbsolute(n)}function BT(t){if(yn.existsSync(t))return yn.realpathSync(t);let e=re.dirname(t);for(;e&&e!==re.dirname(e);){if(yn.existsSync(e)){let n=yn.realpathSync(e),o=re.relative(e,t);return re.resolve(n,o)}e=re.dirname(e)}return t}function xt(t){let e=re.isAbsolute(t)?re.resolve(t):re.resolve(process.cwd(),t);for(let o of DT)if(o.test(e))return null;let n=BT(e);return FT(n,qT())?n:null}function De(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function xy(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function UT(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function WT(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function Mu(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function HT(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Cr(t,e="user"){return xy(t)?null:`ERROR: ${e} contains unsafe characters`}function Lu(t,e="service"){return UT(t)?null:`ERROR: ${e} contains unsafe characters`}var GT=[{type:"function",function:{name:"bash",description:"Run shell commands in the project directory. Timeout: 90s. Use for tests, installs, git, builds, servers, and compilers. Do not use for reading/searching files: use read_file, grep, glob, or list_directory instead. Quote paths with spaces. Check exit code; non-zero means failure. Dangerous commands require confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read UTF-8 file contents with line numbers. Read before editing so edit_file can match exact text. Use line_start/line_end for targeted or large-file reads; unbounded reads truncate at 350 lines. Prefer this over bash cat/head/tail.",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 by name/path glob, sorted by modification time. Use before reading when paths are unknown. Do not search file contents with this; use grep. Prefer this over bash find/ls.",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 Ar(t,{server:e,context:n}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function gy(t,e,n={}){switch(t){case"bash":{let o=e.command,s=yy(o);if(s)return`BLOCKED: ${s} is a Node.js built-in module and must not be installed. Import it directly instead.`;let r=pT(o);if(r){let f=LT(o);return`BLOCKED: Command matches forbidden pattern: ${r}${f?`
363
- HINT: ${f}`:""}`}let i=gT(o);if(i)return`BLOCKED: Destructive operation on protected path: ${i}
364
- HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(n.autoConfirm?iy(o):mT(o)){let f=iy(o)?"\u26D4":"\u26A0";if(!await gn(` ${f} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let l;try{l=process.cwd(),yn.accessSync(l)}catch{l=require("os").homedir(),n.silent||console.log(`${fe.yellow} \u26A0 Working directory no longer exists \u2014 running in ${l}${fe.reset}`)}let c=AT.test(o.trim())&&!OT.test(o.trim());if(CT.test(o.trim())||c){n.silent||console.log(`${fe.dim} \u25B6 interactive: ${o}${fe.reset}`);let f=fT("sh",["-c",o],{stdio:"inherit",cwd:l});return f.error?`ERROR: ${f.error.message}`:f.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${f.status})`}let{ToolProgress:u}=vs(),d=n.silent?null:new u("bash",`$ ${o.substring(0,72)}`);d&&d.start();try{let{stdout:f,stderr:h}=await lt(o,{cwd:l,timeout:9e4,maxBuffer:5242880});return d&&d.stop(),f||h||"(no output)"}catch(f){d&&d.stop();let h=(f.stderr||f.stdout||f.message||"").toString().substring(0,5e3),m=$y(h,o);return`EXIT ${f.code||1}
365
- ${m}`}}case"read_file":{let o=new Ca("read_file","Reading file...");o.start();try{let s=xt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Gt(s)){let K=await Pa(e.path);if(K.fixedPath)s=K.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${re.relative(process.cwd(),s)}${fe.reset}`),o.update({message:"Resolved path",detail:re.relative(process.cwd(),s)});else return`ERROR: File not found: ${e.path}${K.message?`
366
- `+K.message:""}`}let i=re.relative(process.cwd(),s);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),l=await yn.promises.open(s,"r"),{bytesRead:c}=await l.read(a,0,8192,0);await l.close();for(let K=0;K<c;K++)if(a[K]===0)return`ERROR: ${s} is a binary file (not readable as text)`;let u=await ft.readFile(s,"utf-8");if(!u&&(await ft.stat(s)).size>0)return`WARNING: ${s} is empty or unreadable`;let d=u.split(`
367
- `),f=await ft.stat(s),h=d.length,m=350,g=!e.line_start&&!e.line_end,_=g&&h>m,k=(e.line_start||1)-1,$=_?m:e.line_end||d.length,O=k+1,E=$;o.update({count:Math.max(0,$-k),total:h,detail:`${i} lines ${O}-${E}`,message:_?"Reading excerpt":"Reading"});let T=_?`showing lines 1-${m} of ${h}`:e.line_start||e.line_end?`lines ${k+1}-${$} of ${h}`:`${h} lines`,q=`File: ${i} (${T}, ${f.size} bytes)`,ee=d.slice(k,$).map((K,ae)=>`${k+ae+1}: ${K}`).join(`
362
+ `)}function Sy(t,e,n){let o=Pr(t,e);if(!o)return null;let s=Math.max(2,Math.ceil(e.length*.03));return o.distance>s?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(n),distance:o.distance,line:o.line}}var yy=!1,Us=null;function qT(){Us&&(Us(),Us=null)}var Du=null;function FT(t){Du=t}async function Lu(){if(!yy){yy=!0;try{let{stdout:t}=await lt("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await lt('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await lt("git stash pop",{cwd:process.cwd(),timeout:1e4}),await lt("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var BT=[/\.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 UT(){let t=process.cwd();try{return yn.realpathSync(t)}catch{return re.resolve(t)}}function WT(t,e){let n=re.relative(e,t);return n===""||!n.startsWith("..")&&!re.isAbsolute(n)}function HT(t){if(yn.existsSync(t))return yn.realpathSync(t);let e=re.dirname(t);for(;e&&e!==re.dirname(e);){if(yn.existsSync(e)){let n=yn.realpathSync(e),o=re.relative(e,t);return re.resolve(n,o)}e=re.dirname(e)}return t}function St(t){let e=re.isAbsolute(t)?re.resolve(t):re.resolve(process.cwd(),t);for(let o of BT)if(o.test(e))return null;let n=HT(e);return WT(n,UT())?n:null}function De(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function vy(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function GT(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function YT(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function Iu(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function zT(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Ar(t,e="user"){return vy(t)?null:`ERROR: ${e} contains unsafe characters`}function ju(t,e="service"){return GT(t)?null:`ERROR: ${e} contains unsafe characters`}var KT=[{type:"function",function:{name:"bash",description:"Run shell commands in the project directory. Timeout: 90s. Use for tests, installs, git, builds, servers, and compilers. Do not use for reading/searching files: use read_file, grep, glob, or list_directory instead. Quote paths with spaces. Check exit code; non-zero means failure. Dangerous commands require confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read UTF-8 file contents with line numbers. Read before editing so edit_file can match exact text. Use line_start/line_end for targeted or large-file reads; unbounded reads truncate at 350 lines. Prefer this over bash cat/head/tail.",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 by name/path glob, sorted by modification time. Use before reading when paths are unknown. Do not search file contents with this; use grep. Prefer this over bash find/ls.",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 Or(t,{server:e,context:n}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function by(t,e,n={}){switch(t){case"bash":{let o=e.command,s=wy(o);if(s)return`BLOCKED: ${s} is a Node.js built-in module and must not be installed. Import it directly instead.`;let r=gT(o);if(r){let f=DT(o);return`BLOCKED: Command matches forbidden pattern: ${r}${f?`
363
+ HINT: ${f}`:""}`}let i=wT(o);if(i)return`BLOCKED: Destructive operation on protected path: ${i}
364
+ HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(n.autoConfirm?ly(o):bT(o)){let f=ly(o)?"\u26D4":"\u26A0";if(!await gn(` ${f} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let l;try{l=process.cwd(),yn.accessSync(l)}catch{l=require("os").homedir(),n.silent||console.log(`${pe.yellow} \u26A0 Working directory no longer exists \u2014 running in ${l}${pe.reset}`)}let c=NT.test(o.trim())&&!MT.test(o.trim());if(PT.test(o.trim())||c){n.silent||console.log(`${pe.dim} \u25B6 interactive: ${o}${pe.reset}`);let f=mT("sh",["-c",o],{stdio:"inherit",cwd:l});return f.error?`ERROR: ${f.error.message}`:f.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${f.status})`}let{ToolProgress:u}=Es(),d=n.silent?null:new u("bash",`$ ${o.substring(0,72)}`);d&&d.start();try{let{stdout:f,stderr:h}=await lt(o,{cwd:l,timeout:9e4,maxBuffer:5242880});return d&&d.stop(),f||h||"(no output)"}catch(f){d&&d.stop();let h=(f.stderr||f.stdout||f.message||"").toString().substring(0,5e3),m=xy(h,o);return`EXIT ${f.code||1}
365
+ ${m}`}}case"read_file":{let o=new Aa("read_file","Reading file...");o.start();try{let s=St(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await zt(s)){let K=await Na(e.path);if(K.fixedPath)s=K.fixedPath,console.log(`${pe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${re.relative(process.cwd(),s)}${pe.reset}`),o.update({message:"Resolved path",detail:re.relative(process.cwd(),s)});else return`ERROR: File not found: ${e.path}${K.message?`
366
+ `+K.message:""}`}let i=re.relative(process.cwd(),s);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),l=await yn.promises.open(s,"r"),{bytesRead:c}=await l.read(a,0,8192,0);await l.close();for(let K=0;K<c;K++)if(a[K]===0)return`ERROR: ${s} is a binary file (not readable as text)`;let u=await pt.readFile(s,"utf-8");if(!u&&(await pt.stat(s)).size>0)return`WARNING: ${s} is empty or unreadable`;let d=u.split(`
367
+ `),f=await pt.stat(s),h=d.length,m=350,g=!e.line_start&&!e.line_end,_=g&&h>m,k=(e.line_start||1)-1,$=_?m:e.line_end||d.length,O=k+1,E=$;o.update({count:Math.max(0,$-k),total:h,detail:`${i} lines ${O}-${E}`,message:_?"Reading excerpt":"Reading"});let T=_?`showing lines 1-${m} of ${h}`:e.line_start||e.line_end?`lines ${k+1}-${$} of ${h}`:`${h} lines`,q=`File: ${i} (${T}, ${f.size} bytes)`,ee=d.slice(k,$).map((K,ae)=>`${k+ae+1}: ${K}`).join(`
368
368
  `),te=_?`
369
369
 
370
370
  [\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${m} of ${h} total lines. The rest of the file is HIDDEN. You MUST use line_start and line_end to read further down (e.g. line_start=${m+1}), or use grep_search to find specific keywords.]`:!g&&h>$?`
371
371
 
372
372
  [\u{1F6A8} FILE CONTINUES: This is only lines ${k+1} to ${$} of ${h} total. The rest is HIDDEN. Use line_start=${$+1} to read the next section, or grep_search for keywords.]`:"";return`${q}
373
- ${ee}${te}`}finally{o.stop()}}case"write_file":{let o=new Ca("write_file","Preparing write...");o.start();try{await Nu();let s=xt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await Gt(s),i=null,a=String(e.content||"").split(`
374
- `).length;if(o.update({count:a,detail:`${re.relative(process.cwd(),s)} ${a} lines`,message:r?"Overwriting":"Creating"}),n.autoConfirm)r&&(i=await ft.readFile(s,"utf-8"));else if(r){i=await ft.readFile(s,"utf-8");let f=await Tr(s,e.content);if(Ra(s,i,e.content,{annotations:f}),!await Er("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let f=await Tr(s,e.content);if(yT(s,e.content,{annotations:f}),!await Er("Create"))return"CANCELLED: User declined to create file."}let l=re.dirname(s);await Gt(l)||await ft.mkdir(l,{recursive:!0}),o.update({message:"Writing",detail:`${re.relative(process.cwd(),s)} ${a} lines`}),await ft.writeFile(s,e.content,"utf-8");let u=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||e.content.startsWith("#!");u&&(o.update({message:"Chmod",detail:re.relative(process.cwd(),s)}),await ft.chmod(s,493)),Aa("write_file",s,i,e.content);let d=u?" [chmod +x applied]":"";return`Written: ${s} (${e.content.length} chars)${d}`}finally{o.stop()}}case"edit_file":{let o=new Ca("edit_file","Preparing edit...");o.start();try{await Nu();let s=xt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Gt(s)){let d=await Pa(e.path);if(d.fixedPath)s=d.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${re.relative(process.cwd(),s)}${fe.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
375
- `+d.message:""}`}o.update({message:"Loading",detail:re.relative(process.cwd(),s)});let i=await ft.readFile(s,"utf-8"),a=e.old_text,l=!1,c=!1;if(!i.includes(e.old_text)){o.update({message:"Matching target",detail:`${re.relative(process.cwd(),s)} ${String(e.old_text||"").trim().split(`
376
- `)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=$t();if(fy(d(),f())==="strict"){let g=Or(i,e.old_text);return g?`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)
373
+ ${ee}${te}`}finally{o.stop()}}case"write_file":{let o=new Aa("write_file","Preparing write...");o.start();try{await Lu();let s=St(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await zt(s),i=null,a=String(e.content||"").split(`
374
+ `).length;if(o.update({count:a,detail:`${re.relative(process.cwd(),s)} ${a} lines`,message:r?"Overwriting":"Creating"}),n.autoConfirm)r&&(i=await pt.readFile(s,"utf-8"));else if(r){i=await pt.readFile(s,"utf-8");let f=await Rr(s,e.content);if(Ca(s,i,e.content,{annotations:f}),!await Tr("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let f=await Rr(s,e.content);if(_T(s,e.content,{annotations:f}),!await Tr("Create"))return"CANCELLED: User declined to create file."}let l=re.dirname(s);await zt(l)||await pt.mkdir(l,{recursive:!0}),o.update({message:"Writing",detail:`${re.relative(process.cwd(),s)} ${a} lines`}),await pt.writeFile(s,e.content,"utf-8");let u=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||e.content.startsWith("#!");u&&(o.update({message:"Chmod",detail:re.relative(process.cwd(),s)}),await pt.chmod(s,493)),Oa("write_file",s,i,e.content);let d=u?" [chmod +x applied]":"";return`Written: ${s} (${e.content.length} chars)${d}`}finally{o.stop()}}case"edit_file":{let o=new Aa("edit_file","Preparing edit...");o.start();try{await Lu();let s=St(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await zt(s)){let d=await Na(e.path);if(d.fixedPath)s=d.fixedPath,console.log(`${pe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${re.relative(process.cwd(),s)}${pe.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
375
+ `+d.message:""}`}o.update({message:"Loading",detail:re.relative(process.cwd(),s)});let i=await pt.readFile(s,"utf-8"),a=e.old_text,l=!1,c=!1;if(!i.includes(e.old_text)){o.update({message:"Matching target",detail:`${re.relative(process.cwd(),s)} ${String(e.old_text||"").trim().split(`
376
+ `)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=kt();if(hy(d(),f())==="strict"){let g=Pr(i,e.old_text);return g?`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)
377
377
  Most similar text (line ${g.line}, distance ${g.distance}):
378
- ${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let m=ly(i,e.old_text);if(m)a=m,l=!0,o.update({message:"Matched target",detail:`${re.relative(process.cwd(),s)} whitespace-normalized`}),console.log(`${fe.dim} \u2713 fuzzy whitespace match applied${fe.reset}`);else{let g=ky(i,e.old_text,e.new_text);if(g){if(!n.autoConfirm){let E=await Tr(s,g.content);if(Ra(s,i,g.content,{annotations:E}),!await Er(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await ft.writeFile(s,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||g.content.startsWith("#!"))&&await ft.chmod(s,493),Aa("edit_file",s,i,g.content);let O=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${fe.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${fe.reset}`),`Edited: ${s} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${O}")`}let _=Or(i,e.old_text);if(_){let O=i.split(`
378
+ ${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let m=uy(i,e.old_text);if(m)a=m,l=!0,o.update({message:"Matched target",detail:`${re.relative(process.cwd(),s)} whitespace-normalized`}),console.log(`${pe.dim} \u2713 fuzzy whitespace match applied${pe.reset}`);else{let g=Sy(i,e.old_text,e.new_text);if(g){if(!n.autoConfirm){let E=await Rr(s,g.content);if(Ca(s,i,g.content,{annotations:E}),!await Tr(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await pt.writeFile(s,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||g.content.startsWith("#!"))&&await pt.chmod(s,493),Oa("edit_file",s,i,g.content);let O=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${pe.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${pe.reset}`),`Edited: ${s} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${O}")`}let _=Pr(i,e.old_text);if(_){let O=i.split(`
379
379
  `),E=Math.max(0,_.line-6),T=Math.min(O.length,_.line+10),q=O.slice(E,T).map((te,K)=>`${E+K+1}: ${te}`).join(`
380
380
  `),ee=`line_start=${Math.max(1,_.line-5)} line_end=${Math.min(O.length,_.line+15)}`;return`ERROR: old_text not found in ${s} (most similar at line ${_.line}, distance ${_.distance})
381
381
 
@@ -386,27 +386,27 @@ Fix: update old_text to match the exact lines above, then retry. If you need mor
386
386
  `)[0].slice(0,60),$=k?`
387
387
  Recovery: grep -n "${k.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
388
388
  Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${s}${$}`}}if(!n.autoConfirm){o.update({message:"Previewing edit",detail:`${re.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
389
- `)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await Tr(s,d);if(Ra(s,i,d,{annotations:f}),!await Er(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:`${re.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
390
- `)[0].slice(0,40)}`}),await ft.writeFile(s,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||u.startsWith("#!"))&&(o.update({message:"Chmod",detail:re.relative(process.cwd(),s)}),await ft.chmod(s,493)),Aa("edit_file",s,i,u),l?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}finally{o.stop()}}case"list_directory":{let o=xt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Gt(o)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=xt(c),d=await Gt(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 ft.readdir(c,{withFileTypes:!0})}catch{return}f=f.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of f){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let m=h.isDirectory()?"/":"";a.push(`${d}${h.name}${m}`),h.isDirectory()&&await l(re.join(c,h.name),u+1,d+" ")}};return await l(o,1,""),a.join(`
391
- `)||"(empty)"}case"search_files":{let o=xt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=["-rn","-H"];e.file_pattern&&s.push(`--include=${e.file_pattern}`),s.push(e.pattern,o);try{let{stdout:r}=await Fs("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=Rr(r).slice(0,50);return(await Pu(i,{query:e.pattern,basePath:o})).join(`
392
- `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?xt(e.path):s,i=e.pattern,a=T=>{let q=T.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${q}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=vs(),f=new d("glob","Finding files...");f.start();let h=cy();vT(r)||(await ST(r),h=cy());let m=h.filter(T=>l.test(T)||u.test(re.basename(T))).map(T=>re.join(r,T));if(m.length===0)return f.stop(),"(no matches)"+Ou(e.path);let g=await Promise.all(m.slice(0,210).map(async T=>{try{let q=await ft.stat(T);return{path:T,mtime:q.mtimeMs}}catch{return{path:T,mtime:0}}})),_=new Map(g.map(T=>[T.path,T.mtime])),k=await wy(i,r),$=_y(g.map(T=>T.path),{query:i,basePath:r,definitionScores:k,mtimeByPath:_}),O=m.length>200,E=$.slice(0,200).join(`
389
+ `)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await Rr(s,d);if(Ca(s,i,d,{annotations:f}),!await Tr(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:`${re.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
390
+ `)[0].slice(0,40)}`}),await pt.writeFile(s,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||u.startsWith("#!"))&&(o.update({message:"Chmod",detail:re.relative(process.cwd(),s)}),await pt.chmod(s,493)),Oa("edit_file",s,i,u),l?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}finally{o.stop()}}case"list_directory":{let o=St(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await zt(o)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=St(c),d=await zt(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 pt.readdir(c,{withFileTypes:!0})}catch{return}f=f.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of f){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let m=h.isDirectory()?"/":"";a.push(`${d}${h.name}${m}`),h.isDirectory()&&await l(re.join(c,h.name),u+1,d+" ")}};return await l(o,1,""),a.join(`
391
+ `)||"(empty)"}case"search_files":{let o=St(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=["-rn","-H"];e.file_pattern&&s.push(`--include=${e.file_pattern}`),s.push(e.pattern,o);try{let{stdout:r}=await Bs("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=Cr(r).slice(0,50);return(await Mu(i,{query:e.pattern,basePath:o})).join(`
392
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?St(e.path):s,i=e.pattern,a=T=>{let q=T.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${q}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=Es(),f=new d("glob","Finding files...");f.start();let h=dy();RT(r)||(await TT(r),h=dy());let m=h.filter(T=>l.test(T)||u.test(re.basename(T))).map(T=>re.join(r,T));if(m.length===0)return f.stop(),"(no matches)"+Nu(e.path);let g=await Promise.all(m.slice(0,210).map(async T=>{try{let q=await pt.stat(T);return{path:T,mtime:q.mtimeMs}}catch{return{path:T,mtime:0}}})),_=new Map(g.map(T=>[T.path,T.mtime])),k=await $y(i,r),$=ky(g.map(T=>T.path),{query:i,basePath:r,definitionScores:k,mtimeByPath:_}),O=m.length>200,E=$.slice(0,200).join(`
393
393
  `);return f.update({count:m.length,detail:e.pattern}),f.stop(),O?`${E}
394
394
 
395
- \u26A0 Results truncated at 200. Use a more specific pattern.`:E}case"grep":{let o=e.path?xt(e.path):process.cwd();if(e.staged){let{getDiff:l}=Ji(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
396
- `);for(let _ of d)if(_.startsWith("diff --git")){let k=_.match(/diff --git a\/(.+) b\/(.+)/);k&&u.add(k[2])}let f=["-rn","-E","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&f.push("-i"),e.include&&f.push(`--include=${e.include}`),e.type&&f.push(`--include=*.${e.type}`),e.context?f.push("-C",String(e.context)):(e.before_context&&f.push("-B",String(e.before_context)),e.after_context&&f.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?f.push("-l"):e.output_mode==="count"&&f.push("-c"),f.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=vs(),m=new h("grep","Searching staged content...");m.start();let g=[];for(let _ of u)try{let k=re.join(process.cwd(),_);if(await Gt(k)){let $=[...f];$.push(e.pattern,k);let{stdout:O}=await Fs("grep",$,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let E=Rr(O,e.output_mode);g=g.concat(E)}else g=g.concat(Rr(O))}}catch{}return g=await Pu(g,{query:e.pattern,basePath:process.cwd(),outputMode:e.output_mode}),m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
397
- `).trim()||"(no matches in staged files)"}let s=["-rn","-E","-H"];e.ignore_case&&s.push("-i"),e.include&&s.push(`--include=${e.include}`),e.type&&s.push(`--include=*.${e.type}`);let r=20;e.context?s.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&s.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&s.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?s.push("-l"):e.output_mode==="count"&&s.push("-c"),s.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),s.push(e.pattern,o);let{ToolProgress:i}=vs(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await Fs("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;e.output_mode==="files_with_matches"||e.output_mode==="count"?c=Rr(l,e.output_mode):c=Rr(l);let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=await Pu(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(`
398
- `).trim()||"(no matches)"+Ou(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)"+Ou(e.path)}}case"patch_file":{let o=new Ca("patch_file","Preparing patches...");o.start();try{await Nu();let s=xt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Gt(s)){let $=await Pa(e.path);if($.fixedPath)s=$.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${re.relative(process.cwd(),s)}${fe.reset}`);else return`ERROR: File not found: ${e.path}${$.message?`
399
- `+$.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:`${re.relative(process.cwd(),s)} ${i.length} patches`,message:"Validating patches"});let a=await ft.readFile(s,"utf-8"),{getActiveModelId:l,getActiveProviderName:c}=$t(),u=fy(l(),c()),d=[],f=!1,h=!1;for(let $=0;$<i.length;$++){o.update({count:$+1,total:i.length,detail:`${re.relative(process.cwd(),s)} patch ${$+1}/${i.length}`,message:"Matching patches"});let{old_text:O,new_text:E}=i[$];if(a.includes(O))d.push({old_text:O,new_text:E});else if(u==="strict"){let T=Or(a,O);return T?`ERROR: Patch ${$+1} old_text not found in ${s} (strict mode \u2014 exact match required)
395
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:E}case"grep":{let o=e.path?St(e.path):process.cwd();if(e.staged){let{getDiff:l}=Zi(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
396
+ `);for(let _ of d)if(_.startsWith("diff --git")){let k=_.match(/diff --git a\/(.+) b\/(.+)/);k&&u.add(k[2])}let f=["-rn","-E","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&f.push("-i"),e.include&&f.push(`--include=${e.include}`),e.type&&f.push(`--include=*.${e.type}`),e.context?f.push("-C",String(e.context)):(e.before_context&&f.push("-B",String(e.before_context)),e.after_context&&f.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?f.push("-l"):e.output_mode==="count"&&f.push("-c"),f.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=Es(),m=new h("grep","Searching staged content...");m.start();let g=[];for(let _ of u)try{let k=re.join(process.cwd(),_);if(await zt(k)){let $=[...f];$.push(e.pattern,k);let{stdout:O}=await Bs("grep",$,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let E=Cr(O,e.output_mode);g=g.concat(E)}else g=g.concat(Cr(O))}}catch{}return g=await Mu(g,{query:e.pattern,basePath:process.cwd(),outputMode:e.output_mode}),m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
397
+ `).trim()||"(no matches in staged files)"}let s=["-rn","-E","-H"];e.ignore_case&&s.push("-i"),e.include&&s.push(`--include=${e.include}`),e.type&&s.push(`--include=*.${e.type}`);let r=20;e.context?s.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&s.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&s.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?s.push("-l"):e.output_mode==="count"&&s.push("-c"),s.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),s.push(e.pattern,o);let{ToolProgress:i}=Es(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await Bs("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;e.output_mode==="files_with_matches"||e.output_mode==="count"?c=Cr(l,e.output_mode):c=Cr(l);let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=await Mu(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(`
398
+ `).trim()||"(no matches)"+Nu(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)"+Nu(e.path)}}case"patch_file":{let o=new Aa("patch_file","Preparing patches...");o.start();try{await Lu();let s=St(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await zt(s)){let $=await Na(e.path);if($.fixedPath)s=$.fixedPath,console.log(`${pe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${re.relative(process.cwd(),s)}${pe.reset}`);else return`ERROR: File not found: ${e.path}${$.message?`
399
+ `+$.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:`${re.relative(process.cwd(),s)} ${i.length} patches`,message:"Validating patches"});let a=await pt.readFile(s,"utf-8"),{getActiveModelId:l,getActiveProviderName:c}=kt(),u=hy(l(),c()),d=[],f=!1,h=!1;for(let $=0;$<i.length;$++){o.update({count:$+1,total:i.length,detail:`${re.relative(process.cwd(),s)} patch ${$+1}/${i.length}`,message:"Matching patches"});let{old_text:O,new_text:E}=i[$];if(a.includes(O))d.push({old_text:O,new_text:E});else if(u==="strict"){let T=Pr(a,O);return T?`ERROR: Patch ${$+1} old_text not found in ${s} (strict mode \u2014 exact match required)
400
400
  Most similar text (line ${T.line}, distance ${T.distance}):
401
- ${T.text}`:`ERROR: Patch ${$+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let T=ly(a,O);if(T)d.push({old_text:T,new_text:E}),f=!0;else{let q=Or(a,O);if(q){let ee=Math.max(3,Math.ceil(O.length*.05));if(q.distance<=ee)d.push({old_text:q.text,new_text:E}),h=!0;else return`ERROR: Patch ${$+1} old_text not found in ${s}
401
+ ${T.text}`:`ERROR: Patch ${$+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let T=uy(a,O);if(T)d.push({old_text:T,new_text:E}),f=!0;else{let q=Pr(a,O);if(q){let ee=Math.max(3,Math.ceil(O.length*.05));if(q.distance<=ee)d.push({old_text:q.text,new_text:E}),h=!0;else return`ERROR: Patch ${$+1} old_text not found in ${s}
402
402
  Most similar text (line ${q.line}, distance ${q.distance}):
403
- ${q.text}`}else return`ERROR: Patch ${$+1} old_text not found in ${s}`}}}let m=a;for(let{old_text:$,new_text:O}of d)m=m.split($).join(O);if(!n.autoConfirm){o.update({message:"Previewing patch set",count:d.length,total:i.length,detail:`${re.relative(process.cwd(),s)} ${d.length} matched`});let $=await Tr(s,m);if(Ra(s,a,m,{annotations:$}),!await Er(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:`${re.relative(process.cwd(),s)} ${d.length} matched`}),await ft.writeFile(s,m,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||m.startsWith("#!");g&&(o.update({message:"Chmod",detail:re.relative(process.cwd(),s)}),await ft.chmod(s,493)),Aa("patch_file",s,a,m);let _=h?" (auto-fixed)":f?" (fuzzy match)":"",k=g?" [chmod +x applied]":"";return`Patched: ${s} (${i.length} replacements)${_}${k}`}finally{o.stop()}}case"web_fetch":{let o=e.url,s=e.max_length||1e4;try{let i=new URL(o).hostname;if(/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|localhost$|\[::1?\]|\[fd|fc)/i.test(i))return"ERROR: Fetching private/internal addresses is not allowed.";let a=await Cu.get(o,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,s)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${o}: ${r.message}`}}case"web_search":{let o=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let s=await Cu.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=s.data?.choices?.[0]?.message?.content||"",i=s.data?.citations||[],a=`[Perplexity grounded search]
403
+ ${q.text}`}else return`ERROR: Patch ${$+1} old_text not found in ${s}`}}}let m=a;for(let{old_text:$,new_text:O}of d)m=m.split($).join(O);if(!n.autoConfirm){o.update({message:"Previewing patch set",count:d.length,total:i.length,detail:`${re.relative(process.cwd(),s)} ${d.length} matched`});let $=await Rr(s,m);if(Ca(s,a,m,{annotations:$}),!await Tr(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:`${re.relative(process.cwd(),s)} ${d.length} matched`}),await pt.writeFile(s,m,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||m.startsWith("#!");g&&(o.update({message:"Chmod",detail:re.relative(process.cwd(),s)}),await pt.chmod(s,493)),Oa("patch_file",s,a,m);let _=h?" (auto-fixed)":f?" (fuzzy match)":"",k=g?" [chmod +x applied]":"";return`Patched: ${s} (${i.length} replacements)${_}${k}`}finally{o.stop()}}case"web_fetch":{let o=e.url,s=e.max_length||1e4;try{let i=new URL(o).hostname;if(/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|localhost$|\[::1?\]|\[fd|fc)/i.test(i))return"ERROR: Fetching private/internal addresses is not allowed.";let a=await Ou.get(o,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,s)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${o}: ${r.message}`}}case"web_search":{let o=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let s=await Ou.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=s.data?.choices?.[0]?.message?.content||"",i=s.data?.citations||[],a=`[Perplexity grounded search]
404
404
 
405
405
  ${r}`;return i.length>0&&(a+=`
406
406
 
407
407
  Sources:
408
408
  `+i.slice(0,o).map((l,c)=>`${c+1}. ${l}`).join(`
409
- `)),a}catch(s){console.error(`${fe.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${fe.reset}`)}try{let r=(await Cu.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}
409
+ `)),a}catch(s){console.error(`${pe.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${pe.reset}`)}try{let r=(await Ou.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}
410
410
  ${c.url}`).join(`
411
411
 
412
412
  `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=Wn();try{let s=await o(e.url,{waitFor:e.wait_for}),r=s.links.length>0?`
@@ -437,10 +437,10 @@ Analyze the screenshot above and provide structured feedback:
437
437
  4. Responsiveness concerns at this viewport
438
438
  5. Specific issues related to: ${r}`;return e.compare_with&&yn.existsSync(e.compare_with)&&(i+=`
439
439
 
440
- COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:s.path,base64:s.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(s){return`ERROR: ${s.message}`}}case"clipboard_image":try{let{_grabClipboardImage:o}=ju(),s=o();return s?{text:`Clipboard image captured: ${s.path}
440
+ COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:s.path,base64:s.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(s){return`ERROR: ${s.message}`}}case"clipboard_image":try{let{_grabClipboardImage:o}=qu(),s=o();return s?{text:`Clipboard image captured: ${s.path}
441
441
  Size: ${Math.round(Buffer.from(s.data,"base64").length/1024)} KB
442
442
 
443
- [Clipboard image is attached for visual analysis]`,images:[{path:s.path,base64:s.data,media_type:s.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(o){return`ERROR: ${o.message}`}case"browser_click":{let{browserClick:o}=Wn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:o}=Wn();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(s){return`ERROR: ${s.message}`}}case"visual_diff":try{let{pixelDiff:o}=As(),s=o(e.before,e.after,{threshold:e.threshold}),r=s.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
443
+ [Clipboard image is attached for visual analysis]`,images:[{path:s.path,base64:s.data,media_type:s.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(o){return`ERROR: ${o.message}`}case"browser_click":{let{browserClick:o}=Wn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:o}=Wn();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(s){return`ERROR: ${s.message}`}}case"visual_diff":try{let{pixelDiff:o}=Os(),s=o(e.before,e.after,{threshold:e.threshold}),r=s.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
444
444
  `):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${s.diffPercent}% of pixels changed
445
445
  Changed: ${s.changedPixels.toLocaleString()} / ${s.totalPixels.toLocaleString()} pixels
446
446
  Canvas: ${s.width}\xD7${s.height}
@@ -449,7 +449,7 @@ Diff image: ${s.diffPath}
449
449
  Regional breakdown:
450
450
  ${i}
451
451
 
452
- [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:s.diffPath,base64:yn.readFileSync(s.diffPath).toString("base64"),media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"responsive_sweep":try{let{responsiveSweep:o}=As(),s=await o(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=s.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
452
+ [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:s.diffPath,base64:yn.readFileSync(s.diffPath).toString("base64"),media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"responsive_sweep":try{let{responsiveSweep:o}=Os(),s=await o(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=s.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
453
453
  `);return{text:`RESPONSIVE SWEEP \u2014 ${s.length} viewports captured
454
454
  URL: ${e.url}
455
455
 
@@ -463,15 +463,15 @@ Analyze these screenshots for:
463
463
  2. Typography scaling (text too small on mobile, too large on desktop)
464
464
  3. Navigation pattern changes across viewports
465
465
  4. Image/media sizing and aspect ratio issues
466
- 5. Touch target sizes on mobile viewports`,images:s.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(o){return`ERROR: ${o.message}`}case"visual_annotate":try{let{annotateImage:o}=As(),s=o(e.image,e.annotations),r=e.annotations.length,i=[...new Set(e.annotations.map(a=>a.type))].join(", ");return{text:`ANNOTATED IMAGE \u2014 ${r} annotation(s) added (${i})
466
+ 5. Touch target sizes on mobile viewports`,images:s.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(o){return`ERROR: ${o.message}`}case"visual_annotate":try{let{annotateImage:o}=Os(),s=o(e.image,e.annotations),r=e.annotations.length,i=[...new Set(e.annotations.map(a=>a.type))].join(", ");return{text:`ANNOTATED IMAGE \u2014 ${r} annotation(s) added (${i})
467
467
  Source: ${e.image}
468
468
  Output: ${s.path}
469
469
 
470
- [Annotated image attached with visual markers]`,images:[{path:s.path,base64:s.base64,media_type:s.media_type}]}}catch(o){return`ERROR: ${o.message}`}case"visual_watch":try{let{visualWatch:o}=As(),s=o(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await s.next();if(r.value?.type==="error")return`ERROR: ${r.value.message}`;let i=[];i.push(`VISUAL WATCH \u2014 monitoring ${e.watch.length} path(s)`,`URL: ${e.url}`,`Baseline screenshot: ${r.value?.path}`,"","Watching for file changes... (will capture up to "+(e.max_iterations||10)+" iterations)");let a=await s.next();if(!a.done&&a.value){let l=a.value;i.push("",`--- Iteration ${l.iteration} ---`,`Screenshot: ${l.path}`),l.diff&&i.push(`Diff: ${l.diff.diffPercent}% changed (${l.diff.changedPixels} pixels)`,`Regions: ${l.diff.regions.map(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:yn.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
470
+ [Annotated image attached with visual markers]`,images:[{path:s.path,base64:s.base64,media_type:s.media_type}]}}catch(o){return`ERROR: ${o.message}`}case"visual_watch":try{let{visualWatch:o}=Os(),s=o(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await s.next();if(r.value?.type==="error")return`ERROR: ${r.value.message}`;let i=[];i.push(`VISUAL WATCH \u2014 monitoring ${e.watch.length} path(s)`,`URL: ${e.url}`,`Baseline screenshot: ${r.value?.path}`,"","Watching for file changes... (will capture up to "+(e.max_iterations||10)+" iterations)");let a=await s.next();if(!a.done&&a.value){let l=a.value;i.push("",`--- Iteration ${l.iteration} ---`,`Screenshot: ${l.path}`),l.diff&&i.push(`Diff: ${l.diff.diffPercent}% changed (${l.diff.changedPixels} pixels)`,`Regions: ${l.diff.regions.map(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:yn.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
471
471
  `),images:c}}return{text:i.join(`
472
472
  `)+`
473
473
 
474
- 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}=As(),s=o(e.image,{sampleRate:e.sample_rate}),r=s.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
474
+ 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}=Os(),s=o(e.image,{sampleRate:e.sample_rate}),r=s.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
475
475
  `),i=s.spacing.length?s.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
476
476
  `):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${s.dimensions.width}\xD7${s.dimensions.height} image
477
477
  Source: ${s.imagePath}
@@ -485,7 +485,7 @@ ${i}
485
485
  Use these values to:
486
486
  - Compare against CSS variables / design system tokens
487
487
  - Identify inconsistent colors or spacing
488
- - Generate a color palette from the rendered output`}catch(o){return`ERROR: ${o.message}`}case"design_compare":try{let{designCompare:o}=As(),s=await o(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=s.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
488
+ - Generate a color palette from the rendered output`}catch(o){return`ERROR: ${o.message}`}case"design_compare":try{let{designCompare:o}=Os(),s=await o(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=s.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
489
489
  `)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${s.diffPercent}% deviation from reference
490
490
  Reference: ${s.referencePath}
491
491
  Live: ${s.livePath}
@@ -497,45 +497,45 @@ Pixel deviation: ${s.changedPixels.toLocaleString()} / ${s.totalPixels.toLocaleS
497
497
  Regional breakdown:
498
498
  ${r}
499
499
 
500
- [Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:s.livePath,base64:s.liveBase64,media_type:"image/png"},{path:s.diffPath,base64:s.diffBase64,media_type:"image/png"},{path:s.annotatedPath,base64:s.annotatedBase64,media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"ask_user":{let{question:o,options:s=[]}=e;return Iu?new Promise(r=>{Bs=()=>r("CANCELLED"),Iu(o,s).then(i=>{Bs=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});Bs=()=>{i.close(),r("CANCELLED")};let a=s.length>0?`
500
+ [Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:s.livePath,base64:s.liveBase64,media_type:"image/png"},{path:s.diffPath,base64:s.diffBase64,media_type:"image/png"},{path:s.annotatedPath,base64:s.annotatedBase64,media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"ask_user":{let{question:o,options:s=[]}=e;return Du?new Promise(r=>{Us=()=>r("CANCELLED"),Du(o,s).then(i=>{Us=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});Us=()=>{i.close(),r("CANCELLED")};let a=s.length>0?`
501
501
  ${s.map((l,c)=>` ${c+1}. ${l}`).join(`
502
502
  `)}
503
503
  `:"";console.log(`
504
- ${fe.cyan}${fe.bold} ? ${o}${fe.reset}${a}`),i.question(`${fe.cyan} > ${fe.reset}`,l=>{Bs=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Au())return"ERROR: Not a git repository";let o=await ay()||"(detached)",s=await _T();if(s.length===0)return`Branch: ${o}
504
+ ${pe.cyan}${pe.bold} ? ${o}${pe.reset}${a}`),i.question(`${pe.cyan} > ${pe.reset}`,l=>{Us=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Pu())return"ERROR: Not a git repository";let o=await cy()||"(detached)",s=await xT();if(s.length===0)return`Branch: ${o}
505
505
  Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${s.length}):`];for(let i of s){let a=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${a}: ${i.file}`)}return r.join(`
506
- `)}case"git_diff":{if(!await Au())return"ERROR: Not a git repository";let o;if(e.file){let s=["diff"];e.staged&&s.push("--cached"),s.push("--",e.file);try{o=execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await $T(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await Au())return"ERROR: Not a git repository";let s=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&s.push("--",e.file);try{return execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:o,updateTask:s,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=fu(),{getActiveTaskProgress:l}=_t(),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(`
506
+ `)}case"git_diff":{if(!await Pu())return"ERROR: Not a git repository";let o;if(e.file){let s=["diff"];e.staged&&s.push("--cached"),s.push("--",e.file);try{o=execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await ST(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await Pu())return"ERROR: Not a git repository";let s=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&s.push("--",e.file);try{return execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:o,updateTask:s,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=hu(),{getActiveTaskProgress:l}=$t(),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(`
507
507
  `+i()),`Created task list "${e.name}" with ${u.length} tasks:
508
508
  `+u.map(d=>` ${d.id}: ${d.description}`).join(`
509
509
  `)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":s(e.task_id,e.status,e.result)?(c||console.log(`
510
510
  `+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(`
511
- `+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:s}=Na();return e.agents?.some(r=>r.background)?s(e):o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:s,getActiveModelId:r}=$t();return o(e.model)?`Switched to ${s()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let o=Math.min(e.limit||10,30),s=["run","list","--limit",String(o),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&s.push("--workflow",e.workflow),e.branch&&s.push("--branch",e.branch),e.status&&s.push("--status",e.status);try{let{stdout:r}=await Fs("gh",s,{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(`
511
+ `+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:s}=Ma();return e.agents?.some(r=>r.background)?s(e):o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:s,getActiveModelId:r}=kt();return o(e.model)?`Switched to ${s()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let o=Math.min(e.limit||10,30),s=["run","list","--limit",String(o),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&s.push("--workflow",e.workflow),e.branch&&s.push("--branch",e.branch),e.status&&s.push("--status",e.status);try{let{stdout:r}=await Bs("gh",s,{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(`
512
512
  `)}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(`
513
- `)[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 Fs("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
514
- ...(truncated)`:"")}let{stdout:o}=await Fs("gh",["run","view",String(e.run_id),"--json","status,conclusion,name,headBranch,createdAt,updatedAt,jobs"],{cwd:process.cwd(),timeout:3e4}),s=JSON.parse(o),r=[`Run: ${s.name} [${e.run_id}]`,`Branch: ${s.headBranch} Status: ${s.conclusion||s.status}`,`Started: ${s.createdAt} Finished: ${s.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of s.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let c=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${c} ${l.name}`)}}return r.join(`
513
+ `)[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 Bs("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
514
+ ...(truncated)`:"")}let{stdout:o}=await Bs("gh",["run","view",String(e.run_id),"--json","status,conclusion,name,headBranch,createdAt,updatedAt,jobs"],{cwd:process.cwd(),timeout:3e4}),s=JSON.parse(o),r=[`Run: ${s.name} [${e.run_id}]`,`Branch: ${s.headBranch} Status: ${s.conclusion||s.status}`,`Started: ${s.createdAt} Finished: ${s.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of s.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let c=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${c} ${l.name}`)}}return r.join(`
515
515
  `)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
516
- `)[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}=or(),s=e.branch||await ay()||"main";if(!/^[\w./-]+$/.test(s))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",s];if(e.inputs)for(let[a,l]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${l}`)}if(console.log(`
517
- ${fe.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${fe.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Fs("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${s}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
518
- `)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=Ar(`get pods ${o} ${s} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await lt(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
519
- `)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let o=e.namespace||"default",s=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${s}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Ar(r,e);try{let{stdout:a,stderr:l}=await lt(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
516
+ `)[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}=rr(),s=e.branch||await cy()||"main";if(!/^[\w./-]+$/.test(s))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",s];if(e.inputs)for(let[a,l]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${l}`)}if(console.log(`
517
+ ${pe.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${pe.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Bs("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${s}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
518
+ `)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=Or(`get pods ${o} ${s} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await lt(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
519
+ `)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let o=e.namespace||"default",s=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${s}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Or(r,e);try{let{stdout:a,stderr:l}=await lt(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
520
520
  ...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
521
521
  `)[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(`
522
- ${fe.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${fe.reset}`),console.log(`${fe.dim} Command: ${e.command}${fe.reset}`),!await gn(" 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=Ar(r,e);try{let{stdout:a,stderr:l}=await lt(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
522
+ ${pe.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${pe.reset}`),console.log(`${pe.dim} Command: ${e.command}${pe.reset}`),!await gn(" 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=Or(r,e);try{let{stdout:a,stderr:l}=await lt(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
523
523
  `)[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(`
524
- ${fe.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${fe.reset}`),!await gn(" Apply to cluster?"))return"CANCELLED: User declined."}let s=`apply -f ${e.file}`;e.namespace&&(s+=` -n ${e.namespace}`),o&&(s+=" --dry-run=client");let r=Ar(s,e);try{let{stdout:i,stderr:a}=await lt(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
524
+ ${pe.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${pe.reset}`),!await gn(" Apply to cluster?"))return"CANCELLED: User declined."}let s=`apply -f ${e.file}`;e.namespace&&(s+=` -n ${e.namespace}`),o&&(s+=" --dry-run=client");let r=Or(s,e);try{let{stdout:i,stderr:a}=await lt(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
525
525
  `)[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(`
526
- ${fe.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${fe.reset}`),!await gn(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=Ar(r,e);try{let{stdout:a,stderr:l}=await lt(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
527
- `)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:o,readDocument:s}=Su(),{name:r,content:i,mode:a}=e;if(a==="create"&&s(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let l=s(r),c=l.content?l.content+`
526
+ ${pe.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${pe.reset}`),!await gn(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=Or(r,e);try{let{stdout:a,stderr:l}=await lt(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
527
+ `)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:o,readDocument:s}=Eu(),{name:r,content:i,mode:a}=e;if(a==="create"&&s(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let l=s(r),c=l.content?l.content+`
528
528
 
529
- `+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=nn(e.server)}catch(q){return`ERROR: ${q.message}`}let s=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=hT(s);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(s)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
529
+ `+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=sn(e.server)}catch(q){return`ERROR: ${q.message}`}let s=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=yT(s);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(s)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
530
530
  grep -n "pattern" /path/to/file -A 50
531
531
  or to read the whole file:
532
532
  cat /path/to/file
533
533
  NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
534
534
  HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(s=s.replace(/(-[BAC])\s*(\d+)/g,(q,ee,te)=>{let K=Math.min(Number(te),20);return`${ee} ${K}`}),s=s.replace(/(--(?:before|after|context)=)(\d+)/g,(q,ee,te)=>ee+Math.min(Number(te),20)),/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(s)){let q=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
535
- ${fe.yellow} \u26A0 Remote command on ${q}: ${s}${fe.reset}`),!await gn(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await Nt(o,s,{timeout:i,sudo:r}),h=[c,u].filter(Boolean).join(`
536
- `).trim();if(d!==0){if(/no such file or directory/i.test(h)){let ee=h.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),te=s.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),K=ee&&ee[1]||te&&te[1];if(K)try{let{remoteAutoFixPath:ae}=$o(),se=K.startsWith("/")?K.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(o.user||"root"),ie=await ae(o,se,K);if(ie.fixedPath){let Be=s.replace(K,ie.fixedPath);console.log(`${fe.dim} \u2713 remote auto-fix: ${K} \u2192 ${ie.fixedPath}${fe.reset}`);let Re=await Nt(o,Be,{timeout:i,sudo:r}),W=[Re.stdout,Re.stderr].filter(Boolean).join(`
537
- `).trim();if(Re.exitCode===0)return`${ie.message}
538
- ${W}`||"(command completed, no output)"}else if(ie.message)return`EXIT ${d}
535
+ ${pe.yellow} \u26A0 Remote command on ${q}: ${s}${pe.reset}`),!await gn(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await Nt(o,s,{timeout:i,sudo:r}),h=[c,u].filter(Boolean).join(`
536
+ `).trim();if(d!==0){if(/no such file or directory/i.test(h)){let ee=h.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),te=s.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),K=ee&&ee[1]||te&&te[1];if(K)try{let{remoteAutoFixPath:ae}=ko(),se=K.startsWith("/")?K.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(o.user||"root"),ie=await ae(o,se,K);if(ie.fixedPath){let Be=s.replace(K,ie.fixedPath);console.log(`${pe.dim} \u2713 remote auto-fix: ${K} \u2192 ${ie.fixedPath}${pe.reset}`);let Ce=await Nt(o,Be,{timeout:i,sudo:r}),H=[Ce.stdout,Ce.stderr].filter(Boolean).join(`
537
+ `).trim();if(Ce.exitCode===0)return`${ie.message}
538
+ ${H}`||"(command completed, no output)"}else if(ie.message)return`EXIT ${d}
539
539
  ${f||h}
540
540
 
541
541
  ${ie.message}`}catch{}}return`EXIT ${d}
@@ -546,35 +546,35 @@ ${f||h||"(no output)"}`}let m=/\bgrep\b/.test(s),g=h;m&&(g=g.split(`
546
546
  `+k.slice(-_).join(`
547
547
  `));let $=4,O=g.split(`
548
548
  `),E=[],T=0;for(;T<O.length;){let q=T+1;for(;q<O.length&&O[q]===O[T];)q++;let ee=q-T;if(E.push(O[T]),ee>$)E.push(`... (${ee-1} identical lines omitted)`);else for(let te=1;te<ee;te++)E.push(O[T]);T=q}return E.join(`
549
- `)||"(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=nn(e.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
550
- ${fe.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${fe.reset}`),!await gn(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await ET(o,e.local_path,e.remote_path);try{$o().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=nn(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await dy(o,e.remote_path,e.local_path)}catch(s){if(/no such file|not found/i.test(s.message))try{let{remoteAutoFixPath:r}=$o(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(o,i,e.remote_path);if(a.fixedPath){console.log(`${fe.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${fe.reset}`);let l=await dy(o,a.fixedPath,e.local_path);return`${a.message}
549
+ `)||"(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=sn(e.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
550
+ ${pe.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${pe.reset}`),!await gn(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await CT(o,e.local_path,e.remote_path);try{ko().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=sn(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await py(o,e.remote_path,e.local_path)}catch(s){if(/no such file|not found/i.test(s.message))try{let{remoteAutoFixPath:r}=ko(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(o,i,e.remote_path);if(a.fixedPath){console.log(`${pe.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${pe.reset}`);let l=await py(o,a.fixedPath,e.local_path);return`${a.message}
551
551
  ${l}`}if(a.message)return`ERROR: ${s.message}
552
552
 
553
553
  ${a.message}`}catch{}return`ERROR: ${s.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),s=null;try{s=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=s?`${s.user||"root"}@${s.host}`:e.server,i=s?.key?["-i",s.key]:[],a=(e.project_path||s?.home||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),l=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),u=['TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt) && chmod 600 "$TMPFILE"',`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",r,`bash -c '${u}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let h=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
554
- ${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=Lu(e.service);if(o)return o;let s=["status","start","stop","restart","reload","enable","disable"];if(!s.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${s.join(", ")}`;let r=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",a=null;if(!r)try{a=nn(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(`
555
- ${fe.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${u}${fe.reset}`),!await gn(" Execute?"))return"CANCELLED: User declined service action."}let l=e.service.includes(".")?e.service:`${e.service}.service`,c=`systemctl ${e.action} ${De(l)}`;if(r){let d=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:f,stderr:h}=await lt(d,{timeout:15e3});return(f||h||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(f){let h=(f.stderr||f.message||"").toString().trim();return/not found|loaded.*not-found/i.test(h)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${f.code||1}
554
+ ${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=ju(e.service);if(o)return o;let s=["status","start","stop","restart","reload","enable","disable"];if(!s.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${s.join(", ")}`;let r=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",a=null;if(!r)try{a=sn(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(`
555
+ ${pe.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${u}${pe.reset}`),!await gn(" Execute?"))return"CANCELLED: User declined service action."}let l=e.service.includes(".")?e.service:`${e.service}.service`,c=`systemctl ${e.action} ${De(l)}`;if(r){let d=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:f,stderr:h}=await lt(d,{timeout:15e3});return(f||h||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(f){let h=(f.stderr||f.message||"").toString().trim();return/not found|loaded.*not-found/i.test(h)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${f.code||1}
556
556
  ${h}`}}else{let{stdout:u,stderr:d,exitCode:f,error:h}=await Nt(a,c,{timeout:15e3,sudo:!0}),m=[u,d].filter(Boolean).join(`
557
557
  `).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}
558
- ${h||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=Lu(e.service);if(o)return o;let s=!e.server||e.server==="local"||e.server==="localhost",r=e.lines||50,i=e.service.includes(".")?e.service:`${e.service}.service`,a=e.since?`--since ${De(e.since)}`:"",l=e.follow?"-f":"",c=`journalctl -u ${De(i)} -n ${r} ${a} ${l} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:_,stderr:k}=await lt(c,{timeout:15e3});return(_||k||"(no log output)").trim()}catch(_){return`EXIT ${_.code||1}
559
- ${(_.stderr||_.message||"").toString().trim()}`}let u;try{u=nn(e.server)}catch(_){return`ERROR: ${_.message}`}let{stdout:d,stderr:f,exitCode:h,error:m}=await Nt(u,c,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
558
+ ${h||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=ju(e.service);if(o)return o;let s=!e.server||e.server==="local"||e.server==="localhost",r=e.lines||50,i=e.service.includes(".")?e.service:`${e.service}.service`,a=e.since?`--since ${De(e.since)}`:"",l=e.follow?"-f":"",c=`journalctl -u ${De(i)} -n ${r} ${a} ${l} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:_,stderr:k}=await lt(c,{timeout:15e3});return(_||k||"(no log output)").trim()}catch(_){return`EXIT ${_.code||1}
559
+ ${(_.stderr||_.message||"").toString().trim()}`}let u;try{u=sn(e.server)}catch(_){return`ERROR: ${_.message}`}let{stdout:d,stderr:f,exitCode:h,error:m}=await Nt(u,c,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
560
560
  `).trim();return h!==0?`EXIT ${h}
561
561
  ${m||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let o=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(o)try{let{stdout:f,stderr:h}=await lt(r,{timeout:1e4});return(f||h||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
562
- ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=nn(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await Nt(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
562
+ ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=sn(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await Nt(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
563
563
  `).trim();return c!==0?`EXIT ${c}
564
564
  ${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",s=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${s} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(o)try{let{stdout:h,stderr:m}=await lt(i,{timeout:15e3});return(h||m||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
565
- ${(h.stderr||h.message||"").toString().trim()}`}let a;try{a=nn(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await Nt(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
565
+ ${(h.stderr||h.message||"").toString().trim()}`}let a;try{a=sn(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await Nt(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
566
566
  `).trim();return u!==0?`EXIT ${u}
567
567
  ${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let o=!e.server||e.server==="local"||e.server==="localhost",s=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!n.autoConfirm&&!s.test(e.command.trim())){let m=o?"local":e.server;if(console.log(`
568
- ${fe.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${fe.reset}`),!await gn(" 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 lt(a,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
569
- ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=nn(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await Nt(l,a,{timeout:35e3}),h=[c,u].filter(Boolean).join(`
568
+ ${pe.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${pe.reset}`),!await gn(" 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 lt(a,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
569
+ ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=sn(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await Nt(l,a,{timeout:35e3}),h=[c,u].filter(Boolean).join(`
570
570
  `).trim();return d!==0?`EXIT ${d}
571
571
  ${f||h}`:h||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let o=["start","stop","restart","remove","inspect"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let s=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!n.autoConfirm){let m=s?"local":e.server;if(console.log(`
572
- ${fe.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${fe.reset}`),!await gn(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(s)try{let{stdout:m,stderr:g}=await lt(a,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
573
- ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=nn(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await Nt(l,a,{timeout:35e3}),h=[c,u].filter(Boolean).join(`
572
+ ${pe.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${pe.reset}`),!await gn(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(s)try{let{stdout:m,stderr:g}=await lt(a,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
573
+ ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=sn(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await Nt(l,a,{timeout:35e3}),h=[c,u].filter(Boolean).join(`
574
574
  `).trim();return d!==0?`EXIT ${d}
575
- ${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...TT(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 s;try{s=nn(e.server)}catch(u){return`ERROR: ${u.message}`}let r=s.user?`${s.user}@${s.host}`:s.host;if(!e.dry_run&&!n.autoConfirm){if(o==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
576
- ${fe.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${fe.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
577
- ${fe.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${fe.reset}`)}if(e.deploy_script&&console.log(`${fe.yellow} Then run: ${e.deploy_script}${fe.reset}`),e.health_check&&console.log(`${fe.yellow} Health check: ${e.health_check}${fe.reset}`),!await gn(" 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}:
575
+ ${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...AT(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 s;try{s=sn(e.server)}catch(u){return`ERROR: ${u.message}`}let r=s.user?`${s.user}@${s.host}`:s.host;if(!e.dry_run&&!n.autoConfirm){if(o==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
576
+ ${pe.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${pe.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
577
+ ${pe.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${pe.reset}`)}if(e.deploy_script&&console.log(`${pe.yellow} Then run: ${e.deploy_script}${pe.reset}`),e.health_check&&console.log(`${pe.yellow} Health check: ${e.health_check}${pe.reset}`),!await gn(" 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}:
578
578
  ${f}${e.deploy_script?`
579
579
  ${e.deploy_script}`:""}`;let{stdout:h,stderr:m,exitCode:g,error:_}=await Nt(s,f,{timeout:12e4});if(i=[h,m].filter(Boolean).join(`
580
580
  `).trim(),g!==0)return`ERROR (git pull, exit ${g}):
@@ -598,9 +598,9 @@ Health check FAILED: ${u} \u2192 ${f.message}`,(o==="git"?"git pull OK":"rsync O
598
598
  Health check FAILED (exit ${m}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
599
599
 
600
600
  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}
601
- ${i}${a}${l}`.trim()}case"deployment_status":{let o=RT(),s=e.config?[e.config]:Object.keys(o);if(s.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of s){let a=o[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let l=nn(a.server||i),u=(await Nt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{d=(await Nt(l,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let h=a.health_check.trim();if(/^https?:\/\//.test(h))try{let m=require("node-fetch"),g=await Promise.race([m(h),new Promise((_,k)=>setTimeout(()=>k(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(m){f=`unhealthy: ${m.message.substring(0,50)}`}else try{f=(await Nt(l,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
601
+ ${i}${a}${l}`.trim()}case"deployment_status":{let o=OT(),s=e.config?[e.config]:Object.keys(o);if(s.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of s){let a=o[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let l=sn(a.server||i),u=(await Nt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{d=(await Nt(l,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let h=a.health_check.trim();if(/^https?:\/\//.test(h))try{let m=require("node-fetch"),g=await Promise.race([m(h),new Promise((_,k)=>setTimeout(()=>k(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(m){f=`unhealthy: ${m.message.substring(0,50)}`}else try{f=(await Nt(l,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
602
602
  ${r.join(`
603
- `)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(E,T=120)=>{try{let q=re.isAbsolute(E)?E:re.join(o,E),te=(await ft.readFile(q,"utf8")).split(`
603
+ `)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(E,T=120)=>{try{let q=re.isAbsolute(E)?E:re.join(o,E),te=(await pt.readFile(q,"utf8")).split(`
604
604
  `),K=te.slice(0,T).join(`
605
605
  `);return te.length>T?K+`
606
606
  ... (${te.length-T} more lines \u2014 use read_file for full content)`:K}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(E=>`-not -path "*/${E}/*"`).join(" "),c=async E=>{try{let{stdout:T}=await lt(`find "${o}" -type f -name "${E}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return T.trim().split(`
@@ -628,26 +628,26 @@ ${q}
628
628
  ${T}
629
629
  \`\`\``):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(`
630
630
  ## STEP 4: Framework Stack
631
- `);let k=[],$=await i(re.join(o,"package.json"),999);if($){if(($.includes('"react"')||$.includes("'react'"))&&k.push("React"),$.includes('"vue"')||$.includes("'vue'")){let T=$.match(/"vue":\s*"[\^~]?(\d+)/);k.push(T?`Vue.js v${T[1]}`:"Vue.js")}let E=$.match(/"alpinejs":\s*"[\^~]?(\d+)/);E&&k.push(`Alpine.js v${E[1]} (\u26A0 v2 vs v3 API differs!)`),($.includes('"htmx')||$.includes("'htmx"))&&k.push("HTMX"),$.includes('"tailwindcss"')&&k.push("Tailwind CSS"),$.includes('"bootstrap"')&&k.push("Bootstrap")}if((await Gt(re.join(o,"manage.py"))||(await i(re.join(o,"requirements.txt"),50)||"").includes("Django"))&&k.push("Django (server-rendered templates)"),!k.some(E=>E.includes("Alpine"))){let E=await u("alpinejs","*.html");if(E.length>0){let q=(await i(E[0],30)||"").match(/alpinejs[@/]v?(\d)/);k.push(q?`Alpine.js v${q[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return k.some(E=>E.includes("HTMX"))||(await u("htmx","*.html")).length>0&&k.push("HTMX (via CDN)"),k.length>0?(r.push(k.map(E=>`- ${E}`).join(`
631
+ `);let k=[],$=await i(re.join(o,"package.json"),999);if($){if(($.includes('"react"')||$.includes("'react'"))&&k.push("React"),$.includes('"vue"')||$.includes("'vue'")){let T=$.match(/"vue":\s*"[\^~]?(\d+)/);k.push(T?`Vue.js v${T[1]}`:"Vue.js")}let E=$.match(/"alpinejs":\s*"[\^~]?(\d+)/);E&&k.push(`Alpine.js v${E[1]} (\u26A0 v2 vs v3 API differs!)`),($.includes('"htmx')||$.includes("'htmx"))&&k.push("HTMX"),$.includes('"tailwindcss"')&&k.push("Tailwind CSS"),$.includes('"bootstrap"')&&k.push("Bootstrap")}if((await zt(re.join(o,"manage.py"))||(await i(re.join(o,"requirements.txt"),50)||"").includes("Django"))&&k.push("Django (server-rendered templates)"),!k.some(E=>E.includes("Alpine"))){let E=await u("alpinejs","*.html");if(E.length>0){let q=(await i(E[0],30)||"").match(/alpinejs[@/]v?(\d)/);k.push(q?`Alpine.js v${q[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return k.some(E=>E.includes("HTMX"))||(await u("htmx","*.html")).length>0&&k.push("HTMX (via CDN)"),k.length>0?(r.push(k.map(E=>`- ${E}`).join(`
632
632
  `)),r.push(`
633
633
  \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(`
634
634
  ---
635
635
  \u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
636
- `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",s;if(!o)try{s=nn(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(o)try{let{stdout:u,stderr:d}=await lt(l,{timeout:c});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:h}=await Nt(s,l,{timeout:c}),m=[u,d].filter(Boolean).join(`
636
+ `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",s;if(!o)try{s=sn(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(o)try{let{stdout:u,stderr:d}=await lt(l,{timeout:c});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:h}=await Nt(s,l,{timeout:c}),m=[u,d].filter(Boolean).join(`
637
637
  `).trim();return{out:h&&f!==0&&!u.trim()?(h+`
638
638
  `+m).trim():m,exitCode:f}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!n.autoConfirm){let l=o?"local":e.server;if(!await gn(`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}
639
639
  (no output)`}case"disk_usage":{let l=e.path||"/",c=De(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}
640
640
  ${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}
641
641
  ${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}
642
- ${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(WT))return"ERROR: package names contain unsafe characters";let d=u.map(De).join(" "),f;switch(e.package_action){case"list":f=c==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=c==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:_}=await r(g,6e4);return _||"(no output from package check)"}case"install":if(!d)return"ERROR: packages required for install";f=c==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=c==="dnf"?`dnf remove -y ${d}`:`apt-get remove -y ${d}`;break;case"update":if(!d)return"ERROR: packages required for update (use upgrade for full system upgrade)";f=c==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=c==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:h,exitCode:m}=await r(f,12e4);return m!==0?`EXIT ${m}
642
+ ${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(YT))return"ERROR: package names contain unsafe characters";let d=u.map(De).join(" "),f;switch(e.package_action){case"list":f=c==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=c==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:_}=await r(g,6e4);return _||"(no output from package check)"}case"install":if(!d)return"ERROR: packages required for install";f=c==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=c==="dnf"?`dnf remove -y ${d}`:`apt-get remove -y ${d}`;break;case"update":if(!d)return"ERROR: packages required for update (use upgrade for full system upgrade)";f=c==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=c==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:h,exitCode:m}=await r(f,12e4);return m!==0?`EXIT ${m}
643
643
  ${h}`:h||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let l=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:c,exitCode:u}=await r(l,1e4);return u!==0?`EXIT ${u}
644
- ${c}`:c||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=Cr(e.user);if(l)return l;let c=De(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}
645
- ${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=Cr(e.user);if(l)return l;if(!(e.groups||[]).every(xy))return"ERROR: groups contain unsafe characters";let c=(e.groups||[]).map(m=>`-G ${De(m)}`).join(" "),u=De(e.user),d=`useradd -m ${c} ${u} && echo "User ${e.user} created"`,{out:f,exitCode:h}=await r(d,15e3);return h!==0?`EXIT ${h}
646
- ${f}`:f}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=Cr(e.user);if(l)return l;let u=`userdel -r ${De(e.user)} && echo "User ${e.user} deleted"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
647
- ${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=Cr(e.user);if(l)return l;let u=`${`/home/${e.user}`}/.ssh`,d=`${u}/authorized_keys`,f=De(e.user),h=`mkdir -p ${De(u)} && chmod 700 ${De(u)} && printf '%s
644
+ ${c}`:c||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=Ar(e.user);if(l)return l;let c=De(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}
645
+ ${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=Ar(e.user);if(l)return l;if(!(e.groups||[]).every(vy))return"ERROR: groups contain unsafe characters";let c=(e.groups||[]).map(m=>`-G ${De(m)}`).join(" "),u=De(e.user),d=`useradd -m ${c} ${u} && echo "User ${e.user} created"`,{out:f,exitCode:h}=await r(d,15e3);return h!==0?`EXIT ${h}
646
+ ${f}`:f}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=Ar(e.user);if(l)return l;let u=`userdel -r ${De(e.user)} && echo "User ${e.user} deleted"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
647
+ ${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=Ar(e.user);if(l)return l;let u=`${`/home/${e.user}`}/.ssh`,d=`${u}/authorized_keys`,f=De(e.user),h=`mkdir -p ${De(u)} && chmod 700 ${De(u)} && printf '%s
648
648
  ' ${De(e.ssh_key)} >> ${De(d)} && chmod 600 ${De(d)} && chown -R ${De(`${e.user}:${e.user}`)} ${De(u)} && echo "SSH key added for ${e.user}"`,{out:m,exitCode:g}=await r(h,15e3);return g!==0?`EXIT ${g}
649
- ${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(!Mu(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 ${De(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(!Mu(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 ${De(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(!Mu(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 ${De(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}
650
- ${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=Cr(e.user);if(c)return c}let l=e.user?`-u ${De(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
649
+ ${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(!Iu(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 ${De(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(!Iu(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 ${De(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(!Iu(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 ${De(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}
650
+ ${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=Ar(e.user);if(c)return c}let l=e.user?`-u ${De(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
651
651
  ' ${De(c)}) | crontab ${l} - && echo "Cron entry added: ${c}"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
652
652
  ${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}
653
653
  ${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=`
@@ -676,11 +676,11 @@ fi
676
676
  `.trim();let{out:c,exitCode:u}=await r(l,25e3),d=/notAfter=|Days until expiry:/i.test(c);return u!==0&&!d?`EXIT ${u}
677
677
  ${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} ${De(e.path)} 2>&1`,{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
678
678
  ${u}`:u||"(empty log)"}case"find_large":{let l=e.path||"/",c=e.limit||20,u=e.min_size||"100M",d=`find ${De(l)} -xdev -type f -size +${De(u)} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${c}`,{out:f,exitCode:h}=await r(d,6e4);return h!==0?`EXIT ${h}
679
- ${f}`:f||`(no files larger than ${u} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";if(e.service_name){let h=Lu(e.service_name,"service_name");if(h)return h}let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",c;switch(e.service_action){case"status":c=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":c="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":c=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":c=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":c=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":c=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":c=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":c=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(c,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
680
- ${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(!HT(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 ${De(e.process_name)} 2>/dev/null | head -5 && pkill -${l} ${De(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}
679
+ ${f}`:f||`(no files larger than ${u} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";if(e.service_name){let h=ju(e.service_name,"service_name");if(h)return h}let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",c;switch(e.service_action){case"status":c=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":c="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":c=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":c=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":c=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":c=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":c=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":c=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(c,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
680
+ ${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(!zT(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 ${De(e.process_name)} 2>/dev/null | head -5 && pkill -${l} ${De(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}
681
681
  ${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}
682
- ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=Sr(),s=o(e.type,e.name,e.content,e.description);return s.ok?s.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${s.path}`:`ERROR: ${s.error}`}case"delete_memory":{let{deleteMemory:o}=Sr();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=na(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function YT(t,e,n={}){let{emit:o}=na(),{logToolExecution:s}=ry(),r=Date.now(),i=n.silent?null:wT(t,e);if(!i){let l=await gy(t,e,n);return s({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}let a=new bT(i);a.start();try{let l=await gy(t,e,n);return a.stop(),s({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw a.stop(),s({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}Sy.exports={TOOL_DEFINITIONS:GT,executeTool:YT,resolvePath:xt,autoFixPath:Pa,autoFixEdit:ky,enrichBashError:$y,getNodeBuiltinInstallAttempt:yy,cancelPendingAskUser:IT,setAskUserHandler:jT,fileExists:Gt}});var cr=J((QP,Ey)=>{Ey.exports=vy()});var qu=J((tN,Ry)=>{var{loadServerProfiles:Ao,resolveProfile:eN,sshExec:zT}=$o(),KT=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,VT=/\b(bug|issue|problem|broken|failing|fails|error|wrong|regression|debug|investigate|why|slow|fix|delete|deleted|deleting|removed|reappears?|returns?|comes?\s+back|webui|production|prod|server|fehler|kaputt|lösche|loesch|gelösch|geloesch|zurück|zurueck|taucht?\s+wieder\s+auf)\b/i,XT=/https?:\/\/[^\s)]+/gi;function JT(t){if(typeof t!="string")return[];let e=new Set,n=[];for(let o of t.match(XT)||[]){let s=o.replace(/[.,;!?]+$/g,"");e.has(s)||(e.add(s),n.push(s))}return n}function ZT(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return null}let o=n.split(".");for(let[s,r]of Object.entries(e))if(o.includes(s.toLowerCase()))return{matchedName:s,matchedProfile:r,hostname:n};for(let[s,r]of Object.entries(e))if(String(r.host||"").toLowerCase()===n)return{matchedName:s,matchedProfile:r,hostname:n};return{matchedName:null,matchedProfile:null,hostname:n}}function Ty(t,e=Ao()){if(typeof t!="string"||!VT.test(t))return null;let n=JT(t).filter(o=>!KT.test(o));if(n.length===0)return null;for(let o of n){let s=ZT(o,e);if(s)return{url:o,hostname:s.hostname,matchedName:s.matchedName,matchedProfile:s.matchedProfile,shouldPreferBrowser:!0,shouldPreferSsh:!!(s.matchedName&&s.matchedProfile)}}return null}var Du={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 QT(){let t=Ao();if(Object.keys(t).length===0)return null;let n=["## Remote Servers (.nex/servers.json)"];n.push(""),n.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[s,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",c=r.sudo?", sudo available":"";n.push(`- **${s}**: ${i}${a}${l}${c}`)}let o=new Set;for(let s of Object.values(t))s.os&&Du[s.os]&&o.add(s.os);if(o.size>0){n.push("");for(let s of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[s]||s;n.push(`### ${r} Notes`);for(let i of Du[s])n.push(`- ${i}`)}}return n.join(`
683
- `)}function eR(t){let e=Ao();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function tR(){return Object.keys(Ao())}function nR(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(n,"utf-8")}catch{}let s=Ao(),r=Object.keys(s);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=o.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let c=r.map(f=>{let h=s[f],m=h.user?`${h.user}@${h.host}`:h.host,g=h.port&&Number(h.port)!==22?`:${h.port}`:"";return` - **${f}**: ${m}${g}${h.os?` (${h.os})`:""}`}).join(`
682
+ ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=vr(),s=o(e.type,e.name,e.content,e.description);return s.ok?s.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${s.path}`:`ERROR: ${s.error}`}case"delete_memory":{let{deleteMemory:o}=vr();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=sa(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function VT(t,e,n={}){let{emit:o}=sa(),{logToolExecution:s}=ay(),r=Date.now(),i=n.silent?null:kT(t,e);if(!i){let l=await by(t,e,n);return s({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}let a=new $T(i);a.start();try{let l=await by(t,e,n);return a.stop(),s({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw a.stop(),s({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}Ey.exports={TOOL_DEFINITIONS:KT,executeTool:VT,resolvePath:St,autoFixPath:Na,autoFixEdit:Sy,enrichBashError:xy,getNodeBuiltinInstallAttempt:wy,cancelPendingAskUser:qT,setAskUserHandler:FT,fileExists:zt}});var ur=J((sN,Ry)=>{Ry.exports=Ty()});var Bu=J((rN,Ay)=>{var{loadServerProfiles:Oo,resolveProfile:oN,sshExec:XT}=ko(),JT=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,ZT=/\b(bug|issue|problem|broken|failing|fails|error|wrong|regression|debug|investigate|why|slow|fix|delete|deleted|deleting|removed|reappears?|returns?|comes?\s+back|webui|production|prod|server|fehler|kaputt|lösche|loesch|gelösch|geloesch|zurück|zurueck|taucht?\s+wieder\s+auf)\b/i,QT=/https?:\/\/[^\s)]+/gi;function eR(t){if(typeof t!="string")return[];let e=new Set,n=[];for(let o of t.match(QT)||[]){let s=o.replace(/[.,;!?]+$/g,"");e.has(s)||(e.add(s),n.push(s))}return n}function tR(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return null}let o=n.split(".");for(let[s,r]of Object.entries(e))if(o.includes(s.toLowerCase()))return{matchedName:s,matchedProfile:r,hostname:n};for(let[s,r]of Object.entries(e))if(String(r.host||"").toLowerCase()===n)return{matchedName:s,matchedProfile:r,hostname:n};return{matchedName:null,matchedProfile:null,hostname:n}}function Cy(t,e=Oo()){if(typeof t!="string"||!ZT.test(t))return null;let n=eR(t).filter(o=>!JT.test(o));if(n.length===0)return null;for(let o of n){let s=tR(o,e);if(s)return{url:o,hostname:s.hostname,matchedName:s.matchedName,matchedProfile:s.matchedProfile,shouldPreferBrowser:!0,shouldPreferSsh:!!(s.matchedName&&s.matchedProfile)}}return null}var Fu={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 nR(){let t=Oo();if(Object.keys(t).length===0)return null;let n=["## Remote Servers (.nex/servers.json)"];n.push(""),n.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[s,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",c=r.sudo?", sudo available":"";n.push(`- **${s}**: ${i}${a}${l}${c}`)}let o=new Set;for(let s of Object.values(t))s.os&&Fu[s.os]&&o.add(s.os);if(o.size>0){n.push("");for(let s of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[s]||s;n.push(`### ${r} Notes`);for(let i of Fu[s])n.push(`- ${i}`)}}return n.join(`
683
+ `)}function sR(t){let e=Oo();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function oR(){return Object.keys(Oo())}function rR(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(n,"utf-8")}catch{}let s=Oo(),r=Object.keys(s);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=o.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let c=r.map(f=>{let h=s[f],m=h.user?`${h.user}@${h.host}`:h.host,g=h.port&&Number(h.port)!==22?`:${h.port}`:"";return` - **${f}**: ${m}${g}${h.os?` (${h.os})`:""}`}).join(`
684
684
  `),u=r.map(f=>s[f].log_path).filter(Boolean),d=u.length>0?`
685
685
  - Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
686
686
 
@@ -699,7 +699,7 @@ ${c}
699
699
  - \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
700
700
  - \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
701
701
 
702
- **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${sR(s)}`}function sR(t){return Object.values(t).some(n=>n.host==="94.130.37.43")?`
702
+ **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${iR(s)}`}function iR(t){return Object.values(t).some(n=>n.host==="94.130.37.43")?`
703
703
 
704
704
  ## Server Debugging Rules
705
705
 
@@ -710,40 +710,40 @@ ${c}
710
710
  - 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.
711
711
  - 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.
712
712
  - 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.
713
- - 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 oR(t){let e=Ao(),n=Ty(t,e);if(!n?.matchedProfile||!n?.matchedName)return null;let{matchedProfile:o,matchedName:s}=n,r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await zT(o,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=o.user?`${o.user}@${o.host}`:o.host;return`[Server context for "${s}" (${a}) \u2014 probed at task start]
714
- `+i.trim()}catch{return null}}Ry.exports={getServerContext:QT,getDeploymentContextBlock:nR,hasServerOS:eR,getProfileNames:tR,probeUrlServer:oR,detectRuntimeDebugTarget:Ty,OS_HINTS:Du}});var Py=J((nN,Oy)=>{var St=require("fs").promises,Ma=require("fs"),ze=require("path"),Pr=require("util").promisify(require("child_process").exec),{C:Oo}=_t(),{getMergeConflicts:Ay}=Ji(),{getServerContext:rR}=qu(),{refreshIndex:iR,getFileIndex:aR,buildContentIndex:lR,summarizeModuleHubs:cR}=Rn(),uR=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),dR=[{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 fR(t,e=6){let n=new Map;for(let o of t){let s=o.includes("/")?o.split("/")[0]:"(root)";!s||s.startsWith(".")||n.set(s,(n.get(s)||0)+1)}return[...n.entries()].sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])).slice(0,e).map(([o,s])=>`${o} (${s})`)}function pR(t){let e=new Set(t),n=new Set;for(let o of dR)(e.has(o.file)||[...e].some(s=>s.startsWith(`${o.file}/`)))&&n.add(o.label);return e.has("package.json")&&n.add("Node.js"),[...e].some(o=>/^tests?\//.test(o)||/\.test\./.test(o)||/\.spec\./.test(o))&&n.add("Tests"),[...e].some(o=>o.startsWith("vscode/"))&&n.add("VS Code Extension"),[...n]}function hR(t){let e=["package.json","cli/index.js","src/index.ts","src/index.js","index.ts","index.js","bin/nex-code.js","dist/nex-code.js","README.md"],n=[];for(let o of e)if(t.includes(o)&&n.push(o),n.length>=5)break;return n}function mR(t,e=6){let n=t.filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(n.length===0)return[];let o=t.filter(r=>!/^tests?\//.test(r)&&!/\.test\./.test(r)&&!/\.spec\./.test(r)&&/\.(js|jsx|ts|tsx|py|go|rs|java)$/.test(r)),s=[];for(let r of o){let i=ze.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=n.filter(l=>l.includes(i));if(a.length>0&&s.push(`${r} -> ${a.slice(0,2).join(", ")}`),s.length>=e)break}return s}function gR(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function yR(t){try{await iR(t);let e=aR();if(!e||e.length===0)return"";let n=pR(e),o=fR(e),s=hR(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=mR(e),a=[];try{let d=ze.join(t,"package.json");if(Ma.existsSync(d)){let f=JSON.parse(Ma.readFileSync(d,"utf-8"));a=gR(f)}}catch{}let l="",c="";try{let d=await lR(t),f=Object.entries(d.files||{}).map(([h,m])=>({file:h,defs:Array.isArray(m.defs)?m.defs.length:0})).filter(h=>h.defs>0).sort((h,m)=>m.defs-h.defs||h.file.localeCompare(m.file)).slice(0,4).map(h=>`${h.file} (${h.defs} defs)`);f.length>0&&(l=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await cR(t,4);d.length>0&&(c=`MODULE HUBS: ${d.join(", ")}`)}catch{}let u=[`REPO MAP: ${e.length} indexed files${n.length?` | stack: ${n.join(", ")}`:""}`];return o.length>0&&u.push(`WORK AREAS: ${o.join(", ")}`),s.length>0&&u.push(`LIKELY ENTRY POINTS: ${s.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(`
715
- `)}catch{return""}}function bR(t){try{return Ma.readFileSync(t,"utf-8").split(`
716
- `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function wR(t,e){for(let n of e)if(n===t||n.includes("*")&&new RegExp("^"+n.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function _R(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=ze.join(t,".gitignore"),r=[...o,...bR(s)],i=0,a=[ze.basename(t)+"/"];function l(c,u,d){if(d>e||i>=n)return;let f;try{f=Ma.readdirSync(c,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=f.filter(m=>!(uR.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||wR(m.name,r)));for(let m=0;m<h.length;m++){if(i>=n){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],_=m===h.length-1,k=_?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",$=u+(_?" ":"\u2502 "),O=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${k}${O}`),i++,g.isDirectory()&&l(ze.join(c,g.name),$,d+1)}}return l(t,"",1),a.join(`
717
- `)}var Fu=new Map,No=new Map,La=null,Cy=3e4,Po={result:null,expiry:0,cwd:null};async function sn(t){try{return await t()}catch{return null}}async function $R(){if(!La||Date.now()>La)return!1;let t=[ze.join(process.cwd(),"package.json"),ze.join(process.cwd(),"README.md"),ze.join(process.cwd(),"AGENTS.md"),ze.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await St.stat(e),o=No.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(No.has(e))return!1}try{let e=ze.join(process.cwd(),".git","HEAD"),n=await St.stat(e),o=No.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function kR(){let t=[ze.join(process.cwd(),"package.json"),ze.join(process.cwd(),"README.md"),ze.join(process.cwd(),"AGENTS.md"),ze.join(process.cwd(),".gitignore"),ze.join(process.cwd(),".git","HEAD"),ze.join(process.cwd(),"CLAUDE.md"),ze.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let n=await St.stat(e);No.set(e,n.mtimeMs)}catch{No.delete(e)}}async function xR(t){let e="fileContext",n=Fu.get(e),o=!1;if(n&&await $R()&&(o=!0),!o){let u=[],d=ze.join(t,"package.json");if(await sn(()=>St.access(d).then(()=>!0).catch(()=>!1)))try{let te=await St.readFile(d,"utf-8"),K=JSON.parse(te),ae={name:K.name,version:K.version};if(K.scripts&&(ae.scripts=Object.keys(K.scripts).slice(0,15)),K.dependencies&&(ae.deps=Object.keys(K.dependencies).length),K.devDependencies&&(ae.devDeps=Object.keys(K.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(ae)}`),K.scripts){let se=["test","build","lint","typecheck","check","benchmark:gate","benchmark"].filter(ie=>K.scripts[ie]).map(ie=>`${ie}=${K.scripts[ie]}`).slice(0,8);se.length>0&&u.push(`PACKAGE SCRIPTS:
713
+ - 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 aR(t){let e=Oo(),n=Cy(t,e);if(!n?.matchedProfile||!n?.matchedName)return null;let{matchedProfile:o,matchedName:s}=n,r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await XT(o,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=o.user?`${o.user}@${o.host}`:o.host;return`[Server context for "${s}" (${a}) \u2014 probed at task start]
714
+ `+i.trim()}catch{return null}}Ay.exports={getServerContext:nR,getDeploymentContextBlock:rR,hasServerOS:sR,getProfileNames:oR,probeUrlServer:aR,detectRuntimeDebugTarget:Cy,OS_HINTS:Fu}});var My=J((iN,Ny)=>{var vt=require("fs").promises,La=require("fs"),Ke=require("path"),Nr=require("util").promisify(require("child_process").exec),{C:Po}=$t(),{getMergeConflicts:Py}=Zi(),{getServerContext:lR}=Bu(),{refreshIndex:cR,getFileIndex:uR,buildContentIndex:dR,summarizeModuleHubs:fR}=Rn(),pR=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),hR=[{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 mR(t,e=6){let n=new Map;for(let o of t){let s=o.includes("/")?o.split("/")[0]:"(root)";!s||s.startsWith(".")||n.set(s,(n.get(s)||0)+1)}return[...n.entries()].sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])).slice(0,e).map(([o,s])=>`${o} (${s})`)}function gR(t){let e=new Set(t),n=new Set;for(let o of hR)(e.has(o.file)||[...e].some(s=>s.startsWith(`${o.file}/`)))&&n.add(o.label);return e.has("package.json")&&n.add("Node.js"),[...e].some(o=>/^tests?\//.test(o)||/\.test\./.test(o)||/\.spec\./.test(o))&&n.add("Tests"),[...e].some(o=>o.startsWith("vscode/"))&&n.add("VS Code Extension"),[...n]}function yR(t){let e=["package.json","cli/index.js","src/index.ts","src/index.js","index.ts","index.js","bin/nex-code.js","dist/nex-code.js","README.md"],n=[];for(let o of e)if(t.includes(o)&&n.push(o),n.length>=5)break;return n}function bR(t,e=6){let n=t.filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(n.length===0)return[];let o=t.filter(r=>!/^tests?\//.test(r)&&!/\.test\./.test(r)&&!/\.spec\./.test(r)&&/\.(js|jsx|ts|tsx|py|go|rs|java)$/.test(r)),s=[];for(let r of o){let i=Ke.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=n.filter(l=>l.includes(i));if(a.length>0&&s.push(`${r} -> ${a.slice(0,2).join(", ")}`),s.length>=e)break}return s}function wR(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function _R(t){try{await cR(t);let e=uR();if(!e||e.length===0)return"";let n=gR(e),o=mR(e),s=yR(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=bR(e),a=[];try{let d=Ke.join(t,"package.json");if(La.existsSync(d)){let f=JSON.parse(La.readFileSync(d,"utf-8"));a=wR(f)}}catch{}let l="",c="";try{let d=await dR(t),f=Object.entries(d.files||{}).map(([h,m])=>({file:h,defs:Array.isArray(m.defs)?m.defs.length:0})).filter(h=>h.defs>0).sort((h,m)=>m.defs-h.defs||h.file.localeCompare(m.file)).slice(0,4).map(h=>`${h.file} (${h.defs} defs)`);f.length>0&&(l=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await fR(t,4);d.length>0&&(c=`MODULE HUBS: ${d.join(", ")}`)}catch{}let u=[`REPO MAP: ${e.length} indexed files${n.length?` | stack: ${n.join(", ")}`:""}`];return o.length>0&&u.push(`WORK AREAS: ${o.join(", ")}`),s.length>0&&u.push(`LIKELY ENTRY POINTS: ${s.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(`
715
+ `)}catch{return""}}function $R(t){try{return La.readFileSync(t,"utf-8").split(`
716
+ `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function kR(t,e){for(let n of e)if(n===t||n.includes("*")&&new RegExp("^"+n.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function xR(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=Ke.join(t,".gitignore"),r=[...o,...$R(s)],i=0,a=[Ke.basename(t)+"/"];function l(c,u,d){if(d>e||i>=n)return;let f;try{f=La.readdirSync(c,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=f.filter(m=>!(pR.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||kR(m.name,r)));for(let m=0;m<h.length;m++){if(i>=n){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],_=m===h.length-1,k=_?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",$=u+(_?" ":"\u2502 "),O=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${k}${O}`),i++,g.isDirectory()&&l(Ke.join(c,g.name),$,d+1)}}return l(t,"",1),a.join(`
717
+ `)}var Uu=new Map,Mo=new Map,Ia=null,Oy=3e4,No={result:null,expiry:0,cwd:null};async function on(t){try{return await t()}catch{return null}}async function SR(){if(!Ia||Date.now()>Ia)return!1;let t=[Ke.join(process.cwd(),"package.json"),Ke.join(process.cwd(),"README.md"),Ke.join(process.cwd(),"AGENTS.md"),Ke.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await vt.stat(e),o=Mo.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(Mo.has(e))return!1}try{let e=Ke.join(process.cwd(),".git","HEAD"),n=await vt.stat(e),o=Mo.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function vR(){let t=[Ke.join(process.cwd(),"package.json"),Ke.join(process.cwd(),"README.md"),Ke.join(process.cwd(),"AGENTS.md"),Ke.join(process.cwd(),".gitignore"),Ke.join(process.cwd(),".git","HEAD"),Ke.join(process.cwd(),"CLAUDE.md"),Ke.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let n=await vt.stat(e);Mo.set(e,n.mtimeMs)}catch{Mo.delete(e)}}async function ER(t){let e="fileContext",n=Uu.get(e),o=!1;if(n&&await SR()&&(o=!0),!o){let u=[],d=Ke.join(t,"package.json");if(await on(()=>vt.access(d).then(()=>!0).catch(()=>!1)))try{let te=await vt.readFile(d,"utf-8"),K=JSON.parse(te),ae={name:K.name,version:K.version};if(K.scripts&&(ae.scripts=Object.keys(K.scripts).slice(0,15)),K.dependencies&&(ae.deps=Object.keys(K.dependencies).length),K.devDependencies&&(ae.devDeps=Object.keys(K.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(ae)}`),K.scripts){let se=["test","build","lint","typecheck","check","benchmark:gate","benchmark"].filter(ie=>K.scripts[ie]).map(ie=>`${ie}=${K.scripts[ie]}`).slice(0,8);se.length>0&&u.push(`PACKAGE SCRIPTS:
718
718
  ${se.join(`
719
- `)}`)}}catch{}let h=ze.join(t,"README.md");if(await sn(()=>St.access(h).then(()=>!0).catch(()=>!1))){let K=(await St.readFile(h,"utf-8")).split(`
719
+ `)}`)}}catch{}let h=Ke.join(t,"README.md");if(await on(()=>vt.access(h).then(()=>!0).catch(()=>!1))){let K=(await vt.readFile(h,"utf-8")).split(`
720
720
  `).slice(0,50);u.push(`README (first 50 lines):
721
721
  ${K.join(`
722
- `)}`)}let g=ze.join(t,".gitignore");if(await sn(()=>St.access(g).then(()=>!0).catch(()=>!1))){let te=await St.readFile(g,"utf-8");u.push(`GITIGNORE:
723
- ${te.trim()}`)}let k=ze.join(t,"AGENTS.md");if(await sn(()=>St.access(k).then(()=>!0).catch(()=>!1))){let te=await St.readFile(k,"utf-8");te.trim()&&u.push(`PROJECT INSTRUCTIONS (AGENTS.md):
724
- ${te.trim()}`)}let O=ze.join(t,"CLAUDE.md");if(await sn(()=>St.access(O).then(()=>!0).catch(()=>!1))){let te=await St.readFile(O,"utf-8");te.trim()&&u.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
725
- ${te.trim()}`)}let T=ze.join(t,".nex","CLAUDE.md");if(await sn(()=>St.access(T).then(()=>!0).catch(()=>!1))){let te=await St.readFile(T,"utf-8");te.trim()&&u.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
726
- ${te.trim()}`)}let ee=await yR(t);ee&&u.push(ee),n=u.join(`
722
+ `)}`)}let g=Ke.join(t,".gitignore");if(await on(()=>vt.access(g).then(()=>!0).catch(()=>!1))){let te=await vt.readFile(g,"utf-8");u.push(`GITIGNORE:
723
+ ${te.trim()}`)}let k=Ke.join(t,"AGENTS.md");if(await on(()=>vt.access(k).then(()=>!0).catch(()=>!1))){let te=await vt.readFile(k,"utf-8");te.trim()&&u.push(`PROJECT INSTRUCTIONS (AGENTS.md):
724
+ ${te.trim()}`)}let O=Ke.join(t,"CLAUDE.md");if(await on(()=>vt.access(O).then(()=>!0).catch(()=>!1))){let te=await vt.readFile(O,"utf-8");te.trim()&&u.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
725
+ ${te.trim()}`)}let T=Ke.join(t,".nex","CLAUDE.md");if(await on(()=>vt.access(T).then(()=>!0).catch(()=>!1))){let te=await vt.readFile(T,"utf-8");te.trim()&&u.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
726
+ ${te.trim()}`)}let ee=await _R(t);ee&&u.push(ee),n=u.join(`
727
727
 
728
- `),Fu.set(e,n),La=Date.now()+Cy,await kR()}let s=[n],r,i,a,l,c;if(Po.result&&Date.now()<Po.expiry&&Po.cwd===t?{branch:r,status:i,log:a,diffStat:l,conflicts:c}=Po.result:([r,i,a,l,c]=await Promise.all([sn(async()=>{let{stdout:u}=await Pr("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),sn(async()=>{let{stdout:u}=await Pr("git status --short",{cwd:t,timeout:5e3});return u.trim()}),sn(async()=>{let{stdout:u}=await Pr("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),sn(async()=>{let{stdout:u}=await Pr("git diff --stat -- .",{cwd:t,timeout:5e3,maxBuffer:2e4});return u.trim()}),Ay()]),Po={result:{branch:r,status:i,log:a,diffStat:l,conflicts:c},expiry:Date.now()+Cy,cwd:t}),r&&s.push(`GIT BRANCH: ${r}`),i&&s.push(`GIT STATUS:
728
+ `),Uu.set(e,n),Ia=Date.now()+Oy,await vR()}let s=[n],r,i,a,l,c;if(No.result&&Date.now()<No.expiry&&No.cwd===t?{branch:r,status:i,log:a,diffStat:l,conflicts:c}=No.result:([r,i,a,l,c]=await Promise.all([on(async()=>{let{stdout:u}=await Nr("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),on(async()=>{let{stdout:u}=await Nr("git status --short",{cwd:t,timeout:5e3});return u.trim()}),on(async()=>{let{stdout:u}=await Nr("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),on(async()=>{let{stdout:u}=await Nr("git diff --stat -- .",{cwd:t,timeout:5e3,maxBuffer:2e4});return u.trim()}),Py()]),No={result:{branch:r,status:i,log:a,diffStat:l,conflicts:c},expiry:Date.now()+Oy,cwd:t}),r&&s.push(`GIT BRANCH: ${r}`),i&&s.push(`GIT STATUS:
729
729
  ${i}`),l&&s.push(`GIT DIFF STAT:
730
730
  ${l}`),a&&s.push(`RECENT COMMITS:
731
731
  ${a}`),c&&c.length>0){let u=c.map(d=>` ${d.file}`).join(`
732
732
  `);s.push(`MERGE CONFLICTS (resolve before editing these files):
733
- ${u}`)}try{let u=rR();u&&s.push(u)}catch{}return s.join(`
733
+ ${u}`)}try{let u=lR();u&&s.push(u)}catch{}return s.join(`
734
734
 
735
- `)}async function SR(t){let e=ze.join(t,"package.json"),n="";if(await sn(()=>St.access(e).then(()=>!0).catch(()=>!1)))try{let i=await St.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([sn(async()=>{let{stdout:i}=await Pr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Ay()]);if(r&&r.length>0){console.log(`${Oo.red} \u26A0 ${r.length} unresolved merge conflict(s):${Oo.reset}`);for(let i of r)console.log(`${Oo.red} ${i.file}${Oo.reset}`);console.log(`${Oo.yellow} \u2192 Resolve conflicts before starting tasks${Oo.reset}`)}console.log()}Oy.exports={gatherProjectContext:xR,printContext:SR,generateFileTree:_R,_clearContextCache:()=>{Fu.clear(),No.clear(),La=null,Po={result:null,expiry:0,cwd:null}}}});var ja=J((sN,Ly)=>{var bn=require("fs"),Ia=require("path"),{atomicWrite:vR}=Ss();function Mr(){return Ia.join(process.cwd(),".nex","sessions")}function Bu(){let t=Mr();bn.existsSync(t)||bn.mkdirSync(t,{recursive:!0,mode:448})}function Uu(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ia.join(Mr(),`${e}.json`)}function Wu(t,e,n={}){Bu();let o=Uu(t),s={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return vR(o,JSON.stringify(s,null,2)),{path:o,name:t}}function Ny(t){let e=Uu(t);if(!bn.existsSync(e))return null;try{return JSON.parse(bn.readFileSync(e,"utf-8"))}catch{return null}}function My(){Bu();let t=Mr(),e=bn.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(bn.readFileSync(Ia.join(t,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function ER(t){let e=Uu(t);return bn.existsSync(e)?(bn.unlinkSync(e),!0):!1}function TR(){let t=My();return t.length===0?null:Ny(t[0].name)}var is=null,Yn=null,Nr=null;function RR(t,e={}){t.length!==0&&(is&&clearTimeout(is),Yn=t,Nr=e||{},is=setTimeout(()=>{Yn&&Yn.length>0&&Wu("_autosave",Yn,Nr),is=null,Yn=null,Nr=null},5e3),is.unref?.())}function CR(){is&&(clearTimeout(is),is=null),Yn&&Yn.length>0&&(Wu("_autosave",Yn,Nr),Yn=null,Nr=null)}function AR(){Bu();let t=Mr(),e=bn.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of e){let i=Ia.join(t,r);try{let a=bn.statSync(i);new Date(a.mtime)<o&&(bn.unlinkSync(i),s++)}catch{}}return s}Ly.exports={saveSession:Wu,loadSession:Ny,listSessions:My,deleteSession:ER,getLastSession:TR,autoSave:RR,flushAutoSave:CR,clearOldSessions:AR,_getSessionsDir:Mr}});var Hy=J((oN,Wy)=>{"use strict";var Lr=require("fs"),Iy=require("path");function jy(t){let e=[];return t.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&e.push({name:s.name||"",input:s.input||{},index:o,id:s.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}e.push({name:r,input:i,index:o,id:s.id||null})}))}),e}function OR(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function Dy(t){let e=[];return t.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");e.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:s,index:o})}}),e}function qy(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function Fy(t,e){let n=[];for(let o=t.length-1;o>=0&&n.length<e;o--){let s=t[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function By(t){let e=new Map;for(let n of t){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;e.set(s,(e.get(s)||0)+1)}return e}function Uy(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],o=jy(t),s=Dy(t),r=o.length,i=OR(t),a=o.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,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let c=o.find(b=>{let L=b.input?.command||b.input?.cmd||"";return/\bsed\s+-n\b/.test(L)});if(c){let b=(c.input?.command||c.input?.cmd||"").slice(0,80);s.some(U=>U.content.includes("BLOCKED: sed -n is forbidden")||U.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${b}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${b}`))}o.find(b=>{if(b.name!=="grep"&&b.name!=="bash"&&b.name!=="ssh_exec")return!1;let L=b.input?.command||b.input?.cmd||"",U=b.input?.pattern||"",Z=`${L} ${U}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(Z)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(Z)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let d=t.some(b=>b.role==="assistant"),f=qy(t),m=Fy(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)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${b}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(b=>{let L=typeof b.content=="string"?b.content:Array.isArray(b.content)?b.content.map(U=>typeof U=="string"?U:U.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(L)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let k=By(a),$=0,O="";for(let[b,L]of k)L>$&&($=L,O=b);if($>=3){let[b]=O.split("|");e-=1,n.push(`Same tool call repeated ${$}\xD7 (tool: ${b})`)}let E=!1,T=t.findIndex(b=>b.role==="user"&&typeof b.content=="string"&&b.content.includes("[SYSTEM STOP]")&&b.content.includes('"valid":true'));T>=0&&o.filter(L=>L.index>T).length>0&&(E=!0),E&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let q=o.filter(b=>b.name==="ssh_exec");if(q.length>=8){let b=0,L=1;for(let U=1;U<q.length;U++)q[U].index<=q[U-1].index+2?L++:(b=Math.max(b,L),L=1);b=Math.max(b,L),b>=8&&(e-=.5,n.push(`SSH reconnect storm: ${b} consecutive SSH calls`))}d&&q.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let ee=new Map;for(let b of a)if(b.name==="read_file"&&b.input?.path){let L=b.input.path;ee.has(L)||ee.set(L,{count:0,ranges:[]});let U=ee.get(L);if(U.count++,b.input.line_start!=null){let Z=b.input.line_start||1,X=b.input.line_end||Z+350;U.ranges.push([Z,X])}}function te(b,L,U){for(let[Z,X]of U){let R=Math.max(b,Z),ce=Math.min(L,X);if(ce>R){let qe=ce-R,be=L-b||1;if(qe/be>=.7)return!0}}return!1}let K=0,ae="";for(let[b,L]of ee){if(L.count<3)continue;if(L.ranges.length===L.count){let X=!1,R=[];for(let[ce,qe]of L.ranges){if(R.length>0&&te(ce,qe,R)){X=!0;break}R.push([ce,qe])}if(!X)continue}if(L.count-L.ranges.length<=2&&L.ranges.length>=1){let X=!1,R=[];for(let[ce,qe]of L.ranges){if(R.length>0&&te(ce,qe,R)){X=!0;break}R.push([ce,qe])}if(!X)continue}L.count>K&&(K=L.count,ae=b)}if(K>=3){e-=1;let b=ae.split("/").slice(-2).join("/");n.push(`read_file loop: "${b}" read ${K}\xD7 (file already in context)`)}let se=0,ie="";for(let[b,L]of ee){if(L.ranges.length<4)continue;let U=[],Z=!1;for(let[X,R]of L.ranges){if(U.length>0&&te(X,R,U)){Z=!0;break}U.push([X,R])}!Z&&L.ranges.length>se&&(se=L.ranges.length,ie=b)}if(se>=4){e-=.5;let b=ie.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${b}" read in ${se} sequential sections \u2014 use grep instead`)}let Be=new Map;for(let b of a)if(b.name==="grep"&&b.input?.path&&b.input?.pattern){let L=b.input.path;Be.has(L)||Be.set(L,new Set),Be.get(L).add(b.input.pattern)}let Re=0,W="";for(let[b,L]of Be)b.split("/").pop().includes(".")&&L.size>Re&&(Re=L.size,W=b);if(Re>=3){e-=.75;let b=W.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${b}" searched ${Re}\xD7 with different patterns (file already in context)`)}{let b=new Set,L=new Set,U=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let X of o){if(X.name==="write_file"&&X.input?.path){let R=X.input.path.split("/").pop(),ce=X.input.path.includes("/tests/");U.test(R)&&!ce&&b.add(X.input.path)}if((X.name==="bash"||X.name==="ssh_exec")&&X.input?.command){let R=X.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(R)for(let ce of R){let qe=ce.split(/\s+/),be=qe[qe.length-1];for(let Le of b)(Le.endsWith(be)||be.endsWith(Le.split("/").pop()))&&L.add(Le)}}}let Z=L.size;if(Z>=1){let X=Math.min(Z*.25,.5);e-=X;let R=[...L].map(ce=>ce.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${R} \u2014 write inline logic or use tests/ instead`)}}let ne=s.filter(b=>b.content.startsWith("EXIT")).length;ne>=10?(e-=1,n.push(`Bash exit-error storm: ${ne} tool results started with EXIT (repeated failing commands)`)):ne>=5&&(e-=.5,n.push(`Repeated bash errors: ${ne} tool results with non-zero exit code`));for(let b of t){if(b.role!=="assistant")continue;let L="";if(typeof b.content=="string"?L=b.content:Array.isArray(b.content)&&(L=b.content.filter(be=>be&&(be.type==="text"||typeof be=="string")).map(be=>typeof be=="string"?be:be.text||"").join("")),L.length<=5e3)continue;let U=L.split(/(?<=\. )/).filter(be=>be.trim().length>0);if(U.length<6)continue;let Z=new Map;for(let be=0;be<=U.length-3;be++){let Le=U.slice(be,be+3).join("").trim();Le.length>30&&Z.set(Le,(Z.get(Le)||0)+1)}let X=0,R="";for(let[be,Le]of Z)Le>X&&(X=Le,R=be);if(X<3)continue;let qe=R.length*X/L.length;if(qe>=.4||X>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${X}\xD7 same paragraph, ${Math.round(qe*100)}% repeated)`);break}}{let b=new Set(["read_file","list_directory","search_files","glob","grep"]),L=t.some(Z=>Array.isArray(Z.tool_calls)?Z.tool_calls.some(X=>b.has(X.function?.name)):Array.isArray(Z.content)?Z.content.some(X=>X.type==="tool_use"&&b.has(X.name)):!1);t.some(Z=>Z.role==="assistant"&&typeof Z.content=="string"&&(Z.content.includes("## Steps")||Z.content.includes("/plan approve")))&&!L&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Ke=s.filter(b=>b.content.startsWith("BLOCKED:")&&!b.content.includes("BLOCKED: sed -n")&&!b.content.includes("SSH paused")&&!b.content.includes("SSH temporarily paused"));if(Ke.length>0){let b=Math.min(Ke.length*.5,1.5);e-=b,n.push(`${Ke.length} tool call${Ke.length===1?"":"s"} blocked (agent attempted denied actions)`)}let ct=t.filter(b=>{let L=typeof b.content=="string"?b.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(L)}).length;if(ct>0){let b=Math.min(ct*1,2);e-=b,n.push(`Super-nuclear context wipe fired ${ct}\xD7 (context collapse \u2014 task too large or read loops)`)}{let b=!1,L=!1,U=!1;for(let X of o){if(X.name!=="bash")continue;let R=(X.input?.command||X.input?.cmd||"").trim();!(/cat\s*>/.test(R)||/<</.test(R))&&/\bcat\s+\S/.test(R)&&(b=!0),/^\s*ls(\s|$)/.test(R)&&!/npm|yarn|pnpm|make|git\b/.test(R)&&(L=!0),/\bfind\s+\S/.test(R)&&!/git\b|npm\b|-exec\b/.test(R)&&(U=!0)}let Z=[b,L,U].filter(Boolean).length;if(Z>0){let X=Math.min(Z*.25,.75);e-=X;let R=[];b&&R.push("cat (use read_file)"),L&&R.push("ls (use list_directory)"),U&&R.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${R.join(", ")}`)}}{let b=o.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&(R.input.path.endsWith("requirements.txt")||R.input.path.endsWith("Pipfile")||R.input.path.endsWith("pyproject.toml"))),L=o.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&R.input.path.endsWith("package.json")),U=o.filter(R=>(R.name==="bash"||R.name==="Bash")&&R.input?.command).map(R=>R.input.command),Z=U.some(R=>/pip\s+install|python\s+-m\s+venv/.test(R)),X=U.some(R=>/npm\s+install/.test(R));b&&!Z?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):L&&!X&&o.some(ce=>(ce.name==="write_file"||ce.name==="Write")&&ce.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(ce.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let b=t.find(R=>R.role==="assistant"),L="";b&&(typeof b.content=="string"?L=b.content:Array.isArray(b.content)&&(L=b.content.filter(R=>R&&(R.type==="text"||typeof R=="string")).map(R=>typeof R=="string"?R:R.text||"").join("")));let U=L.slice(0,400),Z=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,X=U.split(`
736
- `).find(R=>{let ce=R.trim();return ce.length>0&&ce.length<=30&&/^\d/.test(ce)&&/=/.test(ce)&&!/[a-zA-Z]/.test(ce)});if(Z.test(U)||X){e-=1.5;let R=(X||U.split(`
737
- `)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${R}"`)}}if(d&&r>0){let b=t.findIndex(U=>U.role==="assistant"),L=t.findIndex(U=>!!(Array.isArray(U.tool_calls)&&U.tool_calls.length>0||Array.isArray(U.content)&&U.content.some(Z=>Z&&Z.type==="tool_use")));if(b!==-1&&L!==-1&&b<L){let U=t[b],Z="";typeof U.content=="string"?Z=U.content:Array.isArray(U.content)&&(Z=U.content.filter(ce=>ce&&(ce.type==="text"||typeof ce=="string")).map(ce=>typeof ce=="string"?ce:ce.text||"").join(""));let X=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(Z),R=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(Z);(X||R)&&(e-=1,n.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(d){let b=f;if(b.length>100){let U=(b.match(/^```/gm)||[]).length%2!==0,Z=/"\s*:\s*$/.test(b.trimEnd()),X=/[,\[{]\s*$/.test(b.trimEnd());(U||Z||X)&&(e-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let b=[];t.forEach((U,Z)=>{let X=[];Array.isArray(U.tool_calls)&&U.tool_calls.forEach(R=>{if((R.function?.name||R.name||"")==="read_file"){let qe={};try{qe=typeof R.function?.arguments=="string"?JSON.parse(R.function.arguments):R.function?.arguments||{}}catch{}(qe.path||"").endsWith(".json")&&X.push({id:R.id,path:qe.path})}}),Array.isArray(U.content)&&U.content.forEach(R=>{R&&R.type==="tool_use"&&R.name==="read_file"&&(R.input?.path||"").endsWith(".json")&&X.push({id:R.id,path:R.input.path})}),X.forEach(R=>b.push({...R,msgIdx:Z}))});let L=0;for(let U of b){let Z=null;for(let R of t){if(R.role==="tool"&&R.tool_call_id===U.id&&typeof R.content=="string"){Z=R.content;break}if(R.role==="user"&&Array.isArray(R.content)){let ce=R.content.find(qe=>qe&&qe.type==="tool_result"&&qe.tool_use_id===U.id);if(ce){Z=typeof ce.content=="string"?ce.content:"";break}}}if(!Z)continue;Z.split(`
738
- `).filter(R=>R.trim()).length<5&&/^\s*\[/.test(Z)&&!/\]\s*$/.test(Z.trimEnd())&&L++}L>=1&&(e-=.75,n.push(`Shallow JSON read: ${L} .json file${L>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let b=s.filter(L=>/argument errors?/i.test(L.content)||/missing required (argument|parameter)/i.test(L.content)||/invalid argument/i.test(L.content));b.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${b.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):b.length>=2&&(e-=.25,n.push(`Tool argument errors: ${b.length} tool calls returned argument errors`))}{let b=!1,L=0,U=0;for(let Z of a){if((Z.name==="bash"||Z.name==="Bash")&&Z.input?.command&&/git\s+commit\b/.test(Z.input.command)){b&&(U=Math.max(U,L)),b=!0,L=0;continue}b&&(Z.name==="bash"||Z.name==="Bash")&&Z.input?.command&&/git\s+(status|diff|log|show)\b/.test(Z.input.command)&&L++}U=Math.max(U,L),U>=3&&(e-=.75,n.push(`Post-commit verification waste: ${U} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Te=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",ve=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:Te,issues:n,summary:ve}}function PR(t){try{let{loadSession:e}=ja(),n=e(t);return n?Uy(n.messages||[]):null}catch{return null}}function NR(t,e=null){let{score:n,issues:o}=t,s=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(n>=8||o.length===0)return"";let a=o.map(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(n>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
735
+ `)}async function TR(t){let e=Ke.join(t,"package.json"),n="";if(await on(()=>vt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await vt.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([on(async()=>{let{stdout:i}=await Nr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Py()]);if(r&&r.length>0){console.log(`${Po.red} \u26A0 ${r.length} unresolved merge conflict(s):${Po.reset}`);for(let i of r)console.log(`${Po.red} ${i.file}${Po.reset}`);console.log(`${Po.yellow} \u2192 Resolve conflicts before starting tasks${Po.reset}`)}console.log()}Ny.exports={gatherProjectContext:ER,printContext:TR,generateFileTree:xR,_clearContextCache:()=>{Uu.clear(),Mo.clear(),Ia=null,No={result:null,expiry:0,cwd:null}}}});var Da=J((aN,jy)=>{var bn=require("fs"),ja=require("path"),{atomicWrite:RR}=vs();function Lr(){return ja.join(process.cwd(),".nex","sessions")}function Wu(){let t=Lr();bn.existsSync(t)||bn.mkdirSync(t,{recursive:!0,mode:448})}function Hu(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return ja.join(Lr(),`${e}.json`)}function Gu(t,e,n={}){Wu();let o=Hu(t),s={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return RR(o,JSON.stringify(s,null,2)),{path:o,name:t}}function Ly(t){let e=Hu(t);if(!bn.existsSync(e))return null;try{return JSON.parse(bn.readFileSync(e,"utf-8"))}catch{return null}}function Iy(){Wu();let t=Lr(),e=bn.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(bn.readFileSync(ja.join(t,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function CR(t){let e=Hu(t);return bn.existsSync(e)?(bn.unlinkSync(e),!0):!1}function AR(){let t=Iy();return t.length===0?null:Ly(t[0].name)}var is=null,Yn=null,Mr=null;function OR(t,e={}){t.length!==0&&(is&&clearTimeout(is),Yn=t,Mr=e||{},is=setTimeout(()=>{Yn&&Yn.length>0&&Gu("_autosave",Yn,Mr),is=null,Yn=null,Mr=null},5e3),is.unref?.())}function PR(){is&&(clearTimeout(is),is=null),Yn&&Yn.length>0&&(Gu("_autosave",Yn,Mr),Yn=null,Mr=null)}function NR(){Wu();let t=Lr(),e=bn.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of e){let i=ja.join(t,r);try{let a=bn.statSync(i);new Date(a.mtime)<o&&(bn.unlinkSync(i),s++)}catch{}}return s}jy.exports={saveSession:Gu,loadSession:Ly,listSessions:Iy,deleteSession:CR,getLastSession:AR,autoSave:OR,flushAutoSave:PR,clearOldSessions:NR,_getSessionsDir:Lr}});var Yy=J((lN,Gy)=>{"use strict";var Ir=require("fs"),Dy=require("path");function qy(t){let e=[];return t.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&e.push({name:s.name||"",input:s.input||{},index:o,id:s.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}e.push({name:r,input:i,index:o,id:s.id||null})}))}),e}function MR(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function Fy(t){let e=[];return t.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");e.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:s,index:o})}}),e}function By(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function Uy(t,e){let n=[];for(let o=t.length-1;o>=0&&n.length<e;o--){let s=t[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function Wy(t){let e=new Map;for(let n of t){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;e.set(s,(e.get(s)||0)+1)}return e}function Hy(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],o=qy(t),s=Fy(t),r=o.length,i=MR(t),a=o.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,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let c=o.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);s.some(U=>U.content.includes("BLOCKED: sed -n is forbidden")||U.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${b}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${b}`))}o.find(b=>{if(b.name!=="grep"&&b.name!=="bash"&&b.name!=="ssh_exec")return!1;let I=b.input?.command||b.input?.cmd||"",U=b.input?.pattern||"",Z=`${I} ${U}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(Z)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(Z)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let d=t.some(b=>b.role==="assistant"),f=By(t),m=Uy(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)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${b}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(b=>{let I=typeof b.content=="string"?b.content:Array.isArray(b.content)?b.content.map(U=>typeof U=="string"?U:U.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(I)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let k=Wy(a),$=0,O="";for(let[b,I]of k)I>$&&($=I,O=b);if($>=3){let[b]=O.split("|");e-=1,n.push(`Same tool call repeated ${$}\xD7 (tool: ${b})`)}let E=!1,T=t.findIndex(b=>b.role==="user"&&typeof b.content=="string"&&b.content.includes("[SYSTEM STOP]")&&b.content.includes('"valid":true'));T>=0&&o.filter(I=>I.index>T).length>0&&(E=!0),E&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let q=o.filter(b=>b.name==="ssh_exec");if(q.length>=8){let b=0,I=1;for(let U=1;U<q.length;U++)q[U].index<=q[U-1].index+2?I++:(b=Math.max(b,I),I=1);b=Math.max(b,I),b>=8&&(e-=.5,n.push(`SSH reconnect storm: ${b} consecutive SSH calls`))}d&&q.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let 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 U=ee.get(I);if(U.count++,b.input.line_start!=null){let Z=b.input.line_start||1,X=b.input.line_end||Z+350;U.ranges.push([Z,X])}}function te(b,I,U){for(let[Z,X]of U){let R=Math.max(b,Z),ue=Math.min(I,X);if(ue>R){let qe=ue-R,we=I-b||1;if(qe/we>=.7)return!0}}return!1}let K=0,ae="";for(let[b,I]of ee){if(I.count<3)continue;if(I.ranges.length===I.count){let X=!1,R=[];for(let[ue,qe]of I.ranges){if(R.length>0&&te(ue,qe,R)){X=!0;break}R.push([ue,qe])}if(!X)continue}if(I.count-I.ranges.length<=2&&I.ranges.length>=1){let X=!1,R=[];for(let[ue,qe]of I.ranges){if(R.length>0&&te(ue,qe,R)){X=!0;break}R.push([ue,qe])}if(!X)continue}I.count>K&&(K=I.count,ae=b)}if(K>=3){e-=1;let b=ae.split("/").slice(-2).join("/");n.push(`read_file loop: "${b}" read ${K}\xD7 (file already in context)`)}let se=0,ie="";for(let[b,I]of ee){if(I.ranges.length<4)continue;let U=[],Z=!1;for(let[X,R]of I.ranges){if(U.length>0&&te(X,R,U)){Z=!0;break}U.push([X,R])}!Z&&I.ranges.length>se&&(se=I.ranges.length,ie=b)}if(se>=4){e-=.5;let b=ie.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${b}" read in ${se} sequential sections \u2014 use grep instead`)}let Be=new Map;for(let b of a)if(b.name==="grep"&&b.input?.path&&b.input?.pattern){let I=b.input.path;Be.has(I)||Be.set(I,new Set),Be.get(I).add(b.input.pattern)}let Ce=0,H="";for(let[b,I]of Be)b.split("/").pop().includes(".")&&I.size>Ce&&(Ce=I.size,H=b);if(Ce>=3){e-=.75;let b=H.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${b}" searched ${Ce}\xD7 with different patterns (file already in context)`)}{let b=new Set,I=new Set,U=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let X of o){if(X.name==="write_file"&&X.input?.path){let R=X.input.path.split("/").pop(),ue=X.input.path.includes("/tests/");U.test(R)&&!ue&&b.add(X.input.path)}if((X.name==="bash"||X.name==="ssh_exec")&&X.input?.command){let R=X.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(R)for(let ue of R){let qe=ue.split(/\s+/),we=qe[qe.length-1];for(let Ie of b)(Ie.endsWith(we)||we.endsWith(Ie.split("/").pop()))&&I.add(Ie)}}}let Z=I.size;if(Z>=1){let X=Math.min(Z*.25,.5);e-=X;let R=[...I].map(ue=>ue.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${R} \u2014 write inline logic or use tests/ instead`)}}let ne=s.filter(b=>b.content.startsWith("EXIT")).length;ne>=10?(e-=1,n.push(`Bash exit-error storm: ${ne} tool results started with EXIT (repeated failing commands)`)):ne>=5&&(e-=.5,n.push(`Repeated bash errors: ${ne} 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(we=>we&&(we.type==="text"||typeof we=="string")).map(we=>typeof we=="string"?we:we.text||"").join("")),I.length<=5e3)continue;let U=I.split(/(?<=\. )/).filter(we=>we.trim().length>0);if(U.length<6)continue;let Z=new Map;for(let we=0;we<=U.length-3;we++){let Ie=U.slice(we,we+3).join("").trim();Ie.length>30&&Z.set(Ie,(Z.get(Ie)||0)+1)}let X=0,R="";for(let[we,Ie]of Z)Ie>X&&(X=Ie,R=we);if(X<3)continue;let qe=R.length*X/I.length;if(qe>=.4||X>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${X}\xD7 same paragraph, ${Math.round(qe*100)}% repeated)`);break}}{let b=new Set(["read_file","list_directory","search_files","glob","grep"]),I=t.some(Z=>Array.isArray(Z.tool_calls)?Z.tool_calls.some(X=>b.has(X.function?.name)):Array.isArray(Z.content)?Z.content.some(X=>X.type==="tool_use"&&b.has(X.name)):!1);t.some(Z=>Z.role==="assistant"&&typeof Z.content=="string"&&(Z.content.includes("## Steps")||Z.content.includes("/plan approve")))&&!I&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Ve=s.filter(b=>b.content.startsWith("BLOCKED:")&&!b.content.includes("BLOCKED: sed -n")&&!b.content.includes("SSH paused")&&!b.content.includes("SSH temporarily paused"));if(Ve.length>0){let b=Math.min(Ve.length*.5,1.5);e-=b,n.push(`${Ve.length} tool call${Ve.length===1?"":"s"} blocked (agent attempted denied actions)`)}let ut=t.filter(b=>{let I=typeof b.content=="string"?b.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(I)}).length;if(ut>0){let b=Math.min(ut*1,2);e-=b,n.push(`Super-nuclear context wipe fired ${ut}\xD7 (context collapse \u2014 task too large or read loops)`)}{let b=!1,I=!1,U=!1;for(let X of o){if(X.name!=="bash")continue;let R=(X.input?.command||X.input?.cmd||"").trim();!(/cat\s*>/.test(R)||/<</.test(R))&&/\bcat\s+\S/.test(R)&&(b=!0),/^\s*ls(\s|$)/.test(R)&&!/npm|yarn|pnpm|make|git\b/.test(R)&&(I=!0),/\bfind\s+\S/.test(R)&&!/git\b|npm\b|-exec\b/.test(R)&&(U=!0)}let Z=[b,I,U].filter(Boolean).length;if(Z>0){let X=Math.min(Z*.25,.75);e-=X;let R=[];b&&R.push("cat (use read_file)"),I&&R.push("ls (use list_directory)"),U&&R.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${R.join(", ")}`)}}{let b=o.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&(R.input.path.endsWith("requirements.txt")||R.input.path.endsWith("Pipfile")||R.input.path.endsWith("pyproject.toml"))),I=o.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&R.input.path.endsWith("package.json")),U=o.filter(R=>(R.name==="bash"||R.name==="Bash")&&R.input?.command).map(R=>R.input.command),Z=U.some(R=>/pip\s+install|python\s+-m\s+venv/.test(R)),X=U.some(R=>/npm\s+install/.test(R));b&&!Z?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):I&&!X&&o.some(ue=>(ue.name==="write_file"||ue.name==="Write")&&ue.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(ue.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let b=t.find(R=>R.role==="assistant"),I="";b&&(typeof b.content=="string"?I=b.content:Array.isArray(b.content)&&(I=b.content.filter(R=>R&&(R.type==="text"||typeof R=="string")).map(R=>typeof R=="string"?R:R.text||"").join("")));let U=I.slice(0,400),Z=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,X=U.split(`
736
+ `).find(R=>{let ue=R.trim();return ue.length>0&&ue.length<=30&&/^\d/.test(ue)&&/=/.test(ue)&&!/[a-zA-Z]/.test(ue)});if(Z.test(U)||X){e-=1.5;let R=(X||U.split(`
737
+ `)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${R}"`)}}if(d&&r>0){let b=t.findIndex(U=>U.role==="assistant"),I=t.findIndex(U=>!!(Array.isArray(U.tool_calls)&&U.tool_calls.length>0||Array.isArray(U.content)&&U.content.some(Z=>Z&&Z.type==="tool_use")));if(b!==-1&&I!==-1&&b<I){let U=t[b],Z="";typeof U.content=="string"?Z=U.content:Array.isArray(U.content)&&(Z=U.content.filter(ue=>ue&&(ue.type==="text"||typeof ue=="string")).map(ue=>typeof ue=="string"?ue:ue.text||"").join(""));let X=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(Z),R=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(Z);(X||R)&&(e-=1,n.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(d){let b=f;if(b.length>100){let U=(b.match(/^```/gm)||[]).length%2!==0,Z=/"\s*:\s*$/.test(b.trimEnd()),X=/[,\[{]\s*$/.test(b.trimEnd());(U||Z||X)&&(e-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let b=[];t.forEach((U,Z)=>{let X=[];Array.isArray(U.tool_calls)&&U.tool_calls.forEach(R=>{if((R.function?.name||R.name||"")==="read_file"){let qe={};try{qe=typeof R.function?.arguments=="string"?JSON.parse(R.function.arguments):R.function?.arguments||{}}catch{}(qe.path||"").endsWith(".json")&&X.push({id:R.id,path:qe.path})}}),Array.isArray(U.content)&&U.content.forEach(R=>{R&&R.type==="tool_use"&&R.name==="read_file"&&(R.input?.path||"").endsWith(".json")&&X.push({id:R.id,path:R.input.path})}),X.forEach(R=>b.push({...R,msgIdx:Z}))});let I=0;for(let U of b){let Z=null;for(let R of t){if(R.role==="tool"&&R.tool_call_id===U.id&&typeof R.content=="string"){Z=R.content;break}if(R.role==="user"&&Array.isArray(R.content)){let ue=R.content.find(qe=>qe&&qe.type==="tool_result"&&qe.tool_use_id===U.id);if(ue){Z=typeof ue.content=="string"?ue.content:"";break}}}if(!Z)continue;Z.split(`
738
+ `).filter(R=>R.trim()).length<5&&/^\s*\[/.test(Z)&&!/\]\s*$/.test(Z.trimEnd())&&I++}I>=1&&(e-=.75,n.push(`Shallow JSON read: ${I} .json file${I>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let b=s.filter(I=>/argument errors?/i.test(I.content)||/missing required (argument|parameter)/i.test(I.content)||/invalid argument/i.test(I.content));b.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${b.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):b.length>=2&&(e-=.25,n.push(`Tool argument errors: ${b.length} tool calls returned argument errors`))}{let b=!1,I=0,U=0;for(let Z of a){if((Z.name==="bash"||Z.name==="Bash")&&Z.input?.command&&/git\s+commit\b/.test(Z.input.command)){b&&(U=Math.max(U,I)),b=!0,I=0;continue}b&&(Z.name==="bash"||Z.name==="Bash")&&Z.input?.command&&/git\s+(status|diff|log|show)\b/.test(Z.input.command)&&I++}U=Math.max(U,I),U>=3&&(e-=.75,n.push(`Post-commit verification waste: ${U} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Re=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Te=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:Re,issues:n,summary:Te}}function LR(t){try{let{loadSession:e}=Da(),n=e(t);return n?Hy(n.messages||[]):null}catch{return null}}function IR(t,e=null){let{score:n,issues:o}=t,s=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(n>=8||o.length===0)return"";let a=o.map(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(n>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
739
739
  ${s}${f}${r}`}let l="";for(let u of a.slice(0,4))l+=`
740
740
  ${i}\u26A0${r} ${s}${u}${r}`;let c=a.length-4;return c>0&&(l+=`
741
- ${s}(+${c} more)${r}`),l}function MR(t,e={}){try{let n=Iy.join(process.cwd(),".nex");Lr.existsSync(n)||Lr.mkdirSync(n,{recursive:!0});let o=Iy.join(n,"benchmark-history.json"),s=[];if(Lr.existsSync(o))try{s=JSON.parse(Lr.readFileSync(o,"utf-8"))}catch{s=[]}Array.isArray(s)||(s=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};s.push(i),s.length>100&&(s=s.slice(s.length-100)),Lr.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}Wy.exports={scoreMessages:Uy,scoreSession:PR,formatScore:NR,appendScoreHistory:MR,_extractToolCalls:jy,_extractToolResults:Dy,_getLastAssistantText:qy,_getLastNAssistantTexts:Fy,_countDuplicateToolCalls:By}});var Dr=J((rN,Vy)=>{"use strict";var LR=require("os"),Hu=require("path"),as=require("fs"),Ir=Hu.join(LR.homedir(),".nex-code","model-routing.json"),Da={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}},Gy=["agentic","frontend","sysadmin","data","coding"];function IR(t){if(!t||t.length<8)return null;for(let e of Gy){let n=Da[e];if(!n.pattern||n.pattern.test(t))return n}return Da.coding}function jr(){try{if(as.existsSync(Ir))return JSON.parse(as.readFileSync(Ir,"utf-8"))}catch{}return{}}function Yy(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=Da[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:jr()[t]||null}var zy={explore:10,plan:10,implement:35,verify:8},Gu={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Ky(){let t=jr();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=$t();if(e()==="ollama")return Gu}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Gu:null}function jR(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let n=Ky();return n?.[t]?n[t]:e?Yy(e):null}function DR(t){return jr().phaseBudgets?.[t]||zy[t]||20}function qR(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:Ky()!==null}function FR(t){let e=Hu.dirname(Ir);as.existsSync(e)||as.mkdirSync(e,{recursive:!0});let n=jr(),o={...n,...t};!t.phases&&n.phases&&(o.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(o.phaseBudgets=n.phaseBudgets),as.writeFileSync(Ir,JSON.stringify(o,null,2));try{let s=Hu.join(e,".env"),r="";as.existsSync(s)&&(r=as.readFileSync(s,"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)),as.writeFileSync(s,i.filter(l=>l.trim()!=="").join(`
741
+ ${s}(+${c} more)${r}`),l}function jR(t,e={}){try{let n=Dy.join(process.cwd(),".nex");Ir.existsSync(n)||Ir.mkdirSync(n,{recursive:!0});let o=Dy.join(n,"benchmark-history.json"),s=[];if(Ir.existsSync(o))try{s=JSON.parse(Ir.readFileSync(o,"utf-8"))}catch{s=[]}Array.isArray(s)||(s=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};s.push(i),s.length>100&&(s=s.slice(s.length-100)),Ir.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}Gy.exports={scoreMessages:Hy,scoreSession:LR,formatScore:IR,appendScoreHistory:jR,_extractToolCalls:qy,_extractToolResults:Fy,_getLastAssistantText:By,_getLastNAssistantTexts:Uy,_countDuplicateToolCalls:Wy}});var qr=J((cN,Jy)=>{"use strict";var DR=require("os"),Yu=require("path"),as=require("fs"),jr=Yu.join(DR.homedir(),".nex-code","model-routing.json"),qa={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}},zy=["agentic","frontend","sysadmin","data","coding"];function qR(t){if(!t||t.length<8)return null;for(let e of zy){let n=qa[e];if(!n.pattern||n.pattern.test(t))return n}return qa.coding}function Dr(){try{if(as.existsSync(jr))return JSON.parse(as.readFileSync(jr,"utf-8"))}catch{}return{}}function Ky(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=qa[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Dr()[t]||null}var Vy={explore:10,plan:10,implement:35,verify:8},zu={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Xy(){let t=Dr();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=kt();if(e()==="ollama")return zu}catch{}return process.env.NEX_PHASE_ROUTING==="1"?zu:null}function FR(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let n=Xy();return n?.[t]?n[t]:e?Ky(e):null}function BR(t){return Dr().phaseBudgets?.[t]||Vy[t]||20}function UR(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:Xy()!==null}function WR(t){let e=Yu.dirname(jr);as.existsSync(e)||as.mkdirSync(e,{recursive:!0});let n=Dr(),o={...n,...t};!t.phases&&n.phases&&(o.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(o.phaseBudgets=n.phaseBudgets),as.writeFileSync(jr,JSON.stringify(o,null,2));try{let s=Yu.join(e,".env"),r="";as.existsSync(s)&&(r=as.readFileSync(s,"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)),as.writeFileSync(s,i.filter(l=>l.trim()!=="").join(`
742
742
  `)+`
743
- `)}catch{}}Vy.exports={CATEGORIES:Da,DETECTION_ORDER:Gy,detectCategory:IR,getModelForCategory:Yy,getModelForPhase:jR,getPhaseBudget:DR,isPhaseRoutingEnabled:qR,DEFAULT_PHASE_BUDGETS:zy,BUILTIN_PHASE_DEFAULTS:Gu,saveRoutingConfig:FR,loadRoutingConfig:jr,ROUTING_CONFIG_PATH:Ir}});var Qy=J((iN,Zy)=>{"use strict";var Us=require("fs"),qr=require("path"),BR=require("os"),{detectCategory:UR}=Dr(),Mo=qr.join(BR.homedir(),".nex-code","examples"),Yu=qr.join(__dirname,"..","examples");function Xy(t){try{let n=Us.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),o=n.match(/^user:\s*(.+)$/m);if(!o)return null;let s=o[1].trim(),r=n.indexOf(`
743
+ `)}catch{}}Jy.exports={CATEGORIES:qa,DETECTION_ORDER:zy,detectCategory:qR,getModelForCategory:Ky,getModelForPhase:FR,getPhaseBudget:BR,isPhaseRoutingEnabled:UR,DEFAULT_PHASE_BUDGETS:Vy,BUILTIN_PHASE_DEFAULTS:zu,saveRoutingConfig:WR,loadRoutingConfig:Dr,ROUTING_CONFIG_PATH:jr}});var tb=J((uN,eb)=>{"use strict";var Ws=require("fs"),Fr=require("path"),HR=require("os"),{detectCategory:GR}=qr(),Lo=Fr.join(HR.homedir(),".nex-code","examples"),Ku=Fr.join(__dirname,"..","examples");function Zy(t){try{let n=Ws.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),o=n.match(/^user:\s*(.+)$/m);if(!o)return null;let s=o[1].trim(),r=n.indexOf(`
744
744
  A: |`);if(r===-1)return null;let i=n.slice(r+5),a=[],l=0;for(let u of i.split(`
745
745
  `))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(`
746
- `).trim();return{user:s,assistant:c}}catch{return null}}function Jy(t){let e=`${t}.md`,n=qr.join(Mo,e);if(Us.existsSync(n)){let s=Xy(n);if(s)return s}let o=qr.join(Yu,e);return Us.existsSync(o)?Xy(o):null}function WR(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=UR(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:Jy(e.id)}function HR(){let t=new Set;for(let e of[Mo,Yu])try{for(let n of Us.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function GR(t,e){Us.existsSync(Mo)||Us.mkdirSync(Mo,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
746
+ `).trim();return{user:s,assistant:c}}catch{return null}}function Qy(t){let e=`${t}.md`,n=Fr.join(Lo,e);if(Ws.existsSync(n)){let s=Zy(n);if(s)return s}let o=Fr.join(Ku,e);return Ws.existsSync(o)?Zy(o):null}function YR(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=GR(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:Qy(e.id)}function zR(){let t=new Set;for(let e of[Lo,Ku])try{for(let n of Ws.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function KR(t,e){Ws.existsSync(Lo)||Ws.mkdirSync(Lo,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
747
747
 
748
748
  user: ${e.user}
749
749
 
@@ -751,14 +751,14 @@ A: |
751
751
  ${e.assistant.split(`
752
752
  `).map(o=>` ${o}`).join(`
753
753
  `)}
754
- `;Us.writeFileSync(qr.join(Mo,`${t}.md`),n,"utf-8")}Zy.exports={getFewShotForInput:WR,loadExampleForCategory:Jy,listAvailableExamples:HR,savePrivateExample:GR,PRIVATE_EXAMPLES_DIR:Mo,BUNDLED_EXAMPLES_DIR:Yu}});var rb=J((lN,ob)=>{var Yt=require("fs"),Lo=require("path"),{C:aN}=_t(),{atomicWrite:YR,withFileLockSync:zR}=Ss(),qa={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"},Io={...qa};function eb(){let t=Lo.join(process.cwd(),".nex","config.json");if(Yt.existsSync(t))try{let e=JSON.parse(Yt.readFileSync(t,"utf-8"));e.permissions&&(Io={...qa,...e.permissions})}catch{}}function KR(){let t=Lo.join(process.cwd(),".nex"),e=Lo.join(t,"config.json");Yt.existsSync(t)||Yt.mkdirSync(t,{recursive:!0}),zR(e,()=>{let n={};if(Yt.existsSync(e))try{n=JSON.parse(Yt.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=Io,YR(e,JSON.stringify(n,null,2))})}function tb(t){return Io[t]||"ask"}function VR(t,e){return["allow","ask","deny"].includes(e)?(Io[t]=e,!0):!1}function XR(t){return tb(t)}function JR(){return Object.entries(Io).map(([t,e])=>({tool:t,mode:e}))}function ZR(){Io={...qa}}var Fr={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 nb(){let t=Lo.join(process.cwd(),".nex","config.json");try{return Yt.existsSync(t)&&JSON.parse(Yt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function QR(t){let e=Lo.join(process.cwd(),".nex"),n=Lo.join(e,"config.json");Yt.existsSync(e)||Yt.mkdirSync(e,{recursive:!0});let o={};try{Yt.existsSync(n)&&(o=JSON.parse(Yt.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,Yt.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function sb(){let t=nb();if(!t)return Fr.admin;let e=t.role||"admin",n=Fr[e]||Fr.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function e1(t){let e=sb();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 t1(){return Object.entries(Fr).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}eb();ob.exports={getPermission:tb,setPermission:VR,checkPermission:XR,listPermissions:JR,loadPermissions:eb,savePermissions:KR,resetPermissions:ZR,DEFAULT_PERMISSIONS:qa,PERMISSION_PRESETS:Fr,loadPresetConfig:nb,savePresetConfig:QR,getEffectivePreset:sb,isToolAllowed:e1,listPresets:t1}});var Ua=J((uN,ub)=>{var Hs=require("fs"),Fa=require("path"),cN=require("readline"),{C:We}=_t(),Fe=null,Ku=!1,Vu=null,ib=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Ba(){return Fa.join(process.cwd(),".nex","plans")}function ab(){let t=Ba();Hs.existsSync(t)||Hs.mkdirSync(t,{recursive:!0})}function n1(t,e=[]){return Fe={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(n=>({description:n.description||n,files:n.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Fe}function s1(){return Fe}function o1(t){Ku=t}function r1(){return Ku}function i1(){return!Fe||Fe.status!=="draft"?!1:(Fe.status="approved",Fe.updatedAt=new Date().toISOString(),!0)}function a1(){return!Fe||Fe.status!=="approved"?!1:(Fe.status="executing",!0)}function zu(t,e){return!Fe||t<0||t>=Fe.steps.length?!1:(Fe.steps[t].status=e,Fe.updatedAt=new Date().toISOString(),Fe.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Fe.status="completed"),!0)}function l1(t){if(!t)return`${We.dim}No active plan${We.reset}`;let e={draft:`${We.yellow}DRAFT${We.reset}`,approved:`${We.green}APPROVED${We.reset}`,executing:`${We.blue}EXECUTING${We.reset}`,completed:`${We.green}COMPLETED${We.reset}`},n=[];n.push(`
754
+ `;Ws.writeFileSync(Fr.join(Lo,`${t}.md`),n,"utf-8")}eb.exports={getFewShotForInput:YR,loadExampleForCategory:Qy,listAvailableExamples:zR,savePrivateExample:KR,PRIVATE_EXAMPLES_DIR:Lo,BUNDLED_EXAMPLES_DIR:Ku}});var ab=J((fN,ib)=>{var Kt=require("fs"),Io=require("path"),{C:dN}=$t(),{atomicWrite:VR,withFileLockSync:XR}=vs(),Fa={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"},jo={...Fa};function nb(){let t=Io.join(process.cwd(),".nex","config.json");if(Kt.existsSync(t))try{let e=JSON.parse(Kt.readFileSync(t,"utf-8"));e.permissions&&(jo={...Fa,...e.permissions})}catch{}}function JR(){let t=Io.join(process.cwd(),".nex"),e=Io.join(t,"config.json");Kt.existsSync(t)||Kt.mkdirSync(t,{recursive:!0}),XR(e,()=>{let n={};if(Kt.existsSync(e))try{n=JSON.parse(Kt.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=jo,VR(e,JSON.stringify(n,null,2))})}function sb(t){return jo[t]||"ask"}function ZR(t,e){return["allow","ask","deny"].includes(e)?(jo[t]=e,!0):!1}function QR(t){return sb(t)}function e1(){return Object.entries(jo).map(([t,e])=>({tool:t,mode:e}))}function t1(){jo={...Fa}}var Br={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 ob(){let t=Io.join(process.cwd(),".nex","config.json");try{return Kt.existsSync(t)&&JSON.parse(Kt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function n1(t){let e=Io.join(process.cwd(),".nex"),n=Io.join(e,"config.json");Kt.existsSync(e)||Kt.mkdirSync(e,{recursive:!0});let o={};try{Kt.existsSync(n)&&(o=JSON.parse(Kt.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,Kt.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function rb(){let t=ob();if(!t)return Br.admin;let e=t.role||"admin",n=Br[e]||Br.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function s1(t){let e=rb();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 o1(){return Object.entries(Br).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}nb();ib.exports={getPermission:sb,setPermission:ZR,checkPermission:QR,listPermissions:e1,loadPermissions:nb,savePermissions:JR,resetPermissions:t1,DEFAULT_PERMISSIONS:Fa,PERMISSION_PRESETS:Br,loadPresetConfig:ob,savePresetConfig:n1,getEffectivePreset:rb,isToolAllowed:s1,listPresets:o1}});var Wa=J((hN,fb)=>{var Gs=require("fs"),Ba=require("path"),pN=require("readline"),{C:We}=$t(),Fe=null,Xu=!1,Ju=null,lb=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Ua(){return Ba.join(process.cwd(),".nex","plans")}function cb(){let t=Ua();Gs.existsSync(t)||Gs.mkdirSync(t,{recursive:!0})}function r1(t,e=[]){return Fe={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(n=>({description:n.description||n,files:n.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Fe}function i1(){return Fe}function a1(t){Xu=t}function l1(){return Xu}function c1(){return!Fe||Fe.status!=="draft"?!1:(Fe.status="approved",Fe.updatedAt=new Date().toISOString(),!0)}function u1(){return!Fe||Fe.status!=="approved"?!1:(Fe.status="executing",!0)}function Vu(t,e){return!Fe||t<0||t>=Fe.steps.length?!1:(Fe.steps[t].status=e,Fe.updatedAt=new Date().toISOString(),Fe.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Fe.status="completed"),!0)}function d1(t){if(!t)return`${We.dim}No active plan${We.reset}`;let e={draft:`${We.yellow}DRAFT${We.reset}`,approved:`${We.green}APPROVED${We.reset}`,executing:`${We.blue}EXECUTING${We.reset}`,completed:`${We.green}COMPLETED${We.reset}`},n=[];n.push(`
755
755
  ${We.bold}${We.cyan}Plan: ${t.task}${We.reset}`),n.push(`${We.dim}Status: ${e[t.status]||t.status}${We.reset}
756
756
  `);for(let o=0;o<t.steps.length;o++){let s=t.steps[o],r;switch(s.status){case"done":r=`${We.green}\u2713${We.reset}`;break;case"in_progress":r=`${We.blue}\u2192${We.reset}`;break;case"skipped":r=`${We.dim}\u25CB${We.reset}`;break;default:r=`${We.dim} ${We.reset}`}n.push(` ${r} ${We.bold}Step ${o+1}:${We.reset} ${s.description}`),s.files.length>0&&n.push(` ${We.dim}Files: ${s.files.join(", ")}${We.reset}`)}return n.push(""),n.join(`
757
- `)}function c1(t){if(t||(t=Fe),!t)return null;ab();let e=Fa.join(Ba(),`${t.name}.json`);return Hs.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function u1(t){let e=Fa.join(Ba(),`${t}.json`);if(!Hs.existsSync(e))return null;try{let n=JSON.parse(Hs.readFileSync(e,"utf-8"));return Fe=n,n}catch{return null}}function d1(){ab();let t=Ba(),e=Hs.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(Hs.readFileSync(Fa.join(t,o),"utf-8"));n.push({name:s.name,task:s.task,status:s.status,steps:s.steps?s.steps.length:0,createdAt:s.createdAt})}catch{}return n.sort((o,s)=>(s.createdAt||"").localeCompare(o.createdAt||""))}function f1(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=n?n[1]:t,s=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=s.exec(o))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let l=0;l<Math.min(e.length,a.length);l++){let c=a[l][1];e[l].files=c.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function p1(t){Vu=t}function h1(){return Vu}function m1(){Fe=null,Ku=!1,Vu=null,w1()}function g1(){return`
757
+ `)}function f1(t){if(t||(t=Fe),!t)return null;cb();let e=Ba.join(Ua(),`${t.name}.json`);return Gs.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function p1(t){let e=Ba.join(Ua(),`${t}.json`);if(!Gs.existsSync(e))return null;try{let n=JSON.parse(Gs.readFileSync(e,"utf-8"));return Fe=n,n}catch{return null}}function h1(){cb();let t=Ua(),e=Gs.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(Gs.readFileSync(Ba.join(t,o),"utf-8"));n.push({name:s.name,task:s.task,status:s.status,steps:s.steps?s.steps.length:0,createdAt:s.createdAt})}catch{}return n.sort((o,s)=>(s.createdAt||"").localeCompare(o.createdAt||""))}function m1(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=n?n[1]:t,s=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=s.exec(o))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let l=0;l<Math.min(e.length,a.length);l++){let c=a[l][1];e[l].files=c.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function g1(t){Ju=t}function y1(){return Ju}function b1(){Fe=null,Xu=!1,Ju=null,k1()}function w1(){return`
758
758
  PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
759
759
 
760
760
  # Allowed Tools (read-only)
761
- You may ONLY use these tools: ${[...ib].join(", ")}
761
+ You may ONLY use these tools: ${[...lb].join(", ")}
762
762
  Any other tool call will be blocked and returned with an error.
763
763
 
764
764
  # MANDATORY: Read Before You Plan
@@ -810,26 +810,26 @@ Bullet list of potential issues and mitigations.
810
810
  - Order steps by dependency (later steps may depend on earlier ones).
811
811
  - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
812
812
  - Do NOT make any file changes \u2014 your role is analysis and planning only.
813
- - 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 Ws=0;function y1(){!Fe||Fe.status!=="executing"||(Ws>0&&zu(Ws-1,"done"),Ws<Fe.steps.length&&(zu(Ws,"in_progress"),Ws++))}function b1(){if(!Fe||Fe.status!=="executing"||Fe.steps.length===0)return null;let t=Math.min(Ws,Fe.steps.length),e=Fe.steps.length,n=Math.max(0,t-1),o=Fe.steps[n]?.description||"";return{current:t,total:e,description:o}}function w1(){Ws=0}var lb=["interactive","semi-auto","autonomous"],cb="interactive";function _1(t){return lb.includes(t)?(cb=t,!0):!1}function $1(){return cb}ub.exports={createPlan:n1,getActivePlan:s1,setPlanMode:o1,isPlanMode:r1,approvePlan:i1,startExecution:a1,updateStep:zu,formatPlan:l1,savePlan:c1,loadPlan:u1,listPlans:d1,clearPlan:m1,getPlanModePrompt:g1,setPlanContent:p1,getPlanContent:h1,extractStepsFromText:f1,advancePlanStep:y1,getPlanStepInfo:b1,PLAN_MODE_ALLOWED_TOOLS:ib,setAutonomyLevel:_1,getAutonomyLevel:$1,AUTONOMY_LEVELS:lb}});var $b=J((dN,_b)=>{var{C:v}=_t();function db(){return Math.max(10,(process.stdout.columns||80)-2)}function k1(t){if(!t)return"";let e=t.split(`
814
- `),n=[],o=!1,s="";for(let r of e){let i=db();if(r.trim().startsWith("```")){if(o)n.push(`${v.dim}${"\u2500".repeat(40)}${v.reset}`),o=!1,s="";else{o=!0,s=r.trim().substring(3).trim();let a=s?` ${s} `:"";n.push(`${v.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${v.reset}`)}continue}if(o){n.push(` ${Ju(r,s)}`);continue}if(r.startsWith("###### ")){n.push(`${v.bold}${v.cyan} ${zt(r.substring(7))}${v.reset}`);continue}if(r.startsWith("##### ")){n.push(`${v.bold}${v.cyan} ${zt(r.substring(6))}${v.reset}`);continue}if(r.startsWith("#### ")){n.push(`${v.bold}${v.cyan} ${zt(r.substring(5))}${v.reset}`);continue}if(r.startsWith("### ")){n.push(`${v.bold}${v.cyan} ${zt(r.substring(4))}${v.reset}`);continue}if(r.startsWith("## ")){n.push(`${v.bold}${v.cyan} ${zt(r.substring(3))}${v.reset}`);continue}if(r.startsWith("# ")){n.push(`${v.bold}${v.cyan}${zt(r.substring(2))}${v.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${v.cyan}\u2022${v.reset} ${Gs(l)}`;n.push(Ys(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}${v.cyan}${c}.${v.reset} ${Gs(u)}`,f=l+" ".repeat(c.length+2);n.push(Ys(d,i,f));continue}}n.push(Ys(Gs(r),i))}return n.join(`
815
- `)}function zt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Gs(t){return t?t.replace(/`([^`]+)`/g,`${v.cyan}$1${v.reset}`).replace(/\*\*([^*]+)\*\*/g,`${v.bold}$1${v.reset}`).replace(/\*([^*]+)\*/g,`${v.dim}$1${v.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${v.cyan}$1${v.reset} ${v.dim}($2)${v.reset}`):""}function Ju(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?fb(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?pb(t):e==="json"||e==="jsonc"?hb(t):e==="python"||e==="py"?mb(t):e==="go"||e==="golang"?gb(t):e==="rust"||e==="rs"?yb(t):e==="css"||e==="scss"||e==="less"?bb(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?wb(t):t:""}function fb(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,s=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(s,`${v.yellow}$1${v.reset}`),r=r.replace(e,`${v.magenta}$1${v.reset}`),r=r.replace(n,`${v.green}$&${v.reset}`),r=r.replace(o,`${v.dim}$1${v.reset}`),r}function pb(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,r=t;return r=r.replace(n,`${v.cyan}$1${v.reset}`),r=r.replace(e,`$1${v.green}$2${v.reset}`),r=r.replace(o,`${v.yellow}$&${v.reset}`),r=r.replace(s,`${v.dim}$1${v.reset}`),r}function hb(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,o=/:\s*(\d+\.?\d*)/g,s=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${v.cyan}$1${v.reset}:`),r=r.replace(n,`: ${v.green}$1${v.reset}`),r=r.replace(o,`: ${v.yellow}$1${v.reset}`),r=r.replace(s,`: ${v.magenta}$1${v.reset}`),r}function mb(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,n=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,o=/(#.*$)/,s=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(s,`${v.yellow}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(r,`${v.cyan}$1${v.reset}`),i=i.replace(n,`${v.green}$&${v.reset}`),i=i.replace(o,`${v.dim}$1${v.reset}`),i}function gb(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,n=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${v.yellow}$1${v.reset}`),i=i.replace(n,`${v.cyan}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(o,`${v.green}$&${v.reset}`),i=i.replace(s,`${v.dim}$1${v.reset}`),i}function yb(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,n=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${v.yellow}$1${v.reset}`),a=a.replace(n,`${v.cyan}$1${v.reset}`),a=a.replace(e,`${v.magenta}$1${v.reset}`),a=a.replace(i,`${v.yellow}$1${v.reset}`),a=a.replace(o,`${v.green}$&${v.reset}`),a=a.replace(s,`${v.dim}$1${v.reset}`),a}function bb(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,s=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${v.yellow}$1${v.reset}`),a=a.replace(s,`${v.yellow}$1${v.reset}`),a=a.replace(e,`$1${v.cyan}$2${v.reset}:`),a=a.replace(o,`$1${v.magenta}$&${v.reset}`),a=a.replace(r,`${v.dim}$1${v.reset}`),a}function wb(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(s,`${v.dim}$1${v.reset}`),i=i.replace(o,`${v.green}$&${v.reset}`),i=i.replace(e,`<${v.magenta}$1${v.reset}`),i=i.replace(n,` ${v.cyan}$1${v.reset}=`),i=i.replace(r,`${v.yellow}$1${v.reset}`),i}function Ys(t,e,n=""){if(!e||e<10)return t;let o="",s=0,r=-1,i=0,a=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let 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),s++,s>e&&r!==-1){o+=t.slice(a,r)+`
813
+ - 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 Hs=0;function _1(){!Fe||Fe.status!=="executing"||(Hs>0&&Vu(Hs-1,"done"),Hs<Fe.steps.length&&(Vu(Hs,"in_progress"),Hs++))}function $1(){if(!Fe||Fe.status!=="executing"||Fe.steps.length===0)return null;let t=Math.min(Hs,Fe.steps.length),e=Fe.steps.length,n=Math.max(0,t-1),o=Fe.steps[n]?.description||"";return{current:t,total:e,description:o}}function k1(){Hs=0}var ub=["interactive","semi-auto","autonomous"],db="interactive";function x1(t){return ub.includes(t)?(db=t,!0):!1}function S1(){return db}fb.exports={createPlan:r1,getActivePlan:i1,setPlanMode:a1,isPlanMode:l1,approvePlan:c1,startExecution:u1,updateStep:Vu,formatPlan:d1,savePlan:f1,loadPlan:p1,listPlans:h1,clearPlan:b1,getPlanModePrompt:w1,setPlanContent:g1,getPlanContent:y1,extractStepsFromText:m1,advancePlanStep:_1,getPlanStepInfo:$1,PLAN_MODE_ALLOWED_TOOLS:lb,setAutonomyLevel:x1,getAutonomyLevel:S1,AUTONOMY_LEVELS:ub}});var xb=J((mN,kb)=>{var{C:v}=$t();function pb(){return Math.max(10,(process.stdout.columns||80)-2)}function v1(t){if(!t)return"";let e=t.split(`
814
+ `),n=[],o=!1,s="";for(let r of e){let i=pb();if(r.trim().startsWith("```")){if(o)n.push(`${v.dim}${"\u2500".repeat(40)}${v.reset}`),o=!1,s="";else{o=!0,s=r.trim().substring(3).trim();let a=s?` ${s} `:"";n.push(`${v.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${v.reset}`)}continue}if(o){n.push(` ${Qu(r,s)}`);continue}if(r.startsWith("###### ")){n.push(`${v.bold}${v.cyan} ${Vt(r.substring(7))}${v.reset}`);continue}if(r.startsWith("##### ")){n.push(`${v.bold}${v.cyan} ${Vt(r.substring(6))}${v.reset}`);continue}if(r.startsWith("#### ")){n.push(`${v.bold}${v.cyan} ${Vt(r.substring(5))}${v.reset}`);continue}if(r.startsWith("### ")){n.push(`${v.bold}${v.cyan} ${Vt(r.substring(4))}${v.reset}`);continue}if(r.startsWith("## ")){n.push(`${v.bold}${v.cyan} ${Vt(r.substring(3))}${v.reset}`);continue}if(r.startsWith("# ")){n.push(`${v.bold}${v.cyan}${Vt(r.substring(2))}${v.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${v.cyan}\u2022${v.reset} ${Ys(l)}`;n.push(zs(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}${v.cyan}${c}.${v.reset} ${Ys(u)}`,f=l+" ".repeat(c.length+2);n.push(zs(d,i,f));continue}}n.push(zs(Ys(r),i))}return n.join(`
815
+ `)}function Vt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Ys(t){return t?t.replace(/`([^`]+)`/g,`${v.cyan}$1${v.reset}`).replace(/\*\*([^*]+)\*\*/g,`${v.bold}$1${v.reset}`).replace(/\*([^*]+)\*/g,`${v.dim}$1${v.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${v.cyan}$1${v.reset} ${v.dim}($2)${v.reset}`):""}function Qu(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?hb(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?mb(t):e==="json"||e==="jsonc"?gb(t):e==="python"||e==="py"?yb(t):e==="go"||e==="golang"?bb(t):e==="rust"||e==="rs"?wb(t):e==="css"||e==="scss"||e==="less"?_b(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?$b(t):t:""}function hb(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,s=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(s,`${v.yellow}$1${v.reset}`),r=r.replace(e,`${v.magenta}$1${v.reset}`),r=r.replace(n,`${v.green}$&${v.reset}`),r=r.replace(o,`${v.dim}$1${v.reset}`),r}function mb(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,r=t;return r=r.replace(n,`${v.cyan}$1${v.reset}`),r=r.replace(e,`$1${v.green}$2${v.reset}`),r=r.replace(o,`${v.yellow}$&${v.reset}`),r=r.replace(s,`${v.dim}$1${v.reset}`),r}function gb(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,o=/:\s*(\d+\.?\d*)/g,s=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${v.cyan}$1${v.reset}:`),r=r.replace(n,`: ${v.green}$1${v.reset}`),r=r.replace(o,`: ${v.yellow}$1${v.reset}`),r=r.replace(s,`: ${v.magenta}$1${v.reset}`),r}function yb(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,n=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,o=/(#.*$)/,s=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(s,`${v.yellow}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(r,`${v.cyan}$1${v.reset}`),i=i.replace(n,`${v.green}$&${v.reset}`),i=i.replace(o,`${v.dim}$1${v.reset}`),i}function bb(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,n=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${v.yellow}$1${v.reset}`),i=i.replace(n,`${v.cyan}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(o,`${v.green}$&${v.reset}`),i=i.replace(s,`${v.dim}$1${v.reset}`),i}function wb(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,n=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${v.yellow}$1${v.reset}`),a=a.replace(n,`${v.cyan}$1${v.reset}`),a=a.replace(e,`${v.magenta}$1${v.reset}`),a=a.replace(i,`${v.yellow}$1${v.reset}`),a=a.replace(o,`${v.green}$&${v.reset}`),a=a.replace(s,`${v.dim}$1${v.reset}`),a}function _b(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,s=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${v.yellow}$1${v.reset}`),a=a.replace(s,`${v.yellow}$1${v.reset}`),a=a.replace(e,`$1${v.cyan}$2${v.reset}:`),a=a.replace(o,`$1${v.magenta}$&${v.reset}`),a=a.replace(r,`${v.dim}$1${v.reset}`),a}function $b(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(s,`${v.dim}$1${v.reset}`),i=i.replace(o,`${v.green}$&${v.reset}`),i=i.replace(e,`<${v.magenta}$1${v.reset}`),i=i.replace(n,` ${v.cyan}$1${v.reset}=`),i=i.replace(r,`${v.yellow}$1${v.reset}`),i}function zs(t,e,n=""){if(!e||e<10)return t;let o="",s=0,r=-1,i=0,a=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let 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),s++,s>e&&r!==-1){o+=t.slice(a,r)+`
816
816
  `+n,a=r+1,i=a,s=n.length,r=-1;continue}s>e&&r===-1&&(o+=t.slice(a,i)+`
817
- `+n,a=i,s=n.length+1),i++}return o+=t.slice(a),o}function x1(t,e){if(!t||t.length===0)return"";let n=t.map((i,a)=>{let l=e.reduce((c,u)=>Math.max(c,(u[a]||"").length),0);return Math.max(i.length,l)}),o=n.map(i=>"\u2500".repeat(i+2)).join("\u253C"),s=t.map((i,a)=>` ${v.bold}${i.padEnd(n[a])}${v.reset} `).join("\u2502"),r=[];r.push(`${v.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${v.reset}`),r.push(`${v.dim}\u2502${v.reset}${s}${v.dim}\u2502${v.reset}`),r.push(`${v.dim}\u251C${o}\u2524${v.reset}`);for(let i of e){let a=t.map((l,c)=>` ${(i[c]||"").padEnd(n[c])} `).join(`${v.dim}\u2502${v.reset}`);r.push(`${v.dim}\u2502${v.reset}${a}${v.dim}\u2502${v.reset}`)}return r.push(`${v.dim}\u2514${o.replace(/┼/g,"\u2534")}\u2518${v.reset}`),r.join(`
818
- `)}function S1(t,e,n,o=30){let s=n>0?Math.round(e/n*100):0,r=Math.round(s/100*o),i=o-r,a=s>=100?v.green:s>50?v.yellow:v.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${v.dim}${"\u2591".repeat(i)}${v.reset} ${s}% (${e}/${n})`}var Xu=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}_cursorWrite(e){try{process.stderr.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let n=[0,1,2,3,4,3,2,1],o=n[this._cursorFrame%n.length],s="";for(let r=0;r<5;r++)s+=r===o?`${pn().T.cyan}\u25CF${pn().T.reset}`:" ";this._cursorWrite(`\x1B[2K\r${s}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let n;for(;(n=this.buffer.indexOf(`
817
+ `+n,a=i,s=n.length+1),i++}return o+=t.slice(a),o}function E1(t,e){if(!t||t.length===0)return"";let n=t.map((i,a)=>{let l=e.reduce((c,u)=>Math.max(c,(u[a]||"").length),0);return Math.max(i.length,l)}),o=n.map(i=>"\u2500".repeat(i+2)).join("\u253C"),s=t.map((i,a)=>` ${v.bold}${i.padEnd(n[a])}${v.reset} `).join("\u2502"),r=[];r.push(`${v.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${v.reset}`),r.push(`${v.dim}\u2502${v.reset}${s}${v.dim}\u2502${v.reset}`),r.push(`${v.dim}\u251C${o}\u2524${v.reset}`);for(let i of e){let a=t.map((l,c)=>` ${(i[c]||"").padEnd(n[c])} `).join(`${v.dim}\u2502${v.reset}`);r.push(`${v.dim}\u2502${v.reset}${a}${v.dim}\u2502${v.reset}`)}return r.push(`${v.dim}\u2514${o.replace(/┼/g,"\u2534")}\u2518${v.reset}`),r.join(`
818
+ `)}function T1(t,e,n,o=30){let s=n>0?Math.round(e/n*100):0,r=Math.round(s/100*o),i=o-r,a=s>=100?v.green:s>50?v.yellow:v.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${v.dim}${"\u2591".repeat(i)}${v.reset} ${s}% (${e}/${n})`}var Zu=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}_cursorWrite(e){try{process.stderr.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let n=[0,1,2,3,4,3,2,1],o=n[this._cursorFrame%n.length],s="";for(let r=0;r<5;r++)s+=r===o?`${pn().T.cyan}\u25CF${pn().T.reset}`:" ";this._cursorWrite(`\x1B[2K\r${s}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let n;for(;(n=this.buffer.indexOf(`
819
819
  `))!==-1;){let o=this.buffer.substring(0,n);this.buffer=this.buffer.substring(n+1),this._renderLine(o)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${v.dim}${"\u2500".repeat(40)}${v.reset}
820
- `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=db();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${v.dim}${"\u2500".repeat(40)}${v.reset}
820
+ `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=pb();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${v.dim}${"\u2500".repeat(40)}${v.reset}
821
821
  `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${v.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${v.reset}
822
- `)}return}if(this.inCodeBlock){this._safeWrite(` ${Ju(e,this.codeBlockLang)}
823
- `);return}if(e.startsWith("###### ")){this._safeWrite(`${v.bold}${v.cyan} ${zt(e.substring(7))}${v.reset}
824
- `);return}if(e.startsWith("##### ")){this._safeWrite(`${v.bold}${v.cyan} ${zt(e.substring(6))}${v.reset}
825
- `);return}if(e.startsWith("#### ")){this._safeWrite(`${v.bold}${v.cyan} ${zt(e.substring(5))}${v.reset}
826
- `);return}if(e.startsWith("### ")){this._safeWrite(`${v.bold}${v.cyan} ${zt(e.substring(4))}${v.reset}
827
- `);return}if(e.startsWith("## ")){this._safeWrite(`${v.bold}${v.cyan} ${zt(e.substring(3))}${v.reset}
828
- `);return}if(e.startsWith("# ")){this._safeWrite(`${v.bold}${v.cyan}${zt(e.substring(2))}${v.reset}
829
- `);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${v.cyan}\u2022${v.reset} ${Gs(r)}`,a=Ys(i,n,s+" ");this._safeWrite(`${a}
830
- `);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){let r=s[1],i=s[2],a=s[3],l=`${r}${v.cyan}${i}.${v.reset} ${Gs(a)}`,c=r+" ".repeat(i.length+2),u=Ys(l,n,c);this._safeWrite(`${u}
831
- `);return}}let o=Ys(Gs(e),n);this._safeWrite(`${o}
832
- `)}};_b.exports={renderMarkdown:k1,renderInline:Gs,stripHeadingMarkers:zt,highlightCode:Ju,highlightJS:fb,highlightBash:pb,highlightJSON:hb,highlightPython:mb,highlightGo:gb,highlightRust:yb,highlightCSS:bb,highlightHTML:wb,renderTable:x1,renderProgress:S1,wrapAnsi:Ys,StreamRenderer:Xu}});var Eb=J((fN,vb)=>{var{execSync:v1}=require("child_process"),Zu=require("path"),Br=require("fs"),Qu=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function kb(){return Zu.join(process.cwd(),".nex","hooks")}function E1(){return Zu.join(process.cwd(),".nex","config.json")}function xb(){let t=E1();if(!Br.existsSync(t))return{};try{return JSON.parse(Br.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Wa(t){if(!Qu.includes(t))return[];let e=[],n=kb(),o=Zu.join(n,t);Br.existsSync(o)&&e.push(o);let s=xb();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function Sb(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:v1(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(o){let s=typeof o.status=="number"?o.status:1;return{success:!1,exitCode:s,blocked:s===2,output:o.stdout?o.stdout.trim():"",error:o.stderr?o.stderr.trim():o.message}}}function T1(t,e={}){let n=Wa(t);if(n.length===0)return{results:[],blocked:!1};let o={};for(let[r,i]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(i);let s=[];for(let r of n){let i=Sb(r,o);if(s.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:s,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:s,blocked:!1}}function R1(t){return Wa(t).length>0}function C1(){let t=[];for(let e of Qu){let n=Wa(e);n.length>0&&t.push({event:e,commands:n})}return t}function A1(){let t=kb();return Br.existsSync(t)||Br.mkdirSync(t,{recursive:!0}),t}vb.exports={HOOK_EVENTS:Qu,loadHookConfig:xb,getHooksForEvent:Wa,executeHook:Sb,runHooks:T1,hasHooks:R1,listHooks:C1,initHooksDir:A1}});var Ha=J((pN,Rb)=>{var Ur={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
822
+ `)}return}if(this.inCodeBlock){this._safeWrite(` ${Qu(e,this.codeBlockLang)}
823
+ `);return}if(e.startsWith("###### ")){this._safeWrite(`${v.bold}${v.cyan} ${Vt(e.substring(7))}${v.reset}
824
+ `);return}if(e.startsWith("##### ")){this._safeWrite(`${v.bold}${v.cyan} ${Vt(e.substring(6))}${v.reset}
825
+ `);return}if(e.startsWith("#### ")){this._safeWrite(`${v.bold}${v.cyan} ${Vt(e.substring(5))}${v.reset}
826
+ `);return}if(e.startsWith("### ")){this._safeWrite(`${v.bold}${v.cyan} ${Vt(e.substring(4))}${v.reset}
827
+ `);return}if(e.startsWith("## ")){this._safeWrite(`${v.bold}${v.cyan} ${Vt(e.substring(3))}${v.reset}
828
+ `);return}if(e.startsWith("# ")){this._safeWrite(`${v.bold}${v.cyan}${Vt(e.substring(2))}${v.reset}
829
+ `);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${v.cyan}\u2022${v.reset} ${Ys(r)}`,a=zs(i,n,s+" ");this._safeWrite(`${a}
830
+ `);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){let r=s[1],i=s[2],a=s[3],l=`${r}${v.cyan}${i}.${v.reset} ${Ys(a)}`,c=r+" ".repeat(i.length+2),u=zs(l,n,c);this._safeWrite(`${u}
831
+ `);return}}let o=zs(Ys(e),n);this._safeWrite(`${o}
832
+ `)}};kb.exports={renderMarkdown:v1,renderInline:Ys,stripHeadingMarkers:Vt,highlightCode:Qu,highlightJS:hb,highlightBash:mb,highlightJSON:gb,highlightPython:yb,highlightGo:bb,highlightRust:wb,highlightCSS:_b,highlightHTML:$b,renderTable:E1,renderProgress:T1,wrapAnsi:zs,StreamRenderer:Zu}});var Rb=J((gN,Tb)=>{var{execSync:R1}=require("child_process"),ed=require("path"),Ur=require("fs"),td=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Sb(){return ed.join(process.cwd(),".nex","hooks")}function C1(){return ed.join(process.cwd(),".nex","config.json")}function vb(){let t=C1();if(!Ur.existsSync(t))return{};try{return JSON.parse(Ur.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Ha(t){if(!td.includes(t))return[];let e=[],n=Sb(),o=ed.join(n,t);Ur.existsSync(o)&&e.push(o);let s=vb();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function Eb(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:R1(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(o){let s=typeof o.status=="number"?o.status:1;return{success:!1,exitCode:s,blocked:s===2,output:o.stdout?o.stdout.trim():"",error:o.stderr?o.stderr.trim():o.message}}}function A1(t,e={}){let n=Ha(t);if(n.length===0)return{results:[],blocked:!1};let o={};for(let[r,i]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(i);let s=[];for(let r of n){let i=Eb(r,o);if(s.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:s,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:s,blocked:!1}}function O1(t){return Ha(t).length>0}function P1(){let t=[];for(let e of td){let n=Ha(e);n.length>0&&t.push({event:e,commands:n})}return t}function N1(){let t=Sb();return Ur.existsSync(t)||Ur.mkdirSync(t,{recursive:!0}),t}Tb.exports={HOOK_EVENTS:td,loadHookConfig:vb,getHooksForEvent:Ha,executeHook:Eb,runHooks:A1,hasHooks:O1,listHooks:P1,initHooksDir:N1}});var Ga=J((yN,Ab)=>{var Wr={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
833
833
  Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
834
834
  You excel at sysadmin, frontend, and multi-step coding tasks.
835
835
  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.
@@ -842,7 +842,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
842
842
  Prioritize decisive, targeted edits. Read only what you need, then fix.
843
843
  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.
844
844
  Trust your reasoning. Use tools thoroughly when the task demands it.
845
- You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Tb={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function O1(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let r of Object.keys(Ur))e.startsWith(r)&&r.length>o&&(n=r,o=r.length);let s=n?{...Ur[n]}:{...Tb};for(let[r,i]of[["NEX_STALE_WARN_MS","staleWarn"],["NEX_STALE_ABORT_MS","staleAbort"]])if(process.env[r]){let a=parseInt(process.env[r],10);Number.isInteger(a)&&a>=1e3&&a<=3e5&&(s[i]=a)}return s}function P1(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let s of Object.keys(Ur))e.startsWith(s)&&s.length>o&&(n=s,o=s.length);return n&&Ur[n].briefing||""}Rb.exports={getModelProfile:O1,getModelBriefing:P1,PROFILES:Ur,DEFAULTS:Tb}});var Do=J((hN,Cb)=>{var{fork:N1}=require("child_process"),M1=require("path"),L1=M1.join(__dirname,"background-worker.js"),zs=new Map,jo=new Map;function I1(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function j1(t){let e=I1(),n=N1(L1,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:e,agentDef:t}),n.on("message",o=>{o.type==="result"?ed(e,t,o.payload):o.type==="error"&&ed(e,t,{task:t.task,status:"failed",result:`Background agent error: ${o.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),n.on("exit",(o,s)=>{if(zs.has(e)){let r=s?`killed (${s})`:`exit code ${o}`;ed(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),zs.set(e,{process:n,agentDef:t,startedAt:Date.now()}),e}function ed(t,e,n){zs.delete(t),jo.set(t,{jobId:t,agentDef:e,result:n,finishedAt:Date.now()})}function D1(){if(jo.size===0)return[];let t=[...jo.values()];return jo.clear(),t}function q1(){return zs.size>0||jo.size>0}function F1(){let t=zs.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function B1(){for(let[t,e]of zs){try{e.process.kill("SIGTERM")}catch{}zs.delete(t)}jo.clear()}Cb.exports={createJob:j1,getCompletedJobs:D1,getPendingJobSummary:F1,hasPendingOrCompletedJobs:q1,cancelAllJobs:B1}});var Jb=J((bN,Xb)=>{"use strict";var{callWithRetry:Pb,runSubAgent:Ab,clearAllLocks:U1}=Na(),{parseModelSpec:Nb,getActiveProviderName:mN,getActiveModelId:gN}=$t(),{detectCategory:W1,getModelForCategory:Ob}=Dr(),{MultiProgress:H1,C:_e}=_t(),{getModelBriefing:yN}=Ha(),Mb=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Ga=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Lb="devstral-2:123b",Ib="kimi-k2.5",jb=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
845
+ You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Cb={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function M1(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let r of Object.keys(Wr))e.startsWith(r)&&r.length>o&&(n=r,o=r.length);let s=n?{...Wr[n]}:{...Cb};for(let[r,i]of[["NEX_STALE_WARN_MS","staleWarn"],["NEX_STALE_ABORT_MS","staleAbort"]])if(process.env[r]){let a=parseInt(process.env[r],10);Number.isInteger(a)&&a>=1e3&&a<=3e5&&(s[i]=a)}return s}function L1(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let s of Object.keys(Wr))e.startsWith(s)&&s.length>o&&(n=s,o=s.length);return n&&Wr[n].briefing||""}Ab.exports={getModelProfile:M1,getModelBriefing:L1,PROFILES:Wr,DEFAULTS:Cb}});var qo=J((bN,Ob)=>{var{fork:I1}=require("child_process"),j1=require("path"),D1=j1.join(__dirname,"background-worker.js"),Ks=new Map,Do=new Map;function q1(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function F1(t){let e=q1(),n=I1(D1,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:e,agentDef:t}),n.on("message",o=>{o.type==="result"?nd(e,t,o.payload):o.type==="error"&&nd(e,t,{task:t.task,status:"failed",result:`Background agent error: ${o.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),n.on("exit",(o,s)=>{if(Ks.has(e)){let r=s?`killed (${s})`:`exit code ${o}`;nd(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),Ks.set(e,{process:n,agentDef:t,startedAt:Date.now()}),e}function nd(t,e,n){Ks.delete(t),Do.set(t,{jobId:t,agentDef:e,result:n,finishedAt:Date.now()})}function B1(){if(Do.size===0)return[];let t=[...Do.values()];return Do.clear(),t}function U1(){return Ks.size>0||Do.size>0}function W1(){let t=Ks.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function H1(){for(let[t,e]of Ks){try{e.process.kill("SIGTERM")}catch{}Ks.delete(t)}Do.clear()}Ob.exports={createJob:F1,getCompletedJobs:B1,getPendingJobSummary:W1,hasPendingOrCompletedJobs:U1,cancelAllJobs:H1}});var Qb=J((kN,Zb)=>{"use strict";var{callWithRetry:Mb,runSubAgent:Pb,clearAllLocks:G1}=Ma(),{parseModelSpec:Lb,getActiveProviderName:wN,getActiveModelId:_N}=kt(),{detectCategory:Y1,getModelForCategory:Nb}=qr(),{MultiProgress:z1,C:$e}=$t(),{getModelBriefing:$N}=Ga(),Ib=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Ya=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),jb="devstral-2:123b",Db="kimi-k2.5",qb=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
846
846
 
847
847
  RULES:
848
848
  - Output ONLY a JSON array, no markdown fences, no explanation.
@@ -857,7 +857,7 @@ RULES:
857
857
  - If the request is simple (single goal), return an array with exactly 1 item.
858
858
 
859
859
  USER REQUEST:
860
- {prompt}`,Db=`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.
860
+ {prompt}`,Fb=`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.
861
861
 
862
862
  RULES:
863
863
  - Output ONLY a JSON object with these fields:
@@ -873,16 +873,16 @@ ORIGINAL REQUEST:
873
873
  {prompt}
874
874
 
875
875
  SUB-AGENT RESULTS:
876
- {results}`;async function qb(t,e=1,n=2e3){for(let o=0;o<=e;o++)try{return await t()}catch(s){if(o===e)throw s;await new Promise(r=>setTimeout(r,n))}}function Fb(t){let e=0,n=[];return function(){return new Promise(s=>{let r=()=>{e<t?(e++,s(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function G1(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],o=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);o&&o.length>=2&&(e=Math.max(e,o.length),n.push(`${o.length} numbered items`));let s=t.match(/(?:^|\n)\s*[-*]\s+\S/g);s&&s.length>=3&&(e=Math.max(e,s.length),n.push(`${s.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),n.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),n.push(`${i.length} transition keywords`));let a=Bb(t);if(a.isCriticalPath)return{isComplex:!1,estimatedGoals:e,reason:`critical path workflow: ${a.reason}`};let l=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=l,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function Bb(t){if(!t||typeof t!="string")return{isCriticalPath:!1,reason:""};let e=t.toLowerCase(),n=/\b(at the start|before|after|in order|mandatory|must|only when|do not proceed|don't proceed|then)\b/i.test(e),o=/\b(if|when)\b[\s\S]{0,100}\b(stop|abort|do not|don't|without editing|without committing|without pushing)\b/i.test(e),s=[/\bgit status\b/i,/\bcurrent branch\b/i,/\bworktree\b/i,/\bdirty\b/i,/\bunrelated changes?\b/i,/\bclean working tree\b/i,/\bpull\/rebase\b/i,/\brebase\b/i,/\bcommit\b/i,/\bpush\b/i,/\bmerge-to-main\b/i].filter(i=>i.test(e)).length,r=/\b(verification passes|tests? pass|build passes|stage only|never stage|never push|do not commit|do not push)\b/i.test(e);return(n||o)&&s>=2?{isCriticalPath:!0,reason:"ordered git safety gates"}:o&&r?{isCriticalPath:!0,reason:"explicit stop condition"}:{isCriticalPath:!1,reason:""}}function td(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(n)try{return JSON.parse(n[1].trim())}catch{}let o=e.search(/[[\{]/);if(o>=0){let s=e.slice(o);try{return JSON.parse(s)}catch{}}throw new Error(`Could not extract valid JSON from response:
877
- ${e.slice(0,200)}`)}async function Ub(t,e,n={}){let o=n.maxSubTasks||Ga,r=[{role:"system",content:jb.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Nb(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await Pb(r,[],i)).content||"",c=td(l);if(!Array.isArray(c))throw new Error(`Decompose returned non-array: ${typeof c}`);let u=10,f=c.slice(0,o).map((g,_)=>({id:g.id||`t${_+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,u):8,priority:typeof g.priority=="number"?g.priority:_+1})).filter(g=>g.task.length>0),h=f.reduce((g,_)=>g+_.estimatedCalls,0),m=Ga*u;if(h>m){let{debugLog:g}=cc();g(`${pn().T.yellow} \u26A0 Orchestrator: total estimated calls ${h} > ${m} \u2014 consider raising maxSubTasks${pn().T.reset}`)}return f}async function Wb(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((f,h)=>{let m=f.status==="done"?"SUCCESS":f.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${h+1} [${m}] ---
876
+ {results}`;async function Bb(t,e=1,n=2e3){for(let o=0;o<=e;o++)try{return await t()}catch(s){if(o===e)throw s;await new Promise(r=>setTimeout(r,n))}}function Ub(t){let e=0,n=[];return function(){return new Promise(s=>{let r=()=>{e<t?(e++,s(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function K1(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],o=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);o&&o.length>=2&&(e=Math.max(e,o.length),n.push(`${o.length} numbered items`));let s=t.match(/(?:^|\n)\s*[-*]\s+\S/g);s&&s.length>=3&&(e=Math.max(e,s.length),n.push(`${s.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),n.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),n.push(`${i.length} transition keywords`));let a=Wb(t);if(a.isCriticalPath)return{isComplex:!1,estimatedGoals:e,reason:`critical path workflow: ${a.reason}`};let l=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=l,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function Wb(t){if(!t||typeof t!="string")return{isCriticalPath:!1,reason:""};let e=t.toLowerCase(),n=/\b(at the start|before|after|in order|mandatory|must|only when|do not proceed|don't proceed|then)\b/i.test(e),o=/\b(if|when)\b[\s\S]{0,100}\b(stop|abort|do not|don't|without editing|without committing|without pushing)\b/i.test(e),s=[/\bgit status\b/i,/\bcurrent branch\b/i,/\bworktree\b/i,/\bdirty\b/i,/\bunrelated changes?\b/i,/\bclean working tree\b/i,/\bpull\/rebase\b/i,/\brebase\b/i,/\bcommit\b/i,/\bpush\b/i,/\bmerge-to-main\b/i].filter(i=>i.test(e)).length,r=/\b(verification passes|tests? pass|build passes|stage only|never stage|never push|do not commit|do not push)\b/i.test(e);return(n||o)&&s>=2?{isCriticalPath:!0,reason:"ordered git safety gates"}:o&&r?{isCriticalPath:!0,reason:"explicit stop condition"}:{isCriticalPath:!1,reason:""}}function sd(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(n)try{return JSON.parse(n[1].trim())}catch{}let o=e.search(/[[\{]/);if(o>=0){let s=e.slice(o);try{return JSON.parse(s)}catch{}}throw new Error(`Could not extract valid JSON from response:
877
+ ${e.slice(0,200)}`)}async function Hb(t,e,n={}){let o=n.maxSubTasks||Ya,r=[{role:"system",content:qb.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Lb(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await Mb(r,[],i)).content||"",c=sd(l);if(!Array.isArray(c))throw new Error(`Decompose returned non-array: ${typeof c}`);let u=10,f=c.slice(0,o).map((g,_)=>({id:g.id||`t${_+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,u):8,priority:typeof g.priority=="number"?g.priority:_+1})).filter(g=>g.task.length>0),h=f.reduce((g,_)=>g+_.estimatedCalls,0),m=Ya*u;if(h>m){let{debugLog:g}=dc();g(`${pn().T.yellow} \u26A0 Orchestrator: total estimated calls ${h} > ${m} \u2014 consider raising maxSubTasks${pn().T.reset}`)}return f}async function Gb(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((f,h)=>{let m=f.status==="done"?"SUCCESS":f.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${h+1} [${m}] ---
878
878
  Task: ${f.task}
879
879
  Result: ${f.result}
880
880
  Tools: ${(f.toolsUsed||[]).join(", ")||"none"}`}).join(`
881
881
 
882
- `),r=[{role:"system",content:Db.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let f=Nb(n);f.provider&&(i.provider=f.provider),f.model&&(i.model=f.model)}let l=(await Pb(r,[],i)).content||"",c=td(l),u={summary:String(c.summary||""),conflicts:Array.isArray(c.conflicts)?c.conflicts:[],commitMessage:String(c.commitMessage||""),filesChanged:Array.isArray(c.filesChanged)?c.filesChanged:[]},d=Hb(u,t);return d&&(u.commitMessage="",u.commitSuppressedReason=d),u}function Hb(t,e){let n=/\b(fail(?:ed|ure|s)?|did not pass|tests? (?:are )?failing|red|broken)\b/i,o=/\b(reported|claimed|said)\b.*\b(pass|fail)/i;for(let s of t.conflicts)if(typeof s=="string"){if(n.test(s))return"conflict mentions failure";if(o.test(s)&&/pass/i.test(s)&&/fail/i.test(s))return"agents disagree on pass/fail"}for(let s of e){if(s.status==="error"||s.status==="failed"||s.status==="skipped")return`agent reported ${s.status}`;let r=String(s.result||"");if(/\b(test(?:s)? fail|verification fail|build (?:error|fail))/i.test(r))return"agent result describes test/build failure"}return null}async function Y1(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Ib,o=e.workerModel||Lb,s=e.maxParallel||Mb,r=e.maxSubTasks||Ga,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
883
- ${_e.bold}Orchestrator${_e.reset} ${_e.dim}model: ${n} | workers: ${o} | max parallel: ${s}${_e.reset}
884
- `),i("decomposing"),console.log(`${_e.dim}Phase 1: Decomposing prompt into sub-tasks...${_e.reset}`);let l;try{l=await Ub(t,n,{maxSubTasks:r})}catch(W){return console.log(`${_e.red}Decompose failed: ${W.message}${_e.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${W.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${_e.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${_e.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${_e.green}Decomposed into ${l.length} sub-tasks:${_e.reset}`);for(let W of l){console.log(` ${_e.dim}${W.id}:${_e.reset} ${W.task}`);let ne=W.scope.filter(Boolean);ne.length>0&&console.log(` ${_e.dim}scope: ${ne.join(", ")}${_e.reset}`)}console.log("");let c=new Map;for(let W=0;W<l.length;W++)for(let ne of l[W].scope)ne&&!c.has(ne)&&c.set(ne,W);i("executing"),console.log(`${_e.dim}Phase 2: Running ${l.length} sub-agents (max ${s} parallel)...${_e.reset}
885
- `);let u=Date.now(),d=Fb(s),f={findings:[],_lock:!1},h=l.map(W=>{let ne=W1(W.task);return(ne?Ob(ne.id):null)||o}),m=l.map((W,ne)=>{let Ke=`Agent ${ne+1} [${h[ne]}]: `,ct=Math.max(20,60-Ke.length),Te=W.task.substring(0,ct)+(W.task.length>ct?"...":"");return Ke+Te}),g=new H1(m);g.start();let _=`
882
+ `),r=[{role:"system",content:Fb.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let f=Lb(n);f.provider&&(i.provider=f.provider),f.model&&(i.model=f.model)}let l=(await Mb(r,[],i)).content||"",c=sd(l),u={summary:String(c.summary||""),conflicts:Array.isArray(c.conflicts)?c.conflicts:[],commitMessage:String(c.commitMessage||""),filesChanged:Array.isArray(c.filesChanged)?c.filesChanged:[]},d=Yb(u,t);return d&&(u.commitMessage="",u.commitSuppressedReason=d),u}function Yb(t,e){let n=/\b(fail(?:ed|ure|s)?|did not pass|tests? (?:are )?failing|red|broken)\b/i,o=/\b(reported|claimed|said)\b.*\b(pass|fail)/i;for(let s of t.conflicts)if(typeof s=="string"){if(n.test(s))return"conflict mentions failure";if(o.test(s)&&/pass/i.test(s)&&/fail/i.test(s))return"agents disagree on pass/fail"}for(let s of e){if(s.status==="error"||s.status==="failed"||s.status==="skipped")return`agent reported ${s.status}`;let r=String(s.result||"");if(/\b(test(?:s)? fail|verification fail|build (?:error|fail))/i.test(r))return"agent result describes test/build failure"}return null}async function V1(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Db,o=e.workerModel||jb,s=e.maxParallel||Ib,r=e.maxSubTasks||Ya,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
883
+ ${$e.bold}Orchestrator${$e.reset} ${$e.dim}model: ${n} | workers: ${o} | max parallel: ${s}${$e.reset}
884
+ `),i("decomposing"),console.log(`${$e.dim}Phase 1: Decomposing prompt into sub-tasks...${$e.reset}`);let l;try{l=await Hb(t,n,{maxSubTasks:r})}catch(H){return console.log(`${$e.red}Decompose failed: ${H.message}${$e.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${H.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${$e.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${$e.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${$e.green}Decomposed into ${l.length} sub-tasks:${$e.reset}`);for(let H of l){console.log(` ${$e.dim}${H.id}:${$e.reset} ${H.task}`);let ne=H.scope.filter(Boolean);ne.length>0&&console.log(` ${$e.dim}scope: ${ne.join(", ")}${$e.reset}`)}console.log("");let c=new Map;for(let H=0;H<l.length;H++)for(let ne of l[H].scope)ne&&!c.has(ne)&&c.set(ne,H);i("executing"),console.log(`${$e.dim}Phase 2: Running ${l.length} sub-agents (max ${s} parallel)...${$e.reset}
885
+ `);let u=Date.now(),d=Ub(s),f={findings:[],_lock:!1},h=l.map(H=>{let ne=Y1(H.task);return(ne?Nb(ne.id):null)||o}),m=l.map((H,ne)=>{let Ve=`Agent ${ne+1} [${h[ne]}]: `,ut=Math.max(20,60-Ve.length),Re=H.task.substring(0,ut)+(H.task.length>ut?"...":"");return Ve+Re}),g=new z1(m);g.start();let _=`
886
886
  You are a focused coding agent executing ONE specific sub-task.
887
887
  Your scope is limited to the files listed in your task definition.
888
888
 
@@ -906,24 +906,24 @@ RULES:
906
906
  - Start with symbol-aware reads inside your scope: locate the target function/class/module, then read the exact section instead of scanning broadly.
907
907
  - Before finishing, run the smallest relevant verification for your scope and report any residual risk explicitly.
908
908
  - If your sub-task is review/audit/verify/preflight-oriented, do not edit files. Output findings or the blocker first with severity, file/resource, and impact. If nothing is wrong, say so explicitly and mention remaining risk.
909
- `,k=new Map;for(let W=0;W<l.length;W++){let ne=l[W].priority||1;k.has(ne)||k.set(ne,[]),k.get(ne).push({st:l[W],idx:W})}let $=[...k.keys()].sort((W,ne)=>W-ne),O=new Array(l.length),E=null;for(let W of $){let Ke=k.get(W).map(async({st:ve,idx:b})=>{let L=await d();try{let U=await T(ve,b,{acquire:d,subTaskModels:h,labels:m,progress:g,sharedContext:f,_fileOwnership:c,workerModel:o,WORKER_SYSTEM_PROMPT:_});return O[b]=U,U}finally{L()}}),Te=(await Promise.all(Ke)).find(ve=>zb(l[ve?._idx],ve,W,$));if(Te){E={task:l[Te._idx]?.task||Te.task||"unknown task",result:Te.result||""};break}}if(E)for(let W=0;W<O.length;W++)O[W]||(O[W]={task:l[W].task,status:"skipped",result:`Skipped because prerequisite failed: ${E.task}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:l[W].scope,_idx:W});async function T(W,ne,Ke){try{let ct=f.findings.filter(be=>be.agentId!==W.id).map(be=>`Agent ${be.agentId} found: ${be.summary}`).join(`
910
- `),Te=[...c.entries()].filter(([,be])=>be===ne).map(([be])=>be),ve=[...c.entries()].filter(([,be])=>be!==ne).map(([be])=>be),b=Vb(W.task),L=[`Worker mode: ${b}`,ct?`Prior agent findings:
911
- ${ct}
912
- `:"",W.scope.length>0?`Focus on files: ${W.scope.join(", ")}`:"",Te.length>0?`You OWN these files (may read+write): ${Te.join(", ")}`:"",ve.length>0?`READ ONLY (owned by other agents, do NOT write): ${ve.join(", ")}`:""].filter(Boolean),U=h[ne],Z=process.env.NEX_FALLBACK_MODEL||Ob("agentic")||o,X=0,R=await qb(async()=>{let be=X>0;be&&(g.update(ne,"retry"),process.stderr.write(` ${_e.dim}[Agent ${ne+1}] retrying after error...${_e.reset}
913
- `)),X++;let Le=be&&U!==Z?Z:U;return Ab({task:W.task,type:b,context:L.length>0?L.join(`
914
- `):void 0,max_iterations:Math.min(W.estimatedCalls||10,15),model:Le,_skipLog:!0,_systemPrompt:_,_readOnlyFiles:ve},{onUpdate:Wt=>{if(Wt&&Wt.type==="tool_call"&&process.stderr.isTTY){let Vd=`Agent ${ne+1} [${Le}]`,pi=Wt.tool||"...";g.labels[ne]=`${Vd}: ${pi}`}}})},1,2e3),ce="";if(Yb(b,R,W,Te)){let be=[...new Set([...Te,...Array.isArray(R.filesModified)?R.filesModified:[],...Array.isArray(W.scope)?W.scope:[]])].filter(Boolean);try{g.labels[ne]=`Agent ${ne+1} [${U}] review`,g.update(ne,"retry");let Le=await Ab({task:`Review the completed changes for: ${W.task}`,type:"review",context:X1(W,R,be),max_iterations:4,model:U,_skipLog:!0,_systemPrompt:_},{onUpdate:()=>{}},1);Gb(Le.result)?(ce=`
909
+ `,k=new Map;for(let H=0;H<l.length;H++){let ne=l[H].priority||1;k.has(ne)||k.set(ne,[]),k.get(ne).push({st:l[H],idx:H})}let $=[...k.keys()].sort((H,ne)=>H-ne),O=new Array(l.length),E=null;for(let H of $){let Ve=k.get(H).map(async({st:Te,idx:b})=>{let I=await d();try{let U=await T(Te,b,{acquire:d,subTaskModels:h,labels:m,progress:g,sharedContext:f,_fileOwnership:c,workerModel:o,WORKER_SYSTEM_PROMPT:_});return O[b]=U,U}finally{I()}}),Re=(await Promise.all(Ve)).find(Te=>Vb(l[Te?._idx],Te,H,$));if(Re){E={task:l[Re._idx]?.task||Re.task||"unknown task",result:Re.result||""};break}}if(E)for(let H=0;H<O.length;H++)O[H]||(O[H]={task:l[H].task,status:"skipped",result:`Skipped because prerequisite failed: ${E.task}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:l[H].scope,_idx:H});async function T(H,ne,Ve){try{let ut=f.findings.filter(we=>we.agentId!==H.id).map(we=>`Agent ${we.agentId} found: ${we.summary}`).join(`
910
+ `),Re=[...c.entries()].filter(([,we])=>we===ne).map(([we])=>we),Te=[...c.entries()].filter(([,we])=>we!==ne).map(([we])=>we),b=Jb(H.task),I=[`Worker mode: ${b}`,ut?`Prior agent findings:
911
+ ${ut}
912
+ `:"",H.scope.length>0?`Focus on files: ${H.scope.join(", ")}`:"",Re.length>0?`You OWN these files (may read+write): ${Re.join(", ")}`:"",Te.length>0?`READ ONLY (owned by other agents, do NOT write): ${Te.join(", ")}`:""].filter(Boolean),U=h[ne],Z=process.env.NEX_FALLBACK_MODEL||Nb("agentic")||o,X=0,R=await Bb(async()=>{let we=X>0;we&&(g.update(ne,"retry"),process.stderr.write(` ${$e.dim}[Agent ${ne+1}] retrying after error...${$e.reset}
913
+ `)),X++;let Ie=we&&U!==Z?Z:U;return Pb({task:H.task,type:b,context:I.length>0?I.join(`
914
+ `):void 0,max_iterations:Math.min(H.estimatedCalls||10,15),model:Ie,_skipLog:!0,_systemPrompt:_,_readOnlyFiles:Te},{onUpdate:Gt=>{if(Gt&&Gt.type==="tool_call"&&process.stderr.isTTY){let Jd=`Agent ${ne+1} [${Ie}]`,hi=Gt.tool||"...";g.labels[ne]=`${Jd}: ${hi}`}}})},1,2e3),ue="";if(Kb(b,R,H,Re)){let we=[...new Set([...Re,...Array.isArray(R.filesModified)?R.filesModified:[],...Array.isArray(H.scope)?H.scope:[]])].filter(Boolean);try{g.labels[ne]=`Agent ${ne+1} [${U}] review`,g.update(ne,"retry");let Ie=await Pb({task:`Review the completed changes for: ${H.task}`,type:"review",context:Q1(H,R,we),max_iterations:4,model:U,_skipLog:!0,_systemPrompt:_},{onUpdate:()=>{}},1);zb(Ie.result)?(ue=`
915
915
 
916
916
  Reviewer findings:
917
- ${Le.result}`,f.findings.push({agentId:`${W.id}-review`,summary:String(Le.result||"").slice(0,200),files:be})):Le.result&&(ce=`
917
+ ${Ie.result}`,f.findings.push({agentId:`${H.id}-review`,summary:String(Ie.result||"").slice(0,200),files:we})):Ie.result&&(ue=`
918
918
 
919
- Reviewer: ${Le.result}`)}catch(Le){ce=`
919
+ Reviewer: ${Ie.result}`)}catch(Ie){ue=`
920
920
 
921
- Reviewer note: review pass failed (${Le.message})`}}let qe=typeof R.result=="string"?`${R.result}${ce}`.slice(0,200):`${String(R.result||"")}${ce}`.slice(0,200);return f.findings.push({agentId:W.id,summary:qe,files:Array.isArray(W.scope)?W.scope:[]}),g.labels[ne]=m[ne],g.update(ne,R.status==="failed"?"error":"done"),a.input+=R.tokensUsed?.input||0,a.output+=R.tokensUsed?.output||0,R.tokensUsed?._estimated&&(a._estimated=!0),{...R,result:`${String(R.result||"")}${ce}`,_scope:W.scope,_idx:ne}}catch(ct){return g.labels[ne]=m[ne],g.update(ne,"error"),{task:W.task,status:"failed",result:`Error: ${ct.message}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:W.scope,_idx:ne}}}let q;try{q=O}finally{g.stop({silent:!0}),U1()}console.log("");let ee=Math.round((Date.now()-u)/1e3),te=ee>=60?`${Math.floor(ee/60)}m ${ee%60}s`:`${ee}s`;for(let W=0;W<q.length;W++){let ne=q[W],ct=ne.status==="done"||ne.status==="truncated"&&ne.result&&!ne.result.startsWith("Error")?`${_e.green}\u2713${_e.reset}`:`${_e.red}\u2717${_e.reset}`,Te=ne._scope&&ne._scope.length>0?ne._scope.map(L=>L.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],ve=Te.length>0?Te.join(", "):ne.task.substring(0,35)+(ne.task.length>35?"...":""),b=W===q.length-1;console.log(` ${ct} Agent ${W+1} ${_e.dim}${ve}${_e.reset}${b?` ${_e.dim}${te}${_e.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${_e.dim}Phase 3: Synthesizing results...${_e.reset}`);let K;if(E)K={summary:`Stopped before continuing because prerequisite sub-task failed: ${E.task}. ${E.result}`,conflicts:[],commitMessage:"",commitSuppressedReason:"prerequisite sub-task failed",filesChanged:[],resourcesChanged:[]};else try{K=await Wb(q,t,n)}catch(W){console.log(`${_e.yellow}Synthesize failed: ${W.message} \u2014 using raw results.${_e.reset}`),K={summary:q.map(ne=>ne.result).join(`
922
- `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ae=f.findings.flatMap(W=>W.files),se=new Map;for(let W of ae)se.set(W,(se.get(W)||0)+1);let ie=[...se.values()].some(W=>W>1),Be=f.findings.length>1&&ie?` ${_e.dim}(agents shared context)${_e.reset}`:"";if(console.log(`
923
- ${_e.bold}Summary:${_e.reset} ${K.summary}${Be}`),K.conflicts.length>0){console.log(`${_e.yellow}Conflicts:${_e.reset}`);for(let W of K.conflicts)console.log(` - ${W}`)}K.commitMessage?console.log(`${_e.dim}Suggested commit: ${K.commitMessage}${_e.reset}`):K.commitSuppressedReason&&console.log(`${_e.yellow}No commit suggested:${_e.reset} ${K.commitSuppressedReason}`);let Re=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(`${_e.dim}Tokens: ${Re}${_e.reset}
924
- `),{results:q,synthesis:K,totalTokens:a}}var z1=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,K1=/\b(review|audit|verify|validate|inspect|critique)\b/i,V1=/\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 X1(t,e,n){let o=Array.isArray(n)&&n.length>0?`Files to review: ${n.join(", ")}`:"Files to review: inspect the files touched by the implementing agent";return["Review the finished implementation for correctness, regressions, and missing verification.",`Original task: ${t.task}`,o,`Implementation summary: ${String(e.result||"").slice(0,600)}`,'Report findings first. If no material issue exists, say "No material findings" and mention the main residual risk.'].join(`
925
- `)}function Gb(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function Yb(t,e,n,o){if(t!=="implement"||!e||e.status==="failed")return!1;let s=Array.isArray(n?.scope)?n.scope.length:0,r=Array.isArray(e.filesModified)?e.filesModified.length:0,i=Array.isArray(o)?o.length:0;return s+r+i>0}function zb(t,e,n,o){return J1(e)?Kb(t)?!0:o.some(r=>r>n)&&n===o[0]:!1}function J1(t){return t&&(t.status==="failed"||t.status==="error"||t.status==="skipped")}function Kb(t){let e=typeof t=="string"?t:`${t?.task||""} ${(t?.scope||[]).join(" ")}`;return/\b(preflight|git status|current branch|worktree|dirty|unrelated changes?|clean working tree|pull\/rebase|rebase|before changing|before editing|stop without|abort|blocker|verification gate|release gate)\b/i.test(e)}function Vb(t){if(!t)return"implement";let e=z1.test(t),n=K1.test(t);return V1.test(t)?"implement":n?"review":e?"explore":"implement"}Xb.exports={runOrchestrated:Y1,decompose:Ub,synthesize:Wb,shouldSuppressCommit:Hb,detectComplexPrompt:G1,detectCriticalPathPrompt:Bb,extractJSON:td,createSemaphore:Fb,DECOMPOSE_PROMPT:jb,SYNTHESIZE_PROMPT:Db,DEFAULT_ORCHESTRATOR_MODEL:Ib,DEFAULT_WORKER_MODEL:Lb,DEFAULT_MAX_PARALLEL:Mb,DEFAULT_MAX_SUBTASKS:Ga,withRetry:qb,_classifyWorkerType:Vb,_hasMaterialReviewFindings:Gb,_shouldRunFollowUpReview:Yb,_shouldAbortAfterWave:zb,_isBlockingTask:Kb}});var ju=J((SN,Bw)=>{var{C:p,Spinner:Bo,TaskProgress:Z1,formatToolCall:Q1,formatToolSummary:ri,formatSectionHeader:Wr,formatMilestone:eC,setActiveTaskProgress:wN,getThinkingVerb:nd,setActiveModelForSpinner:Zb}=_t(),{debugLog:P,warnLog:_N}=cc(),{MilestoneTracker:tC}=vp(),{callStream:Ya}=$t(),{parseToolArgs:nC}=Yi(),{executeTool:Ld}=cr(),{gatherProjectContext:sC}=Py(),{fitToContext:oC,forceCompress:Nn,getUsage:wn,estimateTokens:rC,buildProgressSnapshot:iC}=Pn(),{autoSave:aC,flushAutoSave:lC}=ja(),{scoreMessages:cC,formatScore:uC,appendScoreHistory:dC}=Hy(),{detectCategory:fC,getModelForPhase:md,getPhaseBudget:ls,isPhaseRoutingEnabled:pC}=Dr();function $e(t){aC(t),lC()}function za(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 yw(t){if(!t||typeof t!="string")return!1;let e=t.slice(-1200);return/\b(done|complete|completed|fixed|implemented|ready|verified|verification complete|tests? pass(?:ed)?|build pass(?:ed)?|all checks pass(?:ed)?|all good)\b/i.test(e)}function bw(t){return!t||typeof t!="string"?!1:/\b(not verified|verification (?:was )?not run|tests? (?:were )?not run|build (?:was )?not run|unchecked|unverified)\b/i.test(t)}function hC(t){return!t||typeof t!="string"?!1:/^\s*(?:final\s+)?(?:summary|report|answer|result)\s*:/i.test(t)}function mC(t){if(!t||typeof t!="string")return!1;let e=t.trim();if(!e)return!1;let n=e.slice(-300);return n.includes("?")?/(?:would you like|do you want|should i|shall i|can you clarify|could you clarify|what would you like me to|which (?:one|option|area|approach)|how would you like me to)\b/i.test(n):!1}function gC(t){return!t||typeof t!="string"?!1:/\.(?:md|mdx|txt|rst|adoc)$/i.test(t)}function vt(t){try{if(!t.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(s=>s&&s.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let n=cC(t);if(!n)return;console.log(uC(n,p));try{let{_getSessionsDir:o}=ja(),s=require("fs"),r=require("path").join(o(),"_autosave.json");if(s.existsSync(r)){let i=JSON.parse(s.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,s.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=Yi(),s=Zl();dC(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:yC}=Sr(),{getDeploymentContextBlock:bC,probeUrlServer:wC,detectRuntimeDebugTarget:Qb}=qu(),{getFewShotForInput:_C}=Qy(),{checkPermission:$C,setPermission:kC,savePermissions:xC}=rb(),{confirm:ww,setAllowAlwaysHandler:SC,getAutoConfirm:$n}=or(),{isPlanMode:Qs,getPlanModePrompt:vC,PLAN_MODE_ALLOWED_TOOLS:_w,setPlanContent:EC,extractStepsFromText:TC,createPlan:RC,getActivePlan:$N,startExecution:kN,advancePlanStep:CC,getPlanStepInfo:AC}=Ua(),{StreamRenderer:OC}=$b(),{runHooks:ew}=Eb(),{routeMCPCall:PC,getMCPToolDefinitions:NC}=Tc(),{getSkillInstructions:MC,getSkillToolDefinitions:LC,routeSkillCall:IC,matchSkillTriggers:jC}=vc(),{trackUsage:tw,estimateTokens:nw,getSessionCosts:sw,getProviderCostMode:ow}=Di();function rw(t){return!t||typeof t!="string"?0:typeof nw=="function"?nw(t):Math.ceil(t.length/4)}var{validateToolArgs:DC}=Ac(),{filterToolsForModel:iw,getModelTier:qC,PROVIDER_DEFAULT_TIER:xN}=mr(),{getConfiguredProviders:FC,getActiveProviderName:In,getActiveModelId:kn,setActiveModel:sd,MODEL_EQUIVALENTS:fl}=$t(),{getModelProfile:BC,getModelBriefing:UC}=Ha(),tt=require("fs"),ot=require("path"),WC=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function HC(t){let e=eC(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
926
- `)}var aw=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,lw=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,GC=/\b(?:clipboard|pasteboard|clipboard screenshot)\b/i;function YC(t){let e=[],n;for(aw.lastIndex=0;(n=aw.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):ot.resolve(o);tt.existsSync(s)&&e.push({raw:o,abs:s})}return e}function $w(t){let e=[],n;for(lw.lastIndex=0;(n=lw.exec(t))!==null;)e.push(n[1].trim());return e}async function kw(t){try{let n=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),o=n.headers["content-type"]||"",s=o.startsWith("image/")?o.split(";")[0]:zC(t);return{data:Buffer.from(n.data).toString("base64"),media_type:s}}catch{return null}}function zC(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 xw(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=ot.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&tt.existsSync(e)){let s=tt.readFileSync(e);if(s.length>100)return{data:s.toString("base64"),media_type:"image/png",path:e};try{tt.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let o=t("osascript",["-e",`try
921
+ Reviewer note: review pass failed (${Ie.message})`}}let qe=typeof R.result=="string"?`${R.result}${ue}`.slice(0,200):`${String(R.result||"")}${ue}`.slice(0,200);return f.findings.push({agentId:H.id,summary:qe,files:Array.isArray(H.scope)?H.scope:[]}),g.labels[ne]=m[ne],g.update(ne,R.status==="failed"?"error":"done"),a.input+=R.tokensUsed?.input||0,a.output+=R.tokensUsed?.output||0,R.tokensUsed?._estimated&&(a._estimated=!0),{...R,result:`${String(R.result||"")}${ue}`,_scope:H.scope,_idx:ne}}catch(ut){return g.labels[ne]=m[ne],g.update(ne,"error"),{task:H.task,status:"failed",result:`Error: ${ut.message}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:H.scope,_idx:ne}}}let q;try{q=O}finally{g.stop({silent:!0}),G1()}console.log("");let ee=Math.round((Date.now()-u)/1e3),te=ee>=60?`${Math.floor(ee/60)}m ${ee%60}s`:`${ee}s`;for(let H=0;H<q.length;H++){let ne=q[H],ut=ne.status==="done"||ne.status==="truncated"&&ne.result&&!ne.result.startsWith("Error")?`${$e.green}\u2713${$e.reset}`:`${$e.red}\u2717${$e.reset}`,Re=ne._scope&&ne._scope.length>0?ne._scope.map(I=>I.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],Te=Re.length>0?Re.join(", "):ne.task.substring(0,35)+(ne.task.length>35?"...":""),b=H===q.length-1;console.log(` ${ut} Agent ${H+1} ${$e.dim}${Te}${$e.reset}${b?` ${$e.dim}${te}${$e.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${$e.dim}Phase 3: Synthesizing results...${$e.reset}`);let K;if(E)K={summary:`Stopped before continuing because prerequisite sub-task failed: ${E.task}. ${E.result}`,conflicts:[],commitMessage:"",commitSuppressedReason:"prerequisite sub-task failed",filesChanged:[],resourcesChanged:[]};else try{K=await Gb(q,t,n)}catch(H){console.log(`${$e.yellow}Synthesize failed: ${H.message} \u2014 using raw results.${$e.reset}`),K={summary:q.map(ne=>ne.result).join(`
922
+ `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ae=f.findings.flatMap(H=>H.files),se=new Map;for(let H of ae)se.set(H,(se.get(H)||0)+1);let ie=[...se.values()].some(H=>H>1),Be=f.findings.length>1&&ie?` ${$e.dim}(agents shared context)${$e.reset}`:"";if(console.log(`
923
+ ${$e.bold}Summary:${$e.reset} ${K.summary}${Be}`),K.conflicts.length>0){console.log(`${$e.yellow}Conflicts:${$e.reset}`);for(let H of K.conflicts)console.log(` - ${H}`)}K.commitMessage?console.log(`${$e.dim}Suggested commit: ${K.commitMessage}${$e.reset}`):K.commitSuppressedReason&&console.log(`${$e.yellow}No commit suggested:${$e.reset} ${K.commitSuppressedReason}`);let Ce=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(`${$e.dim}Tokens: ${Ce}${$e.reset}
924
+ `),{results:q,synthesis:K,totalTokens:a}}var X1=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,J1=/\b(review|audit|verify|validate|inspect|critique)\b/i,Z1=/\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 Q1(t,e,n){let o=Array.isArray(n)&&n.length>0?`Files to review: ${n.join(", ")}`:"Files to review: inspect the files touched by the implementing agent";return["Review the finished implementation for correctness, regressions, and missing verification.",`Original task: ${t.task}`,o,`Implementation summary: ${String(e.result||"").slice(0,600)}`,'Report findings first. If no material issue exists, say "No material findings" and mention the main residual risk.'].join(`
925
+ `)}function zb(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function Kb(t,e,n,o){if(t!=="implement"||!e||e.status==="failed")return!1;let s=Array.isArray(n?.scope)?n.scope.length:0,r=Array.isArray(e.filesModified)?e.filesModified.length:0,i=Array.isArray(o)?o.length:0;return s+r+i>0}function Vb(t,e,n,o){return eC(e)?Xb(t)?!0:o.some(r=>r>n)&&n===o[0]:!1}function eC(t){return t&&(t.status==="failed"||t.status==="error"||t.status==="skipped")}function Xb(t){let e=typeof t=="string"?t:`${t?.task||""} ${(t?.scope||[]).join(" ")}`;return/\b(preflight|git status|current branch|worktree|dirty|unrelated changes?|clean working tree|pull\/rebase|rebase|before changing|before editing|stop without|abort|blocker|verification gate|release gate)\b/i.test(e)}function Jb(t){if(!t)return"implement";let e=X1.test(t),n=J1.test(t);return Z1.test(t)?"implement":n?"review":e?"explore":"implement"}Zb.exports={runOrchestrated:V1,decompose:Hb,synthesize:Gb,shouldSuppressCommit:Yb,detectComplexPrompt:K1,detectCriticalPathPrompt:Wb,extractJSON:sd,createSemaphore:Ub,DECOMPOSE_PROMPT:qb,SYNTHESIZE_PROMPT:Fb,DEFAULT_ORCHESTRATOR_MODEL:Db,DEFAULT_WORKER_MODEL:jb,DEFAULT_MAX_PARALLEL:Ib,DEFAULT_MAX_SUBTASKS:Ya,withRetry:Bb,_classifyWorkerType:Jb,_hasMaterialReviewFindings:zb,_shouldRunFollowUpReview:Kb,_shouldAbortAfterWave:Vb,_isBlockingTask:Xb}});var qu=J((RN,Hw)=>{var{C:p,Spinner:Wo,TaskProgress:tC,formatToolCall:nC,formatToolSummary:ii,formatSectionHeader:Hr,formatMilestone:sC,setActiveTaskProgress:xN,getThinkingVerb:od,setActiveModelForSpinner:ew}=$t(),{debugLog:P,warnLog:SN}=dc(),{MilestoneTracker:oC}=Tp(),{callStream:za}=kt(),{parseToolArgs:rC}=zi(),{executeTool:jd}=ur(),{gatherProjectContext:iC}=My(),{fitToContext:aC,forceCompress:Nn,getUsage:wn,estimateTokens:lC,buildProgressSnapshot:cC}=Pn(),{autoSave:uC,flushAutoSave:dC}=Da(),{scoreMessages:fC,formatScore:pC,appendScoreHistory:hC}=Yy(),{detectCategory:mC,getModelForPhase:yd,getPhaseBudget:ls,isPhaseRoutingEnabled:gC}=qr();function _e(t){uC(t),dC()}function Ka(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 _w(t){if(!t||typeof t!="string")return!1;let e=t.slice(-1200);return/\b(done|complete|completed|fixed|implemented|ready|verified|verification complete|tests? pass(?:ed)?|build pass(?:ed)?|all checks pass(?:ed)?|all good)\b/i.test(e)}function $w(t){return!t||typeof t!="string"?!1:/\b(not verified|verification (?:was )?not run|tests? (?:were )?not run|build (?:was )?not run|unchecked|unverified)\b/i.test(t)}function yC(t){return!t||typeof t!="string"?!1:/^\s*(?:final\s+)?(?:summary|report|answer|result)\s*:/i.test(t)}function bC(t){if(!t||typeof t!="string")return!1;let e=t.trim();if(!e)return!1;let n=e.slice(-300);return n.includes("?")?/(?:would you like|do you want|should i|shall i|can you clarify|could you clarify|what would you like me to|which (?:one|option|area|approach)|how would you like me to)\b/i.test(n):!1}function wC(t){return!t||typeof t!="string"?!1:/\.(?:md|mdx|txt|rst|adoc)$/i.test(t)}function bt(t){try{if(!t.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(s=>s&&s.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let n=fC(t);if(!n)return;console.log(pC(n,p));try{let{_getSessionsDir:o}=Da(),s=require("fs"),r=require("path").join(o(),"_autosave.json");if(s.existsSync(r)){let i=JSON.parse(s.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,s.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=zi(),s=ec();hC(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:_C}=vr(),{getDeploymentContextBlock:$C,probeUrlServer:kC,detectRuntimeDebugTarget:tw}=Bu(),{getFewShotForInput:xC}=tb(),{checkPermission:SC,setPermission:vC,savePermissions:EC}=ab(),{confirm:kw,setAllowAlwaysHandler:TC,getAutoConfirm:$n}=rr(),{isPlanMode:eo,getPlanModePrompt:RC,PLAN_MODE_ALLOWED_TOOLS:xw,setPlanContent:CC,extractStepsFromText:AC,createPlan:OC,getActivePlan:vN,startExecution:EN,advancePlanStep:PC,getPlanStepInfo:NC}=Wa(),{StreamRenderer:MC}=xb(),{runHooks:nw}=Rb(),{routeMCPCall:LC,getMCPToolDefinitions:IC}=Cc(),{getSkillInstructions:jC,getSkillToolDefinitions:DC,routeSkillCall:qC,matchSkillTriggers:FC}=Tc(),{trackUsage:sw,estimateTokens:ow,getSessionCosts:rw,getProviderCostMode:iw}=qi();function aw(t){return!t||typeof t!="string"?0:typeof ow=="function"?ow(t):Math.ceil(t.length/4)}var{validateToolArgs:BC}=Pc(),{filterToolsForModel:lw,getModelTier:UC,PROVIDER_DEFAULT_TIER:TN}=gr(),{getConfiguredProviders:WC,getActiveProviderName:In,getActiveModelId:kn,setActiveModel:rd,MODEL_EQUIVALENTS:hl}=kt(),{getModelProfile:HC,getModelBriefing:GC}=Ga(),tt=require("fs"),ot=require("path"),YC=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function zC(t){let e=sC(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
926
+ `)}var cw=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,uw=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,KC=/\b(?:clipboard|pasteboard|clipboard screenshot)\b/i;function VC(t){let e=[],n;for(cw.lastIndex=0;(n=cw.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):ot.resolve(o);tt.existsSync(s)&&e.push({raw:o,abs:s})}return e}function Sw(t){let e=[],n;for(uw.lastIndex=0;(n=uw.exec(t))!==null;)e.push(n[1].trim());return e}async function vw(t){try{let n=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),o=n.headers["content-type"]||"",s=o.startsWith("image/")?o.split(";")[0]:XC(t);return{data:Buffer.from(n.data).toString("base64"),media_type:s}}catch{return null}}function XC(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 Ew(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=ot.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&tt.existsSync(e)){let s=tt.readFileSync(e);if(s.length>100)return{data:s.toString("base64"),media_type:"image/png",path:e};try{tt.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let o=t("osascript",["-e",`try
927
927
  set imgData to the clipboard as \xABclass PNGf\xBB
928
928
  return "has_image"
929
929
  on error
@@ -934,62 +934,62 @@ end try`],{timeout:3e3});if(o.stdout&&o.stdout.toString().trim()==="has_image"){
934
934
  set fRef to open for access filePath with write permission
935
935
  write imgData to fRef
936
936
  close access fRef
937
- `;if(t("osascript",["-e",s],{timeout:5e3}).status===0&&tt.existsSync(e)){let i=tt.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function cw(t){let e=tt.readFileSync(t),n=ot.extname(t).toLowerCase().replace(".",""),o=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:o}}function Sw(t){let e=YC(t),n=$w(t),o=GC.test(t),s=n.length>0||o;if(e.length===0&&!s)return t;if(!s){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=cw(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}=cw(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){P(`${p.yellow} \u26A0 Path resolution failed: ${a.message}${p.reset}`)}if(n.length>0){let i=await Promise.all(n.map(kw));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=xw();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
937
+ `;if(t("osascript",["-e",s],{timeout:5e3}).status===0&&tt.existsSync(e)){let i=tt.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function dw(t){let e=tt.readFileSync(t),n=ot.extname(t).toLowerCase().replace(".",""),o=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:o}}function Tw(t){let e=VC(t),n=Sw(t),o=KC.test(t),s=n.length>0||o;if(e.length===0&&!s)return t;if(!s){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=dw(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}=dw(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){P(`${p.yellow} \u26A0 Path resolution failed: ${a.message}${p.reset}`)}if(n.length>0){let i=await Promise.all(n.map(vw));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=Ew();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
938
938
  [Clipboard image attached: ${i.path}]`):r[0].text+=`
939
- [No image found in clipboard]`}return r.length>1?r:t})()}var KC=[/\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 vw(t){return typeof t!="string"||!t?!1:KC.some(e=>e.test(t))}function VC(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let n=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(n.length<6)return{text:t,truncated:!1,repeatCount:0};let o=new Map;for(let l=0;l<=n.length-3;l++){let c=n.slice(l,l+3).join("").trim();c.length>30&&o.set(c,(o.get(c)||0)+1)}let s=0,r="";for(let[l,c]of o)c>s&&(s=c,r=l);if(s<3)return{text:t,truncated:!1,repeatCount:s};let i=`
939
+ [No image found in clipboard]`}return r.length>1?r:t})()}var JC=[/\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 Rw(t){return typeof t!="string"||!t?!1:JC.some(e=>e.test(t))}function ZC(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let n=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(n.length<6)return{text:t,truncated:!1,repeatCount:0};let o=new Map;for(let l=0;l<=n.length-3;l++){let c=n.slice(l,l+3).join("").trim();c.length>30&&o.set(c,(o.get(c)||0)+1)}let s=0,r="";for(let[l,c]of o)c>s&&(s=c,r=l);if(s<3)return{text:t,truncated:!1,repeatCount:s};let i=`
940
940
 
941
- [SYSTEM: Output repetition detected \u2014 response truncated (${s}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let l=0,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:s}}function gd(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
941
+ [SYSTEM: Output repetition detected \u2014 response truncated (${s}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let l=0,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:s}}function bd(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
942
942
  `),o=new Map;for(let h of n){let m=h.trim();m.length>=20&&o.set(m,(o.get(m)||0)+1)}let s=0,r="";for(let[h,m]of o)m>s&&(s=m,r=h);let a=r.toLowerCase().includes("read_file")||r.toLowerCase().includes("reading")?2:e;if(s<=a)return{text:t,truncated:!1,repeatCount:s};let l=`
943
943
 
944
- \u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let h=t.indexOf(r,d);if(h===-1)break;c++,u=h+r.length,d=h+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:s}}var od=null,rd=null,id=null;function Bt(){if(od===null){let{TOOL_DEFINITIONS:t}=cr();od=t}return rd===null&&(rd=LC()),id===null&&(id=NC()),[...od,...rd,...id]}var yd=50;function XC(t){Number.isFinite(t)&&t>0&&(yd=t)}function ad(t=In()){if(process.env.NEX_DISABLE_TOOL_BUDGET==="1")return 1/0;let e=process.env.NEX_MAX_TOOL_CALLS;if(e){let n=parseInt(e,10);if(Number.isFinite(n)&&n>0)return n}return t==="local"?5:30}function uw(t,e){return`[SYSTEM STOP] Tool-call budget reached (${t}/${e}). You MUST stop calling tools now. Provide your final answer based only on the information already in the conversation. If the task cannot be completed from the gathered evidence, state the blocker plainly and do not invent facts.`}var Ja=()=>null;function JC(t){Ja=t}var Kr=null,bd=null,Uo=null,Wo="",Ho=0,wd="",_d=0,Za=new Map,ZC=1e4,QC=6e3,eA=/\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 tA(t){return!t||typeof t!="string"?t:t.replace(eA,(e,n)=>`${n}=***REDACTED***`)}var nA=7e3,sA=4e3;function oA(t,e=null){let n=tA(t),o=rC(n),s=e==="read_file"?nA:ZC,r=e==="read_file"?sA:QC;if(o>s)try{let{compressToolResult:i}=Pn();return i(n,r)}catch{return n}return n}function Ew(t){try{let{getActiveModel:e}=$t(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(Za.has(o))return Za.get(o);let s=iw(t);return Za.set(o,s),s}catch{return iw(t)}}function rA(){Za.clear()}function iA(t,e){let n=new Set(e);return(t||[]).some(o=>o.role!=="assistant"?!1:Array.isArray(o.tool_calls)?o.tool_calls.some(s=>n.has(s?.function?.name||s?.name)):Array.isArray(o.content)?o.content.some(s=>s?.type==="tool_use"&&n.has(s?.name)):!1)}var Vr={hash:null,ts:0},aA=3e4;async function Tw(){if(Vr.hash&&Date.now()-Vr.ts<aA)return Vr.hash;try{let t=require("fs").promises,e=require("path"),n=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(n.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=Sr(),a=i();a&&s.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(tt.existsSync(i)){let a=await t.stat(i);s.push(`brain:${a.mtimeMs}`)}}catch{}let r=s.join("|");return Vr={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function $d(){Kr=null,bd=null,Vr={hash:null,ts:0},Uo=null}var lA=new Set(["spawn_agents"]),ld=10,cd=10,Ka=5,dw=6e4,ud=12e4,cA=process.env.NEX_STALE_AUTO_SWITCH!=="0";function uA(t){try{let e=require("fs"),n=require("path"),o=n.join(process.cwd(),".nex","plans");e.existsSync(o)||e.mkdirSync(o,{recursive:!0});let s=n.join(o,"current-plan.md");e.writeFileSync(s,t,"utf-8")}catch{}}SC(t=>{kC(t,"allow"),xC(),console.log(`${p.green} \u2713 ${t}: always allow${p.reset}`)});async function dA(t){let e=t.function.name,n=e;if(typeof e=="string"&&e.includes(".")){let d=e.split(".").pop(),f={exec:"bash",find:"search_files",search:"search_files",grep_search:"grep",read:"read_file"};Bt().some(m=>m.function.name===d)?n=d:f[d]&&(n=f[d])}let o=nC(t.function.arguments),s=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!o){let f=Bt().find(m=>m.function.name===n),h=f?JSON.stringify(f.function.parameters,null,2):"unknown";return P(`${p.yellow} \u26A0 ${n}: malformed arguments, sending schema hint${p.reset}`),{callId:s,fnName:n,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
944
+ \u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let h=t.indexOf(r,d);if(h===-1)break;c++,u=h+r.length,d=h+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:s}}var id=null,ad=null,ld=null;function Bt(){if(id===null){let{TOOL_DEFINITIONS:t}=ur();id=t}return ad===null&&(ad=DC()),ld===null&&(ld=IC()),[...id,...ad,...ld]}var wd=50;function QC(t){Number.isFinite(t)&&t>0&&(wd=t)}function cd(t=In()){if(process.env.NEX_DISABLE_TOOL_BUDGET==="1")return 1/0;let e=process.env.NEX_MAX_TOOL_CALLS;if(e){let n=parseInt(e,10);if(Number.isFinite(n)&&n>0)return n}return t==="local"?5:30}function fw(t,e){return`[SYSTEM STOP] Tool-call budget reached (${t}/${e}). You MUST stop calling tools now. Provide your final answer based only on the information already in the conversation. If the task cannot be completed from the gathered evidence, state the blocker plainly and do not invent facts.`}var Qa=()=>null;function eA(t){Qa=t}var Kr=null,_d=null,Ho=null,Go="",Yo=0,$d="",kd=0,el=new Map,tA=1e4,nA=6e3,sA=/\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 oA(t){return!t||typeof t!="string"?t:t.replace(sA,(e,n)=>`${n}=***REDACTED***`)}var rA=7e3,iA=4e3;function aA(t,e=null){let n=oA(t),o=lC(n),s=e==="read_file"?rA:tA,r=e==="read_file"?iA:nA;if(o>s)try{let{compressToolResult:i}=Pn();return i(n,r)}catch{return n}return n}function Cw(t){try{let{getActiveModel:e}=kt(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(el.has(o))return el.get(o);let s=lw(t);return el.set(o,s),s}catch{return lw(t)}}function lA(){el.clear()}function cA(t,e){let n=new Set(e);return(t||[]).some(o=>o.role!=="assistant"?!1:Array.isArray(o.tool_calls)?o.tool_calls.some(s=>n.has(s?.function?.name||s?.name)):Array.isArray(o.content)?o.content.some(s=>s?.type==="tool_use"&&n.has(s?.name)):!1)}var Vr={hash:null,ts:0},uA=3e4;async function Aw(){if(Vr.hash&&Date.now()-Vr.ts<uA)return Vr.hash;try{let t=require("fs").promises,e=require("path"),n=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(n.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=vr(),a=i();a&&s.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(tt.existsSync(i)){let a=await t.stat(i);s.push(`brain:${a.mtimeMs}`)}}catch{}let r=s.join("|");return Vr={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function xd(){Kr=null,_d=null,Vr={hash:null,ts:0},Ho=null}var dA=new Set(["spawn_agents"]),ud=10,dd=10,Va=5,pw=6e4,fd=12e4,fA=process.env.NEX_STALE_AUTO_SWITCH!=="0";function pA(t){try{let e=require("fs"),n=require("path"),o=n.join(process.cwd(),".nex","plans");e.existsSync(o)||e.mkdirSync(o,{recursive:!0});let s=n.join(o,"current-plan.md");e.writeFileSync(s,t,"utf-8")}catch{}}TC(t=>{vC(t,"allow"),EC(),console.log(`${p.green} \u2713 ${t}: always allow${p.reset}`)});async function hA(t){let e=t.function.name,n=e;if(typeof e=="string"&&e.includes(".")){let d=e.split(".").pop(),f={exec:"bash",find:"search_files",search:"search_files",grep_search:"grep",list:"list_directory",print_tree:"list_directory",read:"read_file",tree:"list_directory"};Bt().some(m=>m.function.name===d)?n=d:f[d]&&(n=f[d])}let o=rC(t.function.arguments),s=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!o){let f=Bt().find(m=>m.function.name===n),h=f?JSON.stringify(f.function.parameters,null,2):"unknown";return P(`${p.yellow} \u26A0 ${n}: malformed arguments, sending schema hint${p.reset}`),{callId:s,fnName:n,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
945
945
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
946
946
 
947
947
  Expected JSON schema for "${n}":
948
948
  ${h}
949
949
 
950
- Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:s}}}if(o&&typeof o.path=="string")try{let d=require("os"),f=ot.resolve(process.cwd(),o.path.replace(/^~/,d.homedir())),h=o.path;o.path=ot.relative(process.cwd(),f)||".",Object.defineProperty(o,"_originalPath",{value:h,enumerable:!1})}catch(d){console.error("path resolution failed:",d.message)}o&&(n==="search_files"||n==="grep")&&typeof o.pattern!="string"&&(typeof o.query=="string"?o.pattern=o.query:typeof o.search=="string"&&(o.pattern=o.search));let r=DC(n,o);if(!r.valid){P(`${p.yellow} \u26A0 ${n}: ${r.error.split(`
951
- `)[0]}${p.reset}`);let d=(pw.get(n)||0)+1;pw.set(n,d);let f=d>=2?`${r.error}
950
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:s}}}if(o&&typeof o.path=="string")try{let d=require("os"),f=ot.resolve(process.cwd(),o.path.replace(/^~/,d.homedir())),h=o.path;o.path=ot.relative(process.cwd(),f)||".",Object.defineProperty(o,"_originalPath",{value:h,enumerable:!1})}catch(d){console.error("path resolution failed:",d.message)}o&&(n==="search_files"||n==="grep")&&typeof o.pattern!="string"&&(typeof o.query=="string"?o.pattern=o.query:typeof o.search=="string"&&(o.pattern=o.search));let r=BC(n,o);if(!r.valid){P(`${p.yellow} \u26A0 ${n}: ${r.error.split(`
951
+ `)[0]}${p.reset}`);let d=(mw.get(n)||0)+1;mw.set(n,d);let f=d>=2?`${r.error}
952
952
 
953
- [SYSTEM: This is argument error #${d} for "${n}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:r.error;return{callId:s,fnName:n,args:o,canExecute:!1,errorResult:{role:"tool",content:f,tool_call_id:s}}}let i=r.corrected||o;if(r.corrected){let d=Object.keys(o),f=Object.keys(r.corrected),h=d.filter(m=>!f.includes(m));h.length&&console.log(`${p.dim} \u2713 ${n}: corrected args (${h.join(", ")})${p.reset}`)}if(Qs()&&!_w.has(n))return console.log(`${p.yellow} \u2717 ${n}: blocked in plan mode${p.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${n}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:s}};let a=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),l=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),c=n==="spawn_agents"&&Array.isArray(i?.agents)&&i.agents.length>0&&i.agents.every(d=>d.background===!0);if(ge&&xe==="plan"&&!a.has(n)&&!n.startsWith("skill_")&&!c)return ps++,zo=n,P(`${p.yellow} \u2717 ${n}: blocked in plan phase (read-only, block #${ps})${p.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${n}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:s}};if(ge&&xe==="verify"&&!l.has(n)&&!n.startsWith("skill_"))return P(`${p.yellow} \u2717 ${n}: blocked in verify phase (read + bash only)${p.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${n}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:s}};let u=$C(n);if(u==="deny")return console.log(`${p.red} \u2717 ${n}: denied by permissions${p.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${n}' is blocked by permissions`,tool_call_id:s}};if(u==="ask"){let d=` Allow ${n}?`;return n==="bash"&&i.command&&(d=` bash: \`${i.command.substring(0,80)}${i.command.length>80?"\u2026":""}\`?`),await ww(d,{toolName:n})?{callId:s,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:s,fnName:n,args:i,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${n}`,tool_call_id:s}}}return{callId:s,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function fA(t,e,n={}){let o=await IC(t,e);if(o!==null)return o;let s=await PC(t,e);return s!==null?s:Ld(t,e,n)}function pA(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 dd(t,e=!1){e||console.log(Q1(t.fnName,t.args));let n=ew("pre-tool",{tool_name:t.fnName}),o=n.results;if(n.blocked){let _=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${n.blockReason}`;e||console.log(`${p.yellow} [hook pre-tool] BLOCKED: ${n.blockReason}${p.reset}`);let k=ri(t.fnName,t.args,_,!0);return e||console.log(k),{msg:{role:"tool",content:_,tool_call_id:t.callId},summary:k}}if(!e&&o.length>0)for(let _ of o)_.success?console.log(`${p.dim} [hook pre-tool] ${_.command} \u2192 ${_.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook pre-tool] ${_.command} \u2192 ERROR: ${_.error}${p.reset}`);rt?.onToolStart&&rt.onToolStart(t.fnName,t.args);let s=await fA(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;s&&typeof s=="object"&&s.text?(i=String(s.text),Array.isArray(s.images)&&s.images.length>0&&(r=s.images)):i=String(s??"");let a=i.length>5e4?i.substring(0,5e4)+`
953
+ [SYSTEM: This is argument error #${d} for "${n}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:r.error;return{callId:s,fnName:n,args:o,canExecute:!1,errorResult:{role:"tool",content:f,tool_call_id:s}}}let i=r.corrected||o;if(r.corrected){let d=Object.keys(o),f=Object.keys(r.corrected),h=d.filter(m=>!f.includes(m));h.length&&console.log(`${p.dim} \u2713 ${n}: corrected args (${h.join(", ")})${p.reset}`)}if(eo()&&!xw.has(n))return console.log(`${p.yellow} \u2717 ${n}: blocked in plan mode${p.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${n}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:s}};let a=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),l=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),c=n==="spawn_agents"&&Array.isArray(i?.agents)&&i.agents.length>0&&i.agents.every(d=>d.background===!0);if(he&&xe==="plan"&&!a.has(n)&&!n.startsWith("skill_")&&!c)return ps++,Vo=n,P(`${p.yellow} \u2717 ${n}: blocked in plan phase (read-only, block #${ps})${p.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${n}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:s}};if(he&&xe==="verify"&&!l.has(n)&&!n.startsWith("skill_"))return P(`${p.yellow} \u2717 ${n}: blocked in verify phase (read + bash only)${p.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${n}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:s}};let u=SC(n);if(u==="deny")return console.log(`${p.red} \u2717 ${n}: denied by permissions${p.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${n}' is blocked by permissions`,tool_call_id:s}};if(u==="ask"){let d=` Allow ${n}?`;return n==="bash"&&i.command&&(d=` bash: \`${i.command.substring(0,80)}${i.command.length>80?"\u2026":""}\`?`),await kw(d,{toolName:n})?{callId:s,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:s,fnName:n,args:i,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${n}`,tool_call_id:s}}}return{callId:s,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function mA(t,e,n={}){let o=await qC(t,e);if(o!==null)return o;let s=await LC(t,e);return s!==null?s:jd(t,e,n)}function gA(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 pd(t,e=!1){e||console.log(nC(t.fnName,t.args));let n=nw("pre-tool",{tool_name:t.fnName}),o=n.results;if(n.blocked){let _=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${n.blockReason}`;e||console.log(`${p.yellow} [hook pre-tool] BLOCKED: ${n.blockReason}${p.reset}`);let k=ii(t.fnName,t.args,_,!0);return e||console.log(k),{msg:{role:"tool",content:_,tool_call_id:t.callId},summary:k}}if(!e&&o.length>0)for(let _ of o)_.success?console.log(`${p.dim} [hook pre-tool] ${_.command} \u2192 ${_.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook pre-tool] ${_.command} \u2192 ERROR: ${_.error}${p.reset}`);rt?.onToolStart&&rt.onToolStart(t.fnName,t.args);let s=await mA(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;s&&typeof s=="object"&&s.text?(i=String(s.text),Array.isArray(s.images)&&s.images.length>0&&(r=s.images)):i=String(s??"");let a=i.length>5e4?i.substring(0,5e4)+`
954
954
  ...(truncated ${i.length-5e4} chars)`:i,l=a.split(`
955
- `)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=ri(t.fnName,t.args,a,c);e||console.log(u),rt?.onToolEnd&&rt.onToolEnd(t.fnName,u,!c);let f=ew("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let _ of f)_.success?console.log(`${p.dim} [hook post-tool] ${_.command} \u2192 ${_.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook post-tool] ${_.command} \u2192 ERROR: ${_.error}${p.reset}`);let m=oA(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let _=t.args.command.trim();!/cat\s*>|<</.test(_)&&/\bcat\s+\S/.test(_)?m+=`
955
+ `)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=ii(t.fnName,t.args,a,c);e||console.log(u),rt?.onToolEnd&&rt.onToolEnd(t.fnName,u,!c);let f=nw("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let _ of f)_.success?console.log(`${p.dim} [hook post-tool] ${_.command} \u2192 ${_.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook post-tool] ${_.command} \u2192 ERROR: ${_.error}${p.reset}`);let m=aA(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let _=t.args.command.trim();!/cat\s*>|<</.test(_)&&/\bcat\s+\S/.test(_)?m+=`
956
956
  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+=`
957
957
  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+=`
958
- 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 hA=[{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 fd(t){for(let{re:e,label:n}of hA){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function mA(t,e=!1,n={}){let o=new Array(t.length),s=[],r=[],i=null;if(e&&!n.skipSpinner){let l=t.filter(c=>c.canExecute);if(l.length>0){let c;if(l.length===1){let u=l[0],d=pA(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 Bo(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await dd(t[l],e);o[l]=c,s.push(u)}else{let l=r.map(u=>dd(t[u],e)),c=await Promise.all(l);for(let u=0;u<r.length;u++)o[r[u]]=c[u].msg,s.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,s.push(ri(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(lA.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await dd(c,e);o[l]=u,s.push(d)}else r.push(l)}if(await a(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let l of s)console.log(l);return{results:o,summaries:s}}var S=[],fw=300,Rw=900*1e3;function Mn(t,e){let n=t.get(e);return n?Date.now()-n.ts>Rw?(t.delete(e),0):n.count:0}function Ks(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=Rw?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function pd(t,e,n){t.set(e,{count:n,ts:Date.now()})}var Id=new Map,Cw=new Map,Qa=new Map,ei=new Set,Aw=new Map,el=new Map,ti=new Set,jn=new Map,zn=new Map,ni=new Map,Mt=new Map,eo=new Map,pw=new Map,pl=new Map,kd=new Map,on=0,Xr=0,tl=0,xd="",nl=0,Kt=!1,Va=0,sl=0,Vs=-1,Sd=!1,ol=0,rl=!1,ln=0,cn=!1,_n=0,un=0,Et=!1,Ft="",Jr=0,cs=0,il="",Xs=0,Js=0,al="",Hr=0,rn=!1,vd=!1,ii=new Map,ai=new Set,Zr=null,Gr=!1,Yr=0,hw=!1,Ae=null,an=!1,jd=null,Ed=!1,Td=!1,ll=!1,ds="",Zs="",Qr="",xe="plan",hl=0,ge=!1,ps=0,zo=null,xn=null,Rd=null,Cd=null,Go=0,Ko=0,Vo=0,si=0,Vn=!1,Dn=0,to=null,no=[],us=new Set,pt=!1,Ut=0,li=0,dn=new Set,Vt=!1,Dd="",cl=!1,fs=0,Xo=0,ml=8,Yo=10,gA=new Set(["read_file","grep","search_files","glob","list_directory","find_files"]),mw=null;function yA(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function Ad(t){let e=String(t||"");if(!e||ui(e)||oi(e).length!==1)return!1;let o=/\b(create|write|add|make|build|scaffold)\b[\s\S]{0,160}\b(refactor|rename|improve|update|change|edit)\b/i.test(e)||/\b(refactor|update|change|edit)\b[\s\S]{0,160}\b(create|write|add|make|build|scaffold)\b/i.test(e),s=/\b(create|write|add|make|build|refactor|update|change|edit)\b[\s\S]{0,160}\bfile\b/i.test(e);return o||s}function ui(t){let e=String(t||"");return e?yl(e)?!0:/\bAutomation(?:\s+ID)?\b|\bLast run:\b/i.test(e)||/\b(work from main|at the start|current branch|git status|worktree|dirty|unrelated changes?|pull\/rebase|before changing|before editing)\b/i.test(e)||/\b(if|when)\b[\s\S]{0,120}\b(stop|abort|do not|don't|without editing|without committing|without pushing)\b/i.test(e)||/\b(backlog|primary backlog|pick (?:at most )?one|at most one|choose (?:one|a task)|priority order|verification is mandatory|stage only|commit and push|push main|push devel)\b/i.test(e):!1}function Ow(t){let e=String(t||"");return!e||!ui(e)?!1:/\b(primary backlog|backlog|pick at most one|at most one|priority order|choose (?:one|a task)|one tightly scoped improvement)\b/i.test(e)}function Kn({blocked:t=!1}={}){return[t?"[SYSTEM BLOCKED] Bounded backlog planning has enough evidence. Do not read or search more files.":"[SYSTEM] Bounded backlog automation plan template.","Before deciding, inspect the concrete backlog/reference paths named by the user prompt. Prefer read_file on those paths over generic searches for words like `backlog`, `TODO`, or `FIXME`.","Ground the selected improvement in those files and the current project. Do not invent generic React bugs, placeholder files, or example components that were not found in the evidence.","Write the plan now using exactly these label lines. Do not use markdown headings for these labels.","Selected improvement: name one scoped task, or write `no safe task found`.","Selection rationale: why this task is the safest/highest-value choice from the backlog evidence.","Files: list the files you will change and any read-only reference files.","Implementation outline: concrete edit steps, kept to this one task.","Verification plan: exact focused commands or reads that will prove the change.","Browser/UI applicability: say required, not required, or blocked, with the reason.",`After ${ml}-${Yo} read/search tools, you must choose one scoped task or stop cleanly with \`no safe task found\`; do not keep exploring.`].join(`
959
- `)}function Jo(t){return String(t||"").replace(/^\.\/+/,"").replace(/\/+$/,"")}function bA(t,e={}){if(!pt||dn.size===0)return!0;let n=[];if(e.path&&n.push(e.path),e.pattern&&/[/.]/.test(String(e.pattern))&&n.push(e.pattern),e.include&&/[/.]/.test(String(e.include))&&n.push(e.include),e.file_pattern&&/[/.]/.test(String(e.file_pattern))&&n.push(e.file_pattern),n.length===0)return!1;let o=n.map(Jo);for(let s of dn){let r=Jo(s);if(r&&o.some(i=>i===r||i.endsWith(`/${r}`)||r.endsWith(`/${i}`)))return!0}return t==="grep"||t==="search_files"?o.some(s=>[...dn].some(r=>s.includes(Jo(r)))):!1}function Pw(t){if(!pt)return!1;let e=String(t||"");if(!e.trim())return!1;let n=String(Dd||"");if(/\b(stale data|list component|ListComponent)\b/i.test(e)&&!/\b(stale data|list component|ListComponent)\b/i.test(n))return!0;let s=new Set,r=/[`'"]?((?:[A-Za-z0-9_.@-]+\/)+[A-Za-z0-9_.@-]+\.(?:tsx|jsx|mjs|cjs|mdx|json|scss|html|yaml|yml|css|ts|js|md))[`'"]?/g,i;for(;i=r.exec(e);)s.add(Jo(i[1]));let a=0,l=0;for(let c of s){if(dn.has(c))continue;a++;let u=ot.resolve(process.cwd(),c);tt.existsSync(u)&&l++}return a>0&&l===0}function ul(t){let e=String(t||"");return!e.trim()||Pw(e)||Nw(e)?!1:/\bno safe task found\b/i.test(e)?!0:/\bselected improvement\s*:/i.test(e)&&/\bselection rationale\s*:/i.test(e)&&/\bfiles\s*:/i.test(e)&&/\bverification plan\s*:/i.test(e)}function Nw(t){let e=String(t||"");return e.trim()?/(?:^|\n)\s*#{1,6}\s*selected improvement\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*selection rationale\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*files\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*verification plan\b/i.test(e):!1}function wA(t){let e=String(t||"");return e.trim()?/\b(need|must|will|should|let'?s|attempt|going)\b.{0,80}\b(call|issue|use|run|read)\b.{0,80}\b(read_file|tool call|tool_calls?|JSON calls?)\b/i.test(e)||/\{\s*["']tool["']\s*:\s*["'](?:read_file|grep|search_files|glob)["']/i.test(e):!1}function zr(t,e){return pt&&Vt&&(Xo>0||Mt.size>0)&&t.size===0&&e===0}function Mw(t){let e=String(t||"");if(!/\bno safe task found\b/i.test(e)||/\bexample only\b|\bnot applicable\b/i.test(e)||!(/\b(because|reason|blocked|blocker|cannot|can't|unable|failed|unavailable|permission denied|missing|not found|no readable|dirty worktree|wrong branch|merge conflict|precheck blocked|preflight failed|ambiguous|unrelated|manual user work|no safe worthwhile improvement)\b/i.test(e)&&e.trim().length>60))return!1;let o=dn.size===0||li>0;return Ut>=ml?o:/\b(blocked|blocker|cannot|can't|unable|failed|unavailable|permission denied|missing|not found|no readable|dirty worktree|wrong branch|merge conflict|precheck blocked|preflight failed)\b/i.test(e)&&/\b(because|reason|preflight|worktree|branch|git|permission|missing|unavailable|inspect|read|search)\b/i.test(e)}function Od(t){let e=String(t||"");if(!e.trim()||/\bexample only\b/i.test(e))return!1;let n=/\bpreflight\s*:/i.test(e),o=/\bpreflight output\s*:/i.test(e),s=/\bbranch\s*:/i.test(e),r=/\b(chosen task|selected improvement)\s*:/i.test(e)||/\bno safe task found\b/i.test(e),i=/\bfiles changed\s*:/i.test(e),a=/\bverification\s*:/i.test(e),l=/\bcommit\s*:/i.test(e),c=/\bpush\s*:/i.test(e),u=/\bfinal git status\s*:/i.test(e);return!(n&&o&&s&&r&&i&&a&&l&&c&&u)||Ae?.ran&&(/\bpreflight\s*:\s*(?:not performed|not run|not applicable|unknown)\b/i.test(e)||/\bpreflight output\s*:\s*(?:not performed|not run|not applicable|unknown|\(missing preflight output\))\b/i.test(e)||/\bbranch\s*:\s*(?:not applicable|unknown)\b/i.test(e))?!1:/\bno safe task found\b/i.test(e)?Mw(e):!0}function yl(t){let e=String(t||"");if(!e)return null;let n=[/\bwork\s+(?:from|on)\s+(?:the\s+)?(?:branch\s+)?[`'"]?([A-Za-z0-9._/-]+)[`'"]?\s+only\b/i,/\bwork\s+(?:from|on)\s+(?:the\s+)?[`'"]?([A-Za-z0-9._/-]+)[`'"]?\s+branch\s+only\b/i];for(let o of n){let s=e.match(o);if(!s)continue;let r=String(s[1]||"").trim();if(r)return r}return null}function _A(t){let e=String(t||"").trim();if(!e)return{branch:null,dirty:null,changedFiles:[]};if(/^fatal:/i.test(e))return{branch:null,dirty:null,changedFiles:[]};let n=e.split(`
960
- `).map(l=>l.replace(/\r$/,"")),o=n.find(l=>l.startsWith("## "))||n[0]||"",s=o.startsWith("## ")?o.slice(3).trim():o.trim(),r=s?s.split("...")[0].trim().split(/\s+/)[0]:null,i=n.filter(l=>!l.startsWith("## ")&&l.trim()!==""),a=[];for(let l of i){let c=l.match(/^[ MADRCU?!]{1,2}\s+(.*)$/);if(!c)continue;let u=(c[1]||"").trim();if(!u)continue;let d=u.includes(" -> ")?u.split(" -> ").pop():u;d&&a.push(d)}return{branch:r||null,dirty:a.length>0,changedFiles:a}}function $A(t){let e=String(t||"");return!e||!ui(e)?!1:yl(e)?!0:/\b(git status|current branch|worktree|dirty|pull\/rebase|rebase|commit|push)\b/i.test(e)}function kA(t,e=2500){let n=String(t??"");return n.trim()?n.length<=e?n:n.slice(0,e)+`
961
- ...(truncated ${n.length-e} chars)`:"(no output)"}async function xA(t,e,n){if(Ae?.ran)return Ae;let o=jd||yl(t),s="git status --short --branch",r="preflight-git-status";Ae={required:!0,ran:!0,ok:!1,command:s,requiredBranch:o,branch:null,dirty:null,changedFiles:[],raw:""};let i="",a=!1;try{let _={role:"assistant",content:"",tool_calls:[{id:r,type:"function",function:{name:"bash",arguments:JSON.stringify({command:s})}}]};n.push(_),e.push(_),rt?.onToolStart&&(rt.onToolStart("bash",{command:s}),a=!0),i=await Ld("bash",{command:s},{silent:!0,autoConfirm:!0})}catch(_){i=`ERROR: failed to run preflight: ${_?.message||String(_)}`}let l=String(i??"");if(a&&rt?.onToolEnd){let _=l.length>5e4?l.substring(0,5e4)+`
958
+ 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 yA=[{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 hd(t){for(let{re:e,label:n}of yA){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function bA(t,e=!1,n={}){let o=new Array(t.length),s=[],r=[],i=null;if(e&&!n.skipSpinner){let l=t.filter(c=>c.canExecute);if(l.length>0){let c;if(l.length===1){let u=l[0],d=gA(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 Wo(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await pd(t[l],e);o[l]=c,s.push(u)}else{let l=r.map(u=>pd(t[u],e)),c=await Promise.all(l);for(let u=0;u<r.length;u++)o[r[u]]=c[u].msg,s.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,s.push(ii(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(dA.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await pd(c,e);o[l]=u,s.push(d)}else r.push(l)}if(await a(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let l of s)console.log(l);return{results:o,summaries:s}}var S=[],hw=300,Ow=900*1e3;function Mn(t,e){let n=t.get(e);return n?Date.now()-n.ts>Ow?(t.delete(e),0):n.count:0}function Vs(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=Ow?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function md(t,e,n){t.set(e,{count:n,ts:Date.now()})}var Dd=new Map,Pw=new Map,tl=new Map,ei=new Set,Nw=new Map,nl=new Map,ti=new Set,jn=new Map,zn=new Map,ni=new Map,Mt=new Map,to=new Map,mw=new Map,ml=new Map,Sd=new Map,rn=0,Xr=0,sl=0,vd="",ol=0,Xt=!1,Xa=0,rl=0,Xs=-1,Ed=!1,il=0,al=!1,cn=0,un=!1,_n=0,dn=0,Et=!1,Ft="",Jr=0,cs=0,ll="",Js=0,Zs=0,cl="",Gr=0,an=!1,Td=!1,ai=new Map,li=new Set,Zr=null,Yr=!1,zr=0,gw=!1,Pe=null,ln=!1,qd=null,Rd=!1,Cd=!1,ul=!1,ds="",Qs="",Qr="",xe="plan",gl=0,he=!1,ps=0,Vo=null,xn=null,Ad=null,Od=null,zo=0,Xo=0,Jo=0,si=0,Vn=!1,Dn=0,no=null,so=[],us=new Set,ct=!1,Ut=0,ci=0,Ht=new Set,Wt=!1,Fd="",dl=!1,fs=0,Zo=0,oi=0,yl=8,Ko=10,yw=3,wA=new Set(["read_file","grep","search_files","glob","list_directory","find_files"]),bw=null;function _A(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function Pd(t){let e=String(t||"");if(!e||di(e)||ri(e).length!==1)return!1;let o=/\b(create|write|add|make|build|scaffold)\b[\s\S]{0,160}\b(refactor|rename|improve|update|change|edit)\b/i.test(e)||/\b(refactor|update|change|edit)\b[\s\S]{0,160}\b(create|write|add|make|build|scaffold)\b/i.test(e),s=/\b(create|write|add|make|build|refactor|update|change|edit)\b[\s\S]{0,160}\bfile\b/i.test(e);return o||s}function di(t){let e=String(t||"");return e?wl(e)?!0:/\bAutomation(?:\s+ID)?\b|\bLast run:\b/i.test(e)||/\b(work from main|at the start|current branch|git status|worktree|dirty|unrelated changes?|pull\/rebase|before changing|before editing)\b/i.test(e)||/\b(if|when)\b[\s\S]{0,120}\b(stop|abort|do not|don't|without editing|without committing|without pushing)\b/i.test(e)||/\b(backlog|primary backlog|pick (?:at most )?one|at most one|choose (?:one|a task)|priority order|verification is mandatory|stage only|commit and push|push main|push devel)\b/i.test(e):!1}function Mw(t){let e=String(t||"");return!e||!di(e)?!1:/\b(primary backlog|backlog|pick at most one|at most one|priority order|choose (?:one|a task)|one tightly scoped improvement)\b/i.test(e)}function Kn({blocked:t=!1}={}){return[t?"[SYSTEM BLOCKED] Bounded backlog planning has enough evidence. Do not read or search more files.":"[SYSTEM] Bounded backlog automation plan template.","Before deciding, inspect the concrete backlog/reference paths named by the user prompt. Prefer read_file on those paths over generic searches for words like `backlog`, `TODO`, or `FIXME`.","Ground the selected improvement in those files and the current project. Do not invent generic React bugs, placeholder files, or example components that were not found in the evidence.","Write the plan now using exactly these label lines. Do not use markdown headings for these labels.","Selected improvement: name one scoped task, or write `no safe task found`.","Selection rationale: why this task is the safest/highest-value choice from the backlog evidence.","Files: list the files you will change and any read-only reference files.","Implementation outline: concrete edit steps, kept to this one task.","Verification plan: exact focused commands or reads that will prove the change.","Browser/UI applicability: say required, not required, or blocked, with the reason.",`After ${yl}-${Ko} read/search tools, you must choose one scoped task or stop cleanly with \`no safe task found\`; do not keep exploring.`].join(`
959
+ `)}function hs(t){return String(t||"").replace(/^\.\/+/,"").replace(/\/+$/,"")}function $A(t,e={}){if(!ct||Ht.size===0)return!0;let n=[];if(e.path&&n.push(e.path),e.pattern&&/[/.]/.test(String(e.pattern))&&n.push(e.pattern),e.include&&/[/.]/.test(String(e.include))&&n.push(e.include),e.file_pattern&&/[/.]/.test(String(e.file_pattern))&&n.push(e.file_pattern),n.length===0)return!1;let o=n.map(hs);for(let s of Ht){let r=hs(s);if(r&&o.some(i=>i===r||i.endsWith(`/${r}`)||r.endsWith(`/${i}`)))return!0}return t==="grep"||t==="search_files"?o.some(s=>[...Ht].some(r=>s.includes(hs(r)))):!1}function kA(t,e={}){if(t!=="grep"&&t!=="search_files"&&t!=="glob"&&t!=="list_directory"&&t!=="find_files")return!1;let n=hs(e.path||e.cwd||"");if(n&&Ht.has(n))return!1;let o=String(e.pattern||e.glob||e.query||e.search||""),s=String(e.include||e.file_pattern||""),r=`${n} ${o} ${s}`;return![...Ht].some(i=>{let a=hs(i);return a&&r.includes(a)})}function Lw(t){if(!ct)return!1;let e=String(t||"");if(!e.trim())return!1;let n=String(Fd||"");if(/\b(stale data|list component|ListComponent)\b/i.test(e)&&!/\b(stale data|list component|ListComponent)\b/i.test(n))return!0;let s=new Set,r=/[`'"]?((?:[A-Za-z0-9_.@-]+\/)+[A-Za-z0-9_.@-]+\.(?:tsx|jsx|mjs|cjs|mdx|json|scss|html|yaml|yml|css|ts|js|md))[`'"]?/g,i;for(;i=r.exec(e);)s.add(hs(i[1]));let a=0,l=0;for(let c of s){if(Ht.has(c))continue;a++;let u=ot.resolve(process.cwd(),c);tt.existsSync(u)&&l++}return!1}function Ja(t,e){let n=String(e||"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:^|\\n)\\s*(?:[-*]\\s*)?(?:\\*\\*)?${n}\\s*:(?:\\*\\*)?`,"i").test(String(t||""))}function fl(t){let e=String(t||"");return!e.trim()||Lw(e)||Iw(e)?!1:/\bno safe task found\b/i.test(e)?!0:Ja(e,"Selected improvement")&&Ja(e,"Selection rationale")&&Ja(e,"Files")&&Ja(e,"Verification plan")}function Iw(t){let e=String(t||"");return e.trim()?/(?:^|\n)\s*#{1,6}\s*selected improvement\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*selection rationale\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*files\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*verification plan\b/i.test(e):!1}function xA(t){let e=String(t||"");return e.trim()?/\b(need|must|will|should|let'?s|attempt|going)\b.{0,80}\b(call|issue|use|run|read)\b.{0,80}\b(read_file|tool call|tool_calls?|JSON calls?)\b/i.test(e)||/\{\s*["']tool["']\s*:\s*["'](?:read_file|grep|search_files|glob)["']/i.test(e):!1}function Fo(t,e){return ct&&Wt&&(Zo>0||Mt.size>0)&&t.size===0&&e===0}function jw(t){let e=String(t||"");if(!/\bno safe task found\b/i.test(e)||/\bexample only\b|\bnot applicable\b/i.test(e)||!(/\b(because|reason|blocked|blocker|cannot|can't|unable|failed|unavailable|permission denied|missing|not found|no readable|dirty worktree|wrong branch|merge conflict|precheck blocked|preflight failed|ambiguous|unrelated|manual user work|no safe worthwhile improvement)\b/i.test(e)&&e.trim().length>60))return!1;let o=Ht.size===0||ci>0;return Ut>=yl?o:/\b(blocked|blocker|cannot|can't|unable|failed|unavailable|permission denied|missing|not found|no readable|dirty worktree|wrong branch|merge conflict|precheck blocked|preflight failed)\b/i.test(e)&&/\b(because|reason|preflight|worktree|branch|git|permission|missing|unavailable|inspect|read|search)\b/i.test(e)}function Nd(t){let e=String(t||"");if(!e.trim()||/\bexample only\b/i.test(e))return!1;let n=/\bpreflight\s*:/i.test(e),o=/\bpreflight output\s*:/i.test(e),s=/\bbranch\s*:/i.test(e),r=/\b(chosen task|selected improvement)\s*:/i.test(e)||/\bno safe task found\b/i.test(e),i=/\bfiles changed\s*:/i.test(e),a=/\bverification\s*:/i.test(e),l=/\bcommit\s*:/i.test(e),c=/\bpush\s*:/i.test(e),u=/\bfinal git status\s*:/i.test(e);return!(n&&o&&s&&r&&i&&a&&l&&c&&u)||Pe?.ran&&(/\bpreflight\s*:\s*(?:not performed|not run|not applicable|unknown)\b/i.test(e)||/\bpreflight output\s*:\s*(?:not performed|not run|not applicable|unknown|\(missing preflight output\))\b/i.test(e)||/\bbranch\s*:\s*(?:not applicable|unknown)\b/i.test(e))?!1:/\bno safe task found\b/i.test(e)?jw(e):!0}function wl(t){let e=String(t||"");if(!e)return null;let n=[/\bwork\s+(?:from|on)\s+(?:the\s+)?(?:branch\s+)?[`'"]?([A-Za-z0-9._/-]+)[`'"]?\s+only\b/i,/\bwork\s+(?:from|on)\s+(?:the\s+)?[`'"]?([A-Za-z0-9._/-]+)[`'"]?\s+branch\s+only\b/i];for(let o of n){let s=e.match(o);if(!s)continue;let r=String(s[1]||"").trim();if(r)return r}return null}function SA(t){let e=String(t||"").trim();if(!e)return{branch:null,dirty:null,changedFiles:[]};if(/^fatal:/i.test(e))return{branch:null,dirty:null,changedFiles:[]};let n=e.split(`
960
+ `).map(l=>l.replace(/\r$/,"")),o=n.find(l=>l.startsWith("## "))||n[0]||"",s=o.startsWith("## ")?o.slice(3).trim():o.trim(),r=s?s.split("...")[0].trim().split(/\s+/)[0]:null,i=n.filter(l=>!l.startsWith("## ")&&l.trim()!==""),a=[];for(let l of i){let c=l.match(/^[ MADRCU?!]{1,2}\s+(.*)$/);if(!c)continue;let u=(c[1]||"").trim();if(!u)continue;let d=u.includes(" -> ")?u.split(" -> ").pop():u;d&&a.push(d)}return{branch:r||null,dirty:a.length>0,changedFiles:a}}function vA(t){let e=String(t||"");return!e||!di(e)?!1:wl(e)?!0:/\b(git status|current branch|worktree|dirty|pull\/rebase|rebase|commit|push)\b/i.test(e)}function EA(t,e=2500){let n=String(t??"");return n.trim()?n.length<=e?n:n.slice(0,e)+`
961
+ ...(truncated ${n.length-e} chars)`:"(no output)"}async function TA(t,e,n){if(Pe?.ran)return Pe;let o=qd||wl(t),s="git status --short --branch",r="preflight-git-status";Pe={required:!0,ran:!0,ok:!1,command:s,requiredBranch:o,branch:null,dirty:null,changedFiles:[],raw:""};let i="",a=!1;try{let _={role:"assistant",content:"",tool_calls:[{id:r,type:"function",function:{name:"bash",arguments:JSON.stringify({command:s})}}]};n.push(_),e.push(_),rt?.onToolStart&&(rt.onToolStart("bash",{command:s}),a=!0),i=await jd("bash",{command:s},{silent:!0,autoConfirm:!0})}catch(_){i=`ERROR: failed to run preflight: ${_?.message||String(_)}`}let l=String(i??"");if(a&&rt?.onToolEnd){let _=l.length>5e4?l.substring(0,5e4)+`
962
962
  ...(truncated ${l.length-5e4} chars)`:l,k=_.split(`
963
- `)[0]||"",$=k.startsWith("ERROR")||k.includes("CANCELLED")||k.includes("BLOCKED");try{rt.onToolEnd("bash",ri("bash",{command:s},_,$),!$)}catch{}}let c=l.trim(),u=/^\s*##\s+\S+/.test(c),d=_A(l);Ae.branch=d.branch,Ae.dirty=d.dirty,Ae.changedFiles=d.changedFiles,Ae.raw=l;let f={role:"tool",tool_call_id:r,content:l||"(no output)"};n.push(f),e.push(f);let h=kA(l),m=`[PRECHECK] Preflight ran: \`${s}\`.`+(o?` Required branch: ${o}.`:"")+`
964
-
965
- ${h}`,g={role:"assistant",content:m};if(n.push(g),e.push(g),!Bd)try{rt?.onToken?rt.onToken(m+`
966
- `):console.log(m)}catch{}return!l||/^ERROR:/i.test(l)||/^fatal:/i.test(l)||!u||d.dirty||o&&(!d.branch||d.branch!==o)?(Ae.ok=!1,Ae):(Ae.ok=!0,Ae)}async function SA(t,e){if(Vt||!pt||dn.size===0)return;let n=[...dn].filter(a=>/\.(md|mdx|txt|rst|adoc|tsx?|jsx?)$/i.test(a)).slice(0,4);if(n.length===0)return;Vt=!0;let o="[BACKLOG PREFLIGHT] Reading prompt-named backlog/reference files before planning.",s={role:"assistant",content:o};if(e.push(s),t.push(s),!Bd)try{rt?.onToken?rt.onToken(o+`
967
- `):console.log(o)}catch{}for(let a=0;a<n.length;a++){let l=n[a],c={path:l,line_start:1,line_end:140},u=`bounded-backlog-evidence-${a}`,d={role:"assistant",content:"",tool_calls:[{id:u,type:"function",function:{name:"read_file",arguments:JSON.stringify(c)}}]};e.push(d),t.push(d);let f="";try{rt?.onToolStart&&rt.onToolStart("read_file",c),f=await Ld("read_file",c,{silent:!0,autoConfirm:!0})}catch(g){f=`ERROR: failed to read backlog evidence ${l}: ${g?.message||String(g)}`}let h=String(f||"");if(rt?.onToolEnd){let g=h.split(`
968
- `)[0]||"",_=/^ERROR:/i.test(g)||g.includes("CANCELLED")||g.includes("BLOCKED");try{rt.onToolEnd("read_file",ri("read_file",c,h.slice(0,5e4),_),!_)}catch{}}let m={role:"tool",tool_call_id:u,content:h||"(no output)"};e.push(m),t.push(m),Ut++,li++}let i={role:"user",content:"[BACKLOG PREFLIGHT] The prompt-named backlog/reference files above have already been read. Your next response must be the bounded plan labels exactly as requested (`Selected improvement:`, `Selection rationale:`, `Files:`, `Implementation outline:`, `Verification plan:`, `Browser/UI applicability:`). Do not request or describe more read_file calls."};e.push(i),t.push(i)}function vA(t){let e=String(t||"").trim();return e?/^(hi|hello|hey|yo)\b/i.test(e)||/\b(introduce yourself|who are you|what can you do|tell me about yourself)\b/i.test(e):!1}function Pd(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function oi(t){let n=String(t||"").match(/(?:^|\s)((?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html))\b/gi);return n?[...new Set(n.map(o=>Pd(o)))]:[]}function qo(t,e){t===xd?(nl++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${nl})${p.reset}
969
- `)):(xd=t,nl=1,P(`${e} \u26A0 ${t}${p.reset}`))}var dl=[];function EA(t){dl.push(t.trim())}function TA(){return dl.length===0?null:dl.splice(0,dl.length).join(`
970
- `)}function RA(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,n=e!==null?`
963
+ `)[0]||"",$=k.startsWith("ERROR")||k.includes("CANCELLED")||k.includes("BLOCKED");try{rt.onToolEnd("bash",ii("bash",{command:s},_,$),!$)}catch{}}let c=l.trim(),u=/^\s*##\s+\S+/.test(c),d=SA(l);Pe.branch=d.branch,Pe.dirty=d.dirty,Pe.changedFiles=d.changedFiles,Pe.raw=l;let f={role:"tool",tool_call_id:r,content:l||"(no output)"};n.push(f),e.push(f);let h=EA(l),m=`[PRECHECK] Preflight ran: \`${s}\`.`+(o?` Required branch: ${o}.`:"")+`
964
+
965
+ ${h}`,g={role:"assistant",content:m};if(n.push(g),e.push(g),!Wd)try{rt?.onToken?rt.onToken(m+`
966
+ `):console.log(m)}catch{}return!l||/^ERROR:/i.test(l)||/^fatal:/i.test(l)||!u||d.dirty||o&&(!d.branch||d.branch!==o)?(Pe.ok=!1,Pe):(Pe.ok=!0,Pe)}async function RA(t,e){if(Wt||!ct||Ht.size===0)return;let n=[...Ht].filter(a=>/\.(md|mdx|txt|rst|adoc|tsx?|jsx?)$/i.test(a)).slice(0,4);if(n.length===0)return;Wt=!0;let o="[BACKLOG PREFLIGHT] Reading prompt-named backlog/reference files before planning.",s={role:"assistant",content:o};if(e.push(s),t.push(s),!Wd)try{rt?.onToken?rt.onToken(o+`
967
+ `):console.log(o)}catch{}for(let a=0;a<n.length;a++){let l=n[a],c={path:l,line_start:1,line_end:140},u=`bounded-backlog-evidence-${a}`,d={role:"assistant",content:"",tool_calls:[{id:u,type:"function",function:{name:"read_file",arguments:JSON.stringify(c)}}]};e.push(d),t.push(d);let f="";try{rt?.onToolStart&&rt.onToolStart("read_file",c),f=await jd("read_file",c,{silent:!0,autoConfirm:!0})}catch(g){f=`ERROR: failed to read backlog evidence ${l}: ${g?.message||String(g)}`}let h=String(f||"");if(rt?.onToolEnd){let g=h.split(`
968
+ `)[0]||"",_=/^ERROR:/i.test(g)||g.includes("CANCELLED")||g.includes("BLOCKED");try{rt.onToolEnd("read_file",ii("read_file",c,h.slice(0,5e4),_),!_)}catch{}}let m={role:"tool",tool_call_id:u,content:h||"(no output)"};e.push(m),t.push(m),Ut++,ci++}let i={role:"user",content:"[BACKLOG PREFLIGHT] The prompt-named backlog/reference files above have already been read. Your next response must be the bounded plan labels exactly as requested (`Selected improvement:`, `Selection rationale:`, `Files:`, `Implementation outline:`, `Verification plan:`, `Browser/UI applicability:`). Do not request or describe more read_file calls."};e.push(i),t.push(i)}function CA(t){let e=String(t||"").trim();return e?/^(hi|hello|hey|yo)\b/i.test(e)||/\b(introduce yourself|who are you|what can you do|tell me about yourself)\b/i.test(e):!1}function Md(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function ri(t){let n=String(t||"").match(/(?:^|\s)((?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html))\b/gi);return n?[...new Set(n.map(o=>Md(o)))]:[]}function Bo(t,e){t===vd?(ol++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${ol})${p.reset}
969
+ `)):(vd=t,ol=1,P(`${e} \u26A0 ${t}${p.reset}`))}var pl=[];function AA(t){pl.push(t.trim())}function OA(){return pl.length===0?null:pl.splice(0,pl.length).join(`
970
+ `)}function PA(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,n=e!==null?`
971
971
  Duration: ${e}s`:"",o=typeof t.result.result=="string"?t.result.result.slice(0,4e3):JSON.stringify(t.result.result||"").slice(0,4e3),s=t.result.filesModified&&t.result.filesModified.length>0?`
972
972
  Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
973
973
  Job: ${t.jobId}
974
974
  Task: "${t.agentDef.task}"`+n+`
975
975
  Status: ${t.result.status||"done"}`+s+`
976
- Result: ${o}`}function Xa(t,e){let{getCompletedJobs:n}=Do(),o=n();for(let s of o){let r={role:"user",content:RA(s)};t.push(r),e.push(r);let i=s.result?.status||"done",a=i==="failed"?p.red+" \u2717":p.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${s.agentDef.task.slice(0,50)} \u2014 ${String(s.result?.result||"").slice(0,80)}${p.reset}
977
- `)}}function Lw(t,e){let n=[],o=new Set([...e.keys(),...ei,...ti]);if(!o.size||!t)return n;for(let s of o){let r=s.split("/").pop();if(r&&(t.includes(r)||t.includes(s))){let a=t.split(`
978
- `).find(l=>l.includes(r)||l.includes(s));n.push({file:s,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return n}function CA(t){if(!t||typeof t!="string")return[];let e=t.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g)||[],n=new Set(["the","and","for","with","from","into","that","this","when","then","have","your","just","read","write","edit","file","files","test","tests","verify","phase","implement","summary","report","pass","fail","changes","change","address","original","task","user","request","code","module","function","class"]),o=new Set,s=[];for(let r of e){let i=r.toLowerCase();n.has(i)||o.has(i)||(o.add(i),s.push(r))}return s.sort((r,i)=>i.length-r.length),s.slice(0,6)}function AA(){return tt.existsSync(ot.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":tt.existsSync(ot.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function Ln(t){let e=AA();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 gw(t,e,n){let o=[...t||[]].slice(0,6).join(", ")||"recently modified files",s=(e||[]).slice(0,3),r=(n||[]).slice(0,3),i=[`[SYSTEM] You already changed code in: ${o}.`,"Run one narrow verification step next before more exploration."];return s.length>0&&i.push(`Suggested verification commands: ${s.join(" | ")}`),r.length>0&&i.push(`Likely related tests: ${r.join(", ")}`),i.push("Do not continue broad read/search loops until the latest edit has been checked."),i.join(`
979
- `)}function OA(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)||/\bnode\s+["']?[\w./ -]+\.(?:c?js|mjs)\b/.test(e)}async function Iw(t){let e=CA(t);if(e.length===0)return[];let{searchContentIndex:n}=Rn(),o=[],s=new Set;for(let r of e)try{let i=await n(r,void 0,process.cwd());for(let a of i.slice(0,3)){let l=`${a.file}:${a.name}:${a.line}`;if(!s.has(l)&&(s.add(l),o.push(a),o.length>=5))return o}}catch{}return o}async function jw(t){let e=await Iw(t);if(e.length===0)return"";let{getRelatedFiles:n,findSymbolReferences:o}=Rn(),s=["Likely symbol targets:"];for(let r=0;r<e.length;r++){let i=e[r],a=Math.max(1,i.line-20),l=i.line+40;s.push(`${r+1}. ${i.name} (${i.type}) in ${i.file}:${i.line} -> read_file(path='${i.file}', line_start=${a}, line_end=${l})`);try{let c=await n(i.file,process.cwd(),3);c.length>0&&s.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&&s.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`${s.join(`
976
+ Result: ${o}`}function Za(t,e){let{getCompletedJobs:n}=qo(),o=n();for(let s of o){let r={role:"user",content:PA(s)};t.push(r),e.push(r);let i=s.result?.status||"done",a=i==="failed"?p.red+" \u2717":p.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${s.agentDef.task.slice(0,50)} \u2014 ${String(s.result?.result||"").slice(0,80)}${p.reset}
977
+ `)}}function Dw(t,e){let n=[],o=new Set([...e.keys(),...ei,...ti]);if(!o.size||!t)return n;for(let s of o){let r=s.split("/").pop();if(r&&(t.includes(r)||t.includes(s))){let a=t.split(`
978
+ `).find(l=>l.includes(r)||l.includes(s));n.push({file:s,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return n}function NA(t){if(!t||typeof t!="string")return[];let e=t.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g)||[],n=new Set(["the","and","for","with","from","into","that","this","when","then","have","your","just","read","write","edit","file","files","test","tests","verify","phase","implement","summary","report","pass","fail","changes","change","address","original","task","user","request","code","module","function","class"]),o=new Set,s=[];for(let r of e){let i=r.toLowerCase();n.has(i)||o.has(i)||(o.add(i),s.push(r))}return s.sort((r,i)=>i.length-r.length),s.slice(0,6)}function MA(){return tt.existsSync(ot.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":tt.existsSync(ot.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function Ln(t){let e=MA();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 ww(t,e,n){let o=[...t||[]].slice(0,6).join(", ")||"recently modified files",s=(e||[]).slice(0,3),r=(n||[]).slice(0,3),i=[`[SYSTEM] You already changed code in: ${o}.`,"Run one narrow verification step next before more exploration."];return s.length>0&&i.push(`Suggested verification commands: ${s.join(" | ")}`),r.length>0&&i.push(`Likely related tests: ${r.join(", ")}`),i.push("Do not continue broad read/search loops until the latest edit has been checked."),i.join(`
979
+ `)}function LA(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)||/\bnode\s+["']?[\w./ -]+\.(?:c?js|mjs)\b/.test(e)}async function qw(t){let e=NA(t);if(e.length===0)return[];let{searchContentIndex:n}=Rn(),o=[],s=new Set;for(let r of e)try{let i=await n(r,void 0,process.cwd());for(let a of i.slice(0,3)){let l=`${a.file}:${a.name}:${a.line}`;if(!s.has(l)&&(s.add(l),o.push(a),o.length>=5))return o}}catch{}return o}async function Fw(t){let e=await qw(t);if(e.length===0)return"";let{getRelatedFiles:n,findSymbolReferences:o}=Rn(),s=["Likely symbol targets:"];for(let r=0;r<e.length;r++){let i=e[r],a=Math.max(1,i.line-20),l=i.line+40;s.push(`${r+1}. ${i.name} (${i.type}) in ${i.file}:${i.line} -> read_file(path='${i.file}', line_start=${a}, line_end=${l})`);try{let c=await n(i.file,process.cwd(),3);c.length>0&&s.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&&s.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`${s.join(`
980
980
  `)}
981
981
  Use these exact targeted reads before broader searching.
982
982
 
983
- `}async function ci(t){let{getFileIndex:e}=Rn(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=Rn(),i=e().filter(c=>/^tests?\//.test(c)||/\.test\./.test(c)||/\.spec\./.test(c));if(i.length===0)return[];let a=new Set,l=await n(process.cwd());for(let c of t||[]){let u=String(c),d=ot.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 s(u,process.cwd(),4);for(let g of m){let _=ot.basename(g).replace(/\.[^.]+$/,"");if(!(_.length<3)){for(let k of i)if(k.includes(_)&&a.add(k),a.size>=4)return[...a]}}}catch{}let h=(Array.isArray(l.files?.[u]?.defs)?l.files[u].defs:[]).filter(m=>["function","class","export"].includes(m.type)).map(m=>m.name).filter((m,g,_)=>m&&_.indexOf(m)===g).slice(0,3);for(let m of h)try{let g=await o(m,process.cwd(),{excludeFile:u,limit:8});for(let _ of g)if(i.includes(_.file)&&a.add(_.file),a.size>=4)return[...a]}catch{}}return[...a]}function PA(t,e={}){if(!Array.isArray(t)||t.length===0)return[];let n=t.slice(0,4).join(" "),o=[],s=String(e.test||"");return/vitest/.test(s)||tt.existsSync(ot.join(process.cwd(),"vitest.config.ts"))||tt.existsSync(ot.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${n}`):(/jest/.test(s)||tt.existsSync(ot.join(process.cwd(),"jest.config.js"))||tt.existsSync(ot.join(process.cwd(),"jest.config.cjs"))||tt.existsSync(ot.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${n}`),(tt.existsSync(ot.join(process.cwd(),"pytest.ini"))||tt.existsSync(ot.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 Fo(t,e,n,o){if(!ge)return null;let s=xe;xe=t,hl=0,xn=md(t,to),t==="implement"&&(si=0,pt&&(Xo=0)),t==="verify"&&(Ko=0,Vo=0,Vn=!1,Dn=0),ln=0,cn=!1,_n=0,un=0,eo.clear(),pl.clear(),Id.clear(),ni.clear(),t==="implement"&&(no=Lw(e||"",jn));let r=no.length>0?`
983
+ `}async function ui(t){let{getFileIndex:e}=Rn(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=Rn(),i=e().filter(c=>/^tests?\//.test(c)||/\.test\./.test(c)||/\.spec\./.test(c));if(i.length===0)return[];let a=new Set,l=await n(process.cwd());for(let c of t||[]){let u=String(c),d=ot.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 s(u,process.cwd(),4);for(let g of m){let _=ot.basename(g).replace(/\.[^.]+$/,"");if(!(_.length<3)){for(let k of i)if(k.includes(_)&&a.add(k),a.size>=4)return[...a]}}}catch{}let h=(Array.isArray(l.files?.[u]?.defs)?l.files[u].defs:[]).filter(m=>["function","class","export"].includes(m.type)).map(m=>m.name).filter((m,g,_)=>m&&_.indexOf(m)===g).slice(0,3);for(let m of h)try{let g=await o(m,process.cwd(),{excludeFile:u,limit:8});for(let _ of g)if(i.includes(_.file)&&a.add(_.file),a.size>=4)return[...a]}catch{}}return[...a]}function IA(t,e={}){if(!Array.isArray(t)||t.length===0)return[];let n=t.slice(0,4).join(" "),o=[],s=String(e.test||"");return/vitest/.test(s)||tt.existsSync(ot.join(process.cwd(),"vitest.config.ts"))||tt.existsSync(ot.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${n}`):(/jest/.test(s)||tt.existsSync(ot.join(process.cwd(),"jest.config.js"))||tt.existsSync(ot.join(process.cwd(),"jest.config.cjs"))||tt.existsSync(ot.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${n}`),(tt.existsSync(ot.join(process.cwd(),"pytest.ini"))||tt.existsSync(ot.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 Uo(t,e,n,o){if(!he)return null;let s=xe;xe=t,gl=0,xn=yd(t,no),t==="implement"&&(si=0,ct&&(Zo=0,oi=0)),t==="verify"&&(Xo=0,Jo=0,Vn=!1,Dn=0),cn=0,un=!1,_n=0,dn=0,to.clear(),ml.clear(),Dd.clear(),ni.clear(),t==="implement"&&(so=Dw(e||"",jn));let r=so.length>0?`
984
984
 
985
985
  ACTION ITEMS (execute these in order, do NOT re-read these files):
986
- `+no.map((l,c)=>`${c+1}. ${l.file} \u2014 ${l.action}`).join(`
987
- `):"",i=await jw(t==="verify"?o:e||o||""),a;if(t==="implement"){Rd=e?.slice(0,2e3)||"";let l=pt?`
986
+ `+so.map((l,c)=>`${c+1}. ${l.file} \u2014 ${l.action}`).join(`
987
+ `):"",i=await Fw(t==="verify"?o:e||o||""),a;if(t==="implement"){Ad=e?.slice(0,2e3)||"";let l=ct?`
988
988
 
989
989
  Bounded backlog implementation guard: preflight and backlog review are already complete. Do not run git status, git log, or re-read the backlog/docs before making progress. Start by reading the concrete implementation file(s) named in the accepted plan with targeted line ranges, then edit one scoped change.`:"";a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
990
- ${Rd}
990
+ ${Ad}
991
991
 
992
- ${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+l+r}else if(t==="verify"){Cd=e?.slice(0,500)||"";let l=n?[...n].join(", "):"none",c=await gl(n),u=await ci(n),d=c.length>0?`Suggested checks (run the narrowest ones that fit the change):
992
+ ${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+l+r}else if(t==="verify"){Od=e?.slice(0,500)||"";let l=n?[...n].join(", "):"none",c=await bl(n),u=await ui(n),d=c.length>0?`Suggested checks (run the narrowest ones that fit the change):
993
993
  ${c.map((h,m)=>`${m+1}. ${h}`).join(`
994
994
  `)}
995
995
 
@@ -1006,7 +1006,7 @@ Prefer these before broader suites when a targeted run is possible.
1006
1006
  Report PASS (all good) or FAIL (list specific issues).
1007
1007
 
1008
1008
  Files modified: ${l}
1009
- ${i}${d}${f}Summary: ${Cd}`}return P(`${p.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${xn||"default"})${p.reset}`),a?{role:"user",content:a}:null}async function gl(t){let e=[],o=[...t||[]].map(l=>String(l).toLowerCase()),s={};try{let l=ot.join(process.cwd(),"package.json");if(tt.existsSync(l)){s=JSON.parse(tt.readFileSync(l,"utf-8")).scripts||{};let u=[["test",Ln("test")],["lint",Ln("lint")],["typecheck",Ln("typecheck")],["check",Ln("check")],["build",Ln("build")]];for(let[d,f]of u)s[d]&&e.push(f)}}catch{}e.length===0&&(tt.existsSync(ot.join(process.cwd(),"package.json"))&&e.push(Ln("test")),(tt.existsSync(ot.join(process.cwd(),"pytest.ini"))||tt.existsSync(ot.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await ci(t);e.unshift(...PA(r,s));let i=o.some(l=>/\.(ts|tsx)$/.test(l)),a=o.some(l=>/\.(js|jsx|ts|tsx)$/.test(l));return i&&!e.includes(Ln("typecheck"))&&e.push(Ln("typecheck")),a&&!e.includes(Ln("lint"))&&e.push(Ln("lint")),[...new Set(e)].slice(0,4)}function qd(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(Fd())return"English";let n=String(t||"").trim();if(!n)return"English";let s=n.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[],r=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please"]),i=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","erstelle","schreibe","erkl\xE4re","funktion","abfrage","datei","zur\xFCck","mit","ohne","danke"]),a=0,l=0;for(let c of s)r.has(c)&&a++,i.has(c)&&l++;return l>=3&&l>a*1.4?"German":"English"}function NA(t){let n=String(t||"").replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[];if(n.length===0)return"English";let o=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please","this","that","it","is","are","as","in"]),s=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","ich","habe","wir","du","sie","es","diese","dieser","dass","wird","wurde","um","mit","ohne","danke"]),r=0,i=0;for(let a of n)o.has(a)&&r++,s.has(a)&&i++;return i>=3&&i>r*1.4?"German":"English"}function MA(t,e){if(typeof e!="string"||typeof t!="string")return!1;let n=t.toLowerCase(),o=e.toLowerCase(),s=/\b(bash|shell|sh)\b/.test(n)||/\b(one-?liner|pre-commit)\b/.test(n),r=/\b(dockerfile|makefile|cron|crontab|sql)\b/.test(n);if(!s&&!r&&(/```bash\b/.test(o)||/```sh\b/.test(o)))return!0;let i=e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase();return[/\b(let me|i(?:'|’)ll|i will)\s+(check|search|look)\b/,/\bfirst,\s*let me\b/,/\bsince i (?:do not|don’t|don't) see\b/,/\b(let me|i(?:'|’)ll|i will)\s+(?:run|execute)\b/,/\bsearch(?:ing)?\s+for\b/,/\bcheck if there(?: is| are)\b/].some(a=>a.test(i))}function Dw(t){let e=String(t||"").trim();if(!e||e.length>2500)return!1;let n=e.toLowerCase();return/\b(?:repo|repository|project|codebase|existing|current workspace|this workspace)\b/.test(n)||/\b(?:create|write|save)\s+(?:a\s+)?file\b/.test(n)||/\b(?:read|search|inspect|look through|find in|run|install)\b/.test(n)?!1:[/\b(?:reply|respond|answer)\b.*\bexactly\b/i,/\b(?:sql\s+query|select\s+.+\s+from)\b/i,/\b(?:cron(?:\s+expression)?|crontab)\b/i,/\bregex\b.*\b(?:explain|refactor|rewrite|readable)\b/i,/\b(?:small|simple|minimal)?\s*makefile\b/i,/\b(?:small|simple|minimal)?\s*dockerfile\b/i,/\b(?:docker\s+healthcheck|healthcheck)\b/i,/\brefactor\b.*\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\btypescript\b.*\binterface\b/i,/\b(?:debug|fix)\b.*\bbash\b.*\bscript\b/i,/\bpre-commit\s+hook\b/i,/\bbash\s+one-?liner\b/i,/\bdataclass\b/i,/\bexpress\b.*\broute\b/i,/\beventemitter\b/i,/\b(?:javascript|js|python)\s+function\b/i,/\bfunction\s+\w+\s*\(/i].some(o=>o.test(e))}function LA(t){if(typeof t!="string")return null;let e=t.toLowerCase();return/\bsieve of eratosthenes\b/i.test(t)&&/\bprimes?\b/i.test(t)&&/\bup to n\b/i.test(t)?["```python","from __future__ import annotations","","from typing import List","","","def sieve_of_eratosthenes(n: int) -> List[int]:",' """Return all prime numbers <= n using the Sieve of Eratosthenes.',""," Args:"," n: Upper bound (inclusive).",""," Returns:"," A list of all primes p such that 2 <= p <= n, in ascending order.",' """'," if n < 2:"," return []",""," is_prime = [True] * (n + 1)"," is_prime[0] = False"," is_prime[1] = False",""," p = 2"," while p * p <= n:"," if is_prime[p]:"," for multiple in range(p * p, n + 1, p):"," is_prime[multiple] = False"," p += 1",""," return [i for i in range(2, n + 1) if is_prime[i]]","```"].join(`
1009
+ ${i}${d}${f}Summary: ${Od}`}return P(`${p.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${xn||"default"})${p.reset}`),a?{role:"user",content:a}:null}async function bl(t){let e=[],o=[...t||[]].map(l=>String(l).toLowerCase()),s={};try{let l=ot.join(process.cwd(),"package.json");if(tt.existsSync(l)){s=JSON.parse(tt.readFileSync(l,"utf-8")).scripts||{};let u=[["test",Ln("test")],["lint",Ln("lint")],["typecheck",Ln("typecheck")],["check",Ln("check")],["build",Ln("build")]];for(let[d,f]of u)s[d]&&e.push(f)}}catch{}e.length===0&&(tt.existsSync(ot.join(process.cwd(),"package.json"))&&e.push(Ln("test")),(tt.existsSync(ot.join(process.cwd(),"pytest.ini"))||tt.existsSync(ot.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await ui(t);e.unshift(...IA(r,s));let i=o.some(l=>/\.(ts|tsx)$/.test(l)),a=o.some(l=>/\.(js|jsx|ts|tsx)$/.test(l));return i&&!e.includes(Ln("typecheck"))&&e.push(Ln("typecheck")),a&&!e.includes(Ln("lint"))&&e.push(Ln("lint")),[...new Set(e)].slice(0,4)}function Bd(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(Ud())return"English";let n=String(t||"").trim();if(!n)return"English";let s=n.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[],r=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please"]),i=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","erstelle","schreibe","erkl\xE4re","funktion","abfrage","datei","zur\xFCck","mit","ohne","danke"]),a=0,l=0;for(let c of s)r.has(c)&&a++,i.has(c)&&l++;return l>=3&&l>a*1.4?"German":"English"}function jA(t){let n=String(t||"").replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[];if(n.length===0)return"English";let o=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please","this","that","it","is","are","as","in"]),s=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","ich","habe","wir","du","sie","es","diese","dieser","dass","wird","wurde","um","mit","ohne","danke"]),r=0,i=0;for(let a of n)o.has(a)&&r++,s.has(a)&&i++;return i>=3&&i>r*1.4?"German":"English"}function DA(t,e){if(typeof e!="string"||typeof t!="string")return!1;let n=t.toLowerCase(),o=e.toLowerCase(),s=/\b(bash|shell|sh)\b/.test(n)||/\b(one-?liner|pre-commit)\b/.test(n),r=/\b(dockerfile|makefile|cron|crontab|sql)\b/.test(n);if(!s&&!r&&(/```bash\b/.test(o)||/```sh\b/.test(o)))return!0;let i=e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase();return[/\b(let me|i(?:'|’)ll|i will)\s+(check|search|look)\b/,/\bfirst,\s*let me\b/,/\bsince i (?:do not|don’t|don't) see\b/,/\b(let me|i(?:'|’)ll|i will)\s+(?:run|execute)\b/,/\bsearch(?:ing)?\s+for\b/,/\bcheck if there(?: is| are)\b/].some(a=>a.test(i))}function Bw(t){let e=String(t||"").trim();if(!e||e.length>2500)return!1;let n=e.toLowerCase();return/\b(?:repo|repository|project|codebase|existing|current workspace|this workspace)\b/.test(n)||/\b(?:create|write|save)\s+(?:a\s+)?file\b/.test(n)||/\b(?:read|search|inspect|look through|find in|run|install)\b/.test(n)?!1:[/\b(?:reply|respond|answer)\b.*\bexactly\b/i,/\b(?:sql\s+query|select\s+.+\s+from)\b/i,/\b(?:cron(?:\s+expression)?|crontab)\b/i,/\bregex\b.*\b(?:explain|refactor|rewrite|readable)\b/i,/\b(?:small|simple|minimal)?\s*makefile\b/i,/\b(?:small|simple|minimal)?\s*dockerfile\b/i,/\b(?:docker\s+healthcheck|healthcheck)\b/i,/\brefactor\b.*\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\btypescript\b.*\binterface\b/i,/\b(?:debug|fix)\b.*\bbash\b.*\bscript\b/i,/\bpre-commit\s+hook\b/i,/\bbash\s+one-?liner\b/i,/\bdataclass\b/i,/\bexpress\b.*\broute\b/i,/\beventemitter\b/i,/\b(?:javascript|js|python)\s+function\b/i,/\bfunction\s+\w+\s*\(/i].some(o=>o.test(e))}function qA(t){if(typeof t!="string")return null;let e=t.toLowerCase();return/\bsieve of eratosthenes\b/i.test(t)&&/\bprimes?\b/i.test(t)&&/\bup to n\b/i.test(t)?["```python","from __future__ import annotations","","from typing import List","","","def sieve_of_eratosthenes(n: int) -> List[int]:",' """Return all prime numbers <= n using the Sieve of Eratosthenes.',""," Args:"," n: Upper bound (inclusive).",""," Returns:"," A list of all primes p such that 2 <= p <= n, in ascending order.",' """'," if n < 2:"," return []",""," is_prime = [True] * (n + 1)"," is_prime[0] = False"," is_prime[1] = False",""," p = 2"," while p * p <= n:"," if is_prime[p]:"," for multiple in range(p * p, n + 1, p):"," is_prime[multiple] = False"," p += 1",""," return [i for i in range(2, n + 1) if is_prime[i]]","```"].join(`
1010
1010
  `):/for\s+f\s+in\s+\$\(\s*ls\s+\*\.txt\s*\)\s*;\s*do/i.test(t)&&/\bfilenames?\s+with\s+spaces\b/i.test(t)?["The problem is word splitting: `$(ls *.txt)` produces whitespace-separated output, so filenames with spaces get split into multiple loop items.","","Use a glob directly (no `ls`, no command substitution) and quote the variable:","","```bash","for f in *.txt; do",' echo "$f"',"done","```","","Why this works:","- `*.txt` is expanded by the shell into one word per matching filename (spaces are preserved as part of the word).",'- Quoting `"$f"` prevents a filename like `My File.txt` from being split again when echoed/used.'].join(`
1011
1011
  `):/\bexplain\b.*\bregex\b/i.test(t)&&/25\[0-5\]/.test(t)&&/2\[0-4\]/.test(t)&&/\[01\]\?/.test(t)&&/\)\\\.\)\{3\}/.test(t)?["This regex validates an IPv4 address in dotted-decimal form (e.g. `192.168.0.1`).","","What it does:","- It matches **four** numeric octets separated by literal dots (`.`).","- Each octet must be in the range **0\u2013255**:"," - `25[0-5]` \u2192 250\u2013255"," - `2[0-4][0-9]` \u2192 200\u2013249"," - `[01]?[0-9][0-9]?` \u2192 0\u2013199 (allows 1\u20133 digits, including leading zeros like `001`)","- `^` and `$` anchor the match to the entire string (no extra characters).","","A more readable rewrite (same logic), using a reusable `octet` subpattern:","","```js","const octet = '(?:25[0-5]|2[0-4]\\\\d|[01]?\\\\d\\\\d?)';","const ipv4Regex = new RegExp(`^(?:${octet}\\\\.){3}${octet}$`);","```"].join(`
1012
1012
  `):/\brefactor\b.*\bcallbacks?\b.*\basync\s*\/\s*await\b/i.test(t)&&/fs\.readFile\(\s*["']a\.txt["']/.test(t)&&/fs\.writeFile\(\s*["']b\.txt["']/.test(t)?["```js","const { readFile, writeFile } = require('fs/promises');","","(async () => {"," const data = await readFile('a.txt');"," await writeFile('b.txt', data);"," console.log('done');",""," // If you need a specific encoding, use: await readFile('a.txt', 'utf8')","})().catch((err) => {"," // Closest to `if (err) throw err;` from the callback version."," console.error(err);"," process.exitCode = 1;","});","```","","This keeps the same control flow, but uses `fs/promises` so the operations can be awaited instead of nested callbacks."].join(`
@@ -1021,24 +1021,24 @@ ${i}${d}${f}Summary: ${Cd}`}return P(`${p.cyan} \u21B3 Phase transition: ${s} \
1021
1021
  `):/\bcron expressions?\b/i.test(t)&&/every\s+weekday/i.test(t)&&/first\s+day\s+of\s+each\s+month/i.test(t)&&/every\s+15\s+minutes/i.test(t)?["(1) Every weekday at 9:30 AM:","```cron","30 9 * * 1-5","```","Runs at minute 30, hour 9, Monday\u2013Friday.","","(2) First day of each month at midnight:","```cron","0 0 1 * *","```","Runs at 00:00 on day 1 of every month.","","(3) Every 15 minutes between 8\u201318h on weekdays:","```cron","*/15 8-18 * * 1-5","```","Runs every 15 minutes during hours 08 through 18 (inclusive), Monday\u2013Friday."].join(`
1022
1022
  `):/\bflatten(deep)?\b/i.test(t)&&/\biterative\b/i.test(t)&&/\brecursive\b/i.test(t)?["Recursive version:","```js","function flattenDeep(arr) {"," const result = [];"," for (const item of arr) {"," if (Array.isArray(item)) result.push(...flattenDeep(item));"," else result.push(item);"," }"," return result;","}","```","","Iterative version (preserves left-to-right order, does not mutate input):","```js","function flattenDeepIterative(arr) {"," const result = [];"," const stack = [{ array: arr, index: 0 }];",""," while (stack.length > 0) {"," const frame = stack[stack.length - 1];"," if (frame.index >= frame.array.length) {"," stack.pop();"," continue;"," }"," const value = frame.array[frame.index++];"," if (Array.isArray(value)) {"," stack.push({ array: value, index: 0 });"," } else {"," result.push(value);"," }"," }",""," return result;","}","```"].join(`
1023
1023
  `):/\bpre-commit\s+hook\b/.test(e)&&/console\.log/.test(t)&&/\.js\b/.test(e)?["```bash","#!/usr/bin/env bash","","# Block commits that contain console.log() in staged .js files.","","# Only inspect staged content (the commit snapshot), not the working tree.","# NOTE: Do NOT use `set -e` in hooks: grep returns 1 on no match.","","# If no staged JS files, allow the commit.",'if ! git diff --cached --name-only --diff-filter=ACMR -- "*.js" | grep -q .; then'," exit 0","fi","","# Scan staged file contents so existing console.log() also blocks the commit.","while IFS= read -r -d '' file; do",' if git show ":$file" | grep -Eq "(^|[^[:alnum:]_])console\\\\.log[[:space:]]*\\\\("; then',' echo "ERROR: console.log() found in staged JavaScript file: $file"',' echo "Remove it (use proper logging) before committing."'," exit 1"," fi",'done < <(git diff --cached --name-only -z --diff-filter=ACMR -- "*.js")',"","exit 0","```","","Why: `console.log()` is usually temporary debug output. Blocking it at commit time keeps debug noise out of the codebase and prevents accidental logs in production.","","Install: save this as `.git/hooks/pre-commit` and run `chmod +x .git/hooks/pre-commit`."].join(`
1024
- `):null}function IA(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,o=Fd(),s=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
1024
+ `):null}function FA(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,o=Ud(),s=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
1025
1025
  `];o?r.push("RESPONSE LANGUAGE: This project requires English. Always respond in English, even if the user writes in another language."):s?r.push(`RESPONSE LANGUAGE: You MUST always respond in ${s}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${s} only.`):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"),$n()?r.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files, documentation): create or edit files only when the user explicitly asks for files or the existing workflow clearly requires files. For self-contained snippet requests, answer in text only."):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 Iterative deep flatten must preserve left-to-right order and must not mutate the caller's input. Initialize the stack with a shallow copy such as input.slice(), pop values, push child array contents onto the stack in their existing order, collect scalar values with push(), then reverse the result once at the end."),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. In Alpine or minimal images, do not assume wget or curl exists unless the Dockerfile installs it; either install the tool explicitly or use a dependency-free command such as "node -e" when Node is present.'),r.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let i=e||"English";r.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${i}.`);let a=n||"English";return r.push(`COMMIT MESSAGES: Write all git commit messages in ${a}.`),s&&r.push(`
1026
1026
  This is a hard requirement. Always respond in ${s}. Do NOT switch to any other language \u2014 even if the user writes to you in German, French, or any other language, your reply MUST be in ${s}.`),r.join(`
1027
1027
  `)+`
1028
1028
 
1029
- `}function jA(t){let e=qd(t);return Fd()?`# Current Turn Language (CRITICAL \u2014 enforce strictly)
1029
+ `}function BA(t){let e=Bd(t);return Ud()?`# Current Turn Language (CRITICAL \u2014 enforce strictly)
1030
1030
  This repository is English-only. You MUST answer this turn in English, even if the user's message is written in German or any other language. Treat non-English input as content to answer, not as a language-switch instruction. Do NOT switch to another language because of the user's wording, repository files, prior conversation, examples, or project instructions.
1031
1031
 
1032
1032
  `:`# Current Turn Language (CRITICAL \u2014 enforce strictly)
1033
1033
  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.
1034
1034
 
1035
- `}function DA(){if(Uo!==null)return Uo;try{let e=FC().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:qC(r.id,s.name),name:r.name})));if(e.length<2)return Uo="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
1035
+ `}function UA(){if(Ho!==null)return Ho;try{let e=WC().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:UC(r.id,s.name),name:r.name})));if(e.length<2)return Ho="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
1036
1036
  # Sub-Agent Model Routing
1037
1037
 
1038
1038
  `;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 |
1039
1039
  |---|---|---|
1040
1040
  `;for(let s of e)o+=`| ${s.spec} | ${s.tier} | ${n[s.tier]||s.tier} |
1041
- `;return Uo=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Uo="",""}}var Nd="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function qA(t){let e=t.indexOf(Nd);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Nd.length).trimStart()}}async function Md(){let t=await Tw()+":"+kn();if(Kr!==null&&t===bd)return Kr;let e=await sC(process.cwd()),n=yC(),o=MC(),s=Qs()?vC():"",r=IA(),i=bC(),a=UC(kn());return Kr=`${a?`## Model Briefing
1041
+ `;return Ho=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Ho="",""}}var Ld="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function WA(t){let e=t.indexOf(Ld);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Ld.length).trimStart()}}async function Id(){let t=await Aw()+":"+kn();if(Kr!==null&&t===_d)return Kr;let e=await iC(process.cwd()),n=_C(),o=jC(),s=eo()?RC():"",r=FA(),i=$C(),a=GC(kn());return Kr=`${a?`## Model Briefing
1042
1042
  ${a}
1043
1043
 
1044
1044
  ---
@@ -1305,7 +1305,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
1305
1305
  - Instead: use bash with inline node -e '...' for quick one-off checks.
1306
1306
  - If the test is worth keeping, write it to tests/ with a proper name.
1307
1307
  - Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
1308
- ${DA()}
1308
+ ${UA()}
1309
1309
 
1310
1310
  # Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
1311
1311
 
@@ -1497,63 +1497,63 @@ class ErrorBoundary extends React.Component {
1497
1497
  - Use migrations for schema changes, never manual ALTER TABLE
1498
1498
  - Add database-level constraints (unique, foreign key, check) not just app-level
1499
1499
 
1500
- `,bd=t,Kr}function qw(){Id.clear(),Cw.clear(),Qa.clear(),ei.clear(),Aw.clear(),el.clear(),ti.clear(),jn.clear(),zn.clear(),ni.clear(),Mt.clear(),eo.clear(),pl.clear(),kd.clear(),on=0,Xr=0,tl=0,Kt=!1,sl=0,Vs=-1,Sd=!1,ol=0,rl=!1,ln=0,cn=!1,_n=0,un=0,Et=!1,Ft="",Jr=0,il="",Xs=0,al="",Js=0,rn=!1,vd=!1,xe="plan",hl=0,ge=!1,xn=null,Rd=null,Cd=null,no=[],Go=0,Ko=0,Vo=0,si=0,Vn=!1,Dn=0,ps=0,zo=null,to=null,pt=!1,Ut=0,li=0,dn.clear(),Vt=!1,Dd="",cl=!1,fs=0,Xo=0,ii.clear(),ai.clear(),Ae=null,an=!1,jd=null,Ed=!1,Td=!1,ll=!1,ds="",Zs="",Qr="",xd="",nl=0}function FA(){S=[],Zr=null,Wo="",Ho=0,wd="",_d=0,qw();try{let{resetCompactionFailures:t}=hu();t()}catch{}try{let{cancelAllJobs:t}=Do();t()}catch{}}function BA(){S.length>fw&&S.splice(0,S.length-fw)}function Fd(){try{let t=require("fs"),n=require("path").join(process.cwd(),"AGENTS.md");if(!t.existsSync(n))return!1;let o=t.readFileSync(n,"utf8");return/all.*english/i.test(o)&&/no german/i.test(o)}catch{return!1}}function hd(t,e,n,o=1500){return!t||!e?!1:t===e&&Date.now()-n<o}function UA(){return S.length}function WA(){return S}function HA(t){S=t}async function GA(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),o=(d,f)=>new Promise(h=>{t(d,f,{cwd:n,timeout:3e3},(m,g)=>{h(m?"":(g||"").trim())})}),[s]=await Promise.all([o("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(s?s.split(`
1500
+ `,_d=t,Kr}function Uw(){Dd.clear(),Pw.clear(),tl.clear(),ei.clear(),Nw.clear(),nl.clear(),ti.clear(),jn.clear(),zn.clear(),ni.clear(),Mt.clear(),to.clear(),ml.clear(),Sd.clear(),rn=0,Xr=0,sl=0,Xt=!1,rl=0,Xs=-1,Ed=!1,il=0,al=!1,cn=0,un=!1,_n=0,dn=0,Et=!1,Ft="",Jr=0,ll="",Js=0,cl="",Zs=0,an=!1,Td=!1,xe="plan",gl=0,he=!1,xn=null,Ad=null,Od=null,so=[],zo=0,Xo=0,Jo=0,si=0,Vn=!1,Dn=0,ps=0,Vo=null,no=null,ct=!1,Ut=0,ci=0,Ht.clear(),Wt=!1,Fd="",dl=!1,fs=0,Zo=0,oi=0,ai.clear(),li.clear(),Pe=null,ln=!1,qd=null,Rd=!1,Cd=!1,ul=!1,ds="",Qs="",Qr="",vd="",ol=0}function HA(){S=[],Zr=null,Go="",Yo=0,$d="",kd=0,Uw();try{let{resetCompactionFailures:t}=gu();t()}catch{}try{let{cancelAllJobs:t}=qo();t()}catch{}}function GA(){S.length>hw&&S.splice(0,S.length-hw)}function Ud(){try{let t=require("fs"),n=require("path").join(process.cwd(),"AGENTS.md");if(!t.existsSync(n))return!1;let o=t.readFileSync(n,"utf8");return/all.*english/i.test(o)&&/no german/i.test(o)}catch{return!1}}function gd(t,e,n,o=1500){return!t||!e?!1:t===e&&Date.now()-n<o}function YA(){return S.length}function zA(){return S}function KA(t){S=t}async function VA(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),o=(d,f)=>new Promise(h=>{t(d,f,{cwd:n,timeout:3e3},(m,g)=>{h(m?"":(g||"").trim())})}),[s]=await Promise.all([o("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(s?s.split(`
1501
1501
  `):[]).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=ot.join(n,"package.json");if(e.existsSync(u))try{let d=JSON.parse(e.readFileSync(u,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let h=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";c+=`
1502
- \u{1F4E6} ${h}${m}`}}catch{}return c}function YA(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 je(t,e,n,o,s,{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(s){let c=Date.now()-s;l=Math.round(c/1e3),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1503
- ${p.dim} ${a}${p.reset}`);try{let{getActiveProviderName:c,getActiveModelId:u}=$t(),d=c(),f=u(),h=typeof ow=="function"?ow(d).label:"cost unknown",m=typeof sw=="function"?sw():null;if(d&&f&&m){let g=m.totalCost>0?`$${m.totalCost.toFixed(4)}`:"free";console.log(`${p.dim} model ${d}:${f} \xB7 ${h} \xB7 ${m.totalInput.toLocaleString()} in / ${m.totalOutput.toLocaleString()} out \xB7 ${g}${p.reset}`)}}catch{}if(l>=30&&process.stdout.isTTY){let c=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;YA(c)}if(ai.size>0&&ii.size>0)for(let c of ai){let u=ii.get(c);u&&console.log(`${p.dim} \u2714 task #${c} auto-matched: ${u.slice(0,60)}${p.reset}`)}n.size>0?console.log(`${p.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${p.reset}`):!r&&o.size>=5&&n.size===0&&t>=3?console.log(`${p.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${p.reset}`):o.size>0&&t>=2&&console.log(`${p.dim} \u{1F4A1} /save \xB7 /clear${p.reset}`)}async function zA(){if(!process.stdout.isTTY)return{action:"quit"};let t=In(),e=kn(),n=fl.fast?.[t],o=fl.strong?.[t],s=n&&n!==e,r=o&&o!==e&&o!==n,i=[];i.push({key:"r",label:`Retry with current model ${p.dim}(${e})${p.reset}`}),s&&i.push({key:"f",label:`Switch to ${p.bold}${n}${p.reset} ${p.dim}\u2014 fast, low latency${p.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${p.bold}${o}${p.reset} ${p.dim}\u2014 reliable tool-calling, medium speed${p.reset}`,model:o}),i.push({key:"q",label:`${p.dim}Quit${p.reset}`}),console.log(),console.log(`${p.yellow} Stream stale \u2014 all retries exhausted.${p.reset} What would you like to do?`);for(let a of i)console.log(` ${p.cyan}[${a.key}]${p.reset} ${a.label}`);return process.stdout.write(` ${p.yellow}> ${p.reset}`),new Promise(a=>{let l=process.stdin,c=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,l.removeListener("data",d),l.setRawMode(c||!1),l.pause();let h=f.toLowerCase().trim();if(process.stdout.write(`${h}
1504
- `),f==="")return a({action:"quit"});let m=i.find(g=>g.key===h);!m||m.key==="q"||!m.model&&m.key!=="r"?a({action:"quit"}):m.key==="r"?a({action:"retry"}):a({action:"switch",model:m.model,provider:t})};l.on("data",d)})}function KA(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,n=new Set,o;for(;(o=e.exec(t))!==null;){let s=o[1].replace(/\/$/,"");s.length>1&&s.split("/").filter(i=>i.length>2).forEach(i=>n.add(i))}return Array.from(n)}function VA(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 rt=null,Bd=!1;async function XA(t,e=null,n={}){let o=BC(kn());dw=o.staleWarn,ud=o.staleAbort,rt=e,Bd=!!n.silent;let s=t;if(Zr&&typeof t=="string"&&(s=`${Zr}
1502
+ \u{1F4E6} ${h}${m}`}}catch{}return c}function XA(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 Me(t,e,n,o,s,{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(s){let c=Date.now()-s;l=Math.round(c/1e3),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1503
+ ${p.dim} ${a}${p.reset}`);try{let{getActiveProviderName:c,getActiveModelId:u}=kt(),d=c(),f=u(),h=typeof iw=="function"?iw(d).label:"cost unknown",m=typeof rw=="function"?rw():null;if(d&&f&&m){let g=m.totalCost>0?`$${m.totalCost.toFixed(4)}`:"free";console.log(`${p.dim} model ${d}:${f} \xB7 ${h} \xB7 ${m.totalInput.toLocaleString()} in / ${m.totalOutput.toLocaleString()} out \xB7 ${g}${p.reset}`)}}catch{}if(l>=30&&process.stdout.isTTY){let c=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;XA(c)}if(li.size>0&&ai.size>0)for(let c of li){let u=ai.get(c);u&&console.log(`${p.dim} \u2714 task #${c} auto-matched: ${u.slice(0,60)}${p.reset}`)}n.size>0?console.log(`${p.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${p.reset}`):!r&&o.size>=5&&n.size===0&&t>=3?console.log(`${p.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${p.reset}`):o.size>0&&t>=2&&console.log(`${p.dim} \u{1F4A1} /save \xB7 /clear${p.reset}`)}async function JA(){if(!process.stdout.isTTY)return{action:"quit"};let t=In(),e=kn(),n=hl.fast?.[t],o=hl.strong?.[t],s=n&&n!==e,r=o&&o!==e&&o!==n,i=[];i.push({key:"r",label:`Retry with current model ${p.dim}(${e})${p.reset}`}),s&&i.push({key:"f",label:`Switch to ${p.bold}${n}${p.reset} ${p.dim}\u2014 fast, low latency${p.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${p.bold}${o}${p.reset} ${p.dim}\u2014 reliable tool-calling, medium speed${p.reset}`,model:o}),i.push({key:"q",label:`${p.dim}Quit${p.reset}`}),console.log(),console.log(`${p.yellow} Stream stale \u2014 all retries exhausted.${p.reset} What would you like to do?`);for(let a of i)console.log(` ${p.cyan}[${a.key}]${p.reset} ${a.label}`);return process.stdout.write(` ${p.yellow}> ${p.reset}`),new Promise(a=>{let l=process.stdin,c=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,l.removeListener("data",d),l.setRawMode(c||!1),l.pause();let h=f.toLowerCase().trim();if(process.stdout.write(`${h}
1504
+ `),f==="")return a({action:"quit"});let m=i.find(g=>g.key===h);!m||m.key==="q"||!m.model&&m.key!=="r"?a({action:"quit"}):m.key==="r"?a({action:"retry"}):a({action:"switch",model:m.model,provider:t})};l.on("data",d)})}function ZA(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,n=new Set,o;for(;(o=e.exec(t))!==null;){let s=o[1].replace(/\/$/,"");s.length>1&&s.split("/").filter(i=>i.length>2).forEach(i=>n.add(i))}return Array.from(n)}function QA(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 rt=null,Wd=!1;async function eO(t,e=null,n={}){let o=HC(kn());pw=o.staleWarn,fd=o.staleAbort,rt=e,Wd=!!n.silent;let s=t;if(Zr&&typeof t=="string"&&(s=`${Zr}
1505
1505
 
1506
- ${t}`,Zr=null),typeof s=="string"){let le=KA(s),we=VA(s);(le.length>0||we.length>0)&&(s+=`
1506
+ ${t}`,Zr=null),typeof s=="string"){let le=ZA(s),ye=QA(s);(le.length>0||ye.length>0)&&(s+=`
1507
1507
 
1508
1508
  [System Note for Assistant: To resolve this task faster, consider these hints:
1509
1509
  `,le.length>0&&(s+=`- The user mentioned URLs containing the paths/folders: ${le.join(", ")}. Prioritize searching these folder names using glob or grep first.
1510
- `),we.length>0&&we.forEach(Oe=>{s+=`- ${Oe}
1511
- `}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&vw(s)&&(s+=`
1510
+ `),ye.length>0&&ye.forEach(Oe=>{s+=`- ${Oe}
1511
+ `}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&Rw(s)&&(s+=`
1512
1512
 
1513
- [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?Qb(t):null,i=typeof t=="string"&&Dw(t),a=typeof t=="string"?qd(t):"English",l=Sw(s);if(l&&typeof l.then=="function"&&(l=await l),S.push({role:"user",content:l}),BA(),i){let le=LA(t);if(le){let we={role:"assistant",content:le};return S.push(we),$e(S),vt(S),console.log(le),{success:!0,deterministic:!0,content:le}}}let c=Qs(),u=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false"&&!c,d=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10),f=typeof l=="string"?l:typeof t=="string"?t:"";if(ui(f)&&(Td=!0),$A(f)){an=!0;let le=yl(f);le&&(jd=le)}let g=an,_=Td;try{let{detectComplexPrompt:le,runOrchestrated:we}=Jb(),Oe=le(typeof t=="string"?t:"");if(!u&&c&&Oe.isComplex&&console.log(`${p.dim}Plan mode active: auto-orchestrate disabled until /plan approve${p.reset}`),!_&&Fw(u,Oe,d,c)){console.log(`${p.yellow}\u26A1 Auto-orchestrate: ${Oe.estimatedGoals} goals \u2192 parallel agents${p.reset}`);let Ce=await we(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});if(Ce&&Ce.synthesis){let ke=Ce.synthesis.summary||"",Jt=Ce.synthesis.filesChanged?.length?`
1513
+ [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?tw(t):null,i=typeof t=="string"&&Bw(t),a=typeof t=="string"?Bd(t):"English",l=Tw(s);if(l&&typeof l.then=="function"&&(l=await l),S.push({role:"user",content:l}),GA(),i){let le=qA(t);if(le){let ye={role:"assistant",content:le};return S.push(ye),_e(S),bt(S),console.log(le),{success:!0,deterministic:!0,content:le}}}let c=eo(),u=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false"&&!c,d=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10),f=typeof l=="string"?l:typeof t=="string"?t:"";if(di(f)&&(Cd=!0),vA(f)){ln=!0;let le=wl(f);le&&(qd=le)}let g=ln,_=Cd;try{let{detectComplexPrompt:le,runOrchestrated:ye}=Qb(),Oe=le(typeof t=="string"?t:"");if(!u&&c&&Oe.isComplex&&console.log(`${p.dim}Plan mode active: auto-orchestrate disabled until /plan approve${p.reset}`),!_&&Ww(u,Oe,d,c)){console.log(`${p.yellow}\u26A1 Auto-orchestrate: ${Oe.estimatedGoals} goals \u2192 parallel agents${p.reset}`);let Se=await ye(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});if(Se&&Se.synthesis){let ke=Se.synthesis.summary||"",Zt=Se.synthesis.filesChanged?.length?`
1514
1514
 
1515
- Files changed: ${Ce.synthesis.filesChanged.join(", ")}`:"",He=Ce.synthesis.conflicts?.length?`
1515
+ Files changed: ${Se.synthesis.filesChanged.join(", ")}`:"",Ge=Se.synthesis.conflicts?.length?`
1516
1516
 
1517
1517
  Conflicts:
1518
- ${Ce.synthesis.conflicts.map(st=>`- ${st}`).join(`
1519
- `)}`:"";S.push({role:"assistant",content:ke+Jt+He}),$e(S),vt(S)}return Ce}Oe.isComplex&&process.stdout.isTTY&&console.log(`${p.dim}Hint: ~${Oe.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${p.reset}`)}catch{}let{setOnChange:k}=fu(),$=null,O=0;k((le,we)=>{le==="create"?($&&$.stop(),$=new Z1(we.name,we.tasks),$.setStats({tokens:O}),$.start()):le==="update"&&$?$.updateTask(we.id,we.status):le==="clear"&&$&&($.stop(),$=null)});let E=await Md(),T=E;try{let{getBrainContext:le}=Su(),we=await le(t);we&&(T=E+`
1520
- `+we+`
1521
- `)}catch(le){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",le.message)}let ee=jC(typeof t=="string"?t:"");if(ee.length>0){let le=ee.map(we=>`[Triggered: ${we.name}]
1522
- ${we.instructions}`).join(`
1518
+ ${Se.synthesis.conflicts.map(st=>`- ${st}`).join(`
1519
+ `)}`:"";S.push({role:"assistant",content:ke+Zt+Ge}),_e(S),bt(S)}return Se}Oe.isComplex&&process.stdout.isTTY&&console.log(`${p.dim}Hint: ~${Oe.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${p.reset}`)}catch{}let{setOnChange:k}=hu(),$=null,O=0;k((le,ye)=>{le==="create"?($&&$.stop(),$=new tC(ye.name,ye.tasks),$.setStats({tokens:O}),$.start()):le==="update"&&$?$.updateTask(ye.id,ye.status):le==="clear"&&$&&($.stop(),$=null)});let E=await Id(),T=E;try{let{getBrainContext:le}=Eu(),ye=await le(t);ye&&(T=E+`
1520
+ `+ye+`
1521
+ `)}catch(le){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",le.message)}let ee=FC(typeof t=="string"?t:"");if(ee.length>0){let le=ee.map(ye=>`[Triggered: ${ye.name}]
1522
+ ${ye.instructions}`).join(`
1523
1523
  `);T+=`
1524
1524
  `+le+`
1525
1525
  `}T+=`
1526
- `+jA(t),i&&(T+=`
1526
+ `+BA(t),i&&(T+=`
1527
1527
  # Current Turn Direct Answer Mode
1528
1528
  This request is self-contained. Answer directly with the requested content. Do not inspect the workspace, create files, run commands, install packages, or mention internal process unless the user explicitly asked for that.
1529
- `);let te=[{role:"system",content:T},...S];Zb(kn());let K=new Bo(nd());K.start();let ae=S.length===1,se=ae&&!i?GA().catch(()=>null):Promise.resolve(null),ie=ae?wC(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),Be=i?[]:Bt(),[{messages:Re,compressed:W,compacted:ne,tokensRemoved:Ke},ct,Te]=await Promise.all([oC(te,Be),se,ie]),ve=wn(te,Be);if(K.stop(),ct&&console.log(`${p.dim}${ct}${p.reset}`),ne)console.log(`${p.dim} [context compacted \u2014 summary (~${Ke} tokens freed)]${p.reset}`);else if(W){let le=ve.limit>0?Math.round(Ke/ve.limit*100):0;P(`${p.dim} [context compressed \u2014 ~${Ke} tokens freed (${le}%)]${p.reset}`)}ve.percentage>85&&P(`${p.yellow} \u26A0 Context ${Math.round(ve.percentage)}% used (${Math.round(100-ve.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${p.reset}`);let b=Re;if(Te&&ae&&(b=[b[0],{role:"user",content:`[Server probe at task start]
1530
- ${Te}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...b.slice(1)]),r&&ae){let le=r.shouldPreferSsh?`[Runtime URL detected]
1529
+ `);let te=[{role:"system",content:T},...S];ew(kn());let K=new Wo(od());K.start();let ae=S.length===1,se=ae&&!i?VA().catch(()=>null):Promise.resolve(null),ie=ae?kC(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),Be=i?[]:Bt(),[{messages:Ce,compressed:H,compacted:ne,tokensRemoved:Ve},ut,Re]=await Promise.all([aC(te,Be),se,ie]),Te=wn(te,Be);if(K.stop(),ut&&console.log(`${p.dim}${ut}${p.reset}`),ne)console.log(`${p.dim} [context compacted \u2014 summary (~${Ve} tokens freed)]${p.reset}`);else if(H){let le=Te.limit>0?Math.round(Ve/Te.limit*100):0;P(`${p.dim} [context compressed \u2014 ~${Ve} tokens freed (${le}%)]${p.reset}`)}Te.percentage>85&&P(`${p.yellow} \u26A0 Context ${Math.round(Te.percentage)}% used (${Math.round(100-Te.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${p.reset}`);let b=Ce;if(Re&&ae&&(b=[b[0],{role:"user",content:`[Server probe at task start]
1530
+ ${Re}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...b.slice(1)]),r&&ae){let le=r.shouldPreferSsh?`[Runtime URL detected]
1531
1531
  The user linked a live app URL (${r.url}) and described broken behavior. Treat this as a runtime/deployed-instance issue first. Reproduce it with browser_open or browser_screenshot on the URL before reading local files. Because this URL matches server profile "${r.matchedName}", prefer ssh_exec/service_logs on that server for investigation before local repo inspection.`:`[Runtime URL detected]
1532
- The user linked a live app URL (${r.url}) and described broken behavior. Treat this as a runtime issue first. Reproduce it with browser_open or browser_screenshot before reading local files. Only inspect the local repo after you have confirmed the live behavior.`;b=[b[0],{role:"user",content:le},{role:"assistant",content:"Understood \u2014 I will inspect the live app/runtime first."},...b.slice(1)]}if(ae&&!_){let le=_C(typeof t=="string"?t:"");le&&(b=[b[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1532
+ The user linked a live app URL (${r.url}) and described broken behavior. Treat this as a runtime issue first. Reproduce it with browser_open or browser_screenshot before reading local files. Only inspect the local repo after you have confirmed the live behavior.`;b=[b[0],{role:"user",content:le},{role:"assistant",content:"Understood \u2014 I will inspect the live app/runtime first."},...b.slice(1)]}if(ae&&!_){let le=xC(typeof t=="string"?t:"");le&&(b=[b[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1533
1533
  `+le.user},{role:"assistant",content:le.assistant+`
1534
- [END EXAMPLE \u2014 wait for the real user request below]`},...b.slice(1)])}if(wn(b,Be).percentage>=65){let{messages:we,tokensRemoved:Oe}=Nn(b,Be);Oe>0&&(b=we,console.log(`${p.dim} [pre-flight compress \u2014 ${Oe} tokens freed, now ${Math.round(wn(b,Be).percentage)}% used]${p.reset}`))}let L=0,U=0,Z=0,X=0,R=0,ce=9,qe=0,be=new Set,Le=(()=>{let le=S.find(we=>we.role==="user");return typeof le?.content=="string"?le.content:""})(),Wt=typeof Le=="string"?Qb(Le):null,Vd=oi(Le),pi=/set_reminder|google.?auth|cron:|api\.log|swarm.{0,30}(agent|crash|fail)|agent.{0,30}(crashed|crash|fail)|server.{0,30}(error|crash|problem)|on.server/i.test(Le)||!!Wt?.shouldPreferSsh,h0=!!Wt,hi=0;if(!Et){let le=S.filter(Oe=>Oe.role==="user"||Oe.role==="tool").map(Oe=>typeof Oe.content=="string"?Oe.content:"").join(`
1535
- `),we=fd(le);we&&(Et=!0,Ft=we.slice(0,120),P(`${p.yellow} \u26A1 Root cause in briefing: ${Ft} \u2014 fix phase active from start (read budget: 3)${p.reset}`))}!Et&&!rn&&/\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(Le)&&(rn=!0,P(`${p.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${p.reset}`));let hs=f||Le;if(!n.skipPhaseRouting&&!vA(hs)&&(S.length<=1||_&&!ge)&&(ge=_?!0:pC(),ge)){to=fC(hs)?.id||"coding";let we=Ad(hs);if(xe=we?"implement":"plan",xn=md(xe,to),hl=0,Go=0,ps=0,zo=null,pt=xe==="plan"&&Ow(hs),Ut=0,li=0,dn.clear(),Vt=!1,Dd=pt?hs:"",pt)for(let Ce of oi(hs))dn.add(Jo(Ce));cl=!1,fs=0,us.clear(),process.stdout.isTTY&&console.log(we?`${p.dim} \u21B3 Phase routing: implement(${xn||"default"}) \u2192 verify ${p.yellow}[plan skipped: direct file task]${p.reset}`:`${p.dim} \u21B3 Phase routing: plan(${xn||"default"}) \u2192 implement \u2192 verify${p.reset}`),P(we?`${p.cyan} \u26A1 Phase routing enabled \u2014 skipping plan phase for direct file task, starting in implement with ${xn||"default model"} (category: ${to})${p.reset}`:`${p.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${xn||"default model"} (category: ${to})${p.reset}`);let Oe=oi(hs);if(we&&Oe.length>0){let ke={role:"user",content:`[SYSTEM] This is a direct file task targeting: ${Oe.slice(0,3).join(", ")}. Modify only the explicitly requested file(s) unless the user asks for more. Do NOT create extra helper or test files for verification. Prefer inline verification with bash or by reading the edited file.`};S.push(ke),b.push(ke)}if(pt){let Ce={role:"user",content:Kn()};S.push(Ce),b.push(Ce)}}if(an){Ae=null;let le=await xA(f,b,S);if(!le.ok){let we=le.requiredBranch,Oe=le.branch?`Current branch: ${le.branch}. `:"",Ce=we?`Required branch: ${we}. `:"",ke=le.dirty===!0?`Worktree is dirty (${le.changedFiles.length} changed file${le.changedFiles.length===1?"":"s"}). `:"",He="[PRECHECK BLOCKED] This prompt contains explicit git/worktree safety gates. I ran `git status --short --branch` as preflight and will not proceed until it's safe.\n\n"+`${!le.raw||/^ERROR:/i.test(le.raw)||/^fatal:/i.test(le.raw)?"Git preflight failed (no usable status output). ":""}${Oe}${Ce}${ke}`.trim()+`
1534
+ [END EXAMPLE \u2014 wait for the real user request below]`},...b.slice(1)])}if(wn(b,Be).percentage>=65){let{messages:ye,tokensRemoved:Oe}=Nn(b,Be);Oe>0&&(b=ye,console.log(`${p.dim} [pre-flight compress \u2014 ${Oe} tokens freed, now ${Math.round(wn(b,Be).percentage)}% used]${p.reset}`))}let I=0,U=0,Z=0,X=0,R=0,ue=9,qe=0,we=new Set,Ie=(()=>{let le=S.find(ye=>ye.role==="user");return typeof le?.content=="string"?le.content:""})(),Gt=typeof Ie=="string"?tw(Ie):null,Jd=ri(Ie),hi=/set_reminder|google.?auth|cron:|api\.log|swarm.{0,30}(agent|crash|fail)|agent.{0,30}(crashed|crash|fail)|server.{0,30}(error|crash|problem)|on.server/i.test(Ie)||!!Gt?.shouldPreferSsh,y0=!!Gt,mi=0;if(!Et){let le=S.filter(Oe=>Oe.role==="user"||Oe.role==="tool").map(Oe=>typeof Oe.content=="string"?Oe.content:"").join(`
1535
+ `),ye=hd(le);ye&&(Et=!0,Ft=ye.slice(0,120),P(`${p.yellow} \u26A1 Root cause in briefing: ${Ft} \u2014 fix phase active from start (read budget: 3)${p.reset}`))}!Et&&!an&&/\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(Ie)&&(an=!0,P(`${p.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${p.reset}`));let ms=f||Ie;if(!n.skipPhaseRouting&&!CA(ms)&&(S.length<=1||_&&!he)&&(he=_?!0:gC(),he)){no=mC(ms)?.id||"coding";let ye=Pd(ms);if(xe=ye?"implement":"plan",xn=yd(xe,no),gl=0,zo=0,ps=0,Vo=null,ct=xe==="plan"&&Mw(ms),Ut=0,ci=0,Ht.clear(),Wt=!1,Fd=ct?ms:"",ct)for(let Se of ri(ms))Ht.add(hs(Se));dl=!1,fs=0,us.clear(),process.stdout.isTTY&&console.log(ye?`${p.dim} \u21B3 Phase routing: implement(${xn||"default"}) \u2192 verify ${p.yellow}[plan skipped: direct file task]${p.reset}`:`${p.dim} \u21B3 Phase routing: plan(${xn||"default"}) \u2192 implement \u2192 verify${p.reset}`),P(ye?`${p.cyan} \u26A1 Phase routing enabled \u2014 skipping plan phase for direct file task, starting in implement with ${xn||"default model"} (category: ${no})${p.reset}`:`${p.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${xn||"default model"} (category: ${no})${p.reset}`);let Oe=ri(ms);if(ye&&Oe.length>0){let ke={role:"user",content:`[SYSTEM] This is a direct file task targeting: ${Oe.slice(0,3).join(", ")}. Modify only the explicitly requested file(s) unless the user asks for more. Do NOT create extra helper or test files for verification. Prefer inline verification with bash or by reading the edited file.`};S.push(ke),b.push(ke)}if(ct){let Se={role:"user",content:Kn()};S.push(Se),b.push(Se)}}if(ln){Pe=null;let le=await TA(f,b,S);if(!le.ok){let ye=le.requiredBranch,Oe=le.branch?`Current branch: ${le.branch}. `:"",Se=ye?`Required branch: ${ye}. `:"",ke=le.dirty===!0?`Worktree is dirty (${le.changedFiles.length} changed file${le.changedFiles.length===1?"":"s"}). `:"",Ge="[PRECHECK BLOCKED] This prompt contains explicit git/worktree safety gates. I ran `git status --short --branch` as preflight and will not proceed until it's safe.\n\n"+`${!le.raw||/^ERROR:/i.test(le.raw)||/^fatal:/i.test(le.raw)?"Git preflight failed (no usable status output). ":""}${Oe}${Se}${ke}`.trim()+`
1536
1536
 
1537
- Next step: make the worktree clean and be on the required branch, then re-run the automation.`,st={role:"assistant",content:He};S.push(st),$e(S),vt(S),console.log(He);return}if(!Ed){let we={role:"user",content:"[SYSTEM] This is a gated automation workflow. In your final summary, use these exact labels (one per line): Preflight:, Preflight output:, Branch:, Chosen task: (or Selected improvement: / no safe task found), Files changed:, Verification:, Commit:, Push:, Final git status:, Remaining risk:. If any field is unknown or not run, write that explicitly. Do not claim safety, verification, commit, push, or git status checks without evidence from tool output."};S.push(we),b.push(we),Ed=!0}}await SA(b,S);let ue=0,Sn=0,Pe=new Map,H=new Set,Ee=new Set,oo=[],ro=[],Zo=new Set,io=0,Xd=0,xl=0,Ve=0,Ne=Date.now(),m0=new tC(WC),Sl=()=>oo.length>0||ro.length>0,g0=ni,ht=n.skillLoop?10:1,y0=3*ht,b0=5*ht,Jd=Id,w0=5*ht,_0=8*ht,$0=Cw,k0=(ge?6:4)*ht,x0=(ge?10:7)*ht,vl=Qa,S0=(ge?5:3)*ht,mi=(ge?8:5)*ht,v0=Aw,E0=(ge?4:3)*ht,T0=(ge?6:4)*ht,R0=3*ht,C0=4*ht,ao=jn,A0=(ge?6:4)*ht,O0=(ge?10:8)*ht,lo=(ge?12:10)*ht,P0=25,ms=0,N0=10*ht,M0=15*ht,gs=0,Zd=5*ht,ys=0,L0=2*ht,I0=3,El=!1,Tl=0,gi=!1,Rl=0,Qo=10,j0=16,Qd=n.skillLoop?999:o.investigationCap,yi=async()=>{let{hasPendingOrCompletedJobs:le,getPendingJobSummary:we}=Do();if(le()){if(we()){let Oe=Date.now()+45e3;for(process.stderr.write(`${p.cyan} \u23F3 Waiting for background agents to finish\u2026${p.reset}
1538
- `);we()&&Date.now()<Oe;)await new Promise(Ce=>setTimeout(Ce,500).unref()),Xa(S,b)}Xa(S,b),S.length>0&&$e(S)}},Jn=typeof t=="string"?t.trim():"",ef=Jn.length>0&&/^\s*(analyze|analyse|explain|describe|review|audit|summari[sz]e|list|understand|document|documentation|docs|what is|what does|how does|show me|show the|show all|tell me about)/i.test(Jn)&&!/\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(Jn),bi=Jn.length>0&&/\b(analyze|analyse|explain|describe|review|audit|summari[sz]e|understand|document|scan|count|inventory|map|list|identify)\b/i.test(Jn)&&/\b(create|write|generate|produce|output)\b/i.test(Jn)&&/\b([A-Z0-9_-]+\.md|markdown|report|summary|overview|architecture|audit|table|documentation|docs|inventory|catalog)\b/i.test(Jn)&&!/\b(fix|bug|crash|error|implement|add(?!\s+(?:to|into)\b)|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|delete|remove|install|setup|deploy|run)\b/i.test(Jn),ut,Lt=n.maxIterations||(ge?ls(xe):yd);ef&&(Lt=Math.min(Lt,4),P(`${p.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${Lt}${p.reset}`));let Cl=0,tf=3,wi=!1,_i=0,Al=!1;e:for(;;){for(wi=!1,ut=0;ut<Lt&&!Ja()?.aborted;ut++){Xa(S,b);{let w=Bt(),y=wn(b,w),I=ue===0?65:78;if(y.percentage>=I){if(H.size>0||ge&&xe!=="plan"){let pe=iC(S,{filesModified:H,currentPhase:ge?xe:null});if(pe){let Q=b.findIndex(C=>C._progressSnapshot);Q!==-1&&b.splice(Q,1);let F=b.findIndex(C=>C.role==="system");b.splice(F+1,0,pe)}}let{messages:j,tokensRemoved:V}=Nn(b,w,ue===0);if(V>0&&(b=j,V>50&&console.log(`${p.dim} [auto-compressed \u2014 ~${V} tokens freed, now ${Math.round(wn(b,w).percentage)}%]${p.reset}`),rn&&H.size>=3)){let pe=[...H].map(F=>F.split("/").pop()).slice(0,10).join(", "),Q={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${H.size} files: ${pe}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};b.push(Q)}}}if(Kt&&!Et&&Jr<2){Jr++;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."};b.push(w),S.push(w),P(`${p.yellow} \u26A0 Pre-call SSH-blocked nudge #${Jr} injected \u2014 model told to synthesize${p.reset}`)}Kt||(Jr=0);let we=!0;ue>0&&CC();let Oe=null;if($&&$.isActive())$._paused&&$.resume();else if(!$){let w,y=AC();if(y&&y.total>1){let V=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;w=`Plan step ${y.current}/${y.total}: ${V}`}else w=ue>0?`${nd()} (step ${ue+1})`:nd();let{getPendingJobSummary:I}=Do(),j=I();j&&(w+=` [${j}]`),Oe=new Bo(w),Oe.start()}let Ce=!0,ke="",Jt=!1,He=new OC,st,bs=Date.now(),$i=!1,Ol=new AbortController,Pl=setInterval(()=>{let w=Date.now()-bs;if(w>=ud)He._clearCursorLine(),P(`${p.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${p.reset}`),Ol.abort();else if(w>=dw&&!$i){$i=!0,He._clearCursorLine();let y=fl.fast?.[In()],I=Z>0?` (retry ${Z+1}/${Ka})`:"",j=Math.round((ud-w)/1e3);P(`${p.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${I}${p.reset}`),y&&y!==kn()?console.log(`${p.dim} \u{1F4A1} Will auto-switch to ${y} in ~${j}s if no tokens arrive${p.reset}`):console.log(`${p.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${j}s${p.reset}`)}},5e3);Pl.unref?.();let Zt="",vn=null;try{let w=i?[]:Ew(Bt()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),I=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),j;El?j=[]:Qs()?j=w.filter(Q=>_w.has(Q.function.name)):ge&&xe==="plan"?(j=w.filter(Q=>y.has(Q.function.name)),pt&&(Vt||Ut>=Yo)&&(j=[])):ge&&xe==="verify"?j=w.filter(Q=>I.has(Q.function.name)):j=w;let V=Ja(),pe=new AbortController;if(V&&V.addEventListener("abort",()=>pe.abort(),{once:!0}),Ol.signal.addEventListener("abort",()=>pe.abort(),{once:!0}),st=await Ya(b,j,{signal:pe.signal,...xn?{model:xn}:{},onThinkingToken:()=>{bs=Date.now(),$i=!1,rt?.onThinkingToken&&rt.onThinkingToken()},onToken:Q=>{if(bs=Date.now(),$i=!1,rt?.onToken){rt.onToken(Q),ke+=Q;return}if(ke+=Q,!Jt&&ke.length>400&&ke.length%250<Q.length+1){let F=gd(ke,3);F.truncated&&(Jt=!0,He._clearCursorLine?.(),P(`${p.yellow} \u26A0 LLM stream loop detected (${F.repeatCount}\xD7 repeated) \u2014 suppressing display${p.reset}`))}Jt||(Zt+=Q,process.stdout.isTTY?vn||(vn=setTimeout(()=>{Zt&&He&&He.push(Zt),Zt="",vn=null},50),vn.unref?.()):(He.push(Zt),Zt=""),Ce&&($&&!$._paused?$.pause():Oe&&Oe.stop(),we||(we=!0),He.startCursor(),Ce=!1))}}),!st||typeof st!="object")throw new Error("Provider returned an empty response (no content/tool_calls)")}catch(w){if(clearInterval(Pl),vn&&(clearTimeout(vn),vn=null),Zt&&He&&(He.push(Zt),Zt=""),$&&!$._paused&&$.pause(),Oe&&Oe.stop(),He.stopCursor(),Ol.signal.aborted&&!Ja()?.aborted){if(Z++,Z>Ka){if(X<1){X++,qo("Stale retries exhausted \u2014 last-resort force-compress...",p.yellow);let C=Bt(),{messages:M,tokensRemoved:A}=Nn(b,C);b=M,A>50&&P(`${p.dim} [force-compressed \u2014 ~${A} tokens freed]${p.reset}`),Z=0,ut--;continue}$&&($.stop(),$=null);let F=await zA();if(F.action==="quit"){k(null),je(ue,Pe,H,Ee,Ne),$e(S);break}F.action==="switch"&&(sd(`${F.provider}:${F.model}`),console.log(`${p.green} \u2713 Switched to ${F.provider}:${F.model}${p.reset}`)),Z=0,ut--;continue}let pe=Z===1?3e3:5e3;if(Z>=1&&qe<1){qe++,qo(`Stale retry ${Z}/${Ka} \u2014 force-compressing before retry...`,p.yellow);let F=Bt(),{messages:C,tokensRemoved:M}=Nn(b,F,!0);if(b=C,M>0&&M>50&&P(`${p.dim} [force-compressed \u2014 ~${M} tokens freed]${p.reset}`),cA){let A=fl.fast?.[In()];A&&A!==kn()&&(sd(`${In()}:${A}`),console.log(`${p.cyan} \u26A1 Auto-switched to ${A} to avoid further stale timeouts${p.reset}`),console.log(`${p.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${p.reset}`))}}else P(`${p.yellow} \u26A0 Stale retry ${Z}/${Ka} \u2014 retrying in ${pe/1e3}s...${p.reset}`);let Q=new Bo(`Waiting ${pe/1e3}s before retry...`);Q.start(),await new Promise(F=>setTimeout(F,pe)),Q.stop(),ut--;continue}if(w.name==="AbortError"||w.name==="CanceledError"||w.message?.includes("canceled")||w.message?.includes("aborted")){$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne),$e(S);break}let y=w.message.includes("Provider returned an empty response"),I=w.message;if(w.code==="ECONNREFUSED"||w.message.includes("ECONNREFUSED"))I="Connection refused \u2014 please check your internet connection or API endpoint";else if(w.code==="ENOTFOUND"||w.message.includes("ENOTFOUND"))I="Network error \u2014 could not reach the API server. Please check your connection";else if(w.code==="ETIMEDOUT"||w.message.includes("timeout"))I="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"))I="Authentication failed \u2014 please check your API key in the .env file";else if(w.message.includes("403")||w.message.includes("Forbidden"))I="Access denied \u2014 your API key may not have permission for this model";else if(w.message.includes("404")){let pe=kn?kn():"unknown",Q=M=>M.includes(":")&&M.split(":")[0].match(/^[a-z]+$/)&&!M.split(":")[1].includes(":")?M.split(":").slice(1).join(":"):M;be.add(Q(pe));let C=(()=>{let M=[];process.env.NEX_FALLBACK_MODEL&&M.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:A}=Dr(),N=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let G of N){let he=A(G);he&&!M.includes(he)&&M.push(he)}}catch{}return M.filter(A=>!be.has(Q(A)))})()[0];if(C){console.log(`${p.yellow} \u26A0 Model ${pe} unavailable (404) \u2014 switching to ${C}${p.reset}`),sd(C),Zb(C),ut--;continue}I=`Model not found (404): ${pe} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${p.red} \u2717 ${I}${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne),$e(S);break}else if(w.message.includes("400")){if(X<3&&R<ce){X++,R++;let pe=ue===0&&X===1,Q=pe||X===3||qe>0;if(pe){X=3;let A=w.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);qo(`Bad request (400) \u2014 ${A||"system prompt too large"}, compressing...`,p.yellow)}else qo(Q?`Bad request (400) \u2014 nuclear compression (attempt ${X}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${X}/3)`,p.yellow);let F=Bt(),{messages:C,tokensRemoved:M}=Nn(b,F,Q);b=C,M>50&&P(`${p.dim} [force-compressed \u2014 ~${M} tokens freed]${p.reset}`),ut--;continue}{let pe=b.find(N=>N.role==="system"),Q=b.find(N=>N.role==="user"&&!String(N.content).startsWith("[SYSTEM")&&!String(N.content).startsWith("BLOCKED:")),F=[pe,Q].filter(Boolean),{getUsage:C}=Pn(),M=Pn().estimateMessagesTokens(F),A=Pn().estimateMessagesTokens(b);if(M<A){let N=[],G=S.filter(D=>D.role==="assistant"&&typeof D.content=="string"&&D.content.trim().length>30).slice(-5).map(D=>D.content.trim().slice(0,300).replace(/\n+/g," "));G.length>0&&N.push(`Key findings:
1537
+ Next step: make the worktree clean and be on the required branch, then re-run the automation.`,st={role:"assistant",content:Ge};S.push(st),_e(S),bt(S),console.log(Ge);return}if(!Rd){let ye={role:"user",content:"[SYSTEM] This is a gated automation workflow. In your final summary, use these exact labels (one per line): Preflight:, Preflight output:, Branch:, Chosen task: (or Selected improvement: / no safe task found), Files changed:, Verification:, Commit:, Push:, Final git status:, Remaining risk:. If any field is unknown or not run, write that explicitly. Do not claim safety, verification, commit, push, or git status checks without evidence from tool output."};S.push(ye),b.push(ye),Rd=!0}}await RA(b,S);let ce=0,Sn=0,Ae=new Map,W=new Set,ve=new Set,ro=[],io=[],Qo=new Set,ao=0,Zd=0,vl=0,He=0,Ne=Date.now(),b0=new oC(YC),El=()=>ro.length>0||io.length>0,w0=ni,ht=n.skillLoop?10:1,_0=3*ht,$0=5*ht,Qd=Dd,k0=5*ht,x0=8*ht,S0=Pw,v0=(he?6:4)*ht,E0=(he?10:7)*ht,Tl=tl,T0=(he?5:3)*ht,gi=(he?8:5)*ht,R0=Nw,C0=(he?4:3)*ht,A0=(he?6:4)*ht,O0=3*ht,P0=4*ht,lo=jn,N0=(he?6:4)*ht,M0=(he?10:8)*ht,co=(he?12:10)*ht,L0=25,gs=0,I0=10*ht,j0=15*ht,ys=0,ef=5*ht,bs=0,D0=2*ht,q0=3,Rl=!1,Cl=0,yi=!1,Al=0,er=10,F0=16,tf=n.skillLoop?999:o.investigationCap,bi=async()=>{let{hasPendingOrCompletedJobs:le,getPendingJobSummary:ye}=qo();if(le()){if(ye()){let Oe=Date.now()+45e3;for(process.stderr.write(`${p.cyan} \u23F3 Waiting for background agents to finish\u2026${p.reset}
1538
+ `);ye()&&Date.now()<Oe;)await new Promise(Se=>setTimeout(Se,500).unref()),Za(S,b)}Za(S,b),S.length>0&&_e(S)}},Jn=typeof t=="string"?t.trim():"",nf=Jn.length>0&&/^\s*(analyze|analyse|explain|describe|review|audit|summari[sz]e|list|understand|document|documentation|docs|what is|what does|how does|show me|show the|show all|tell me about)/i.test(Jn)&&!/\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(Jn),wi=Jn.length>0&&/\b(analyze|analyse|explain|describe|review|audit|summari[sz]e|understand|document|scan|count|inventory|map|list|identify)\b/i.test(Jn)&&/\b(create|write|generate|produce|output)\b/i.test(Jn)&&/\b([A-Z0-9_-]+\.md|markdown|report|summary|overview|architecture|audit|table|documentation|docs|inventory|catalog)\b/i.test(Jn)&&!/\b(fix|bug|crash|error|implement|add(?!\s+(?:to|into)\b)|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|delete|remove|install|setup|deploy|run)\b/i.test(Jn),dt,Lt=n.maxIterations||(he?ls(xe):wd);nf&&(Lt=Math.min(Lt,4),P(`${p.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${Lt}${p.reset}`));let Ol=0,sf=3,_i=!1,$i=0,Pl=!1;e:for(;;){for(_i=!1,dt=0;dt<Lt&&!Qa()?.aborted;dt++){Za(S,b);{let w=Bt(),y=wn(b,w),M=ce===0?65:78;if(y.percentage>=M){if(W.size>0||he&&xe!=="plan"){let de=cC(S,{filesModified:W,currentPhase:he?xe:null});if(de){let Q=b.findIndex(C=>C._progressSnapshot);Q!==-1&&b.splice(Q,1);let F=b.findIndex(C=>C.role==="system");b.splice(F+1,0,de)}}let{messages:j,tokensRemoved:V}=Nn(b,w,ce===0);if(V>0&&(b=j,V>50&&console.log(`${p.dim} [auto-compressed \u2014 ~${V} tokens freed, now ${Math.round(wn(b,w).percentage)}%]${p.reset}`),an&&W.size>=3)){let de=[...W].map(F=>F.split("/").pop()).slice(0,10).join(", "),Q={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${W.size} files: ${de}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};b.push(Q)}}}if(Xt&&!Et&&Jr<2){Jr++;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."};b.push(w),S.push(w),P(`${p.yellow} \u26A0 Pre-call SSH-blocked nudge #${Jr} injected \u2014 model told to synthesize${p.reset}`)}Xt||(Jr=0);let ye=!0;ce>0&&PC();let Oe=null;if($&&$.isActive())$._paused&&$.resume();else if(!$){let w,y=NC();if(y&&y.total>1){let V=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;w=`Plan step ${y.current}/${y.total}: ${V}`}else w=ce>0?`${od()} (step ${ce+1})`:od();let{getPendingJobSummary:M}=qo(),j=M();j&&(w+=` [${j}]`),Oe=new Wo(w),Oe.start()}let Se=!0,ke="",Zt=!1,Ge=new MC,st,ws=Date.now(),ki=!1,Nl=new AbortController,Ml=setInterval(()=>{let w=Date.now()-ws;if(w>=fd)Ge._clearCursorLine(),P(`${p.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${p.reset}`),Nl.abort();else if(w>=pw&&!ki){ki=!0,Ge._clearCursorLine();let y=hl.fast?.[In()],M=Z>0?` (retry ${Z+1}/${Va})`:"",j=Math.round((fd-w)/1e3);P(`${p.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${M}${p.reset}`),y&&y!==kn()?console.log(`${p.dim} \u{1F4A1} Will auto-switch to ${y} in ~${j}s if no tokens arrive${p.reset}`):console.log(`${p.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${j}s${p.reset}`)}},5e3);Ml.unref?.();let Qt="",vn=null;try{let w=i?[]:Cw(Bt()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),M=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),j;Rl?j=[]:eo()?j=w.filter(Q=>xw.has(Q.function.name)):he&&xe==="plan"?(j=w.filter(Q=>y.has(Q.function.name)),ct&&(Wt||Ut>=Ko)&&(j=[])):he&&xe==="verify"?j=w.filter(Q=>M.has(Q.function.name)):j=w;let V=Qa(),de=new AbortController;if(V&&V.addEventListener("abort",()=>de.abort(),{once:!0}),Nl.signal.addEventListener("abort",()=>de.abort(),{once:!0}),st=await za(b,j,{signal:de.signal,...xn?{model:xn}:{},onThinkingToken:()=>{ws=Date.now(),ki=!1,rt?.onThinkingToken&&rt.onThinkingToken()},onToken:Q=>{if(ws=Date.now(),ki=!1,rt?.onToken){rt.onToken(Q),ke+=Q;return}if(ke+=Q,!Zt&&ke.length>400&&ke.length%250<Q.length+1){let F=bd(ke,3);F.truncated&&(Zt=!0,Ge._clearCursorLine?.(),P(`${p.yellow} \u26A0 LLM stream loop detected (${F.repeatCount}\xD7 repeated) \u2014 suppressing display${p.reset}`))}Zt||(Qt+=Q,process.stdout.isTTY?vn||(vn=setTimeout(()=>{Qt&&Ge&&Ge.push(Qt),Qt="",vn=null},50),vn.unref?.()):(Ge.push(Qt),Qt=""),Se&&($&&!$._paused?$.pause():Oe&&Oe.stop(),ye||(ye=!0),Ge.startCursor(),Se=!1))}}),!st||typeof st!="object")throw new Error("Provider returned an empty response (no content/tool_calls)")}catch(w){if(clearInterval(Ml),vn&&(clearTimeout(vn),vn=null),Qt&&Ge&&(Ge.push(Qt),Qt=""),$&&!$._paused&&$.pause(),Oe&&Oe.stop(),Ge.stopCursor(),Nl.signal.aborted&&!Qa()?.aborted){if(Z++,Z>Va){if(X<1){X++,Bo("Stale retries exhausted \u2014 last-resort force-compress...",p.yellow);let C=Bt(),{messages:L,tokensRemoved:A}=Nn(b,C);b=L,A>50&&P(`${p.dim} [force-compressed \u2014 ~${A} tokens freed]${p.reset}`),Z=0,dt--;continue}$&&($.stop(),$=null);let F=await JA();if(F.action==="quit"){k(null),Me(ce,Ae,W,ve,Ne),_e(S);break}F.action==="switch"&&(rd(`${F.provider}:${F.model}`),console.log(`${p.green} \u2713 Switched to ${F.provider}:${F.model}${p.reset}`)),Z=0,dt--;continue}let de=Z===1?3e3:5e3;if(Z>=1&&qe<1){qe++,Bo(`Stale retry ${Z}/${Va} \u2014 force-compressing before retry...`,p.yellow);let F=Bt(),{messages:C,tokensRemoved:L}=Nn(b,F,!0);if(b=C,L>0&&L>50&&P(`${p.dim} [force-compressed \u2014 ~${L} tokens freed]${p.reset}`),fA){let A=hl.fast?.[In()];A&&A!==kn()&&(rd(`${In()}:${A}`),console.log(`${p.cyan} \u26A1 Auto-switched to ${A} to avoid further stale timeouts${p.reset}`),console.log(`${p.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${p.reset}`))}}else P(`${p.yellow} \u26A0 Stale retry ${Z}/${Va} \u2014 retrying in ${de/1e3}s...${p.reset}`);let Q=new Wo(`Waiting ${de/1e3}s before retry...`);Q.start(),await new Promise(F=>setTimeout(F,de)),Q.stop(),dt--;continue}if(w.name==="AbortError"||w.name==="CanceledError"||w.message?.includes("canceled")||w.message?.includes("aborted")){$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne),_e(S);break}let y=w.message.includes("Provider returned an empty response"),M=w.message;if(w.code==="ECONNREFUSED"||w.message.includes("ECONNREFUSED"))M="Connection refused \u2014 please check your internet connection or API endpoint";else if(w.code==="ENOTFOUND"||w.message.includes("ENOTFOUND"))M="Network error \u2014 could not reach the API server. Please check your connection";else if(w.code==="ETIMEDOUT"||w.message.includes("timeout"))M="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"))M="Authentication failed \u2014 please check your API key in the .env file";else if(w.message.includes("403")||w.message.includes("Forbidden"))M="Access denied \u2014 your API key may not have permission for this model";else if(w.message.includes("404")){let de=kn?kn():"unknown",Q=L=>L.includes(":")&&L.split(":")[0].match(/^[a-z]+$/)&&!L.split(":")[1].includes(":")?L.split(":").slice(1).join(":"):L;we.add(Q(de));let C=(()=>{let L=[];process.env.NEX_FALLBACK_MODEL&&L.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:A}=qr(),N=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let G of N){let me=A(G);me&&!L.includes(me)&&L.push(me)}}catch{}return L.filter(A=>!we.has(Q(A)))})()[0];if(C){console.log(`${p.yellow} \u26A0 Model ${de} unavailable (404) \u2014 switching to ${C}${p.reset}`),rd(C),ew(C),dt--;continue}M=`Model not found (404): ${de} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${p.red} \u2717 ${M}${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne),_e(S);break}else if(w.message.includes("400")){if(X<3&&R<ue){X++,R++;let de=ce===0&&X===1,Q=de||X===3||qe>0;if(de){X=3;let A=w.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);Bo(`Bad request (400) \u2014 ${A||"system prompt too large"}, compressing...`,p.yellow)}else Bo(Q?`Bad request (400) \u2014 nuclear compression (attempt ${X}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${X}/3)`,p.yellow);let F=Bt(),{messages:C,tokensRemoved:L}=Nn(b,F,Q);b=C,L>50&&P(`${p.dim} [force-compressed \u2014 ~${L} tokens freed]${p.reset}`),dt--;continue}{let de=b.find(N=>N.role==="system"),Q=b.find(N=>N.role==="user"&&!String(N.content).startsWith("[SYSTEM")&&!String(N.content).startsWith("BLOCKED:")),F=[de,Q].filter(Boolean),{getUsage:C}=Pn(),L=Pn().estimateMessagesTokens(F),A=Pn().estimateMessagesTokens(b);if(L<A){let N=[],G=S.filter(D=>D.role==="assistant"&&typeof D.content=="string"&&D.content.trim().length>30).slice(-5).map(D=>D.content.trim().slice(0,300).replace(/\n+/g," "));G.length>0&&N.push(`Key findings:
1539
1539
  `+G.map(D=>`- ${D}`).join(`
1540
- `));let he=S.filter(D=>D.role==="tool"&&typeof D.content=="string"&&!D.content.startsWith("BLOCKED:")&&D.content.trim().length>10).slice(-5).map(D=>D.content.trim().split(`
1540
+ `));let me=S.filter(D=>D.role==="tool"&&typeof D.content=="string"&&!D.content.startsWith("BLOCKED:")&&D.content.trim().length>10).slice(-5).map(D=>D.content.trim().split(`
1541
1541
  `).slice(0,8).join(`
1542
- `).slice(0,500));if(he.length>0&&N.push(`Tool results summary:
1543
- `+he.map(D=>`- ${D}`).join(`
1544
- `)),H.size>0){let D=[...H].map(de=>de.split("/").slice(-2).join("/")).join(", ");N.unshift(`Already modified: ${D} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(Ee.size>0){let D=[...Ee].map(de=>de.split("/").slice(-2).join("/")).join(", ");N.push(`Files already investigated: ${D}`)}let ye=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(ye,JSON.stringify({filesWritten:[...H].map(D=>D.split("/").slice(-2).join("/")),filesRead:[...Ee].map(D=>D.split("/").slice(-2).join("/")),isCreationTask:rn,wipeNumber:Xr+1,timestamp:Date.now()},null,2)),N.push(`Session checkpoint: ${ye} \u2014 read it for exact file list`)}catch{}let oe=0;{let de=((typeof Q?.content=="string"?Q.content:Array.isArray(Q?.content)?Q.content.filter(gt=>gt.type==="text").map(gt=>gt.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(gt=>gt.trim()).filter(Boolean),Me=[...H],Ue=de.filter(gt=>!Me.some(Zn=>Zn.endsWith(gt)||gt.endsWith(Zn.split("/").pop())));oe=Ue.length;let it=[...S].reverse().find(gt=>gt.role==="tool"&&typeof gt.content=="string"&&!gt.content.startsWith("BLOCKED:")&&gt.content.length>5),fn={completed:Me.map(gt=>gt.split("/").slice(-2).join("/")),pending:Ue.length>0?Ue:Me.length===0?["(task files not yet identified)"]:[],lastEdit:it?it.content.trim().slice(0,120):null};(fn.completed.length>0||fn.pending.length>0)&&N.unshift(`Work manifest:
1542
+ `).slice(0,500));if(me.length>0&&N.push(`Tool results summary:
1543
+ `+me.map(D=>`- ${D}`).join(`
1544
+ `)),W.size>0){let D=[...W].map(fe=>fe.split("/").slice(-2).join("/")).join(", ");N.unshift(`Already modified: ${D} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(ve.size>0){let D=[...ve].map(fe=>fe.split("/").slice(-2).join("/")).join(", ");N.push(`Files already investigated: ${D}`)}let be=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(be,JSON.stringify({filesWritten:[...W].map(D=>D.split("/").slice(-2).join("/")),filesRead:[...ve].map(D=>D.split("/").slice(-2).join("/")),isCreationTask:an,wipeNumber:Xr+1,timestamp:Date.now()},null,2)),N.push(`Session checkpoint: ${be} \u2014 read it for exact file list`)}catch{}let oe=0;{let fe=((typeof Q?.content=="string"?Q.content:Array.isArray(Q?.content)?Q.content.filter(gt=>gt.type==="text").map(gt=>gt.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(gt=>gt.trim()).filter(Boolean),Le=[...W],Ue=fe.filter(gt=>!Le.some(Zn=>Zn.endsWith(gt)||gt.endsWith(Zn.split("/").pop())));oe=Ue.length;let it=[...S].reverse().find(gt=>gt.role==="tool"&&typeof gt.content=="string"&&!gt.content.startsWith("BLOCKED:")&&gt.content.length>5),fn={completed:Le.map(gt=>gt.split("/").slice(-2).join("/")),pending:Ue.length>0?Ue:Le.length===0?["(task files not yet identified)"]:[],lastEdit:it?it.content.trim().slice(0,120):null};(fn.completed.length>0||fn.pending.length>0)&&N.unshift(`Work manifest:
1545
1545
  ${JSON.stringify(fn,null,2)}`)}if(N.length>0){let D={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1546
1546
  ${N.join(`
1547
1547
  `)}
1548
- Continue implementing the fixes based on these findings.`};F.push(D)}if(Xr>=3){let D=H.size>0?`
1549
- Files modified so far: ${[...H].map(de=>de.split("/").slice(-1)[0]).join(", ")}`:"";P(`${p.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${p.reset}`),console.log(`${p.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${D?p.dim+D:""}${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne,{suppressHint:!0}),$e(S);break}b=F,Xr++,Vs=10+Math.min(oe*3,7),Sd=!0,ol=H.size,rl=!1,on=0,hi=0;for(let[D,de]of jn){let Me=de?.count??de??0;pd(jn,D,Me>=2?Me:1)}for(let[D]of zn)Mn(jn,D)<2&&zn.delete(D);Mt.clear(),eo.clear(),rn&&un>0&&(cn=!0,P(`${p.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${un} edits already made)${p.reset}`));for(let[D]of Qa)pd(Qa,D,mi-1);if(qo(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${A-M} tokens freed)`,p.yellow),Xr>=1){let D=[...jn.entries()].filter(([,it])=>it>=lo).map(([it])=>it.split("/").slice(-1)[0]),de=D.length>0?`
1548
+ Continue implementing the fixes based on these findings.`};F.push(D)}if(Xr>=3){let D=W.size>0?`
1549
+ Files modified so far: ${[...W].map(fe=>fe.split("/").slice(-1)[0]).join(", ")}`:"";P(`${p.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${p.reset}`),console.log(`${p.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${D?p.dim+D:""}${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne,{suppressHint:!0}),_e(S);break}b=F,Xr++,Xs=10+Math.min(oe*3,7),Ed=!0,il=W.size,al=!1,rn=0,mi=0;for(let[D,fe]of jn){let Le=fe?.count??fe??0;md(jn,D,Le>=2?Le:1)}for(let[D]of zn)Mn(jn,D)<2&&zn.delete(D);Mt.clear(),to.clear(),an&&dn>0&&(un=!0,P(`${p.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${dn} edits already made)${p.reset}`));for(let[D]of tl)md(tl,D,gi-1);if(Bo(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${A-L} tokens freed)`,p.yellow),Xr>=1){let D=[...jn.entries()].filter(([,it])=>it>=co).map(([it])=>it.split("/").slice(-1)[0]),fe=D.length>0?`
1550
1550
 
1551
- Files already at read cap \u2014 use grep_search instead: ${D.join(", ")}`:"",Ue={role:"user",content:Kt&&!Et?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${de}`};S.push(Ue),b.push(Ue)}X=0,ut--;continue}}I="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")?I="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(w.message.includes("fetch failed")||w.message.includes("fetch"))&&(I="Network request failed \u2014 please check your internet connection");if(console.log(`${p.red} \u2717 ${I}${p.reset}`),y){$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne),$e(S);break e}if(w.message.includes("429")){if(L++,L>ld){console.log(`${p.red} Rate limit: max retries (${ld}) exceeded. Try again later or use /budget to check your limits.${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne),$e(S);break e}let pe=Math.min(1e4*Math.pow(2,L-1),12e4),Q=new Bo(`Rate limit \u2014 waiting ${Math.round(pe/1e3)}s (retry ${L}/${ld})`);Q.start(),await new Promise(F=>setTimeout(F,pe)),Q.stop();continue}let j=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return $t().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")||j&&(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(U++,U>cd){console.log(`${p.red} Network error: max retries (${cd}) exceeded. Check your connection and try again.
1552
- Use /undo to revert changes made during this session.${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne),$e(S);break e}let pe=Math.min(2e3*Math.pow(2,U-1),3e4),Q=new Bo(`API temporarily unavailable \u2014 retrying in ${Math.round(pe/1e3)}s (${U}/${cd}). Your changes are safe.`);Q.start(),await new Promise(F=>setTimeout(F,pe)),Q.stop(),ut--;continue}$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne),$e(S);break}if(clearInterval(Pl),L=0,U=0,Ce&&($&&!$._paused&&$.pause(),Oe&&Oe.stop()),vn&&(clearTimeout(vn),vn=null),Zt&&He&&(He.push(Zt),Zt=""),ke&&He.flush(),U=0,Z=0,st&&st.usage){let w=st.usage.prompt_tokens||0,y=st.usage.completion_tokens||0;tw(In(),kn(),w,y),O+=w+y,$&&$.setStats({tokens:O})}else if(st&&!st.usage){let w=b.map(j=>typeof j.content=="string"?j.content:Array.isArray(j.content)?j.content.map(V=>typeof V=="string"?V:V.text||"").join(""):"").join(" "),y=rw(w),I=rw(st.content||ke||"");tw(In(),kn(),y,I),O+=y+I,$&&$.setStats({tokens:O})}let{content:nf,tool_calls:co}=st,Xe=co,Nl=!1;if(Array.isArray(co)&&co.length>0){let w=co.filter(y=>y?.function?.name==="ask_user");w.length>0&&(Xe=[w[0]],Nl=co.length!==1,Nl&&P(`${p.yellow} \u26A0 ask_user must run alone \u2014 deferring ${co.length-1} other tool call(s) until the user replies${p.reset}`))}let ki=gd(nf||""),sf=ki.truncated?ki.text:nf;ki.truncated&&P(`${p.yellow} \u26A0 LLM output loop detected (${ki.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${p.reset}`);let xi=VC(sf||""),Je=xi.truncated?xi.text:sf;if(xi.truncated&&P(`${p.yellow} \u26A0 LLM output loop detected (${xi.repeatCount}\xD7 repeated window) \u2014 response truncated${p.reset}`),Array.isArray(Xe)&&Xe.length>0&&mC(Je||"")&&(P(`${p.yellow} \u26A0 Assistant asked the user a direct question in text \u2014 dropping tool calls and waiting for user input${p.reset}`),Xe=[]),gi=!1,Array.isArray(Xe)&&Xe.length>0){let w=ad(In());if(Number.isFinite(w)){let y=w-Sn;if(y<=0){if(Tl++,P(`${p.yellow} \u26A0 Tool-call budget reached (${Sn}/${w}) \u2014 forcing final answer${p.reset}`),ge&&xe==="implement"&&H.size===0&&Ve===0||zr(H,Ve)){let j=`Implementation stalled before edits.
1551
+ Files already at read cap \u2014 use grep_search instead: ${D.join(", ")}`:"",Ue={role:"user",content:Xt&&!Et?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${fe}`};S.push(Ue),b.push(Ue)}X=0,dt--;continue}}M="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")?M="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(w.message.includes("fetch failed")||w.message.includes("fetch"))&&(M="Network request failed \u2014 please check your internet connection");if(console.log(`${p.red} \u2717 ${M}${p.reset}`),y){$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne),_e(S);break e}if(w.message.includes("429")){if(I++,I>ud){console.log(`${p.red} Rate limit: max retries (${ud}) exceeded. Try again later or use /budget to check your limits.${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne),_e(S);break e}let de=Math.min(1e4*Math.pow(2,I-1),12e4),Q=new Wo(`Rate limit \u2014 waiting ${Math.round(de/1e3)}s (retry ${I}/${ud})`);Q.start(),await new Promise(F=>setTimeout(F,de)),Q.stop();continue}let j=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return kt().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")||j&&(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(U++,U>dd){console.log(`${p.red} Network error: max retries (${dd}) exceeded. Check your connection and try again.
1552
+ Use /undo to revert changes made during this session.${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne),_e(S);break e}let de=Math.min(2e3*Math.pow(2,U-1),3e4),Q=new Wo(`API temporarily unavailable \u2014 retrying in ${Math.round(de/1e3)}s (${U}/${dd}). Your changes are safe.`);Q.start(),await new Promise(F=>setTimeout(F,de)),Q.stop(),dt--;continue}$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne),_e(S);break}if(clearInterval(Ml),I=0,U=0,Se&&($&&!$._paused&&$.pause(),Oe&&Oe.stop()),vn&&(clearTimeout(vn),vn=null),Qt&&Ge&&(Ge.push(Qt),Qt=""),ke&&Ge.flush(),U=0,Z=0,st&&st.usage){let w=st.usage.prompt_tokens||0,y=st.usage.completion_tokens||0;sw(In(),kn(),w,y),O+=w+y,$&&$.setStats({tokens:O})}else if(st&&!st.usage){let w=b.map(j=>typeof j.content=="string"?j.content:Array.isArray(j.content)?j.content.map(V=>typeof V=="string"?V:V.text||"").join(""):"").join(" "),y=aw(w),M=aw(st.content||ke||"");sw(In(),kn(),y,M),O+=y+M,$&&$.setStats({tokens:O})}let{content:of,tool_calls:uo}=st,Xe=uo,Ll=!1;if(Array.isArray(uo)&&uo.length>0){let w=uo.filter(y=>y?.function?.name==="ask_user");w.length>0&&(Xe=[w[0]],Ll=uo.length!==1,Ll&&P(`${p.yellow} \u26A0 ask_user must run alone \u2014 deferring ${uo.length-1} other tool call(s) until the user replies${p.reset}`))}let xi=bd(of||""),rf=xi.truncated?xi.text:of;xi.truncated&&P(`${p.yellow} \u26A0 LLM output loop detected (${xi.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${p.reset}`);let Si=ZC(rf||""),Je=Si.truncated?Si.text:rf;if(Si.truncated&&P(`${p.yellow} \u26A0 LLM output loop detected (${Si.repeatCount}\xD7 repeated window) \u2014 response truncated${p.reset}`),Array.isArray(Xe)&&Xe.length>0&&bC(Je||"")&&(P(`${p.yellow} \u26A0 Assistant asked the user a direct question in text \u2014 dropping tool calls and waiting for user input${p.reset}`),Xe=[]),yi=!1,Array.isArray(Xe)&&Xe.length>0){let w=cd(In());if(Number.isFinite(w)){let y=w-Sn;if(y<=0){if(Cl++,P(`${p.yellow} \u26A0 Tool-call budget reached (${Sn}/${w}) \u2014 forcing final answer${p.reset}`),he&&xe==="implement"&&W.size===0&&He===0||Fo(W,He)){let j=`Implementation stalled before edits.
1553
1553
 
1554
1554
  The implementation phase reached the tool-call budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,V={role:"assistant",content:j};S.push(V),b.push(V),console.log(`
1555
- ${j}`),$e(S),vt(S);break e}let I={role:"user",content:uw(Sn,w)};if(S.push(I),b.push(I),El=!0,Tl>=2){let j={role:"assistant",content:"I reached the tool-call budget and cannot safely continue executing tools. Based on the information gathered so far, I cannot complete more investigation without risking a tool loop."};S.push(j),console.log(`
1556
- ${j.content}`),$e(S),vt(S),await yi();return}continue}Xe.length>y&&(P(`${p.yellow} \u26A0 Tool-call batch trimmed from ${Xe.length} to ${y} (budget ${Sn}/${w})${p.reset}`),Xe=Xe.slice(0,y),gi=!0)}}let uo={role:"assistant",content:Je||""};if(Xe&&Xe.length>0&&(uo.tool_calls=Xe),S.push(uo),b.push(uo),ge&&xe==="plan"&&pt&&Xe&&Xe.length>0&&(Vt&&String(Je||ke||"").trim()||ul(Je||ke||""))&&(delete uo.tool_calls,Xe=[]),ef&&!za(Je||ke||"")&&H.size===0&&Ve===0){P(`${p.green} \u2713 Analysis-only early exit: ${(Je||"").length} chars produced, no file changes${p.reset}`),uo.tool_calls&&delete uo.tool_calls,je(ue,Pe,H,Ee,Ne),$e(S);break e}if(!Et&&Je&&Xe&&Xe.length>0){let w=fd(Je);if(w){Et=!0,Ft=w.slice(0,120),ln=0,cn=!1,_n=0,P(`${p.yellow} \u26A1 Root cause in model analysis: ${Ft} \u2014 fix phase (read budget: 3)${p.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${Ft}. Read only the file that needs fixing, then edit it. Do not read other files.`};S.push(y),b.push(y)}}if(!Xe||Xe.length===0){let w=(Je||"").trim().length>0||ke.trim().length>0;if(i&&w&&(a==="English"&&NA(Je||ke||"")!=="English"||MA(t,Je||ke||"")))try{let C=[b[0],{role:"user",content:`Rewrite the text below to be a clean, direct answer.
1555
+ ${j}`),_e(S),bt(S);break e}let M={role:"user",content:fw(Sn,w)};if(S.push(M),b.push(M),Rl=!0,Cl>=2){let j={role:"assistant",content:"I reached the tool-call budget and cannot safely continue executing tools. Based on the information gathered so far, I cannot complete more investigation without risking a tool loop."};S.push(j),console.log(`
1556
+ ${j.content}`),_e(S),bt(S),await bi();return}continue}Xe.length>y&&(P(`${p.yellow} \u26A0 Tool-call batch trimmed from ${Xe.length} to ${y} (budget ${Sn}/${w})${p.reset}`),Xe=Xe.slice(0,y),yi=!0)}}let fo={role:"assistant",content:Je||""};if(Xe&&Xe.length>0&&(fo.tool_calls=Xe),S.push(fo),b.push(fo),he&&xe==="plan"&&ct&&Xe&&Xe.length>0&&(Wt&&String(Je||ke||"").trim()||fl(Je||ke||""))&&(delete fo.tool_calls,Xe=[]),nf&&!Ka(Je||ke||"")&&W.size===0&&He===0){P(`${p.green} \u2713 Analysis-only early exit: ${(Je||"").length} chars produced, no file changes${p.reset}`),fo.tool_calls&&delete fo.tool_calls,Me(ce,Ae,W,ve,Ne),_e(S);break e}if(!Et&&Je&&Xe&&Xe.length>0){let w=hd(Je);if(w){Et=!0,Ft=w.slice(0,120),cn=0,un=!1,_n=0,P(`${p.yellow} \u26A1 Root cause in model analysis: ${Ft} \u2014 fix phase (read budget: 3)${p.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${Ft}. Read only the file that needs fixing, then edit it. Do not read other files.`};S.push(y),b.push(y)}}if(!Xe||Xe.length===0){let w=(Je||"").trim().length>0||ke.trim().length>0;if(i&&w&&(a==="English"&&jA(Je||ke||"")!=="English"||DA(t,Je||ke||"")))try{let C=[b[0],{role:"user",content:`Rewrite the text below to be a clean, direct answer.
1557
1557
  - Keep any code blocks exactly the same (do not change code).
1558
1558
  - Remove any claims about inspecting the workspace, running commands, searching files, creating files, installing packages, or other internal process.
1559
1559
  - If any prose is not in English, translate the prose to English.
@@ -1561,78 +1561,84 @@ ${j.content}`),$e(S),vt(S),await yi();return}continue}Xe.length>y&&(P(`${p.yello
1561
1561
 
1562
1562
  ---
1563
1563
 
1564
- `+(Je||ke||"")}],A=((await Ya(C,[],{}))?.content||"").trim();if(A){let N=S[S.length-1];N&&N.role==="assistant"&&(N.content=A);let G=b[b.length-1];G&&G.role==="assistant"&&(G.content=A),console.log(`\\n${A}`)}}catch{}let y=!1;if(Kt&&w&&(Va>=2?P(`${p.yellow} \u26A0 SSH permanently blocked after ${Va} storm warnings \u2014 no further SSH calls allowed${p.reset}`):(Kt=!1,on=Qo-4,y=!0)),y&&w){let F=(Je||"").trim();if(F.endsWith("?")||/\b(Where |Please |Can you|Should I)\b/.test(F.slice(-200))){let M={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};b.push(M),S.push(M);continue}}if(!w&&ue>0&&ut<yd-1){let F={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."};b.push(F),S.push(F);continue}let I=/can.?t use.*tool|Tool.?Budget|cannot.*access|no.*tool.*access/i;if(w&&ut<3&&I.test((Je||"").slice(0,600)))if(Sd&&Vs<=0||Kt){P(`${p.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${p.reset}`);let C={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."};b.push(C),S.push(C);continue}else{P(`${p.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${p.reset}`);let C={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."};b.push(C),S.push(C);continue}if(n.skillLoop&&w&&ue>3&&_i<5){let F=(Je||ke||"").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(F.slice(-600))){_i=(_i||0)+1,P(`${p.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${_i}${p.reset}`);let M={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."};b.push(M),S.push(M);continue}}if((ge&&xe==="implement"||zr(H,Ve))&&$n()&&w&&H.size===0&&Ve===0){if(si<3){si++;let M={role:"user",content:"[SYSTEM] Implementation is not complete: you produced prose but made no file changes. Do not finish or restate the plan. In the next response, either call read_file with line_start/line_end on the concrete implementation file from the accepted plan, or call edit_file/patch_file/write_file to make the scoped change. Keep prose minimal and include at least one tool call."};S.push(M),b.push(M),P(`${p.yellow} \u26A0 Implement phase made no progress \u2014 nudging for concrete tool use (${si}/3)${p.reset}`);continue}let F=`Implementation stalled before edits.
1564
+ `+(Je||ke||"")}],A=((await za(C,[],{}))?.content||"").trim();if(A){let N=S[S.length-1];N&&N.role==="assistant"&&(N.content=A);let G=b[b.length-1];G&&G.role==="assistant"&&(G.content=A),console.log(`\\n${A}`)}}catch{}let y=!1;if(Xt&&w&&(Xa>=2?P(`${p.yellow} \u26A0 SSH permanently blocked after ${Xa} storm warnings \u2014 no further SSH calls allowed${p.reset}`):(Xt=!1,rn=er-4,y=!0)),y&&w){let F=(Je||"").trim();if(F.endsWith("?")||/\b(Where |Please |Can you|Should I)\b/.test(F.slice(-200))){let L={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};b.push(L),S.push(L);continue}}if(!w&&ce>0&&dt<wd-1){let F={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."};b.push(F),S.push(F);continue}let M=/can.?t use.*tool|Tool.?Budget|cannot.*access|no.*tool.*access/i;if(w&&dt<3&&M.test((Je||"").slice(0,600)))if(Ed&&Xs<=0||Xt){P(`${p.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${p.reset}`);let C={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."};b.push(C),S.push(C);continue}else{P(`${p.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${p.reset}`);let C={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."};b.push(C),S.push(C);continue}if(n.skillLoop&&w&&ce>3&&$i<5){let F=(Je||ke||"").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(F.slice(-600))){$i=($i||0)+1,P(`${p.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${$i}${p.reset}`);let L={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."};b.push(L),S.push(L);continue}}if((he&&xe==="implement"||Fo(W,He))&&$n()&&w&&W.size===0&&He===0){if(si<3){si++;let L={role:"user",content:"[SYSTEM] Implementation is not complete: you produced prose but made no file changes. Do not finish or restate the plan. In the next response, either call read_file with line_start/line_end on the concrete implementation file from the accepted plan, or call edit_file/patch_file/write_file to make the scoped change. Keep prose minimal and include at least one tool call."};S.push(L),b.push(L),P(`${p.yellow} \u26A0 Implement phase made no progress \u2014 nudging for concrete tool use (${si}/3)${p.reset}`);continue}let F=`Implementation stalled before edits.
1565
1565
 
1566
1566
  The plan phase completed, but the implementation phase produced text-only responses without changing files. Stopping without commit or push so the workflow does not falsely report success.`,C={role:"assistant",content:F};S.push(C),b.push(C),console.log(`
1567
- ${F}`),je(ue,Pe,H,Ee,Ne),$e(S),vt(S);break e}if(w&&hC(Je||ke||"")&&!n.skillLoop&&!Qs()&&!ge&&!an){P(`${p.green} \u2713 Explicit final summary exit: no follow-up provider call needed${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne),$e(S),vt(S),await yi();return}if($n()&&!n.skillLoop&&H.size===0&&Ve===0&&Ee.size===0&&ue===0&&w&&!ge){P(`${p.green} \u2713 Headless direct response exit: text-only response received${p.reset}`),$e(S);break e}if($n()&&!n.skillLoop&&!ge&&(H.size>0||Ve>0)&&Vn&&!Sl()&&Dn<2){Dn++;let F=await gl(H),C=await ci(H),M={role:"user",content:gw(H,F,C)+`
1568
- Do not write a final completion summary until this verification evidence exists.`};S.push(M),b.push(M),P(`${p.yellow} \u26A0 Headless completion blocked \u2014 verification required (${Dn}/2)${p.reset}`);continue}if($n()&&!n.skillLoop&&(H.size>0||Ve>0)&&w&&!za(Je||ke||"")&&ue>=1&&(!Vn||Sl())&&!ge){P(`${p.green} \u2713 Headless early exit: ${H.size} file(s) modified (+ ${Ve} bash writes), substantive text response received${p.reset}`),je(ue,Pe,H,Ee,Ne),$e(S);break e}let V=yA(zo)?1:2;if(ge&&xe==="plan"&&ps>=V){P(`${p.cyan} \u21B3 Plan phase: ${ps} consecutive blocks (last: ${zo||"unknown"}) \u2014 auto-advancing to implement${p.reset}`),ps=0,zo=null;let F=await Fo("implement","[auto-advance: task only requires direct action]");if(F){S.push(F),b.push(F),ut=0,Lt=ls("implement");continue}}if(ge&&w){let F=(Je||ke||"").trim();if(xe==="plan"){if(pt&&/\bno safe task found\b/i.test(F)){if(!Mw(F)){fs++;let ye={role:"user",content:Kn()+"\n\nDo not answer `no safe task found` before reading/searching backlog evidence unless you name a concrete blocker such as dirty worktree, wrong branch, missing files, or unavailable permissions. If git preflight is clean, inspect the listed backlog/UI files and select one scoped improvement."};S.push(ye),b.push(ye),P(`${p.yellow} \u26A0 Bounded backlog plan: premature no-safe-task response \u2014 requiring backlog evidence${p.reset}`);continue}P(`${p.yellow} \u26A0 Bounded backlog plan: no safe task found \u2014 exiting gracefully${p.reset}`),je(ue,Pe,H,Ee,Ne),$e(S);break e}if(pt&&!ul(F)){if(Vt&&wA(F)){fs++;let D={role:"user",content:Kn({blocked:!0})+`
1567
+ ${F}`),Me(ce,Ae,W,ve,Ne),_e(S),bt(S);break e}if(w&&yC(Je||ke||"")&&!n.skillLoop&&!eo()&&!he&&!ln){P(`${p.green} \u2713 Explicit final summary exit: no follow-up provider call needed${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne),_e(S),bt(S),await bi();return}if($n()&&!n.skillLoop&&W.size===0&&He===0&&ve.size===0&&ce===0&&w&&!he){P(`${p.green} \u2713 Headless direct response exit: text-only response received${p.reset}`),_e(S);break e}if($n()&&!n.skillLoop&&!he&&(W.size>0||He>0)&&Vn&&!El()&&Dn<2){Dn++;let F=await bl(W),C=await ui(W),L={role:"user",content:ww(W,F,C)+`
1568
+ Do not write a final completion summary until this verification evidence exists.`};S.push(L),b.push(L),P(`${p.yellow} \u26A0 Headless completion blocked \u2014 verification required (${Dn}/2)${p.reset}`);continue}if($n()&&!n.skillLoop&&(W.size>0||He>0)&&w&&!Ka(Je||ke||"")&&ce>=1&&(!Vn||El())&&!he){P(`${p.green} \u2713 Headless early exit: ${W.size} file(s) modified (+ ${He} bash writes), substantive text response received${p.reset}`),Me(ce,Ae,W,ve,Ne),_e(S);break e}let V=_A(Vo)?1:2;if(he&&xe==="plan"&&ps>=V){P(`${p.cyan} \u21B3 Plan phase: ${ps} consecutive blocks (last: ${Vo||"unknown"}) \u2014 auto-advancing to implement${p.reset}`),ps=0,Vo=null;let F=await Uo("implement","[auto-advance: task only requires direct action]");if(F){S.push(F),b.push(F),dt=0,Lt=ls("implement");continue}}if(he&&w){let F=(Je||ke||"").trim();if(xe==="plan"){if(ct&&/\bno safe task found\b/i.test(F)){if(!jw(F)){fs++;let be={role:"user",content:Kn()+"\n\nDo not answer `no safe task found` before reading/searching backlog evidence unless you name a concrete blocker such as dirty worktree, wrong branch, missing files, or unavailable permissions. If git preflight is clean, inspect the listed backlog/UI files and select one scoped improvement."};S.push(be),b.push(be),P(`${p.yellow} \u26A0 Bounded backlog plan: premature no-safe-task response \u2014 requiring backlog evidence${p.reset}`);continue}P(`${p.yellow} \u26A0 Bounded backlog plan: no safe task found \u2014 exiting gracefully${p.reset}`),Me(ce,Ae,W,ve,Ne),_e(S);break e}if(ct&&!fl(F)){if(Wt&&xA(F)){fs++;let D={role:"user",content:Kn({blocked:!0})+`
1569
1569
 
1570
- The backlog evidence has already been read into the conversation. Do not describe tool calls, JSON tool calls, or read_file calls in text. Write only the required bounded plan labels now.`};S.push(D),b.push(D),P(`${p.yellow} \u26A0 Bounded backlog plan: textual tool-call attempt after evidence prefetch${p.reset}`);continue}if(Nw(F)){fs++;let D={role:"user",content:Kn({blocked:Vt})+"\n\nYour previous plan used markdown headings. Rewrite the same plan using exact label lines, for example `Selected improvement:` instead of `### Selected improvement`."};S.push(D),b.push(D),P(`${p.yellow} \u26A0 Bounded backlog plan: heading labels rejected \u2014 requesting exact labels${p.reset}`);continue}if(Pw(F)){fs++;let D={role:"user",content:Kn({blocked:Ut>=Yo})+`
1570
+ The backlog evidence has already been read into the conversation. Do not describe tool calls, JSON tool calls, or read_file calls in text. Write only the required bounded plan labels now.`};S.push(D),b.push(D),P(`${p.yellow} \u26A0 Bounded backlog plan: textual tool-call attempt after evidence prefetch${p.reset}`);continue}if(Iw(F)){fs++;let D={role:"user",content:Kn({blocked:Wt})+"\n\nYour previous plan used markdown headings. Rewrite the same plan using exact label lines, for example `Selected improvement:` instead of `### Selected improvement`."};S.push(D),b.push(D),P(`${p.yellow} \u26A0 Bounded backlog plan: heading labels rejected \u2014 requesting exact labels${p.reset}`);continue}if(Lw(F)){fs++;let D={role:"user",content:Kn({blocked:Ut>=Ko})+`
1571
1571
 
1572
- Your previous plan was rejected because it invented an off-task React/list-component issue or referenced files that do not exist in this repository. Use only the prompt-named backlog evidence above and select one nex-note notation-editor workflow improvement.`};S.push(D),b.push(D),P(`${p.yellow} \u26A0 Bounded backlog plan: rejected off-topic selected improvement${p.reset}`);continue}if(fs++,fs>=(Vt?4:2)||Ut>=Yo){let D=`no safe task found
1572
+ Your previous plan was rejected because it invented an off-task React/list-component issue or referenced files that do not exist in this repository. Use only the prompt-named backlog evidence above and select one nex-note notation-editor workflow improvement.`};S.push(D),b.push(D),P(`${p.yellow} \u26A0 Bounded backlog plan: rejected off-topic selected improvement${p.reset}`);continue}if(fs++,fs>=(Wt?4:2)||Ut>=Ko){let D=`no safe task found
1573
1573
 
1574
- Bounded backlog planning requires an explicit selected-improvement decision with files and verification evidence. Stopping before implementation because the plan response did not follow the required template.`,de={role:"assistant",content:D};S.push(de),console.log(`
1575
- ${D}`),$e(S),vt(S);break e}let oe={role:"user",content:Kn({blocked:Ut>=Yo})};S.push(oe),b.push(oe),P(`${p.yellow} \u26A0 Bounded backlog plan: missing selected-improvement decision \u2014 re-prompting in plan phase${p.reset}`);continue}let C=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files)\b/i,M=Lw(F,jn).length===0,A=ei.size>0,N=ti.size>0,G=F.length>1500;if($n()&&M&&!A&&!N&&!G&&C.test(F)){P(`${p.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${p.reset}`),process.stdout.isTTY&&process.stderr.write(`${p.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${p.reset}
1576
- `),je(ue,Pe,H,Ee,Ne),$e(S);break e}let he=await Fo("implement",F);if(he){S.push(he),b.push(he),ut=0,Lt=ls("implement");continue}}else if(xe==="implement"&&(H.size>0||Ve>0)){let C=S.find(N=>N.role==="user"),M=typeof C?.content=="string"?C.content:"",A=await Fo("verify",F,H,M);if(A){S.push(A),b.push(A),ut=0,Lt=Math.min(ls("verify")+Math.max(0,(H.size-2)*2),20);continue}}else if(xe==="verify"){let C=/\bPASS\b/i.test(F.slice(0,500)),A=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(F.slice(0,500)),N=Ko>0||b.some(G=>G.role==="assistant"&&typeof G.content=="string"&&/\bPASS\b/i.test(G.content.slice(0,500)));if($n()&&!n.skillLoop&&N&&!A&&!za(F)){if(P(`${p.green} \u2713 Verification phase complete (headless substantive summary)${p.reset}`),an&&!Od(F))try{let G=oo.length>0?oo.join(" | "):ro.length>0?`post-edit read: ${ro.slice(0,8).join(", ")}`:"not run; state this explicitly and do not claim tests/build/checks passed",he=Ae&&Ae.command||"git status --short --branch",ye=Ae&&String(Ae.raw||"").trim()||"(missing preflight output)",oe=Ae&&Ae.branch||mw||"(unknown)",D=[...H].slice(0,24).join(", ")||(Ve>0?"files changed by shell commands":"(none)"),de=Gr?"detected (git commit succeeded per bash output)":"not detected",Me=ll?"detected (git push succeeded per bash output)":ds?"attempted (see tool output)":"not detected",Ue=Zs?`${Qr}
1577
- ${Zs}`:"(not checked in this run)",it=["Write a final automation report using EXACT labels (one per line):",`Preflight: ${he}`,"Preflight output: (paste exactly; do not paraphrase)",ye,`Branch: ${oe}`,"Chosen task: (what you actually did; or `no safe task found`)",`Files changed: ${D}`,`Verification: ${G}`,`Commit: ${de}`,`Push: ${Me}`,`Final git status: ${Ue}`,"Remaining risk: (if any; otherwise `none`)","","Hard rules: do not claim verification/commit/push/git status checks without evidence from tool output. If unknown, write unknown."].join(`
1578
- `),fn=[...b,{role:"user",content:it}],Zn=((await Ya(fn,[],{}))?.content||"").trim();Zn&&(console.log(`
1579
- ${Zn}`),S.push({role:"user",content:it},{role:"assistant",content:Zn}),b.push({role:"user",content:it},{role:"assistant",content:Zn}))}catch{}je(ue,Pe,H,Ee,Ne),$e(S),vt(S);break e}if(A&&Go<3){Go++;let G={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1574
+ Bounded backlog planning requires an explicit selected-improvement decision with files and verification evidence. Stopping before implementation because the plan response did not follow the required template.`,fe={role:"assistant",content:D};S.push(fe),console.log(`
1575
+ ${D}`),_e(S),bt(S);break e}let oe={role:"user",content:Kn({blocked:Ut>=Ko})};S.push(oe),b.push(oe),P(`${p.yellow} \u26A0 Bounded backlog plan: missing selected-improvement decision \u2014 re-prompting in plan phase${p.reset}`);continue}let C=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files)\b/i,L=Dw(F,jn).length===0,A=ei.size>0,N=ti.size>0,G=F.length>1500;if($n()&&L&&!A&&!N&&!G&&C.test(F)){P(`${p.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${p.reset}`),process.stdout.isTTY&&process.stderr.write(`${p.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${p.reset}
1576
+ `),Me(ce,Ae,W,ve,Ne),_e(S);break e}let me=await Uo("implement",F);if(me){S.push(me),b.push(me),dt=0,Lt=ls("implement");continue}}else if(xe==="implement"&&(W.size>0||He>0)){let C=S.find(N=>N.role==="user"),L=typeof C?.content=="string"?C.content:"",A=await Uo("verify",F,W,L);if(A){S.push(A),b.push(A),dt=0,Lt=Math.min(ls("verify")+Math.max(0,(W.size-2)*2),20);continue}}else if(xe==="verify"){let C=/\bPASS\b/i.test(F.slice(0,500)),A=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(F.slice(0,500)),N=Xo>0||b.some(G=>G.role==="assistant"&&typeof G.content=="string"&&/\bPASS\b/i.test(G.content.slice(0,500)));if($n()&&!n.skillLoop&&N&&!A&&!Ka(F)){if(P(`${p.green} \u2713 Verification phase complete (headless substantive summary)${p.reset}`),ln&&!Nd(F))try{let G=ro.length>0?ro.join(" | "):io.length>0?`post-edit read: ${io.slice(0,8).join(", ")}`:"not run; state this explicitly and do not claim tests/build/checks passed",me=Pe&&Pe.command||"git status --short --branch",be=Pe&&String(Pe.raw||"").trim()||"(missing preflight output)",oe=Pe&&Pe.branch||bw||"(unknown)",D=[...W].slice(0,24).join(", ")||(He>0?"files changed by shell commands":"(none)"),fe=Yr?"detected (git commit succeeded per bash output)":"not detected",Le=ul?"detected (git push succeeded per bash output)":ds?"attempted (see tool output)":"not detected",Ue=Qs?`${Qr}
1577
+ ${Qs}`:"(not checked in this run)",it=["Write a final automation report using EXACT labels (one per line):",`Preflight: ${me}`,"Preflight output: (paste exactly; do not paraphrase)",be,`Branch: ${oe}`,"Chosen task: (what you actually did; or `no safe task found`)",`Files changed: ${D}`,`Verification: ${G}`,`Commit: ${fe}`,`Push: ${Le}`,`Final git status: ${Ue}`,"Remaining risk: (if any; otherwise `none`)","","Hard rules: do not claim verification/commit/push/git status checks without evidence from tool output. If unknown, write unknown."].join(`
1578
+ `),fn=[...b,{role:"user",content:it}],Zn=((await za(fn,[],{}))?.content||"").trim();Zn&&(console.log(`
1579
+ ${Zn}`),S.push({role:"user",content:it},{role:"assistant",content:Zn}),b.push({role:"user",content:it},{role:"assistant",content:Zn}))}catch{}Me(ce,Ae,W,ve,Ne),_e(S),bt(S);break e}if(A&&zo<3){zo++;let G={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1580
1580
  ${F.slice(0,400)}
1581
1581
 
1582
- Fix the identified issues. This is attempt ${Go}/3.`};xe="implement",xn=md("implement",to),S.push(G),b.push(G),ut=0,Lt=ls("implement"),P(`${p.yellow} \u21B3 Verify \u2192 implement loop-back #${Go} (issues found)${p.reset}`);continue}if(!A&&(!C||Ko===0)){if(Vo<2){Vo++;let G=[];Ko===0&&G.push("run at least one verification tool"),C||G.push("end your report with PASS or FAIL");let he={role:"user",content:`[SYSTEM] Verification is incomplete: ${G.join(" and ")}. Do not stop yet. Re-read the modified files and/or run tests or linters, then respond with PASS or FAIL.`};S.push(he),b.push(he),P(`${p.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${Vo}/2)${p.reset}`);continue}P(`${p.yellow} \u26A0 Verify phase completion accepted without full markers after ${Vo} nudges${p.reset}`)}if(P(`${p.green} \u2713 Verification phase complete${A?" (loop-back exhausted)":" (PASS)"}${p.reset}`),!A){je(ue,Pe,H,Ee,Ne),$e(S),vt(S);break e}}}if(Qs()&&w&&ue===0)if(tl++,tl>2)P(`${p.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${p.reset}`);else{let F={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.).
1582
+ Fix the identified issues. This is attempt ${zo}/3.`};xe="implement",xn=yd("implement",no),S.push(G),b.push(G),dt=0,Lt=ls("implement"),P(`${p.yellow} \u21B3 Verify \u2192 implement loop-back #${zo} (issues found)${p.reset}`);continue}if(!A&&(!C||Xo===0)){if(Jo<2){Jo++;let G=[];Xo===0&&G.push("run at least one verification tool"),C||G.push("end your report with PASS or FAIL");let me={role:"user",content:`[SYSTEM] Verification is incomplete: ${G.join(" and ")}. Do not stop yet. Re-read the modified files and/or run tests or linters, then respond with PASS or FAIL.`};S.push(me),b.push(me),P(`${p.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${Jo}/2)${p.reset}`);continue}P(`${p.yellow} \u26A0 Verify phase completion accepted without full markers after ${Jo} nudges${p.reset}`)}if(P(`${p.green} \u2713 Verification phase complete${A?" (loop-back exhausted)":" (PASS)"}${p.reset}`),!A){Me(ce,Ae,W,ve,Ne),_e(S),bt(S);break e}}}if(eo()&&w&&ce===0)if(sl++,sl>2)P(`${p.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${p.reset}`);else{let F={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.).
1583
1583
 
1584
- 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.`};S.push(F),b.push(F),P(`${p.yellow} \u26A0 Plan rejected (${tl}/2): no files read \u2014 forcing investigation${p.reset}`);continue}if(Qs()&&w){let F=(Je||ke||"").trim();EC(F),uA(F);let C=TC(F);if(C.length>0){let M=S.find(ye=>ye.role==="user"),A=typeof M?.content=="string"?M.content.slice(0,120):"Task";RC(A,C);let N=C.length===1?"step":"steps",G=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:ye,startExecution:oe,setPlanMode:D}=Ua();process.stdout.write(`
1585
- ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${C.length} ${N})${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.yellow}[E]${p.reset}${p.dim}dit${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let de=process.stdin.isRaw,Me=await new Promise(Ue=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",it=>{try{process.stdin.setRawMode(de||!1)}catch{}let fn=it.toString().toLowerCase()[0]||"\r";Ue(fn)})});if(process.stdout.write(`
1586
- `),Me==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(Me==="e")console.log(`${p.yellow}Type /plan edit to open in editor, or give feedback.${p.reset}`);else if(ye()){oe(),D(!1),$d(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing ${C.length} ${N}...`);let Ue=`[PLAN APPROVED \u2014 EXECUTE NOW]
1584
+ 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.`};S.push(F),b.push(F),P(`${p.yellow} \u26A0 Plan rejected (${sl}/2): no files read \u2014 forcing investigation${p.reset}`);continue}if(eo()&&w){let F=(Je||ke||"").trim();CC(F),pA(F);let C=AC(F);if(C.length>0){let L=S.find(be=>be.role==="user"),A=typeof L?.content=="string"?L.content.slice(0,120):"Task";OC(A,C);let N=C.length===1?"step":"steps",G=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:be,startExecution:oe,setPlanMode:D}=Wa();process.stdout.write(`
1585
+ ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${C.length} ${N})${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.yellow}[E]${p.reset}${p.dim}dit${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let fe=process.stdin.isRaw,Le=await new Promise(Ue=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",it=>{try{process.stdin.setRawMode(fe||!1)}catch{}let fn=it.toString().toLowerCase()[0]||"\r";Ue(fn)})});if(process.stdout.write(`
1586
+ `),Le==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(Le==="e")console.log(`${p.yellow}Type /plan edit to open in editor, or give feedback.${p.reset}`);else if(be()){oe(),D(!1),xd(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing ${C.length} ${N}...`);let Ue=`[PLAN APPROVED \u2014 EXECUTE NOW]
1587
1587
 
1588
1588
  Implement the following plan step by step. All tools are now available.
1589
1589
 
1590
1590
  ${F}`;S.push({role:"user",content:Ue}),b.push({role:"user",content:Ue}),G=!0}}else console.log(`
1591
- ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${C.length} ${N} extracted).${p.reset} Type ${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ${p.reset}${p.cyan}/plan edit${p.reset}${p.dim} to review.${p.reset}`);if(G){$&&($.stop(),$=null),ut--;continue}}else{let M=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:N,startExecution:G,setPlanMode:he}=Ua();process.stdout.write(`
1592
- ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let ye=process.stdin.isRaw,oe=await new Promise(D=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",de=>{try{process.stdin.setRawMode(ye||!1)}catch{}D(de.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1593
- `),oe==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(N()){G(),he(!1),$d(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing...`);let de=`[PLAN APPROVED \u2014 EXECUTE NOW]
1591
+ ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${C.length} ${N} extracted).${p.reset} Type ${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ${p.reset}${p.cyan}/plan edit${p.reset}${p.dim} to review.${p.reset}`);if(G){$&&($.stop(),$=null),dt--;continue}}else{let L=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:N,startExecution:G,setPlanMode:me}=Wa();process.stdout.write(`
1592
+ ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let be=process.stdin.isRaw,oe=await new Promise(D=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",fe=>{try{process.stdin.setRawMode(be||!1)}catch{}D(fe.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1593
+ `),oe==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(N()){G(),me(!1),xd(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing...`);let fe=`[PLAN APPROVED \u2014 EXECUTE NOW]
1594
1594
 
1595
1595
  Implement the following plan step by step. All tools are now available.
1596
1596
 
1597
- ${getPlanContent()||st.content}`;S.push({role:"user",content:de}),b.push({role:"user",content:de}),M=!0}}else console.log(`
1598
- ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.dim}Type ${p.reset}${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ask follow-up questions to refine.${p.reset}`);if(M){$&&($.stop(),$=null),ut--;continue}}}if($&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne),rn&&H.size>=3){let F=[...H].map(G=>G.split("/").pop()).slice(0,8).join(", "),C=[...H].some(G=>G.endsWith("package.json")),M=[...H].some(G=>G.endsWith("requirements.txt")),A=[...H].some(G=>G.endsWith("package-lock.json")||G.endsWith("yarn.lock")||G.endsWith("pnpm-lock.yaml")),N=C&&!A?"npm install not yet run":M?"pip install not yet run":null;Zr=`[Previous session created ${H.size} files: ${F}`+(N?` \u2014 ${N}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(rn&&!vd&&ue>0){let F=[...H].some(D=>D.endsWith("package.json")),C=[...H].some(D=>D.endsWith("requirements.txt")||D.endsWith("Pipfile")||D.endsWith("pyproject.toml")),M=[...H].some(D=>D.endsWith("package-lock.json")||D.endsWith("yarn.lock")||D.endsWith("pnpm-lock.yaml")),A=S.flatMap(D=>{let de=Array.isArray(D.tool_calls)?D.tool_calls:[],Me=Array.isArray(D.content)?D.content.filter(Ue=>Ue?.type==="tool_use"):[];return[...de,...Me]}).filter(D=>{let de=D.function?.name||D.name||"";return de==="bash"||de==="Bash"}).map(D=>{try{let de=D.function?.arguments??D.input??{};return(typeof de=="string"?JSON.parse(de):de)?.command||""}catch{return""}}),N=A.some(D=>/pip\s+install|python\s+-m\s+venv/.test(D)),G=A.some(D=>/npm\s+install/.test(D)),ye=[...H].some(D=>/\/App\.(js|ts|jsx|tsx)$/.test(D))&&!F&&!G;if(C&&!N||F&&!M&&!G||ye){vd=!0;let D=[];C&&!N&&D.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),ye?D.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):F&&!M&&!G&&D.push("npm install");let de=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${D.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;P(`${p.dim} [post-creation] bootstrapping environment (${D.join(", ")})${p.reset}`),S.push({role:"user",content:de}),b.push({role:"user",content:de});continue}}let pe=(H.size>0||Ve>0)&&!Sl()&&yw(Je||ke||"")&&!bw(Je||ke||""),Q=an&&!Od(Je||ke||"");if(ue>0&&!n._isSummaryTurn&&(za(Je)||pe||Q))try{P(`${p.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${p.reset}`);let F=oo.length>0?oo.join(" | "):ro.length>0?`post-edit read: ${ro.slice(0,8).join(", ")}`:"not run; state this explicitly and do not claim tests/build/checks passed",C=Ae&&Ae.command||"git status --short --branch",M=Ae&&String(Ae.raw||"").trim()||"(missing preflight output)",A=Ae&&Ae.branch||mw||"(unknown)",N=[...H].slice(0,24).join(", ")||(Ve>0?"files changed by shell commands":"(none)"),G=Gr?"detected (git commit succeeded per bash output)":"not detected",he=ll?"detected (git push succeeded per bash output)":ds?"attempted (see tool output)":"not detected",ye=Zs?`${Qr}
1599
- ${Zs}`:"(not checked in this run)",oe=an?["Write a final automation report using EXACT labels (one per line):",`Preflight: ${C}`,"Preflight output: (paste exactly; do not paraphrase)",M,`Branch: ${A}`,"Chosen task: (what you actually did; or `no safe task found`)",`Files changed: ${N}`,`Verification: ${F}`,`Commit: ${G}`,`Push: ${he}`,`Final git status: ${ye}`,"Remaining risk: (if any; otherwise `none`)","","Hard rules: do not claim verification/commit/push/git status checks without evidence from tool output. If unknown, write unknown."].join(`
1600
- `):H.size>0||Ve>0?["Write a closing summary (3+ sentences) with:",`- changed files: ${[...H].slice(0,8).join(", ")||"files changed by shell commands"}`,`- verification: ${F}`,"- remaining risk or follow-up, if any."].join(`
1601
- `):"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.",D=[...b,{role:"user",content:oe}],Me=((await Ya(D,[],{}))?.content||"").trim();Me&&(console.log(`
1602
- ${Me}`),S.push({role:"user",content:oe},{role:"assistant",content:Me}))}catch{}$e(S),vt(S),await yi();return}ue++,hl++,ue>=1&&(we=!1),Sn+=Xe.length;{let w=ad(In());Number.isFinite(w)&&Sn>=w&&(gi=!0)}for(let w of Xe){let y=w.function.name;Pe.set(y,(Pe.get(y)||0)+1)}if(Sn>=30&&!hw){hw=!0,P(`${p.yellow} \u26A0 Tool budget warning: ${Sn} tool calls used \u2014 nudging model to wrap up${p.reset}`);let w={role:"user",content:"[SYSTEM] \u26A0 You have used "+Sn+" 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."};S.push(w),b.push(w)}let Se=await Promise.all(Xe.map(w=>dA(w)));if(Al){let w=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let y of Se)!y.canExecute||!w.has(y.fnName)||(y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: You already have enough evidence to produce the requested summary/document. Write the deliverable now and stop reading more files.",tool_call_id:y.callId})}if(pt&&ge&&xe==="plan"&&(Vt||Ut>=Yo))for(let w of Se)w.canExecute&&(w.canExecute=!1,w.errorResult={role:"tool",content:Kn({blocked:!0}),tool_call_id:w.callId});if(pt&&ge&&xe==="implement"&&Vt&&H.size===0)for(let w of Se){if(!w.canExecute)continue;let y=Jo(w.args?.path||""),I=w.fnName==="write_file"||w.fnName==="edit_file"||w.fnName==="patch_file",j=w.fnName==="read_file"&&y&&!dn.has(y)&&(w.args?.line_start||w.args?.line_end),V=j&&(Mt.get(w.args?.path)||0)>0;if(I)continue;if(j&&Xo<2||V){V||Xo++;continue}let pe=w.fnName==="read_file"&&y&&dn.has(y),Q=j&&Xo>=2;w.canExecute=!1,w.errorResult={role:"tool",content:pe?"BLOCKED: implementation phase has already completed backlog review. Do not re-read backlog files. Edit the concrete implementation file from the accepted plan now.":Q?"BLOCKED: implementation phase has already read enough targeted code context. Make the scoped edit now with edit_file or patch_file; do not read more before editing.":"BLOCKED: implementation phase must not use bash/find/git or broad reading. Use read_file with line_start/line_end on the concrete implementation file if one more section is needed, then use edit_file or patch_file.",tool_call_id:w.callId}}{let w=wn(b,Bt()),y=w.percentage,I=Se.some(Q=>Q.canExecute&&Q.fnName==="read_file"&&!Q.args?.line_end),j=Se.filter(Q=>Q.canExecute&&Q.fnName==="read_file"&&Q.args?.path&&Mn(ao,Q.args.path)>=1&&!Q.args?.line_start).map(Q=>Q.args.path.split("/").slice(-2).join("/")),V=j.length>0;if(y>=70&&I&&Rl<70||y>=85&&Rl<85||V){Rl=y;let Q=y>=85?"URGENT":"WARNING",F;V?(Q="WARNING",F=`Full-file read of ${j.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):I?F=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:F="Use targeted reads (line_start/line_end) to save space.";let C={role:"user",content:`[SYSTEM ${Q}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${F}`};if(S.push(C),b.push(C),y>=85){let M=V?` (re-read of: ${j.join(", ")})`:"";P(`${p.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${M}${p.reset}`)}}}let Ml=new Map;for(let w of Se){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let I=Mn(ao,y),j=Ml.get(y)||0,V=I+j,pe=us.has(y),Q=w.args?.line_start!=null,F=Mt.get(y)||0,C=F>0,M=2;if(!pe&&V>=lo){let A=y.split("/").slice(-2).join("/"),N=(eo.get(y)||0)+1;if(eo.set(y,N),N===1)P(`${p.red} \u2716 Blocked: "${A}" read ${V}\xD7 \u2014 hard cap (${lo}) reached${p.reset}`);else if(N===2){P(`${p.red} \u2716 Escalated block: "${A}" \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let G={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 (${lo}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};S.push(G),b.push(G)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${V}\xD7 (hard cap: ${lo}). 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(!pe&&V>=1&&Q)if(C&&F<=M){let A=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Targeted re-read: "${A}" (line_start=${w.args.line_start}) \u2014 edit recovery #${F}${p.reset}`),Mt.set(y,F-1)}else if(C&&F>M){let A=y.split("/").slice(-2).join("/");P(`${p.red} \u2716 Edit recovery blocked: "${A}" \u2014 ${M} recovery reads already used. Use grep to find the exact line numbers, then retry.${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${M} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:w.callId}}else{let A=parseInt(w.args.line_start,10)||1,N=parseInt(w.args.line_end,10)||A+350,G=zn.get(y)||[],he=!1;for(let[ye,oe]of G){let D=Math.max(A,ye),de=Math.min(N,oe);if(de>D){let Me=de-D,Ue=N-A||1,it=oe-ye||1,fn=Me/it>=.7&&Me/Ue<.7,gt=N-A<=P0;if(Me>=Ue||!gt&&(Me/Ue>=.7||Me/it>=.7)){let Il=y.split("/").slice(-2).join("/"),cf=`${y}:${A}-${N}`,po=(pl.get(cf)||0)+1;if(pl.set(cf,po),P(fn?`${p.red} \u2716 Blocked superread: "${Il}" lines ${A}-${N} subsumes already-read ${ye}-${oe} \u2014 use line_start=${oe+1} to skip known content (block #${po})${p.reset}`:`${p.red} \u2716 Blocked duplicate read: "${Il}" lines ${A}-${N} (\u226570% overlap with lines ${ye}-${oe} already in context, block #${po})${p.reset}`),po>=2){P(`${p.red} \u2716 Escalated range-block: "${Il}" lines ${A}-${N} \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let uf={role:"user",content:fn?`[SYSTEM] Read blocked ${po}\xD7 for read_file("${y}", lines ${A}-${N}). Lines ${ye}-${oe} were already read. Use line_start=${oe+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${po}\xD7 for read_file("${y}", lines ${A}-${N}). Lines ${ye}-${oe} were already read and will NOT change. Use grep_search to find specific content instead.`};S.push(uf),b.push(uf)}w.canExecute=!1,w.errorResult={role:"tool",content:fn?`BLOCKED: read_file("${y}", lines ${A}-${N}) re-reads lines ${ye}-${oe} already in context. Use line_start=${oe+1} to read only the new content beyond line ${oe}.`:`BLOCKED: read_file("${y}", lines ${A}-${N}) is a duplicate \u2014 lines ${ye}-${oe} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:w.callId},he=!0;break}}}if(!he){let ye=G.length,oe=2;if(ye>=3){let de=y.split("/").slice(-2).join("/");P(`${p.red} \u2716 Blocked file-scroll: "${de}" \u2014 ${ye} sections already read. Use grep to find specific content.${p.reset}`);let Me=Mn(vl,y)>=mi;w.canExecute=!1,w.errorResult={role:"tool",content:Me?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${ye} 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 ${ye} 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 ye>=oe&&(w._scrollWarn={sectionCount:ye+1,path:y})}}else if(!pe&&V>=1){let A=Mt.get(y)||0;if(A>0){let N=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Full re-read: "${N}" \u2014 test-failure recovery (${A} remaining)${p.reset}`);let G=A-1;G<=0?Mt.delete(y):Mt.set(y,G)}else{let N=y.split("/").slice(-2).join("/"),G=(eo.get(y)||0)+1;if(eo.set(y,G),G===1)P(`${p.red} \u2716 Blocked unbounded re-read: "${N}" \u2014 already in context. Use line_start/line_end for specific sections.${p.reset}`);else if(G===2){P(`${p.red} \u2716 Escalated block: "${N}" \u2014 model ignored unbounded re-read block, injecting system warning${p.reset}`);let he={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.`};S.push(he),b.push(he)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${V}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:w.callId}}}w.canExecute&&Ml.set(y,(Ml.get(y)||0)+1)}if(cs>=3)for(let w of Se)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(P(`${p.red} \u2716 Blocked ${w.fnName} \u2014 ${cs} consecutive file-not-found errors, must search first${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${cs} 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 Se){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)){P(`${p.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:w.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(P(`${p.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:w.callId})}for(let w of Se)w.canExecute&&(w.fnName!=="ssh_exec"&&w.fnName!=="bash"||/\bsed\s+-n\b/.test(w.args?.command||"")&&(P(`${p.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:w.callId}));for(let w of Se){if(!w.canExecute||w.fnName!=="write_file")continue;let y=w.args?.path,I=w.args?.content||"";if(y)try{let j=require("fs"),V=require("path").resolve(process.cwd(),y);if(j.existsSync(V)){let pe=j.statSync(V).size,Q=Buffer.byteLength(I,"utf8"),F=pe>0?Q/pe:1,C=Pd(Le),M=Pd(y);if(Ad(Le)&&(C.includes(M)||C.includes(`./${M}`)))continue;if(F<.6&&pe>200){let N=y.split("/").slice(-2).join("/");console.log(`${p.red} \u2716 write_file shrink guard: "${N}" would shrink to ${Math.round(F*100)}% of original \u2014 likely context loss${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(F*100)}% of current file size (${pe} \u2192 ${Q} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:w.callId}}}}catch{}}let of=new Map;for(let w of Se){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let I=of.get(y)||0,j=Mn(vl,y)+I,V=Mn(ao,y)>=1,pe=V?Math.min(3,mi):mi;if(j>=pe){let Q=y.split("/").slice(-2).join("/");P(`${p.red} \u2716 Blocked grep: "${Q}" grepped ${j}\xD7 with different patterns \u2014 flood threshold exceeded${p.reset}`);let F=Mn(ao,y),C=F>=lo;if(C){let M={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${F} sections and tried ${j} 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.`};S.push(M),b.push(M),P(`${p.red} \u2716 Deadlock detected: "${Q}" \u2014 both read and grep blocked, injecting deadlock-break${p.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:C?`BLOCKED: grep("${y}") denied \u2014 ${j} 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.`:V?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${j} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${j} patterns already tried. Work with the grep results already in your context.`,tool_call_id:w.callId}}w.canExecute&&of.set(y,I+1)}let D0=5,rf=new Map;for(let w of Se){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let I=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),j=rf.get(I)||0,V=Mn(Jd,I)+j;V>=D0&&(P(`${p.yellow} \u26A0 Blocked ssh_exec: same command run ${V}\xD7 \u2014 result already in context${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${V} 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&&rf.set(I,j+1)}if(Kt){let w=Se.filter(j=>j.canExecute&&j.fnName==="ssh_exec"),y=Se.some(j=>j.canExecute&&j.fnName!=="ssh_exec"),I=pi&&hi<3;if(w.length>0&&!y&&I&&sl<1)Kt=!1,sl++,on=Math.max(0,Qo-2),P(`${p.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${sl}/1)]${p.reset}`);else for(let j of w)j.canExecute=!1,j.errorResult={role:"tool",content:Et?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Qo}+ calls). Root cause is known (${Ft}). 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 (${Qo}+ 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:j.callId}}let q0=iA(S,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((pi||h0)&&!q0&&hi<3&&!Kt)for(let w of Se){if(!w.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(w.fnName))continue;hi++;{let j=Bt(),{messages:V}=Nn(b,j);b=V}let y=Wt?.matchedName?`${Wt.matchedName} (${Wt.matchedProfile?.host||"server"})`:Wt?.url,I=Wt?.shouldPreferSsh?`BLOCKED: ${w.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${Wt?.url} with browser_open or use ssh_exec on ${y} first, then return to local code if needed.`:`BLOCKED: ${w.fnName} denied \u2014 this looks like a live app issue. Inspect ${Wt?.url} with browser_open first, then return to local code if needed.`;P(`${p.yellow} \u26A0 Runtime guard: blocking local ${w.fnName} \u2014 inspect the live app first${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:I,tool_call_id:w.callId};break}if(!ge&&cn&&rn&&un>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of Se)y.canExecute&&w.includes(y.fnName)&&(P(`${p.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(Vs>=0){let w=Se.filter(y=>y.canExecute).length;if(w>0&&(Vs-=w,Vs<0))if(!rl&&H.size>ol){rl=!0,Vs=5,P(`${p.green} \u2713 Post-wipe progress detected (${H.size-ol} files modified) \u2014 granting 5 bonus tool calls${p.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};S.push(y),b.push(y)}else{P(`${p.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${p.reset}`);for(let I of Se)I.canExecute&&(I.canExecute=!1,I.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:I.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."};S.push(y),b.push(y)}}let F0=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 Se){if(!w.canExecute||F0.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),I=`${w.fnName}|${y}`,j=Mn(kd,I);j>=2?(P(`${p.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${j+1}\xD7 with identical args${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName}() with these exact arguments has already been called ${j}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:w.callId}):j===1&&P(`${p.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${p.reset}`),Ks(kd,I)}{let w=new Set;for(let y of Se){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let I=y.args?.path;I&&(w.has(I)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${I}" is already being edited in this batch. Finish one edit first, then re-read the changed section before the next one.`,tool_call_id:y.callId},P(`${p.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${I.split("/").slice(-1)[0]}"${p.reset}`)):Zo.has(I)&&!us.has(I)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${I}" 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},P(`${p.yellow} \u26A0 Map-first gate: blocked re-edit of "${I.split("/").slice(-1)[0]}" \u2014 re-read required${p.reset}`)):w.add(I))}}let er=$?{skipSpinner:!0,skipSummaries:!0}:{},B0=Se.some(w=>w.fnName==="ask_user"),af=!er.skipSummaries&&!we,Qt=null,fo=null;if(af&&!B0){if(we=!0,er.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(fo=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let w=Wr(Se,ue,!1,0),y=Wr(Se,ue,!1);process.stdout.write(`${ue>1?`
1603
- `:""}${w}`),Wo=y,Ho=Date.now(),Qt={start:Date.now(),frame:0,timer:null}}else if(!rt){let w=Wr(Se,ue,!1);hd(w,Wo,Ho)||(process.stdout.write(`${ue>1?`
1597
+ ${getPlanContent()||st.content}`;S.push({role:"user",content:fe}),b.push({role:"user",content:fe}),L=!0}}else console.log(`
1598
+ ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.dim}Type ${p.reset}${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ask follow-up questions to refine.${p.reset}`);if(L){$&&($.stop(),$=null),dt--;continue}}}if($&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne),an&&W.size>=3){let F=[...W].map(G=>G.split("/").pop()).slice(0,8).join(", "),C=[...W].some(G=>G.endsWith("package.json")),L=[...W].some(G=>G.endsWith("requirements.txt")),A=[...W].some(G=>G.endsWith("package-lock.json")||G.endsWith("yarn.lock")||G.endsWith("pnpm-lock.yaml")),N=C&&!A?"npm install not yet run":L?"pip install not yet run":null;Zr=`[Previous session created ${W.size} files: ${F}`+(N?` \u2014 ${N}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(an&&!Td&&ce>0){let F=[...W].some(D=>D.endsWith("package.json")),C=[...W].some(D=>D.endsWith("requirements.txt")||D.endsWith("Pipfile")||D.endsWith("pyproject.toml")),L=[...W].some(D=>D.endsWith("package-lock.json")||D.endsWith("yarn.lock")||D.endsWith("pnpm-lock.yaml")),A=S.flatMap(D=>{let fe=Array.isArray(D.tool_calls)?D.tool_calls:[],Le=Array.isArray(D.content)?D.content.filter(Ue=>Ue?.type==="tool_use"):[];return[...fe,...Le]}).filter(D=>{let fe=D.function?.name||D.name||"";return fe==="bash"||fe==="Bash"}).map(D=>{try{let fe=D.function?.arguments??D.input??{};return(typeof fe=="string"?JSON.parse(fe):fe)?.command||""}catch{return""}}),N=A.some(D=>/pip\s+install|python\s+-m\s+venv/.test(D)),G=A.some(D=>/npm\s+install/.test(D)),be=[...W].some(D=>/\/App\.(js|ts|jsx|tsx)$/.test(D))&&!F&&!G;if(C&&!N||F&&!L&&!G||be){Td=!0;let D=[];C&&!N&&D.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),be?D.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):F&&!L&&!G&&D.push("npm install");let fe=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${D.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;P(`${p.dim} [post-creation] bootstrapping environment (${D.join(", ")})${p.reset}`),S.push({role:"user",content:fe}),b.push({role:"user",content:fe});continue}}let de=(W.size>0||He>0)&&!El()&&_w(Je||ke||"")&&!$w(Je||ke||""),Q=ln&&!Nd(Je||ke||"");if(ce>0&&!n._isSummaryTurn&&(Ka(Je)||de||Q))try{P(`${p.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${p.reset}`);let F=ro.length>0?ro.join(" | "):io.length>0?`post-edit read: ${io.slice(0,8).join(", ")}`:"not run; state this explicitly and do not claim tests/build/checks passed",C=Pe&&Pe.command||"git status --short --branch",L=Pe&&String(Pe.raw||"").trim()||"(missing preflight output)",A=Pe&&Pe.branch||bw||"(unknown)",N=[...W].slice(0,24).join(", ")||(He>0?"files changed by shell commands":"(none)"),G=Yr?"detected (git commit succeeded per bash output)":"not detected",me=ul?"detected (git push succeeded per bash output)":ds?"attempted (see tool output)":"not detected",be=Qs?`${Qr}
1599
+ ${Qs}`:"(not checked in this run)",oe=ln?["Write a final automation report using EXACT labels (one per line):",`Preflight: ${C}`,"Preflight output: (paste exactly; do not paraphrase)",L,`Branch: ${A}`,"Chosen task: (what you actually did; or `no safe task found`)",`Files changed: ${N}`,`Verification: ${F}`,`Commit: ${G}`,`Push: ${me}`,`Final git status: ${be}`,"Remaining risk: (if any; otherwise `none`)","","Hard rules: do not claim verification/commit/push/git status checks without evidence from tool output. If unknown, write unknown."].join(`
1600
+ `):W.size>0||He>0?["Write a closing summary (3+ sentences) with:",`- changed files: ${[...W].slice(0,8).join(", ")||"files changed by shell commands"}`,`- verification: ${F}`,"- remaining risk or follow-up, if any."].join(`
1601
+ `):"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.",D=[...b,{role:"user",content:oe}],Le=((await za(D,[],{}))?.content||"").trim();Le&&(console.log(`
1602
+ ${Le}`),S.push({role:"user",content:oe},{role:"assistant",content:Le}))}catch{}_e(S),bt(S),await bi();return}ce++,gl++,ce>=1&&(ye=!1),Sn+=Xe.length;{let w=cd(In());Number.isFinite(w)&&Sn>=w&&(yi=!0)}for(let w of Xe){let y=w.function.name;Ae.set(y,(Ae.get(y)||0)+1)}if(Sn>=30&&!gw){gw=!0,P(`${p.yellow} \u26A0 Tool budget warning: ${Sn} tool calls used \u2014 nudging model to wrap up${p.reset}`);let w={role:"user",content:"[SYSTEM] \u26A0 You have used "+Sn+" 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."};S.push(w),b.push(w)}let Ee=await Promise.all(Xe.map(w=>hA(w)));if(Pl){let w=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let y of Ee)!y.canExecute||!w.has(y.fnName)||(y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: You already have enough evidence to produce the requested summary/document. Write the deliverable now and stop reading more files.",tool_call_id:y.callId})}if(ct&&he&&xe==="plan"&&(Wt||Ut>=Ko))for(let w of Ee)w.canExecute&&(w.canExecute=!1,w.errorResult={role:"tool",content:Kn({blocked:!0}),tool_call_id:w.callId});if(ct&&he&&xe==="implement"&&Wt&&W.size===0)for(let w of Ee){if(!w.canExecute)continue;let y=hs(w.args?.path||""),M=w.fnName==="write_file"||w.fnName==="edit_file"||w.fnName==="patch_file",j=w.fnName==="read_file"&&y&&!Ht.has(y)&&(w.args?.line_start||w.args?.line_end),V=j&&(Mt.get(w.args?.path)||0)>0,de=kA(w.fnName,w.args||{});if(M)continue;if(j&&Zo<2||V){V||Zo++;continue}if(de&&oi<yw){oi++;continue}let Q=w.fnName==="read_file"&&y&&Ht.has(y),F=j&&Zo>=2,C=de&&oi>=yw;w.canExecute=!1,w.errorResult={role:"tool",content:Q?"BLOCKED: implementation phase has already completed backlog review. Do not re-read backlog files. Edit the concrete implementation file from the accepted plan now.":F?"BLOCKED: implementation phase has already read enough targeted code context. Make the scoped edit now with edit_file or patch_file; do not read more before editing.":C?"BLOCKED: implementation phase has already used enough path discovery. Read the concrete implementation file with line_start/line_end or make the scoped edit now.":"BLOCKED: implementation phase must not use bash/git or broad reading. Use a targeted glob/search/list_directory call only to locate the concrete implementation file, then read it with line_start/line_end or edit it.",tool_call_id:w.callId}}{let w=wn(b,Bt()),y=w.percentage,M=Ee.some(Q=>Q.canExecute&&Q.fnName==="read_file"&&!Q.args?.line_end),j=Ee.filter(Q=>Q.canExecute&&Q.fnName==="read_file"&&Q.args?.path&&Mn(lo,Q.args.path)>=1&&!Q.args?.line_start).map(Q=>Q.args.path.split("/").slice(-2).join("/")),V=j.length>0;if(y>=70&&M&&Al<70||y>=85&&Al<85||V){Al=y;let Q=y>=85?"URGENT":"WARNING",F;V?(Q="WARNING",F=`Full-file read of ${j.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):M?F=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:F="Use targeted reads (line_start/line_end) to save space.";let C={role:"user",content:`[SYSTEM ${Q}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${F}`};if(S.push(C),b.push(C),y>=85){let L=V?` (re-read of: ${j.join(", ")})`:"";P(`${p.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${L}${p.reset}`)}}}let Il=new Map;for(let w of Ee){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let M=Mn(lo,y),j=Il.get(y)||0,V=M+j,de=us.has(y),Q=w.args?.line_start!=null,F=Mt.get(y)||0,C=F>0,L=2;if(!de&&V>=co){let A=y.split("/").slice(-2).join("/"),N=(to.get(y)||0)+1;if(to.set(y,N),N===1)P(`${p.red} \u2716 Blocked: "${A}" read ${V}\xD7 \u2014 hard cap (${co}) reached${p.reset}`);else if(N===2){P(`${p.red} \u2716 Escalated block: "${A}" \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let G={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 (${co}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};S.push(G),b.push(G)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${V}\xD7 (hard cap: ${co}). 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(!de&&V>=1&&Q)if(C&&F<=L){let A=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Targeted re-read: "${A}" (line_start=${w.args.line_start}) \u2014 edit recovery #${F}${p.reset}`),Mt.set(y,F-1)}else if(C&&F>L){let A=y.split("/").slice(-2).join("/");P(`${p.red} \u2716 Edit recovery blocked: "${A}" \u2014 ${L} recovery reads already used. Use grep to find the exact line numbers, then retry.${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${L} 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 A=parseInt(w.args.line_start,10)||1,N=parseInt(w.args.line_end,10)||A+350,G=zn.get(y)||[],me=!1;for(let[be,oe]of G){let D=Math.max(A,be),fe=Math.min(N,oe);if(fe>D){let Le=fe-D,Ue=N-A||1,it=oe-be||1,fn=Le/it>=.7&&Le/Ue<.7,gt=N-A<=L0;if(Le>=Ue||!gt&&(Le/Ue>=.7||Le/it>=.7)){let Dl=y.split("/").slice(-2).join("/"),df=`${y}:${A}-${N}`,ho=(ml.get(df)||0)+1;if(ml.set(df,ho),P(fn?`${p.red} \u2716 Blocked superread: "${Dl}" lines ${A}-${N} subsumes already-read ${be}-${oe} \u2014 use line_start=${oe+1} to skip known content (block #${ho})${p.reset}`:`${p.red} \u2716 Blocked duplicate read: "${Dl}" lines ${A}-${N} (\u226570% overlap with lines ${be}-${oe} already in context, block #${ho})${p.reset}`),ho>=2){P(`${p.red} \u2716 Escalated range-block: "${Dl}" lines ${A}-${N} \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let ff={role:"user",content:fn?`[SYSTEM] Read blocked ${ho}\xD7 for read_file("${y}", lines ${A}-${N}). Lines ${be}-${oe} were already read. Use line_start=${oe+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${ho}\xD7 for read_file("${y}", lines ${A}-${N}). Lines ${be}-${oe} were already read and will NOT change. Use grep_search to find specific content instead.`};S.push(ff),b.push(ff)}w.canExecute=!1,w.errorResult={role:"tool",content:fn?`BLOCKED: read_file("${y}", lines ${A}-${N}) re-reads lines ${be}-${oe} already in context. Use line_start=${oe+1} to read only the new content beyond line ${oe}.`:`BLOCKED: read_file("${y}", lines ${A}-${N}) is a duplicate \u2014 lines ${be}-${oe} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:w.callId},me=!0;break}}}if(!me){let be=G.length,oe=2;if(be>=3){let fe=y.split("/").slice(-2).join("/");P(`${p.red} \u2716 Blocked file-scroll: "${fe}" \u2014 ${be} sections already read. Use grep to find specific content.${p.reset}`);let Le=Mn(Tl,y)>=gi;w.canExecute=!1,w.errorResult={role:"tool",content:Le?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${be} 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 ${be} 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 be>=oe&&(w._scrollWarn={sectionCount:be+1,path:y})}}else if(!de&&V>=1){let A=Mt.get(y)||0;if(A>0){let N=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Full re-read: "${N}" \u2014 test-failure recovery (${A} remaining)${p.reset}`);let G=A-1;G<=0?Mt.delete(y):Mt.set(y,G)}else{let N=y.split("/").slice(-2).join("/"),G=(to.get(y)||0)+1;if(to.set(y,G),G===1)P(`${p.red} \u2716 Blocked unbounded re-read: "${N}" \u2014 already in context. Use line_start/line_end for specific sections.${p.reset}`);else if(G===2){P(`${p.red} \u2716 Escalated block: "${N}" \u2014 model ignored unbounded re-read block, injecting system warning${p.reset}`);let me={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.`};S.push(me),b.push(me)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${V}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:w.callId}}}w.canExecute&&Il.set(y,(Il.get(y)||0)+1)}if(cs>=3)for(let w of Ee)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(P(`${p.red} \u2716 Blocked ${w.fnName} \u2014 ${cs} consecutive file-not-found errors, must search first${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${cs} 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 Ee){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)){P(`${p.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:w.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(P(`${p.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:w.callId})}for(let w of Ee)w.canExecute&&(w.fnName!=="ssh_exec"&&w.fnName!=="bash"||/\bsed\s+-n\b/.test(w.args?.command||"")&&(P(`${p.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:w.callId}));for(let w of Ee){if(!w.canExecute||w.fnName!=="write_file")continue;let y=w.args?.path,M=w.args?.content||"";if(y)try{let j=require("fs"),V=require("path").resolve(process.cwd(),y);if(j.existsSync(V)){let de=j.statSync(V).size,Q=Buffer.byteLength(M,"utf8"),F=de>0?Q/de:1,C=Md(Ie),L=Md(y);if(Pd(Ie)&&(C.includes(L)||C.includes(`./${L}`)))continue;if(F<.6&&de>200){let N=y.split("/").slice(-2).join("/");console.log(`${p.red} \u2716 write_file shrink guard: "${N}" would shrink to ${Math.round(F*100)}% of original \u2014 likely context loss${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(F*100)}% of current file size (${de} \u2192 ${Q} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:w.callId}}}}catch{}}let af=new Map;for(let w of Ee){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let M=af.get(y)||0,j=Mn(Tl,y)+M,V=Mn(lo,y)>=1,de=V?Math.min(3,gi):gi;if(j>=de){let Q=y.split("/").slice(-2).join("/");P(`${p.red} \u2716 Blocked grep: "${Q}" grepped ${j}\xD7 with different patterns \u2014 flood threshold exceeded${p.reset}`);let F=Mn(lo,y),C=F>=co;if(C){let L={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${F} sections and tried ${j} 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.`};S.push(L),b.push(L),P(`${p.red} \u2716 Deadlock detected: "${Q}" \u2014 both read and grep blocked, injecting deadlock-break${p.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:C?`BLOCKED: grep("${y}") denied \u2014 ${j} 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.`:V?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${j} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${j} patterns already tried. Work with the grep results already in your context.`,tool_call_id:w.callId}}w.canExecute&&af.set(y,M+1)}let B0=5,lf=new Map;for(let w of Ee){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let M=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),j=lf.get(M)||0,V=Mn(Qd,M)+j;V>=B0&&(P(`${p.yellow} \u26A0 Blocked ssh_exec: same command run ${V}\xD7 \u2014 result already in context${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${V} 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&&lf.set(M,j+1)}if(Xt){let w=Ee.filter(j=>j.canExecute&&j.fnName==="ssh_exec"),y=Ee.some(j=>j.canExecute&&j.fnName!=="ssh_exec"),M=hi&&mi<3;if(w.length>0&&!y&&M&&rl<1)Xt=!1,rl++,rn=Math.max(0,er-2),P(`${p.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${rl}/1)]${p.reset}`);else for(let j of w)j.canExecute=!1,j.errorResult={role:"tool",content:Et?`BLOCKED: ssh_exec denied \u2014 SSH paused (${er}+ calls). Root cause is known (${Ft}). 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 (${er}+ 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:j.callId}}let U0=cA(S,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((hi||y0)&&!U0&&mi<3&&!Xt)for(let w of Ee){if(!w.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(w.fnName))continue;mi++;{let j=Bt(),{messages:V}=Nn(b,j);b=V}let y=Gt?.matchedName?`${Gt.matchedName} (${Gt.matchedProfile?.host||"server"})`:Gt?.url,M=Gt?.shouldPreferSsh?`BLOCKED: ${w.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${Gt?.url} with browser_open or use ssh_exec on ${y} first, then return to local code if needed.`:`BLOCKED: ${w.fnName} denied \u2014 this looks like a live app issue. Inspect ${Gt?.url} with browser_open first, then return to local code if needed.`;P(`${p.yellow} \u26A0 Runtime guard: blocking local ${w.fnName} \u2014 inspect the live app first${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:M,tool_call_id:w.callId};break}if(!he&&un&&an&&dn>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of Ee)y.canExecute&&w.includes(y.fnName)&&(P(`${p.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(Xs>=0){let w=Ee.filter(y=>y.canExecute).length;if(w>0&&(Xs-=w,Xs<0))if(!al&&W.size>il){al=!0,Xs=5,P(`${p.green} \u2713 Post-wipe progress detected (${W.size-il} files modified) \u2014 granting 5 bonus tool calls${p.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};S.push(y),b.push(y)}else{P(`${p.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${p.reset}`);for(let M of Ee)M.canExecute&&(M.canExecute=!1,M.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:M.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."};S.push(y),b.push(y)}}let W0=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 Ee){if(!w.canExecute||W0.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),M=`${w.fnName}|${y}`,j=Mn(Sd,M);j>=2?(P(`${p.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${j+1}\xD7 with identical args${p.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName}() with these exact arguments has already been called ${j}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:w.callId}):j===1&&P(`${p.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${p.reset}`),Vs(Sd,M)}{let w=new Set;for(let y of Ee){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let M=y.args?.path;M&&(w.has(M)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${M}" is already being edited in this batch. Finish one edit first, then re-read the changed section before the next one.`,tool_call_id:y.callId},P(`${p.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${M.split("/").slice(-1)[0]}"${p.reset}`)):Qo.has(M)&&!us.has(M)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${M}" 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},P(`${p.yellow} \u26A0 Map-first gate: blocked re-edit of "${M.split("/").slice(-1)[0]}" \u2014 re-read required${p.reset}`)):w.add(M))}}let tr=$?{skipSpinner:!0,skipSummaries:!0}:{},H0=Ee.some(w=>w.fnName==="ask_user"),cf=!tr.skipSummaries&&!ye,en=null,po=null;if(cf&&!H0){if(ye=!0,tr.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(po=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let w=Hr(Ee,ce,!1,0),y=Hr(Ee,ce,!1);process.stdout.write(`${ce>1?`
1603
+ `:""}${w}`),Go=y,Yo=Date.now(),en={start:Date.now(),frame:0,timer:null}}else if(!rt){let w=Hr(Ee,ce,!1);gd(w,Go,Yo)||(process.stdout.write(`${ce>1?`
1604
1604
  `:""}${w}
1605
- `),Wo=w,Ho=Date.now())}}else af&&(we=!0,er.skipSpinner=!0);$&&$._paused&&$.resume(),Qt&&process.stdout.isTTY&&(Qt.timer=setInterval(()=>{Qt.frame++;let w=Math.round((Date.now()-Qt.start)/1e3),y=w>=1?` ${p.dim}[${w}s]${p.reset}`:"",I=`${Wr(Se,ue,!1,Qt.frame)}${y}`;fo!==null?process.stdout.write(`\x1B[${fo};1H\x1B[2K${I}`):process.stdout.write(`\r\x1B[2K${I}`)},120),Qt.timer.unref?.());let{results:mt,summaries:U0}=await mA(Se,!0,{...er,skipSummaries:!0});if(Nl){let w={role:"user",content:"[SYSTEM] ask_user is exclusive. Wait for the user's answer before making any other tool calls."};S.push(w),b.push(w)}if(Qt){Qt.timer&&(clearInterval(Qt.timer),Qt.timer=null);let w=Wr(Se,ue,!1);hd(w,Wo,Ho)||(fo!==null?process.stdout.write(`\x1B[${fo};1H\x1B[2K${w}
1605
+ `),Go=w,Yo=Date.now())}}else cf&&(ye=!0,tr.skipSpinner=!0);$&&$._paused&&$.resume(),en&&process.stdout.isTTY&&(en.timer=setInterval(()=>{en.frame++;let w=Math.round((Date.now()-en.start)/1e3),y=w>=1?` ${p.dim}[${w}s]${p.reset}`:"",M=`${Hr(Ee,ce,!1,en.frame)}${y}`;po!==null?process.stdout.write(`\x1B[${po};1H\x1B[2K${M}`):process.stdout.write(`\r\x1B[2K${M}`)},120),en.timer.unref?.());let{results:mt,summaries:G0}=await bA(Ee,!0,{...tr,skipSummaries:!0});if(Ll){let w={role:"user",content:"[SYSTEM] ask_user is exclusive. Wait for the user's answer before making any other tool calls."};S.push(w),b.push(w)}if(en){en.timer&&(clearInterval(en.timer),en.timer=null);let w=Hr(Ee,ce,!1);gd(w,Go,Yo)||(po!==null?process.stdout.write(`\x1B[${po};1H\x1B[2K${w}
1606
1606
  `):process.stdout.write(`\r\x1B[2K${w}
1607
- `),Wo=w,Ho=Date.now()),fo=null,Qt=null}if(!er.skipSummaries){let w=U0.filter((j,V)=>!(Se[V]&&Se[V].fnName==="ask_user"));for(let j of w)hd(j,wd,_d)||(console.log(j),wd=j,_d=Date.now());let y=Se.filter(j=>j&&j.fnName!=="ask_user").map(j=>j.fnName),I=m0.record(0,y,Ee,H);I&&HC(I)}for(let w of Se){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:"))&&(gs++,gs>=Zd)){P(`${p.red} \u2716 Loop abort: ${gs} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne,{suppressHint:!0}),$e(S);return}}let Ll=!1;for(let w=0;w<Se.length;w++){let y=Se[w];if(!y.canExecute)continue;let I=mt[w].content,j=I.split(`
1608
- `)[0],V=!j.startsWith("ERROR")&&!j.startsWith("CANCELLED")&&!j.startsWith("Command failed")&&!j.startsWith("EXIT")&&!/old_text not found/i.test(j);if(y.fnName==="git_status"&&V&&(Qr="git_status",Zs=I),y.fnName==="bash"&&y.canExecute&&typeof y.args?.command=="string"){let C=y.args.command;/git\s+status\s+--short\s+--branch\b/.test(C)&&(Qr="bash:git status --short --branch",Zs=I),/git\s+push\b/.test(C)&&(ds=I,V&&!ds.startsWith("EXIT")&&(/\bEverything up[- ]to[- ]date\b/i.test(ds)||/\bTo\s+\S+/i.test(ds)||/\bWriting objects\b/i.test(ds))&&(ll=!0))}if(!V&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&j.includes("old_text not found")){let C=Mt.get(y.args.path)||0;Mt.set(y.args.path,C+1)}if(!V&&y.fnName==="bash"&&ni.size>0){let C=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(C))for(let[A]of ni)Mt.has(A)||(Mt.set(A,1),P(`${p.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${A.split("/").pop()}"${p.reset}`))}if(!V&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(j)){if(cs++,cs>=2){P(`${p.yellow} \u26A0 File-not-found streak: ${cs} consecutive misses \u2014 forcing search${p.reset}`);let C={role:"user",content:`[SYSTEM] ${cs} 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.`};S.push(C),b.push(C)}}else V&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(cs=0);if(V&&y.fnName==="write_file"&&y.args?.path){let C=y.args.path.split("/").pop(),M=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(C)&&!M){P(`${p.yellow} \u26A0 Temp file: "${C}" \u2014 delete with bash rm when done to keep the workspace clean${p.reset}`);let N={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.`};S.push(N),b.push(N)}}if(V&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Mt.delete(y.args.path),H.add(y.args.path);for(let A of no)!A.done&&y.args.path.endsWith(A.file.split("/").pop())&&(A.done=!0,P(`${p.green} \u2713 TODO done: ${A.file}${p.reset}`));let C=Ks(g0,y.args.path),M=y.args.path.split("/").slice(-2).join("/");if(C===y0){P(`${p.yellow} \u26A0 Loop warning: "${M}" edited ${C}\xD7 \u2014 possible edit loop${p.reset}`);let A={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${C}\xD7. One more edit max, then move on.`};S.push(A),b.push(A)}else if(C>=b0){P(`${p.red} \u2716 Loop abort: "${M}" edited ${C}\xD7 \u2014 aborting to prevent runaway loop${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne,{suppressHint:!0}),$e(S);return}ge&&xe==="verify"||(Vn=!0,Dn=0,Ll=!0)}if(V&&y.canExecute&&ge&&(ps=0),V&&y.canExecute&&pt&&ge&&xe==="plan"&&gA.has(y.fnName)&&(Ut++,bA(y.fnName,y.args)&&li++,Ut>=ml&&!cl)){cl=!0;let C={role:"user",content:Kn()};S.push(C),b.push(C),P(`${p.yellow} \u26A0 Bounded backlog plan: ${Ut} read/search tools used \u2014 requiring a decision${p.reset}`)}if(V&&y.canExecute&&!(ge&&xe==="plan")){let C=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){ln=0,cn=!1,_n=0,un++;let oe=y.args?.path||y.args?.file_path;oe&&(y.fnName==="write_file"?(us.add(oe),jn.delete(oe),zn.delete(oe),Zo.delete(oe)):(us.delete(oe),pd(jn,oe,1),zn.delete(oe),Zo.add(oe)))}else if(C.includes(y.fnName)){if(ln++,cn&&_n++,ge&&xe==="implement"&&y.fnName==="read_file"){let oe=y.args?.path||y.args?.file_path||"";if(oe&&us.has(oe)){let D={role:"user",content:`[SYSTEM] You just created and re-read "${oe}". Do NOT analyze further. Apply the requested refactor now with edit_file.`};S.push(D),b.push(D),P(`${p.yellow} \u26A0 Fresh-write nudge: ${oe} \u2014 refactor directly after re-read${p.reset}`)}}if(ge&&xe==="implement"&&y.fnName==="read_file"&&no.length>0){let oe=y.args?.path||y.args?.file_path||"",D=no.find(de=>!de.done&&oe.endsWith(de.file.split("/").pop()));if(D){let de={role:"user",content:`[TODO OBSERVER] You already analyzed "${D.file}" in the plan phase. Action: ${D.action}
1609
- Do NOT re-read \u2014 apply the edit directly with edit_file.`};S.push(de),b.push(de),P(`${p.yellow} \u26A0 TODO nudge: ${D.file} \u2014 already analyzed, edit directly${p.reset}`)}}ge&&xe==="implement"&&Vn&&Dn<1&&(Dn++,Ll=!0)}if(ge&&xe==="verify"&&Ko++,V&&OA(y)){let oe=String(y.args?.command||"").trim();oe&&oo.push(oe.slice(0,160)),Vn=!1,Dn=0}let A=o.postEditCap,N=ge&&xe==="implement"?Math.min(Qd,10):Qd,G=Et?8:bi?un>0?4:6:rn?un>0?6:10:un>0?A:N,he=6,ye=!ge&&cn&&(Et&&_n>=he||rn&&un>=3&&_n>=he||_n>=he);if(Hr<2&&!cn&&ln>=3&&H.size===0){let oe=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,D=Date.now()-Ne,de=Hr===0?.4:.65;if(oe>0&&D>oe*de){Hr++;let Me=Math.round(D/6e4),Ue=Math.round(D/oe*100);P(`${p.yellow} \u26A0 Time nudge #${Hr}: ${Me}m elapsed (${Ue}%), ${ln} reads, 0 edits${p.reset}`);let it={role:"user",content:Hr===1?`[SYSTEM] ${Ue}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${Ue}% 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.`};S.push(it),b.push(it)}}if(ye&&C.includes(y.fnName)){let oe=Et?`root cause already identified (${Ft})`:_n>=he?`${ln} consecutive reads without an edit`:`${un} file edit(s) already made`;P(`${p.red} \u2716 Blocked read-only tool: cap fired, ${oe}${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:Et?`BLOCKED: root cause already identified (${Ft}). Use edit_file to fix the issue \u2014 do not read more files.`:rn?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":_n>=he?`BLOCKED: You have read ${ln} 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: ${un} 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(ln>=G&&!cn){if(cn=!0,bi&&(Al=!0),P(`${p.yellow} \u26A0 Investigation cap: ${ln} read-only calls without an edit \u2014 forcing implementation${p.reset}`),ge&&xe==="plan"){let de=[...b].reverse().find(it=>it.role==="assistant"),Me=typeof de?.content=="string"?de.content:"",Ue=await Fo("implement",Me);Ue&&(S.push(Ue),b.push(Ue),ut=0,Lt=ls("implement"))}let oe;Et?oe=`[SYSTEM] Root cause was already identified (${Ft}). Edit the file now \u2014 do not read more files.`:bi?oe="[SYSTEM] You have enough evidence to write the requested summary/document now. Use write_file or edit_file to produce the deliverable, and stop reading more files unless a required section is still unsupported.":Kt?oe="[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.":oe="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let D={role:"user",content:oe};S.push(D),b.push(D)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let C=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),M=Ks(Jd,C);if(M===w0){P(`${p.yellow} \u26A0 Loop warning: same bash command run ${M}\xD7 \u2014 possible debug loop${p.reset}`);let A={role:"user",content:`[SYSTEM WARNING] Same bash command ${M}\xD7. Debug loop detected \u2014 try a different approach.`};S.push(A),b.push(A)}else if(M>=_0){P(`${p.red} \u2716 Loop abort: same bash command run ${M}\xD7 \u2014 aborting runaway debug loop${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne,{suppressHint:!0}),$e(S);return}}if(y.fnName==="ssh_exec"){on++;{let A=(mt[w]?.content??"").split(`
1610
- `).map(N=>N.trim()).find(N=>N.length>0&&!N.startsWith("**")&&(N.startsWith("EXIT")||/^[\w./-]+:\s/.test(N)||N.startsWith("bash:")||N.startsWith("sh:")))??"";if(A){if(A===il?Xs++:(il=A,Xs=1),Xs===3&&!Kt){P(`${p.yellow} \u26A0 SSH repeated-error: "${A.slice(0,60)}" returned ${Xs}\xD7 \u2014 nudging to change approach${p.reset}`);let N={role:"user",content:`[SYSTEM WARNING] The last ${Xs} SSH commands all failed with the same error: "${A}". 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).`};S.push(N),b.push(N)}}else il="",Xs=0}if(on>=j0){P(`${p.red} \u2716 SSH storm abort: ${on} consecutive ssh_exec calls \u2014 aborting${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne,{suppressHint:!0}),$e(S);return}else if(on===Qo){{let A=Bt(),{messages:N}=Nn(b,A);b=N}Kt=!0,Va++,P(`${p.yellow} \u26A0 SSH storm warning (#${Va}): ${on} consecutive ssh_exec calls \u2014 blocking further SSH${p.reset}`);let M={role:"user",content:Et?`[SYSTEM WARNING] ${on} consecutive SSH calls. Root cause identified (${Ft}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${on} 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.`};S.push(M),b.push(M)}}else y.canExecute&&(on=0);if(y.fnName==="bash"&&y.canExecute){let A=(mt[w]?.content??"").split(`
1611
- `).map(N=>N.trim()).find(N=>N.length>0&&(N.startsWith("EXIT")||/^[\w./-]+:\s/.test(N)||N.startsWith("bash:")||N.startsWith("sh:")))??"";if(A){if(A===al?Js++:(al=A,Js=1),Js===3){P(`${p.yellow} \u26A0 Bash repeated-error: "${A.slice(0,60)}" returned ${Js}\xD7 \u2014 nudging to change approach${p.reset}`);let N={role:"user",content:`[SYSTEM WARNING] The last ${Js} bash commands all failed with the same error: "${A}". 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).`};S.push(N),b.push(N)}}else al="",Js=0}if(y.fnName==="bash"&&y.canExecute&&!Gr&&y.args?.command){let C=mt[w]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!C.startsWith("EXIT")&&!C.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(C)||C.includes("files changed")||C.includes("file changed")||C.includes("insertions(+)")||C.includes("create mode"))){Gr=!0,Yr=0;let N=an?4:2;P(`${p.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max ${N} git status/diff/log)${p.reset}`);let G=an?{role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. This is a gated automation workflow: ensure you still capture final-state evidence. Next: push (if required by the prompt), then run `git status --short --branch` once and include its output in the final automation report. Avoid extra git diff/log unless needed to explain a blocker."}:{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."};S.push(G),b.push(G)}}if(Gr&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(Yr++,Yr>(an?4:2))){P(`${p.yellow} \u26A0 Post-commit git verification blocked (call ${Yr})${p.reset}`);let A={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(Yr-1)+" git verification commands after committing. "+(an?"In gated automation workflows, keep tool use minimal: you already have enough evidence for the final report. Write the final automation report now and stop.":"The commit is confirmed. Write your final summary NOW and do not make any more tool calls.")};S.push(A),b.push(A)}if(V&&y.fnName==="grep"&&I&&!I.startsWith("(no matches)")){let C=I.split(`
1612
- `);for(let M of C){let A=M.indexOf(":");if(A>0){let N=M.substring(0,A);N.startsWith("/")&&!N.includes(" ")&&ei.add(N)}else M.startsWith("/")&&!M.includes(" ")&&ei.add(M.trim())}}{let C=["grep","search_files","glob","glob_files"].includes(y.fnName);if(C&&V&&I&&(I.startsWith("(no matches)")||I.trim()===""||/^No matches found/.test(I.trim())||/^\(0 results\)/.test(I.trim()))){if(xl++,xl===3){P(`${p.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${p.reset}`);let A={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."};S.push(A),b.push(A)}}else C&&V&&I&&I.trim().length>0&&(xl=0)}if(V&&y.fnName==="grep"&&y.args&&y.args.pattern){let C=`${y.args.pattern}|${y.args.path||""}`,M=Ks($0,C);if(M===k0){P(`${p.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${M}\xD7 \u2014 possible search loop${p.reset}`);let A={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${M}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};S.push(A),b.push(A)}else if(M>=x0){P(`${p.red} \u2716 Loop abort: grep pattern run ${M}\xD7 \u2014 aborting runaway search loop${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne,{suppressHint:!0}),$e(S);return}if(y.args.path){let A=Ks(vl,y.args.path),N=Mn(ao,y.args.path)>=1;if(A===(N?1:S0)){let he=y.args.path.split("/").slice(-2).join("/");P(`${p.yellow} \u26A0 Loop warning: "${he}" grepped ${A}\xD7 with different patterns \u2014 context flood risk${p.reset}`);let ye={role:"user",content:N?`[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 ${A}\xD7 \u2014 use the search results already in context instead of searching again.`};S.push(ye),b.push(ye)}}}if(V&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(I&&!I.startsWith("(no matches)")){let N=I.split(`
1613
- `);for(let G of N)(G.startsWith("/")&&!G.includes(" ")||!G.includes(":")&&!G.startsWith("["))&&ti.add(G.trim())}let C=y.args.pattern||y.args.query||y.args.path||"",M=Ks(v0,C);if(M===E0){P(`${p.yellow} \u26A0 Loop warning: glob pattern "${C.slice(0,40)}" run ${M}\xD7 \u2014 possible search loop${p.reset}`);let N={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${M}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};S.push(N),b.push(N)}else if(M>=T0){P(`${p.red} \u2716 Loop abort: glob pattern run ${M}\xD7 \u2014 aborting runaway search loop${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne,{suppressHint:!0}),$e(S);return}let A=C.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(N=>N.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(N));for(let N of A){let G=N.toLowerCase();el.has(G)||el.set(G,new Set);let he=el.get(G);if(he.add(C),he.size===C0){P(`${p.red} \u2716 Glob core-term block: ${he.size} different patterns all searching for "${G}" \u2014 search loop${p.reset}`);let ye={role:"user",content:`[SYSTEM WARNING] You have searched for "${G}" using ${he.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.`};S.push(ye),b.push(ye)}else if(he.size===R0){P(`${p.yellow} \u26A0 Glob core-term warning: ${he.size} different patterns searching for "${G}"${p.reset}`);let ye={role:"user",content:`[SYSTEM WARNING] ${he.size} different glob patterns all target "${G}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};S.push(ye),b.push(ye)}}}let pe=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),Q=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(pe)||/\/(health|status|ping|ready|alive)\b/.test(pe);if(V&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&Q&&I.includes('"valid":true')){{let M=Bt();if(wn(b,M).percentage>=60){let{messages:N,tokensRemoved:G}=Nn(b,M);G>0&&(b=N,console.log(`${p.dim} [pre-stop-compress \u2014 ~${G} tokens freed before STOP injection, now ${Math.round(wn(b,M).percentage)}%]${p.reset}`))}}let C={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};S.push(C),b.push(C),console.log(`${p.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${p.reset}`)}if(V&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&pe&&/\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(pe)&&(Ve++,P(`${p.dim} [bash write detected: _bashModifiedFiles=${Ve}]${p.reset}`)),I.startsWith("BLOCKED:")){if(gs++,gs>=Zd){P(`${p.red} \u2716 Loop abort: ${gs} consecutive blocked calls \u2014 model not heeding BLOCKED messages${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne,{suppressHint:!0}),$e(S);return}}else gs=0;if(V)ms=0,wi=!0;else if(ms++,ms===N0){P(`${p.yellow} \u26A0 Loop warning: ${ms} consecutive tool errors \u2014 possible stuck loop${p.reset}`);let C={role:"user",content:`[SYSTEM WARNING] ${ms} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};S.push(C),b.push(C)}else if(ms>=M0){P(`${p.red} \u2716 Loop abort: ${ms} consecutive errors \u2014 aborting stuck loop${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne,{suppressHint:!0}),$e(S);return}if(V&&y.fnName==="read_file"&&y.args&&y.args.path){Ee.add(y.args.path),(H.has(y.args.path)||us.has(y.args.path)||Zo.has(y.args.path))&&(ro.push(y.args.path),Vn=!1,Dn=0),us.delete(y.args.path),Zo.delete(y.args.path);let C=Ks(ao,y.args.path);{let G=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,he=y.args.line_start!=null?parseInt(y.args.line_end,10)||G+350:350;zn.has(y.args.path)||zn.set(y.args.path,[]),zn.get(y.args.path).push([G,he])}if(y._scrollWarn){let{sectionCount:G,path:he}=y._scrollWarn,ye={role:"user",content:`[SYSTEM WARNING] "${he}" \u2014 you have now read ${G} 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.`};S.push(ye),b.push(ye),P(`${p.yellow} \u26A0 Scroll warning: "${he.split("/").slice(-2).join("/")}" \u2014 ${G} sections read \u2014 use grep instead${p.reset}`)}let M=y.args.path.split("/").slice(-2).join("/"),A=!y.args?.line_start&&!y.args?.line_end,N=ge&&xe==="plan";if(!N&&A&&C===A0){{let he=Bt();if(wn(b,he).percentage>=60){let{messages:oe}=Nn(b,he);b=oe}}P(`${p.yellow} \u26A0 Loop warning: "${M}" read unbounded ${C}\xD7 \u2014 use line_start/line_end${p.reset}`);let G={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${C}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};S.push(G),b.push(G)}else if(!N&&A&&C>=O0){P(`${p.red} \u2716 Loop abort: "${M}" read unbounded ${C}\xD7 \u2014 aborting runaway read loop${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne,{suppressHint:!0}),$e(S);return}}if(y.fnName==="spawn_agents"){let C=(I.match(/\bStatus: done\b/g)||[]).length;if((I.match(/\bStatus: truncated\b/g)||[]).length>0&&C===0){if(ys++,ys===L0){P(`${p.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${ys}\xD7 in a row${p.reset}`);let A={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${ys}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};S.push(A),b.push(A)}else if(ys>=I0){console.log(`${p.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${ys}\xD7 \u2014 aborting stuck swarm${p.reset}`),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne,{suppressHint:!0}),$e(S);return}}else C>0&&(ys=0)}}if(Ll&&Vn&&!(ge&&xe==="verify")){let w=await gl(H),y=await ci(H),I={role:"user",content:gw(H,w,y)};S.push(I),b.push(I),P(`${p.cyan} \u21B3 Post-edit verify prompt injected (${w.length} checks, ${y.length} tests)${p.reset}`)}let W0=[...Mt.values()].reduce((w,y)=>w+y,0);if(zr(H,Ve)&&W0>=2){let w=`Implementation stalled before edits.
1607
+ `),Go=w,Yo=Date.now()),po=null,en=null}if(!tr.skipSummaries){let w=G0.filter((j,V)=>!(Ee[V]&&Ee[V].fnName==="ask_user"));for(let j of w)gd(j,$d,kd)||(console.log(j),$d=j,kd=Date.now());let y=Ee.filter(j=>j&&j.fnName!=="ask_user").map(j=>j.fnName),M=b0.record(0,y,ve,W);M&&zC(M)}for(let w of Ee){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:"))&&(ys++,ys>=ef)){P(`${p.red} \u2716 Loop abort: ${ys} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne,{suppressHint:!0}),_e(S);return}}let jl=!1;for(let w=0;w<Ee.length;w++){let y=Ee[w];if(!y.canExecute)continue;let M=mt[w].content,j=M.split(`
1608
+ `)[0],V=!j.startsWith("ERROR")&&!j.startsWith("CANCELLED")&&!j.startsWith("Command failed")&&!j.startsWith("EXIT")&&!/old_text not found/i.test(j);if(y.fnName==="git_status"&&V&&(Qr="git_status",Qs=M),y.fnName==="bash"&&y.canExecute&&typeof y.args?.command=="string"){let C=y.args.command;/git\s+status\s+--short\s+--branch\b/.test(C)&&(Qr="bash:git status --short --branch",Qs=M),/git\s+push\b/.test(C)&&(ds=M,V&&!ds.startsWith("EXIT")&&(/\bEverything up[- ]to[- ]date\b/i.test(ds)||/\bTo\s+\S+/i.test(ds)||/\bWriting objects\b/i.test(ds))&&(ul=!0))}if(!V&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&j.includes("old_text not found")){let C=Mt.get(y.args.path)||0;Mt.set(y.args.path,C+1)}if(!V&&y.fnName==="bash"&&ni.size>0){let C=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(C))for(let[A]of ni)Mt.has(A)||(Mt.set(A,1),P(`${p.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${A.split("/").pop()}"${p.reset}`))}if(!V&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(j)){if(cs++,cs>=2){P(`${p.yellow} \u26A0 File-not-found streak: ${cs} consecutive misses \u2014 forcing search${p.reset}`);let C={role:"user",content:`[SYSTEM] ${cs} 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.`};S.push(C),b.push(C)}}else V&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(cs=0);if(V&&y.fnName==="write_file"&&y.args?.path){let C=y.args.path.split("/").pop(),L=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(C)&&!L){P(`${p.yellow} \u26A0 Temp file: "${C}" \u2014 delete with bash rm when done to keep the workspace clean${p.reset}`);let N={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.`};S.push(N),b.push(N)}}if(V&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Mt.delete(y.args.path),W.add(y.args.path);for(let A of so)!A.done&&y.args.path.endsWith(A.file.split("/").pop())&&(A.done=!0,P(`${p.green} \u2713 TODO done: ${A.file}${p.reset}`));let C=Vs(w0,y.args.path),L=y.args.path.split("/").slice(-2).join("/");if(C===_0){P(`${p.yellow} \u26A0 Loop warning: "${L}" edited ${C}\xD7 \u2014 possible edit loop${p.reset}`);let A={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${C}\xD7. One more edit max, then move on.`};S.push(A),b.push(A)}else if(C>=$0){P(`${p.red} \u2716 Loop abort: "${L}" edited ${C}\xD7 \u2014 aborting to prevent runaway loop${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne,{suppressHint:!0}),_e(S);return}he&&xe==="verify"||(Vn=!0,Dn=0,jl=!0)}if(V&&y.canExecute&&he&&(ps=0),V&&y.canExecute&&ct&&he&&xe==="plan"&&wA.has(y.fnName)&&(Ut++,$A(y.fnName,y.args)&&ci++,Ut>=yl&&!dl)){dl=!0;let C={role:"user",content:Kn()};S.push(C),b.push(C),P(`${p.yellow} \u26A0 Bounded backlog plan: ${Ut} read/search tools used \u2014 requiring a decision${p.reset}`)}if(V&&y.canExecute&&!(he&&xe==="plan")){let C=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){cn=0,un=!1,_n=0,dn++;let oe=y.args?.path||y.args?.file_path;oe&&(y.fnName==="write_file"?(us.add(oe),jn.delete(oe),zn.delete(oe),Qo.delete(oe)):(us.delete(oe),md(jn,oe,1),zn.delete(oe),Qo.add(oe)))}else if(C.includes(y.fnName)){if(cn++,un&&_n++,he&&xe==="implement"&&y.fnName==="read_file"){let oe=y.args?.path||y.args?.file_path||"";if(oe&&us.has(oe)){let D={role:"user",content:`[SYSTEM] You just created and re-read "${oe}". Do NOT analyze further. Apply the requested refactor now with edit_file.`};S.push(D),b.push(D),P(`${p.yellow} \u26A0 Fresh-write nudge: ${oe} \u2014 refactor directly after re-read${p.reset}`)}}if(he&&xe==="implement"&&y.fnName==="read_file"&&so.length>0){let oe=y.args?.path||y.args?.file_path||"",D=so.find(fe=>!fe.done&&oe.endsWith(fe.file.split("/").pop()));if(D){let fe={role:"user",content:`[TODO OBSERVER] You already analyzed "${D.file}" in the plan phase. Action: ${D.action}
1609
+ Do NOT re-read \u2014 apply the edit directly with edit_file.`};S.push(fe),b.push(fe),P(`${p.yellow} \u26A0 TODO nudge: ${D.file} \u2014 already analyzed, edit directly${p.reset}`)}}he&&xe==="implement"&&Vn&&Dn<1&&(Dn++,jl=!0)}if(he&&xe==="verify"&&Xo++,V&&LA(y)){let oe=String(y.args?.command||"").trim();oe&&ro.push(oe.slice(0,160)),Vn=!1,Dn=0}let A=o.postEditCap,N=he&&xe==="implement"?Math.min(tf,10):tf,G=Et?8:wi?dn>0?4:6:an?dn>0?6:10:dn>0?A:N,me=6,be=!he&&un&&(Et&&_n>=me||an&&dn>=3&&_n>=me||_n>=me);if(Gr<2&&!un&&cn>=3&&W.size===0){let oe=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,D=Date.now()-Ne,fe=Gr===0?.4:.65;if(oe>0&&D>oe*fe){Gr++;let Le=Math.round(D/6e4),Ue=Math.round(D/oe*100);P(`${p.yellow} \u26A0 Time nudge #${Gr}: ${Le}m elapsed (${Ue}%), ${cn} reads, 0 edits${p.reset}`);let it={role:"user",content:Gr===1?`[SYSTEM] ${Ue}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${Ue}% 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.`};S.push(it),b.push(it)}}if(be&&C.includes(y.fnName)){let oe=Et?`root cause already identified (${Ft})`:_n>=me?`${cn} consecutive reads without an edit`:`${dn} file edit(s) already made`;P(`${p.red} \u2716 Blocked read-only tool: cap fired, ${oe}${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:Et?`BLOCKED: root cause already identified (${Ft}). Use edit_file to fix the issue \u2014 do not read more files.`:an?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":_n>=me?`BLOCKED: You have read ${cn} 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: ${dn} 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(cn>=G&&!un){if(un=!0,wi&&(Pl=!0),P(`${p.yellow} \u26A0 Investigation cap: ${cn} read-only calls without an edit \u2014 forcing implementation${p.reset}`),he&&xe==="plan"){let fe=[...b].reverse().find(it=>it.role==="assistant"),Le=typeof fe?.content=="string"?fe.content:"",Ue=await Uo("implement",Le);Ue&&(S.push(Ue),b.push(Ue),dt=0,Lt=ls("implement"))}let oe;Et?oe=`[SYSTEM] Root cause was already identified (${Ft}). Edit the file now \u2014 do not read more files.`:wi?oe="[SYSTEM] You have enough evidence to write the requested summary/document now. Use write_file or edit_file to produce the deliverable, and stop reading more files unless a required section is still unsupported.":Xt?oe="[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.":oe="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let D={role:"user",content:oe};S.push(D),b.push(D)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let C=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),L=Vs(Qd,C);if(L===k0){P(`${p.yellow} \u26A0 Loop warning: same bash command run ${L}\xD7 \u2014 possible debug loop${p.reset}`);let A={role:"user",content:`[SYSTEM WARNING] Same bash command ${L}\xD7. Debug loop detected \u2014 try a different approach.`};S.push(A),b.push(A)}else if(L>=x0){P(`${p.red} \u2716 Loop abort: same bash command run ${L}\xD7 \u2014 aborting runaway debug loop${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne,{suppressHint:!0}),_e(S);return}}if(y.fnName==="ssh_exec"){rn++;{let A=(mt[w]?.content??"").split(`
1610
+ `).map(N=>N.trim()).find(N=>N.length>0&&!N.startsWith("**")&&(N.startsWith("EXIT")||/^[\w./-]+:\s/.test(N)||N.startsWith("bash:")||N.startsWith("sh:")))??"";if(A){if(A===ll?Js++:(ll=A,Js=1),Js===3&&!Xt){P(`${p.yellow} \u26A0 SSH repeated-error: "${A.slice(0,60)}" returned ${Js}\xD7 \u2014 nudging to change approach${p.reset}`);let N={role:"user",content:`[SYSTEM WARNING] The last ${Js} SSH commands all failed with the same error: "${A}". 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).`};S.push(N),b.push(N)}}else ll="",Js=0}if(rn>=F0){P(`${p.red} \u2716 SSH storm abort: ${rn} consecutive ssh_exec calls \u2014 aborting${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne,{suppressHint:!0}),_e(S);return}else if(rn===er){{let A=Bt(),{messages:N}=Nn(b,A);b=N}Xt=!0,Xa++,P(`${p.yellow} \u26A0 SSH storm warning (#${Xa}): ${rn} consecutive ssh_exec calls \u2014 blocking further SSH${p.reset}`);let L={role:"user",content:Et?`[SYSTEM WARNING] ${rn} consecutive SSH calls. Root cause identified (${Ft}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${rn} 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.`};S.push(L),b.push(L)}}else y.canExecute&&(rn=0);if(y.fnName==="bash"&&y.canExecute){let A=(mt[w]?.content??"").split(`
1611
+ `).map(N=>N.trim()).find(N=>N.length>0&&(N.startsWith("EXIT")||/^[\w./-]+:\s/.test(N)||N.startsWith("bash:")||N.startsWith("sh:")))??"";if(A){if(A===cl?Zs++:(cl=A,Zs=1),Zs===3){P(`${p.yellow} \u26A0 Bash repeated-error: "${A.slice(0,60)}" returned ${Zs}\xD7 \u2014 nudging to change approach${p.reset}`);let N={role:"user",content:`[SYSTEM WARNING] The last ${Zs} bash commands all failed with the same error: "${A}". 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).`};S.push(N),b.push(N)}}else cl="",Zs=0}if(y.fnName==="bash"&&y.canExecute&&!Yr&&y.args?.command){let C=mt[w]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!C.startsWith("EXIT")&&!C.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(C)||C.includes("files changed")||C.includes("file changed")||C.includes("insertions(+)")||C.includes("create mode"))){Yr=!0,zr=0;let N=ln?4:2;P(`${p.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max ${N} git status/diff/log)${p.reset}`);let G=ln?{role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. This is a gated automation workflow: ensure you still capture final-state evidence. Next: push (if required by the prompt), then run `git status --short --branch` once and include its output in the final automation report. Avoid extra git diff/log unless needed to explain a blocker."}:{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."};S.push(G),b.push(G)}}if(Yr&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(zr++,zr>(ln?4:2))){P(`${p.yellow} \u26A0 Post-commit git verification blocked (call ${zr})${p.reset}`);let A={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(zr-1)+" git verification commands after committing. "+(ln?"In gated automation workflows, keep tool use minimal: you already have enough evidence for the final report. Write the final automation report now and stop.":"The commit is confirmed. Write your final summary NOW and do not make any more tool calls.")};S.push(A),b.push(A)}if(V&&y.fnName==="grep"&&M&&!M.startsWith("(no matches)")){let C=M.split(`
1612
+ `);for(let L of C){let A=L.indexOf(":");if(A>0){let N=L.substring(0,A);N.startsWith("/")&&!N.includes(" ")&&ei.add(N)}else L.startsWith("/")&&!L.includes(" ")&&ei.add(L.trim())}}{let C=["grep","search_files","glob","glob_files"].includes(y.fnName);if(C&&V&&M&&(M.startsWith("(no matches)")||M.trim()===""||/^No matches found/.test(M.trim())||/^\(0 results\)/.test(M.trim()))){if(vl++,vl===3){P(`${p.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${p.reset}`);let A={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."};S.push(A),b.push(A)}}else C&&V&&M&&M.trim().length>0&&(vl=0)}if(V&&y.fnName==="grep"&&y.args&&y.args.pattern){let C=`${y.args.pattern}|${y.args.path||""}`,L=Vs(S0,C);if(L===v0){P(`${p.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${L}\xD7 \u2014 possible search loop${p.reset}`);let A={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${L}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};S.push(A),b.push(A)}else if(L>=E0){P(`${p.red} \u2716 Loop abort: grep pattern run ${L}\xD7 \u2014 aborting runaway search loop${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne,{suppressHint:!0}),_e(S);return}if(y.args.path){let A=Vs(Tl,y.args.path),N=Mn(lo,y.args.path)>=1;if(A===(N?1:T0)){let me=y.args.path.split("/").slice(-2).join("/");P(`${p.yellow} \u26A0 Loop warning: "${me}" grepped ${A}\xD7 with different patterns \u2014 context flood risk${p.reset}`);let be={role:"user",content:N?`[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 ${A}\xD7 \u2014 use the search results already in context instead of searching again.`};S.push(be),b.push(be)}}}if(V&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(M&&!M.startsWith("(no matches)")){let N=M.split(`
1613
+ `);for(let G of N)(G.startsWith("/")&&!G.includes(" ")||!G.includes(":")&&!G.startsWith("["))&&ti.add(G.trim())}let C=y.args.pattern||y.args.query||y.args.path||"",L=Vs(R0,C);if(L===C0){P(`${p.yellow} \u26A0 Loop warning: glob pattern "${C.slice(0,40)}" run ${L}\xD7 \u2014 possible search loop${p.reset}`);let N={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${L}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};S.push(N),b.push(N)}else if(L>=A0){P(`${p.red} \u2716 Loop abort: glob pattern run ${L}\xD7 \u2014 aborting runaway search loop${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne,{suppressHint:!0}),_e(S);return}let A=C.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(N=>N.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(N));for(let N of A){let G=N.toLowerCase();nl.has(G)||nl.set(G,new Set);let me=nl.get(G);if(me.add(C),me.size===P0){P(`${p.red} \u2716 Glob core-term block: ${me.size} different patterns all searching for "${G}" \u2014 search loop${p.reset}`);let be={role:"user",content:`[SYSTEM WARNING] You have searched for "${G}" using ${me.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.`};S.push(be),b.push(be)}else if(me.size===O0){P(`${p.yellow} \u26A0 Glob core-term warning: ${me.size} different patterns searching for "${G}"${p.reset}`);let be={role:"user",content:`[SYSTEM WARNING] ${me.size} different glob patterns all target "${G}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};S.push(be),b.push(be)}}}let de=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),Q=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(de)||/\/(health|status|ping|ready|alive)\b/.test(de);if(V&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&Q&&M.includes('"valid":true')){{let L=Bt();if(wn(b,L).percentage>=60){let{messages:N,tokensRemoved:G}=Nn(b,L);G>0&&(b=N,console.log(`${p.dim} [pre-stop-compress \u2014 ~${G} tokens freed before STOP injection, now ${Math.round(wn(b,L).percentage)}%]${p.reset}`))}}let C={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};S.push(C),b.push(C),console.log(`${p.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${p.reset}`)}if(V&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&de&&/\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(de)&&(He++,P(`${p.dim} [bash write detected: _bashModifiedFiles=${He}]${p.reset}`)),M.startsWith("BLOCKED:")){if(ys++,ys>=ef){P(`${p.red} \u2716 Loop abort: ${ys} consecutive blocked calls \u2014 model not heeding BLOCKED messages${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne,{suppressHint:!0}),_e(S);return}}else ys=0;if(V)gs=0,_i=!0;else if(gs++,gs===I0){P(`${p.yellow} \u26A0 Loop warning: ${gs} consecutive tool errors \u2014 possible stuck loop${p.reset}`);let C={role:"user",content:`[SYSTEM WARNING] ${gs} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};S.push(C),b.push(C)}else if(gs>=j0){P(`${p.red} \u2716 Loop abort: ${gs} consecutive errors \u2014 aborting stuck loop${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne,{suppressHint:!0}),_e(S);return}if(V&&y.fnName==="read_file"&&y.args&&y.args.path){ve.add(y.args.path),(W.has(y.args.path)||us.has(y.args.path)||Qo.has(y.args.path))&&(io.push(y.args.path),Vn=!1,Dn=0),us.delete(y.args.path),Qo.delete(y.args.path);let C=Vs(lo,y.args.path);{let G=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,me=y.args.line_start!=null?parseInt(y.args.line_end,10)||G+350:350;zn.has(y.args.path)||zn.set(y.args.path,[]),zn.get(y.args.path).push([G,me])}if(y._scrollWarn){let{sectionCount:G,path:me}=y._scrollWarn,be={role:"user",content:`[SYSTEM WARNING] "${me}" \u2014 you have now read ${G} 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.`};S.push(be),b.push(be),P(`${p.yellow} \u26A0 Scroll warning: "${me.split("/").slice(-2).join("/")}" \u2014 ${G} sections read \u2014 use grep instead${p.reset}`)}let L=y.args.path.split("/").slice(-2).join("/"),A=!y.args?.line_start&&!y.args?.line_end,N=he&&xe==="plan";if(!N&&A&&C===N0){{let me=Bt();if(wn(b,me).percentage>=60){let{messages:oe}=Nn(b,me);b=oe}}P(`${p.yellow} \u26A0 Loop warning: "${L}" read unbounded ${C}\xD7 \u2014 use line_start/line_end${p.reset}`);let G={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${C}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};S.push(G),b.push(G)}else if(!N&&A&&C>=M0){P(`${p.red} \u2716 Loop abort: "${L}" read unbounded ${C}\xD7 \u2014 aborting runaway read loop${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne,{suppressHint:!0}),_e(S);return}}if(y.fnName==="spawn_agents"){let C=(M.match(/\bStatus: done\b/g)||[]).length;if((M.match(/\bStatus: truncated\b/g)||[]).length>0&&C===0){if(bs++,bs===D0){P(`${p.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${bs}\xD7 in a row${p.reset}`);let A={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${bs}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};S.push(A),b.push(A)}else if(bs>=q0){console.log(`${p.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${bs}\xD7 \u2014 aborting stuck swarm${p.reset}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne,{suppressHint:!0}),_e(S);return}}else C>0&&(bs=0)}}if(jl&&Vn&&!(he&&xe==="verify")){let w=await bl(W),y=await ui(W),M={role:"user",content:ww(W,w,y)};S.push(M),b.push(M),P(`${p.cyan} \u21B3 Post-edit verify prompt injected (${w.length} checks, ${y.length} tests)${p.reset}`)}let Y0=[...Mt.values()].reduce((w,y)=>w+y,0);if(Fo(W,He)&&Y0>=2){let w=`Implementation stalled before edits.
1614
1614
 
1615
1615
  The implementation phase attempted file edits, but the edits did not match the current file content. Stopping without commit or push so the workflow does not falsely report success.`,y={role:"assistant",content:w};S.push(y),b.push(y),console.log(`
1616
- ${w}`),$e(S),vt(S);break e}{let y=mt.reduce((I,j)=>I+(typeof j.content=="string"?j.content.length:0),0);if(y>2e5){let I=mt.map((j,V)=>({i:V,len:typeof j.content=="string"?j.content.length:0})).sort((j,V)=>V.len-j.len);for(let{i:j,len:V}of I){if(y<=2e5)break;let pe=y-2e5,Q=Math.max(V-pe,500);Q<V&&typeof mt[j].content=="string"&&(mt[j]={...mt[j],content:mt[j].content.substring(0,Q)+`
1617
- ...(truncated ${V-Q} chars \u2014 per-message budget)`},y-=V-Q)}}}for(let w of mt)S.push(w),b.push(w);if(gi){let w=ad(In());if(ge&&xe==="implement"&&H.size===0&&Ve===0||zr(H,Ve)){let I=`Implementation stalled before edits.
1616
+ ${w}`),_e(S),bt(S);break e}{let y=mt.reduce((M,j)=>M+(typeof j.content=="string"?j.content.length:0),0);if(y>2e5){let M=mt.map((j,V)=>({i:V,len:typeof j.content=="string"?j.content.length:0})).sort((j,V)=>V.len-j.len);for(let{i:j,len:V}of M){if(y<=2e5)break;let de=y-2e5,Q=Math.max(V-de,500);Q<V&&typeof mt[j].content=="string"&&(mt[j]={...mt[j],content:mt[j].content.substring(0,Q)+`
1617
+ ...(truncated ${V-Q} chars \u2014 per-message budget)`},y-=V-Q)}}}for(let w of mt)S.push(w),b.push(w);if(yi){let w=cd(In());if(he&&xe==="implement"&&W.size===0&&He===0||Fo(W,He)){let M=`Implementation stalled before edits.
1618
1618
 
1619
- The implementation phase reached the tool-call budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,j={role:"assistant",content:I};S.push(j),b.push(j),console.log(`
1620
- ${I}`),$e(S),vt(S);break e}let y={role:"user",content:uw(Sn,w)};S.push(y),b.push(y),El=!0,Tl++}let H0=bi&&Se.some((w,y)=>{if(!w||!["write_file","edit_file","patch_file"].includes(w.fnName))return!1;let I=w.args?.path||w.args?.file_path;return gC(I)&&typeof mt[y]?.content=="string"&&!mt[y].content.startsWith("ERROR")&&!mt[y].content.startsWith("BLOCKED:")});if($n()&&!n.skillLoop&&Al&&H0){P(`${p.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${p.reset}`),je(ue,Pe,H,Ee,Ne),$e(S);break e}if(Xa(S,b),!Et)for(let w=0;w<mt.length;w++){if(!Se[w]||Se[w].fnName!=="ssh_exec")continue;let y=mt[w];if(!y||typeof y.content!="string")continue;let I=fd(y.content);if(I){Et=!0,Ft=I.slice(0,120),ln=0,cn=!1,_n=0,P(`${p.yellow} \u26A1 Root cause detected: ${Ft} \u2014 fix phase (read budget: 3)${p.reset}`);let j={role:"user",content:`[SYSTEM] Root cause identified: ${Ft}. Read only the file that needs fixing, then edit it. Do not read other files.`};S.push(j),b.push(j);break}}for(let w=0;w<mt.length;w++){let y=Se[w];if(!y)continue;let I=typeof mt[w]?.content=="string"?mt[w].content:"";if(y.fnName==="create_task"){let j=I.match(/Task #(\d+) created/),V=typeof y.args?.subject=="string"?y.args.subject:"";j&&V&&ii.set(j[1],V)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!I.startsWith("BLOCKED:")&&I.trim().length>0){let V=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),pe=V.split(/[._\-/]/).filter(Q=>Q.length>2);for(let[Q,F]of ii){if(ai.has(Q))continue;let C=F.toLowerCase().split(/\W+/).filter(A=>A.length>3);pe.filter(A=>C.some(N=>N.includes(A)||A.includes(N))).length>=1&&(ai.add(Q),P(`${p.green} \u2714 Auto-matched task #${Q} to ${V}: ${F.slice(0,60)}${p.reset}`))}}}{let w=Bt();if(wn(b,w).percentage>=78){let{messages:I,tokensRemoved:j}=Nn(b,w);j>0&&(b=I,console.log(`${p.dim} [auto-compressed \u2014 ~${j} tokens freed, now ${Math.round(wn(b,w).percentage)}%]${p.reset}`))}}if($n()&&!n.skillLoop&&(Se.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?io=0:(io===0&&(Xd=H.size),io++),io>=9&&ue>=4&&H.size===Xd)){P(`${p.green} \u2713 Stagnation exit: ${io} read-only iterations, no new file changes${p.reset}`),process.stdout.isTTY&&process.stderr.write(`${p.yellow} \u26A0 Stagnation detected: ${io} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${p.reset}
1621
- `),$&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne),$e(S);break e}let lf=TA();if(lf){let w={role:"user",content:`[User note mid-run]: ${lf}`};S.push(w),b.push(w),console.log(`${p.cyan} \u270E Context added${p.reset}`)}}if(ut>=Lt){if($&&($.stop(),$=null),k(null),je(ue,Pe,H,Ee,Ne),$e(S),vt(S),ge&&xe==="plan"){let Ce=[...S].reverse().find(He=>He.role==="assistant"),ke=typeof Ce?.content=="string"?Ce.content:"";if(pt&&Ut>=ml&&!ul(ke)){let He=`no safe task found
1619
+ The implementation phase reached the tool-call budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,j={role:"assistant",content:M};S.push(j),b.push(j),console.log(`
1620
+ ${M}`),_e(S),bt(S);break e}let y={role:"user",content:fw(Sn,w)};S.push(y),b.push(y),Rl=!0,Cl++}let z0=wi&&Ee.some((w,y)=>{if(!w||!["write_file","edit_file","patch_file"].includes(w.fnName))return!1;let M=w.args?.path||w.args?.file_path;return wC(M)&&typeof mt[y]?.content=="string"&&!mt[y].content.startsWith("ERROR")&&!mt[y].content.startsWith("BLOCKED:")});if($n()&&!n.skillLoop&&Pl&&z0){P(`${p.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${p.reset}`),Me(ce,Ae,W,ve,Ne),_e(S);break e}if(Za(S,b),!Et)for(let w=0;w<mt.length;w++){if(!Ee[w]||Ee[w].fnName!=="ssh_exec")continue;let y=mt[w];if(!y||typeof y.content!="string")continue;let M=hd(y.content);if(M){Et=!0,Ft=M.slice(0,120),cn=0,un=!1,_n=0,P(`${p.yellow} \u26A1 Root cause detected: ${Ft} \u2014 fix phase (read budget: 3)${p.reset}`);let j={role:"user",content:`[SYSTEM] Root cause identified: ${Ft}. Read only the file that needs fixing, then edit it. Do not read other files.`};S.push(j),b.push(j);break}}for(let w=0;w<mt.length;w++){let y=Ee[w];if(!y)continue;let M=typeof mt[w]?.content=="string"?mt[w].content:"";if(y.fnName==="create_task"){let j=M.match(/Task #(\d+) created/),V=typeof y.args?.subject=="string"?y.args.subject:"";j&&V&&ai.set(j[1],V)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!M.startsWith("BLOCKED:")&&M.trim().length>0){let V=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),de=V.split(/[._\-/]/).filter(Q=>Q.length>2);for(let[Q,F]of ai){if(li.has(Q))continue;let C=F.toLowerCase().split(/\W+/).filter(A=>A.length>3);de.filter(A=>C.some(N=>N.includes(A)||A.includes(N))).length>=1&&(li.add(Q),P(`${p.green} \u2714 Auto-matched task #${Q} to ${V}: ${F.slice(0,60)}${p.reset}`))}}}{let w=Bt();if(wn(b,w).percentage>=78){let{messages:M,tokensRemoved:j}=Nn(b,w);j>0&&(b=M,console.log(`${p.dim} [auto-compressed \u2014 ~${j} tokens freed, now ${Math.round(wn(b,w).percentage)}%]${p.reset}`))}}if($n()&&!n.skillLoop&&(Ee.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?ao=0:(ao===0&&(Zd=W.size),ao++),ao>=9&&ce>=4&&W.size===Zd)){if(he&&xe==="implement"&&W.size===0&&He===0||Fo(W,He)){let y=`Implementation stalled before edits.
1622
1621
 
1623
- The bounded backlog plan phase used ${Ut} read/search tools without producing the required selected-improvement decision. Stopping before implementation because the workflow requires choosing one scoped task with files and verification evidence.`,st={role:"assistant",content:He};S.push(st),console.log(`
1624
- ${He}`),$e(S),vt(S);break e}let Jt=await Fo("implement",ke);if(Jt){S.push(Jt),b=[{role:"system",content:await Md()},...S],Lt=ls("implement"),P(`${p.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${p.reset}`);continue e}}else if(ge&&xe==="verify"){P(`${p.yellow} \u26A0 Verify budget exhausted \u2014 completing session${p.reset}`);break e}else if(ge&&xe==="implement"&&(H.size>0||Ve>0)){let Ce=[...S].reverse().find(bs=>bs.role==="assistant"),ke=typeof Ce?.content=="string"?Ce.content:"",Jt=S.find(bs=>bs.role==="user"),He=typeof Jt?.content=="string"?Jt.content:"",st=await Fo("verify",ke,H,He);if(st){S.push(st),b.push(st),Lt=Math.min(ls("verify")+Math.max(0,(H.size-2)*2),20),P(`${p.yellow} \u26A0 Implement budget exhausted after edits \u2014 auto-transitioning to verify${p.reset}`);continue e}}else if(ge&&xe==="implement"&&H.size===0&&Ve===0||zr(H,Ve)){let Ce=`Implementation stalled before edits.
1622
+ The implementation phase kept reading/searching without changing files. Stopping without commit or push so the workflow does not falsely report success.`,M={role:"assistant",content:y};S.push(M),b.push(M),console.log(`
1623
+ ${y}`),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne),_e(S),bt(S);break e}P(`${p.green} \u2713 Stagnation exit: ${ao} read-only iterations, no new file changes${p.reset}`),process.stdout.isTTY&&process.stderr.write(`${p.yellow} \u26A0 Stagnation detected: ${ao} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${p.reset}
1624
+ `),$&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne),_e(S);break e}let uf=OA();if(uf){let w={role:"user",content:`[User note mid-run]: ${uf}`};S.push(w),b.push(w),console.log(`${p.cyan} \u270E Context added${p.reset}`)}}if(dt>=Lt){if($&&($.stop(),$=null),k(null),Me(ce,Ae,W,ve,Ne),_e(S),bt(S),he&&xe==="plan"){let Se=[...S].reverse().find(Ge=>Ge.role==="assistant"),ke=typeof Se?.content=="string"?Se.content:"";if(ct&&Ut>=yl&&!fl(ke)){let Ge=`no safe task found
1625
1625
 
1626
- The plan phase completed, but the implementation phase exhausted its turn budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,ke={role:"assistant",content:Ce};S.push(ke),b.push(ke),console.log(`
1627
- ${Ce}`),$e(S),vt(S);break e}let{getActiveProviderName:le}=$t(),we=le();if(pt&&Vt&&H.size===0&&Ve===0&&!wi){let Ce=`Implementation stalled before edits.
1626
+ The bounded backlog plan phase used ${Ut} read/search tools without producing the required selected-improvement decision. Stopping before implementation because the workflow requires choosing one scoped task with files and verification evidence.`,st={role:"assistant",content:Ge};S.push(st),console.log(`
1627
+ ${Ge}`),_e(S),bt(S);break e}let Zt=await Uo("implement",ke);if(Zt){S.push(Zt),b=[{role:"system",content:await Id()},...S],Lt=ls("implement"),P(`${p.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${p.reset}`);continue e}}else if(he&&xe==="verify"){P(`${p.yellow} \u26A0 Verify budget exhausted \u2014 completing session${p.reset}`);break e}else if(he&&xe==="implement"&&(W.size>0||He>0)){let Se=[...S].reverse().find(ws=>ws.role==="assistant"),ke=typeof Se?.content=="string"?Se.content:"",Zt=S.find(ws=>ws.role==="user"),Ge=typeof Zt?.content=="string"?Zt.content:"",st=await Uo("verify",ke,W,Ge);if(st){S.push(st),b.push(st),Lt=Math.min(ls("verify")+Math.max(0,(W.size-2)*2),20),P(`${p.yellow} \u26A0 Implement budget exhausted after edits \u2014 auto-transitioning to verify${p.reset}`);continue e}}else if(he&&xe==="implement"&&W.size===0&&He===0||Fo(W,He)){let Se=`Implementation stalled before edits.
1628
1628
 
1629
- The bounded backlog workflow reached its turn budget after planning but before changing files. Stopping without commit or push so the workflow does not falsely report success.`,ke={role:"assistant",content:Ce};S.push(ke),b.push(ke),console.log(`
1630
- ${Ce}`),$e(S),vt(S);break e}if(we==="ollama"&&Cl<tf){if(H.size===0&&!wi){console.log(`${p.yellow} \u26A0 Max iterations reached with no progress. Stopping.${p.reset}`);break e}Cl++,Lt=20,console.log(`${p.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Cl}/${tf}) \u2500\u2500${p.reset}`);continue e}if(console.log(`
1631
- ${p.yellow}\u26A0 Max iterations reached.${p.reset}`),await ww(" Continue for 20 more turns?")){Lt=20;continue e}console.log(`${p.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${p.reset}`)}break e}await yi()}function Fw(t,e,n,o=!1){return!o&&t&&e&&e.isComplex&&e.estimatedGoals>=n}Bw.exports={processInput:XA,clearConversation:FA,getConversationLength:UA,getConversationMessages:WA,setConversationMessages:HA,setAbortSignalGetter:JC,setMaxIterations:XC,invalidateSystemPromptCache:$d,clearToolFilterCache:rA,getCachedFilteredTools:Ew,buildSystemPrompt:Md,splitSystemPrompt:qA,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Nd,getProjectContextHash:Tw,_inferVerificationCommands:gl,_inferRelevantTests:ci,_inferSymbolTargets:Iw,_buildSymbolHintBlock:jw,_detectResponseLanguage:qd,_isSimpleDirectAnswerPrompt:Dw,_claimsVerificationOrCompletion:yw,_statesVerificationGap:bw,_shouldAutoOrchestrate:Fw,_shouldSkipPlanPhaseForDirectCreation:Ad,_hasAutomationOrPreflightGate:ui,_extractDirectTaskPaths:oi,_isBoundedBacklogPlanningPrompt:Ow,_buildBoundedBacklogPlanInstruction:Kn,_looksLikeBoundedBacklogDecision:ul,_looksLikeGatedAutomationFinalSummary:Od,buildUserContent:Sw,_detectImageURLs:$w,_downloadImageURL:kw,_grabClipboardImage:xw,detectFrustration:vw,detectAndTruncateLoop:gd,injectMidRunNote:EA,resetSessionTracking:qw}});var $t=J((vN,Yw)=>{var{OllamaProvider:JA,getOllamaRecommendations:ZA}=mf(),{OpenAIProvider:QA}=Wl(),{DeepSeekProvider:eO}=$f(),{AnthropicProvider:tO}=vf(),{GeminiProvider:nO}=Cf(),{LocalProvider:sO}=Pf(),{checkBudget:oO,formatProviderCostMode:rO,getProviderCostMode:iO}=Di(),Wd={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",deepseek:"deepseek-v4-pro",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",deepseek:"deepseek-v4-pro",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",deepseek:"deepseek-v4-flash",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},Ud=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Ww={};for(let[t,e]of Object.entries(Wd))for(let n of Object.values(e))Ww[n]=t;function Hw(t,e){let n=Ww[t];return n&&Wd[n][e]||t}function bl(){return["No configured provider available.","Lowest-cost path: run /setup and choose Ollama Cloud, or set OLLAMA_API_KEY plus DEFAULT_PROVIDER=ollama.","Local free path: start Ollama locally, pull a coding model, then use /model local:<model>.","Paid fallback: set DEEPSEEK_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, or GEMINI_API_KEY and use /fallback only when you want paid backup."].join(`
1632
- `)}var nt={},Tt=null,bt=null,so=[];function Xt(){let t=process.env.NEX_MOCK_PROVIDER==="1";if(Object.keys(nt).length>0){if(t&&!nt.mock){let{MockProvider:s}=Jl();Xn("mock",new s)}t&&nt.mock&&Tt!=="mock"&&(Tt="mock",bt=nt.mock.defaultModel||"mock-model",so=[],di());return}if(Xn("ollama",new JA),Xn("openai",new QA),Xn("deepseek",new eO),Xn("anthropic",new tO),Xn("gemini",new nO),Xn("local",new sO),t){let{MockProvider:s}=Jl();Xn("mock",new s)}let e=process.env.DEFAULT_PROVIDER||"ollama",n=process.env.DEFAULT_MODEL||null;t?(Tt="mock",bt=nt.mock?.defaultModel||"mock-model",so=[]):nt[e]?(Tt=e,bt=n||nt[e].defaultModel):(Tt="ollama",bt="kimi-k2.5");let o=process.env.FALLBACK_CHAIN;o&&(so=o.split(",").map(s=>s.trim()).filter(Boolean))}function Xn(t,e){nt[t]=e}function aO(t){return Xt(),nt[t]||null}function Hd(){return Xt(),nt[Tt]||null}function lO(){return Xt(),Tt}function cO(){return Xt(),bt}function uO(){Xt();let t=Hd();if(!t)return{id:bt,name:bt,provider:Tt};let e=t.getModel(bt);return e?{...e,provider:Tt}:{id:bt,name:bt,provider:Tt}}function Gd(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(nt[n]||["ollama","openai","deepseek","anthropic","gemini","local","mock"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function dO(t){Xt();let{provider:e,model:n}=Gd(t);if(e){let s=nt[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(Tt=e,bt=n,di(),!0):!1}let o=Hd();if(o&&o.getModel(n))return bt=n,di(),!0;for(let[s,r]of Object.entries(nt))if(r.getModel(n))return Tt=s,bt=n,di(),!0;return!1}function di(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ju();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Pn();t()}catch{}}function fO(){Xt();let t=new Set;for(let e of Object.values(nt))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function pO(){return Xt(),Object.entries(nt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===Tt&&n.id===bt}))}))}function hO(){Xt();let t=[];for(let[e,n]of Object.entries(nt)){let o=n.isConfigured();for(let s of Object.values(n.getModels()))t.push({spec:`${e}:${s.id}`,name:s.name,provider:e,configured:o,maxTokens:s.maxTokens,contextWindow:s.contextWindow,capability:s.capability,speed:s.speed,quality:s.quality,recommendedFor:s.recommendedFor||[]})}return t}function mO(t="coding",e={}){Xt();let n=e.limit||5,o=e.configuredOnly!==!1,s=[],r=nt.ollama;if(r&&(!o||r.isConfigured()))for(let i of ZA(t,n))s.push({...i,spec:`ollama:${i.id}`,provider:"ollama",configured:r.isConfigured()});if(s.length>=n)return s.slice(0,n);for(let[i,a]of Object.entries(nt)){if(i==="ollama"||o&&!a.isConfigured())continue;let l=a.getModel(a.defaultModel);if(l&&(s.push({...l,spec:`${i}:${l.id}`,provider:i,configured:a.isConfigured()}),s.length>=n))break}return s}function gO(t){so=Array.isArray(t)?t:[]}function yO(){return[...so]}function Uw(t){let e=t.message||"",n=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ECONNRESET"||n==="EHOSTUNREACH"||n==="ENETUNREACH"||n==="EPIPE"||n==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function Gw(t){let e=[Tt,...so.filter(r=>r!==Tt)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],a=nt[i];if(!a||!a.isConfigured())continue;s++;let l=oO(i);if(!l.allowed){o++,n=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}let c=r>0,u=c?Hw(bt,i):bt;try{if(c){let d=iO(i).label;process.stderr.write(` [fallback: ${i}:${u} \xB7 ${d}]
1633
- `)}return await t(a,i,u)}catch(d){if(n=d,!Uw(d)||r>=e.length-1)throw d;if(i==="ollama"&&Ud.length>0){let f=u;for(let h of Ud)if(h!==f)try{return process.stderr.write(` [ollama fallback: ${h}]
1634
- `),await t(a,i,h)}catch(m){if(n=m,!Uw(m))throw m}}continue}}throw o>0&&o===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):s===0?new Error(bl()):n||new Error(bl())}async function bO(t,e,n={}){Xt();let o=n.model,s=o?(()=>{let{model:i}=Gd(o);return i||o})():void 0,r=s!==o?{...n,model:s}:n;return Gw((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function wO(t,e,n={}){if(Xt(),n.provider){let o=nt[n.provider];if(!o||!o.isConfigured()){let r=rO(n.provider);throw new Error(`Provider '${n.provider}' is not available (${r}).
1635
- `+bl())}let s={model:n.model||bt,...n};try{return await o.chat(t,e,s)}catch(r){if(typeof o.stream=="function")try{return await o.stream(t,e,{...s,onToken:()=>{}})}catch{}throw r}}return Gw(async(o,s,r)=>{try{return await o.chat(t,e,{model:r,...n})}catch(i){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function _O(){Xt();let t=[];for(let[e,n]of Object.entries(nt))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function $O(){for(let t of Object.keys(nt))delete nt[t];Tt=null,bt=null,so=[]}Yw.exports={registerProvider:Xn,getProvider:aO,getActiveProvider:Hd,getActiveProviderName:lO,getActiveModelId:cO,getActiveModel:uO,setActiveModel:dO,getModelNames:fO,parseModelSpec:Gd,listProviders:pO,listAllModels:hO,recommendModels:mO,callStream:bO,callChat:wO,getConfiguredProviders:_O,setFallbackChain:gO,getFallbackChain:yO,resolveModelForProvider:Hw,buildNoConfiguredProviderError:bl,MODEL_EQUIVALENTS:Wd,OLLAMA_FALLBACK_MODELS:Ud,_reset:$O}});var Na=J((TN,p0)=>{var{callStream:kO,getActiveProviderName:_l,getActiveModelId:zw,getConfiguredProviders:xO,getProvider:Kw,getActiveProvider:Vw,parseModelSpec:Xw}=$t(),{parseToolArgs:Jw}=Yi(),{filterToolsForModel:SO,getModelTier:wl}=mr(),{getModelBriefing:vO}=Ha(),{trackUsage:Zw,estimateTokens:Qw}=Di(),{MultiProgress:EO,C:EN}=_t();function e0(t){return!t||typeof t!="string"?0:typeof Qw=="function"?Qw(t):Math.ceil(t.length/4)}var s0=15,TO=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),t0=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),o0=8,RO=2,$l=new Map,r0=600*1e3;function CO(t,e){let n=$l.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<r0?!1:($l.set(t,{agentId:e,timestamp:Date.now()}),!0)}function fi(t){$l.delete(t)}function Yd(){$l.clear()}function zd(t){let e=(t.message||"").toLowerCase(),n=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":n==="ECONNRESET"||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function i0(t){let e=zd(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function a0(t,e,n){let o;for(let s=0;s<=t0;s++)try{return await kO(t,e,n)}catch(r){o=r;let i=zd(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(s<t0&&i0(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(c=>setTimeout(c,l).unref());continue}throw r}throw o}var n0=new Set(["ask_user","task_list"]);function l0(t){return t>=2?new Set([...n0,"spawn_agents"]):n0}var AO=new Set(["write_file","edit_file","patch_file"]),c0={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:""}},OO=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,PO=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function u0(t){return PO.test(t)?"full":OO.test(t)?"essential":t.length>300?"full":"standard"}function d0(t){let e=xO(),n=_l(),o=[...e].sort((s,r)=>(s.name===n?-1:1)-(r.name===n?-1:1));for(let s of o)for(let r of s.models)if(wl(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var NO={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function kl(t){if(t.model){let{provider:s,model:r}=Xw(t.model),i=s?Kw(s):Vw(),a=s||_l();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=wl(r,a);return{provider:a,model:r,tier:l}}}let e=u0(t.task),n=NO[e];if(n){let{provider:s,model:r}=Xw(n),i=s?Kw(s):Vw(),a=s||_l();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=wl(r,a);return{provider:a,model:r,tier:l}}}let o=d0(e);if(o){let s=wl(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function f0(t,e={},n=0){let o=n===0?s0:o0,s=Math.min(t.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},l=new Set,c=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
1629
+ The plan phase completed, but the implementation phase exhausted its turn budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,ke={role:"assistant",content:Se};S.push(ke),b.push(ke),console.log(`
1630
+ ${Se}`),_e(S),bt(S);break e}let{getActiveProviderName:le}=kt(),ye=le();if(ct&&Wt&&W.size===0&&He===0&&!_i){let Se=`Implementation stalled before edits.
1631
+
1632
+ The bounded backlog workflow reached its turn budget after planning but before changing files. Stopping without commit or push so the workflow does not falsely report success.`,ke={role:"assistant",content:Se};S.push(ke),b.push(ke),console.log(`
1633
+ ${Se}`),_e(S),bt(S);break e}if(ye==="ollama"&&Ol<sf){if(W.size===0&&!_i){console.log(`${p.yellow} \u26A0 Max iterations reached with no progress. Stopping.${p.reset}`);break e}Ol++,Lt=20,console.log(`${p.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Ol}/${sf}) \u2500\u2500${p.reset}`);continue e}if(console.log(`
1634
+ ${p.yellow}\u26A0 Max iterations reached.${p.reset}`),await kw(" Continue for 20 more turns?")){Lt=20;continue e}console.log(`${p.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${p.reset}`)}break e}if(ct&&Wt&&W.size===0&&He===0){let le=[...S].reverse().find(Se=>Se.role==="assistant"),ye=typeof le?.content=="string"?le.content:"";if(!/\b(no safe task found|implementation stalled before edits)\b/i.test(ye)){let Se=`Implementation stalled before edits.
1635
+
1636
+ The bounded backlog workflow ended after reading/searching but before changing files. Stopping without commit or push so the workflow does not falsely report success.`,ke={role:"assistant",content:Se};S.push(ke),b.push(ke),console.log(`
1637
+ ${Se}`),Me(ce,Ae,W,ve,Ne),_e(S),bt(S)}}await bi()}function Ww(t,e,n,o=!1){return!o&&t&&e&&e.isComplex&&e.estimatedGoals>=n}Hw.exports={processInput:eO,clearConversation:HA,getConversationLength:YA,getConversationMessages:zA,setConversationMessages:KA,setAbortSignalGetter:eA,setMaxIterations:QC,invalidateSystemPromptCache:xd,clearToolFilterCache:lA,getCachedFilteredTools:Cw,buildSystemPrompt:Id,splitSystemPrompt:WA,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Ld,getProjectContextHash:Aw,_inferVerificationCommands:bl,_inferRelevantTests:ui,_inferSymbolTargets:qw,_buildSymbolHintBlock:Fw,_detectResponseLanguage:Bd,_isSimpleDirectAnswerPrompt:Bw,_claimsVerificationOrCompletion:_w,_statesVerificationGap:$w,_shouldAutoOrchestrate:Ww,_shouldSkipPlanPhaseForDirectCreation:Pd,_hasAutomationOrPreflightGate:di,_extractDirectTaskPaths:ri,_isBoundedBacklogPlanningPrompt:Mw,_buildBoundedBacklogPlanInstruction:Kn,_looksLikeBoundedBacklogDecision:fl,_looksLikeGatedAutomationFinalSummary:Nd,buildUserContent:Tw,_detectImageURLs:Sw,_downloadImageURL:vw,_grabClipboardImage:Ew,detectFrustration:Rw,detectAndTruncateLoop:bd,injectMidRunNote:AA,resetSessionTracking:Uw}});var kt=J((CN,Vw)=>{var{OllamaProvider:tO,getOllamaRecommendations:nO}=yf(),{OpenAIProvider:sO}=Gl(),{DeepSeekProvider:oO}=xf(),{AnthropicProvider:rO}=Tf(),{GeminiProvider:iO}=Of(),{LocalProvider:aO}=Mf(),{checkBudget:lO,formatProviderCostMode:cO,getProviderCostMode:uO}=qi(),Gd={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",deepseek:"deepseek-v4-pro",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",deepseek:"deepseek-v4-pro",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",deepseek:"deepseek-v4-flash",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},Hd=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Yw={};for(let[t,e]of Object.entries(Gd))for(let n of Object.values(e))Yw[n]=t;function zw(t,e){let n=Yw[t];return n&&Gd[n][e]||t}function _l(){return["No configured provider available.","Lowest-cost path: run /setup and choose Ollama Cloud, or set OLLAMA_API_KEY plus DEFAULT_PROVIDER=ollama.","Local free path: start Ollama locally, pull a coding model, then use /model local:<model>.","Paid fallback: set DEEPSEEK_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, or GEMINI_API_KEY and use /fallback only when you want paid backup."].join(`
1638
+ `)}var nt={},Tt=null,wt=null,oo=[];function Jt(){let t=process.env.NEX_MOCK_PROVIDER==="1";if(Object.keys(nt).length>0){if(t&&!nt.mock){let{MockProvider:s}=Ql();Xn("mock",new s)}t&&nt.mock&&Tt!=="mock"&&(Tt="mock",wt=nt.mock.defaultModel||"mock-model",oo=[],fi());return}if(Xn("ollama",new tO),Xn("openai",new sO),Xn("deepseek",new oO),Xn("anthropic",new rO),Xn("gemini",new iO),Xn("local",new aO),t){let{MockProvider:s}=Ql();Xn("mock",new s)}let e=process.env.DEFAULT_PROVIDER||"ollama",n=process.env.DEFAULT_MODEL||null;t?(Tt="mock",wt=nt.mock?.defaultModel||"mock-model",oo=[]):nt[e]?(Tt=e,wt=n||nt[e].defaultModel):(Tt="ollama",wt="kimi-k2.5");let o=process.env.FALLBACK_CHAIN;o&&(oo=o.split(",").map(s=>s.trim()).filter(Boolean))}function Xn(t,e){nt[t]=e}function dO(t){return Jt(),nt[t]||null}function Yd(){return Jt(),nt[Tt]||null}function fO(){return Jt(),Tt}function pO(){return Jt(),wt}function hO(){Jt();let t=Yd();if(!t)return{id:wt,name:wt,provider:Tt};let e=t.getModel(wt);return e?{...e,provider:Tt}:{id:wt,name:wt,provider:Tt}}function zd(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(nt[n]||["ollama","openai","deepseek","anthropic","gemini","local","mock"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function mO(t){Jt();let{provider:e,model:n}=zd(t);if(e){let s=nt[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(Tt=e,wt=n,fi(),!0):!1}let o=Yd();if(o&&o.getModel(n))return wt=n,fi(),!0;for(let[s,r]of Object.entries(nt))if(r.getModel(n))return Tt=s,wt=n,fi(),!0;return!1}function fi(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=qu();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Pn();t()}catch{}}function gO(){Jt();let t=new Set;for(let e of Object.values(nt))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function yO(){return Jt(),Object.entries(nt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===Tt&&n.id===wt}))}))}function bO(){Jt();let t=[];for(let[e,n]of Object.entries(nt)){let o=n.isConfigured();for(let s of Object.values(n.getModels()))t.push({spec:`${e}:${s.id}`,name:s.name,provider:e,configured:o,maxTokens:s.maxTokens,contextWindow:s.contextWindow,capability:s.capability,speed:s.speed,quality:s.quality,recommendedFor:s.recommendedFor||[]})}return t}function wO(t="coding",e={}){Jt();let n=e.limit||5,o=e.configuredOnly!==!1,s=[],r=nt.ollama;if(r&&(!o||r.isConfigured()))for(let i of nO(t,n))s.push({...i,spec:`ollama:${i.id}`,provider:"ollama",configured:r.isConfigured()});if(s.length>=n)return s.slice(0,n);for(let[i,a]of Object.entries(nt)){if(i==="ollama"||o&&!a.isConfigured())continue;let l=a.getModel(a.defaultModel);if(l&&(s.push({...l,spec:`${i}:${l.id}`,provider:i,configured:a.isConfigured()}),s.length>=n))break}return s}function _O(t){oo=Array.isArray(t)?t:[]}function $O(){return[...oo]}function Gw(t){let e=t.message||"",n=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ECONNRESET"||n==="EHOSTUNREACH"||n==="ENETUNREACH"||n==="EPIPE"||n==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function Kw(t){let e=[Tt,...oo.filter(r=>r!==Tt)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],a=nt[i];if(!a||!a.isConfigured())continue;s++;let l=lO(i);if(!l.allowed){o++,n=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}let c=r>0,u=c?zw(wt,i):wt;try{if(c){let d=uO(i).label;process.stderr.write(` [fallback: ${i}:${u} \xB7 ${d}]
1639
+ `)}return await t(a,i,u)}catch(d){if(n=d,!Gw(d)||r>=e.length-1)throw d;if(i==="ollama"&&Hd.length>0){let f=u;for(let h of Hd)if(h!==f)try{return process.stderr.write(` [ollama fallback: ${h}]
1640
+ `),await t(a,i,h)}catch(m){if(n=m,!Gw(m))throw m}}continue}}throw o>0&&o===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):s===0?new Error(_l()):n||new Error(_l())}async function kO(t,e,n={}){Jt();let o=n.model,s=o?(()=>{let{model:i}=zd(o);return i||o})():void 0,r=s!==o?{...n,model:s}:n;return Kw((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function xO(t,e,n={}){if(Jt(),n.provider){let o=nt[n.provider];if(!o||!o.isConfigured()){let r=cO(n.provider);throw new Error(`Provider '${n.provider}' is not available (${r}).
1641
+ `+_l())}let s={model:n.model||wt,...n};try{return await o.chat(t,e,s)}catch(r){if(typeof o.stream=="function")try{return await o.stream(t,e,{...s,onToken:()=>{}})}catch{}throw r}}return Kw(async(o,s,r)=>{try{return await o.chat(t,e,{model:r,...n})}catch(i){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function SO(){Jt();let t=[];for(let[e,n]of Object.entries(nt))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function vO(){for(let t of Object.keys(nt))delete nt[t];Tt=null,wt=null,oo=[]}Vw.exports={registerProvider:Xn,getProvider:dO,getActiveProvider:Yd,getActiveProviderName:fO,getActiveModelId:pO,getActiveModel:hO,setActiveModel:mO,getModelNames:gO,parseModelSpec:zd,listProviders:yO,listAllModels:bO,recommendModels:wO,callStream:kO,callChat:xO,getConfiguredProviders:SO,setFallbackChain:_O,getFallbackChain:$O,resolveModelForProvider:zw,buildNoConfiguredProviderError:_l,MODEL_EQUIVALENTS:Gd,OLLAMA_FALLBACK_MODELS:Hd,_reset:vO}});var Ma=J((ON,g0)=>{var{callStream:EO,getActiveProviderName:kl,getActiveModelId:Xw,getConfiguredProviders:TO,getProvider:Jw,getActiveProvider:Zw,parseModelSpec:Qw}=kt(),{parseToolArgs:e0}=zi(),{filterToolsForModel:RO,getModelTier:$l}=gr(),{getModelBriefing:CO}=Ga(),{trackUsage:t0,estimateTokens:n0}=qi(),{MultiProgress:AO,C:AN}=$t();function s0(t){return!t||typeof t!="string"?0:typeof n0=="function"?n0(t):Math.ceil(t.length/4)}var i0=15,OO=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),o0=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),a0=8,PO=2,xl=new Map,l0=600*1e3;function NO(t,e){let n=xl.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<l0?!1:(xl.set(t,{agentId:e,timestamp:Date.now()}),!0)}function pi(t){xl.delete(t)}function Kd(){xl.clear()}function Vd(t){let e=(t.message||"").toLowerCase(),n=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":n==="ECONNRESET"||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function c0(t){let e=Vd(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function u0(t,e,n){let o;for(let s=0;s<=o0;s++)try{return await EO(t,e,n)}catch(r){o=r;let i=Vd(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(s<o0&&c0(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(c=>setTimeout(c,l).unref());continue}throw r}throw o}var r0=new Set(["ask_user","task_list"]);function d0(t){return t>=2?new Set([...r0,"spawn_agents"]):r0}var MO=new Set(["write_file","edit_file","patch_file"]),f0={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:""}},LO=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,IO=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function p0(t){return IO.test(t)?"full":LO.test(t)?"essential":t.length>300?"full":"standard"}function h0(t){let e=TO(),n=kl(),o=[...e].sort((s,r)=>(s.name===n?-1:1)-(r.name===n?-1:1));for(let s of o)for(let r of s.models)if($l(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var jO={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Sl(t){if(t.model){let{provider:s,model:r}=Qw(t.model),i=s?Jw(s):Zw(),a=s||kl();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=$l(r,a);return{provider:a,model:r,tier:l}}}let e=p0(t.task),n=jO[e];if(n){let{provider:s,model:r}=Qw(n),i=s?Jw(s):Zw(),a=s||kl();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=$l(r,a);return{provider:a,model:r,tier:l}}}let o=h0(e);if(o){let s=$l(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function m0(t,e={},n=0){let o=n===0?i0:a0,s=Math.min(t.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},l=new Set,c=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
1636
1642
 
1637
1643
  TASK: ${t.task}
1638
1644
  ${t.context?`
@@ -1658,19 +1664,19 @@ TOOL STRATEGY:
1658
1664
  ERROR RECOVERY:
1659
1665
  - If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
1660
1666
  - If bash fails: read the error, fix the root cause, then retry.
1661
- - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&c0[t.type],f=d&&d.systemSuffix?`
1667
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&f0[t.type],f=d&&d.systemSuffix?`
1662
1668
 
1663
- ${d.systemSuffix}`:"",h=kl(t),m=h.provider,g=h.model,_=h.tier,k=vO(g||zw()),O=[{role:"system",content:(k?`## Model Briefing
1669
+ ${d.systemSuffix}`:"",h=Sl(t),m=h.provider,g=h.model,_=h.tier,k=CO(g||Xw()),O=[{role:"system",content:(k?`## Model Briefing
1664
1670
  ${k}
1665
1671
 
1666
1672
  ---
1667
1673
 
1668
- `:"")+u+f}];O.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:E,executeTool:T}=cr(),q=l0(n),ee=SO(E.filter(ae=>!q.has(ae.function.name)),_);if(d&&d.allowedTools&&(ee=ee.filter(ae=>d.allowedTools.has(ae.function.name))),g&&!t._skipLog){let ae=_?` (${_})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${ae}]
1669
- `)}let te={};m&&(te.provider=m),g&&(te.model=g);let K=new Set;try{for(let se=0;se<s;se++){let ie=await a0(O,ee,te);if(!ie||typeof ie!="object")throw new Error("Empty or invalid response from provider");{let Te=m||_l(),ve=g||zw();if(ie.usage){let b=ie.usage.prompt_tokens||0,L=ie.usage.completion_tokens||0;a.input+=b,a.output+=L,Zw(Te,ve,b,L)}else{let b=ie.content||"",L=O.map(X=>typeof X.content=="string"?X.content:Array.isArray(X.content)?X.content.map(R=>typeof R=="string"?R:R.text||"").join(""):"").join(" "),U=e0(L),Z=e0(b);a.input+=U,a.output+=Z,a._estimated=!0,Zw(Te,ve,U,Z)}}let Be=ie.content||"",Re=ie.tool_calls,W={role:"assistant",content:Be||""};if(Re&&Re.length>0&&(W.tool_calls=Re),O.push(W),!Re||Re.length===0){for(let Te of l)fi(Te);return{task:t.task,status:"done",result:Be||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let ne=new Set,Ke=Re.map(Te=>{let ve=Te.function.name,b=Jw(Te.function.arguments),L=Te.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!b)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${ve}`,tool_call_id:L});if(["edit_file","patch_file"].includes(ve)&&b.path){if(K.has(b.path)||ne.has(b.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${b.path}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:L});ne.add(b.path)}let U=null;if(AO.has(ve)&&b.path){let X=require("path"),R=X.isAbsolute(b.path)?b.path:X.resolve(process.cwd(),b.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let ce=X.relative(process.cwd(),R);if(t._readOnlyFiles.some(be=>ce===be||ce.startsWith(be+"/")||R===be||R.startsWith(be+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${b.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:L})}if(l.has(R)||!CO(R,r))return Promise.resolve({role:"tool",content:`ERROR: File '${b.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:L});l.add(R),U=R}return i.push(ve),e.onUpdate&&e.onUpdate({type:"tool_call",tool:ve,agentId:r}),(ve==="spawn_agents"?Kd(b,n+1):T(ve,b,{autoConfirm:!0,silent:!0})).then(X=>{U&&(fi(U),l.delete(U));let R=String(X??"");return b&&b.path&&(["edit_file","patch_file","write_file"].includes(ve)&&R.startsWith("Edited:")?K.add(b.path):ve==="read_file"&&!R.startsWith("ERROR")&&K.delete(b.path)),{role:"tool",content:R.length>2e4?R.substring(0,2e4)+`
1670
- ...(truncated)`:R,tool_call_id:L}}).catch(X=>(U&&(fi(U),l.delete(U)),{role:"tool",content:`ERROR: ${X.message}`,tool_call_id:L}))}),ct=await Promise.all(Ke);if(O.push(...ct),se>=7&&O.length>12)try{let{compressMessage:Te}=Pn(),ve=O.length-6;for(let b=1;b<ve;b++)O[b]._subAgentCompressed||(O[b]={...Te(O[b],"light"),_subAgentCompressed:!0})}catch{}for(let Te=0;Te<Re.length;Te++){let ve=Re[Te];if(ve.function.name==="bash_exec"){let b=Jw(ve.function.arguments);if((ct[Te]?.content||"").startsWith("ERROR")&&b&&b.command){let U=b.command.replace(/\s+/g," ").trim().slice(0,100);c.set(U,(c.get(U)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${se+1}/${s}`)}for(let se of l)fi(se);let ae=[...c.entries()].filter(([,se])=>se>=3).sort((se,ie)=>ie[1]-se[1]).slice(0,3).map(([se,ie])=>`"${se}" (failed ${ie}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ae,result:O[O.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(ae){for(let se of l)fi(se);return{task:t.task,status:"failed",result:`Error: ${ae.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function Kd(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let n=e===0?TO:RO,o=e===0?s0:o0,s=(t.agents||[]).slice(0,n);if(s.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=s.map(u=>kl(u)),l=s.map((u,d)=>{let f=a[d],h=f.model?` [${f.model}]`:"",m=u.task.substring(0,i-h.length);return`${r}Agent ${d+1}${h}: ${m}${u.task.length>m.length?"...":""}`}),c=new EO(l);c.start();try{let u=s.map((g,_)=>{let k=a[_],$=Math.min(g.max_iterations||o,o),O=k.model?{...g,model:`${k.provider}:${k.model}`,_skipLog:!0,max_iterations:$}:{...g,_skipLog:!0,max_iterations:$};return f0(O,{onUpdate:()=>{}},e).then(E=>(c.update(_,E.status==="failed"?"error":"done"),E)).catch(E=>(c.update(_,"error"),{task:g.task,status:"failed",result:`Error: ${E.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),Yd();let f=["Sub-agent results:",""],h=0,m=0;for(let g=0;g<d.length;g++){let _=d[g],k=_.status==="done"?"\u2713":_.status==="truncated"?"\u26A0":"\u2717",$=_.modelSpec?` [${_.modelSpec}]`:"";f.push(`${k} Agent ${g+1}${$}: ${_.task}`),f.push(` Status: ${_.status}`),f.push(` Tools used: ${_.toolsUsed.length>0?_.toolsUsed.join(", "):"none"}`),f.push(` Result: ${_.result}`),_.repeatedFailures&&_.repeatedFailures.length>0&&f.push(` Repeated failures: ${_.repeatedFailures.join("; ")}`),f.push(""),h+=_.tokensUsed.input,m+=_.tokensUsed.output}return f.push(`Total sub-agent tokens: ${h} input + ${m} output`),f.join(`
1671
- `)}catch(u){return c.stop(),Yd(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function MO(t){let{createJob:e}=Do(),n=(t.agents||[]).filter(i=>i.background),o=(t.agents||[]).filter(i=>!i.background),s=n.map(i=>{let a=kl(i),l=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(l)}),r=[];if(s.length>0&&r.push(`Background agents started: [${s.join(", ")}]
1674
+ `:"")+u+f}];O.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:E,executeTool:T}=ur(),q=d0(n),ee=RO(E.filter(ae=>!q.has(ae.function.name)),_);if(d&&d.allowedTools&&(ee=ee.filter(ae=>d.allowedTools.has(ae.function.name))),g&&!t._skipLog){let ae=_?` (${_})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${ae}]
1675
+ `)}let te={};m&&(te.provider=m),g&&(te.model=g);let K=new Set;try{for(let se=0;se<s;se++){let ie=await u0(O,ee,te);if(!ie||typeof ie!="object")throw new Error("Empty or invalid response from provider");{let Re=m||kl(),Te=g||Xw();if(ie.usage){let b=ie.usage.prompt_tokens||0,I=ie.usage.completion_tokens||0;a.input+=b,a.output+=I,t0(Re,Te,b,I)}else{let b=ie.content||"",I=O.map(X=>typeof X.content=="string"?X.content:Array.isArray(X.content)?X.content.map(R=>typeof R=="string"?R:R.text||"").join(""):"").join(" "),U=s0(I),Z=s0(b);a.input+=U,a.output+=Z,a._estimated=!0,t0(Re,Te,U,Z)}}let Be=ie.content||"",Ce=ie.tool_calls,H={role:"assistant",content:Be||""};if(Ce&&Ce.length>0&&(H.tool_calls=Ce),O.push(H),!Ce||Ce.length===0){for(let Re of l)pi(Re);return{task:t.task,status:"done",result:Be||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let ne=new Set,Ve=Ce.map(Re=>{let Te=Re.function.name,b=e0(Re.function.arguments),I=Re.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!b)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${Te}`,tool_call_id:I});if(["edit_file","patch_file"].includes(Te)&&b.path){if(K.has(b.path)||ne.has(b.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${b.path}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:I});ne.add(b.path)}let U=null;if(MO.has(Te)&&b.path){let X=require("path"),R=X.isAbsolute(b.path)?b.path:X.resolve(process.cwd(),b.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let ue=X.relative(process.cwd(),R);if(t._readOnlyFiles.some(we=>ue===we||ue.startsWith(we+"/")||R===we||R.startsWith(we+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${b.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:I})}if(l.has(R)||!NO(R,r))return Promise.resolve({role:"tool",content:`ERROR: File '${b.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:I});l.add(R),U=R}return i.push(Te),e.onUpdate&&e.onUpdate({type:"tool_call",tool:Te,agentId:r}),(Te==="spawn_agents"?Xd(b,n+1):T(Te,b,{autoConfirm:!0,silent:!0})).then(X=>{U&&(pi(U),l.delete(U));let R=String(X??"");return b&&b.path&&(["edit_file","patch_file","write_file"].includes(Te)&&R.startsWith("Edited:")?K.add(b.path):Te==="read_file"&&!R.startsWith("ERROR")&&K.delete(b.path)),{role:"tool",content:R.length>2e4?R.substring(0,2e4)+`
1676
+ ...(truncated)`:R,tool_call_id:I}}).catch(X=>(U&&(pi(U),l.delete(U)),{role:"tool",content:`ERROR: ${X.message}`,tool_call_id:I}))}),ut=await Promise.all(Ve);if(O.push(...ut),se>=7&&O.length>12)try{let{compressMessage:Re}=Pn(),Te=O.length-6;for(let b=1;b<Te;b++)O[b]._subAgentCompressed||(O[b]={...Re(O[b],"light"),_subAgentCompressed:!0})}catch{}for(let Re=0;Re<Ce.length;Re++){let Te=Ce[Re];if(Te.function.name==="bash_exec"){let b=e0(Te.function.arguments);if((ut[Re]?.content||"").startsWith("ERROR")&&b&&b.command){let U=b.command.replace(/\s+/g," ").trim().slice(0,100);c.set(U,(c.get(U)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${se+1}/${s}`)}for(let se of l)pi(se);let ae=[...c.entries()].filter(([,se])=>se>=3).sort((se,ie)=>ie[1]-se[1]).slice(0,3).map(([se,ie])=>`"${se}" (failed ${ie}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ae,result:O[O.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(ae){for(let se of l)pi(se);return{task:t.task,status:"failed",result:`Error: ${ae.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function Xd(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let n=e===0?OO:PO,o=e===0?i0:a0,s=(t.agents||[]).slice(0,n);if(s.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=s.map(u=>Sl(u)),l=s.map((u,d)=>{let f=a[d],h=f.model?` [${f.model}]`:"",m=u.task.substring(0,i-h.length);return`${r}Agent ${d+1}${h}: ${m}${u.task.length>m.length?"...":""}`}),c=new AO(l);c.start();try{let u=s.map((g,_)=>{let k=a[_],$=Math.min(g.max_iterations||o,o),O=k.model?{...g,model:`${k.provider}:${k.model}`,_skipLog:!0,max_iterations:$}:{...g,_skipLog:!0,max_iterations:$};return m0(O,{onUpdate:()=>{}},e).then(E=>(c.update(_,E.status==="failed"?"error":"done"),E)).catch(E=>(c.update(_,"error"),{task:g.task,status:"failed",result:`Error: ${E.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),Kd();let f=["Sub-agent results:",""],h=0,m=0;for(let g=0;g<d.length;g++){let _=d[g],k=_.status==="done"?"\u2713":_.status==="truncated"?"\u26A0":"\u2717",$=_.modelSpec?` [${_.modelSpec}]`:"";f.push(`${k} Agent ${g+1}${$}: ${_.task}`),f.push(` Status: ${_.status}`),f.push(` Tools used: ${_.toolsUsed.length>0?_.toolsUsed.join(", "):"none"}`),f.push(` Result: ${_.result}`),_.repeatedFailures&&_.repeatedFailures.length>0&&f.push(` Repeated failures: ${_.repeatedFailures.join("; ")}`),f.push(""),h+=_.tokensUsed.input,m+=_.tokensUsed.output}return f.push(`Total sub-agent tokens: ${h} input + ${m} output`),f.join(`
1677
+ `)}catch(u){return c.stop(),Kd(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function DO(t){let{createJob:e}=qo(),n=(t.agents||[]).filter(i=>i.background),o=(t.agents||[]).filter(i=>!i.background),s=n.map(i=>{let a=Sl(i),l=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(l)}),r=[];if(s.length>0&&r.push(`Background agents started: [${s.join(", ")}]
1672
1678
  `+n.map((i,a)=>` ${s[a]}: ${i.task}`).join(`
1673
1679
  `)+`
1674
- Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await Kd({agents:o});r.push(i)}return r.join(`
1680
+ Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await Xd({agents:o});r.push(i)}return r.join(`
1675
1681
 
1676
- `)||"No agents specified."}p0.exports={runSubAgent:f0,executeSpawnAgents:Kd,executeSpawnAgentsBackground:MO,clearAllLocks:Yd,classifyTask:u0,pickModelForTier:d0,resolveSubAgentModel:kl,classifyError:zd,isRetryableError:i0,callWithRetry:a0,getExcludedTools:l0,LOCK_TIMEOUT_MS:r0,SUB_AGENT_TYPES:c0}});var{runSubAgent:LO}=Na();process.on("message",async({jobId:t,agentDef:e})=>{try{let n=await LO({...e,_skipLog:!0},{onUpdate:()=>{}},0);process.send({type:"result",jobId:t,payload:n})}catch(n){process.send({type:"error",jobId:t,error:n.message})}finally{process.exit(0)}});
1682
+ `)||"No agents specified."}g0.exports={runSubAgent:m0,executeSpawnAgents:Xd,executeSpawnAgentsBackground:DO,clearAllLocks:Kd,classifyTask:p0,pickModelForTier:h0,resolveSubAgentModel:Sl,classifyError:Vd,isRetryableError:c0,callWithRetry:u0,getExcludedTools:d0,LOCK_TIMEOUT_MS:l0,SUB_AGENT_TYPES:f0}});var{runSubAgent:qO}=Ma();process.on("message",async({jobId:t,agentDef:e})=>{try{let n=await qO({...e,_skipLog:!0},{onUpdate:()=>{}},0);process.send({type:"result",jobId:t,payload:n})}catch(n){process.send({type:"error",jobId:t,error:n.message})}finally{process.exit(0)}});