nex-code 0.5.28 → 0.5.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/background-worker.js +373 -373
- package/dist/benchmark.js +381 -381
- package/dist/nex-code.js +523 -523
- package/package.json +1 -1
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
var
|
|
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")}},Gi=class extends To{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}}))}}},Yi=class extends Eo{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 Gi(e,n)}},zi=class extends To{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}}})}}},ac="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Ki=class extends Eo{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(ac);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+ac.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 zi(e,n)}};function If(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 Vi=class extends To{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:If(e.function?.arguments??e.arguments)}}))}}},Xi=class extends Eo{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:If(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,n={}){return new Vi(e,n)}},k_=new Yi,x_=new Ki,S_=new Xi;jf.exports={ANTHROPIC_CACHE_BOUNDARY:ac,WireProtocol:Eo,StreamParser:To,OpenAICompatibleProtocol:Yi,AnthropicProtocol:Ki,OllamaChatProtocol:Xi,OpenAIStreamParser:Gi,AnthropicStreamParser:zi,OllamaStreamParser:Vi,openaiProtocol:k_,anthropicProtocol:x_,ollamaProtocol:S_}});var qf=ee((mP,Df)=>{var Ji=require("axios"),v_=require("http"),E_=require("https"),{BaseProvider:T_,readStreamErrorBody:R_}=Ms(),{ollamaProtocol:Ns}=Ro(),Zi=new v_.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Qi=new E_.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ea={"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}},lc={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=lc[t]||lc.coding;return n.map(s=>ea[s]).filter(Boolean).concat(Object.values(ea).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 cc=class extends T_{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||ea,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){Ji.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Zi,httpsAgent:Qi}).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 Ji.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Zi,httpsAgent:Qi})).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=Ns.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
|
|
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(Ls.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),o),c;try{c=await
|
|
1
|
+
var ac=Object.defineProperty;var m_=Object.getOwnPropertyDescriptor;var g_=Object.getOwnPropertyNames;var y_=Object.prototype.hasOwnProperty;var b_=(t,e)=>()=>(t&&(e=t(t=0)),e);var ee=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),w_=(t,e)=>{for(var n in e)ac(t,n,{get:e[n],enumerable:!0})},__=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of g_(e))!y_.call(t,s)&&s!==n&&ac(t,s,{get:()=>e[s],enumerable:!(o=m_(e,s))||o.enumerable});return t};var $_=t=>__(ac({},"__esModule",{value:!0}),t);var Ms=ee((hP,If)=>{async function k_(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 lc=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`)}};If.exports={BaseProvider:lc,readStreamErrorBody:k_}});var Ro=ee((mP,Df)=>{var Eo=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")}},To=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")}},zi=class extends To{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}}))}}},Ki=class extends Eo{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 zi(e,n)}},Vi=class extends To{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}}})}}},cc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Xi=class extends Eo{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(cc);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+cc.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 Vi(e,n)}};function jf(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 Ji=class extends To{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:jf(e.function?.arguments??e.arguments)}}))}}},Zi=class extends Eo{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:jf(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,n={}){return new Ji(e,n)}},x_=new Ki,S_=new Xi,v_=new Zi;Df.exports={ANTHROPIC_CACHE_BOUNDARY:cc,WireProtocol:Eo,StreamParser:To,OpenAICompatibleProtocol:Ki,AnthropicProtocol:Xi,OllamaChatProtocol:Zi,OpenAIStreamParser:zi,AnthropicStreamParser:Vi,OllamaStreamParser:Ji,openaiProtocol:x_,anthropicProtocol:S_,ollamaProtocol:v_}});var Ff=ee((gP,qf)=>{var Qi=require("axios"),E_=require("http"),T_=require("https"),{BaseProvider:R_,readStreamErrorBody:C_}=Ms(),{ollamaProtocol:Ns}=Ro(),ea=new E_.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ta=new T_.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),na={"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}},uc={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 A_(t="coding",e=5){let n=uc[t]||uc.coding;return n.map(s=>na[s]).filter(Boolean).concat(Object.values(na).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 dc=class extends R_{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||na,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){Qi.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ea,httpsAgent:ta}).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 Qi.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ea,httpsAgent:ta})).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=Ns.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 Qi.post(`${this.baseUrl}${Ns.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:ea,httpsAgent:ta})}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 Ns.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=Ns.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 Qi.post(`${this.baseUrl}${Ns.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:ea,httpsAgent:ta})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await C_(f,w=>w?.error),g=new Error(`API Error${p}: ${m}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=Ns.createStreamParser(a,{onThinkingToken:l});return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:w}=d.feed(m.toString());g&&f(w)}),u.data.on("error",m=>{if(o.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,p(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Ns.normalizeResponse(e)}};qf.exports={OllamaProvider:dc,OLLAMA_MODELS:na,OLLAMA_USE_CASES:uc,getOllamaRecommendations:A_}});var pc=ee((yP,Wf)=>{var Bf=require("axios"),{BaseProvider:O_,readStreamErrorBody:P_}=Ms(),{openaiProtocol:Ls}=Ro(),Uf={"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}},fc=class extends O_{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Uf,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(Ls.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}${Ls.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 Ls.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(Ls.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}${Ls.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await P_(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Ls.createStreamParser(a);return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:w}=d.feed(m.toString());g&&f(w)}),u.data.on("error",m=>{o.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Ls.normalizeResponse(e)}};Wf.exports={OpenAIProvider:fc,OPENAI_MODELS:Uf}});var Yf=ee((bP,Gf)=>{var{OpenAIProvider:M_}=pc(),Hf={"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"]}},hc=class extends M_{constructor(e={}){super({name:"deepseek",baseUrl:e.baseUrl||process.env.DEEPSEEK_BASE_URL||"https://api.deepseek.com",models:e.models||Hf,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"}}}};Gf.exports={DeepSeekProvider:hc,DEEPSEEK_MODELS:Hf}});var Xf=ee((wP,Vf)=>{var zf=require("axios"),{BaseProvider:N_,readStreamErrorBody:L_}=Ms(),{anthropicProtocol:ds}=Ro(),Kf={"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}},I_="2023-06-01",mc=class extends N_{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Kf,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||I_}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 ds.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=ds.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Yf.post(`${this.baseUrl}${ds.getEndpoint()}`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",g=p.response?.data?.error?.message||p.response?.data?.error||p.message;throw new Error(`API Error${m}: ${g}`)}return ds.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=ds.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await Yf.post(`${this.baseUrl}${ds.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 w=g.response?.status?` [HTTP ${g.response.status}]`:"",k=await N_(g,T=>T?.error?.message||T?.error);throw new Error(`API Error${w}: ${k}`)}let m=ds.createStreamParser(l);return new Promise((g,w)=>{o.signal&&o.signal.addEventListener("abort",()=>{p.data.destroy(),w(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",k=>{let{done:T,result:$}=m.feed(k.toString());T&&g($)}),p.data.on("error",k=>{o.signal?.aborted||w(new Error(`Stream error: ${k.message}`))}),p.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return ds.normalizeResponse(e)}};Kf.exports={AnthropicProvider:pc,ANTHROPIC_MODELS:zf}});var Qf=ee((wP,Zf)=>{var Xf=require("axios"),{BaseProvider:I_,readStreamErrorBody:j_}=Ms(),{openaiProtocol:Is}=Ro(),Jf={"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}},hc=class extends I_{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Jf,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=Is.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),c;try{c=await Xf.post(`${this.baseUrl}${Is.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 Is.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=Is.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),u;try{u=await Xf.post(`${this.baseUrl}${Is.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await j_(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Is.createStreamParser(a);return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:w}=d.feed(m.toString());g&&f(w)}),u.data.on("error",m=>{o.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Is.normalizeResponse(e)}};Zf.exports={GeminiProvider:hc,GEMINI_MODELS:Jf}});var np=ee((_P,tp)=>{var ta=require("axios"),{BaseProvider:D_,readStreamErrorBody:q_}=Ms(),{ollamaProtocol:js}=Ro(),ep="http://localhost:11434",mc=class extends D_{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||ep,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 ta.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 ta.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=js.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await
|
|
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
|
|
9
|
-
`);else if(r.limit>0&&r.spent>=r.limit*.8){let i=`${t}:${r.limit}:80`;
|
|
10
|
-
`))}}}function
|
|
11
|
-
`)}function
|
|
12
|
-
`):String(t.content||""):""}function
|
|
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 ds.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=ds.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await zf.post(`${this.baseUrl}${ds.getEndpoint()}`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",g=p.response?.data?.error?.message||p.response?.data?.error||p.message;throw new Error(`API Error${m}: ${g}`)}return ds.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=ds.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await zf.post(`${this.baseUrl}${ds.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 w=g.response?.status?` [HTTP ${g.response.status}]`:"",k=await L_(g,T=>T?.error?.message||T?.error);throw new Error(`API Error${w}: ${k}`)}let m=ds.createStreamParser(l);return new Promise((g,w)=>{o.signal&&o.signal.addEventListener("abort",()=>{p.data.destroy(),w(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",k=>{let{done:T,result:$}=m.feed(k.toString());T&&g($)}),p.data.on("error",k=>{o.signal?.aborted||w(new Error(`Stream error: ${k.message}`))}),p.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return ds.normalizeResponse(e)}};Vf.exports={AnthropicProvider:mc,ANTHROPIC_MODELS:Kf}});var ep=ee((_P,Qf)=>{var Jf=require("axios"),{BaseProvider:j_,readStreamErrorBody:D_}=Ms(),{openaiProtocol:Is}=Ro(),Zf={"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}},gc=class extends j_{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Zf,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=Is.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),c;try{c=await Jf.post(`${this.baseUrl}${Is.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 Is.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=Is.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),u;try{u=await Jf.post(`${this.baseUrl}${Is.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await D_(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Is.createStreamParser(a);return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:w}=d.feed(m.toString());g&&f(w)}),u.data.on("error",m=>{o.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Is.normalizeResponse(e)}};Qf.exports={GeminiProvider:gc,GEMINI_MODELS:Zf}});var sp=ee(($P,np)=>{var sa=require("axios"),{BaseProvider:q_,readStreamErrorBody:F_}=Ms(),{ollamaProtocol:js}=Ro(),tp="http://localhost:11434",yc=class extends q_{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||tp,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 sa.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 sa.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=js.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await sa.post(`${this.baseUrl}${js.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 js.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=js.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await sa.post(`${this.baseUrl}${js.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 F_(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=js.createStreamParser(r);return new Promise((c,u)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:p}=l.feed(d.toString());f&&c(p)}),a.data.on("error",d=>{o.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{c(l.flush())})})}normalizeResponse(e){return js.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}};np.exports={LocalProvider:yc,DEFAULT_LOCAL_URL:tp}});var Sn=ee((kP,up)=>{"use strict";var op="\x1B[0m",rp="\x1B[1m",Co="\x1B[2m";function X(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function B_(){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 ip(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function U_(t){try{let n=require("fs").readFileSync(ip(),"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=ip(),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 H_(){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=U_(n);if(o!==null)return o;let s=B_(),r=s!==null?s:!0;return W_(n,r),r}var ap=H_(),lp={reset:op,bold:rp,dim:Co,primary:X(80,190,255),secondary:X(60,170,190),success:X(80,210,120),warning:X(245,175,50),error:X(230,80,80),muted:Co,subtle:X(130,130,145),tool_read:X(80,190,255),tool_write:X(245,165,55),tool_exec:X(185,100,235),tool_search:X(70,185,190),tool_git:X(90,210,100),tool_web:X(100,215,250),tool_sysadmin:X(225,150,75),tool_default:X(100,205,115),syn_keyword:X(185,100,235),syn_string:X(90,210,120),syn_number:X(245,175,50),syn_comment:Co,syn_key:X(80,190,255),diff_add:X(80,210,120),diff_rem:X(230,80,80),banner_logo:X(80,200,255),banner_name:X(80,200,255),banner_version:Co,banner_model:Co,banner_yolo:X(245,175,50),banner_gemini:X(138,180,248),footer_sep:Co,footer_model:X(80,175,235),footer_branch:X(80,210,100),footer_project:X(130,130,145),footer_divider:X(80,80,95),footer_mode:X(210,150,50),white:X(210,210,220),red:X(220,85,85),green:X(80,200,110),yellow:X(230,185,60),blue:X(70,140,230),magenta:X(200,120,190),cyan:X(90,200,215),gray:X(120,120,135),bgRed:"\x1B[48;2;140;40;40m",bgGreen:"\x1B[48;2;30;100;50m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:X(110,215,230),brightMagenta:X(220,140,210),brightBlue:X(100,160,240)},cp={reset:op,bold:rp,dim:X(110,110,120),primary:X(0,110,190),secondary:X(0,125,148),success:X(0,148,62),warning:X(168,92,0),error:X(188,32,32),muted:X(110,110,120),subtle:X(155,155,165),tool_read:X(0,110,190),tool_write:X(168,92,0),tool_exec:X(128,42,188),tool_search:X(0,122,148),tool_git:X(0,138,62),tool_web:X(0,112,178),tool_sysadmin:X(168,82,0),tool_default:X(0,138,62),syn_keyword:X(128,42,188),syn_string:X(0,138,62),syn_number:X(168,92,0),syn_comment:X(135,135,148),syn_key:X(0,110,190),diff_add:X(0,148,62),diff_rem:X(188,32,32),banner_logo:X(0,122,205),banner_name:X(0,122,205),banner_version:X(100,100,118),banner_model:X(100,100,118),banner_yolo:X(168,62,0),banner_gemini:X(26,115,232),footer_sep:X(168,168,178),footer_model:X(0,102,175),footer_branch:X(0,138,62),footer_project:X(135,135,148),footer_divider:X(168,168,178),footer_mode:X(148,88,0),white:X(40,40,52),red:X(188,32,32),green:X(0,148,62),yellow:X(168,92,0),blue:X(0,110,190),magenta:X(128,42,188),cyan:X(0,125,148),gray:X(132,132,142),bgRed:"\x1B[48;2;180;50;50m",bgGreen:"\x1B[48;2;30;130;60m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:X(0,158,182),brightMagenta:X(158,52,208),brightBlue:X(0,112,208)},G_=ap?lp:cp;up.exports={T:G_,isDark:ap,DARK:lp,LIGHT:cp}});var Ds=ee((xP,fp)=>{"use strict";var Jt=require("fs"),dp=require("path");function Y_(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function z_(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function K_(t,e){let n=dp.dirname(t),o=dp.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Jt.existsSync(n)||Jt.mkdirSync(n,{recursive:!0,mode:448}),Jt.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Jt.renameSync(o,t)}catch(s){try{Jt.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=Jt.openSync(s,"wx"),Jt.writeSync(i,Buffer.from(String(process.pid))),Jt.closeSync(i),i=-1;try{return e()}finally{try{Jt.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{Jt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=Jt.readFileSync(s,"utf-8").trim(),c=parseInt(l,10);if(!Y_(c)){try{Jt.unlinkSync(s)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Jt.unlinkSync(s)}catch{}return e()}z_(o)}}}fp.exports={atomicWrite:K_,withFileLockSync:V_}});var aa=ee((SP,wp)=>{var Ao=require("fs"),bc=require("path"),{T:oa}=Sn(),{atomicWrite:X_,withFileLockSync:J_}=Ds(),pp={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:{}},Z_=new Set(["ollama","local"]),Q_=new Set(["openai","deepseek","anthropic","gemini"]),ia=[],fs={},ra=new Set;function gr(t){let e=String(t||"").toLowerCase();return Z_.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"}:Q_.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 e$(t){return gr(t).tier==="affordable"}function t$(t){return gr(t).tier==="premium"}function n$(t){let e=gr(t);return`${e.label} \u2014 ${e.detail}`}function s$(t,e,n,o,s=0){if(ia.push({provider:t,model:e,input:n,output:o,cacheRead:s}),fs[t]!==void 0){let r=yp(t);if(!r.allowed)process.stderr.write(`${oa.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${oa.reset}
|
|
9
|
+
`);else if(r.limit>0&&r.spent>=r.limit*.8){let i=`${t}:${r.limit}:80`;ra.has(i)||(ra.add(i),process.stderr.write(`${oa.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.${oa.reset}
|
|
10
|
+
`))}}}function wc(t,e){let n=pp[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function hp(t){let e=wc(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function mp(){let t={};for(let i of ia){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:hp(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 o$(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=mp();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=gr(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 r$(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function i$(t,e,n,o){let s=wc(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function a$(){ia=[],ra=new Set}function l$(t,e){fs[t]=e}function c$(t){delete fs[t]}function u$(){return{...fs}}function gp(t){let e=0;for(let n of ia)n.provider===t&&(e+=hp(n));return e}function yp(t){let e=gp(t),n=fs[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 bp(){let t=bc.join(process.cwd(),".nex","config.json");if(Ao.existsSync(t))try{let e=JSON.parse(Ao.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(fs={...e.costLimits})}catch{}}function d$(){let t=bc.join(process.cwd(),".nex"),e=bc.join(t,"config.json");Ao.existsSync(t)||Ao.mkdirSync(t,{recursive:!0}),J_(e,()=>{let n={};if(Ao.existsSync(e))try{n=JSON.parse(Ao.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=fs,X_(e,JSON.stringify(n,null,2))})}function f$(){fs={},ra=new Set}bp();wp.exports={PRICING:pp,trackUsage:s$,getSessionCosts:mp,formatCosts:o$,formatCostHint:i$,resetCosts:a$,getPricing:wc,setCostLimit:l$,removeCostLimit:c$,getCostLimits:u$,getProviderSpend:gp,checkBudget:yp,getProviderCostMode:gr,formatProviderCostMode:n$,isAffordableProvider:e$,isPremiumProvider:t$,loadCostLimits:bp,saveCostLimits:d$,resetCostLimits:f$,estimateTokens:r$}});var $c=ee((vP,xp)=>{var{BaseProvider:p$}=Ms();function Se(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 Oe(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?kp(e):""}function kp(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 _p(t){return Array.isArray(t)?t.filter(e=>e?.role==="user").map(e=>kp(e)).filter(Boolean).join(`
|
|
13
13
|
|
|
14
|
-
`):""}var
|
|
14
|
+
`):""}var la=null;function m$(){return la||(la={scenario:null,lastStep:0},la)}var g$=`// 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
|
-
`,
|
|
48
|
+
`,y$=`// 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
|
|
59
|
-
`)}function
|
|
60
|
-
`)}var
|
|
58
|
+
`;function b$(){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 w$(){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 _$=`// Scenario E fixture: nested callback flow with a simulated missing dependency.
|
|
61
61
|
|
|
62
62
|
function loadJson(file, cb) {
|
|
63
63
|
setTimeout(() => {
|
|
@@ -100,12 +100,12 @@ run()
|
|
|
100
100
|
console.error(err.message);
|
|
101
101
|
process.exitCode = 1;
|
|
102
102
|
});
|
|
103
|
-
`;function
|
|
104
|
-
`)}function
|
|
103
|
+
`;function $$(){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 k$(t){let e=String(t||"");return/malformed tool call/i.test(e)?"malformed":/Scenario I|bounded backlog same-file locate/i.test(e)?"i":/Scenario G|merge conflicts/i.test(e)?"g":/Scenario H|bounded backlog missing prompt example/i.test(e)?"h":/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 $p(t){let e=_p(t),n=k$(e||h$(t)),o=m$();!o.scenario&&n&&(o.scenario=n);let s=o.scenario||n;if(process.env.NEX_MOCK_MALFORMED_TOOL_CALL==="1"||s==="malformed"){let r=Oe(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:[Se("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=Oe(t,"a3")?3:Oe(t,"a2")?2:Oe(t,"a1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Inspecting current implementation.",tool_calls:[Se("read_file",{path:"app.js"},"a1")]}):o.lastStep<2?(o.lastStep=2,{content:"Applying async/await refactor.",tool_calls:[Se("write_file",{path:"app.js",content:g$},"a2")]}):o.lastStep<3?(o.lastStep=3,{content:"Verifying behavior.",tool_calls:[Se("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=Oe(t,"b4")?4:Oe(t,"b3")?3:Oe(t,"b2")?2:Oe(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:[Se("read_file",{path:"src/main.js"},"b1")]}):o.lastStep<2?(o.lastStep=2,{content:"Locating the bug in discount calculation.",tool_calls:[Se("read_file",{path:"src/discount.js"},"b2")]}):o.lastStep<3?(o.lastStep=3,{content:"Fixing discount logic.",tool_calls:[Se("write_file",{path:"src/discount.js",content:y$},"b3")]}):o.lastStep<4?(o.lastStep=4,{content:"Verifying the fix.",tool_calls:[Se("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=Oe(t,"c5")?5:Oe(t,"c4")?4:Oe(t,"c3")||Oe(t,"c2")?3:Oe(t,"c1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Inspecting nginx configuration.",tool_calls:[Se("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:[Se("write_file",{path:"sandbox-local/etc/nginx/nginx.conf",content:b$()},"c2"),Se("write_file",{path:"restart-nginx-dry-run.sh",content:w$()},"c3")]}):o.lastStep<4?(o.lastStep=4,{content:"Making the restart helper executable.",tool_calls:[Se("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:[Se("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=Oe(t,"d1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Investigating.",tool_calls:[Se("list_directory",{path:".",max_depth:2},"d1"),Se("glob",{pattern:"**/*.js"},"d2"),Se("grep",{pattern:"fakeApiGet",path:"."},"d3"),Se("read_file",{path:"README.md"},"d4"),Se("read_file",{path:"app.js"},"d5"),Se("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=Oe(t,"e3")?3:Oe(t,"e2")?2:Oe(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:[Se("read_file",{path:"processor.js"},"e1")]}):o.lastStep<2?(o.lastStep=2,{content:"Refactoring nested callbacks to async helpers without adding dependencies.",tool_calls:[Se("write_file",{path:"processor.js",content:_$},"e2")]}):o.lastStep<3?(o.lastStep=3,{content:"Verifying the refactored processor.",tool_calls:[Se("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=Oe(t,"f3")?3:Oe(t,"f2")?2:Oe(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:[Se("read_file",{path:"mock-root/etc/nginx/nginx.conf"},"f1")]}):o.lastStep<2?(o.lastStep=2,{content:"Fixing the upstream name typo.",tool_calls:[Se("write_file",{path:"mock-root/etc/nginx/nginx.conf",content:$$()},"f2")]}):o.lastStep<3?(o.lastStep=3,{content:"Checking the dummy service command stays sandboxed.",tool_calls:[Se("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=Oe(t,"g5")?5:Oe(t,"g4")?4:Oe(t,"g3")||Oe(t,"g2")?3:Oe(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:[Se("grep",{pattern:"<<<<<<<|=======|>>>>>>>",path:"."},"g1")]}):o.lastStep<3?(o.lastStep=3,{content:"Reading conflicted files.",tool_calls:[Se("read_file",{path:"service.js"},"g2"),Se("read_file",{path:"README.md"},"g3")]}):o.lastStep<5?(o.lastStep=5,{content:"Resolving conflicts by preserving configurable behavior.",tool_calls:[Se("write_file",{path:"service.js",content:`function port() { return Number(process.env.PORT || 3000); }
|
|
105
105
|
|
|
106
106
|
module.exports = { port };
|
|
107
107
|
`},"g4"),Se("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:[]}}if(s==="h"){let r=
|
|
108
|
+
`},"g5")]}):{content:"Resolved the simulated multi-file git conflict while preserving the configurable port behavior.",tool_calls:[]}}if(s==="h"){let r=_p(t),i=/previous plan named implementation files that do not exist/i.test(r),a=Oe(t,"h5")?5:Oe(t,"h4")?4:Oe(t,"h3")?3:Oe(t,"h2")?2:0;return o.lastStep=Math.max(o.lastStep,a),!i&&o.lastStep<1?{content:`Selected improvement: add an accessible label to the notation toolbar
|
|
109
109
|
Selection rationale: current UI evidence shows active editing controls need clearer labels
|
|
110
110
|
Files: components/NotationToolbar.tsx
|
|
111
111
|
Implementation outline: update one existing button label
|
|
@@ -120,37 +120,37 @@ Selection rationale: components/CommandCenter.tsx is an existing active editing
|
|
|
120
120
|
Files: components/CommandCenter.tsx
|
|
121
121
|
Implementation outline: read the planned implementation file, locate the Apply button if the first range misses it, then add one aria-label without changing behavior
|
|
122
122
|
Verification plan: npm test && npm run build
|
|
123
|
-
Browser/UI applicability: not required for this deterministic harness scenario`,tool_calls:[]}):o.lastStep<2?(o.lastStep=2,{content:"Reading the accepted implementation file.",tool_calls:[Se("read_file",{path:"components/CommandCenter.tsx",line_start:90,line_end:150},"i2")]}):o.lastStep<3?(o.lastStep=3,{content:"Checking labels inside the same planned file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"Apply"},"i3")]}):o.lastStep<4?(o.lastStep=4,{content:"Trying the more specific Apply label in the same file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"Apply changes"},"i4")]}):o.lastStep<5?(o.lastStep=5,{content:"Locating the Apply action class inside the same planned file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"apply-action"},"i5")]}):o.lastStep<6?(o.lastStep=6,{content:"Reading the located Apply button range.",tool_calls:[Se("read_file",{path:"components/CommandCenter.tsx",line_start:200,line_end:230},"i6")]}):o.lastStep<7?(o.lastStep=7,{content:"Applying the scoped accessibility label.",tool_calls:[Se("edit_file",{path:"components/CommandCenter.tsx",old_text:'<button className="apply-action">Apply</button>',new_text:'<button className="apply-action" aria-label="Apply changes">Apply</button>'},"i7")]}):o.lastStep<8?(o.lastStep=8,{content:"Verifying, committing, pushing, and checking final status.",tool_calls:[Se("bash",{command:'npm test && npm run build && git status --short --branch && git add components/CommandCenter.tsx && git commit -m "fix: clarify command center apply label" && git push origin main && git status --short --branch'},"i8")]}):{content:"Located the Apply button with a same-file search after the initial range missed it, implemented the command center accessibility label, verified with npm test and npm run build, committed the scoped change, pushed main to origin, and confirmed the worktree is clean.",tool_calls:[]}}return{content:"No mock scenario matched this prompt. Set a Scenario A\u2013I prompt (or enable malformed mode) to run deterministic E2E flows.",tool_calls:[]}}var
|
|
123
|
+
Browser/UI applicability: not required for this deterministic harness scenario`,tool_calls:[]}):o.lastStep<2?(o.lastStep=2,{content:"Reading the accepted implementation file.",tool_calls:[Se("read_file",{path:"components/CommandCenter.tsx",line_start:90,line_end:150},"i2")]}):o.lastStep<3?(o.lastStep=3,{content:"Checking labels inside the same planned file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"Apply"},"i3")]}):o.lastStep<4?(o.lastStep=4,{content:"Trying the more specific Apply label in the same file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"Apply changes"},"i4")]}):o.lastStep<5?(o.lastStep=5,{content:"Locating the Apply action class inside the same planned file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"apply-action"},"i5")]}):o.lastStep<6?(o.lastStep=6,{content:"Reading the located Apply button range.",tool_calls:[Se("read_file",{path:"components/CommandCenter.tsx",line_start:200,line_end:230},"i6")]}):o.lastStep<7?(o.lastStep=7,{content:"Applying the scoped accessibility label.",tool_calls:[Se("edit_file",{path:"components/CommandCenter.tsx",old_text:'<button className="apply-action">Apply</button>',new_text:'<button className="apply-action" aria-label="Apply changes">Apply</button>'},"i7")]}):o.lastStep<8?(o.lastStep=8,{content:"Verifying, committing, pushing, and checking final status.",tool_calls:[Se("bash",{command:'npm test && npm run build && git status --short --branch && git add components/CommandCenter.tsx && git commit -m "fix: clarify command center apply label" && git push origin main && git status --short --branch'},"i8")]}):{content:"Located the Apply button with a same-file search after the initial range missed it, implemented the command center accessibility label, verified with npm test and npm run build, committed the scoped change, pushed main to origin, and confirmed the worktree is clean.",tool_calls:[]}}return{content:"No mock scenario matched this prompt. Set a Scenario A\u2013I prompt (or enable malformed mode) to run deterministic E2E flows.",tool_calls:[]}}var _c=class extends p${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 process.env.NEX_MOCK_NULL_RESPONSE==="1"?null:$p(e)}async stream(e,n,o={}){if(process.env.NEX_MOCK_NULL_RESPONSE==="1")return null;let s=typeof o.onToken=="function"?o.onToken:()=>{},r=$p(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}};xp.exports={MockProvider:_c}});var kc=ee((EP,x$)=>{x$.exports={name:"nex-code",version:"0.5.30",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 qs=ee((TP,Cp)=>{var{T:Z}=Sn(),xc=5,Oo=(()=>{let t=[];for(let e=0;e<xc;e++)t.push(e);for(let e=xc-2;e>=1;e--)t.push(e);return t})(),Sp=["\u273D","\u2726","\u2727","\u2726"],vp=["\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<xc;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 Rp(t){return`${Z.dim}${vp[t%vp.length]}${Z.reset}`}var Sc=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Oo[this.frame%Oo.length],n=Ep(this.text),o=Tp(e,n.glyph,n.color),s=Rp(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}},vc=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=Oo[this.frame%Oo.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}
|
|
124
124
|
`}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+=`
|
|
125
125
|
`;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
|
|
126
126
|
`;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}
|
|
127
|
-
`}process.stderr.write(s)}},
|
|
128
|
-
`;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=
|
|
127
|
+
`}process.stderr.write(s)}},ca={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},ua={done:Z.green,in_progress:Z.cyan,pending:Z.dim,failed:Z.red},ps=null,Ec=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=Sp[this.frame%Sp.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}
|
|
128
|
+
`;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=ca[l.status]||ca.pending,d=ua[l.status]||ua.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}
|
|
129
129
|
`}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+=`
|
|
130
130
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),ps=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,ps===this&&(ps=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
|
|
131
131
|
`;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+=`
|
|
132
132
|
`;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}
|
|
133
|
-
`;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=
|
|
134
|
-
`}process.stderr.write(i)}},
|
|
133
|
+
`;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=ca[l.status]||ca.pending,d=ua[l.status]||ua.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}
|
|
134
|
+
`}process.stderr.write(i)}},Tc=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=Oo[this.frame%Oo.length],n=Ep(this.message),o=Tp(e,n.glyph,n.color),s=Rp(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 S$(t){ps=t}function v$(){return ps}function E$(){ps&&(ps.stop(),ps=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Cp.exports={C:Z,Spinner:Sc,MultiProgress:vc,TaskProgress:Ec,ToolProgress:Tc,setActiveTaskProgress:S$,getActiveTaskProgress:v$,cleanupTerminal:E$}});var da=ee((RP,Np)=>{"use strict";var{T:Fs}=Sn(),ye={kw:Fs.syn_keyword,str:Fs.syn_string,cmt:Fs.syn_comment,num:Fs.syn_number,type:Fs.cyan,punct:Fs.magenta,reset:Fs.reset},Ap={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"])},T$={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 Pp(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return T$[e]||null}var Op=/\x1b\[[0-9;]*m/g;function Vn(t,e,n){let o=t.split(Op),s=t.match(Op)||[],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=>ye.type+n+ye.reset),e=Vn(e,/"([^"\\]|\\.)*"/g,n=>ye.str+n+ye.reset),e=Vn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,n=>ye.num+n+ye.reset),e=Vn(e,/\b(true|false|null)\b/g,n=>ye.kw+n+ye.reset),e}function C$(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,n=>ye.cmt+n+ye.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(n,o,s)=>o+ye.type+s+ye.reset),e=Vn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(n,o)=>" "+ye.kw+o+ye.reset+"="),e=Vn(e,/"([^"]*)"/g,n=>ye.str+n+ye.reset),e}function A$(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,n=>ye.cmt+n+ye.reset),e=Vn(e,/#[0-9a-fA-F]{3,8}\b/g,n=>ye.num+n+ye.reset),e=Vn(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(n,o,s)=>ye.num+o+ye.reset+s),e=Vn(e,/([a-z][a-z-]*)(\s*:)/g,(n,o,s)=>ye.type+o+ye.reset+s),e=Vn(e,/"[^"]*"|'[^']*'/g,n=>ye.str+n+ye.reset),e}function Mp(t,e,n){if(e==="json")return R$(t);if(e==="html"||e==="xml")return C$(t);if(e==="css")return A$(t);if(e==="md")return t;let o=Ap[e]||Ap.js,s="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ye.cmt+t+ye.reset;if(s+=ye.cmt+t.slice(0,i+2)+ye.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return s}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return ye.str+t+ye.reset;if(s+=ye.str+t.slice(0,i+1)+ye.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+=ye.cmt+t.slice(r)+ye.reset,n.inBlockComment=!0,s;s+=ye.cmt+t.slice(r,a+2)+ye.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+=ye.cmt+t.slice(r)+ye.reset,s;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,s+=ye.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+ye.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+=ye.num+a+ye.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+=ye.punct+a+ye.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+=ye.kw+a+ye.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?s+=ye.type+a+ye.reset:s+=a;continue}s+=i,r++}return n.inString&&n.inString!=="`"&&(s+=ye.reset,n.inString=null),s}function O$(t,e){let n=Pp(e);if(!n)return t.split(`
|
|
135
135
|
`);let o=t.split(`
|
|
136
|
-
`),s={inString:null,inBlockComment:!1};return o.map(r=>
|
|
137
|
-
`),n=[],o=!1,s="";for(let r of e){let i=
|
|
136
|
+
`),s={inString:null,inBlockComment:!1};return o.map(r=>Mp(r,n,s))}function P$(t,e){return e?Mp(t,e,{inString:null,inBlockComment:!1}):t}Np.exports={detectLang:Pp,highlightLine:P$,highlightLines:O$}});var Oc=ee((CP,Wp)=>{var{C:S}=Et(),Bs=null;function pt(){if(Bs!==null)return Bs;let t=(process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"").toLowerCase();if(t.includes("utf-8")||t.includes("utf8"))Bs=!0;else try{process.stdout.isTTY&&process.stdout.columns>0?Bs=!0:Bs=process.env.TERM?!/^(vt100|vt220|ansi|xterm)$/.test(process.env.TERM):!0}catch{Bs=!1}return Bs}var Ze={tl:()=>pt()?"\u250C":"+",tr:()=>pt()?"\u2510":"+",bl:()=>pt()?"\u2514":"+",br:()=>pt()?"\u2518":"+",h:()=>pt()?"\u2500":"-",v:()=>pt()?"\u2502":"|",bq:()=>pt()?"\u258E":"|",dot:()=>pt()?"\u25CF":"*",error:()=>pt()?"\u2716":"x",diamond:()=>pt()?"\u25C6":"#",doutline:()=>pt()?"\u25C7":"o",dcircle:()=>pt()?"\u25CE":"@",circle:()=>pt()?"\u25CB":"o",bullet:()=>pt()?"\u2022":"-"};function Rc(){return Math.max(10,(process.stdout.columns||80)-2)}function M$(t){if(!t)return"";let e=t.split(`
|
|
137
|
+
`),n=[],o=!1,s="";for(let r of e){let i=Rc();if(r.trim().startsWith("```")){if(o){let a=Ze.h().repeat(Math.min(i-1,50));n.push(`${S.dim}${Ze.bl()}${a}${S.reset}`),o=!1,s=""}else{o=!0,s=r.trim().substring(3).trim();let a=s?` ${s} `:" code ",l=Ze.h().repeat(Math.max(0,Math.min(i-a.length-2,50)));n.push(`${S.dim}${Ze.tl()}${a}${l}${S.reset}`)}continue}if(o){n.push(`${S.dim}${Ze.v()}${S.reset} ${Ac(r,s)}`);continue}if(r.startsWith("###### ")){n.push(`${S.dim}${S.cyan} ${Zt(r.substring(7))}${S.reset}`);continue}if(r.startsWith("##### ")){n.push(`${S.dim}${S.cyan} ${Zt(r.substring(6))}${S.reset}`);continue}if(r.startsWith("#### ")){n.push(`${S.dim}${S.bold} ${Zt(r.substring(5))}${S.reset}`);continue}if(r.startsWith("### ")){n.push(`${S.bold}${S.cyan} ${Zt(r.substring(4))}${S.reset}`);continue}if(r.startsWith("## ")){n.push(`${S.bold}${S.primary} ${Zt(r.substring(3))}${S.reset}`);continue}if(r.startsWith("# ")){let a=Zt(r.substring(2)),l=Ze.h().repeat(Math.min(a.length+2,i-2));n.push(`
|
|
138
138
|
${S.bold}${S.primary} ${a}${S.reset}
|
|
139
139
|
${S.dim} ${l}${S.reset}`);continue}if(/^(\s*)(-{3,}|\*{3,}|_{3,})\s*$/.test(r)){n.push(`${S.dim}${Ze.h().repeat(Math.min(i,50))}${S.reset}`);continue}if(/^\s*>\s?/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*>\s?/,""),c=`${a}${S.dim}${Ze.bq()}${S.reset} ${S.dim}${Xn(l)}${S.reset}`;n.push(Jn(c,i,a+" "));continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${S.cyan}${Ze.bullet()}${S.reset} ${Xn(l)}`;n.push(Jn(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}${S.cyan}${c}.${S.reset} ${Xn(u)}`,f=l+" ".repeat(c.length+2);n.push(Jn(d,i,f));continue}}n.push(Jn(Xn(r),i))}return n.join(`
|
|
140
|
-
`)}function
|
|
140
|
+
`)}function Zt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Xn(t){return t?t.replace(/`([^`]+)`/g,`${S.cyan}$1${S.reset}`).replace(/\*\*([^*]+)\*\*/g,`${S.bold}$1${S.reset}`).replace(/\*([^*]+)\*/g,`${S.dim}$1${S.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${S.cyan}$1${S.reset} ${S.dim}($2)${S.reset}`):""}function Ac(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Lp(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Ip(t):e==="json"||e==="jsonc"?jp(t):e==="python"||e==="py"?Dp(t):e==="go"||e==="golang"?qp(t):e==="rust"||e==="rs"?Fp(t):e==="css"||e==="scss"||e==="less"?Bp(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Up(t):t:""}function Lp(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,`${S.yellow}$1${S.reset}`),r=r.replace(e,`${S.magenta}$1${S.reset}`),r=r.replace(n,`${S.green}$&${S.reset}`),r=r.replace(o,`${S.dim}$1${S.reset}`),r}function Ip(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,r=t;return r=r.replace(n,`${S.cyan}$1${S.reset}`),r=r.replace(e,`$1${S.green}$2${S.reset}`),r=r.replace(o,`${S.yellow}$&${S.reset}`),r=r.replace(s,`${S.dim}$1${S.reset}`),r}function jp(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,`${S.cyan}$1${S.reset}:`),r=r.replace(n,`: ${S.green}$1${S.reset}`),r=r.replace(o,`: ${S.yellow}$1${S.reset}`),r=r.replace(s,`: ${S.magenta}$1${S.reset}`),r}function Dp(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,`${S.yellow}$1${S.reset}`),i=i.replace(e,`${S.magenta}$1${S.reset}`),i=i.replace(r,`${S.cyan}$1${S.reset}`),i=i.replace(n,`${S.green}$&${S.reset}`),i=i.replace(o,`${S.dim}$1${S.reset}`),i}function qp(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,`${S.yellow}$1${S.reset}`),i=i.replace(n,`${S.cyan}$1${S.reset}`),i=i.replace(e,`${S.magenta}$1${S.reset}`),i=i.replace(o,`${S.green}$&${S.reset}`),i=i.replace(s,`${S.dim}$1${S.reset}`),i}function Fp(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,`${S.yellow}$1${S.reset}`),a=a.replace(n,`${S.cyan}$1${S.reset}`),a=a.replace(e,`${S.magenta}$1${S.reset}`),a=a.replace(i,`${S.yellow}$1${S.reset}`),a=a.replace(o,`${S.green}$&${S.reset}`),a=a.replace(s,`${S.dim}$1${S.reset}`),a}function Bp(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,`${S.yellow}$1${S.reset}`),a=a.replace(s,`${S.yellow}$1${S.reset}`),a=a.replace(e,`$1${S.cyan}$2${S.reset}:`),a=a.replace(o,`$1${S.magenta}$&${S.reset}`),a=a.replace(r,`${S.dim}$1${S.reset}`),a}function Up(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,`${S.dim}$1${S.reset}`),i=i.replace(o,`${S.green}$&${S.reset}`),i=i.replace(e,`<${S.magenta}$1${S.reset}`),i=i.replace(n,` ${S.cyan}$1${S.reset}=`),i=i.replace(r,`${S.yellow}$1${S.reset}`),i}function Jn(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)+`
|
|
141
141
|
`+n,a=r+1,i=a,s=n.length,r=-1;continue}s>e&&r===-1&&(o+=t.slice(a,i)+`
|
|
142
|
-
`+n,a=i,s=n.length+1),i++}return o+=t.slice(a),o}function
|
|
143
|
-
`)}function
|
|
144
|
-
`))!==-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(){if(this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock){let e=
|
|
145
|
-
`),this.inCodeBlock=!1,this.codeBlockLang=""}}_renderLine(e){let n=
|
|
142
|
+
`+n,a=i,s=n.length+1),i++}return o+=t.slice(a),o}function N$(t,e){if(!t||t.length===0)return"";let n=t.map((d,f)=>{let p=e.reduce((m,g)=>Math.max(m,(g[f]||"").length),0);return Math.max(d.length,p)}),o=Ze.v(),s=Ze.h(),r=pt()?"\u253C":"+",i=pt()?"\u252C":"+",a=pt()?"\u2534":"+",l=n.map(d=>s.repeat(d+2)).join(r),c=t.map((d,f)=>` ${S.bold}${d.padEnd(n[f])}${S.reset} `).join(o),u=[];u.push(`${S.dim}${Ze.tl()}${l.replace(/\+/g,i)}${Ze.tr()}${S.reset}`),u.push(`${S.dim}${o}${S.reset}${c}${S.dim}${o}${S.reset}`),u.push(`${S.dim}${pt()?"\u251C":"+"}${l}${pt()?"\u2524":"+"}${S.reset}`);for(let d of e){let f=t.map((p,m)=>` ${(d[m]||"").padEnd(n[m])} `).join(`${S.dim}${o}${S.reset}`);u.push(`${S.dim}${o}${S.reset}${f}${S.dim}${o}${S.reset}`)}return u.push(`${S.dim}${Ze.bl()}${l.replace(/\+/g,a)}${Ze.br()}${S.reset}`),u.join(`
|
|
143
|
+
`)}function L$(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?S.green:s>50?S.yellow:S.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${S.dim}${"\u2591".repeat(i)}${S.reset} ${s}% (${e}/${n})`}var Cc=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(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?`${Sn().T.cyan}\u25CF${Sn().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(`
|
|
144
|
+
`))!==-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(){if(this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock){let e=Rc();this._safeWrite(`${S.dim}${Ze.bl()}${Ze.h().repeat(Math.min(e-1,50))}${S.reset}
|
|
145
|
+
`),this.inCodeBlock=!1,this.codeBlockLang=""}}_renderLine(e){let n=Rc();if(e.trim().startsWith("```")){if(this.inCodeBlock){let s=Ze.h().repeat(Math.min(n-1,50));this._safeWrite(`${S.dim}${Ze.bl()}${s}${S.reset}
|
|
146
146
|
`),this.inCodeBlock=!1,this.codeBlockLang=""}else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:" code ",r=Ze.h().repeat(Math.max(0,Math.min(n-s.length-2,50)));this._safeWrite(`${S.dim}${Ze.tl()}${s}${r}${S.reset}
|
|
147
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(`${S.dim}${Ze.v()}${S.reset} ${
|
|
148
|
-
`);return}if(e.startsWith("###### ")){this._safeWrite(`${S.dim}${S.cyan} ${
|
|
149
|
-
`);return}if(e.startsWith("##### ")){this._safeWrite(`${S.dim}${S.cyan} ${
|
|
150
|
-
`);return}if(e.startsWith("#### ")){this._safeWrite(`${S.dim}${S.bold} ${
|
|
151
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${S.bold}${S.cyan} ${
|
|
152
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${S.bold}${S.primary} ${
|
|
153
|
-
`);return}if(e.startsWith("# ")){let s=
|
|
147
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(`${S.dim}${Ze.v()}${S.reset} ${Ac(e,this.codeBlockLang)}
|
|
148
|
+
`);return}if(e.startsWith("###### ")){this._safeWrite(`${S.dim}${S.cyan} ${Zt(e.substring(7))}${S.reset}
|
|
149
|
+
`);return}if(e.startsWith("##### ")){this._safeWrite(`${S.dim}${S.cyan} ${Zt(e.substring(6))}${S.reset}
|
|
150
|
+
`);return}if(e.startsWith("#### ")){this._safeWrite(`${S.dim}${S.bold} ${Zt(e.substring(5))}${S.reset}
|
|
151
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${S.bold}${S.cyan} ${Zt(e.substring(4))}${S.reset}
|
|
152
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${S.bold}${S.primary} ${Zt(e.substring(3))}${S.reset}
|
|
153
|
+
`);return}if(e.startsWith("# ")){let s=Zt(e.substring(2)),r=Ze.h().repeat(Math.min(s.length+2,n-2));this._safeWrite(`
|
|
154
154
|
${S.bold}${S.primary} ${s}${S.reset}
|
|
155
155
|
${S.dim} ${r}${S.reset}
|
|
156
156
|
`);return}if(/^(\s*)(-{3,}|\*{3,}|_{3,})\s*$/.test(e)){this._safeWrite(`${S.dim}${Ze.h().repeat(Math.min(n,50))}${S.reset}
|
|
@@ -158,40 +158,40 @@ ${S.dim} ${r}${S.reset}
|
|
|
158
158
|
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${S.cyan}\u2022${S.reset} ${Xn(r)}`,a=Jn(i,n,s+" ");this._safeWrite(`${a}
|
|
159
159
|
`);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}${S.cyan}${i}.${S.reset} ${Xn(a)}`,c=r+" ".repeat(i.length+2),u=Jn(l,n,c);this._safeWrite(`${u}
|
|
160
160
|
`);return}}let o=Jn(Xn(e),n);this._safeWrite(`${o}
|
|
161
|
-
`)}};function
|
|
162
|
-
`)}
|
|
161
|
+
`)}};function I$(t,e={}){let{maxDepth:n=4,maxFiles:o=60,highlight:s=new Set,dim:r=new Set,icons:i=!0}=e,a=require("fs"),l=require("path"),c=new Set([".git","node_modules",".next","__pycache__",".venv","venv",".cache","dist",".nex","coverage",".DS_Store","target"]);function u(O,N){if(!i)return"";if(N)return"\u{1F4C1} ";let z=l.extname(O).toLowerCase(),K={".js":"\u{1F4DC} ",".ts":"\u{1F537} ",".jsx":"\u269B ",".tsx":"\u{1F536} ",".py":"\u{1F40D} ",".rs":"\u{1F980} ",".go":"\u{1F535} ",".css":"\u{1F3A8} ",".scss":"\u{1F3A8} ",".html":"\u{1F310} ",".md":"\u{1F4DD} ",".json":"\u{1F4CB} ",".toml":"\u2699 ",".yml":"\u2699 ",".yaml":"\u2699 ",".sh":"\u26A1 ",".env":"\u{1F512} ",".svg":"\u{1F5BC} ",".test.js":"\u{1F9EA} ",".test.ts":"\u{1F9EA} ",".spec.js":"\u{1F9EA} "};return K[z]||K[O]||"\u{1F4C4} "}function d(O,N){if(N)return S.cyan;let z=l.extname(O).toLowerCase();return/\.(js|ts|jsx|tsx)$/.test(z)?S.yellow:/\.(py|rs|go|java|rb)$/.test(z)?S.green:/\.(css|scss|less)$/.test(z)?S.magenta:/\.(html|xml|svg)$/.test(z)?S.primary:/\.(md|txt|rst)$/.test(z)?S.white:/\.(json|toml|yml|yaml)$/.test(z)?S.subtle:/\.(sh|bash|zsh)$/.test(z)?S.success:S.reset}let f=[],p=0,m=pt(),g=m?"\u251C\u2500\u2500 ":"|-- ",w=m?"\u2514\u2500\u2500 ":"`-- ",k=m?"\u2502 ":"| ",T=" ",$=l.relative(process.cwd(),t)||".";f.push(`${S.bold}${S.cyan}${$}${S.reset}`);function R(O,N,z){if(N>n||p>=o)return;let K;try{K=a.readdirSync(O,{withFileTypes:!0})}catch{f.push(`${z}${g}${S.dim}(unreadable)${S.reset}`);return}K.sort((J,ne)=>J.isDirectory()!==ne.isDirectory()?J.isDirectory()?-1:1:J.name.localeCompare(ne.name)),K=K.filter(J=>!c.has(J.name)&&!J.name.startsWith("."));let V=20,ie=K.length-V;ie>0&&(K=K.slice(0,V));for(let J=0;J<K.length;J++){if(p>=o){f.push(`${z}${g}${S.dim}\u2026 +${ie} more${S.reset}`);return}let ne=K[J],Ke=J===K.length-1&&ie<=0,ve=Ke?w:g,H=z+(Ke?T:k),oe=l.join(O,ne.name),et=l.relative(process.cwd(),oe),Ve=S.reset;s.has(et)?Ve=S.yellow:r.has(et)?Ve=S.dim:Ve=d(ne.name,ne.isDirectory());let Ce=u(ne.name,ne.isDirectory()),Ae=ne.isDirectory()?`${S.bold}${ne.name}/${S.reset}`:ne.name;f.push(`${z}${ve}${Ve}${Ce}${Ae}${S.reset}`),p++,ne.isDirectory()&&R(oe,N+1,H)}ie>0&&f.push(`${z}${g}${S.dim}\u2026 +${ie} more${S.reset}`)}return R(t,1,""),f.join(`
|
|
162
|
+
`)}Wp.exports={hasUnicode:pt,G:Ze,renderTree:I$,renderMarkdown:M$,renderInline:Xn,stripHeadingMarkers:Zt,highlightCode:Ac,highlightJS:Lp,highlightBash:Ip,highlightJSON:jp,highlightPython:Dp,highlightGo:qp,highlightRust:Fp,highlightCSS:Bp,highlightHTML:Up,renderTable:N$,renderProgress:L$,wrapAnsi:Jn,StreamRenderer:Cc}});var eh=ee((AP,Qp)=>{var{T:v}=Sn(),Po=null;function fa(){if(Po!==null)return Po;let t=(process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"").toLowerCase();return t.includes("utf-8")||t.includes("utf8")||process.stdout.isTTY&&process.stdout.columns>0?Po=!0:Po=process.env.TERM?!/^(vt100|vt220|ansi|xterm)$/.test(process.env.TERM):!0,Po}var Fe=v,Hp=require("path"),Gp=fa()?["\u25C6","\u25C7","\u25CE","\u25C7"]:["#","o","@","o"];function ha(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var j$={read_file:v.tool_read,list_directory:v.tool_read,write_file:v.tool_write,edit_file:v.tool_write,patch_file:v.tool_write,bash:v.tool_exec,grep:v.tool_search,search_files:v.tool_search,glob:v.tool_search,git_commit:v.tool_git,git_push:v.tool_git,git_pull:v.tool_git,git_status:v.tool_git,git_diff:v.tool_git,git_log:v.tool_git,git_branch:v.tool_git,git_stash:v.tool_git,web_fetch:v.tool_web,web_search:v.tool_web,sysadmin:v.tool_sysadmin,ssh_exec:v.tool_sysadmin,ssh_upload:v.tool_sysadmin,ssh_download:v.tool_sysadmin,deploy:v.tool_sysadmin},Vp={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:v.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:v.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:v.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:v.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:v.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:v.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:v.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:v.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:v.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:v.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:v.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:v.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:v.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:v.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:v.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:v.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:v.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:v.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:v.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:v.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:v.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:v.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:v.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:v.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:v.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:v.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:v.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:v.tool_git,icon:"\u2713"}};function Xp(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 q$(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 F$(t){let e=Xp(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&&q$(s)||n.push(s.replace(/[ \t]+$/g,""))}return n.join(`
|
|
163
163
|
`).replace(/\n{3,}/g,`
|
|
164
164
|
|
|
165
|
-
`).trim()}function
|
|
166
|
-
`).map(e=>{let n=e.match(/^(\d+):\s?(.*)$/s);return n?{lineNumber:n[1],content:n[2]||""}:null}).filter(Boolean)}function
|
|
167
|
-
`)}function
|
|
168
|
-
`).filter((a,l,c)=>a.trim()||c.length===1||l===0),i=r.slice(0,n).map(a=>
|
|
169
|
-
`)}function
|
|
170
|
-
`)}function
|
|
171
|
-
`)}function
|
|
172
|
-
${i}`:r}if(t==="edit_file"){let i=
|
|
173
|
-
${i}`:r}if(t==="patch_file"){let i=
|
|
174
|
-
${i}`:r}return r}function
|
|
165
|
+
`).trim()}function Mc(t){return D$[t]||{label:"Run",accent:v.tool_default,icon:"\u2022"}}function Yp(t){let e=Mc(t);return`${e.accent}${Fe.bold}${e.icon} ${e.label.toUpperCase()}${v.reset}`}function B$(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function zp(t,e={}){return e.path?ha(e.path):e.file?ha(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):Vp[t]||B$(t)}function U$(t){return String(t||"").split(`
|
|
166
|
+
`).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}=da(),c=l(t||null),u=e.slice(0,o),d=u.map(({lineNumber:f,content:p})=>{let m=p.length>r?p.substring(0,r-1)+"\u2026":p;return`${s}${v.subtle}${f}:${v.reset} ${a(m,c)}${v.reset}`});return i&&e.length>u.length&&d.push(`${s}${v.subtle}\u2026 +${e.length-u.length} more line${e.length-u.length!==1?"s":""}${v.reset}`),d.join(`
|
|
167
|
+
`)}function H$(t,e=96){let n=String(t||"").replace(/\t/g," ").trimEnd();return n.length>e?n.substring(0,Math.max(1,e-1))+"\u2026":n}function Pc(t,e={}){let{maxLines:n=3,maxContent:o=96}=e,r=String(t||"").split(`
|
|
168
|
+
`).filter((a,l,c)=>a.trim()||c.length===1||l===0),i=r.slice(0,n).map(a=>H$(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function Jp(t,e={}){let{indent:n=" ",maxLines:o=2,maxContent:s=100}=e;if(!t)return"";let{shown:r,more:i}=Pc(t,{maxLines:o,maxContent:s});if(r.length===0)return"";let a=r.map((l,c)=>`${n}${v.subtle}${c===0?"$":">"}${v.reset} ${v.muted}${l}${v.reset}`);return i>0&&a.push(`${n}${v.subtle}\u2026 +${i} more command line${i!==1?"s":""}${v.reset}`),a.join(`
|
|
169
|
+
`)}function Nc(t,e,n,o={}){let{indent:s=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=o,{highlightLine:l,detectLang:c}=da(),u=c(t||null),{shown:d,more:f}=Pc(e,{maxLines:r,maxContent:i}),{shown:p,more:m}=Pc(n,{maxLines:r,maxContent:i}),g=[];return d.length>0&&a&&g.push(`${s}${v.subtle}before${v.reset}`),d.forEach(w=>{g.push(`${s}${v.diff_rem}- ${v.reset}${l(w,u)}${v.reset}`)}),f>0&&g.push(`${s}${v.subtle}\u2026 ${f} more removed line${f!==1?"s":""}${v.reset}`),p.length>0&&a&&g.push(`${s}${v.subtle}after${v.reset}`),p.forEach(w=>{g.push(`${s}${v.diff_add}+ ${v.reset}${l(w,u)}${v.reset}`)}),m>0&&g.push(`${s}${v.subtle}\u2026 ${m} more added line${m!==1?"s":""}${v.reset}`),g.join(`
|
|
170
|
+
`)}function Zp(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}${v.subtle}patch ${c+1}${v.reset}`);let u=Nc(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}${v.subtle}\u2026 +${e.length-s} more patches${v.reset}`),a.join(`
|
|
171
|
+
`)}function G$(t){let e=new Set,n=[];for(let o of t){let s=Mc(o.fnName).label;e.has(s)||(e.add(s),n.push(s))}return n.length===0?"":n.length<=3?n.join(`${Fe.dim} \u2192 ${Fe.reset}`):`${n.slice(0,3).join(`${Fe.dim} \u2192 ${Fe.reset}`)}${Fe.dim} \u2192 +${n.length-3}${Fe.reset}`}function pa(t,e=!1,n=null){if(e)return`${v.error}${fa()?"\u2716":"x"}${v.reset}`;let o=j$[t]||v.tool_default;if(n==="blink")return`${o}\x1B[5m${fa()?"\u25CF":"*"}\x1B[25m${v.reset}`;let s=typeof n=="number"?Gp[n%Gp.length]:n!==null?n:fa()?"\u25CF":"*";return`${o}${s}${v.reset}`}function Y$(t,e,n=!1,o=null){let s=(t||[]).filter(c=>c&&c.canExecute!==!1);if(s.length===0)return`${pa("",n,o)} Step ${e}`;if(s.length===1){let c=s[0],u=c.args||{},d=zp(c.fnName,{...u,path:u._originalPath||u.path});return`${pa(c.fnName,n,o)} ${Yp(c.fnName)} ${Fe.bold}${d}${Fe.reset}`}let r=s[0].fnName,i=G$(s)||`${s.length} tools`,a=s.slice(0,2).map(c=>zp(c.fnName,c.args||{})).filter(Boolean).join(`${Fe.dim} \xB7 ${Fe.reset}`),l=a?` ${v.subtle}\xB7${v.reset} ${Fe.dim}${a}${Fe.reset}`:"";return`${pa(r,n,o)} ${Yp(r)} ${Fe.bold}${i}${Fe.reset}${l}`}function z$(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,52);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=Vp[t]||t.replace(/_/g," "),s=n?` ${Fe.dim}${n}${Fe.reset}`:"",r=`${pa(t)} ${Fe.bold}${o}${Fe.reset}${s}`;if(t==="bash"||t==="ssh_exec"){let i=Jp(e.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
|
|
172
|
+
${i}`:r}if(t==="edit_file"){let i=Nc(e.path,e.old_text,e.new_text,{indent:" ",maxLines:2,maxContent:92});return i?`${r}
|
|
173
|
+
${i}`:r}if(t==="patch_file"){let i=Zp(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
|
|
174
|
+
${i}`:r}return r}function K$(t,e=8){let n=t.split(`
|
|
175
175
|
`),o=n.slice(0,e),s=n.length-e,r=o.map(i=>`${v.subtle} \u23BF${v.reset} ${i}`).join(`
|
|
176
176
|
`);return s>0&&(r+=`
|
|
177
|
-
${v.subtle} \u2026 +${s} lines${v.reset}`),r}var
|
|
177
|
+
${v.subtle} \u2026 +${s} lines${v.reset}`),r}var ma=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Kp=Math.floor(Math.random()*ma.length),V$=null;function X$(t){V$=t}function J$(){let t=ma[Kp%ma.length];return Kp++,t}function Z$(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 Q$(t,e,n,o){let s=String(n||""),r=Mc(t),i=` ${v.subtle}\u2502${v.reset} ${r.accent}${Fe.bold}${r.label}${v.reset} ${v.subtle}\xB7${v.reset} `;if(o){let c=s.split(`
|
|
178
178
|
`)[0];if(c.startsWith("BLOCKED:")){let p=c.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${v.muted}blocked: ${p}${v.reset}`}let u=c.replace(/^ERROR:\s*/i,"").substring(0,80),d=s.match(/\nHINT: (.+)/),f=d?`
|
|
179
|
-
${v.muted}${d[1].substring(0,100)}${v.reset}`:"";return`${i}${v.error}${u}${v.reset}${f}`}let a;switch(t){case"read_file":{let c=
|
|
179
|
+
${v.muted}${d[1].substring(0,100)}${v.reset}`:"";return`${i}${v.error}${u}${v.reset}${f}`}let a;switch(t){case"read_file":{let c=U$(s),u=c.length,d=c[c.length-1],f=d?parseInt(d.lineNumber||"0"):0,p=e.line_start||e.line_end,m=e.path?Hp.basename(e.path):null,g=m?` ${v.muted}from ${m}${v.reset}`:"";p&&f>u?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${u} line${u!==1?"s":""}${g}`;let w=W$(e.path,c,{maxLines:4,maxContent:120});w&&(a+=`
|
|
180
180
|
${w}`);break}case"write_file":{let u=(e.content||"").split(`
|
|
181
|
-
`).length,d=e.path?
|
|
181
|
+
`).length,d=e.path?Hp.basename(e.path):null,f=d?`Wrote ${d} \xB7 ${u} line${u!==1?"s":""}`:`Wrote ${u} line${u!==1?"s":""}`,{highlightLines:p}=da(),m=p(e.content||"",e.path||null),g=40,w=8;if(u<=g){let k=m.map(T=>` ${T}`).join(`
|
|
182
182
|
`);a=`${f}
|
|
183
183
|
${k}`}else{let k=m.slice(0,w).map(T=>` ${T}`).join(`
|
|
184
184
|
`);a=`${f}
|
|
185
185
|
${k}
|
|
186
186
|
${v.subtle}\u2026 +${u-w} lines${v.reset}`}break}case"edit_file":{let c=(e.old_text||"").split(`
|
|
187
187
|
`),u=(e.new_text||"").split(`
|
|
188
|
-
`),d=c.length,f=u.length,p=e.path?
|
|
188
|
+
`),d=c.length,f=u.length,p=e.path?ha(e.path):null,m=p?` ${v.muted}${p}${v.reset}`:"",g=Nc(e.path,e.old_text,e.new_text,{indent:" ",maxLines:4,maxContent:96});a=`${v.diff_rem}\u2212${d}${v.reset} ${v.diff_add}+${f}${v.reset}${m}`+(g?`
|
|
189
189
|
`+g:"");break}case"patch_file":{let c=e.patches||[],u=c.reduce((g,w)=>g+(w.old_text||"").split(`
|
|
190
190
|
`).length,0),d=c.reduce((g,w)=>g+(w.new_text||"").split(`
|
|
191
|
-
`).length,0),f=e.path?
|
|
191
|
+
`).length,0),f=e.path?ha(e.path):null,p=f?` ${v.muted}${f}${v.reset}`:"";a=`${c.length} patch${c.length!==1?"es":""} ${v.diff_rem}\u2212${u}${v.reset} ${v.diff_add}+${d}${v.reset}${p}`;let m=Zp(e.path,c,{indent:" ",maxPatches:3,maxLinesPerSide:2,maxContent:92});m&&(a+=`
|
|
192
192
|
${m}`);break}case"bash":{let u=s.match(/^EXIT (\d+)/),d=s.split(`
|
|
193
193
|
`).filter(g=>g&&!g.startsWith("EXIT ")&&!g.startsWith("HINT:")&&g.trim()),f=u?u[1]==="0"?`${v.success}\u2713${v.reset}`:`${v.error}\u2717 Exit ${u[1]}${v.reset}`:`${v.success}\u2713${v.reset}`,p=s.match(/\nHINT: (.+)/);if(p)a=`${f} ${v.muted}\u2014 ${p[1].substring(0,100)}${v.reset}`;else if(d.length===0)a=f;else{let g=u&&u[1]!=="0",w=g?d.slice(-3):d.slice(0,3),k=d.length-3,T=w.map(($,R)=>R===0?`${f} ${v.muted}${$.substring(0,120)}${v.reset}`:` ${v.muted}${$.substring(0,120)}${v.reset}`);if(k>0){let $=g?` ${v.subtle}${k} lines above\u2026${v.reset}`:` ${v.subtle}\u2026 +${k} lines${v.reset}`;g?T.unshift($):T.push($)}a=T.join(`
|
|
194
|
-
`)}let m=
|
|
194
|
+
`)}let m=Jp(e.command,{indent:" ",maxLines:2,maxContent:108});m&&(a=`${m}
|
|
195
195
|
${a}`);break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")a=`No matches${e.pattern?` ${v.muted}"${String(e.pattern).substring(0,40)}"${v.reset}`:""}`;else{let w=function(R){let O=R.indexOf(":");if(O===-1)return`${v.muted}${R.substring(0,90)}${v.reset}`;let N=R.substring(0,O),z=R.substring(O+1),K=z.match(/^(\d+)[:-](.*)/s),V=K?`:${K[1]}`:"",ie=(K?K[2]:z).trim(),J=`${v.subtle}${c.basename(N)}${V}${v.reset}`,ne=`${v.muted}${ie.substring(0,80)}${ie.length>80?"\u2026":""}${v.reset}`;return`${J} ${ne}`};var l=w;let c=require("path"),u=s.split(`
|
|
196
196
|
`).filter(Boolean),d=u.length,p=new Set(u.map(R=>R.split(":")[0]).filter(Boolean)).size,m=e.pattern?` ${v.muted}"${String(e.pattern).substring(0,40)}"${v.reset}`:"",g=p>1?`${d} match${d!==1?"es":""} in ${p} files${m}`:`${d} match${d!==1?"es":""}${m}`,k=e.path?`
|
|
197
197
|
${v.subtle}path:${v.reset} ${v.muted}${String(e.path).substring(0,70)}${v.reset}`:"",T=u.slice(0,5).map((R,O)=>O===0?`${g}${k}
|
|
@@ -210,87 +210,87 @@ ${g.join(`
|
|
|
210
210
|
`)[0].replace(/^\d+\.\s*/,"").trim():null,f=d?` ${v.muted}\u2014 ${d.substring(0,70)}${v.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(`
|
|
211
211
|
`).filter(p=>p.trim()&&!p.startsWith("EXIT ")),f=u?`${v.error}\u2717${v.reset}`:`${v.success}\u2713${v.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,w=m.map((k,T)=>T===0?`${f} ${v.muted}${k.substring(0,120)}${v.reset}`:` ${v.muted}${k.substring(0,120)}${v.reset}`);if(g>0){let k=u?` ${v.subtle}${g} lines above\u2026${v.reset}`:` ${v.subtle}\u2026 +${g} lines${v.reset}`;u?w.unshift(k):w.push(k)}a=w.join(`
|
|
212
212
|
`)}break}default:{let c=s.split(`
|
|
213
|
-
`).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?` ${v.subtle}\u2026 +${c.length-1} lines${v.reset}`:"";a=`${v.muted}${u}${v.reset}${d}`}else a=`${r.label} complete`}}return`${i}${a}${v.reset}`}function
|
|
214
|
-
${v.success}\u25C6${
|
|
213
|
+
`).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?` ${v.subtle}\u2026 +${c.length-1} lines${v.reset}`:"";a=`${v.muted}${u}${v.reset}${d}`}else a=`${r.label} complete`}}return`${i}${a}${v.reset}`}function ek(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=`
|
|
214
|
+
${v.success}\u25C6${Fe.reset} ${Fe.bold}${t}${Fe.reset}`;l+=` ${v.subtle}\u2501\u2501${v.reset} ${Fe.dim}${a}`,r.size>0&&(l+=` \xB7 ${v.warning}${r.size} file${r.size!==1?"s":""} modified${Fe.reset}`),s.size>0&&(l+=` \xB7 ${v.subtle}${s.size} scanned${Fe.reset}`),l+=Fe.reset;let c=8,u=[...r].slice(0,c),d=[...s].filter(f=>!r.has(f)).slice(0,Math.max(0,c-u.length));if(u.length>0||d.length>0){let f=require("path"),p=(()=>{try{return Oc().hasUnicode()}catch{return!0}})(),m=p?"\u251C\u2500 ":"|-- ",g=p?"\u2514\u2500 ":"`-- ",w=p?"\u2502 ":"| ",k=" ",T=[],$=0;for(let N of u){let z=f.relative(process.cwd(),N)||N,K=$===0&&d.length===0&&u.length===1?k:$===u.length-1&&d.length===0?g:m;T.push(`${v.subtle} ${K}${v.reset}${v.warning}${z}${v.reset}`),$++}for(let N=0;N<d.length;N++){let z=d[N],K=f.relative(process.cwd(),z)||z,V=N===d.length-1?g:m;T.push(`${v.subtle} ${V}${v.reset}${v.subtle}${K}${Fe.reset}`)}let R=r.size,O=s.size;if(R>c||u.length+d.length<R+O){let N=R-u.length+(O-d.length-(s.size-d.length));T.push(`${v.subtle} ${g}${v.reset}${Fe.dim}\u2026 +${Math.max(0,R+O-u.length-d.length)} more${Fe.reset}`)}T.length>0&&(l+=`
|
|
215
215
|
`+T.join(`
|
|
216
|
-
`))}return l}
|
|
216
|
+
`))}return l}Qp.exports={C:Fe,formatToolCall:z$,formatResult:K$,getToolSpinnerText:Z$,formatToolSummary:Q$,formatSectionHeader:Y$,formatMilestone:ek,stripAnsiControlSequences:Xp,sanitizeFinalAnswer:F$,getThinkingVerb:J$,setActiveModelForSpinner:X$,THINKING_VERBS:ma}});var Et=ee((OP,nh)=>{var{T:Nn}=Sn(),ga=Nn,tk=require("path"),th=["01100110","01111110","01111110","01011010","01111110","00111100"];function nk(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 sk(t,e,n={}){let o=ga.bold,s=ga.reset,r=nk(th,Nn.banner_logo),i=n.yolo?` ${o}${Nn.banner_yolo}\u26A1 YOLO${s}`:"",a=n.gemini?` ${o}${Nn.banner_gemini}\u2726 GEMINI${s}`:"",l=kc().version,c=e?tk.basename(e):null,u=`${Nn.muted}[${t||"model"}]${s}`,d=`${Nn.muted}[${c||"workspace"}]${s}`,f=[` ${Nn.banner_name}${o}nex-code${s} ${Nn.banner_version}v${l}${s}`,` ${u} ${d}`,` ${Nn.banner_logo}${o}terminal workbench${s} ${Nn.muted}\xB7 /help${s}${a}${i}`,` ${ga.dim}${"\u2014".repeat(50)}${s}`],p=Math.max(r.length,f.length),m=Math.floor((p-r.length)/2),g=Math.floor((p-f.length)/2),w=th[0].length,k=[];for(let T=0;T<p;T++){let $=r[T-m]??" ".repeat(w),R=f[T-g]??"";k.push($+R)}console.log(`
|
|
217
217
|
`+k.join(`
|
|
218
|
-
`))}var{Spinner:
|
|
219
|
-
`),a}catch(a){throw s.stop(),a}}async function
|
|
220
|
-
`){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 p=f.toLowerCase().trim();if(p==="y"){l(!0);return}if(p==="n"){l(!1);return}if(p==="a"&&e.toolName){
|
|
218
|
+
`))}var{Spinner:ok,MultiProgress:rk,TaskProgress:ik,ToolProgress:ak,setActiveTaskProgress:lk,getActiveTaskProgress:ck,cleanupTerminal:uk}=qs(),{formatToolCall:dk,formatResult:fk,getToolSpinnerText:pk,formatToolSummary:hk,formatSectionHeader:mk,formatMilestone:gk,getThinkingVerb:yk,setActiveModelForSpinner:bk}=eh();nh.exports={C:ga,banner:sk,Spinner:ok,MultiProgress:rk,TaskProgress:ik,ToolProgress:ak,setActiveTaskProgress:lk,getActiveTaskProgress:ck,cleanupTerminal:uk,formatToolCall:dk,formatResult:fk,getToolSpinnerText:pk,formatToolSummary:hk,formatSectionHeader:mk,formatMilestone:gk,getThinkingVerb:yk,setActiveModelForSpinner:bk}});var Ic=ee((PP,sh)=>{function Lc(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var wk=Lc();function _k(...t){Lc()&&console.log(...t)}function $k(...t){Lc()&&console.warn(...t)}sh.exports={DEBUG:wk,debugLog:_k,warnLog:$k}});var ih=ee((MP,rh)=>{"use strict";var kk=new Set(["read_file","grep","glob","search_files","list_directory"]),xk=new Set(["write_file","edit_file","patch_file"]),Sk=new Set(["bash"]),vk=new Set(["web_search","web_fetch","perplexity_search"]);function oh(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[a,l]of t)i+=l,kk.has(a)&&(n+=l),xk.has(a)&&(o+=l),Sk.has(a)&&(s+=l),vk.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 jc=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:oh(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}};rh.exports={MilestoneTracker:jc,_phaseName:oh}});var br=ee((NP,ah)=>{var yr=Tt(),Ek={"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 Tk(){return yr.getActiveModel()}function Rk(t){return yr.setActiveModel(t)}function Ck(){return yr.getModelNames()}function Ak(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}=Et(),{Spinner:o}=Et(),s=new o("Thinking...");s.start();let r=!0,i="";try{let a=await yr.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}
|
|
219
|
+
`),a}catch(a){throw s.stop(),a}}async function Pk(t,e){return yr.callChat(t,e)}ah.exports={MODELS:Ek,getActiveModel:Tk,setActiveModel:Rk,getModelNames:Ck,callOllamaStream:Ok,callOllama:Pk,parseToolArgs:Ak}});var _r=ee((LP,ph)=>{var Mk=require("readline"),{C:Ln}=Et(),Nk=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,Lk=/^=([\w-]+)/;function wr(t){return typeof t!="string"?t:t.replace(Nk,"").replace(Lk,"$1")}var Fc=[/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/],lh=[...Fc,/\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 Ik(t){for(let e of lh)if(e.test(t))return e;return null}var ch=[/\.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)/],jk=/\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 uh(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 Bc=[/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/],dh=[/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/],fh=[...Bc,...dh],Uc=!1,Zn=null,qc=null;function Dk(t){Uc=t}function qk(t){qc=t}function Fk(){return Uc}function Bk(t){Zn=t}function Uk(t){let e=wr(t);for(let n of Fc)if(n.test(e))return n;return null}function Wk(t){let e=wr(t);if(/ssh\s/.test(e)&&uh(e))return!1;for(let n of fh)if(n.test(e))return!0;return!1}function Hk(t){let e=wr(t);for(let n of Bc)if(n.test(e))return!0;return!1}function Gk(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=wr(t);if(!jk.test(e))return null;for(let n of ch)if(n.test(e))return n;return null}function Yk(t,e={}){if(Uc)return Promise.resolve(!0);if(qc)return qc(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 zk(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Zn&&typeof Zn.pause=="function"&&Zn.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${Ln.yellow}${t}${Ln.reset}`;for(let p=0;p<n.length;p++){let m=p===s,g=m?`${Ln.yellow}\u276F${Ln.reset}`:" ",w=m?`${Ln.yellow}${n[p]}${Ln.reset}`:n[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${w}`}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)),p=i(),m="";for(let g=0;g<n.length+1;g++)m+=`\x1B[${p+g};1H\x1B[2K`;f(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Zn&&typeof Zn.resume=="function"&&Zn.resume(),o(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&ya(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
|
|
220
|
+
`){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 p=f.toLowerCase().trim();if(p==="y"){l(!0);return}if(p==="n"){l(!1);return}if(p==="a"&&e.toolName){ya(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function zk(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?(ya(e.toolName),o(!0)):o(i!=="n")};if(Zn)Zn.question(`${Ln.yellow}${t} ${n}${Ln.reset}`,s);else{let r=Mk.createInterface({input:process.stdin,output:process.stdout});r.question(`${Ln.yellow}${t} ${n}${Ln.reset}`,i=>{r.close(),s(i)})}})}var ya=()=>{};function Kk(t){ya=t}ph.exports={sanitizeBashCommand:wr,FORBIDDEN_PATTERNS:Fc,SSH_FORBIDDEN_PATTERNS:lh,BASH_PROTECTED_PATHS:ch,SSH_SAFE_PATTERNS:Dc,isSSHReadOnly:uh,DANGEROUS_BASH:fh,CRITICAL_BASH:Bc,NOTABLE_BASH:dh,isForbidden:Uk,isSSHForbidden:Ik,isDangerous:Wk,isCritical:Hk,isBashPathForbidden:Gk,confirm:Yk,setAutoConfirm:Dk,getAutoConfirm:Fk,setConfirmHook:qk,setReadlineInterface:Bk,setAllowAlwaysHandler:Kk}});var gh=ee((jP,mh)=>{var ba=require("path"),{C:U}=Et(),{T:Wc,isDark:IP}=Sn(),{confirm:Vk,getAutoConfirm:Xk}=_r(),hh=2e3;function $r(t,e){let n=t.split(`
|
|
221
221
|
`),o=e.split(`
|
|
222
|
-
`),s=[],r=n.length,i=o.length;if(r>
|
|
223
|
-
${U.bold}${U.cyan} Diff: ${t}${U.reset}`);let s
|
|
224
|
-
${U.bold}${U.cyan} File exists \u2014 showing changes: ${t}${U.reset}`);let o
|
|
222
|
+
`),s=[],r=n.length,i=o.length;if(r>hh||i>hh){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 Jk(t,e,n,o=3){console.log(`
|
|
223
|
+
${U.bold}${U.cyan} Diff: ${t}${U.reset}`);let s=$r(e,n),r=[];if(s.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${U.gray} (no changes)${U.reset}`);return}let i=Math.max(0,r[0]-o),a=Math.min(s.length,r[r.length-1]+o+1);i>0&&console.log(`${U.gray} ...${U.reset}`);for(let l=i;l<a;l++){let c=s[l];switch(c.type){case"remove":console.log(`${U.red} - ${c.line}${U.reset}`);break;case"add":console.log(`${U.green} + ${c.line}${U.reset}`);break;default:console.log(`${U.gray} ${c.line}${U.reset}`)}}a<s.length&&console.log(`${U.gray} ...${U.reset}`),console.log()}function Zk(t,e,n){console.log(`
|
|
224
|
+
${U.bold}${U.cyan} File exists \u2014 showing changes: ${t}${U.reset}`);let o=$r(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${U.gray} (identical content)${U.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${U.gray} ...(${s-r} more changes)${U.reset}`);break}switch(i.type){case"remove":console.log(`${U.red} - ${i.line}${U.reset}`),r++;break;case"add":console.log(`${U.green} + ${i.line}${U.reset}`),r++;break;default:r>0&&console.log(`${U.gray} ${i.line}${U.reset}`)}}console.log()}function Qk(t,e){console.log(`
|
|
225
225
|
${U.bold}${U.cyan} New file: ${t}${U.reset}`);let n=e.split(`
|
|
226
|
-
`),o=n.slice(0,20);for(let s of o)console.log(`${U.green} + ${s}${U.reset}`);n.length>20&&console.log(`${U.gray} ...+${n.length-20} more lines${U.reset}`),console.log()}async function
|
|
227
|
-
${U.bold}${U.cyan} Side-by-side: ${t}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${U.reset}`);let i
|
|
228
|
-
`)}function
|
|
226
|
+
`),o=n.slice(0,20);for(let s of o)console.log(`${U.green} + ${s}${U.reset}`);n.length>20&&console.log(`${U.gray} ...+${n.length-20} more lines${U.reset}`),console.log()}async function ex(t){return Xk()?!0:Vk(` ${t}?`)}function tx(t,e,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
|
|
227
|
+
${U.bold}${U.cyan} Side-by-side: ${t}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${U.reset}`);let i=$r(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 p=[];for(;l<i.length&&i[l].type==="remove";)p.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(p.length,m.length);for(let w=0;w<g;w++)a.push({left:w<p.length?p[w]:"",right:w<m.length?m[w]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let c=a.map((p,m)=>p.type!=="same"?m:-1).filter(p=>p>=0);if(c.length===0){console.log(` ${U.gray}(no changes)${U.reset}`);return}let u=Math.max(0,c[0]-2),d=Math.min(a.length,c[c.length-1]+3),f=(p,m)=>{let g=p.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?p.substring(0,m):p+" ".repeat(m-g.length)};u>0&&console.log(` ${U.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${U.reset}`);for(let p=u;p<d;p++){let m=a[p];if(m.type==="same")console.log(` ${U.gray}${f(m.left,r)}${U.reset}\u2502${U.gray}${f(m.right,r)}${U.reset}`);else{let g=m.left?`${U.red}${f(m.left,r)}${U.reset}`:`${f("",r)}`,w=m.right?`${U.green}${f(m.right,r)}${U.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${w}`)}}d<a.length&&console.log(` ${U.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${U.reset}
|
|
228
|
+
`)}function nx(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],a=ba.isAbsolute(t)?ba.relative(process.cwd(),t):t,l=$r(e,n),c=1,u=1;for(let N of l)N.type==="same"?(N.oldLine=c++,N.newLine=u++):N.type==="remove"?(N.oldLine=c++,N.newLine=null):(N.oldLine=null,N.newLine=u++);let d=0,f=0;for(let N of l)N.type==="add"?d++:N.type==="remove"&&f++;if(console.log(`
|
|
229
229
|
${U.green}\u23FA${U.reset} ${U.bold}${s}(${a})${U.reset}`),d===0&&f===0){console.log(` ${U.dim}\u23BF (no changes)${U.reset}
|
|
230
|
-
`);return}let p=[];if(d>0&&p.push(`Added ${d} line${d!==1?"s":""}`),f>0&&p.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let N=i.filter(ie=>ie.severity==="error").length,z=i.filter(ie=>ie.severity==="warn").length,K=i.filter(ie=>ie.severity==="info").length,V=[];N>0&&V.push(`${U.red}${N} error${N!==1?"s":""}${U.dim}`),z>0&&V.push(`${U.yellow}${z} warning${z!==1?"s":""}${U.dim}`),K>0&&V.push(`${U.cyan}${K} info${K!==1?"s":""}${U.dim}`),p.push(`found ${V.join(", ")}`)}console.log(` ${U.dim}\u23BF ${p.join(", ")}${U.reset}`);let g=[];l.forEach((N,z)=>{N.type!=="same"&&g.push(z)});let w=[],k=null,T=null;for(let N of g){let z=Math.max(0,N-r),K=Math.min(l.length-1,N+r);k===null?(k=z,T=K):(z<=T+1||(w.push([k,T]),k=z),T=K)}k!==null&&w.push([k,T]);let $=" ",R=process.stdout.columns||120;function O(N,z,K){let V=K.replace(/\x1b\[[0-9;]*m/g,""),ie=K+" ".repeat(Math.max(0,R-V.length));return`${N}${z}${ie}${U.reset}`}for(let N=0;N<w.length;N++){N>0&&console.log(`${$}${U.dim}\xB7\xB7\xB7${U.reset}`);let[z,K]=w[N];for(let V=z;V<=K;V++){let ie=l[V],J=ie.newLine!=null?ie.newLine:ie.oldLine,ne=String(J).padStart(4),Ke=ie.type!=="remove"?i.filter(ve=>ve.line===ie.newLine):[];ie.type==="remove"?console.log(O(
|
|
230
|
+
`);return}let p=[];if(d>0&&p.push(`Added ${d} line${d!==1?"s":""}`),f>0&&p.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let N=i.filter(ie=>ie.severity==="error").length,z=i.filter(ie=>ie.severity==="warn").length,K=i.filter(ie=>ie.severity==="info").length,V=[];N>0&&V.push(`${U.red}${N} error${N!==1?"s":""}${U.dim}`),z>0&&V.push(`${U.yellow}${z} warning${z!==1?"s":""}${U.dim}`),K>0&&V.push(`${U.cyan}${K} info${K!==1?"s":""}${U.dim}`),p.push(`found ${V.join(", ")}`)}console.log(` ${U.dim}\u23BF ${p.join(", ")}${U.reset}`);let g=[];l.forEach((N,z)=>{N.type!=="same"&&g.push(z)});let w=[],k=null,T=null;for(let N of g){let z=Math.max(0,N-r),K=Math.min(l.length-1,N+r);k===null?(k=z,T=K):(z<=T+1||(w.push([k,T]),k=z),T=K)}k!==null&&w.push([k,T]);let $=" ",R=process.stdout.columns||120;function O(N,z,K){let V=K.replace(/\x1b\[[0-9;]*m/g,""),ie=K+" ".repeat(Math.max(0,R-V.length));return`${N}${z}${ie}${U.reset}`}for(let N=0;N<w.length;N++){N>0&&console.log(`${$}${U.dim}\xB7\xB7\xB7${U.reset}`);let[z,K]=w[N];for(let V=z;V<=K;V++){let ie=l[V],J=ie.newLine!=null?ie.newLine:ie.oldLine,ne=String(J).padStart(4),Ke=ie.type!=="remove"?i.filter(ve=>ve.line===ie.newLine):[];ie.type==="remove"?console.log(O(Wc.diff_rem_bg,U.red,`${$}${ne} - ${ie.line}`)):ie.type==="add"?console.log(O(Wc.diff_add_bg,U.green,`${$}${ne} + ${ie.line}`)):console.log(`${$}${U.dim}${ne} ${U.reset}${ie.line}`);for(let ve of Ke){let H=U.cyan,oe="\u2139";ve.severity==="error"?(H=U.red,oe="\u2716"):ve.severity==="warn"&&(H=U.yellow,oe="\u26A0"),console.log(`${$} ${H}${oe} ${ve.message}${U.reset}`)}}}console.log()}function sx(t,e,n={}){let o=ba.isAbsolute(t)?ba.relative(process.cwd(),t):t,s=e.split(`
|
|
231
231
|
`),r=n.annotations||[];console.log(`
|
|
232
|
-
${U.green}\u23FA${U.reset} ${U.bold}Create(${o})${U.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,p=r.filter(g=>g.severity==="info").length,m=[];d>0&&m.push(`${U.red}${d} error${d!==1?"s":""}${U.dim}`),f>0&&m.push(`${U.yellow}${f} warning${f!==1?"s":""}${U.dim}`),p>0&&m.push(`${U.cyan}${p} info${p!==1?"s":""}${U.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${U.dim}\u23BF ${i.join(", ")}${U.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(s.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),p=d+1,m=r.filter(T=>T.line===p),g=`${l}${f} + ${s[d]}`,w=g.replace(/\x1b\[[0-9;]*m/g,""),k=g+" ".repeat(Math.max(0,c-w.length));console.log(`${
|
|
233
|
-
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function
|
|
234
|
-
`);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
|
|
232
|
+
${U.green}\u23FA${U.reset} ${U.bold}Create(${o})${U.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,p=r.filter(g=>g.severity==="info").length,m=[];d>0&&m.push(`${U.red}${d} error${d!==1?"s":""}${U.dim}`),f>0&&m.push(`${U.yellow}${f} warning${f!==1?"s":""}${U.dim}`),p>0&&m.push(`${U.cyan}${p} info${p!==1?"s":""}${U.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${U.dim}\u23BF ${i.join(", ")}${U.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(s.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),p=d+1,m=r.filter(T=>T.line===p),g=`${l}${f} + ${s[d]}`,w=g.replace(/\x1b\[[0-9;]*m/g,""),k=g+" ".repeat(Math.max(0,c-w.length));console.log(`${Wc.diff_add_bg}${U.green}${k}${U.reset}`);for(let T of m){let $=U.cyan,R="\u2139";T.severity==="error"?($=U.red,R="\u2716"):T.severity==="warn"&&($=U.yellow,R="\u26A0"),console.log(`${l} ${$}${R} ${T.message}${U.reset}`)}}s.length>20&&console.log(`${l}${U.dim} ...+${s.length-20} more lines${U.reset}`),console.log()}mh.exports={diffLines:$r,showEditDiff:Jk,showWriteDiff:Zk,showNewFilePreview:Qk,confirmFileChange:ex,showSideBySideDiff:tx,showDiff:nx,showNewFile:sx}});var $a=ee((DP,wh)=>{var yh=require("util").promisify(require("child_process").exec),ox=require("util").promisify(require("child_process").execFile),{C:ht}=Et();async function Hc(t){try{let{stdout:e}=await yh(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function wa(...t){try{let{stdout:e}=await ox("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function rx(){return await Hc("git rev-parse --is-inside-work-tree")==="true"}async function ix(){return await Hc("git branch --show-current")}async function Gc(){try{let{stdout:t}=await yh("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
233
|
+
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function _a(t=!1){return await Hc(`git diff ${t?"--cached":""}`)||""}async function Yc(){return(await Gc()).map(e=>e.file)}async function bh(){let t=await Yc();if(t.length===0)return null;let e=await _a(),o=await _a(!0)||e,s=0,r=0;if(o){let u=o.split(`
|
|
234
|
+
`);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 ax(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await wa("checkout","-b",n)!==null?n:null}async function lx(t){return await wa("add","-A"),await wa("commit","-m",t)?await wa("rev-parse","--short","HEAD"):null}async function cx(){let t=await bh();if(!t)return`${ht.dim}No changes${ht.reset}`;let e=[];e.push(`
|
|
235
235
|
${ht.bold}${ht.cyan}Git Diff Summary:${ht.reset}`),e.push(` ${ht.green}+${t.stats.additions}${ht.reset} ${ht.red}-${t.stats.deletions}${ht.reset} in ${t.files.length} file(s)`),e.push(`
|
|
236
236
|
${ht.bold}${ht.cyan}Files:${ht.reset}`);for(let n of t.files.slice(0,20))e.push(` ${ht.dim}${n}${ht.reset}`);return t.files.length>20&&e.push(` ${ht.dim}...+${t.files.length-20} more${ht.reset}`),e.push(`
|
|
237
237
|
${ht.bold}${ht.cyan}Suggested message:${ht.reset}`),e.push(` ${ht.cyan}${t.summary}${ht.reset}
|
|
238
238
|
`),e.join(`
|
|
239
|
-
`)}async function
|
|
239
|
+
`)}async function ux(){return(await Gc()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function dx(){let t=await Yc();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 _a();if(n){let o=n.length>5e3?n.substring(0,5e3)+`
|
|
240
240
|
...(truncated)`:n;e.push(`
|
|
241
241
|
DIFF:
|
|
242
242
|
${o}`)}return e.join(`
|
|
243
|
-
`)}
|
|
244
|
-
`).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(
|
|
245
|
-
`)){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
|
|
243
|
+
`)}wh.exports={isGitRepo:rx,getCurrentBranch:ix,getStatus:Gc,getDiff:_a,getChangedFiles:Yc,analyzeDiff:bh,createBranch:ax,commit:lx,formatDiffSummary:cx,getDiffContext:dx,getMergeConflicts:ux}});var Th=ee((FP,Eh)=>{var Rt=require("fs").promises,qP=require("fs"),fn=require("path"),fx=require("crypto"),{execSync:zc,execFileSync:kh}=require("child_process"),px=100*1024,xh=50,Wt=[],Mo=[];function hx(t,e,n,o){for(Wt.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});Wt.length>xh;)Wt.shift();Mo.length=0,Sh(Wt[Wt.length-1]).catch(()=>{})}async function mx(){if(Wt.length===0)return null;let t=Wt.pop();if(t.oldContent===null)try{await Rt.unlink(t.filePath)}catch{}else await Rt.writeFile(t.filePath,t.oldContent,"utf-8");return Mo.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function gx(){if(Mo.length===0)return null;let t=Mo.pop();return await Rt.writeFile(t.filePath,t.newContent,"utf-8"),Wt.push(t),{tool:t.tool,filePath:t.filePath}}function yx(t=10){return Wt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function bx(){return Wt.length}function wx(){return Mo.length}function _x({diskToo:t=!0}={}){if(Wt.length=0,Mo.length=0,t){let e=xa();Rt.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&Rt.unlink(fn.join(e,o)).catch(()=>{})}).catch(()=>{})}}function xa(){return fn.join(process.cwd(),".nex","history")}async function _h(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=px)return{inline:!0,content:t};let n=fx.createHash("sha256").update(t,"utf-8").digest("hex"),o=fn.join(e,"blobs");return await Rt.mkdir(o,{recursive:!0}),await Rt.writeFile(fn.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function Sh(t){let e=xa();await Rt.mkdir(e,{recursive:!0});let n=fn.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await _h(t.oldContent,e),r=await _h(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 Rt.writeFile(fn.join(e,o),JSON.stringify(i),"utf-8")}async function $h(t,e){if(!t)return null;if(t.inline)return t.content;let n=fn.join(e,"blobs",t.hash);return Rt.readFile(n,"utf-8")}async function $x(){let t=xa(),e;try{e=await Rt.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 Rt.readFile(fn.join(t,s),"utf-8"),i=JSON.parse(r),a=await $h(i.oldContent,t),l=await $h(i.newContent,t);Wt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),o++}catch{}for(;Wt.length>xh;)Wt.shift();return o}async function kx(t=7){let e=xa(),n;try{n=await Rt.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 Rt.readFile(fn.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 Rt.unlink(fn.join(e,c))}catch{}let l=fn.join(e,"blobs");try{let c=await Rt.readdir(l);for(let u of c)if(!i.has(u))try{await Rt.unlink(fn.join(l,u))}catch{}}catch{}return r}var ka="nex-snapshot";function xx(t,e=process.cwd()){let n=t?`${ka}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${ka}-${Date.now()}`;try{return zc("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(kh("git",["stash","push","-u","-m",n],{cwd:e,timeout:15e3}),zc("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 vh(t=process.cwd()){try{let e=zc("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
|
|
244
|
+
`).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(ka)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${ka}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function Sx(t,e=process.cwd()){try{let n=vh(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?(kh("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}}}Eh.exports={recordChange:hx,undo:mx,redo:gx,getHistory:yx,getUndoCount:bx,getRedoCount:wx,clearHistory:_x,persistEntry:Sh,loadPersistedHistory:$x,pruneHistory:kx,createSnapshot:xx,listSnapshots:vh,restoreSnapshot:Sx}});var Zc=ee((BP,Mh)=>{var it=require("fs"),Ht=require("path"),{atomicWrite:vx,withFileLockSync:Ex}=Ds(),jt=[];function kr(){return Ht.join(process.cwd(),".nex","skills")}function Rh(){return Ht.join(process.cwd(),".nex","config.json")}function Ch(){let t=kr();return it.existsSync(t)||it.mkdirSync(t,{recursive:!0}),t}function Xc(){let t=Rh();if(!it.existsSync(t))return[];try{let e=JSON.parse(it.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Ah(t){let e=Rh(),n=Ht.dirname(e);it.existsSync(n)||it.mkdirSync(n,{recursive:!0}),Ex(e,()=>{let o={};if(it.existsSync(e))try{o=JSON.parse(it.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,vx(e,JSON.stringify(o,null,2))})}function Oh(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 Ph(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(`
|
|
245
|
+
`)){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 Kc(t){try{let e=it.readFileSync(t,"utf-8").trim();if(!e)return null;let n=Ht.basename(t,".md"),{triggers:o,body:s}=Ph(e);return{name:n,type:"prompt",filePath:t,instructions:s||e,triggers:o,commands:[],tools:[]}}catch{return null}}function Vc(t){try{let e=require(t),{valid:n,errors:o}=Oh(e,t);return n?{name:e.name||Ht.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}
|
|
246
246
|
${o.join(`
|
|
247
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
247
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Jc(){jt=[];let t=Xc(),e=kr(),n=[];if(it.existsSync(e))try{n=it.readdirSync(e)}catch{n=[]}for(let s of n){let r=Ht.join(e,s),i;try{i=it.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;s.endsWith(".md")?a=Kc(r):s.endsWith(".js")&&(a=Vc(r)),a&&(a.enabled=!t.includes(a.name),jt.push(a))}let o=Ht.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&it.existsSync(o)){let s;try{s=it.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{s=[]}for(let r of s){let i=Ht.join(o,r),a=Ht.basename(r,Ht.extname(r));if(jt.some(u=>u.name===a))continue;let l;try{l=it.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?Kc(i):Vc(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),jt.push(c))}}return jt}function Tx(){let t=[];for(let e of jt)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
248
248
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
249
249
|
${t.join(`
|
|
250
250
|
|
|
251
|
-
`)}`}function
|
|
251
|
+
`)}`}function Rx(){let t=[];for(let e of jt)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function Cx(){let t=[];for(let e of jt)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 Ax(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let o of jt)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 jt)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 Px(){return jt.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 Mx(t){let e=jt.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=Xc().filter(o=>o!==t);return Ah(n),!0}function Nx(t){let e=jt.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=Xc();return n.includes(t)||(n.push(t),Ah(n)),!0}function Lx(){return jt}async function Ix(t,e={}){let{execFileSync:n}=require("child_process"),o=Ch(),s=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(s=`https://github.com/${t}.git`);let r=e.name||Ht.basename(s,".git").replace(/^nex-skill-/,""),i=Ht.join(o,r);if(it.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=Ht.join(i,"skill.json"),l=it.existsSync(a),c=it.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{it.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(it.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{it.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Jc(),{ok:!0,name:r}}async function jx(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=Ht.join(kr(),t);if(!it.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${kr()}`};try{return it.rmSync(e,{recursive:!0,force:!0}),Jc(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function qx(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let o of jt){if(!o.enabled||!o.triggers||o.triggers.length===0)continue;let s=0;for(let r of o.triggers){let i=r.toLowerCase();new RegExp("\\b"+i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b").test(e)?s=Math.max(s,3):e.includes(i)&&(s=Math.max(s,1))}if(s>0){let r=(o.instructions||"").trim();n.push({name:o.name,instructions:r,score:s})}}return n.sort((o,s)=>s.score-o.score),n}Mh.exports={initSkillsDir:Ch,loadAllSkills:Jc,getSkillInstructions:Tx,getSkillCommands:Rx,getSkillToolDefinitions:Cx,routeSkillCall:Ax,handleSkillCommand:Ox,listSkills:Px,enableSkill:Mx,disableSkill:Nx,getLoadedSkills:Lx,installSkill:Ix,searchSkills:jx,removeSkill:Dx,matchSkillTriggers:qx,_getSkillsDir:kr,_validateScriptSkill:Oh,_loadMarkdownSkill:Kc,_loadScriptSkill:Vc,_parseFrontmatter:Ph}});var eu=ee((UP,qh)=>{var{spawn:Fx}=require("child_process"),Bx=require("path"),Nh=require("fs"),Qn=new Map;function Ux(){return Bx.join(process.cwd(),".nex","config.json")}function Qc(){let t=Ux();if(!Nh.existsSync(t))return{};try{return JSON.parse(Nh.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Sa(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})+`
|
|
252
252
|
`,l="",c=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},o);function u(f){l+=f.toString();let p=l.split(`
|
|
253
|
-
`);for(let m of p)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=p[p.length-1]||""}function d(){clearTimeout(c),t.stdout.removeListener("data",u)}t.stdout.on("data",u);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function
|
|
254
|
-
`):JSON.stringify(s)}function
|
|
255
|
-
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=
|
|
253
|
+
`);for(let m of p)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=p[p.length-1]||""}function d(){clearTimeout(c),t.stdout.removeListener("data",u)}t.stdout.on("data",u);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function Lh(t,e){if(Qn.has(t))return Qn.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=Fx(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await Sa(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Sa(s,"tools/list",{});return r.tools=i&&i.tools||[],Qn.set(t,r),r}catch(i){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Ih(t){let e=Qn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Qn.delete(t),!0}function Wx(){for(let[t]of Qn)Ih(t)}async function jh(t,e,n={}){let o=Qn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await Sa(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(`
|
|
254
|
+
`):JSON.stringify(s)}function Dh(){let t=[];for(let[e,n]of Qn)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 Hx(){return Dh().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Gx(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 jh(o,s,e)}function Yx(){let t=Qc();return Object.entries(t).map(([e,n])=>{let o=Qn.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function zx(){let t=Qc(),e=[];for(let[n,o]of Object.entries(t))try{let s=await Lh(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}qh.exports={loadMCPConfig:Qc,sendRequest:Sa,connectServer:Lh,disconnectServer:Ih,disconnectAll:Wx,callTool:jh,getAllTools:Dh,getMCPToolDefinitions:Hx,routeMCPCall:Gx,listServers:Yx,connectAll:zx}});var Ea=ee((WP,Wh)=>{var Fh=require("fs"),tu=require("path"),va=[],xr=[],Us={},Sr=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Bh(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 xr.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(xr.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Uh(t,e){return Sr.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Us[t]||(Us[t]=[]),Us[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Sr.join(", ")}`}}async function nu(t,e){let n=Us[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 Kx(){let t=tu.join(process.cwd(),".nex","plugins"),e=[];if(!Fh.existsSync(t))return{loaded:0,errors:[]};let n=Fh.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:Bh,registerHook:Uh,EVENTS:Sr};for(let s of n){let r=tu.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}va.push({name:i.name||tu.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:va.length,errors:e}}function Vx(){return xr.map(t=>t.definition)}async function Xx(t,e,n={}){let o=xr.find(a=>a.definition.function.name===t);if(!o)return null;let s=await nu("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await nu("afterToolExec",{name:t,args:e,result:r})).result||r}function Jx(){return[...va]}function Zx(){let t={};for(let e of Sr)t[e]=(Us[e]||[]).length;return t}function Qx(){va.length=0,xr.length=0;for(let t of Object.keys(Us))delete Us[t]}Wh.exports={registerTool:Bh,registerHook:Uh,emit:nu,loadPlugins:Kx,getPluginToolDefinitions:Vx,executePluginTool:Xx,getLoadedPlugins:Jx,getHookCounts:Zx,clearPlugins:Qx,EVENTS:Sr}});var su=ee((HP,zh)=>{var{getSkillToolDefinitions:eS}=Zc(),{getMCPToolDefinitions:tS}=eu(),{getPluginToolDefinitions:nS}=Ea(),Ta=new Map;function Hh(){let{TOOL_DEFINITIONS:t}=vr();return[...t,...eS(),...tS(),...nS()]}function Gh(t){if(Ta.has(t))return Ta.get(t);let n=Hh().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return Ta.set(t,o),o}function sS(){Ta.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=Yh(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function Yh(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 oS(t,e){let n=Gh(t);if(n===null){let d=Hh().map(p=>p.function.name),f=Ra(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
255
|
+
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:
|
|
256
256
|
`+i.map(u=>` - ${u}`).join(`
|
|
257
257
|
`)+`
|
|
258
258
|
|
|
259
|
-
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function
|
|
259
|
+
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function rS(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}}zh.exports={validateToolArgs:oS,validateToolCallFormat:rS,closestMatch:Ra,levenshtein:Yh,getCachedSchema:Gh,clearSchemaCache:sS}});var Jh=ee((GP,Xh)=>{var{levenshtein:Ca}=su(),iS=200,aS=.3,lS=2;function ou(t){return t.replace(/\r\n/g,`
|
|
260
260
|
`).replace(/\r/g,`
|
|
261
|
-
`).replace(/\t/g," ".repeat(
|
|
261
|
+
`).replace(/\t/g," ".repeat(lS)).split(`
|
|
262
262
|
`).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(`
|
|
263
|
-
`)}function
|
|
263
|
+
`)}function cS(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=ou(t),o=ou(e);if(!n.includes(o))return null;let s=t.split(`
|
|
264
264
|
`),r=n.split(`
|
|
265
265
|
`),i=o.split(`
|
|
266
266
|
`),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(`
|
|
267
|
-
`)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(o)!==-1)return s[c]}return null}function
|
|
267
|
+
`)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(o)!==-1)return s[c]}return null}function uS(t,e){if(!t||!e)return null;let n=t.split(`
|
|
268
268
|
`),s=e.split(`
|
|
269
|
-
`).length;return n.length===0||s===0?null:s===1?
|
|
270
|
-
`),c=
|
|
271
|
-
`),p=
|
|
272
|
-
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function
|
|
273
|
-
`),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
|
|
269
|
+
`).length;return n.length===0||s===0?null:s===1?dS(n,e):pS(n,e,s)}function Kh(t){return Math.max(1,Math.floor(t/iS))}function Vh(t,e){return t<=Math.ceil(e*aS)}function dS(t,e){let n=e.trim(),o=Kh(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=Ca(a.trim(),n);l<r&&(r=l,s={text:a,distance:l,line:i+1})}return s&&o>1&&(s=fS(t,n,s,o)||s,r=s.distance),Vh(r,e.length)?s:null}function fS(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=Ca(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function pS(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=Kh(o),r=null,i=1/0;for(let a=0;a<o;a+=s){let l=t.slice(a,a+n).join(`
|
|
270
|
+
`),c=Ca(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&s>1&&(r=hS(t,e,r,s,n,o)||r,i=r.distance),Vh(i,e.length)?r:null}function hS(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(`
|
|
271
|
+
`),p=Ca(f,e);p<c&&(c=p,u={text:f,distance:p,line:d+1})}return u}Xh.exports={normalizeWhitespace:ou,fuzzyFindText:cS,findMostSimilar:uS}});var im=ee((YP,iu)=>{var Zh=require("fs"),mS=require("path"),{execFileSync:gS}=require("child_process"),Qh=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],yS=/(^|\/)(tests\/.*\.test\.(js|ts|jsx|tsx)|__tests__\/.*\.(js|ts|jsx|tsx))$/i,em=[{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}],bS=/(^|\/)\.env(?:\.[^/]+)?\.(example|sample|template)$/i,tm=[{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 gS("git",t,{cwd:e,encoding:"utf8"})}function wS(t=process.cwd()){return Aa(["rev-parse","--show-toplevel"],t).trim()}function _S(t){let e=mS.join(t,".nex","push-allowlist");return Zh.existsSync(e)?Zh.readFileSync(e,"utf8").split(`
|
|
272
|
+
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function ru(t,e){return e.some(n=>t.includes(n))}function nm(t){return bS.test(t)}function sm(t,e){let n=[];for(let o of t)if(!nm(o))for(let s of tm)s.regex.test(o)&&(ru(o,e)||n.push({category:s.category,location:o,preview:o}));return n}function $S(t){let e=t.split(`
|
|
273
|
+
`),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 om(t,e){let n=[];for(let o of $S(t))if(!yS.test(o.filePath||""))for(let s of em)s.regex.test(o.text)&&(ru(o.raw,e)||ru(o.text,e)||n.push({category:s.category,location:`${o.lineNumber}:${o.raw}`,preview:o.raw}));return n}function kS(t){return Aa(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function xS(t,e){return Aa(["diff",e,...Qh],t)}function SS(t){return Aa(["diff","--cached",...Qh],t)}function rm({repoRoot:t,mode:e,range:n}){let o=_S(t),s=e==="staged"?kS(t):[],r=sm(s,o),i=e==="range"?xS(t,n):SS(t),a=om(i,o);return[...r,...a]}function vS(t){return t.map(e=>` [${e.category}]
|
|
274
274
|
${e.location}`).join(`
|
|
275
|
-
`)}function
|
|
276
|
-
`),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
|
|
277
|
-
`).filter(Boolean),
|
|
278
|
-
`);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(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&n.push({type:"export",name:p,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
|
|
279
|
-
`);for(let w=0;w<g.length;w++){let k=g[w],T=w+1;if(!c.test(k)||o&&f===o&&s===T||
|
|
275
|
+
`)}function ES(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 TS(){let t=ES(process.argv.slice(2)),e=wS(),n=rm({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(vS(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===iu&&TS();iu.exports={SECRET_PATTERNS:em,SENSITIVE_FILE_RULES:tm,scanDiffText:om,scanFileNames:sm,scanRepo:rm,isSafeExampleFile:nm}});var lm=ee((KP,am)=>{var{C:zP}=Et(),{SECRET_PATTERNS:RS}=im(),CS=[{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 AS(t,e){let n=e.split(`
|
|
276
|
+
`),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 RS)l.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${l.category}`,severity:"error"});for(let l of CS)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}}am.exports={runDiagnostics:AS,getMemoryUsage:OS}});var In=ee((VP,_m)=>{var Ws=require("fs").promises,Gt=require("path"),{exec:PS}=require("util").promisify(require("child_process").exec),hs=[],cu=null,Oa=!1,lu=0,MS=6e4;function uu(t){return!(hs.length===0||cu!==t||Date.now()-lu>MS)}async function pm(t){if(!Oa&&!uu(t)){Oa=!0,cu=t;try{try{let{stdout:o}=await PS("rg --files",{cwd:t,timeout:5e3});hs=o.split(`
|
|
277
|
+
`).filter(Boolean),lu=Date.now(),Oa=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await Ws.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(Gt.join(o,i.name),a):e.push(a)}};await n(t,""),hs=e,lu=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Oa=!1}}}function Er(){return hs}function NS(){return cu}function LS(t){return hs.filter(e=>Gt.basename(e)===t)}function IS(t){let e=t.toLowerCase();return hs.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}function hm(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 mm(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=Gt.basename(t).toLowerCase(),l=Gt.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-hm(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 jS(t,{limit:e=10,minScore:n=15}={}){if(!t||hs.length===0)return[];let o=[];for(let s of hs){let r=mm(s,t);r>=n&&o.push({file:s,score:r})}return o.sort((s,r)=>r.score-s.score),o.slice(0,e)}var au=null,cm=0,um=null,gm=12e4,Pa=null,dm=0,fm=null,ym=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function bm(t,e){let n=[],o=t.split(`
|
|
278
|
+
`);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(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&n.push({type:"export",name:p,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 Ma(t){t=t||process.cwd();let e=Gt.join(t,".nex","index","content-index.json"),n={};if(au&&um===t&&Date.now()-cm<gm)return au;try{let i=await Ws.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}let o=Er();(!uu(t)||o.length===0)&&(await pm(t),o=Er());let s={files:{}},r=!1;for(let i of Er()){let a=Gt.extname(i);if(!ym.has(a))continue;let l=Gt.join(t,i);try{let u=(await Ws.stat(l)).mtimeMs;if(n.files[i]&&n.files[i].mtime===u){s.files[i]=n.files[i];continue}let d=await Ws.readFile(l,"utf-8"),f=bm(d,a);s.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=Gt.join(t,".nex","index");await Ws.mkdir(i,{recursive:!0}),await Ws.writeFile(e,JSON.stringify(s),"utf-8")}return au=s,cm=Date.now(),um=t,s}async function DS(t,e,n){let o=await Ma(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 qS(t,e,n){if(!e||!e.startsWith("."))return null;let o=Gt.posix.dirname(t.replace(/\\/g,"/")),s=Gt.posix.normalize(Gt.posix.join(o==="."?"":o,e)),r=[];if(Gt.posix.extname(s))r.push(s);else for(let a of ym)r.push(`${s}${a}`),r.push(Gt.posix.join(s,`index${a}`));for(let a of r)if(n.has(a))return a;return null}async function du(t){if(t=t||process.cwd(),Pa&&fm===t&&Date.now()-dm<gm)return Pa;let e=await Ma(t),n=Er(),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=qS(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 Pa={importsByFile:s,importedByFile:r},dm=Date.now(),fm=t,Pa}async function FS(t,e,n=6){if(!t)return[];let o=await du(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 BS(t,e=4){let n=await du(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 wm(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function US(t,e){let n=wm(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 Ma(e),a=wm(t),l=new RegExp(`\\b${a}\\s*\\(`),c=new RegExp(`\\b${a}\\b`),u=[];for(let d of Object.keys(i.files||{})){let f=d.replace(/\\/g,"/");try{let p=Gt.join(e,f),g=(await Ws.readFile(p,"utf-8")).split(`
|
|
279
|
+
`);for(let w=0;w<g.length;w++){let k=g[w],T=w+1;if(!c.test(k)||o&&f===o&&s===T||US(k,t))continue;let $=(f===o?0:4)+(l.test(k)?3:1);u.push({file:f,line:T,context:k.trim(),score:$})}}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)}_m.exports={refreshIndex:pm,getFileIndex:Er,getIndexedCwd:NS,findFileInIndex:LS,searchIndex:IS,isIndexValid:uu,buildContentIndex:Ma,searchContentIndex:DS,extractDefinitions:bm,buildImportGraph:du,getRelatedFiles:FS,summarizeModuleHubs:BS,findSymbolReferences:WS,smartSearch:jS,scorePathMatch:mm,pathLevenshtein:hm}});var No=ee((XP,Em)=>{var Na=require("fs"),Da=require("path"),qa=require("os"),{execFile:HS}=require("child_process"),{promisify:GS}=require("util"),fu=GS(HS),YS=Da.join(qa.homedir(),".nex","servers.json"),La=Da.join(qa.tmpdir(),"nex-ssh-sockets");function zS(){return Da.join(process.cwd(),".nex","servers.json")}function $m(){let t=o=>{if(!Na.existsSync(o))return{};try{return JSON.parse(Na.readFileSync(o,"utf-8"))}catch{return{}}},e=t(YS),n=t(zS());return{...e,...n}}function KS(t){let e=$m();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(){Na.existsSync(La)||Na.mkdirSync(La,{recursive:!0})}function km(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,qa.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=Da.join(La,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function xm(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,qa.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Ia(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=km(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await fu("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:Fa(l,t)}}}async function XS(t,e,n,{timeout:o=12e4}={}){let s=xm(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:a}=await fu("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(Fa(a,t)||a)}}async function JS(t,e,n,{timeout:o=12e4}={}){let s=xm(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:a}=await fu("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(Fa(a,t)||a)}}function Fa(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
|
|
280
280
|
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}
|
|
281
281
|
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}
|
|
282
282
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
283
283
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
284
284
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
285
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
286
|
-
`).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return
|
|
285
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function ZS(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 ja=new Map,QS=12e4;async function Sm(t,e,{force:n=!1}={}){let s=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=ja.get(s);if(!n&&r&&Date.now()-r.time<QS)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 Ia(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let c=e.endsWith("/")?e:e+"/",u=a.split(`
|
|
286
|
+
`).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return ja.set(s,{files:u,time:Date.now()}),u}async function vm(t,e,n,{limit:o=5,minScore:s=15}={}){let r=await Sm(t,e);if(r.length===0)return[];let{scorePathMatch:i}=In(),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 ev(t,e,n){if(!n)return{fixedPath:null,message:""};let o=n.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await Ia(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await Ia(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let s=await vm(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:
|
|
287
287
|
${s.map(a=>` - ${a.file}`).join(`
|
|
288
|
-
`)}`}}return{fixedPath:null,message:""}}function
|
|
289
|
-
`,"utf-8")}
|
|
288
|
+
`)}`}}return{fixedPath:null,message:""}}function tv(t){t?ja.delete(t):ja.clear()}Em.exports={loadServerProfiles:$m,resolveProfile:KS,buildSSHArgs:km,sshExec:Ia,scpUpload:XS,scpDownload:JS,enrichSSHError:Fa,formatProfile:ZS,SSH_SOCKET_DIR:La,getRemoteIndex:Sm,remoteSmartSearch:vm,remoteAutoFixPath:ev,clearRemoteIndex:tv}});var Cm=ee((JP,Rm)=>{var Tr=require("fs"),pu=require("path"),nv=pu.join(".nex","deploy.json");function hu(){return pu.join(process.cwd(),nv)}function Tm(){let t=hu();if(!Tr.existsSync(t))return{};try{return JSON.parse(Tr.readFileSync(t,"utf-8"))}catch{return{}}}function sv(t){let e=Tm();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 ov(t){let e=pu.join(process.cwd(),".nex");Tr.existsSync(e)||Tr.mkdirSync(e,{recursive:!0}),Tr.writeFileSync(hu(),JSON.stringify(t,null,2)+`
|
|
289
|
+
`,"utf-8")}Rm.exports={loadDeployConfigs:Tm,resolveDeployConfig:sv,saveDeployConfigs:ov,getDeployConfigPath:hu}});var Or=ee((ZP,Pm)=>{var{getActiveModel:rv,getActiveProviderName:iv}=Tt(),Rr={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},Cr={"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"},Ar={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},jn={};function Om(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(jn=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{jn={}}}Om();function mu(){let e=rv()?.id,n=iv();return e&&jn[e]?jn[e]:n&&jn[`${n}:*`]?jn[`${n}:*`]:e&&Cr[e]?Cr[e]:n&&Ar[n]?Ar[n]:"full"}var av=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"]),Am={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function lv(t,e){return t&&(av.has(t)||t.startsWith("claude-"))?"strict":e&&Am[e]?Am[e]:"fuzzy"}function cv(t,e){return t&&jn[t]?jn[t]:e&&jn[`${e}:*`]?jn[`${e}:*`]:t&&Cr[t]?Cr[t]:e&&Ar[e]?Ar[e]:"full"}function uv(t,e){let n=e||mu();if(n==="full"||!Rr[n])return t;let o=new Set(Rr[n]);return t.filter(s=>o.has(s.function.name))}function dv(){let t=mu(),e=Rr[t]?Rr[t].length:"all";return{tier:t,toolCount:e}}Pm.exports={filterToolsForModel:uv,getActiveTier:mu,getModelTier:cv,getEditMode:lv,getTierInfo:dv,TIERS:Rr,MODEL_TIERS:Cr,PROVIDER_DEFAULT_TIER:Ar,loadConfigOverrides:Om}});var ts=ee((QP,Im)=>{var gu=null,es=null,Pr=null,yu=Symbol.for("nex-code.browserExitCleanup"),Mm=`Playwright is not installed. Install with:
|
|
290
290
|
npm install playwright && npx playwright install chromium
|
|
291
|
-
Then restart nex-code.`;function
|
|
292
|
-
...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function pv(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await qa()).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 hv(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await qa()).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 mv(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 qa()).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()}}Lm.exports={isPlaywrightAvailable:Mm,browserNavigate:fv,browserScreenshot:pv,browserClick:hv,browserFill:mv,closeBrowser:dv,INSTALL_MSG:Pm}});var gu=ee((QP,jm)=>{"use strict";var gv=require("util"),Im=require("stream"),xn=jm.exports=function(){Im.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};gv.inherits(xn,Im);xn.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))};xn.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};xn.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()))};xn.prototype.destroySoon=xn.prototype.end;xn.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};xn.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};xn.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))};xn.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)};xn.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 bu=ee(yu=>{"use strict";var ms=[{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]}];yu.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<ms.length;a++){let l=ms[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};yu.getInterlaceIterator=function(t){return function(e,n,o){let s=e%ms[o].x.length,r=(e-s)/ms[o].x.length*8+ms[o].x[s],i=n%ms[o].y.length,a=(n-i)/ms[o].y.length*8+ms[o].y[i];return r*4+a*t*4}}});var wu=ee((tM,Dm)=>{"use strict";Dm.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 _u=ee((nM,Fm)=>{"use strict";var yv=bu(),bv=wu();function qm(t,e,n){let o=t*e;return n!==8&&(o=Math.ceil(o/(8/n))),o}var Lo=Fm.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=yv.getImagePasses(n,o);for(let l=0;l<a.length;l++)this._images.push({byteWidth:qm(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:qm(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Lo.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Lo.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}};Lo.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}};Lo.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}};Lo.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=bv(c,l,u);e[i]=a+d}};Lo.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 Wm=ee((sM,Um)=>{"use strict";var wv=require("util"),Bm=gu(),_v=_u(),$v=Um.exports=function(t){Bm.call(this);let e=[],n=this;this._filter=new _v(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};wv.inherits($v,Bm)});var Io=ee((oM,Hm)=>{"use strict";Hm.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 xu=ee((rM,Gm)=>{"use strict";var $u=[];(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;$u[t]=e}})();var ku=Gm.exports=function(){this._crc=-1};ku.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=$u[(this._crc^t[e])&255]^this._crc>>>8;return!0};ku.prototype.crc32=function(){return this._crc^-1};ku.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=$u[(e^t[n])&255]^e>>>8;return e^-1}});var Su=ee((iM,Ym)=>{"use strict";var _t=Io(),kv=xu(),kt=Ym.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[_t.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[_t.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[_t.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[_t.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[_t.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[_t.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(){}};kt.prototype.start=function(){this.read(_t.PNG_SIGNATURE.length,this._parseSignature.bind(this))};kt.prototype._parseSignature=function(t){let e=_t.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))};kt.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!==_t.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new kv,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))};kt.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};kt.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};kt.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))};kt.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};kt.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 _t.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=_t.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:o,interlace:!!a,palette:!!(s&_t.COLORTYPE_PALETTE),color:!!(s&_t.COLORTYPE_COLOR),alpha:!!(s&_t.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};kt.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};kt.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()};kt.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};kt.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===_t.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===_t.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===_t.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};kt.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};kt.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/_t.GAMMA_DIVISION),this._handleChunkEnd()};kt.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};kt.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===_t.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()};kt.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};kt.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var vu=ee(Km=>{"use strict";var zm=bu(),xv=[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]}],Sv=[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 vv(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,p;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,p=r>>4,n.push(p,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,n.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,n.push(p,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);xv[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);Sv[o](e,d,f,r)}s.resetAfterLine()}}Km.dataToBitMap=function(t,e){let n=e.width,o=e.height,s=e.depth,r=e.bpp,i=e.interlace,a;s!==8&&(a=vv(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=zm.getImagePasses(n,o),f=zm.getInterlaceIterator(n,o);else{let p=0;f=function(){let m=p;return p+=4,m},d=[{width:n,height:o}]}for(let p=0;p<d.length;p++)s===8?u=Ev(d[p],l,f,r,t,u):Tv(d[p],l,f,r,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Eu=ee((lM,Vm)=>{"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 Cv(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}}Vm.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&&Cv(t,c,s,r,a),o!==8&&!n&&(o===16&&(c=Buffer.alloc(s*r*4)),Av(t,c,s,r,o))),c}});var Zm=ee((cM,Jm)=>{"use strict";var Ov=require("util"),Tu=require("zlib"),Xm=gu(),Pv=Wm(),Mv=Su(),Nv=vu(),Lv=Eu(),Dn=Jm.exports=function(t){Xm.call(this),this._parser=new Mv(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()};Ov.inherits(Dn,Xm);Dn.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};Dn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Tu.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,Tu.Z_MIN_CHUNK);this._inflate=Tu.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)};Dn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Pv(this._bitmapInfo)};Dn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Dn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Dn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Dn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Dn.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Dn.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Nv.dataToBitMap(t,this._bitmapInfo);e=Lv(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var eg=ee((uM,Qm)=>{"use strict";var dn=Io();Qm.exports=function(t,e,n,o){let s=[dn.COLORTYPE_COLOR_ALPHA,dn.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=dn.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let l=dn.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 p(){let m,g,w,k=i;switch(o.inputColorType){case dn.COLORTYPE_COLOR_ALPHA:k=r[u+3],m=r[u],g=r[u+1],w=r[u+2];break;case dn.COLORTYPE_COLOR:m=r[u],g=r[u+1],w=r[u+2];break;case dn.COLORTYPE_ALPHA:k=r[u+1],m=r[u],g=m,w=m;break;case dn.COLORTYPE_GRAYSCALE:m=r[u],g=m,w=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),w=Math.min(Math.max(Math.round((1-k)*f.blue+k*w),0),i))),{red:m,green:g,blue:w,alpha:k}}for(let m=0;m<n;m++)for(let g=0;g<e;g++){let w=p(r,u);switch(o.colorType){case dn.COLORTYPE_COLOR_ALPHA:case dn.COLORTYPE_COLOR:o.bitDepth===8?(c[d]=w.red,c[d+1]=w.green,c[d+2]=w.blue,s&&(c[d+3]=w.alpha)):(c.writeUInt16BE(w.red,d),c.writeUInt16BE(w.green,d+2),c.writeUInt16BE(w.blue,d+4),s&&c.writeUInt16BE(w.alpha,d+6));break;case dn.COLORTYPE_ALPHA:case dn.COLORTYPE_GRAYSCALE:{let k=(w.red+w.green+w.blue)/3;o.bitDepth===8?(c[d]=k,s&&(c[d+1]=w.alpha)):(c.writeUInt16BE(k,d),s&&c.writeUInt16BE(w.alpha,d+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}u+=a,d+=l}return c}});var sg=ee((dM,ng)=>{"use strict";var tg=wu();function Iv(t,e,n,o,s){for(let r=0;r<n;r++)o[s+r]=t[e+r]}function jv(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++)o+=Math.abs(t[r]);return o}function Dv(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 qv(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 Fv(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 Uv(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 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=t[e+r]-(i+a>>1);s+=Math.abs(l)}return s}function Hv(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]-tg(a,l,c);o[s+i]=u}}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=e>0?t[e+r-n]:0,l=e>0&&r>=o?t[e+r-(n+o)]:0,c=t[e+r]-tg(i,a,l);s+=Math.abs(c)}return s}var Yv={0:Iv,1:Dv,2:Fv,3:Uv,4:Hv},zv={0:jv,1:qv,2:Bv,3:Wv,4:Gv};ng.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 p=0;p<r.length;p++){let m=zv[r[p]](t,l,i,s);m<f&&(u=r[p],f=m)}}c[a]=u,a++,Yv[u](t,l,i,c,a,s),a+=i,l+=i}return c}});var Ru=ee((fM,og)=>{"use strict";var Mt=Io(),Kv=xu(),Vv=eg(),Xv=sg(),Jv=require("zlib"),gs=og.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||Jv.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:Mt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:Mt.COLORTYPE_COLOR_ALPHA,[Mt.COLORTYPE_GRAYSCALE,Mt.COLORTYPE_COLOR,Mt.COLORTYPE_COLOR_ALPHA,Mt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([Mt.COLORTYPE_GRAYSCALE,Mt.COLORTYPE_COLOR,Mt.COLORTYPE_COLOR_ALPHA,Mt.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")};gs.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};gs.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};gs.prototype.filterData=function(t,e,n){let o=Vv(t,e,n,this._options),s=Mt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Xv(o,e,n,this._options,s)};gs.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};gs.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Mt.GAMMA_DIVISION),0),this._packChunk(Mt.TYPE_gAMA,e)};gs.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(Mt.TYPE_IHDR,n)};gs.prototype.packIDAT=function(t){return this._packChunk(Mt.TYPE_IDAT,t)};gs.prototype.packIEND=function(){return this._packChunk(Mt.TYPE_IEND,null)}});var lg=ee((pM,ag)=>{"use strict";var Zv=require("util"),rg=require("stream"),Qv=Io(),eE=Ru(),ig=ag.exports=function(t){rg.call(this);let e=t||{};this._packer=new eE(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Zv.inherits(ig,rg);ig.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(Qv.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 hg=ee((Pr,pg)=>{"use strict";var cg=require("assert").ok,jo=require("zlib"),tE=require("util"),ug=require("buffer").kMaxLength;function Hs(t){if(!(this instanceof Hs))return new Hs(t);t&&t.chunkSize<jo.Z_MIN_CHUNK&&(t.chunkSize=jo.Z_MIN_CHUNK),jo.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 nE(t){return new Hs(t)}function dg(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Hs.prototype._processChunk=function(t,e,n){if(typeof n=="function")return jo.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 w=r-g;if(cg(w>=0,"have should not go down"),w>0){let k=o._buffer.slice(o._offset,o._offset+w);if(o._offset+=w,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}cg(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>=ug)throw dg(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+ug.toString(16)+" bytes");let p=Buffer.concat(l,c);return dg(this),p};tE.inherits(Hs,jo.Inflate);function sE(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=jo.Z_FINISH),t._processChunk(e,n)}function fg(t,e){return sE(new Hs(e),t)}pg.exports=Pr=fg;Pr.Inflate=Hs;Pr.createInflate=nE;Pr.inflateSync=fg});var Cu=ee((hM,gg)=>{"use strict";var mg=gg.exports=function(t){this._buffer=t,this._reads=[]};mg.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};mg.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 bg=ee(yg=>{"use strict";var oE=Cu(),rE=_u();yg.process=function(t,e){let n=[],o=new oE(t);return new rE(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var kg=ee((gM,$g)=>{"use strict";var wg=!0,_g=require("zlib"),iE=hg();_g.deflateSync||(wg=!1);var aE=Cu(),lE=bg(),cE=Su(),uE=vu(),dE=Eu();$g.exports=function(t,e){if(!wg)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(R){n=R}let s;function r(R){s=R}function i(R){s.transColor=R}function a(R){s.palette=R}function l(){s.alpha=!0}let c;function u(R){c=R}let d=[];function f(R){d.push(R)}let p=new aE(t);if(new cE(e,{read:p.read.bind(p),error:o,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),p.process(),n)throw n;let g=Buffer.concat(d);d.length=0;let w;if(s.interlace)w=_g.inflateSync(g);else{let O=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;w=iE(g,{chunkSize:O,maxLength:O})}if(g=null,!w||!w.length)throw new Error("bad png - invalid inflate data response");let k=lE.process(w,s);g=null;let T=uE.dataToBitMap(k,s);k=null;let $=dE(T,s,e.skipRescale);return s.data=$,s.gamma=c||0,s}});var Eg=ee((yM,vg)=>{"use strict";var xg=!0,Sg=require("zlib");Sg.deflateSync||(xg=!1);var fE=Io(),pE=Ru();vg.exports=function(t,e){if(!xg)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 pE(n),s=[];s.push(Buffer.from(fE.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=Sg.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 Tg=ee(Au=>{"use strict";var hE=kg(),mE=Eg();Au.read=function(t,e){return hE(t,e||{})};Au.write=function(t,e){return mE(t,e)}});var Ag=ee(Cg=>{"use strict";var gE=require("util"),Rg=require("stream"),yE=Zm(),bE=lg(),wE=Tg(),Dt=Cg.PNG=function(t){Rg.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 yE(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 bE(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"))};gE.inherits(Dt,Rg);Dt.sync=wE;Dt.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)};Dt.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};Dt.prototype.write=function(t){return this._parser.write(t),!0};Dt.prototype.end=function(t){this._parser.end(t)};Dt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Dt.prototype._gamma=function(t){this.gamma=t};Dt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};Dt.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)};Dt.prototype.bitblt=function(t,e,n,o,s,r,i){return Dt.bitblt(this,t,e,n,o,s,r,i),this};Dt.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}};Dt.prototype.adjustGamma=function(){Dt.adjustGamma(this)}});var Lg={};b_(Lg,{default:()=>Mg});function Mg(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(!Ou(t)||!Ou(e)||n&&!Ou(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 p=o*s,m=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),w=!0;for(let ne=0;ne<p;ne++)if(m[ne]!==g[ne]){w=!1;break}if(w){if(n&&!f)for(let ne=0;ne<p;ne++)Pg(t,4*ne,a,n);return 0}let k=35215*i*i,[T,$,R]=l,[O,N,z]=c,[K,V,ie]=d||c,J=0;for(let ne=0;ne<s;ne++)for(let Ke=0;Ke<o;Ke++){let ve=ne*o+Ke,H=ve*4,oe=m[ve]===g[ve]?0:Ng(t,e,H,H,!1);if(Math.abs(oe)>k){let et=Og(t,Ke,ne,o,s,m,g)||Og(e,Ke,ne,o,s,g,m);!u&&et?n&&!f&&Ba(n,H,T,$,R):(n&&(oe<0?Ba(n,H,K,V,ie):Ba(n,H,O,N,z)),J++)}else n&&!f&&Pg(t,H,a,n)}return J}function Ou(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Og(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,p=0,m=0,g=0,w=0,k=0,T=0;for(let $=a;$<=c;$++)for(let R=l;R<=u;R++){if($===e&&R===n)continue;let O=Ng(t,t,d*4,(R*o+$)*4,!0);if(O===0){if(f++,f>2)return!1}else O<p?(p=O,g=$,w=R):O>m&&(m=O,k=$,T=R)}return p===0||m===0?!1:Fa(r,g,w,o,s)&&Fa(i,g,w,o,s)||Fa(r,k,T,o,s)&&Fa(i,k,T,o,s)}function Fa(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],p=r-c,m=i-u,g=a-d,w=l-f;if(!p&&!m&&!g&&!w)return 0;if(l<255||f<255){let O=48+159*(n%2),N=48+159*((n/1.618033988749895|0)%2),z=48+159*((n/2.618033988749895|0)%2);p=(r*l-c*f-O*w)/255,m=(i*l-u*f-N*w)/255,g=(a*l-d*f-z*w)/255}let k=p*.29889531+m*.58662247+g*.11448223;if(s)return k;let T=p*.59597799-m*.2741761-g*.32180189,$=p*.21147017-m*.52261711+g*.31114694,R=.5053*k*k+.299*T*T+.1957*$*$;return k>0?-R:R}function Ba(t,e,n,o,s){t[e+0]=n,t[e+1]=o,t[e+2]=s,t[e+3]=255}function Pg(t,e,n,o){let s=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;Ba(o,e,s,s,s)}var Ig=y_(()=>{});var Gs=ee((_M,Bg)=>{var ns=require("fs"),_E=require("path"),$E=require("os"),kE="nex-visual-";function Dg(t){return _E.join($E.tmpdir(),`${kE}${Date.now()}-${t}`)}var Pu=null;function Ua(){return Pu||(Pu=Ag().PNG),Pu}var Mu=null;function xE(){if(!Mu){let t=(Ig(),__(Lg));Mu=t.default||t}return Mu}function Iu(t,e,{threshold:n=.1}={}){let o=Ua(),s=xE(),r=o.sync.read(ns.readFileSync(t)),i=o.sync.read(ns.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=jg(r,a,l),u=jg(i,a,l),d=new o({width:a,height:l}),f=s(c,u,d.data,a,l,{threshold:n,includeAA:!1}),p=a*l,m=(f/p*100).toFixed(1),g=SE(d.data,a,l,3,3),w=Dg("diff.png");return ns.writeFileSync(w,o.sync.write(d),{mode:384}),{diffPath:w,diffPercent:parseFloat(m),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function jg(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 SE(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,p=u*i,m=c*a,g=Math.min(p+i,e),w=Math.min(m+a,n);for(let k=m;k<w;k++)for(let T=p;T<g;T++){f++;let $=(k*e+T)*4;(t[$]>0||t[$+1]>0)&&d++}if(d>0){let k=(d/f*100).toFixed(1),T=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:T,changedPercent:parseFloat(k),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var qg=[{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 vE(t,{viewports:e=qg,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=ts(),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 Fg(t,e=[]){let n=Ua(),o=n.sync.read(ns.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&&Lu(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&&Lu(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(CE(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Lu(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=Dg("annotated.png");ns.writeFileSync(s,n.sync.write(o),{mode:384});let r=ns.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 qn(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++)qn(t,e+l,n+a,r),qn(t,e+l,n+s-1-a,r);for(let l=0;l<s;l++)qn(t,e+a,n+l,r),qn(t,e+o-1-a,n+l,r)}}function Nu(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,p=n;for(;;){let m=Math.floor(i/2);for(let w=-m;w<=m;w++)for(let k=-m;k<=m;k++)qn(t,f+w,p+k,r);if(f===o&&p===s)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,p+=u)}}function RE(t,e,n,o,s,r,i=3){Nu(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;Nu(t,o,s,Math.round(o+l*Math.cos(c)),Math.round(s+l*Math.sin(c)),r,i),Nu(t,o,s,Math.round(o+l*Math.cos(u)),Math.round(s+l*Math.sin(u)),r,i)}function CE(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));qn(t,u,d,s)}}}function Lu(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++)qn(t,e+c,n+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)qn(t,e+l,n+a-1,s),qn(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++)qn(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}=ts(),l=OE("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 ME(()=>d,3e5),d=!1,u++,await PE(o);let p=await a(t,{width:s,height:r,timeout:i}),m=null;try{m=Iu(c.path,p.path)}catch{}c=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function OE(t){try{return require(t)}catch{return null}}function PE(t){return new Promise(e=>setTimeout(e,t))}function ME(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 NE(t,{sampleRate:e=4}={}){let o=Ua().sync.read(ns.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],p=o.data[d+1],m=o.data[d+2];if(o.data[d+3]<128)continue;let w=Math.round(f/8)*8,k=Math.round(p/8)*8,T=Math.round(m/8)*8,$=`${w},${k},${T}`;s.set($,(s.get($)||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,p]=c.split(",").map(Number);return{hex:LE(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:IE(d,f,p)}}),l=jE(o);return{colors:a,spacing:l,dimensions:{width:o.width,height:o.height},imagePath:t}}function LE(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function IE(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 jE(t){let e=[],n=!1,o=0,s=DE(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 DE(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 qE(t,e,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=ts(),c=Ua().sync.read(ns.readFileSync(e)),u=n||c.width,d=o||c.height,f=await a(t,{width:u,height:d,fullPage:s,timeout:i}),p=Iu(e,f.path,{threshold:r}),m=Fg(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,w)=>{let $=Math.ceil(p.width/3),R=Math.ceil(p.height/3),O=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],N=0,z=0;for(let K=0;K<3;K++)for(let V=0;V<3;V++)O[K][V]===g.name&&(N=V,z=K);return{type:"box",x:N*$+2,y:z*R+2,width:$-4,height:R-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:p.diffPath,annotatedPath:m.path,diffPercent:p.diffPercent,changedPixels:p.changedPixels,totalPixels:p.totalPixels,regions:p.regionSummary,liveBase64:f.base64,diffBase64:ns.readFileSync(p.diffPath).toString("base64"),annotatedBase64:m.base64}}Bg.exports={pixelDiff:Iu,responsiveSweep:vE,annotateImage:Fg,visualWatch:AE,extractDesignTokens:NE,designCompare:qE,DEFAULT_VIEWPORTS:qg}});var ju=ee(($M,Ug)=>{var{C:at}=Et(),Nr="",qt=[],Mr=0,Ys=null;function FE(t){Ys=t}function BE(t,e){Nr=t,qt=[],Mr=0;for(let o of e){Mr++;let s=`t${Mr}`;qt.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${Mr}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=qt.map(o=>({...o}));return Ys&&Ys("create",{name:t,tasks:n}),n}function UE(t,e,n){let o=qt.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),Ys&&Ys("update",{id:t,status:e,result:n}),{...o}):null}function WE(){return{name:Nr,tasks:qt.map(t=>({...t}))}}function HE(){Nr="",qt=[],Mr=0,Ys&&Ys("clear",{})}function GE(){return qt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=qt.find(o=>o.id===e);return n&&n.status==="done"}))}function YE(){if(qt.length===0)return`${at.dim}No active tasks${at.reset}`;let t=[];Nr&&(t.push(` ${at.bold}${at.cyan}Tasks: ${Nr}${at.reset}`),t.push(` ${at.dim}${"\u2500".repeat(40)}${at.reset}`));for(let s of qt){let r,i;switch(s.status){case"done":r="\u2713",i=at.green;break;case"in_progress":r="\u2192",i=at.cyan;break;case"failed":r="\u2717",i=at.red;break;default:r="\xB7",i=at.dim}let a=s.dependsOn.length>0?` ${at.dim}(after: ${s.dependsOn.join(", ")})${at.reset}`:"",l=`[${s.status}]`,c=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${at.reset} ${at.bold}${s.id}${at.reset} ${c.padEnd(40)} ${i}${l}${at.reset}${a}`),s.result&&s.status==="done"){let u=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${at.dim}\u2192 ${u}${at.reset}`)}}let e=qt.filter(s=>s.status==="done").length,n=qt.filter(s=>s.status==="failed").length,o=qt.length;return t.push(` ${at.dim}${"\u2500".repeat(40)}${at.reset}`),t.push(` ${at.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${at.reset}`),t.join(`
|
|
293
|
-
`)}function
|
|
291
|
+
Then restart nex-code.`;function Nm(){if(Pr!==null)return Pr;try{require("playwright"),Pr=!0}catch{Pr=!1}return Pr}async function Ba(){if(!Nm())throw new Error(Mm);return gu||(gu=require("playwright")),(!es||!es.isConnected())&&(es=await gu.chromium.launch({headless:!0})),es}async function fv(){if(es){try{await es.close()}catch(t){console.error("closeBrowser failed:",t.message)}es=null}}globalThis[yu]&&process.off("exit",globalThis[yu]);var Lm=()=>{if(es)try{es.close()}catch(t){console.error("Error closing browser on exit:",t.message)}};globalThis[yu]=Lm;process.on("exit",Lm);async function pv(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?`
|
|
292
|
+
...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function hv(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 mv(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 gv(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()}}Im.exports={isPlaywrightAvailable:Nm,browserNavigate:pv,browserScreenshot:hv,browserClick:mv,browserFill:gv,closeBrowser:fv,INSTALL_MSG:Mm}});var bu=ee((eM,Dm)=>{"use strict";var yv=require("util"),jm=require("stream"),vn=Dm.exports=function(){jm.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};yv.inherits(vn,jm);vn.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))};vn.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};vn.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()))};vn.prototype.destroySoon=vn.prototype.end;vn.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};vn.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};vn.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))};vn.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)};vn.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 _u=ee(wu=>{"use strict";var ms=[{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]}];wu.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<ms.length;a++){let l=ms[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};wu.getInterlaceIterator=function(t){return function(e,n,o){let s=e%ms[o].x.length,r=(e-s)/ms[o].x.length*8+ms[o].x[s],i=n%ms[o].y.length,a=(n-i)/ms[o].y.length*8+ms[o].y[i];return r*4+a*t*4}}});var $u=ee((nM,qm)=>{"use strict";qm.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 ku=ee((sM,Bm)=>{"use strict";var bv=_u(),wv=$u();function Fm(t,e,n){let o=t*e;return n!==8&&(o=Math.ceil(o/(8/n))),o}var Lo=Bm.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=bv.getImagePasses(n,o);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Fm(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Fm(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Lo.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Lo.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}};Lo.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}};Lo.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}};Lo.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=wv(c,l,u);e[i]=a+d}};Lo.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 Hm=ee((oM,Wm)=>{"use strict";var _v=require("util"),Um=bu(),$v=ku(),kv=Wm.exports=function(t){Um.call(this);let e=[],n=this;this._filter=new $v(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};_v.inherits(kv,Um)});var Io=ee((rM,Gm)=>{"use strict";Gm.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 vu=ee((iM,Ym)=>{"use strict";var xu=[];(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;xu[t]=e}})();var Su=Ym.exports=function(){this._crc=-1};Su.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=xu[(this._crc^t[e])&255]^this._crc>>>8;return!0};Su.prototype.crc32=function(){return this._crc^-1};Su.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=xu[(e^t[n])&255]^e>>>8;return e^-1}});var Eu=ee((aM,zm)=>{"use strict";var _t=Io(),xv=vu(),kt=zm.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[_t.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[_t.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[_t.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[_t.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[_t.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[_t.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(){}};kt.prototype.start=function(){this.read(_t.PNG_SIGNATURE.length,this._parseSignature.bind(this))};kt.prototype._parseSignature=function(t){let e=_t.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))};kt.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!==_t.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new xv,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))};kt.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};kt.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};kt.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))};kt.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};kt.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 _t.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=_t.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:o,interlace:!!a,palette:!!(s&_t.COLORTYPE_PALETTE),color:!!(s&_t.COLORTYPE_COLOR),alpha:!!(s&_t.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};kt.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};kt.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()};kt.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};kt.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===_t.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===_t.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===_t.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};kt.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};kt.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/_t.GAMMA_DIVISION),this._handleChunkEnd()};kt.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};kt.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===_t.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()};kt.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};kt.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Tu=ee(Vm=>{"use strict";var Km=_u(),Sv=[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]}],vv=[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 Ev(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,p;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,p=r>>4,n.push(p,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,n.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,n.push(p,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 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=n(u,c,l);Sv[o](e,s,d,r),r+=o}return r}function Rv(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);vv[o](e,d,f,r)}s.resetAfterLine()}}Vm.dataToBitMap=function(t,e){let n=e.width,o=e.height,s=e.depth,r=e.bpp,i=e.interlace,a;s!==8&&(a=Ev(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=Km.getImagePasses(n,o),f=Km.getInterlaceIterator(n,o);else{let p=0;f=function(){let m=p;return p+=4,m},d=[{width:n,height:o}]}for(let p=0;p<d.length;p++)s===8?u=Tv(d[p],l,f,r,t,u):Rv(d[p],l,f,r,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Ru=ee((cM,Xm)=>{"use strict";function Cv(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 Av(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}}Xm.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?Cv(t,c,s,r,l):(a&&Av(t,c,s,r,a),o!==8&&!n&&(o===16&&(c=Buffer.alloc(s*r*4)),Ov(t,c,s,r,o))),c}});var Qm=ee((uM,Zm)=>{"use strict";var Pv=require("util"),Cu=require("zlib"),Jm=bu(),Mv=Hm(),Nv=Eu(),Lv=Tu(),Iv=Ru(),Dn=Zm.exports=function(t){Jm.call(this),this._parser=new Nv(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()};Pv.inherits(Dn,Jm);Dn.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};Dn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Cu.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,Cu.Z_MIN_CHUNK);this._inflate=Cu.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)};Dn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Mv(this._bitmapInfo)};Dn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Dn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Dn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Dn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Dn.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Dn.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Lv.dataToBitMap(t,this._bitmapInfo);e=Iv(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var tg=ee((dM,eg)=>{"use strict";var pn=Io();eg.exports=function(t,e,n,o){let s=[pn.COLORTYPE_COLOR_ALPHA,pn.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=pn.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let l=pn.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 p(){let m,g,w,k=i;switch(o.inputColorType){case pn.COLORTYPE_COLOR_ALPHA:k=r[u+3],m=r[u],g=r[u+1],w=r[u+2];break;case pn.COLORTYPE_COLOR:m=r[u],g=r[u+1],w=r[u+2];break;case pn.COLORTYPE_ALPHA:k=r[u+1],m=r[u],g=m,w=m;break;case pn.COLORTYPE_GRAYSCALE:m=r[u],g=m,w=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),w=Math.min(Math.max(Math.round((1-k)*f.blue+k*w),0),i))),{red:m,green:g,blue:w,alpha:k}}for(let m=0;m<n;m++)for(let g=0;g<e;g++){let w=p(r,u);switch(o.colorType){case pn.COLORTYPE_COLOR_ALPHA:case pn.COLORTYPE_COLOR:o.bitDepth===8?(c[d]=w.red,c[d+1]=w.green,c[d+2]=w.blue,s&&(c[d+3]=w.alpha)):(c.writeUInt16BE(w.red,d),c.writeUInt16BE(w.green,d+2),c.writeUInt16BE(w.blue,d+4),s&&c.writeUInt16BE(w.alpha,d+6));break;case pn.COLORTYPE_ALPHA:case pn.COLORTYPE_GRAYSCALE:{let k=(w.red+w.green+w.blue)/3;o.bitDepth===8?(c[d]=k,s&&(c[d+1]=w.alpha)):(c.writeUInt16BE(k,d),s&&c.writeUInt16BE(w.alpha,d+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}u+=a,d+=l}return c}});var og=ee((fM,sg)=>{"use strict";var ng=$u();function jv(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 qv(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 Fv(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 Bv(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 Uv(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 Hv(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 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=e>0&&i>=r?t[e+i-(n+r)]:0,u=t[e+i]-ng(a,l,c);o[s+i]=u}}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=e>0&&r>=o?t[e+r-(n+o)]:0,c=t[e+r]-ng(i,a,l);s+=Math.abs(c)}return s}var zv={0:jv,1:qv,2:Bv,3:Wv,4:Gv},Kv={0:Dv,1:Fv,2:Uv,3:Hv,4:Yv};sg.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 p=0;p<r.length;p++){let m=Kv[r[p]](t,l,i,s);m<f&&(u=r[p],f=m)}}c[a]=u,a++,zv[u](t,l,i,c,a,s),a+=i,l+=i}return c}});var Au=ee((pM,rg)=>{"use strict";var Mt=Io(),Vv=vu(),Xv=tg(),Jv=og(),Zv=require("zlib"),gs=rg.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||Zv.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:Mt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:Mt.COLORTYPE_COLOR_ALPHA,[Mt.COLORTYPE_GRAYSCALE,Mt.COLORTYPE_COLOR,Mt.COLORTYPE_COLOR_ALPHA,Mt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([Mt.COLORTYPE_GRAYSCALE,Mt.COLORTYPE_COLOR,Mt.COLORTYPE_COLOR_ALPHA,Mt.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")};gs.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};gs.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};gs.prototype.filterData=function(t,e,n){let o=Xv(t,e,n,this._options),s=Mt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Jv(o,e,n,this._options,s)};gs.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};gs.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Mt.GAMMA_DIVISION),0),this._packChunk(Mt.TYPE_gAMA,e)};gs.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(Mt.TYPE_IHDR,n)};gs.prototype.packIDAT=function(t){return this._packChunk(Mt.TYPE_IDAT,t)};gs.prototype.packIEND=function(){return this._packChunk(Mt.TYPE_IEND,null)}});var cg=ee((hM,lg)=>{"use strict";var Qv=require("util"),ig=require("stream"),eE=Io(),tE=Au(),ag=lg.exports=function(t){ig.call(this);let e=t||{};this._packer=new tE(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Qv.inherits(ag,ig);ag.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(eE.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 mg=ee((Mr,hg)=>{"use strict";var ug=require("assert").ok,jo=require("zlib"),nE=require("util"),dg=require("buffer").kMaxLength;function Hs(t){if(!(this instanceof Hs))return new Hs(t);t&&t.chunkSize<jo.Z_MIN_CHUNK&&(t.chunkSize=jo.Z_MIN_CHUNK),jo.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 sE(t){return new Hs(t)}function fg(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Hs.prototype._processChunk=function(t,e,n){if(typeof n=="function")return jo.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 w=r-g;if(ug(w>=0,"have should not go down"),w>0){let k=o._buffer.slice(o._offset,o._offset+w);if(o._offset+=w,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}ug(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>=dg)throw fg(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+dg.toString(16)+" bytes");let p=Buffer.concat(l,c);return fg(this),p};nE.inherits(Hs,jo.Inflate);function oE(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=jo.Z_FINISH),t._processChunk(e,n)}function pg(t,e){return oE(new Hs(e),t)}hg.exports=Mr=pg;Mr.Inflate=Hs;Mr.createInflate=sE;Mr.inflateSync=pg});var Ou=ee((mM,yg)=>{"use strict";var gg=yg.exports=function(t){this._buffer=t,this._reads=[]};gg.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};gg.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 wg=ee(bg=>{"use strict";var rE=Ou(),iE=ku();bg.process=function(t,e){let n=[],o=new rE(t);return new iE(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var xg=ee((yM,kg)=>{"use strict";var _g=!0,$g=require("zlib"),aE=mg();$g.deflateSync||(_g=!1);var lE=Ou(),cE=wg(),uE=Eu(),dE=Tu(),fE=Ru();kg.exports=function(t,e){if(!_g)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(R){n=R}let s;function r(R){s=R}function i(R){s.transColor=R}function a(R){s.palette=R}function l(){s.alpha=!0}let c;function u(R){c=R}let d=[];function f(R){d.push(R)}let p=new lE(t);if(new uE(e,{read:p.read.bind(p),error:o,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),p.process(),n)throw n;let g=Buffer.concat(d);d.length=0;let w;if(s.interlace)w=$g.inflateSync(g);else{let O=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;w=aE(g,{chunkSize:O,maxLength:O})}if(g=null,!w||!w.length)throw new Error("bad png - invalid inflate data response");let k=cE.process(w,s);g=null;let T=dE.dataToBitMap(k,s);k=null;let $=fE(T,s,e.skipRescale);return s.data=$,s.gamma=c||0,s}});var Tg=ee((bM,Eg)=>{"use strict";var Sg=!0,vg=require("zlib");vg.deflateSync||(Sg=!1);var pE=Io(),hE=Au();Eg.exports=function(t,e){if(!Sg)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 hE(n),s=[];s.push(Buffer.from(pE.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=vg.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 Rg=ee(Pu=>{"use strict";var mE=xg(),gE=Tg();Pu.read=function(t,e){return mE(t,e||{})};Pu.write=function(t,e){return gE(t,e)}});var Og=ee(Ag=>{"use strict";var yE=require("util"),Cg=require("stream"),bE=Qm(),wE=cg(),_E=Rg(),Dt=Ag.PNG=function(t){Cg.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 bE(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 wE(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"))};yE.inherits(Dt,Cg);Dt.sync=_E;Dt.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)};Dt.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};Dt.prototype.write=function(t){return this._parser.write(t),!0};Dt.prototype.end=function(t){this._parser.end(t)};Dt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Dt.prototype._gamma=function(t){this.gamma=t};Dt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};Dt.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)};Dt.prototype.bitblt=function(t,e,n,o,s,r,i){return Dt.bitblt(this,t,e,n,o,s,r,i),this};Dt.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}};Dt.prototype.adjustGamma=function(){Dt.adjustGamma(this)}});var Ig={};w_(Ig,{default:()=>Ng});function Ng(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(!Mu(t)||!Mu(e)||n&&!Mu(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 p=o*s,m=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),w=!0;for(let ne=0;ne<p;ne++)if(m[ne]!==g[ne]){w=!1;break}if(w){if(n&&!f)for(let ne=0;ne<p;ne++)Mg(t,4*ne,a,n);return 0}let k=35215*i*i,[T,$,R]=l,[O,N,z]=c,[K,V,ie]=d||c,J=0;for(let ne=0;ne<s;ne++)for(let Ke=0;Ke<o;Ke++){let ve=ne*o+Ke,H=ve*4,oe=m[ve]===g[ve]?0:Lg(t,e,H,H,!1);if(Math.abs(oe)>k){let et=Pg(t,Ke,ne,o,s,m,g)||Pg(e,Ke,ne,o,s,g,m);!u&&et?n&&!f&&Wa(n,H,T,$,R):(n&&(oe<0?Wa(n,H,K,V,ie):Wa(n,H,O,N,z)),J++)}else n&&!f&&Mg(t,H,a,n)}return J}function Mu(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Pg(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,p=0,m=0,g=0,w=0,k=0,T=0;for(let $=a;$<=c;$++)for(let R=l;R<=u;R++){if($===e&&R===n)continue;let O=Lg(t,t,d*4,(R*o+$)*4,!0);if(O===0){if(f++,f>2)return!1}else O<p?(p=O,g=$,w=R):O>m&&(m=O,k=$,T=R)}return p===0||m===0?!1:Ua(r,g,w,o,s)&&Ua(i,g,w,o,s)||Ua(r,k,T,o,s)&&Ua(i,k,T,o,s)}function Ua(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 Lg(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],p=r-c,m=i-u,g=a-d,w=l-f;if(!p&&!m&&!g&&!w)return 0;if(l<255||f<255){let O=48+159*(n%2),N=48+159*((n/1.618033988749895|0)%2),z=48+159*((n/2.618033988749895|0)%2);p=(r*l-c*f-O*w)/255,m=(i*l-u*f-N*w)/255,g=(a*l-d*f-z*w)/255}let k=p*.29889531+m*.58662247+g*.11448223;if(s)return k;let T=p*.59597799-m*.2741761-g*.32180189,$=p*.21147017-m*.52261711+g*.31114694,R=.5053*k*k+.299*T*T+.1957*$*$;return k>0?-R:R}function Wa(t,e,n,o,s){t[e+0]=n,t[e+1]=o,t[e+2]=s,t[e+3]=255}function Mg(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 jg=b_(()=>{});var Gs=ee(($M,Ug)=>{var ns=require("fs"),$E=require("path"),kE=require("os"),xE="nex-visual-";function qg(t){return $E.join(kE.tmpdir(),`${xE}${Date.now()}-${t}`)}var Nu=null;function Ha(){return Nu||(Nu=Og().PNG),Nu}var Lu=null;function SE(){if(!Lu){let t=(jg(),$_(Ig));Lu=t.default||t}return Lu}function Du(t,e,{threshold:n=.1}={}){let o=Ha(),s=SE(),r=o.sync.read(ns.readFileSync(t)),i=o.sync.read(ns.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=Dg(r,a,l),u=Dg(i,a,l),d=new o({width:a,height:l}),f=s(c,u,d.data,a,l,{threshold:n,includeAA:!1}),p=a*l,m=(f/p*100).toFixed(1),g=vE(d.data,a,l,3,3),w=qg("diff.png");return ns.writeFileSync(w,o.sync.write(d),{mode:384}),{diffPath:w,diffPercent:parseFloat(m),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function Dg(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 vE(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,p=u*i,m=c*a,g=Math.min(p+i,e),w=Math.min(m+a,n);for(let k=m;k<w;k++)for(let T=p;T<g;T++){f++;let $=(k*e+T)*4;(t[$]>0||t[$+1]>0)&&d++}if(d>0){let k=(d/f*100).toFixed(1),T=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:T,changedPercent:parseFloat(k),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var Fg=[{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 EE(t,{viewports:e=Fg,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=ts(),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 Bg(t,e=[]){let n=Ha(),o=n.sync.read(ns.readFileSync(t));for(let i of e){let a=TE(i.color||"#FF0000");i.type==="box"?(RE(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&ju(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(CE(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&ju(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(AE(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&ju(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=qg("annotated.png");ns.writeFileSync(s,n.sync.write(o),{mode:384});let r=ns.readFileSync(s).toString("base64");return{path:s,base64:r,media_type:"image/png"}}function TE(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 qn(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 RE(t,e,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<o;l++)qn(t,e+l,n+a,r),qn(t,e+l,n+s-1-a,r);for(let l=0;l<s;l++)qn(t,e+a,n+l,r),qn(t,e+o-1-a,n+l,r)}}function Iu(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,p=n;for(;;){let m=Math.floor(i/2);for(let w=-m;w<=m;w++)for(let k=-m;k<=m;k++)qn(t,f+w,p+k,r);if(f===o&&p===s)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,p+=u)}}function CE(t,e,n,o,s,r,i=3){Iu(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;Iu(t,o,s,Math.round(o+l*Math.cos(c)),Math.round(s+l*Math.sin(c)),r,i),Iu(t,o,s,Math.round(o+l*Math.cos(u)),Math.round(s+l*Math.sin(u)),r,i)}function AE(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));qn(t,u,d,s)}}}function ju(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++)qn(t,e+c,n+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)qn(t,e+l,n+a-1,s),qn(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++)qn(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}=ts(),l=PE("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 NE(()=>d,3e5),d=!1,u++,await ME(o);let p=await a(t,{width:s,height:r,timeout:i}),m=null;try{m=Du(c.path,p.path)}catch{}c=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function PE(t){try{return require(t)}catch{return null}}function ME(t){return new Promise(e=>setTimeout(e,t))}function NE(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=Ha().sync.read(ns.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],p=o.data[d+1],m=o.data[d+2];if(o.data[d+3]<128)continue;let w=Math.round(f/8)*8,k=Math.round(p/8)*8,T=Math.round(m/8)*8,$=`${w},${k},${T}`;s.set($,(s.get($)||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,p]=c.split(",").map(Number);return{hex:IE(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:jE(d,f,p)}}),l=DE(o);return{colors:a,spacing:l,dimensions:{width:o.width,height:o.height},imagePath:t}}function IE(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function jE(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=qE(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 qE(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 FE(t,e,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=ts(),c=Ha().sync.read(ns.readFileSync(e)),u=n||c.width,d=o||c.height,f=await a(t,{width:u,height:d,fullPage:s,timeout:i}),p=Du(e,f.path,{threshold:r}),m=Bg(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,w)=>{let $=Math.ceil(p.width/3),R=Math.ceil(p.height/3),O=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],N=0,z=0;for(let K=0;K<3;K++)for(let V=0;V<3;V++)O[K][V]===g.name&&(N=V,z=K);return{type:"box",x:N*$+2,y:z*R+2,width:$-4,height:R-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:p.diffPath,annotatedPath:m.path,diffPercent:p.diffPercent,changedPixels:p.changedPixels,totalPixels:p.totalPixels,regions:p.regionSummary,liveBase64:f.base64,diffBase64:ns.readFileSync(p.diffPath).toString("base64"),annotatedBase64:m.base64}}Ug.exports={pixelDiff:Du,responsiveSweep:EE,annotateImage:Bg,visualWatch:OE,extractDesignTokens:LE,designCompare:FE,DEFAULT_VIEWPORTS:Fg}});var qu=ee((kM,Wg)=>{var{C:at}=Et(),Lr="",qt=[],Nr=0,Ys=null;function BE(t){Ys=t}function UE(t,e){Lr=t,qt=[],Nr=0;for(let o of e){Nr++;let s=`t${Nr}`;qt.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${Nr}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=qt.map(o=>({...o}));return Ys&&Ys("create",{name:t,tasks:n}),n}function WE(t,e,n){let o=qt.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),Ys&&Ys("update",{id:t,status:e,result:n}),{...o}):null}function HE(){return{name:Lr,tasks:qt.map(t=>({...t}))}}function GE(){Lr="",qt=[],Nr=0,Ys&&Ys("clear",{})}function YE(){return qt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=qt.find(o=>o.id===e);return n&&n.status==="done"}))}function zE(){if(qt.length===0)return`${at.dim}No active tasks${at.reset}`;let t=[];Lr&&(t.push(` ${at.bold}${at.cyan}Tasks: ${Lr}${at.reset}`),t.push(` ${at.dim}${"\u2500".repeat(40)}${at.reset}`));for(let s of qt){let r,i;switch(s.status){case"done":r="\u2713",i=at.green;break;case"in_progress":r="\u2192",i=at.cyan;break;case"failed":r="\u2717",i=at.red;break;default:r="\xB7",i=at.dim}let a=s.dependsOn.length>0?` ${at.dim}(after: ${s.dependsOn.join(", ")})${at.reset}`:"",l=`[${s.status}]`,c=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${at.reset} ${at.bold}${s.id}${at.reset} ${c.padEnd(40)} ${i}${l}${at.reset}${a}`),s.result&&s.status==="done"){let u=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${at.dim}\u2192 ${u}${at.reset}`)}}let e=qt.filter(s=>s.status==="done").length,n=qt.filter(s=>s.status==="failed").length,o=qt.length;return t.push(` ${at.dim}${"\u2500".repeat(40)}${at.reset}`),t.push(` ${at.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${at.reset}`),t.join(`
|
|
293
|
+
`)}function KE(){return qt.length>0&&qt.some(t=>t.status==="pending"||t.status==="in_progress")}Wg.exports={createTasks:UE,updateTask:WE,getTaskList:HE,clearTasks:GE,getReadyTasks:YE,renderTaskList:zE,setOnChange:BE,hasActiveTasks:KE}});var Bu=ee((xM,Vg)=>{var{callChat:VE}=Tt(),{estimateTokens:Fu}=Fn(),Hg=process.env.NEX_COMPACTION!=="false",Gg=6,Yg=2e3,zg=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.
|
|
294
294
|
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.
|
|
295
295
|
|
|
296
296
|
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:
|
|
@@ -322,38 +322,38 @@ Format your output as:
|
|
|
322
322
|
|
|
323
323
|
<summary>
|
|
324
324
|
[Sections 1-9 above]
|
|
325
|
-
</summary>`,zs=0;async function
|
|
326
|
-
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return zs++,null}}function
|
|
325
|
+
</summary>`,zs=0;async function JE(t){if(!Hg||t.length<Gg||zs>=zg)return null;let e=[{role:"system",content:XE},{role:"user",content:Kg(t)}];try{let o=((await VE(e,[],{temperature:0,maxTokens:Yg})).content||"").trim();if(!o)return zs++,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 zs++,null;let r=t.reduce((a,l)=>a+Fu(l.content||"")+(l.tool_calls?Fu(JSON.stringify(l.tool_calls)):0),0),i=Fu(o);return i>=r*.8?(zs++,null):(zs=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
326
|
+
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return zs++,null}}function ZE(){zs=0}function Kg(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}
|
|
327
327
|
tools: ${s}`}return`[${n}] ${o}`}).join(`
|
|
328
328
|
|
|
329
|
-
`)}
|
|
329
|
+
`)}Vg.exports={compactMessages:JE,formatMessagesForSummary:Kg,resetCompactionFailures:ZE,COMPACTION_ENABLED:Hg,COMPACTION_MIN_MESSAGES:Gg,COMPACTION_SUMMARY_BUDGET:Yg,MAX_CONSECUTIVE_FAILURES:zg}});var Fn=ee((SM,ry)=>{var QE=require("path");function Jg(){return Tt().getActiveModel()}var eT={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},tT={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},Ks=new Map,Xg=1e3,Uu=new WeakMap,Vs=null;function nT(){if(Vs!==null)return Vs;try{let t=Jg(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(tT))if(n.startsWith(o))return Vs=s,Vs;return Vs=eT[e]||4,Vs}catch{return 4}}function sT(){Vs=null}function Xs(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=Ks.get(e);if(n!==void 0)return Ks.delete(e),Ks.set(e,n),n;let o=Math.ceil(t.length/nT());if(Ks.size>=Xg){let s=Xg>>1,r=Ks.keys();for(let i=0;i<s;i++)Ks.delete(r.next().value)}return Ks.set(e,o),o}function oT(t){if(Uu.has(t))return Uu.get(t);let e=JSON.stringify(t);return Uu.set(t,e),e}function ys(t){let n=4;if(t.content&&(n+=Xs(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=Xs(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=Xs(s):s&&(n+=Xs(JSON.stringify(s)))}return n}function hn(t){let e=0;for(let n of t)e+=ys(n);return e}function rT(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+=ys(e[r]);return s}var Wu=new WeakMap;function Ga(t){if(!t||t.length===0)return 0;if(Wu.has(t))return Wu.get(t);let e=Xs(JSON.stringify(t));return Wu.set(t,e),e}function Ya(){return Jg()?.contextWindow||32768}var Ft={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function iT(t,e){let n=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(Ft.result&&t.length===Ft.msgCount&&n===Ft.lastMsgRef&&o===Ft.toolCount)return Ft.result;let s,r,i,a;if(Ft.messagesRef===t&&t.length>Ft.msgCount&&Ft.msgCount>=0){s=Ft.messageTokens,r=Ft.systemTokens,i=Ft.conversationTokens,a=Ft.toolResultTokens;for(let p=Ft.msgCount;p<t.length;p++){let m=ys(t[p]);s+=m,t[p].role==="system"?r+=m:t[p].role==="tool"?a+=m:i+=m}}else{s=0,r=0,i=0,a=0;for(let p of t){let m=ys(p);s+=m,p.role==="system"?r+=m:p.role==="tool"?a+=m:i+=m}}let l=Ga(e),c=s+l,u=Ya(),d=u>0?c/u*100:0,f={used:c,limit:u,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return Ft={msgCount:t.length,lastMsgRef:n,toolCount:o,result:f,messagesRef:t,messageTokens:s,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Ir=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Zg=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Qg=parseInt(process.env.NEX_KEEP_RECENT,10)||10,ey={essential:.6,standard:.65,full:Math.min(Ir,.75)};function ty(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Ir;try{let{getActiveTier:t}=Or(),e=t();return ey[e]??Ir}catch{return Ir}}var aT=200,lT=1e3;function ny(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(`
|
|
330
330
|
`);if(s.length<=10){let m=Math.floor(o*.6),g=Math.floor(o*.4),w=t.substring(0,m),k=t.substring(t.length-g);return w+`
|
|
331
331
|
...(${t.length} chars total)...
|
|
332
332
|
`+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 p=s.length-a.length-u.length;return a.join(`
|
|
333
333
|
`)+`
|
|
334
334
|
...(${p} lines omitted, ${s.length} total)...
|
|
335
335
|
`+u.join(`
|
|
336
|
-
`)}function qo(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:
|
|
337
|
-
...(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
|
|
336
|
+
`)}function qo(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:lT,o=e==="aggressive"?50:e==="medium"?100:aT;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:ny(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
|
|
337
|
+
...(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 sy(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(QE.basename(l)))&&a++;s+=Math.min(30,a*10)}return Math.min(100,s)}function oy(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 cT(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:
|
|
338
338
|
`+s.map(r=>`- ${r}`).join(`
|
|
339
339
|
`)),o.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
|
|
340
340
|
${o.join(`
|
|
341
|
-
`)}`,_pinned:!0,_progressSnapshot:!0}}var Do={msgCount:-1,lastMsgRef:null,result:null};function
|
|
341
|
+
`)}`,_pinned:!0,_progressSnapshot:!0}}var Do={msgCount:-1,lastMsgRef:null,result:null};function uT(){Do={msgCount:-1,lastMsgRef:null,result:null},Ft={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function dT(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&Do.result&&t.length===Do.msgCount&&o===Do.lastMsgRef)return Do.result;let s=n.threshold??ty(),r=n.safetyMargin??Zg,i=n.keepRecent??Qg,a=Ya(),l=Ga(e),c=Math.floor(a*(s-r)),u=c-l,d=hn(t);if(d+l<=c){let J={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Do={msgCount:t.length,lastMsgRef:o,result:J},J}let p=d,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let w=Math.max(g,t.length-i),k=t.slice(g,w),T=t.slice(w),$=k.map(J=>qo(J,"light")),R=ss(m,$,T),O=hn(R);if(O+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-O};if($=k.map(J=>qo(J,"medium")),R=ss(m,$,T),O=hn(R),O+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-O};if($=k.map(J=>qo(J,"aggressive")),R=ss(m,$,T),O=hn(R),O+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-O};let N=process.env.NEX_SKIP_COMPACTOR==="1",z=k.filter(J=>J._pinned),K=k.filter(J=>!J._compacted&&!J._pinned);if(!N&&K.length>=6)try{let{compactMessages:J}=Bu(),ne=await J(K);if(ne){let Ke=k.filter(et=>et._compacted&&!et._pinned),ve=[...z,...Ke,ne.message],H=ss(m,ve,T),oe=hn(H);if(oe+l<=c)return{messages:H,compressed:!0,compacted:!0,tokensRemoved:p-oe};k=ve}}catch(J){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",J.message)}let V=oy([...$,...T]),ie=$.map((J,ne)=>({msg:J,score:J._pinned?1/0:sy(J,ne,$.length,V),tokens:ys(J)}));for(;ie.length>0&&O>u;){let J=-1;for(let ne=0;ne<ie.length;ne++)ie[ne].score!==1/0&&(J===-1||ie[ne].score<ie[J].score)&&(J=ne);if(J===-1)break;O-=ie[J].tokens,ie.splice(J,1)}return $=ie.map(J=>J.msg),R=ss(m,$,T),O=hn(R),{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-O}}function ss(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function fT(t,e){if(!t)return"";if(Xs(t)<=e)return t;let o=e*4,s=t.split(`
|
|
342
342
|
`),r=Math.floor(o*.6),i=Math.floor(o*.4),a="",l=0;for(let p of s){if(a.length+p.length+1>r)break;a+=(a?`
|
|
343
343
|
`:"")+p,l++}let c="",u=0;for(let p=s.length-1;p>=l;p--){let m=s[p]+(c?`
|
|
344
344
|
`:"")+c;if(m.length>i)break;c=m,u++}let f=`
|
|
345
345
|
|
|
346
346
|
... (${s.length-l-u} lines omitted, ${s.length} total) ...
|
|
347
347
|
|
|
348
|
-
`;return a+f+c}var
|
|
349
|
-
`);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
|
|
350
|
-
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of
|
|
348
|
+
`;return a+f+c}var pT=6;function hT(t,e,n=!1){let o=Ya(),s=Ga(e),r=Math.floor(o*(n?.35:.5))-s,i=hn(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:pT,d=Math.max(c,t.length-u),f=t.slice(c,d),p=t.slice(d),m=f;n&&(p=p.map(O=>qo(O,"aggressive")));let g=ss(l,m,p),w=hn(g);for(;m.length>0&&w>r;){let O=m.shift();w-=ys(O)}if(!n&&w>r&&m.length>0)for(m=m.map(O=>qo(O,"aggressive")),g=ss(l,m,p),w=hn(g);m.length>0&&w>r;){let O=m.shift();w-=ys(O)}n&&w>r&&(p=p.filter(N=>N.role==="user").slice(-1),g=ss(l,[],p),w=hn(g)),g=ss(l,m,p);let k=t.filter(O=>O.role==="user"),T=O=>{let N=typeof O.content=="string"?O.content:"";return N.startsWith("[SYSTEM WARNING]")||N.startsWith("[SYSTEM:")||N.startsWith("BLOCKED:")},$=k.find(O=>!T(O)),R=[...k].reverse().find(O=>!T(O));if($&&!g.find(O=>O===$)){let O=g.findIndex(z=>z.role==="system"),N=O>=0?O+1:0;g.splice(N,0,$)}return R&&R!==$&&!g.find(O=>O===R)&&g.push(R),{messages:g,tokensRemoved:i-hn(g)}}ry.exports={estimateTokens:Xs,estimateMessageTokens:ys,estimateMessagesTokens:hn,estimateDeltaTokens:rT,estimateToolsTokens:Ga,serializeMessage:oT,getContextWindow:Ya,getUsage:iT,compressMessage:qo,compressToolResult:ny,scoreMessageRelevance:sy,extractActiveFiles:oy,buildProgressSnapshot:cT,fitToContext:dT,forceCompress:hT,truncateFileContent:fT,invalidateTokenRatioCache:sT,invalidateFitToContextCache:uT,getEffectiveCompressionThreshold:ty,COMPRESSION_THRESHOLD:Ir,TIER_COMPRESSION_THRESHOLDS:ey,SAFETY_MARGIN:Zg,KEEP_RECENT:Qg}});var Ju=ee((vM,wy)=>{var gt=require("fs"),os=require("path"),{atomicWrite:iy,withFileLockSync:ay}=Ds(),mT=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 Bo(){let t=os.join(process.cwd(),".nex","brain");return gt.existsSync(t)||gt.mkdirSync(t,{recursive:!0}),t}function Ka(){return os.join(Bo(),".brain-index.json")}function Yu(){return os.join(Bo(),".embeddings.json")}function jr(){let t=os.join(process.cwd(),".nex","brain");if(!gt.existsSync(t))return[];try{return gt.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=os.join(t,e),o=gt.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 Dr(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(`
|
|
349
|
+
`);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 ly(t){let e=os.join(Bo(),`${t}.md`);if(!gt.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=gt.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=Dr(n);return{name:t,content:n,body:s,frontmatter:o}}function gT(t,e){let n=os.join(Bo(),`${t}.md`);iy(n,e),wT(t,e),yT()}function yT(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Yu();gt.existsSync(t)&&setImmediate(async()=>{try{await my()}catch{}})}function bT(t){let e=os.join(Bo(),`${t}.md`);return gt.existsSync(e)?(gt.unlinkSync(e),_T(t),!0):!1}function za(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!mT.has(e))}function zu(t){let e={},{frontmatter:n,body:o}=Dr(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(`
|
|
350
|
+
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of za(a))e[l]=(e[l]||0)+3}for(let i of za(o||t))e[i]=(e[i]||0)+1;return e}function Ku(){let t=Ka();if(!gt.existsSync(t))return{documents:{}};try{return JSON.parse(gt.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Vu(t){iy(Ka(),JSON.stringify(t,null,2))}function wT(t,e){ay(Ka(),()=>{let n=Ku(),{frontmatter:o}=Dr(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:zu(e),tags:s,modified:new Date().toISOString()},Vu(n)})}function _T(t){ay(Ka(),()=>{let e=Ku();delete e.documents[t],Vu(e)})}function Gu(){let t=jr(),e={documents:{}};for(let n of t){let o=gt.readFileSync(n.path,"utf-8"),{frontmatter:s}=Dr(o),r=Array.isArray(s.tags)?s.tags:[];e.documents[n.name]={keywords:zu(o),tags:r,modified:n.modified.toISOString()}}return Vu(e),e}function cy(){let t=Ku(),e=jr();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return Gu()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return Gu();return t}function uy(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=za(t);if(s.length===0)return[];let r=cy(),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 dy=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Hu=400,$T=50;async function fy(){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(dy.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:dy,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 py(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 hy(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+Hu).join(" ");if(n.push({text:s,offset:o}),o+Hu>=e.length)break;o+=Hu-$T}return n}async function my(){let t=jr(),e={documents:{}},n=Yu();if(gt.existsSync(n))try{e=JSON.parse(gt.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=gt.readFileSync(o.path,"utf-8"),i=hy(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 gt.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function gy(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=Yu();if(!gt.existsSync(s))return[];let r;try{r=JSON.parse(gt.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 p=py(i,f.embedding);p>u&&(u=p,d=f.text)}u>=o&&a.push({name:l,score:u,bestChunk:d})}return a.sort((l,c)=>c.score-l.score),a.slice(0,n)}function yy(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 by(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=uy(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await fy()){let a=await gy(t,{topK:n});r=yy(s,a,{topK:n})}}catch{}return r.map(i=>{let a=ly(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 Fo={queryKey:null,result:null,ts:0},kT=3e5;async function xT(t){if(!t||!t.trim())return"";let e=os.join(process.cwd(),".nex","brain");if(!gt.existsSync(e)||jr().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(Fo.result!==null&&Fo.queryKey===o&&Date.now()-Fo.ts<kT)return Fo.result;let s;try{s=await by(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=Fn().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],l=0;for(let u of 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))+`
|
|
351
351
|
...(truncated)`}let p=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${p}) ---
|
|
352
352
|
${d}`),l+=r(d),l>=i)break}if(a.length===0)return Fo={queryKey:o,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
|
|
353
353
|
|
|
354
354
|
${a.join(`
|
|
355
355
|
|
|
356
|
-
`)}`;return Fo={queryKey:o,result:c,ts:Date.now()},c}
|
|
356
|
+
`)}`;return Fo={queryKey:o,result:c,ts:Date.now()},c}wy.exports={getBrainDir:Bo,listDocuments:jr,readDocument:ly,writeDocument:gT,removeDocument:bT,buildIndex:Gu,getIndex:cy,query:by,getBrainContext:xT,isEmbeddingAvailable:fy,generateEmbedding:Xu,buildEmbeddingIndex:my,semanticQuery:gy,cosineSimilarity:py,_keywordQuery:uy,_extractKeywords:zu,_chunkText:hy,parseFrontmatter:Dr,tokenize:za,_fuseResults:yy}});var Ur=ee((EM,My)=>{var Ye=require("fs"),Nt=require("path"),ST=require("os"),{atomicWrite:qr,withFileLockSync:_y}=Ds(),Js=["user","feedback","project","reference"],vT=50;function Zs(){return Nt.join(process.cwd(),".nex","memory")}function Uo(){return Nt.join(Zs(),"memory.json")}function $y(){return Nt.join(Zs(),"MEMORY.md")}function ET(){return Nt.join(process.cwd(),"NEX.md")}function ky(){return Nt.join(ST.homedir(),".nex","NEX.md")}function Va(){let t=Zs();Ye.existsSync(t)||Ye.mkdirSync(t,{recursive:!0})}function Xa(t){let e=Nt.join(Zs(),t);return Ye.existsSync(e)||Ye.mkdirSync(e,{recursive:!0}),e}function Fr(){let t=Uo();if(!Ye.existsSync(t))return{};try{return JSON.parse(Ye.readFileSync(t,"utf-8"))}catch{return{}}}function xy(t){Va(),qr(Uo(),JSON.stringify(t,null,2))}function Sy(){let t=Uo();if(!Ye.existsSync(t))return;let e=Fr(),n=Object.keys(e);if(n.length===0){try{Ye.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=Xa("project"),l=Nt.join(a,`${i}.md`),c=r.split(`
|
|
357
357
|
`)[0].slice(0,100),u=`---
|
|
358
358
|
name: ${o}
|
|
359
359
|
description: ${c}
|
|
@@ -361,7 +361,7 @@ type: project
|
|
|
361
361
|
---
|
|
362
362
|
|
|
363
363
|
${r}
|
|
364
|
-
`;
|
|
364
|
+
`;qr(l,u)}Br();try{Ye.renameSync(t,t+".bak")}catch{}}function TT(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=Xa(t),i=Nt.join(r,`${s}.md`);if(Ye.existsSync(i))try{if(Qu(Ye.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(`
|
|
365
365
|
`)[0].slice(0,100),l=`---
|
|
366
366
|
name: ${e}
|
|
367
367
|
description: ${a}
|
|
@@ -369,58 +369,58 @@ type: ${t}
|
|
|
369
369
|
---
|
|
370
370
|
|
|
371
371
|
${n}
|
|
372
|
-
`;return
|
|
373
|
-
`).length+e.length+1>n?!1:(t.push(e),!0)}function
|
|
372
|
+
`;return qr(i,l),Br(),{ok:!0,path:i,updated:!0}}function RT(t,e){if(!Js.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=Nt.join(Zs(),t,`${n}.md`);if(!Ye.existsSync(o))return!1;try{return Ye.unlinkSync(o),Br(),!0}catch{return!1}}function Qu(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 vy({includeBody:t=!1}={}){let e=[],n=Zs();for(let o of Js){let s=Nt.join(n,o);if(!Ye.existsSync(s))continue;let r;try{r=Ye.readdirSync(s).filter(i=>i.endsWith(".md"))}catch{continue}for(let i of r){let a=Nt.join(s,i);try{let l=Ye.readFileSync(a,"utf-8"),c=Qu(l),u=null;try{u=Ye.statSync(a)}catch{u=null}let d={type:o,name:c.name||Nt.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 Ey(){return vy()}function Ty(t){return String(t||"").replace(/\s+/g," ").trim()}function CT(t,e){let n=Ty(t);return n.length<=e?n:n.slice(0,Math.max(0,e-15)).trimEnd()+" [truncated]"}function Zu(t,e,n){return t.join(`
|
|
373
|
+
`).length+e.length+1>n?!1:(t.push(e),!0)}function Ry(t){if(t<=200)return"";let e=Cy(),n=vy({includeBody:!0});if(!e&&n.length===0){let r=Ay();if(r.length===0)return"";let i=["PROJECT MEMORY:"];for(let a of r)if(!Zu(i,` ${a.key}: ${a.value}`,t)){i.push("[Memory truncated - use delete_memory to prune old entries]");break}return i.join(`
|
|
374
374
|
`)}let o=[];if(e){let r=Math.max(350,Math.floor(t*.45)),i=e.split(`
|
|
375
|
-
`);for(let a of i)if(!
|
|
375
|
+
`);for(let a of i)if(!Zu(o,a,r)){o.push("[Memory index truncated - use delete_memory to prune old entries]");break}}let s=n.filter(r=>Ty(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(`
|
|
376
376
|
`).length<t-220){o.length>0&&o.push(""),o.push("ACTIVE MEMORY EXCERPTS:");for(let r of s){let i=t-o.join(`
|
|
377
|
-
`).length-1;if(i<180)break;let a=Math.min(520,Math.max(120,i-90)),l=`${r.type}/${Nt.basename(r.filePath)}`,c=r.description?` - ${r.description}`:"",u=
|
|
378
|
-
`)}function
|
|
377
|
+
`).length-1;if(i<180)break;let a=Math.min(520,Math.max(120,i-90)),l=`${r.type}/${Nt.basename(r.filePath)}`,c=r.description?` - ${r.description}`:"",u=CT(r.body,a),d=`- ${r.name} (${l})${c}: ${u}`;if(!Zu(o,d,t))break}}return o.length===0?"":o.join(`
|
|
378
|
+
`)}function Br(){let t=Ey(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=vT+2)break;let o=`${n.type}/${Nt.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Va(),qr($y(),e.join(`
|
|
379
379
|
`)+`
|
|
380
|
-
`)}function
|
|
380
|
+
`)}function Cy(){let t=$y();if(!Ye.existsSync(t))return"";try{return Ye.readFileSync(t,"utf-8").trim()}catch{return""}}function AT(t,e){Va(),_y(Uo(),()=>{let n=Fr();n[t]={value:e,updatedAt:new Date().toISOString()},xy(n)})}function OT(t){let e=Fr();return e[t]?e[t].value:null}function PT(t){return Va(),_y(Uo(),()=>{let e=Fr();return t in e?(delete e[t],xy(e),!0):!1})}function Ay(){let t=Fr();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function Oy(){let t=ky();if(!Ye.existsSync(t))return"";try{return Ye.readFileSync(t,"utf-8").trim()}catch{return""}}function Py(){let t=ET();if(!Ye.existsSync(t))return"";try{return Ye.readFileSync(t,"utf-8").trim()}catch{return""}}function MT(t,e){let n=Xa("reference"),o=Nt.join(n,"learned-patterns.md"),s=new Date().toISOString().split("T")[0],r=e?`- **${t}** (${e}, ${s})
|
|
381
381
|
`:`- **${t}** (${s})
|
|
382
382
|
`,i="";Ye.existsSync(o)&&(i=Ye.readFileSync(o,"utf-8")),!i.includes(t)&&(i.startsWith("# Learned Patterns")?i+=r:i=`# Learned Patterns
|
|
383
383
|
|
|
384
|
-
`+r,
|
|
385
|
-
`).filter(s=>s.startsWith("- **")).map(s=>s.replace(/^-\s*\*\*/,"").replace(/\*\*.*$/,"").trim())}catch{return[]}}function
|
|
386
|
-
${e}`);let n=
|
|
384
|
+
`+r,qr(o,i),Br())}function NT(){let t=Xa("reference"),e=Nt.join(t,"learned-patterns.md");if(!Ye.existsSync(e))return[];try{return Ye.readFileSync(e,"utf-8").split(`
|
|
385
|
+
`).filter(s=>s.startsWith("- **")).map(s=>s.replace(/^-\s*\*\*/,"").replace(/\*\*.*$/,"").trim())}catch{return[]}}function LT(){Sy();let t=[],e=Oy();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
386
|
+
${e}`);let n=Py();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
387
387
|
${n}`);let o=t.join(`
|
|
388
388
|
|
|
389
|
-
`),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=
|
|
389
|
+
`),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=Ry(a),c=[...t];return l&&c.push(l),c.length>0&&c.push(s),c.join(`
|
|
390
390
|
|
|
391
|
-
`)}
|
|
392
|
-
`;
|
|
393
|
-
`).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
|
|
391
|
+
`)}My.exports={saveMemory:TT,deleteMemory:RT,scanMemories:Ey,rebuildIndex:Br,loadMemoryIndex:Cy,remember:AT,recall:OT,forget:PT,listMemories:Ay,saveLearnedPattern:MT,getLearnedPatterns:NT,loadGlobalInstructions:Oy,loadProjectInstructions:Py,getMemoryContext:LT,_getMemoryDir:Zs,_getMemoryFile:Uo,_getGlobalNexMdPath:ky,_parseMemoryFile:Qu,_buildMemoryPromptSection:Ry,_migrateIfNeeded:Sy,VALID_TYPES:Js}});var qy=ee((TM,Dy)=>{var Wr=require("fs"),ed=require("path"),td=process.env.NEX_AUDIT!=="false",Qs=null;function Ny(){return Qs||(Qs=ed.join(process.cwd(),".nex","audit"),Wr.existsSync(Qs)||Wr.mkdirSync(Qs,{recursive:!0}),Qs)}function Ly(){let t=new Date().toISOString().split("T")[0];return ed.join(Ny(),`${t}.jsonl`)}function IT(t){if(td)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Iy(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)+`
|
|
392
|
+
`;Wr.appendFileSync(Ly(),n,"utf-8")}catch{}}function Iy(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 jy(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=ed.join(e,`${r}.jsonl`);if(!Wr.existsSync(i))continue;let a=Wr.readFileSync(i,"utf-8").split(`
|
|
393
|
+
`).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 jT(t=1){let e=jy({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 DT(t){td=t}function qT(){return td}function FT(){Qs=null}Dy.exports={logToolExecution:IT,sanitizeArgs:Iy,readAuditLog:jy,getAuditSummary:jT,setAuditEnabled:DT,isAuditEnabled:qT,getAuditLogPath:Ly,_reset:FT}});var rb=ee((CM,ob)=>{var yt=require("fs").promises,Tn=require("fs"),ae=require("path"),mt=require("util").promisify(require("child_process").exec),eo=require("util").promisify(require("child_process").execFile),{spawnSync:BT}=require("child_process"),nd=require("axios"),{isForbidden:UT,isSSHForbidden:WT,isDangerous:HT,isCritical:Fy,isBashPathForbidden:GT,confirm:En}=_r(),{showDiff:Ja,showNewFile:YT,showEditDiff:RM,confirmFileChange:Hr}=gh(),{C:ge,Spinner:zT,getToolSpinnerText:KT}=Et(),{ToolProgress:Za}=qs(),{isGitRepo:sd,getCurrentBranch:By,getStatus:VT,getDiff:XT}=$a(),{recordChange:Qa}=Th(),{fuzzyFindText:Uy,findMostSimilar:Vr}=Jh(),{runDiagnostics:Gr}=lm(),{findFileInIndex:JT,getFileIndex:Wy,searchContentIndex:ZT,scorePathMatch:Hy,refreshIndex:QT,isIndexValid:eR}=In(),{resolveProfile:mn,sshExec:Bt,scpUpload:tR,scpDownload:Gy}=No(),{resolveDeployConfig:nR,loadDeployConfigs:sR}=Cm(),{getEditMode:Yy}=Or(),oR=/^(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/,rR=/^ssh\s/,iR=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/,aR=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 Jy(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=>aR.has(s))||null}async function Qt(t){return yt.access(t).then(()=>!0).catch(()=>!1)}var el=null,zy=0,lR=12e4;function cR(){let t=Date.now();if(el&&t-zy<lR)return el;let e=ae.dirname(process.cwd());try{let n=Tn.readdirSync(e,{withFileTypes:!0}),o=ae.basename(process.cwd()),s=n.filter(r=>r.isDirectory()&&r.name!==o&&!r.name.startsWith(".")).map(r=>r.name).sort();return el=s.length>0?s:null,zy=t,el}catch{return null}}function od(t){if(t&&ae.resolve(t)!==process.cwd())return"";let e=cR();if(!e)return"";let n=ae.dirname(process.cwd());return`
|
|
394
394
|
Hint: no matches in current project. Sibling directories in ${n}/:
|
|
395
395
|
${e.join(", ")}
|
|
396
|
-
You can search there with: grep pattern --path ${n}/<dir>`}async function
|
|
396
|
+
You can search there with: grep pattern --path ${n}/<dir>`}async function tl(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=Ct(e);if(n&&await Qt(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=ae.extname(t);if(!s)for(let i of o){let a=Ct(t+i);if(a&&await Qt(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=Ct(i+a);if(l&&await Qt(l))return{fixedPath:l,message:`(auto-fixed: ${s} \u2192 ${a})`}}}let r=ae.basename(t);if(r&&r.length>2)try{let i=JT(r).map(a=>Ct(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${ae.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
397
397
|
${i.map(l=>ae.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
398
398
|
`)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=In(),l=a().filter(c=>ae.basename(c).toLowerCase()===i).map(c=>Ct(c));if(l.length===1)return{fixedPath:l[0],message:`(auto-fixed: case-insensitive match \u2192 ${ae.relative(process.cwd(),l[0])})`};if(l.length>1&&l.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
399
399
|
${l.map(u=>ae.relative(process.cwd(),u)).map(u=>` - ${u}`).join(`
|
|
400
400
|
`)}`}}catch{}try{let{smartSearch:i}=In(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=Ct(a[0].file);if(a[0].score>=200||a.length===1&&a[0].score>=50)return{fixedPath:l,message:`(auto-fixed: smart matched ${t} \u2192 ${ae.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 ${ae.relative(process.cwd(),l)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
401
401
|
${a.map(u=>ae.relative(process.cwd(),Ct(u.file))).map(u=>` - ${u}`).join(`
|
|
402
|
-
`)}`}}}catch{}return{fixedPath:null,message:""}}function
|
|
402
|
+
`)}`}}}catch{}return{fixedPath:null,message:""}}function uR(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 Zy(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 Qy(t,e){let n=Zy(t);if(!n)return new Map;try{let o=await ZT(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 Ky(t,e){if(!t)return"";let n=e||process.cwd(),o=ae.isAbsolute(t)?t:ae.resolve(n,t),s=ae.relative(n,o);return s&&!s.startsWith("..")&&!ae.isAbsolute(s)?s:ae.relative(process.cwd(),o)}function Yr(t,e){let n=(t||"").trim();return n?e==="files_with_matches"||e==="count"?n.split(`
|
|
403
403
|
`).filter(o=>o.trim()):n.split(`
|
|
404
|
-
`).filter(o=>o.trim()):[]}function
|
|
404
|
+
`).filter(o=>o.trim()):[]}function eb(t,{query:e,basePath:n,definitionScores:o=new Map,mtimeByPath:s=new Map}={}){let r=Zy(e);return[...t].sort((i,a)=>{let l=Ky(i,n),c=Ky(a,n),u=0,d=0;if(r&&(u+=Hy(l,r),d+=Hy(c,r)),u+=o.get(l)||0,d+=o.get(c)||0,u!==d)return d-u;let f=s.get(i)||0,p=s.get(a)||0;return f!==p?p-f:l.localeCompare(c)})}async function rd(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 Qy(e,n),a=eb(r,{query:e,basePath:n,definitionScores:i}),l=[];for(let c of a)l.push(...s.get(c)||[]);return l}function tb(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+`
|
|
405
405
|
|
|
406
406
|
`+n.join(`
|
|
407
|
-
`)}function tb(t,e,n){let o=Kr(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 Ky=!1,to=null;function uR(){to&&(to(),to=null)}var ad=null;function dR(t){ad=t}async function od(){if(!Ky){Ky=!0;try{let{stdout:t}=await mt("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await mt('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await mt("git stash pop",{cwd:process.cwd(),timeout:1e4}),await mt("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var fR=[/\.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 pR(){let t=process.cwd();try{return vn.realpathSync(t)}catch{return ae.resolve(t)}}function hR(t,e){let n=ae.relative(e,t);return n===""||!n.startsWith("..")&&!ae.isAbsolute(n)}function mR(t){if(vn.existsSync(t))return vn.realpathSync(t);let e=ae.dirname(t);for(;e&&e!==ae.dirname(e);){if(vn.existsSync(e)){let n=vn.realpathSync(e),o=ae.relative(e,t);return ae.resolve(n,o)}e=ae.dirname(e)}return t}function Ct(t){let e=ae.isAbsolute(t)?ae.resolve(t):ae.resolve(process.cwd(),t);for(let o of fR)if(o.test(e))return null;let n=mR(e);return hR(n,pR())?n:null}function We(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function nb(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function gR(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function yR(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function rd(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function bR(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Yr(t,e="user"){return nb(t)?null:`ERROR: ${e} contains unsafe characters`}function id(t,e="service"){return gR(t)?null:`ERROR: ${e} contains unsafe characters`}var wR=[{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 zr(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 Vy(t,e,n={}){switch(t){case"bash":{let o=e.command,s=Xy(o);if(s)return`BLOCKED: ${s} is a Node.js built-in module and must not be installed. Import it directly instead.`;let r=BT(o);if(r){let f=cR(o);return`BLOCKED: Command matches forbidden pattern: ${r}${f?`
|
|
408
|
-
HINT: ${f}`:""}`}let i=
|
|
409
|
-
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?
|
|
410
|
-
${m}`}}case"read_file":{let o=new
|
|
411
|
-
`+V.message:""}`}let i=ae.relative(process.cwd(),s);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),l=await
|
|
407
|
+
`)}function nb(t,e,n){let o=Vr(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 Vy=!1,to=null;function dR(){to&&(to(),to=null)}var cd=null;function fR(t){cd=t}async function id(){if(!Vy){Vy=!0;try{let{stdout:t}=await mt("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await mt('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await mt("git stash pop",{cwd:process.cwd(),timeout:1e4}),await mt("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var pR=[/\.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 hR(){let t=process.cwd();try{return Tn.realpathSync(t)}catch{return ae.resolve(t)}}function mR(t,e){let n=ae.relative(e,t);return n===""||!n.startsWith("..")&&!ae.isAbsolute(n)}function gR(t){if(Tn.existsSync(t))return Tn.realpathSync(t);let e=ae.dirname(t);for(;e&&e!==ae.dirname(e);){if(Tn.existsSync(e)){let n=Tn.realpathSync(e),o=ae.relative(e,t);return ae.resolve(n,o)}e=ae.dirname(e)}return t}function Ct(t){let e=ae.isAbsolute(t)?ae.resolve(t):ae.resolve(process.cwd(),t);for(let o of pR)if(o.test(e))return null;let n=gR(e);return mR(n,hR())?n:null}function We(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function sb(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function yR(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function bR(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function ad(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function wR(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function zr(t,e="user"){return sb(t)?null:`ERROR: ${e} contains unsafe characters`}function ld(t,e="service"){return yR(t)?null:`ERROR: ${e} contains unsafe characters`}var _R=[{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 Kr(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 Xy(t,e,n={}){switch(t){case"bash":{let o=e.command,s=Jy(o);if(s)return`BLOCKED: ${s} is a Node.js built-in module and must not be installed. Import it directly instead.`;let r=UT(o);if(r){let f=uR(o);return`BLOCKED: Command matches forbidden pattern: ${r}${f?`
|
|
408
|
+
HINT: ${f}`:""}`}let i=GT(o);if(i)return`BLOCKED: Destructive operation on protected path: ${i}
|
|
409
|
+
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?Fy(o):HT(o)){let f=Fy(o)?"\u26D4":"\u26A0";if(!await En(` ${f} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let l;try{l=process.cwd(),Tn.accessSync(l)}catch{l=require("os").homedir(),n.silent||console.log(`${ge.yellow} \u26A0 Working directory no longer exists \u2014 running in ${l}${ge.reset}`)}let c=rR.test(o.trim())&&!iR.test(o.trim());if(oR.test(o.trim())||c){n.silent||console.log(`${ge.dim} \u25B6 interactive: ${o}${ge.reset}`);let f=BT("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}=qs(),d=n.silent?null:new u("bash",`$ ${o.substring(0,72)}`);d&&d.start();try{let{stdout:f,stderr:p}=await mt(o,{cwd:l,timeout:9e4,maxBuffer:5242880});return d&&d.stop(),f||p||"(no output)"}catch(f){d&&d.stop();let p=(f.stderr||f.stdout||f.message||"").toString().substring(0,5e3),m=tb(p,o);return`EXIT ${f.code||1}
|
|
410
|
+
${m}`}}case"read_file":{let o=new Za("read_file","Reading file...");o.start();try{let s=Ct(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(s)){let V=await tl(e.path);if(V.fixedPath)s=V.fixedPath,console.log(`${ge.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ae.relative(process.cwd(),s)}${ge.reset}`),o.update({message:"Resolved path",detail:ae.relative(process.cwd(),s)});else return`ERROR: File not found: ${e.path}${V.message?`
|
|
411
|
+
`+V.message:""}`}let i=ae.relative(process.cwd(),s);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),l=await Tn.promises.open(s,"r"),{bytesRead:c}=await l.read(a,0,8192,0);await l.close();for(let V=0;V<c;V++)if(a[V]===0)return`ERROR: ${s} is a binary file (not readable as text)`;let u=await yt.readFile(s,"utf-8");if(!u&&(await yt.stat(s)).size>0)return`WARNING: ${s} is empty or unreadable`;let d=u.split(`
|
|
412
412
|
`),f=await yt.stat(s),p=d.length,m=350,g=!e.line_start&&!e.line_end,w=g&&p>m,k=(e.line_start||1)-1,T=w?m:e.line_end||d.length,$=k+1,R=T;o.update({count:Math.max(0,T-k),total:p,detail:`${i} lines ${$}-${R}`,message:w?"Reading excerpt":"Reading"});let O=w?`showing lines 1-${m} of ${p}`:e.line_start||e.line_end?`lines ${k+1}-${T} of ${p}`:`${p} lines`,N=`File: ${i} (${O}, ${f.size} bytes)`,z=d.slice(k,T).map((V,ie)=>`${k+ie+1}: ${V}`).join(`
|
|
413
413
|
`),K=w?`
|
|
414
414
|
|
|
415
415
|
[\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${m} of ${p} total lines. The rest of the file is HIDDEN. You MUST use line_start and line_end to read further down (e.g. line_start=${m+1}), or use grep_search to find specific keywords.]`:!g&&p>T?`
|
|
416
416
|
|
|
417
417
|
[\u{1F6A8} FILE CONTINUES: This is only lines ${k+1} to ${T} of ${p} total. The rest is HIDDEN. Use line_start=${T+1} to read the next section, or grep_search for keywords.]`:"";return`${N}
|
|
418
|
-
${z}${K}`}finally{o.stop()}}case"write_file":{let o=new
|
|
419
|
-
`).length;if(o.update({count:a,detail:`${ae.relative(process.cwd(),s)} ${a} lines`,message:r?"Overwriting":"Creating"}),n.autoConfirm)r&&(i=await yt.readFile(s,"utf-8"));else if(r){i=await yt.readFile(s,"utf-8");let f=await
|
|
418
|
+
${z}${K}`}finally{o.stop()}}case"write_file":{let o=new Za("write_file","Preparing write...");o.start();try{await id();let s=Ct(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await Qt(s),i=null,a=String(e.content||"").split(`
|
|
419
|
+
`).length;if(o.update({count:a,detail:`${ae.relative(process.cwd(),s)} ${a} lines`,message:r?"Overwriting":"Creating"}),n.autoConfirm)r&&(i=await yt.readFile(s,"utf-8"));else if(r){i=await yt.readFile(s,"utf-8");let f=await Gr(s,e.content);if(Ja(s,i,e.content,{annotations:f}),!await Hr("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let f=await Gr(s,e.content);if(YT(s,e.content,{annotations:f}),!await Hr("Create"))return"CANCELLED: User declined to create file."}let l=ae.dirname(s);await Qt(l)||await yt.mkdir(l,{recursive:!0}),o.update({message:"Writing",detail:`${ae.relative(process.cwd(),s)} ${a} lines`}),await yt.writeFile(s,e.content,"utf-8");let u=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||e.content.startsWith("#!");u&&(o.update({message:"Chmod",detail:ae.relative(process.cwd(),s)}),await yt.chmod(s,493)),Qa("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 Za("edit_file","Preparing edit...");o.start();try{await id();let s=Ct(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(s)){let d=await tl(e.path);if(d.fixedPath)s=d.fixedPath,console.log(`${ge.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ae.relative(process.cwd(),s)}${ge.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
420
420
|
`+d.message:""}`}o.update({message:"Loading",detail:ae.relative(process.cwd(),s)});let i=await yt.readFile(s,"utf-8"),a=e.old_text,l=!1,c=!1;if(!i.includes(e.old_text)){o.update({message:"Matching target",detail:`${ae.relative(process.cwd(),s)} ${String(e.old_text||"").trim().split(`
|
|
421
|
-
`)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=Tt();if(
|
|
421
|
+
`)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=Tt();if(Yy(d(),f())==="strict"){let g=Vr(i,e.old_text);return g?`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)
|
|
422
422
|
Most similar text (line ${g.line}, distance ${g.distance}):
|
|
423
|
-
${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let m=
|
|
423
|
+
${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:`${ae.relative(process.cwd(),s)} whitespace-normalized`}),console.log(`${ge.dim} \u2713 fuzzy whitespace match applied${ge.reset}`);else{let g=nb(i,e.old_text,e.new_text);if(g){if(!n.autoConfirm){let R=await Gr(s,g.content);if(Ja(s,i,g.content,{annotations:R}),!await Hr(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await yt.writeFile(s,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||g.content.startsWith("#!"))&&await yt.chmod(s,493),Qa("edit_file",s,i,g.content);let $=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${ge.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${ge.reset}`),`Edited: ${s} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${$}")`}let w=Vr(i,e.old_text);if(w){let $=i.split(`
|
|
424
424
|
`),R=Math.max(0,w.line-6),O=Math.min($.length,w.line+10),N=$.slice(R,O).map((K,V)=>`${R+V+1}: ${K}`).join(`
|
|
425
425
|
`),z=`line_start=${Math.max(1,w.line-5)} line_end=${Math.min($.length,w.line+15)}`;return`ERROR: old_text not found in ${s} (most similar at line ${w.line}, distance ${w.distance})
|
|
426
426
|
|
|
@@ -431,27 +431,27 @@ Fix: update old_text to match the exact lines above, then retry. If you need mor
|
|
|
431
431
|
`)[0].slice(0,60),T=k?`
|
|
432
432
|
Recovery: grep -n "${k.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
|
|
433
433
|
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}${T}`}}if(!n.autoConfirm){o.update({message:"Previewing edit",detail:`${ae.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
|
|
434
|
-
`)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await
|
|
435
|
-
`)[0].slice(0,40)}`}),await yt.writeFile(s,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||u.startsWith("#!"))&&(o.update({message:"Chmod",detail:ae.relative(process.cwd(),s)}),await yt.chmod(s,493)),
|
|
436
|
-
`)||"(empty)"}case"search_files":{let o=Ct(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 eo("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=
|
|
437
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?Ct(e.path):s,i=e.pattern,a=O=>{let N=O.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${N}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=qs(),f=new d("glob","Finding files...");f.start();let p=
|
|
434
|
+
`)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await Gr(s,d);if(Ja(s,i,d,{annotations:f}),!await Hr(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:`${ae.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
|
|
435
|
+
`)[0].slice(0,40)}`}),await yt.writeFile(s,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||u.startsWith("#!"))&&(o.update({message:"Chmod",detail:ae.relative(process.cwd(),s)}),await yt.chmod(s,493)),Qa("edit_file",s,i,u),l?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}finally{o.stop()}}case"list_directory":{let o=Ct(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(o)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=Ct(c),d=await Qt(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 yt.readdir(c,{withFileTypes:!0})}catch{return}f=f.filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules");for(let p of f){if(i&&!p.isDirectory()&&!i.test(p.name))continue;let m=p.isDirectory()?"/":"";a.push(`${d}${p.name}${m}`),p.isDirectory()&&await l(ae.join(c,p.name),u+1,d+" ")}};return await l(o,1,""),a.join(`
|
|
436
|
+
`)||"(empty)"}case"search_files":{let o=Ct(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 eo("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=Yr(r).slice(0,50);return(await rd(i,{query:e.pattern,basePath:o})).join(`
|
|
437
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?Ct(e.path):s,i=e.pattern,a=O=>{let N=O.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${N}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=qs(),f=new d("glob","Finding files...");f.start();let p=Wy();eR(r)||(await QT(r),p=Wy());let m=p.filter(O=>l.test(O)||u.test(ae.basename(O))).map(O=>ae.join(r,O));if(m.length===0)return f.stop(),"(no matches)"+od(e.path);let g=await Promise.all(m.slice(0,210).map(async O=>{try{let N=await yt.stat(O);return{path:O,mtime:N.mtimeMs}}catch{return{path:O,mtime:0}}})),w=new Map(g.map(O=>[O.path,O.mtime])),k=await Qy(i,r),T=eb(g.map(O=>O.path),{query:i,basePath:r,definitionScores:k,mtimeByPath:w}),$=m.length>200,R=T.slice(0,200).join(`
|
|
438
438
|
`);return f.update({count:m.length,detail:e.pattern}),f.stop(),$?`${R}
|
|
439
439
|
|
|
440
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:R}case"grep":{let o=e.path?Ct(e.path):process.cwd();if(e.staged){let{getDiff:l}
|
|
441
|
-
`);for(let w of d)if(w.startsWith("diff --git")){let k=w.match(/diff --git a\/(.+) b\/(.+)/);k&&u.add(k[2])}let f=["-rn","-E","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&f.push("-i"),e.include&&f.push(`--include=${e.include}`),e.type&&f.push(`--include=*.${e.type}`),e.context?f.push("-C",String(e.context)):(e.before_context&&f.push("-B",String(e.before_context)),e.after_context&&f.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?f.push("-l"):e.output_mode==="count"&&f.push("-c"),f.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:p}=qs(),m=new p("grep","Searching staged content...");m.start();let g=[];for(let w of u)try{let k=ae.join(process.cwd(),w);if(await
|
|
442
|
-
`).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}=qs(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await eo("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;e.output_mode==="files_with_matches"||e.output_mode==="count"?c=
|
|
443
|
-
`).trim()||"(no matches)"+
|
|
444
|
-
`+T.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";o.update({count:0,total:i.length,detail:`${ae.relative(process.cwd(),s)} ${i.length} patches`,message:"Validating patches"});let a=await yt.readFile(s,"utf-8"),{getActiveModelId:l,getActiveProviderName:c}=Tt(),u=
|
|
440
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:R}case"grep":{let o=e.path?Ct(e.path):process.cwd();if(e.staged){let{getDiff:l}=$a(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
|
|
441
|
+
`);for(let w of d)if(w.startsWith("diff --git")){let k=w.match(/diff --git a\/(.+) b\/(.+)/);k&&u.add(k[2])}let f=["-rn","-E","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&f.push("-i"),e.include&&f.push(`--include=${e.include}`),e.type&&f.push(`--include=*.${e.type}`),e.context?f.push("-C",String(e.context)):(e.before_context&&f.push("-B",String(e.before_context)),e.after_context&&f.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?f.push("-l"):e.output_mode==="count"&&f.push("-c"),f.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:p}=qs(),m=new p("grep","Searching staged content...");m.start();let g=[];for(let w of u)try{let k=ae.join(process.cwd(),w);if(await Qt(k)){let T=[...f];T.push(e.pattern,k);let{stdout:$}=await eo("grep",T,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let R=Yr($,e.output_mode);g=g.concat(R)}else g=g.concat(Yr($))}}catch{}return g=await rd(g,{query:e.pattern,basePath:process.cwd(),outputMode:e.output_mode}),m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
|
|
442
|
+
`).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}=qs(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await eo("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;e.output_mode==="files_with_matches"||e.output_mode==="count"?c=Yr(l,e.output_mode):c=Yr(l);let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=await rd(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(`
|
|
443
|
+
`).trim()||"(no matches)"+od(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)"+od(e.path)}}case"patch_file":{let o=new Za("patch_file","Preparing patches...");o.start();try{await id();let s=Ct(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(s)){let T=await tl(e.path);if(T.fixedPath)s=T.fixedPath,console.log(`${ge.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ae.relative(process.cwd(),s)}${ge.reset}`);else return`ERROR: File not found: ${e.path}${T.message?`
|
|
444
|
+
`+T.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";o.update({count:0,total:i.length,detail:`${ae.relative(process.cwd(),s)} ${i.length} patches`,message:"Validating patches"});let a=await yt.readFile(s,"utf-8"),{getActiveModelId:l,getActiveProviderName:c}=Tt(),u=Yy(l(),c()),d=[],f=!1,p=!1;for(let T=0;T<i.length;T++){o.update({count:T+1,total:i.length,detail:`${ae.relative(process.cwd(),s)} patch ${T+1}/${i.length}`,message:"Matching patches"});let{old_text:$,new_text:R}=i[T];if(a.includes($))d.push({old_text:$,new_text:R});else if(u==="strict"){let O=Vr(a,$);return O?`ERROR: Patch ${T+1} old_text not found in ${s} (strict mode \u2014 exact match required)
|
|
445
445
|
Most similar text (line ${O.line}, distance ${O.distance}):
|
|
446
|
-
${O.text}`:`ERROR: Patch ${T+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let O=
|
|
446
|
+
${O.text}`:`ERROR: Patch ${T+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let O=Uy(a,$);if(O)d.push({old_text:O,new_text:R}),f=!0;else{let N=Vr(a,$);if(N){let z=Math.max(3,Math.ceil($.length*.05));if(N.distance<=z)d.push({old_text:N.text,new_text:R}),p=!0;else return`ERROR: Patch ${T+1} old_text not found in ${s}
|
|
447
447
|
Most similar text (line ${N.line}, distance ${N.distance}):
|
|
448
|
-
${N.text}`}else return`ERROR: Patch ${T+1} old_text not found in ${s}`}}}let m=a;for(let{old_text:T,new_text:$}of d)m=m.split(T).join($);if(!n.autoConfirm){o.update({message:"Previewing patch set",count:d.length,total:i.length,detail:`${ae.relative(process.cwd(),s)} ${d.length} matched`});let T=await
|
|
448
|
+
${N.text}`}else return`ERROR: Patch ${T+1} old_text not found in ${s}`}}}let m=a;for(let{old_text:T,new_text:$}of d)m=m.split(T).join($);if(!n.autoConfirm){o.update({message:"Previewing patch set",count:d.length,total:i.length,detail:`${ae.relative(process.cwd(),s)} ${d.length} matched`});let T=await Gr(s,m);if(Ja(s,a,m,{annotations:T}),!await Hr(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:`${ae.relative(process.cwd(),s)} ${d.length} matched`}),await yt.writeFile(s,m,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||m.startsWith("#!");g&&(o.update({message:"Chmod",detail:ae.relative(process.cwd(),s)}),await yt.chmod(s,493)),Qa("patch_file",s,a,m);let w=p?" (auto-fixed)":f?" (fuzzy match)":"",k=g?" [chmod +x applied]":"";return`Patched: ${s} (${i.length} replacements)${w}${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 nd.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 nd.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]
|
|
449
449
|
|
|
450
450
|
${r}`;return i.length>0&&(a+=`
|
|
451
451
|
|
|
452
452
|
Sources:
|
|
453
453
|
`+i.slice(0,o).map((l,c)=>`${c+1}. ${l}`).join(`
|
|
454
|
-
`)),a}catch(s){console.error(`${ge.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${ge.reset}`)}try{let r=(await
|
|
454
|
+
`)),a}catch(s){console.error(`${ge.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${ge.reset}`)}try{let r=(await nd.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}
|
|
455
455
|
${c.url}`).join(`
|
|
456
456
|
|
|
457
457
|
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=ts();try{let s=await o(e.url,{waitFor:e.wait_for}),r=s.links.length>0?`
|
|
@@ -480,9 +480,9 @@ Analyze the screenshot above and provide structured feedback:
|
|
|
480
480
|
2. Visual hierarchy (typography, contrast, colors)
|
|
481
481
|
3. Consistency (margins, padding patterns)
|
|
482
482
|
4. Responsiveness concerns at this viewport
|
|
483
|
-
5. Specific issues related to: ${r}`;return e.compare_with&&
|
|
483
|
+
5. Specific issues related to: ${r}`;return e.compare_with&&Tn.existsSync(e.compare_with)&&(i+=`
|
|
484
484
|
|
|
485
|
-
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}=
|
|
485
|
+
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}=ud(),s=o();return s?{text:`Clipboard image captured: ${s.path}
|
|
486
486
|
Size: ${Math.round(Buffer.from(s.data,"base64").length/1024)} KB
|
|
487
487
|
|
|
488
488
|
[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}=ts();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:o}=ts();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}=Gs(),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(`
|
|
@@ -494,7 +494,7 @@ Diff image: ${s.diffPath}
|
|
|
494
494
|
Regional breakdown:
|
|
495
495
|
${i}
|
|
496
496
|
|
|
497
|
-
[Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:s.diffPath,base64:
|
|
497
|
+
[Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:s.diffPath,base64:Tn.readFileSync(s.diffPath).toString("base64"),media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"responsive_sweep":try{let{responsiveSweep:o}=Gs(),s=await o(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=s.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
|
|
498
498
|
`);return{text:`RESPONSIVE SWEEP \u2014 ${s.length} viewports captured
|
|
499
499
|
URL: ${e.url}
|
|
500
500
|
|
|
@@ -512,7 +512,7 @@ Analyze these screenshots for:
|
|
|
512
512
|
Source: ${e.image}
|
|
513
513
|
Output: ${s.path}
|
|
514
514
|
|
|
515
|
-
[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}=Gs(),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:
|
|
515
|
+
[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}=Gs(),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:Tn.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
|
|
516
516
|
`),images:c}}return{text:i.join(`
|
|
517
517
|
`)+`
|
|
518
518
|
|
|
@@ -542,42 +542,42 @@ Pixel deviation: ${s.changedPixels.toLocaleString()} / ${s.totalPixels.toLocaleS
|
|
|
542
542
|
Regional breakdown:
|
|
543
543
|
${r}
|
|
544
544
|
|
|
545
|
-
[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
|
|
545
|
+
[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 cd?new Promise(r=>{to=()=>r("CANCELLED"),cd(o,s).then(i=>{to=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});to=()=>{i.close(),r("CANCELLED")};let a=s.length>0?`
|
|
546
546
|
${s.map((l,c)=>` ${c+1}. ${l}`).join(`
|
|
547
547
|
`)}
|
|
548
548
|
`:"";console.log(`
|
|
549
|
-
${ge.cyan}${ge.bold} ? ${o}${ge.reset}${a}`),i.question(`${ge.cyan} > ${ge.reset}`,l=>{to=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await
|
|
549
|
+
${ge.cyan}${ge.bold} ? ${o}${ge.reset}${a}`),i.question(`${ge.cyan} > ${ge.reset}`,l=>{to=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await sd())return"ERROR: Not a git repository";let o=await By()||"(detached)",s=await VT();if(s.length===0)return`Branch: ${o}
|
|
550
550
|
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(`
|
|
551
|
-
`)}case"git_diff":{if(!await
|
|
551
|
+
`)}case"git_diff":{if(!await sd())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 XT(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await sd())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}=qu(),{getActiveTaskProgress:l}=Et(),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(`
|
|
552
552
|
`+i()),`Created task list "${e.name}" with ${u.length} tasks:
|
|
553
553
|
`+u.map(d=>` ${d.id}: ${d.description}`).join(`
|
|
554
554
|
`)}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(`
|
|
555
555
|
`+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(`
|
|
556
|
-
`+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}=
|
|
556
|
+
`+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}=nl();return e.agents?.some(r=>r.background)?s(e):o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:s,getActiveModelId:r}=Tt();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 eo("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(`
|
|
557
557
|
`)}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(`
|
|
558
558
|
`)[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 eo("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
559
559
|
...(truncated)`:"")}let{stdout:o}=await eo("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(`
|
|
560
560
|
`)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
|
|
561
|
-
`)[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}=
|
|
561
|
+
`)[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}=_r(),s=e.branch||await By()||"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(`
|
|
562
562
|
${ge.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${ge.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await eo("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(`
|
|
563
|
-
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=
|
|
564
|
-
`)[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=
|
|
563
|
+
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=Kr(`get pods ${o} ${s} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await mt(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
|
|
564
|
+
`)[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=Kr(r,e);try{let{stdout:a,stderr:l}=await mt(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
|
|
565
565
|
...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
566
566
|
`)[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(`
|
|
567
|
-
${ge.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${ge.reset}`),console.log(`${ge.dim} Command: ${e.command}${ge.reset}`),!await
|
|
567
|
+
${ge.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${ge.reset}`),console.log(`${ge.dim} Command: ${e.command}${ge.reset}`),!await En(" 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=Kr(r,e);try{let{stdout:a,stderr:l}=await mt(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
568
568
|
`)[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(`
|
|
569
|
-
${ge.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ge.reset}`),!await
|
|
569
|
+
${ge.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ge.reset}`),!await En(" 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=Kr(s,e);try{let{stdout:i,stderr:a}=await mt(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
570
570
|
`)[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(`
|
|
571
|
-
${ge.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${ge.reset}`),!await
|
|
572
|
-
`)[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}=
|
|
571
|
+
${ge.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${ge.reset}`),!await En(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=Kr(r,e);try{let{stdout:a,stderr:l}=await mt(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
572
|
+
`)[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}=Ju(),{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+`
|
|
573
573
|
|
|
574
|
-
`+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=
|
|
574
|
+
`+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=mn(e.server)}catch(N){return`ERROR: ${N.message}`}let s=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=WT(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:
|
|
575
575
|
grep -n "pattern" /path/to/file -A 50
|
|
576
576
|
or to read the whole file:
|
|
577
577
|
cat /path/to/file
|
|
578
578
|
NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
|
|
579
579
|
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,(N,z,K)=>{let V=Math.min(Number(K),20);return`${z} ${V}`}),s=s.replace(/(--(?:before|after|context)=)(\d+)/g,(N,z,K)=>z+Math.min(Number(K),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 N=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
580
|
-
${ge.yellow} \u26A0 Remote command on ${N}: ${s}${ge.reset}`),!await
|
|
580
|
+
${ge.yellow} \u26A0 Remote command on ${N}: ${s}${ge.reset}`),!await En(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await Bt(o,s,{timeout:i,sudo:r}),p=[c,u].filter(Boolean).join(`
|
|
581
581
|
`).trim();if(d!==0){if(/no such file or directory/i.test(p)){let z=p.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),K=s.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),V=z&&z[1]||K&&K[1];if(V)try{let{remoteAutoFixPath:ie}=No(),J=V.startsWith("/")?V.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(o.user||"root"),ne=await ie(o,J,V);if(ne.fixedPath){let Ke=s.replace(V,ne.fixedPath);console.log(`${ge.dim} \u2713 remote auto-fix: ${V} \u2192 ${ne.fixedPath}${ge.reset}`);let ve=await Bt(o,Ke,{timeout:i,sudo:r}),H=[ve.stdout,ve.stderr].filter(Boolean).join(`
|
|
582
582
|
`).trim();if(ve.exitCode===0)return`${ne.message}
|
|
583
583
|
${H}`||"(command completed, no output)"}else if(ne.message)return`EXIT ${d}
|
|
@@ -591,35 +591,35 @@ ${f||p||"(no output)"}`}let m=/\bgrep\b/.test(s),g=p;m&&(g=g.split(`
|
|
|
591
591
|
`+k.slice(-w).join(`
|
|
592
592
|
`));let T=4,$=g.split(`
|
|
593
593
|
`),R=[],O=0;for(;O<$.length;){let N=O+1;for(;N<$.length&&$[N]===$[O];)N++;let z=N-O;if(R.push($[O]),z>T)R.push(`... (${z-1} identical lines omitted)`);else for(let K=1;K<z;K++)R.push($[O]);O=N}return R.join(`
|
|
594
|
-
`)||"(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=
|
|
595
|
-
${ge.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${ge.reset}`),!await
|
|
594
|
+
`)||"(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=mn(e.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
595
|
+
${ge.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${ge.reset}`),!await En(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await tR(o,e.local_path,e.remote_path);try{No().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=mn(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await Gy(o,e.remote_path,e.local_path)}catch(s){if(/no such file|not found/i.test(s.message))try{let{remoteAutoFixPath:r}=No(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(o,i,e.remote_path);if(a.fixedPath){console.log(`${ge.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${ge.reset}`);let l=await Gy(o,a.fixedPath,e.local_path);return`${a.message}
|
|
596
596
|
${l}`}if(a.message)return`ERROR: ${s.message}
|
|
597
597
|
|
|
598
598
|
${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 p=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
|
|
599
|
-
${p.slice(-2e3)}`:p.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=
|
|
600
|
-
${ge.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${u}${ge.reset}`),!await
|
|
599
|
+
${p.slice(-2e3)}`:p.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=ld(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=mn(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(`
|
|
600
|
+
${ge.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${u}${ge.reset}`),!await En(" Execute?"))return"CANCELLED: User declined service action."}let l=e.service.includes(".")?e.service:`${e.service}.service`,c=`systemctl ${e.action} ${We(l)}`;if(r){let d=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:f,stderr:p}=await mt(d,{timeout:15e3});return(f||p||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(f){let p=(f.stderr||f.message||"").toString().trim();return/not found|loaded.*not-found/i.test(p)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${f.code||1}
|
|
601
601
|
${p}`}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await Bt(a,c,{timeout:15e3,sudo:!0}),m=[u,d].filter(Boolean).join(`
|
|
602
602
|
`).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}
|
|
603
|
-
${p||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=
|
|
604
|
-
${(w.stderr||w.message||"").toString().trim()}`}let u;try{u=
|
|
603
|
+
${p||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=ld(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 ${We(e.since)}`:"",l=e.follow?"-f":"",c=`journalctl -u ${We(i)} -n ${r} ${a} ${l} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:w,stderr:k}=await mt(c,{timeout:15e3});return(w||k||"(no log output)").trim()}catch(w){return`EXIT ${w.code||1}
|
|
604
|
+
${(w.stderr||w.message||"").toString().trim()}`}let u;try{u=mn(e.server)}catch(w){return`ERROR: ${w.message}`}let{stdout:d,stderr:f,exitCode:p,error:m}=await Bt(u,c,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
|
|
605
605
|
`).trim();return p!==0?`EXIT ${p}
|
|
606
606
|
${m||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let o=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(o)try{let{stdout:f,stderr:p}=await mt(r,{timeout:1e4});return(f||p||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
|
|
607
|
-
${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=
|
|
607
|
+
${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=mn(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await Bt(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
|
|
608
608
|
`).trim();return c!==0?`EXIT ${c}
|
|
609
609
|
${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:p,stderr:m}=await mt(i,{timeout:15e3});return(p||m||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
610
|
-
${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=
|
|
610
|
+
${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=mn(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await Bt(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
|
|
611
611
|
`).trim();return u!==0?`EXIT ${u}
|
|
612
612
|
${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(`
|
|
613
|
-
${ge.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${ge.reset}`),!await
|
|
614
|
-
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=
|
|
613
|
+
${ge.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${ge.reset}`),!await En(" 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 mt(a,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
614
|
+
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=mn(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await Bt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
|
|
615
615
|
`).trim();return d!==0?`EXIT ${d}
|
|
616
616
|
${f||p}`:p||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let o=["start","stop","restart","remove","inspect"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let s=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!n.autoConfirm){let m=s?"local":e.server;if(console.log(`
|
|
617
|
-
${ge.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${ge.reset}`),!await
|
|
618
|
-
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=
|
|
617
|
+
${ge.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${ge.reset}`),!await En(" 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 mt(a,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
|
|
618
|
+
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=mn(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await Bt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
|
|
619
619
|
`).trim();return d!==0?`EXIT ${d}
|
|
620
|
-
${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...
|
|
620
|
+
${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...nR(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=mn(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(`
|
|
621
621
|
${ge.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${ge.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
|
|
622
|
-
${ge.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ge.reset}`)}if(e.deploy_script&&console.log(`${ge.yellow} Then run: ${e.deploy_script}${ge.reset}`),e.health_check&&console.log(`${ge.yellow} Health check: ${e.health_check}${ge.reset}`),!await
|
|
622
|
+
${ge.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ge.reset}`)}if(e.deploy_script&&console.log(`${ge.yellow} Then run: ${e.deploy_script}${ge.reset}`),e.health_check&&console.log(`${ge.yellow} Health check: ${e.health_check}${ge.reset}`),!await En(" 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}:
|
|
623
623
|
${f}${e.deploy_script?`
|
|
624
624
|
${e.deploy_script}`:""}`;let{stdout:p,stderr:m,exitCode:g,error:w}=await Bt(s,f,{timeout:12e4});if(i=[p,m].filter(Boolean).join(`
|
|
625
625
|
`).trim(),g!==0)return`ERROR (git pull, exit ${g}):
|
|
@@ -643,7 +643,7 @@ Health check FAILED: ${u} \u2192 ${f.message}`,(o==="git"?"git pull OK":"rsync O
|
|
|
643
643
|
Health check FAILED (exit ${m}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
|
|
644
644
|
|
|
645
645
|
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}
|
|
646
|
-
${i}${a}${l}`.trim()}case"deployment_status":{let o=
|
|
646
|
+
${i}${a}${l}`.trim()}case"deployment_status":{let o=sR(),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=mn(a.server||i),u=(await Bt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await Bt(l,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let m=require("node-fetch"),g=await Promise.race([m(p),new Promise((w,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 Bt(l,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
|
|
647
647
|
${r.join(`
|
|
648
648
|
`)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(R,O=120)=>{try{let N=ae.isAbsolute(R)?R:ae.join(o,R),K=(await yt.readFile(N,"utf8")).split(`
|
|
649
649
|
`),V=K.slice(0,O).join(`
|
|
@@ -673,26 +673,26 @@ ${N}
|
|
|
673
673
|
${O}
|
|
674
674
|
\`\`\``):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(`
|
|
675
675
|
## STEP 4: Framework Stack
|
|
676
|
-
`);let k=[],T=await i(ae.join(o,"package.json"),999);if(T){if((T.includes('"react"')||T.includes("'react'"))&&k.push("React"),T.includes('"vue"')||T.includes("'vue'")){let O=T.match(/"vue":\s*"[\^~]?(\d+)/);k.push(O?`Vue.js v${O[1]}`:"Vue.js")}let R=T.match(/"alpinejs":\s*"[\^~]?(\d+)/);R&&k.push(`Alpine.js v${R[1]} (\u26A0 v2 vs v3 API differs!)`),(T.includes('"htmx')||T.includes("'htmx"))&&k.push("HTMX"),T.includes('"tailwindcss"')&&k.push("Tailwind CSS"),T.includes('"bootstrap"')&&k.push("Bootstrap")}if((await
|
|
676
|
+
`);let k=[],T=await i(ae.join(o,"package.json"),999);if(T){if((T.includes('"react"')||T.includes("'react'"))&&k.push("React"),T.includes('"vue"')||T.includes("'vue'")){let O=T.match(/"vue":\s*"[\^~]?(\d+)/);k.push(O?`Vue.js v${O[1]}`:"Vue.js")}let R=T.match(/"alpinejs":\s*"[\^~]?(\d+)/);R&&k.push(`Alpine.js v${R[1]} (\u26A0 v2 vs v3 API differs!)`),(T.includes('"htmx')||T.includes("'htmx"))&&k.push("HTMX"),T.includes('"tailwindcss"')&&k.push("Tailwind CSS"),T.includes('"bootstrap"')&&k.push("Bootstrap")}if((await Qt(ae.join(o,"manage.py"))||(await i(ae.join(o,"requirements.txt"),50)||"").includes("Django"))&&k.push("Django (server-rendered templates)"),!k.some(R=>R.includes("Alpine"))){let R=await u("alpinejs","*.html");if(R.length>0){let N=(await i(R[0],30)||"").match(/alpinejs[@/]v?(\d)/);k.push(N?`Alpine.js v${N[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return k.some(R=>R.includes("HTMX"))||(await u("htmx","*.html")).length>0&&k.push("HTMX (via CDN)"),k.length>0?(r.push(k.map(R=>`- ${R}`).join(`
|
|
677
677
|
`)),r.push(`
|
|
678
678
|
\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(`
|
|
679
679
|
---
|
|
680
680
|
\u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
|
|
681
|
-
`)}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=
|
|
681
|
+
`)}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=mn(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(o)try{let{stdout:u,stderr:d}=await mt(l,{timeout:c});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await Bt(s,l,{timeout:c}),m=[u,d].filter(Boolean).join(`
|
|
682
682
|
`).trim();return{out:p&&f!==0&&!u.trim()?(p+`
|
|
683
|
-
`+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
|
|
683
|
+
`+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 En(`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}
|
|
684
684
|
(no output)`}case"disk_usage":{let l=e.path||"/",c=We(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}
|
|
685
685
|
${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}
|
|
686
686
|
${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}
|
|
687
|
-
${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(
|
|
687
|
+
${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(bR))return"ERROR: package names contain unsafe characters";let d=u.map(We).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:w}=await r(g,6e4);return w||"(no output from package check)"}case"install":if(!d)return"ERROR: packages required for install";f=c==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=c==="dnf"?`dnf remove -y ${d}`:`apt-get remove -y ${d}`;break;case"update":if(!d)return"ERROR: packages required for update (use upgrade for full system upgrade)";f=c==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=c==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:p,exitCode:m}=await r(f,12e4);return m!==0?`EXIT ${m}
|
|
688
688
|
${p}`:p||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let l=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:c,exitCode:u}=await r(l,1e4);return u!==0?`EXIT ${u}
|
|
689
|
-
${c}`:c||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=
|
|
690
|
-
${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=
|
|
691
|
-
${f}`:f}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=
|
|
692
|
-
${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=
|
|
689
|
+
${c}`:c||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=zr(e.user);if(l)return l;let c=We(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}
|
|
690
|
+
${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=zr(e.user);if(l)return l;if(!(e.groups||[]).every(sb))return"ERROR: groups contain unsafe characters";let c=(e.groups||[]).map(m=>`-G ${We(m)}`).join(" "),u=We(e.user),d=`useradd -m ${c} ${u} && echo "User ${e.user} created"`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
|
|
691
|
+
${f}`:f}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=zr(e.user);if(l)return l;let u=`userdel -r ${We(e.user)} && echo "User ${e.user} deleted"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
692
|
+
${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=zr(e.user);if(l)return l;let u=`${`/home/${e.user}`}/.ssh`,d=`${u}/authorized_keys`,f=We(e.user),p=`mkdir -p ${We(u)} && chmod 700 ${We(u)} && printf '%s
|
|
693
693
|
' ${We(e.ssh_key)} >> ${We(d)} && chmod 600 ${We(d)} && chown -R ${We(`${e.user}:${e.user}`)} ${We(u)} && echo "SSH key added for ${e.user}"`,{out:m,exitCode:g}=await r(p,15e3);return g!==0?`EXIT ${g}
|
|
694
|
-
${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(!
|
|
695
|
-
${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=
|
|
694
|
+
${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(!ad(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 ${We(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(!ad(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 ${We(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(!ad(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 ${We(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}
|
|
695
|
+
${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=zr(e.user);if(c)return c}let l=e.user?`-u ${We(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
|
|
696
696
|
' ${We(c)}) | crontab ${l} - && echo "Cron entry added: ${c}"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
697
697
|
${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}
|
|
698
698
|
${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=`
|
|
@@ -721,11 +721,11 @@ fi
|
|
|
721
721
|
`.trim();let{out:c,exitCode:u}=await r(l,25e3),d=/notAfter=|Days until expiry:/i.test(c);return u!==0&&!d?`EXIT ${u}
|
|
722
722
|
${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} ${We(e.path)} 2>&1`,{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
|
|
723
723
|
${u}`:u||"(empty log)"}case"find_large":{let l=e.path||"/",c=e.limit||20,u=e.min_size||"100M",d=`find ${We(l)} -xdev -type f -size +${We(u)} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${c}`,{out:f,exitCode:p}=await r(d,6e4);return p!==0?`EXIT ${p}
|
|
724
|
-
${f}`:f||`(no files larger than ${u} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";if(e.service_name){let p=
|
|
725
|
-
${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(!
|
|
724
|
+
${f}`:f||`(no files larger than ${u} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";if(e.service_name){let p=ld(e.service_name,"service_name");if(p)return p}let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",c;switch(e.service_action){case"status":c=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":c="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":c=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":c=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":c=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":c=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":c=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":c=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(c,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
|
|
725
|
+
${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(!wR(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 ${We(e.process_name)} 2>/dev/null | head -5 && pkill -${l} ${We(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}
|
|
726
726
|
${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}
|
|
727
|
-
${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=
|
|
728
|
-
`)}function
|
|
727
|
+
${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=Ur(),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}=Ur();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=Ea(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function $R(t,e,n={}){let{emit:o}=Ea(),{logToolExecution:s}=qy(),r=Date.now(),i=n.silent?null:KT(t,e);if(!i){let l=await Xy(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 zT(i);a.start();try{let l=await Xy(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}}ob.exports={TOOL_DEFINITIONS:_R,executeTool:$R,resolvePath:Ct,autoFixPath:tl,autoFixEdit:nb,enrichBashError:tb,getNodeBuiltinInstallAttempt:Jy,cancelPendingAskUser:dR,setAskUserHandler:fR,fileExists:Qt}});var vr=ee((AM,ib)=>{ib.exports=rb()});var fd=ee((PM,lb)=>{var{loadServerProfiles:Wo,resolveProfile:OM,sshExec:kR}=No(),xR=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,SR=/\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,vR=/https?:\/\/[^\s)]+/gi;function ER(t){if(typeof t!="string")return[];let e=new Set,n=[];for(let o of t.match(vR)||[]){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 ab(t,e=Wo()){if(typeof t!="string"||!SR.test(t))return null;let n=ER(t).filter(o=>!xR.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 dd={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 RR(){let t=Wo();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&&dd[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 dd[s])n.push(`- ${i}`)}}return n.join(`
|
|
728
|
+
`)}function CR(t){let e=Wo();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function AR(){return Object.keys(Wo())}function OR(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(n,"utf-8")}catch{}let s=Wo(),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 p=s[f],m=p.user?`${p.user}@${p.host}`:p.host,g=p.port&&Number(p.port)!==22?`:${p.port}`:"";return` - **${f}**: ${m}${g}${p.os?` (${p.os})`:""}`}).join(`
|
|
729
729
|
`),u=r.map(f=>s[f].log_path).filter(Boolean),d=u.length>0?`
|
|
730
730
|
- Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
|
|
731
731
|
|
|
@@ -744,7 +744,7 @@ ${c}
|
|
|
744
744
|
- \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
|
|
745
745
|
- \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
|
|
746
746
|
|
|
747
|
-
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${
|
|
747
|
+
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${PR(s)}`}function PR(t){return Object.values(t).some(n=>n.host==="94.130.37.43")?`
|
|
748
748
|
|
|
749
749
|
## Server Debugging Rules
|
|
750
750
|
|
|
@@ -755,40 +755,40 @@ ${c}
|
|
|
755
755
|
- 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.
|
|
756
756
|
- 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.
|
|
757
757
|
- 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.
|
|
758
|
-
- 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
|
|
759
|
-
`+i.trim()}catch{return null}}
|
|
760
|
-
`)}catch{return""}}function
|
|
761
|
-
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function
|
|
762
|
-
`)}var
|
|
758
|
+
- 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 MR(t){let e=Wo(),n=ab(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 kR(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]
|
|
759
|
+
`+i.trim()}catch{return null}}lb.exports={getServerContext:RR,getDeploymentContextBlock:OR,hasServerOS:CR,getProfileNames:AR,probeUrlServer:MR,detectRuntimeDebugTarget:ab,OS_HINTS:dd}});var fb=ee((MM,db)=>{var At=require("fs").promises,sl=require("fs"),st=require("path"),Xr=require("util").promisify(require("child_process").exec),{C:Ho}=Et(),{getMergeConflicts:ub}=$a(),{getServerContext:NR}=fd(),{refreshIndex:LR,getFileIndex:IR,buildContentIndex:jR,summarizeModuleHubs:DR}=In(),qR=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),FR=[{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 BR(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 UR(t){let e=new Set(t),n=new Set;for(let o of FR)(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 WR(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 HR(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=st.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 LR(t);let e=IR();if(!e||e.length===0)return"";let n=UR(e),o=BR(e),s=WR(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=HR(e),a=[];try{let d=st.join(t,"package.json");if(sl.existsSync(d)){let f=JSON.parse(sl.readFileSync(d,"utf-8"));a=GR(f)}}catch{}let l="",c="";try{let d=await jR(t),f=Object.entries(d.files||{}).map(([p,m])=>({file:p,defs:Array.isArray(m.defs)?m.defs.length:0})).filter(p=>p.defs>0).sort((p,m)=>m.defs-p.defs||p.file.localeCompare(m.file)).slice(0,4).map(p=>`${p.file} (${p.defs} defs)`);f.length>0&&(l=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await DR(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(`
|
|
760
|
+
`)}catch{return""}}function zR(t){try{return sl.readFileSync(t,"utf-8").split(`
|
|
761
|
+
`).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 VR(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=st.join(t,".gitignore"),r=[...o,...zR(s)],i=0,a=[st.basename(t)+"/"];function l(c,u,d){if(d>e||i>=n)return;let f;try{f=sl.readdirSync(c,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let p=f.filter(m=>!(qR.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||KR(m.name,r)));for(let m=0;m<p.length;m++){if(i>=n){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=p[m],w=m===p.length-1,k=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",T=u+(w?" ":"\u2502 "),$=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${k}${$}`),i++,g.isDirectory()&&l(st.join(c,g.name),T,d+1)}}return l(t,"",1),a.join(`
|
|
762
|
+
`)}var pd=new Map,Yo=new Map,ol=null,cb=3e4,Go={result:null,expiry:0,cwd:null};async function gn(t){try{return await t()}catch{return null}}async function XR(){if(!ol||Date.now()>ol)return!1;let t=[st.join(process.cwd(),"package.json"),st.join(process.cwd(),"README.md"),st.join(process.cwd(),"AGENTS.md"),st.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await At.stat(e),o=Yo.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(Yo.has(e))return!1}try{let e=st.join(process.cwd(),".git","HEAD"),n=await At.stat(e),o=Yo.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function JR(){let t=[st.join(process.cwd(),"package.json"),st.join(process.cwd(),"README.md"),st.join(process.cwd(),"AGENTS.md"),st.join(process.cwd(),".gitignore"),st.join(process.cwd(),".git","HEAD"),st.join(process.cwd(),"CLAUDE.md"),st.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let n=await At.stat(e);Yo.set(e,n.mtimeMs)}catch{Yo.delete(e)}}async function ZR(t){let e="fileContext",n=pd.get(e),o=!1;if(n&&await XR()&&(o=!0),!o){let u=[],d=st.join(t,"package.json");if(await gn(()=>At.access(d).then(()=>!0).catch(()=>!1)))try{let K=await At.readFile(d,"utf-8"),V=JSON.parse(K),ie={name:V.name,version:V.version};if(V.scripts&&(ie.scripts=Object.keys(V.scripts).slice(0,15)),V.dependencies&&(ie.deps=Object.keys(V.dependencies).length),V.devDependencies&&(ie.devDeps=Object.keys(V.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(ie)}`),V.scripts){let J=["test","build","lint","typecheck","check","benchmark:gate","benchmark"].filter(ne=>V.scripts[ne]).map(ne=>`${ne}=${V.scripts[ne]}`).slice(0,8);J.length>0&&u.push(`AVAILABLE TOOL COMMANDS (use bash to run these):
|
|
763
763
|
${J.map(ne=>` npm run ${ne.split("=")[0]} # ${ne}`).join(`
|
|
764
|
-
`)}`)}}catch{}let p=st.join(t,"README.md");if(await
|
|
764
|
+
`)}`)}}catch{}let p=st.join(t,"README.md");if(await gn(()=>At.access(p).then(()=>!0).catch(()=>!1))){let V=(await At.readFile(p,"utf-8")).split(`
|
|
765
765
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
766
766
|
${V.join(`
|
|
767
|
-
`)}`)}let g=st.join(t,".gitignore");if(await
|
|
768
|
-
${K.trim()}`)}let k=st.join(t,"AGENTS.md");if(await
|
|
769
|
-
${K.trim()}`)}let $=st.join(t,"CLAUDE.md");if(await
|
|
770
|
-
${K.trim()}`)}let O=st.join(t,".nex","CLAUDE.md");if(await
|
|
771
|
-
${K.trim()}`)}let z=await
|
|
767
|
+
`)}`)}let g=st.join(t,".gitignore");if(await gn(()=>At.access(g).then(()=>!0).catch(()=>!1))){let K=await At.readFile(g,"utf-8");u.push(`GITIGNORE:
|
|
768
|
+
${K.trim()}`)}let k=st.join(t,"AGENTS.md");if(await gn(()=>At.access(k).then(()=>!0).catch(()=>!1))){let K=await At.readFile(k,"utf-8");K.trim()&&u.push(`PROJECT INSTRUCTIONS (AGENTS.md):
|
|
769
|
+
${K.trim()}`)}let $=st.join(t,"CLAUDE.md");if(await gn(()=>At.access($).then(()=>!0).catch(()=>!1))){let K=await At.readFile($,"utf-8");K.trim()&&u.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
|
|
770
|
+
${K.trim()}`)}let O=st.join(t,".nex","CLAUDE.md");if(await gn(()=>At.access(O).then(()=>!0).catch(()=>!1))){let K=await At.readFile(O,"utf-8");K.trim()&&u.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
|
|
771
|
+
${K.trim()}`)}let z=await YR(t);z&&u.push(z),n=u.join(`
|
|
772
772
|
|
|
773
|
-
`),
|
|
773
|
+
`),pd.set(e,n),ol=Date.now()+cb,await JR()}let s=[n],r,i,a,l,c;if(Go.result&&Date.now()<Go.expiry&&Go.cwd===t?{branch:r,status:i,log:a,diffStat:l,conflicts:c}=Go.result:([r,i,a,l,c]=await Promise.all([gn(async()=>{let{stdout:u}=await Xr("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),gn(async()=>{let{stdout:u}=await Xr("git status --short",{cwd:t,timeout:5e3});return u.trim()}),gn(async()=>{let{stdout:u}=await Xr("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),gn(async()=>{let{stdout:u}=await Xr("git diff --stat -- .",{cwd:t,timeout:5e3,maxBuffer:2e4});return u.trim()}),ub()]),Go={result:{branch:r,status:i,log:a,diffStat:l,conflicts:c},expiry:Date.now()+cb,cwd:t}),r&&s.push(`GIT BRANCH: ${r}`),i&&s.push(`GIT STATUS:
|
|
774
774
|
${i}`),l&&s.push(`GIT DIFF STAT:
|
|
775
775
|
${l}`),a&&s.push(`RECENT COMMITS:
|
|
776
776
|
${a}`),c&&c.length>0){let u=c.map(d=>` ${d.file}`).join(`
|
|
777
777
|
`);s.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
778
|
-
${u}`)}try{let u=
|
|
778
|
+
${u}`)}try{let u=NR();u&&s.push(u)}catch{}return s.join(`
|
|
779
779
|
|
|
780
|
-
`)}async function ZR(t){let e=st.join(t,"package.json"),n="";if(await hn(()=>At.access(e).then(()=>!0).catch(()=>!1)))try{let i=await At.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([hn(async()=>{let{stdout:i}=await Vr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),cb()]);if(r&&r.length>0){console.log(`${Ho.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ho.reset}`);for(let i of r)console.log(`${Ho.red} ${i.file}${Ho.reset}`);console.log(`${Ho.yellow} \u2192 Resolve conflicts before starting tasks${Ho.reset}`)}console.log()}ub.exports={gatherProjectContext:JR,printContext:ZR,generateFileTree:KR,_clearContextCache:()=>{dd.clear(),Yo.clear(),nl=null,Go={result:null,expiry:0,cwd:null}}}});var ol=ee((MM,hb)=>{var En=require("fs"),sl=require("path"),{atomicWrite:QR}=Ds();function Jr(){return sl.join(process.cwd(),".nex","sessions")}function fd(){let t=Jr();En.existsSync(t)||En.mkdirSync(t,{recursive:!0,mode:448})}function pd(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return sl.join(Jr(),`${e}.json`)}function hd(t,e,n={}){fd();let o=pd(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 QR(o,JSON.stringify(s,null,2)),{path:o,name:t}}function fb(t){let e=pd(t);if(!En.existsSync(e))return null;try{return JSON.parse(En.readFileSync(e,"utf-8"))}catch{return null}}function pb(){fd();let t=Jr(),e=En.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(En.readFileSync(sl.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 e1(t){let e=pd(t);return En.existsSync(e)?(En.unlinkSync(e),!0):!1}function t1(){let t=pb();return t.length===0?null:fb(t[0].name)}var bs=null,rs=null,Xr=null;function n1(t,e={}){t.length!==0&&(bs&&clearTimeout(bs),rs=t,Xr=e||{},bs=setTimeout(()=>{rs&&rs.length>0&&hd("_autosave",rs,Xr),bs=null,rs=null,Xr=null},5e3),bs.unref?.())}function s1(){bs&&(clearTimeout(bs),bs=null),rs&&rs.length>0&&(hd("_autosave",rs,Xr),rs=null,Xr=null)}function o1(){fd();let t=Jr(),e=En.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=sl.join(t,r);try{let a=En.statSync(i);new Date(a.mtime)<o&&(En.unlinkSync(i),s++)}catch{}}return s}hb.exports={saveSession:hd,loadSession:fb,listSessions:pb,deleteSession:e1,getLastSession:t1,autoSave:n1,flushAutoSave:s1,clearOldSessions:o1,_getSessionsDir:Jr}});var xb=ee((NM,kb)=>{"use strict";var Zr=require("fs"),mb=require("path");function gb(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 r1(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 yb(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 bb(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 wb(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 _b(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 $b(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=gb(t),s=yb(t),r=o.length,i=r1(t),a=o.filter(E=>!E.id||!i.has(E.id));t.some(E=>E.role==="user"&&typeof E.content=="string"&&E.content.startsWith("[SYSTEM WARNING]")&&(E.content.includes("edited")||E.content.includes("bash command")||E.content.includes("grep pattern")||E.content.includes("re-read")||E.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(E=>{let _=E.input?.command||E.input?.cmd||"";return/\bsed\s+-n\b/.test(_)});if(c){let E=(c.input?.command||c.input?.cmd||"").slice(0,80);s.some(W=>W.content.includes("BLOCKED: sed -n is forbidden")||W.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${E}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${E}`))}o.find(E=>{if(E.name!=="grep"&&E.name!=="bash"&&E.name!=="ssh_exec")return!1;let _=E.input?.command||E.input?.cmd||"",W=E.input?.pattern||"",se=`${_} ${W}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(se)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(se)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let d=t.some(E=>E.role==="assistant"),f=bb(t),m=wb(t,3).some(E=>E.length>100&&!/^[^.!]{0,40}\?$/.test(E));if(d&&!m&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let E=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: ${E}`)}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(E=>{let _=typeof E.content=="string"?E.content:Array.isArray(E.content)?E.content.map(W=>typeof W=="string"?W:W.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(_)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let k=_b(a),T=0,$="";for(let[E,_]of k)_>T&&(T=_,$=E);if(T>=3){let[E]=$.split("|");e-=1,n.push(`Same tool call repeated ${T}\xD7 (tool: ${E})`)}let R=!1,O=t.findIndex(E=>E.role==="user"&&typeof E.content=="string"&&E.content.includes("[SYSTEM STOP]")&&E.content.includes('"valid":true'));O>=0&&o.filter(_=>_.index>O).length>0&&(R=!0),R&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let N=o.filter(E=>E.name==="ssh_exec");if(N.length>=8){let E=0,_=1;for(let W=1;W<N.length;W++)N[W].index<=N[W-1].index+2?_++:(E=Math.max(E,_),_=1);E=Math.max(E,_),E>=8&&(e-=.5,n.push(`SSH reconnect storm: ${E} consecutive SSH calls`))}d&&N.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let z=new Map;for(let E of a)if(E.name==="read_file"&&E.input?.path){let _=E.input.path;z.has(_)||z.set(_,{count:0,ranges:[]});let W=z.get(_);if(W.count++,E.input.line_start!=null){let se=E.input.line_start||1,te=E.input.line_end||se+350;W.ranges.push([se,te])}}function K(E,_,W){for(let[se,te]of W){let P=Math.max(E,se),pe=Math.min(_,te);if(pe>P){let Xe=pe-P,_e=_-E||1;if(Xe/_e>=.7)return!0}}return!1}let V=0,ie="";for(let[E,_]of z){if(_.count<3)continue;if(_.ranges.length===_.count){let te=!1,P=[];for(let[pe,Xe]of _.ranges){if(P.length>0&&K(pe,Xe,P)){te=!0;break}P.push([pe,Xe])}if(!te)continue}if(_.count-_.ranges.length<=2&&_.ranges.length>=1){let te=!1,P=[];for(let[pe,Xe]of _.ranges){if(P.length>0&&K(pe,Xe,P)){te=!0;break}P.push([pe,Xe])}if(!te)continue}_.count>V&&(V=_.count,ie=E)}if(V>=3){e-=1;let E=ie.split("/").slice(-2).join("/");n.push(`read_file loop: "${E}" read ${V}\xD7 (file already in context)`)}let J=0,ne="";for(let[E,_]of z){if(_.ranges.length<4)continue;let W=[],se=!1;for(let[te,P]of _.ranges){if(W.length>0&&K(te,P,W)){se=!0;break}W.push([te,P])}!se&&_.ranges.length>J&&(J=_.ranges.length,ne=E)}if(J>=4){e-=.5;let E=ne.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${E}" read in ${J} sequential sections \u2014 use grep instead`)}let Ke=new Map;for(let E of a)if(E.name==="grep"&&E.input?.path&&E.input?.pattern){let _=E.input.path;Ke.has(_)||Ke.set(_,new Set),Ke.get(_).add(E.input.pattern)}let ve=0,H="";for(let[E,_]of Ke)E.split("/").pop().includes(".")&&_.size>ve&&(ve=_.size,H=E);if(ve>=3){e-=.75;let E=H.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${E}" searched ${ve}\xD7 with different patterns (file already in context)`)}{let E=new Set,_=new Set,W=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let te of o){if(te.name==="write_file"&&te.input?.path){let P=te.input.path.split("/").pop(),pe=te.input.path.includes("/tests/");W.test(P)&&!pe&&E.add(te.input.path)}if((te.name==="bash"||te.name==="ssh_exec")&&te.input?.command){let P=te.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(P)for(let pe of P){let Xe=pe.split(/\s+/),_e=Xe[Xe.length-1];for(let tt of E)(tt.endsWith(_e)||_e.endsWith(tt.split("/").pop()))&&_.add(tt)}}}let se=_.size;if(se>=1){let te=Math.min(se*.25,.5);e-=te;let P=[..._].map(pe=>pe.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${P} \u2014 write inline logic or use tests/ instead`)}}let oe=s.filter(E=>E.content.startsWith("EXIT")).length;oe>=10?(e-=1,n.push(`Bash exit-error storm: ${oe} tool results started with EXIT (repeated failing commands)`)):oe>=5&&(e-=.5,n.push(`Repeated bash errors: ${oe} tool results with non-zero exit code`));for(let E of t){if(E.role!=="assistant")continue;let _="";if(typeof E.content=="string"?_=E.content:Array.isArray(E.content)&&(_=E.content.filter(_e=>_e&&(_e.type==="text"||typeof _e=="string")).map(_e=>typeof _e=="string"?_e:_e.text||"").join("")),_.length<=5e3)continue;let W=_.split(/(?<=\. )/).filter(_e=>_e.trim().length>0);if(W.length<6)continue;let se=new Map;for(let _e=0;_e<=W.length-3;_e++){let tt=W.slice(_e,_e+3).join("").trim();tt.length>30&&se.set(tt,(se.get(tt)||0)+1)}let te=0,P="";for(let[_e,tt]of se)tt>te&&(te=tt,P=_e);if(te<3)continue;let Xe=P.length*te/_.length;if(Xe>=.4||te>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${te}\xD7 same paragraph, ${Math.round(Xe*100)}% repeated)`);break}}{let E=new Set(["read_file","list_directory","search_files","glob","grep"]),_=t.some(se=>Array.isArray(se.tool_calls)?se.tool_calls.some(te=>E.has(te.function?.name)):Array.isArray(se.content)?se.content.some(te=>te.type==="tool_use"&&E.has(te.name)):!1);t.some(se=>se.role==="assistant"&&typeof se.content=="string"&&(se.content.includes("## Steps")||se.content.includes("/plan approve")))&&!_&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let et=s.filter(E=>E.content.startsWith("BLOCKED:")&&!E.content.includes("BLOCKED: sed -n")&&!E.content.includes("SSH paused")&&!E.content.includes("SSH temporarily paused"));if(et.length>0){let E=Math.min(et.length*.5,1.5);e-=E,n.push(`${et.length} tool call${et.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Ve=t.filter(E=>{let _=typeof E.content=="string"?E.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(_)}).length;if(Ve>0){let E=Math.min(Ve*1,2);e-=E,n.push(`Super-nuclear context wipe fired ${Ve}\xD7 (context collapse \u2014 task too large or read loops)`)}{let E=!1,_=!1,W=!1;for(let te of o){if(te.name!=="bash")continue;let P=(te.input?.command||te.input?.cmd||"").trim();!(/cat\s*>/.test(P)||/<</.test(P))&&/\bcat\s+\S/.test(P)&&(E=!0),/^\s*ls(\s|$)/.test(P)&&!/npm|yarn|pnpm|make|git\b/.test(P)&&(_=!0),/\bfind\s+\S/.test(P)&&!/git\b|npm\b|-exec\b/.test(P)&&(W=!0)}let se=[E,_,W].filter(Boolean).length;if(se>0){let te=Math.min(se*.25,.75);e-=te;let P=[];E&&P.push("cat (use read_file)"),_&&P.push("ls (use list_directory)"),W&&P.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${P.join(", ")}`)}}{let E=o.some(P=>(P.name==="write_file"||P.name==="Write")&&P.input?.path&&(P.input.path.endsWith("requirements.txt")||P.input.path.endsWith("Pipfile")||P.input.path.endsWith("pyproject.toml"))),_=o.some(P=>(P.name==="write_file"||P.name==="Write")&&P.input?.path&&P.input.path.endsWith("package.json")),W=o.filter(P=>(P.name==="bash"||P.name==="Bash")&&P.input?.command).map(P=>P.input.command),se=W.some(P=>/pip\s+install|python\s+-m\s+venv/.test(P)),te=W.some(P=>/npm\s+install/.test(P));E&&!se?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):_&&!te&&o.some(pe=>(pe.name==="write_file"||pe.name==="Write")&&pe.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(pe.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let E=t.find(P=>P.role==="assistant"),_="";E&&(typeof E.content=="string"?_=E.content:Array.isArray(E.content)&&(_=E.content.filter(P=>P&&(P.type==="text"||typeof P=="string")).map(P=>typeof P=="string"?P:P.text||"").join("")));let W=_.slice(0,400),se=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,te=W.split(`
|
|
780
|
+
`)}async function QR(t){let e=st.join(t,"package.json"),n="";if(await gn(()=>At.access(e).then(()=>!0).catch(()=>!1)))try{let i=await At.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([gn(async()=>{let{stdout:i}=await Xr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),ub()]);if(r&&r.length>0){console.log(`${Ho.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ho.reset}`);for(let i of r)console.log(`${Ho.red} ${i.file}${Ho.reset}`);console.log(`${Ho.yellow} \u2192 Resolve conflicts before starting tasks${Ho.reset}`)}console.log()}db.exports={gatherProjectContext:ZR,printContext:QR,generateFileTree:VR,_clearContextCache:()=>{pd.clear(),Yo.clear(),ol=null,Go={result:null,expiry:0,cwd:null}}}});var il=ee((NM,mb)=>{var Rn=require("fs"),rl=require("path"),{atomicWrite:e1}=Ds();function Zr(){return rl.join(process.cwd(),".nex","sessions")}function hd(){let t=Zr();Rn.existsSync(t)||Rn.mkdirSync(t,{recursive:!0,mode:448})}function md(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return rl.join(Zr(),`${e}.json`)}function gd(t,e,n={}){hd();let o=md(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 e1(o,JSON.stringify(s,null,2)),{path:o,name:t}}function pb(t){let e=md(t);if(!Rn.existsSync(e))return null;try{return JSON.parse(Rn.readFileSync(e,"utf-8"))}catch{return null}}function hb(){hd();let t=Zr(),e=Rn.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(Rn.readFileSync(rl.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 t1(t){let e=md(t);return Rn.existsSync(e)?(Rn.unlinkSync(e),!0):!1}function n1(){let t=hb();return t.length===0?null:pb(t[0].name)}var bs=null,rs=null,Jr=null;function s1(t,e={}){t.length!==0&&(bs&&clearTimeout(bs),rs=t,Jr=e||{},bs=setTimeout(()=>{rs&&rs.length>0&&gd("_autosave",rs,Jr),bs=null,rs=null,Jr=null},5e3),bs.unref?.())}function o1(){bs&&(clearTimeout(bs),bs=null),rs&&rs.length>0&&(gd("_autosave",rs,Jr),rs=null,Jr=null)}function r1(){hd();let t=Zr(),e=Rn.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=rl.join(t,r);try{let a=Rn.statSync(i);new Date(a.mtime)<o&&(Rn.unlinkSync(i),s++)}catch{}}return s}mb.exports={saveSession:gd,loadSession:pb,listSessions:hb,deleteSession:t1,getLastSession:n1,autoSave:s1,flushAutoSave:o1,clearOldSessions:r1,_getSessionsDir:Zr}});var Sb=ee((LM,xb)=>{"use strict";var Qr=require("fs"),gb=require("path");function yb(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 i1(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 bb(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 wb(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 _b(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 $b(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 kb(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=yb(t),s=bb(t),r=o.length,i=i1(t),a=o.filter(E=>!E.id||!i.has(E.id));t.some(E=>E.role==="user"&&typeof E.content=="string"&&E.content.startsWith("[SYSTEM WARNING]")&&(E.content.includes("edited")||E.content.includes("bash command")||E.content.includes("grep pattern")||E.content.includes("re-read")||E.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(E=>{let _=E.input?.command||E.input?.cmd||"";return/\bsed\s+-n\b/.test(_)});if(c){let E=(c.input?.command||c.input?.cmd||"").slice(0,80);s.some(W=>W.content.includes("BLOCKED: sed -n is forbidden")||W.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${E}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${E}`))}o.find(E=>{if(E.name!=="grep"&&E.name!=="bash"&&E.name!=="ssh_exec")return!1;let _=E.input?.command||E.input?.cmd||"",W=E.input?.pattern||"",se=`${_} ${W}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(se)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(se)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let d=t.some(E=>E.role==="assistant"),f=wb(t),m=_b(t,3).some(E=>E.length>100&&!/^[^.!]{0,40}\?$/.test(E));if(d&&!m&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let E=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: ${E}`)}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(E=>{let _=typeof E.content=="string"?E.content:Array.isArray(E.content)?E.content.map(W=>typeof W=="string"?W:W.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(_)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let k=$b(a),T=0,$="";for(let[E,_]of k)_>T&&(T=_,$=E);if(T>=3){let[E]=$.split("|");e-=1,n.push(`Same tool call repeated ${T}\xD7 (tool: ${E})`)}let R=!1,O=t.findIndex(E=>E.role==="user"&&typeof E.content=="string"&&E.content.includes("[SYSTEM STOP]")&&E.content.includes('"valid":true'));O>=0&&o.filter(_=>_.index>O).length>0&&(R=!0),R&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let N=o.filter(E=>E.name==="ssh_exec");if(N.length>=8){let E=0,_=1;for(let W=1;W<N.length;W++)N[W].index<=N[W-1].index+2?_++:(E=Math.max(E,_),_=1);E=Math.max(E,_),E>=8&&(e-=.5,n.push(`SSH reconnect storm: ${E} consecutive SSH calls`))}d&&N.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let z=new Map;for(let E of a)if(E.name==="read_file"&&E.input?.path){let _=E.input.path;z.has(_)||z.set(_,{count:0,ranges:[]});let W=z.get(_);if(W.count++,E.input.line_start!=null){let se=E.input.line_start||1,te=E.input.line_end||se+350;W.ranges.push([se,te])}}function K(E,_,W){for(let[se,te]of W){let P=Math.max(E,se),pe=Math.min(_,te);if(pe>P){let Xe=pe-P,_e=_-E||1;if(Xe/_e>=.7)return!0}}return!1}let V=0,ie="";for(let[E,_]of z){if(_.count<3)continue;if(_.ranges.length===_.count){let te=!1,P=[];for(let[pe,Xe]of _.ranges){if(P.length>0&&K(pe,Xe,P)){te=!0;break}P.push([pe,Xe])}if(!te)continue}if(_.count-_.ranges.length<=2&&_.ranges.length>=1){let te=!1,P=[];for(let[pe,Xe]of _.ranges){if(P.length>0&&K(pe,Xe,P)){te=!0;break}P.push([pe,Xe])}if(!te)continue}_.count>V&&(V=_.count,ie=E)}if(V>=3){e-=1;let E=ie.split("/").slice(-2).join("/");n.push(`read_file loop: "${E}" read ${V}\xD7 (file already in context)`)}let J=0,ne="";for(let[E,_]of z){if(_.ranges.length<4)continue;let W=[],se=!1;for(let[te,P]of _.ranges){if(W.length>0&&K(te,P,W)){se=!0;break}W.push([te,P])}!se&&_.ranges.length>J&&(J=_.ranges.length,ne=E)}if(J>=4){e-=.5;let E=ne.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${E}" read in ${J} sequential sections \u2014 use grep instead`)}let Ke=new Map;for(let E of a)if(E.name==="grep"&&E.input?.path&&E.input?.pattern){let _=E.input.path;Ke.has(_)||Ke.set(_,new Set),Ke.get(_).add(E.input.pattern)}let ve=0,H="";for(let[E,_]of Ke)E.split("/").pop().includes(".")&&_.size>ve&&(ve=_.size,H=E);if(ve>=3){e-=.75;let E=H.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${E}" searched ${ve}\xD7 with different patterns (file already in context)`)}{let E=new Set,_=new Set,W=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let te of o){if(te.name==="write_file"&&te.input?.path){let P=te.input.path.split("/").pop(),pe=te.input.path.includes("/tests/");W.test(P)&&!pe&&E.add(te.input.path)}if((te.name==="bash"||te.name==="ssh_exec")&&te.input?.command){let P=te.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(P)for(let pe of P){let Xe=pe.split(/\s+/),_e=Xe[Xe.length-1];for(let tt of E)(tt.endsWith(_e)||_e.endsWith(tt.split("/").pop()))&&_.add(tt)}}}let se=_.size;if(se>=1){let te=Math.min(se*.25,.5);e-=te;let P=[..._].map(pe=>pe.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${P} \u2014 write inline logic or use tests/ instead`)}}let oe=s.filter(E=>E.content.startsWith("EXIT")).length;oe>=10?(e-=1,n.push(`Bash exit-error storm: ${oe} tool results started with EXIT (repeated failing commands)`)):oe>=5&&(e-=.5,n.push(`Repeated bash errors: ${oe} tool results with non-zero exit code`));for(let E of t){if(E.role!=="assistant")continue;let _="";if(typeof E.content=="string"?_=E.content:Array.isArray(E.content)&&(_=E.content.filter(_e=>_e&&(_e.type==="text"||typeof _e=="string")).map(_e=>typeof _e=="string"?_e:_e.text||"").join("")),_.length<=5e3)continue;let W=_.split(/(?<=\. )/).filter(_e=>_e.trim().length>0);if(W.length<6)continue;let se=new Map;for(let _e=0;_e<=W.length-3;_e++){let tt=W.slice(_e,_e+3).join("").trim();tt.length>30&&se.set(tt,(se.get(tt)||0)+1)}let te=0,P="";for(let[_e,tt]of se)tt>te&&(te=tt,P=_e);if(te<3)continue;let Xe=P.length*te/_.length;if(Xe>=.4||te>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${te}\xD7 same paragraph, ${Math.round(Xe*100)}% repeated)`);break}}{let E=new Set(["read_file","list_directory","search_files","glob","grep"]),_=t.some(se=>Array.isArray(se.tool_calls)?se.tool_calls.some(te=>E.has(te.function?.name)):Array.isArray(se.content)?se.content.some(te=>te.type==="tool_use"&&E.has(te.name)):!1);t.some(se=>se.role==="assistant"&&typeof se.content=="string"&&(se.content.includes("## Steps")||se.content.includes("/plan approve")))&&!_&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let et=s.filter(E=>E.content.startsWith("BLOCKED:")&&!E.content.includes("BLOCKED: sed -n")&&!E.content.includes("SSH paused")&&!E.content.includes("SSH temporarily paused"));if(et.length>0){let E=Math.min(et.length*.5,1.5);e-=E,n.push(`${et.length} tool call${et.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Ve=t.filter(E=>{let _=typeof E.content=="string"?E.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(_)}).length;if(Ve>0){let E=Math.min(Ve*1,2);e-=E,n.push(`Super-nuclear context wipe fired ${Ve}\xD7 (context collapse \u2014 task too large or read loops)`)}{let E=!1,_=!1,W=!1;for(let te of o){if(te.name!=="bash")continue;let P=(te.input?.command||te.input?.cmd||"").trim();!(/cat\s*>/.test(P)||/<</.test(P))&&/\bcat\s+\S/.test(P)&&(E=!0),/^\s*ls(\s|$)/.test(P)&&!/npm|yarn|pnpm|make|git\b/.test(P)&&(_=!0),/\bfind\s+\S/.test(P)&&!/git\b|npm\b|-exec\b/.test(P)&&(W=!0)}let se=[E,_,W].filter(Boolean).length;if(se>0){let te=Math.min(se*.25,.75);e-=te;let P=[];E&&P.push("cat (use read_file)"),_&&P.push("ls (use list_directory)"),W&&P.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${P.join(", ")}`)}}{let E=o.some(P=>(P.name==="write_file"||P.name==="Write")&&P.input?.path&&(P.input.path.endsWith("requirements.txt")||P.input.path.endsWith("Pipfile")||P.input.path.endsWith("pyproject.toml"))),_=o.some(P=>(P.name==="write_file"||P.name==="Write")&&P.input?.path&&P.input.path.endsWith("package.json")),W=o.filter(P=>(P.name==="bash"||P.name==="Bash")&&P.input?.command).map(P=>P.input.command),se=W.some(P=>/pip\s+install|python\s+-m\s+venv/.test(P)),te=W.some(P=>/npm\s+install/.test(P));E&&!se?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):_&&!te&&o.some(pe=>(pe.name==="write_file"||pe.name==="Write")&&pe.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(pe.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let E=t.find(P=>P.role==="assistant"),_="";E&&(typeof E.content=="string"?_=E.content:Array.isArray(E.content)&&(_=E.content.filter(P=>P&&(P.type==="text"||typeof P=="string")).map(P=>typeof P=="string"?P:P.text||"").join("")));let W=_.slice(0,400),se=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,te=W.split(`
|
|
781
781
|
`).find(P=>{let pe=P.trim();return pe.length>0&&pe.length<=30&&/^\d/.test(pe)&&/=/.test(pe)&&!/[a-zA-Z]/.test(pe)});if(se.test(W)||te){e-=1.5;let P=(te||W.split(`
|
|
782
782
|
`)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${P}"`)}}if(d&&r>0){let E=t.findIndex(W=>W.role==="assistant"),_=t.findIndex(W=>!!(Array.isArray(W.tool_calls)&&W.tool_calls.length>0||Array.isArray(W.content)&&W.content.some(se=>se&&se.type==="tool_use")));if(E!==-1&&_!==-1&&E<_){let W=t[E],se="";typeof W.content=="string"?se=W.content:Array.isArray(W.content)&&(se=W.content.filter(pe=>pe&&(pe.type==="text"||typeof pe=="string")).map(pe=>typeof pe=="string"?pe:pe.text||"").join(""));let te=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(se),P=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(se);(te||P)&&(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 E=f;if(E.length>100){let W=(E.match(/^```/gm)||[]).length%2!==0,se=/"\s*:\s*$/.test(E.trimEnd()),te=/[,\[{]\s*$/.test(E.trimEnd());(W||se||te)&&(e-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let E=[];t.forEach((W,se)=>{let te=[];Array.isArray(W.tool_calls)&&W.tool_calls.forEach(P=>{if((P.function?.name||P.name||"")==="read_file"){let Xe={};try{Xe=typeof P.function?.arguments=="string"?JSON.parse(P.function.arguments):P.function?.arguments||{}}catch{}(Xe.path||"").endsWith(".json")&&te.push({id:P.id,path:Xe.path})}}),Array.isArray(W.content)&&W.content.forEach(P=>{P&&P.type==="tool_use"&&P.name==="read_file"&&(P.input?.path||"").endsWith(".json")&&te.push({id:P.id,path:P.input.path})}),te.forEach(P=>E.push({...P,msgIdx:se}))});let _=0;for(let W of E){let se=null;for(let P of t){if(P.role==="tool"&&P.tool_call_id===W.id&&typeof P.content=="string"){se=P.content;break}if(P.role==="user"&&Array.isArray(P.content)){let pe=P.content.find(Xe=>Xe&&Xe.type==="tool_result"&&Xe.tool_use_id===W.id);if(pe){se=typeof pe.content=="string"?pe.content:"";break}}}if(!se)continue;se.split(`
|
|
783
|
-
`).filter(P=>P.trim()).length<5&&/^\s*\[/.test(se)&&!/\]\s*$/.test(se.trimEnd())&&_++}_>=1&&(e-=.75,n.push(`Shallow JSON read: ${_} .json file${_>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let E=s.filter(_=>/argument errors?/i.test(_.content)||/missing required (argument|parameter)/i.test(_.content)||/invalid argument/i.test(_.content));E.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${E.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):E.length>=2&&(e-=.25,n.push(`Tool argument errors: ${E.length} tool calls returned argument errors`))}{let E=!1,_=0,W=0;for(let se of a){if((se.name==="bash"||se.name==="Bash")&&se.input?.command&&/git\s+commit\b/.test(se.input.command)){E&&(W=Math.max(W,_)),E=!0,_=0;continue}E&&(se.name==="bash"||se.name==="Bash")&&se.input?.command&&/git\s+(status|diff|log|show)\b/.test(se.input.command)&&_++}W=Math.max(W,_),W>=3&&(e-=.75,n.push(`Post-commit verification waste: ${W} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Ce=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Ae=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:Ce,issues:n,summary:Ae}}function
|
|
783
|
+
`).filter(P=>P.trim()).length<5&&/^\s*\[/.test(se)&&!/\]\s*$/.test(se.trimEnd())&&_++}_>=1&&(e-=.75,n.push(`Shallow JSON read: ${_} .json file${_>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let E=s.filter(_=>/argument errors?/i.test(_.content)||/missing required (argument|parameter)/i.test(_.content)||/invalid argument/i.test(_.content));E.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${E.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):E.length>=2&&(e-=.25,n.push(`Tool argument errors: ${E.length} tool calls returned argument errors`))}{let E=!1,_=0,W=0;for(let se of a){if((se.name==="bash"||se.name==="Bash")&&se.input?.command&&/git\s+commit\b/.test(se.input.command)){E&&(W=Math.max(W,_)),E=!0,_=0;continue}E&&(se.name==="bash"||se.name==="Bash")&&se.input?.command&&/git\s+(status|diff|log|show)\b/.test(se.input.command)&&_++}W=Math.max(W,_),W>=3&&(e-=.75,n.push(`Post-commit verification waste: ${W} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Ce=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Ae=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:Ce,issues:n,summary:Ae}}function a1(t){try{let{loadSession:e}=il(),n=e(t);return n?kb(n.messages||[]):null}catch{return null}}function l1(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})`),`
|
|
784
784
|
${s}${f}${r}`}let l="";for(let u of a.slice(0,4))l+=`
|
|
785
785
|
${i}\u26A0${r} ${s}${u}${r}`;let c=a.length-4;return c>0&&(l+=`
|
|
786
|
-
${s}(+${c} more)${r}`),l}function
|
|
786
|
+
${s}(+${c} more)${r}`),l}function c1(t,e={}){try{let n=gb.join(process.cwd(),".nex");Qr.existsSync(n)||Qr.mkdirSync(n,{recursive:!0});let o=gb.join(n,"benchmark-history.json"),s=[];if(Qr.existsSync(o))try{s=JSON.parse(Qr.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)),Qr.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}xb.exports={scoreMessages:kb,scoreSession:a1,formatScore:l1,appendScoreHistory:c1,_extractToolCalls:yb,_extractToolResults:bb,_getLastAssistantText:wb,_getLastNAssistantTexts:_b,_countDuplicateToolCalls:$b}});var ni=ee((IM,Cb)=>{"use strict";var u1=require("os"),yd=require("path"),ws=require("fs"),ei=yd.join(u1.homedir(),".nex-code","model-routing.json"),al={"bug-fix":{id:"bug-fix",label:"Bug Fix",icon:"\u{1F41B}",envVar:"NEX_ROUTE_BUG_FIX",pattern:/\b(bug|crash|broken|fail|patch|stack\s*trace|typeerror|referenceerror|syntaxerror|unhandled|throw|throws|exception|root\s*cause|debug\s+(?:the\s+)?(?:stack|trace|issue|error)|resolve\s*(?:the|this)\s*(?:issue|bug|error|problem))\b/i},"feature-add":{id:"feature-add",label:"Feature",icon:"\u2728",envVar:"NEX_ROUTE_FEATURE",pattern:/\b(add|create|implement|build|scaffold|generate|new\s+feature|feature\s+request|enhancement|extend|introduce)\b/i},refactor:{id:"refactor",label:"Refactor",icon:"\u{1F527}",envVar:"NEX_ROUTE_REFACTOR",pattern:/\b(refactor|rewrite|restructure|reorgani[sz]e|clean\s*up|cleanup|simplify|extract\s+(?:function|method|class|component|module)|rename|move\s+(?:to|into)|split\s+(?:into|up)|consolidate|moderni[sz]e)\b/i},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}},vb=["agentic","frontend","sysadmin","data","bug-fix","feature-add","refactor","coding"];function d1(t){if(!t||t.length<8)return null;for(let e of vb){let n=al[e];if(!n.pattern||n.pattern.test(t))return n}return al.coding}function ti(){try{if(ws.existsSync(ei))return JSON.parse(ws.readFileSync(ei,"utf-8"))}catch{}return{}}function Eb(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=al[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:ti()[t]||null}var Tb={explore:10,plan:10,implement:35,verify:8},bd={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Rb(){let t=ti();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=Tt();if(e()==="ollama")return bd}catch{}return process.env.NEX_PHASE_ROUTING==="1"?bd:null}function f1(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let n=Rb();return n?.[t]?n[t]:e?Eb(e):null}function p1(t){return ti().phaseBudgets?.[t]||Tb[t]||20}function h1(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:Rb()!==null}function m1(t){let e=yd.dirname(ei);ws.existsSync(e)||ws.mkdirSync(e,{recursive:!0});let n=ti(),o={...n,...t};!t.phases&&n.phases&&(o.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(o.phaseBudgets=n.phaseBudgets),ws.writeFileSync(ei,JSON.stringify(o,null,2));try{let s=yd.join(e,".env"),r="";ws.existsSync(s)&&(r=ws.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)),ws.writeFileSync(s,i.filter(l=>l.trim()!=="").join(`
|
|
787
787
|
`)+`
|
|
788
|
-
`)}catch{}}
|
|
788
|
+
`)}catch{}}Cb.exports={CATEGORIES:al,DETECTION_ORDER:vb,detectCategory:d1,getModelForCategory:Eb,getModelForPhase:f1,getPhaseBudget:p1,isPhaseRoutingEnabled:h1,DEFAULT_PHASE_BUDGETS:Tb,BUILTIN_PHASE_DEFAULTS:bd,saveRoutingConfig:m1,loadRoutingConfig:ti,ROUTING_CONFIG_PATH:ei}});var Mb=ee((jM,Pb)=>{"use strict";var no=require("fs"),si=require("path"),g1=require("os"),{detectCategory:y1}=ni(),zo=si.join(g1.homedir(),".nex-code","examples"),wd=si.join(__dirname,"..","examples");function Ab(t){try{let n=no.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(`
|
|
789
789
|
A: |`);if(r===-1)return null;let i=n.slice(r+5),a=[],l=0;for(let u of i.split(`
|
|
790
790
|
`))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(`
|
|
791
|
-
`).trim();return{user:s,assistant:c}}catch{return null}}function
|
|
791
|
+
`).trim();return{user:s,assistant:c}}catch{return null}}function Ob(t){let e=`${t}.md`,n=si.join(zo,e);if(no.existsSync(n)){let s=Ab(n);if(s)return s}let o=si.join(wd,e);return no.existsSync(o)?Ab(o):null}function b1(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=y1(t);return!e||e.id==="coding"&&/\b(analy[sz]e|explain|describe|list|summari[sz]e|what is|how does|tell me about|review|audit)\b/i.test(t)?null:Ob(e.id)}function w1(){let t=new Set;for(let e of[zo,wd])try{for(let n of no.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function _1(t,e){no.existsSync(zo)||no.mkdirSync(zo,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
|
|
792
792
|
|
|
793
793
|
user: ${e.user}
|
|
794
794
|
|
|
@@ -796,14 +796,14 @@ A: |
|
|
|
796
796
|
${e.assistant.split(`
|
|
797
797
|
`).map(o=>` ${o}`).join(`
|
|
798
798
|
`)}
|
|
799
|
-
`;no.writeFileSync(
|
|
799
|
+
`;no.writeFileSync(si.join(zo,`${t}.md`),n,"utf-8")}Pb.exports={getFewShotForInput:b1,loadExampleForCategory:Ob,listAvailableExamples:w1,savePrivateExample:_1,PRIVATE_EXAMPLES_DIR:zo,BUNDLED_EXAMPLES_DIR:wd}});var qb=ee((qM,Db)=>{var en=require("fs"),Ko=require("path"),{C:DM}=Et(),{atomicWrite:$1,withFileLockSync:k1}=Ds(),ll={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"},Vo={...ll};function Nb(){let t=Ko.join(process.cwd(),".nex","config.json");if(en.existsSync(t))try{let e=JSON.parse(en.readFileSync(t,"utf-8"));e.permissions&&(Vo={...ll,...e.permissions})}catch{}}function x1(){let t=Ko.join(process.cwd(),".nex"),e=Ko.join(t,"config.json");en.existsSync(t)||en.mkdirSync(t,{recursive:!0}),k1(e,()=>{let n={};if(en.existsSync(e))try{n=JSON.parse(en.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=Vo,$1(e,JSON.stringify(n,null,2))})}function Lb(t){return Vo[t]||"ask"}function S1(t,e){return["allow","ask","deny"].includes(e)?(Vo[t]=e,!0):!1}function v1(t){return Lb(t)}function E1(){return Object.entries(Vo).map(([t,e])=>({tool:t,mode:e}))}function T1(){Vo={...ll}}var oi={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 Ib(){let t=Ko.join(process.cwd(),".nex","config.json");try{return en.existsSync(t)&&JSON.parse(en.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function R1(t){let e=Ko.join(process.cwd(),".nex"),n=Ko.join(e,"config.json");en.existsSync(e)||en.mkdirSync(e,{recursive:!0});let o={};try{en.existsSync(n)&&(o=JSON.parse(en.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,en.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function jb(){let t=Ib();if(!t)return oi.admin;let e=t.role||"admin",n=oi[e]||oi.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function C1(t){let e=jb();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 A1(){return Object.entries(oi).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}Nb();Db.exports={getPermission:Lb,setPermission:S1,checkPermission:v1,listPermissions:E1,loadPermissions:Nb,savePermissions:x1,resetPermissions:T1,DEFAULT_PERMISSIONS:ll,PERMISSION_PRESETS:oi,loadPresetConfig:Ib,savePresetConfig:R1,getEffectivePreset:jb,isToolAllowed:C1,listPresets:A1}});var dl=ee((BM,Hb)=>{var oo=require("fs"),cl=require("path"),FM=require("readline"),{C:ze}=Et(),He=null,$d=!1,kd=null,Fb=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function ul(){return cl.join(process.cwd(),".nex","plans")}function Bb(){let t=ul();oo.existsSync(t)||oo.mkdirSync(t,{recursive:!0})}function O1(t,e=[]){return He={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()},He}function P1(){return He}function M1(t){$d=t}function N1(){return $d}function L1(){return!He||He.status!=="draft"?!1:(He.status="approved",He.updatedAt=new Date().toISOString(),!0)}function I1(){return!He||He.status!=="approved"?!1:(He.status="executing",!0)}function _d(t,e){return!He||t<0||t>=He.steps.length?!1:(He.steps[t].status=e,He.updatedAt=new Date().toISOString(),He.steps.every(n=>n.status==="done"||n.status==="skipped")&&(He.status="completed"),!0)}function j1(t){if(!t)return`${ze.dim}No active plan${ze.reset}`;let e={draft:`${ze.yellow}DRAFT${ze.reset}`,approved:`${ze.green}APPROVED${ze.reset}`,executing:`${ze.blue}EXECUTING${ze.reset}`,completed:`${ze.green}COMPLETED${ze.reset}`},n=[];n.push(`
|
|
800
800
|
${ze.bold}${ze.cyan}Plan: ${t.task}${ze.reset}`),n.push(`${ze.dim}Status: ${e[t.status]||t.status}${ze.reset}
|
|
801
801
|
`);for(let o=0;o<t.steps.length;o++){let s=t.steps[o],r;switch(s.status){case"done":r=`${ze.green}\u2713${ze.reset}`;break;case"in_progress":r=`${ze.blue}\u2192${ze.reset}`;break;case"skipped":r=`${ze.dim}\u25CB${ze.reset}`;break;default:r=`${ze.dim} ${ze.reset}`}n.push(` ${r} ${ze.bold}Step ${o+1}:${ze.reset} ${s.description}`),s.files.length>0&&n.push(` ${ze.dim}Files: ${s.files.join(", ")}${ze.reset}`)}return n.push(""),n.join(`
|
|
802
|
-
`)}function
|
|
802
|
+
`)}function D1(t){if(t||(t=He),!t)return null;Bb();let e=cl.join(ul(),`${t.name}.json`);return oo.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function q1(t){let e=cl.join(ul(),`${t}.json`);if(!oo.existsSync(e))return null;try{let n=JSON.parse(oo.readFileSync(e,"utf-8"));return He=n,n}catch{return null}}function F1(){Bb();let t=ul(),e=oo.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(oo.readFileSync(cl.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 B1(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 U1(t){kd=t}function W1(){return kd}function H1(){He=null,$d=!1,kd=null,K1()}function G1(){return`
|
|
803
803
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
804
804
|
|
|
805
805
|
# Allowed Tools (read-only)
|
|
806
|
-
You may ONLY use these tools: ${[...
|
|
806
|
+
You may ONLY use these tools: ${[...Fb].join(", ")}
|
|
807
807
|
Any other tool call will be blocked and returned with an error.
|
|
808
808
|
|
|
809
809
|
# MANDATORY: Read Before You Plan
|
|
@@ -855,7 +855,7 @@ Bullet list of potential issues and mitigations.
|
|
|
855
855
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
856
856
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
857
857
|
- Do NOT make any file changes \u2014 your role is analysis and planning only.
|
|
858
|
-
- 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 so=0;function
|
|
858
|
+
- 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 so=0;function Y1(){!He||He.status!=="executing"||(so>0&&_d(so-1,"done"),so<He.steps.length&&(_d(so,"in_progress"),so++))}function z1(){if(!He||He.status!=="executing"||He.steps.length===0)return null;let t=Math.min(so,He.steps.length),e=He.steps.length,n=Math.max(0,t-1),o=He.steps[n]?.description||"";return{current:t,total:e,description:o}}function K1(){so=0}var Ub=["interactive","semi-auto","autonomous"],Wb="interactive";function V1(t){return Ub.includes(t)?(Wb=t,!0):!1}function X1(){return Wb}Hb.exports={createPlan:O1,getActivePlan:P1,setPlanMode:M1,isPlanMode:N1,approvePlan:L1,startExecution:I1,updateStep:_d,formatPlan:j1,savePlan:D1,loadPlan:q1,listPlans:F1,clearPlan:H1,getPlanModePrompt:G1,setPlanContent:U1,getPlanContent:W1,extractStepsFromText:B1,advancePlanStep:Y1,getPlanStepInfo:z1,PLAN_MODE_ALLOWED_TOOLS:Fb,setAutonomyLevel:V1,getAutonomyLevel:X1,AUTONOMY_LEVELS:Ub}});var Vb=ee((UM,Kb)=>{var{execSync:J1}=require("child_process"),xd=require("path"),ri=require("fs"),Sd=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Gb(){return xd.join(process.cwd(),".nex","hooks")}function Z1(){return xd.join(process.cwd(),".nex","config.json")}function Yb(){let t=Z1();if(!ri.existsSync(t))return{};try{return JSON.parse(ri.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function fl(t){if(!Sd.includes(t))return[];let e=[],n=Gb(),o=xd.join(n,t);ri.existsSync(o)&&e.push(o);let s=Yb();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function zb(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:J1(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 Q1(t,e={}){let n=fl(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=zb(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 eC(t){return fl(t).length>0}function tC(){let t=[];for(let e of Sd){let n=fl(e);n.length>0&&t.push({event:e,commands:n})}return t}function nC(){let t=Gb();return ri.existsSync(t)||ri.mkdirSync(t,{recursive:!0}),t}Kb.exports={HOOK_EVENTS:Sd,loadHookConfig:Yb,getHooksForEvent:fl,executeHook:zb,runHooks:Q1,hasHooks:eC,listHooks:tC,initHooksDir:nC}});var pl=ee((WM,Jb)=>{var ii={"devstral-2":{staleWarn:6e4,staleAbort:18e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
|
|
859
859
|
Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
|
|
860
860
|
You excel at sysadmin, frontend, and multi-step coding tasks.
|
|
861
861
|
Prefer action over narration \u2014 read, fix, verify, done.`},"devstral-small":{staleWarn:4e4,staleAbort:12e4,investigationCap:10,postEditCap:8,briefing:`You are devstral-small, a fast and lightweight coding model.
|
|
@@ -868,7 +868,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:4e4,staleAbort:12e4,
|
|
|
868
868
|
Prioritize decisive, targeted edits. Read only what you need, then fix.
|
|
869
869
|
Stay on-scope \u2014 your strength is focused, efficient coding tasks.`},"qwen3-vl":{staleWarn:12e4,staleAbort:3e5,investigationCap:15,postEditCap:12,briefing:`You are qwen3-vl, the highest-ranked model for data, frontend, and agentic tasks.
|
|
870
870
|
Trust your reasoning. Use tools thoroughly when the task demands it.
|
|
871
|
-
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},
|
|
871
|
+
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Xb={staleWarn:12e4,staleAbort:24e4,investigationCap:18,postEditCap:10};function sC(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let r of Object.keys(ii))e.startsWith(r)&&r.length>o&&(n=r,o=r.length);let s=n?{...ii[n]}:{...Xb};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 oC(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let s of Object.keys(ii))e.startsWith(s)&&s.length>o&&(n=s,o=s.length);return n&&ii[n].briefing||""}Jb.exports={getModelProfile:sC,getModelBriefing:oC,PROFILES:ii,DEFAULTS:Xb}});var Jo=ee((HM,Zb)=>{var{fork:rC}=require("child_process"),iC=require("path"),aC=iC.join(__dirname,"background-worker.js"),ro=new Map,Xo=new Map;function lC(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function cC(t){let e=lC(),n=rC(aC,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:e,agentDef:t}),n.on("message",o=>{o.type==="result"?vd(e,t,o.payload):o.type==="error"&&vd(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(ro.has(e)){let r=s?`killed (${s})`:`exit code ${o}`;vd(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),ro.set(e,{process:n,agentDef:t,startedAt:Date.now()}),e}function vd(t,e,n){ro.delete(t),Xo.set(t,{jobId:t,agentDef:e,result:n,finishedAt:Date.now()})}function uC(){if(Xo.size===0)return[];let t=[...Xo.values()];return Xo.clear(),t}function dC(){return ro.size>0||Xo.size>0}function fC(){let t=ro.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function pC(){for(let[t,e]of ro){try{e.process.kill("SIGTERM")}catch{}ro.delete(t)}Xo.clear()}Zb.exports={createJob:cC,getCompletedJobs:uC,getPendingJobSummary:fC,hasPendingOrCompletedJobs:dC,cancelAllJobs:pC}});var _w=ee((KM,ww)=>{"use strict";var{callWithRetry:tw,runSubAgent:Qb,clearAllLocks:hC}=nl(),{parseModelSpec:nw,getActiveProviderName:GM,getActiveModelId:YM}=Tt(),{detectCategory:mC,getModelForCategory:ew}=ni(),{MultiProgress:gC,C:xe}=Et(),{getModelBriefing:zM}=pl(),sw=parseInt(process.env.NEX_MAX_PARALLEL||"8",10),hl=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),ow="devstral-2:123b",rw="kimi-k2.5",iw=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
872
872
|
|
|
873
873
|
RULES:
|
|
874
874
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -883,7 +883,7 @@ RULES:
|
|
|
883
883
|
- If the request is simple (single goal), return an array with exactly 1 item.
|
|
884
884
|
|
|
885
885
|
USER REQUEST:
|
|
886
|
-
{prompt}`,
|
|
886
|
+
{prompt}`,aw=`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.
|
|
887
887
|
|
|
888
888
|
RULES:
|
|
889
889
|
- Output ONLY a JSON object with these fields:
|
|
@@ -899,23 +899,23 @@ ORIGINAL REQUEST:
|
|
|
899
899
|
{prompt}
|
|
900
900
|
|
|
901
901
|
SUB-AGENT RESULTS:
|
|
902
|
-
{results}`;async function
|
|
903
|
-
${e.slice(0,200)}`)}function
|
|
902
|
+
{results}`;async function lw(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 cw(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 yC(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=uw(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 uw(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 Ed(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:
|
|
903
|
+
${e.slice(0,200)}`)}function bC(){let t=require("fs"),e=require("path"),n=[];try{let o=process.cwd(),s=t.readdirSync(o,{withFileTypes:!0}),r=s.filter(l=>l.isDirectory()).map(l=>l.name),i=s.filter(l=>l.isFile()).map(l=>l.name);n.push(`Project root: ${o}`),n.push(`Top-level dirs: ${r.join(", ")||"(none)"}`),n.push(`Top-level files: ${i.join(", ")||"(none)"}`);let a=e.join(o,"package.json");if(t.existsSync(a)){let l=JSON.parse(t.readFileSync(a,"utf-8")),c=Object.keys(l.scripts||{}).slice(0,6);c.length&&n.push(`Scripts: ${c.join(", ")}`);let u=Object.keys(l.dependencies||{}).slice(0,8);u.length&&n.push(`Dependencies: ${u.join(", ")}`)}i.some(l=>/\.tsx?$/.test(l))?n.push("Language: TypeScript"):i.some(l=>/\.jsx?$/.test(l))&&n.push("Language: JavaScript"),i.some(l=>/\.py$/.test(l))&&n.push("Language: Python"),(r.includes("tests")||r.includes("test"))&&n.push("Test directory: found")}catch{}return n.length>1?`
|
|
904
904
|
## Project Structure Preview
|
|
905
905
|
${n.join(`
|
|
906
906
|
`)}
|
|
907
|
-
`:""}async function
|
|
907
|
+
`:""}async function dw(t,e,n={}){let o=n.maxSubTasks||hl,s=bC(),r=s?`${t}
|
|
908
908
|
|
|
909
909
|
${s}
|
|
910
|
-
Use the project structure above to scope sub-tasks to real files and directories. Do not invent paths or files that do not exist.`:t,a=[{role:"system",content:
|
|
910
|
+
Use the project structure above to scope sub-tasks to real files and directories. Do not invent paths or files that do not exist.`:t,a=[{role:"system",content:iw.replace("{maxSubTasks}",String(o)).replace("{prompt}",r)},{role:"user",content:t}],l={};if(e){let k=nw(e);k.provider&&(l.provider=k.provider),k.model&&(l.model=k.model)}let u=(await tw(a,[],l)).content||"",d=Ed(u);if(!Array.isArray(d))throw new Error(`Decompose returned non-array: ${typeof d}`);let f=10,m=d.slice(0,o).map((k,T)=>({id:k.id||`t${T+1}`,task:String(k.task||""),scope:Array.isArray(k.scope)?k.scope:[],estimatedCalls:typeof k.estimatedCalls=="number"?Math.min(k.estimatedCalls,f):8,priority:typeof k.priority=="number"?k.priority:T+1})).filter(k=>k.task.length>0),g=m.reduce((k,T)=>k+T.estimatedCalls,0),w=hl*f;if(g>w){let{debugLog:k}=Ic();k(`${Sn().T.yellow} \u26A0 Orchestrator: total estimated calls ${g} > ${w} \u2014 consider raising maxSubTasks${Sn().T.reset}`)}return m}async function fw(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((f,p)=>{let m=f.status==="done"?"SUCCESS":f.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${p+1} [${m}] ---
|
|
911
911
|
Task: ${f.task}
|
|
912
912
|
Result: ${f.result}
|
|
913
913
|
Tools: ${(f.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
914
914
|
|
|
915
|
-
`),r=[{role:"system",content:
|
|
915
|
+
`),r=[{role:"system",content:aw.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let f=nw(n);f.provider&&(i.provider=f.provider),f.model&&(i.model=f.model)}let l=(await tw(r,[],i)).content||"",c=Ed(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=pw(u,t);return d&&(u.commitMessage="",u.commitSuppressedReason=d),u}function pw(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 wC(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||rw,o=e.workerModel||ow,s=e.maxParallel||sw,r=e.maxSubTasks||hl,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
|
|
916
916
|
${xe.bold}Orchestrator${xe.reset} ${xe.dim}model: ${n} | workers: ${o} | max parallel: ${s}${xe.reset}
|
|
917
|
-
`),i("decomposing"),console.log(`${xe.dim}Phase 1: Decomposing prompt into sub-tasks...${xe.reset}`);let l;try{l=await
|
|
918
|
-
`);let u=Date.now(),d=
|
|
917
|
+
`),i("decomposing"),console.log(`${xe.dim}Phase 1: Decomposing prompt into sub-tasks...${xe.reset}`);let l;try{l=await dw(t,n,{maxSubTasks:r})}catch(H){return console.log(`${xe.red}Decompose failed: ${H.message}${xe.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${H.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${xe.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${xe.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${xe.green}Decomposed into ${l.length} sub-tasks:${xe.reset}`);for(let H of l){console.log(` ${xe.dim}${H.id}:${xe.reset} ${H.task}`);let oe=H.scope.filter(Boolean);oe.length>0&&console.log(` ${xe.dim}scope: ${oe.join(", ")}${xe.reset}`)}console.log("");let c=new Map;for(let H=0;H<l.length;H++)for(let oe of l[H].scope)oe&&!c.has(oe)&&c.set(oe,H);i("executing"),console.log(`${xe.dim}Phase 2: Running ${l.length} sub-agents (max ${s} parallel)...${xe.reset}
|
|
918
|
+
`);let u=Date.now(),d=cw(s),f={findings:[],_lock:!1},p=l.map(H=>{let oe=mC(H.task);return(oe?ew(oe.id):null)||o}),m=l.map((H,oe)=>{let et=`Agent ${oe+1} [${p[oe]}]: `,Ve=Math.max(20,60-et.length),Ce=H.task.substring(0,Ve)+(H.task.length>Ve?"...":"");return et+Ce}),g=new gC(m);g.start();let w=`
|
|
919
919
|
You are a focused coding agent executing ONE specific sub-task.
|
|
920
920
|
Your scope is limited to the files listed in your task definition.
|
|
921
921
|
|
|
@@ -939,24 +939,24 @@ RULES:
|
|
|
939
939
|
- Start with symbol-aware reads inside your scope: locate the target function/class/module, then read the exact section instead of scanning broadly.
|
|
940
940
|
- Before finishing, run the smallest relevant verification for your scope and report any residual risk explicitly.
|
|
941
941
|
- 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.
|
|
942
|
-
`,k=new Map;for(let H=0;H<l.length;H++){let oe=l[H].priority||1;k.has(oe)||k.set(oe,[]),k.get(oe).push({st:l[H],idx:H})}let T=[...k.keys()].sort((H,oe)=>H-oe),$=new Array(l.length),R=null;for(let H of T){let et=k.get(H).map(async({st:Ae,idx:E})=>{let _=await d();try{let W=await O(Ae,E,{acquire:d,subTaskModels:p,labels:m,progress:g,sharedContext:f,_fileOwnership:c,workerModel:o,WORKER_SYSTEM_PROMPT:w});return $[E]=W,W}finally{_()}}),Ce=(await Promise.all(et)).find(Ae=>
|
|
943
|
-
`),Ce=[...c.entries()].filter(([,_e])=>_e===oe).map(([_e])=>_e),Ae=[...c.entries()].filter(([,_e])=>_e!==oe).map(([_e])=>_e),E=
|
|
942
|
+
`,k=new Map;for(let H=0;H<l.length;H++){let oe=l[H].priority||1;k.has(oe)||k.set(oe,[]),k.get(oe).push({st:l[H],idx:H})}let T=[...k.keys()].sort((H,oe)=>H-oe),$=new Array(l.length),R=null;for(let H of T){let et=k.get(H).map(async({st:Ae,idx:E})=>{let _=await d();try{let W=await O(Ae,E,{acquire:d,subTaskModels:p,labels:m,progress:g,sharedContext:f,_fileOwnership:c,workerModel:o,WORKER_SYSTEM_PROMPT:w});return $[E]=W,W}finally{_()}}),Ce=(await Promise.all(et)).find(Ae=>gw(l[Ae?._idx],Ae,H,T));if(Ce){R={task:l[Ce._idx]?.task||Ce.task||"unknown task",result:Ce.result||""};break}}if(R)for(let H=0;H<$.length;H++)$[H]||($[H]={task:l[H].task,status:"skipped",result:`Skipped because prerequisite failed: ${R.task}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:l[H].scope,_idx:H});async function O(H,oe,et){try{let Ve=f.findings.filter(_e=>_e.agentId!==H.id).map(_e=>`Agent ${_e.agentId} found: ${_e.summary}`).join(`
|
|
943
|
+
`),Ce=[...c.entries()].filter(([,_e])=>_e===oe).map(([_e])=>_e),Ae=[...c.entries()].filter(([,_e])=>_e!==oe).map(([_e])=>_e),E=bw(H.task),_=[`Worker mode: ${E}`,Ve?`Prior agent findings:
|
|
944
944
|
${Ve}
|
|
945
|
-
`:"",H.scope.length>0?`Focus on files: ${H.scope.join(", ")}`:"",Ce.length>0?`You OWN these files (may read+write): ${Ce.join(", ")}`:"",Ae.length>0?`READ ONLY (owned by other agents, do NOT write): ${Ae.join(", ")}`:""].filter(Boolean),W=p[oe],se=process.env.NEX_FALLBACK_MODEL||
|
|
946
|
-
`)),te++;let tt=_e&&W!==se?se:W;return
|
|
947
|
-
`):void 0,max_iterations:Math.min(H.estimatedCalls||10,15),model:tt,_skipLog:!0,_systemPrompt:w,_readOnlyFiles:Ae},{onUpdate:
|
|
945
|
+
`:"",H.scope.length>0?`Focus on files: ${H.scope.join(", ")}`:"",Ce.length>0?`You OWN these files (may read+write): ${Ce.join(", ")}`:"",Ae.length>0?`READ ONLY (owned by other agents, do NOT write): ${Ae.join(", ")}`:""].filter(Boolean),W=p[oe],se=process.env.NEX_FALLBACK_MODEL||ew("agentic")||o,te=0,P=await lw(async()=>{let _e=te>0;_e&&(g.update(oe,"retry"),process.stderr.write(` ${xe.dim}[Agent ${oe+1}] retrying after error...${xe.reset}
|
|
946
|
+
`)),te++;let tt=_e&&W!==se?se:W;return Qb({task:H.task,type:E,context:_.length>0?_.join(`
|
|
947
|
+
`):void 0,max_iterations:Math.min(H.estimatedCalls||10,15),model:tt,_skipLog:!0,_systemPrompt:w,_readOnlyFiles:Ae},{onUpdate:ln=>{if(ln&&ln.type==="tool_call"&&process.stderr.isTTY){let kn=`Agent ${oe+1} [${tt}]`,_f=ln.tool||"...";g.labels[oe]=`${kn}: ${_f}`}}})},1,2e3),pe="";if(mw(E,P,H,Ce)){let _e=[...new Set([...Ce,...Array.isArray(P.filesModified)?P.filesModified:[],...Array.isArray(H.scope)?H.scope:[]])].filter(Boolean);try{g.labels[oe]=`Agent ${oe+1} [${W}] review`,g.update(oe,"retry");let tt=await Qb({task:`Review the completed changes for: ${H.task}`,type:"review",context:xC(H,P,_e),max_iterations:4,model:W,_skipLog:!0,_systemPrompt:w},{onUpdate:()=>{}},1);hw(tt.result)?(pe=`
|
|
948
948
|
|
|
949
949
|
Reviewer findings:
|
|
950
950
|
${tt.result}`,f.findings.push({agentId:`${H.id}-review`,summary:String(tt.result||"").slice(0,200),files:_e})):tt.result&&(pe=`
|
|
951
951
|
|
|
952
952
|
Reviewer: ${tt.result}`)}catch(tt){pe=`
|
|
953
953
|
|
|
954
|
-
Reviewer note: review pass failed (${tt.message})`}}let Xe=typeof P.result=="string"?`${P.result}${pe}`.slice(0,200):`${String(P.result||"")}${pe}`.slice(0,200);return f.findings.push({agentId:H.id,summary:Xe,files:Array.isArray(H.scope)?H.scope:[]}),g.labels[oe]=m[oe],g.update(oe,P.status==="failed"?"error":"done"),a.input+=P.tokensUsed?.input||0,a.output+=P.tokensUsed?.output||0,P.tokensUsed?._estimated&&(a._estimated=!0),{...P,result:`${String(P.result||"")}${pe}`,_scope:H.scope,_idx:oe}}catch(Ve){return g.labels[oe]=m[oe],g.update(oe,"error"),{task:H.task,status:"failed",result:`Error: ${Ve.message}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:H.scope,_idx:oe}}}let N;try{N=$}finally{g.stop({silent:!0}),
|
|
954
|
+
Reviewer note: review pass failed (${tt.message})`}}let Xe=typeof P.result=="string"?`${P.result}${pe}`.slice(0,200):`${String(P.result||"")}${pe}`.slice(0,200);return f.findings.push({agentId:H.id,summary:Xe,files:Array.isArray(H.scope)?H.scope:[]}),g.labels[oe]=m[oe],g.update(oe,P.status==="failed"?"error":"done"),a.input+=P.tokensUsed?.input||0,a.output+=P.tokensUsed?.output||0,P.tokensUsed?._estimated&&(a._estimated=!0),{...P,result:`${String(P.result||"")}${pe}`,_scope:H.scope,_idx:oe}}catch(Ve){return g.labels[oe]=m[oe],g.update(oe,"error"),{task:H.task,status:"failed",result:`Error: ${Ve.message}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:H.scope,_idx:oe}}}let N;try{N=$}finally{g.stop({silent:!0}),hC()}console.log("");let z=Math.round((Date.now()-u)/1e3),K=z>=60?`${Math.floor(z/60)}m ${z%60}s`:`${z}s`;for(let H=0;H<N.length;H++){let oe=N[H],Ve=oe.status==="done"||oe.status==="truncated"&&oe.result&&!oe.result.startsWith("Error")?`${xe.green}\u2713${xe.reset}`:`${xe.red}\u2717${xe.reset}`,Ce=oe._scope&&oe._scope.length>0?oe._scope.map(_=>_.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],Ae=Ce.length>0?Ce.join(", "):oe.task.substring(0,35)+(oe.task.length>35?"...":""),E=H===N.length-1;console.log(` ${Ve} Agent ${H+1} ${xe.dim}${Ae}${xe.reset}${E?` ${xe.dim}${K}${xe.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${xe.dim}Phase 3: Synthesizing results...${xe.reset}`);let V;if(R)V={summary:`Stopped before continuing because prerequisite sub-task failed: ${R.task}. ${R.result}`,conflicts:[],commitMessage:"",commitSuppressedReason:"prerequisite sub-task failed",filesChanged:[],resourcesChanged:[]};else try{V=await fw(N,t,n)}catch(H){console.log(`${xe.yellow}Synthesize failed: ${H.message} \u2014 using raw results.${xe.reset}`),V={summary:N.map(oe=>oe.result).join(`
|
|
955
955
|
`),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ie=f.findings.flatMap(H=>H.files),J=new Map;for(let H of ie)J.set(H,(J.get(H)||0)+1);let ne=[...J.values()].some(H=>H>1),Ke=f.findings.length>1&&ne?` ${xe.dim}(agents shared context)${xe.reset}`:"";if(console.log(`
|
|
956
956
|
${xe.bold}Summary:${xe.reset} ${V.summary}${Ke}`),V.conflicts.length>0){console.log(`${xe.yellow}Conflicts:${xe.reset}`);for(let H of V.conflicts)console.log(` - ${H}`)}V.commitMessage?console.log(`${xe.dim}Suggested commit: ${V.commitMessage}${xe.reset}`):V.commitSuppressedReason&&console.log(`${xe.yellow}No commit suggested:${xe.reset} ${V.commitSuppressedReason}`);let ve=a.input===0&&a.output===0?"n/a (provider does not report token counts)":a._estimated?`~${a.input} input / ~${a.output} output (est.)`:`${a.input} input + ${a.output} output`;return console.log(`${xe.dim}Tokens: ${ve}${xe.reset}
|
|
957
|
-
`),{results:N,synthesis:V,totalTokens:a}}var
|
|
958
|
-
`)}function
|
|
959
|
-
`),global._nexFooter&&global._nexFooter.setFileInfo({modified:t.filesModified?.size||0,scanned:t.filesRead?.size||0})}var
|
|
957
|
+
`),{results:N,synthesis:V,totalTokens:a}}var _C=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,$C=/\b(review|audit|verify|validate|inspect|critique)\b/i,kC=/\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 xC(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(`
|
|
958
|
+
`)}function hw(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function mw(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 gw(t,e,n,o){return SC(e)?yw(t)?!0:o.some(r=>r>n)&&n===o[0]:!1}function SC(t){return t&&(t.status==="failed"||t.status==="error"||t.status==="skipped")}function yw(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 bw(t){if(!t)return"implement";let e=_C.test(t),n=$C.test(t);return kC.test(t)?"implement":n?"review":e?"explore":"implement"}ww.exports={runOrchestrated:wC,decompose:dw,synthesize:fw,shouldSuppressCommit:pw,detectComplexPrompt:yC,detectCriticalPathPrompt:uw,extractJSON:Ed,createSemaphore:cw,DECOMPOSE_PROMPT:iw,SYNTHESIZE_PROMPT:aw,DEFAULT_ORCHESTRATOR_MODEL:rw,DEFAULT_WORKER_MODEL:ow,DEFAULT_MAX_PARALLEL:sw,DEFAULT_MAX_SUBTASKS:hl,withRetry:lw,_classifyWorkerType:bw,_hasMaterialReviewFindings:hw,_shouldRunFollowUpReview:mw,_shouldAbortAfterWave:gw,_isBlockingTask:yw}});var ud=ee((eN,d0)=>{var{C:h,Spinner:tr,TaskProgress:vC,formatToolCall:EC,formatToolSummary:vi,formatSectionHeader:ai,formatMilestone:TC,setActiveTaskProgress:VM,getThinkingVerb:Td,setActiveModelForSpinner:Rd}=Et(),{debugLog:M,warnLog:XM}=Ic(),{MilestoneTracker:RC}=ih(),{callStream:ml}=Tt(),{parseToolArgs:CC}=br(),{executeTool:af}=vr(),{gatherProjectContext:AC}=fb(),{fitToContext:OC,forceCompress:Bn,getUsage:Cn,estimateTokens:PC,buildProgressSnapshot:MC}=Fn(),{autoSave:NC,flushAutoSave:LC}=il(),{scoreMessages:IC,formatScore:jC,appendScoreHistory:DC}=Sb(),{detectCategory:qC,getModelForPhase:Bd,getPhaseBudget:_s,isPhaseRoutingEnabled:FC}=ni();function be(t){NC(t),LC()}function gl(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 Ud(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 Wd(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 BC(t){return!t||typeof t!="string"?!1:/^\s*(?:final\s+)?(?:summary|report|answer|result)\s*:/i.test(t)}function UC(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 Qe(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=IC(t);if(!n)return;console.log(jC(n,h));try{let{_getSessionsDir:o}=il(),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}=br(),s=kc();DC(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:HC}=Ur(),{getDeploymentContextBlock:GC,probeUrlServer:YC,detectRuntimeDebugTarget:$w}=fd(),{getFewShotForInput:zC}=Mb(),{checkPermission:KC,setPermission:VC,savePermissions:XC}=qb(),{confirm:Uw,setAllowAlwaysHandler:JC,getAutoConfirm:Kt}=_r(),{isPlanMode:fo,getPlanModePrompt:ZC,PLAN_MODE_ALLOWED_TOOLS:Ww,setPlanContent:QC,extractStepsFromText:eA,createPlan:tA,getActivePlan:JM,startExecution:ZM,advancePlanStep:nA,getPlanStepInfo:sA}=dl(),{StreamRenderer:oA}=Oc(),{runHooks:kw}=Vb(),{routeMCPCall:rA,getMCPToolDefinitions:iA}=eu(),{getSkillInstructions:aA,getSkillToolDefinitions:lA,routeSkillCall:cA,matchSkillTriggers:uA}=Zc(),{trackUsage:xw,estimateTokens:Sw,getSessionCosts:vw,getProviderCostMode:Ew}=aa();function Tw(t){return!t||typeof t!="string"?0:typeof Sw=="function"?Sw(t):Math.ceil(t.length/4)}var{validateToolArgs:dA}=su(),{filterToolsForModel:Rw,getModelTier:fA,PROVIDER_DEFAULT_TIER:QM}=Or(),{getConfiguredProviders:pA,getActiveProviderName:bn,getActiveModelId:on,setActiveModel:yl,MODEL_EQUIVALENTS:bi}=Tt(),{getModelProfile:hA,getModelBriefing:mA}=pl(),Be=require("fs"),Ge=require("path"),gA=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function yA(t){let e=TC(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
959
|
+
`),global._nexFooter&&global._nexFooter.setFileInfo({modified:t.filesModified?.size||0,scanned:t.filesRead?.size||0})}var Cw=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,Aw=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,bA=/\b(?:clipboard|pasteboard|clipboard screenshot)\b/i;function wA(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||""):Ge.resolve(o);Be.existsSync(s)&&e.push({raw:o,abs:s})}return e}function Hw(t){let e=[],n;for(Aw.lastIndex=0;(n=Aw.exec(t))!==null;)e.push(n[1].trim());return e}async function Gw(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]:_A(t);return{data:Buffer.from(n.data).toString("base64"),media_type:s}}catch{return null}}function _A(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 Yw(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=Ge.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&Be.existsSync(e)){let s=Be.readFileSync(e);if(s.length>100)return{data:s.toString("base64"),media_type:"image/png",path:e};try{Be.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let o=t("osascript",["-e",`try
|
|
960
960
|
set imgData to the clipboard as \xABclass PNGf\xBB
|
|
961
961
|
return "has_image"
|
|
962
962
|
on error
|
|
@@ -967,62 +967,62 @@ end try`],{timeout:3e3});if(o.stdout&&o.stdout.toString().trim()==="has_image"){
|
|
|
967
967
|
set fRef to open for access filePath with write permission
|
|
968
968
|
write imgData to fRef
|
|
969
969
|
close access fRef
|
|
970
|
-
`;if(t("osascript",["-e",s],{timeout:5e3}).status===0&&Be.existsSync(e)){let i=Be.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function
|
|
970
|
+
`;if(t("osascript",["-e",s],{timeout:5e3}).status===0&&Be.existsSync(e)){let i=Be.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function Ow(t){let e=Be.readFileSync(t),n=Ge.extname(t).toLowerCase().replace(".",""),o=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:o}}function zw(t){let e=wA(t),n=Hw(t),o=bA.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}=Ow(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}=Ow(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){M(`${h.yellow} \u26A0 Path resolution failed: ${a.message}${h.reset}`)}if(n.length>0){let i=await Promise.all(n.map(Gw));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=Yw();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
|
|
971
971
|
[Clipboard image attached: ${i.path}]`):r[0].text+=`
|
|
972
|
-
[No image found in clipboard]`}return r.length>1?r:t})()}var
|
|
972
|
+
[No image found in clipboard]`}return r.length>1?r:t})()}var $A=[/\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 Kw(t){return typeof t!="string"||!t?!1:$A.some(e=>e.test(t))}function kA(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=`
|
|
973
973
|
|
|
974
|
-
[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
|
|
974
|
+
[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 Hd(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
|
|
975
975
|
`),o=new Map;for(let p of n){let m=p.trim();m.length>=20&&o.set(m,(o.get(m)||0)+1)}let s=0,r="";for(let[p,m]of o)m>s&&(s=m,r=p);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=`
|
|
976
976
|
|
|
977
|
-
\u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let p=t.indexOf(r,d);if(p===-1)break;c++,u=p+r.length,d=p+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:s}}var
|
|
977
|
+
\u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let p=t.indexOf(r,d);if(p===-1)break;c++,u=p+r.length,d=p+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:s}}var Cd=null,Ad=null,Od=null;function zt(){if(Cd===null){let{TOOL_DEFINITIONS:t}=vr();Cd=t}return Ad===null&&(Ad=lA()),Od===null&&(Od=iA()),[...Cd,...Ad,...Od]}var kl=50;function xA(t){Number.isFinite(t)&&t>0&&(kl=t)}function Pd(t=bn()){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 Pw(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 xl=()=>null;function SA(t){xl=t}var ui=null,Gd=null,nr=null,sr="",or=0,Yd="",zd=0,Sl=new Map,vA=1e4,EA=6e3,TA=/\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 RA(t){return!t||typeof t!="string"?t:t.replace(TA,(e,n)=>`${n}=***REDACTED***`)}var CA=7e3,AA=4e3;function OA(t,e=null){let n=RA(t),o=PC(n),s=e==="read_file"?CA:vA,r=e==="read_file"?AA:EA;if(o>s)try{let{compressToolResult:i}=Fn();return i(n,r)}catch{return n}return n}function Vw(t){try{let{getActiveModel:e}=Tt(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(Sl.has(o))return Sl.get(o);let s=Rw(t);return Sl.set(o,s),s}catch{return Rw(t)}}function PA(){Sl.clear()}function MA(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 di={hash:null,ts:0},NA=3e4;async function Xw(){if(di.hash&&Date.now()-di.ts<NA)return di.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}=Ur(),a=i();a&&s.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Be.existsSync(i)){let a=await t.stat(i);s.push(`brain:${a.mtimeMs}`)}}catch{}let r=s.join("|");return di={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function vl(){ui=null,Gd=null,di={hash:null,ts:0},nr=null}var LA=new Set(["spawn_agents"]),Md=10,Nd=10,Ld=5,Mw=6e4,Id=12e4,Nw=process.env.NEX_STALE_AUTO_SWITCH!=="0";function IA(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{}}JC(t=>{VC(t,"allow"),XC(),console.log(`${h.green} \u2713 ${t}: always allow${h.reset}`)});async function jA(t){let e=t.function.name,n=e;if(typeof e=="string"&&e.includes(".")){let f=e.split(".").pop(),p={exec:"bash",find:"search_files",search:"search_files",grep_search:"grep",list:"list_directory",print_tree:"list_directory",read:"read_file",tree:"list_directory"};zt().some(g=>g.function.name===f)?n=f:p[f]&&(n=p[f])}let o=CC(t.function.arguments),s=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!o){let p=zt().find(g=>g.function.name===n),m=p?JSON.stringify(p.function.parameters,null,2):"unknown";return M(`${h.yellow} \u26A0 ${n}: malformed arguments, sending schema hint${h.reset}`),{callId:s,fnName:n,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
978
978
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
979
979
|
|
|
980
980
|
Expected JSON schema for "${n}":
|
|
981
981
|
${m}
|
|
982
982
|
|
|
983
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:s}}}if(o&&typeof o.path=="string")try{let f=require("os"),p=Ge.resolve(process.cwd(),o.path.replace(/^~/,f.homedir())),m=o.path;o.path=Ge.relative(process.cwd(),p)||".",Object.defineProperty(o,"_originalPath",{value:m,enumerable:!1})}catch(f){console.error("path resolution failed:",f.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=
|
|
984
|
-
`)[0]}${h.reset}`);let f=(
|
|
983
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:s}}}if(o&&typeof o.path=="string")try{let f=require("os"),p=Ge.resolve(process.cwd(),o.path.replace(/^~/,f.homedir())),m=o.path;o.path=Ge.relative(process.cwd(),p)||".",Object.defineProperty(o,"_originalPath",{value:m,enumerable:!1})}catch(f){console.error("path resolution failed:",f.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=dA(n,o);if(!r.valid){M(`${h.yellow} \u26A0 ${n}: ${r.error.split(`
|
|
984
|
+
`)[0]}${h.reset}`);let f=(Iw.get(n)||0)+1;Iw.set(n,f);let p=f>=2?`${r.error}
|
|
985
985
|
|
|
986
|
-
[SYSTEM: This is argument error #${f} 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:p,tool_call_id:s}}}let i=r.corrected||o;if(r.corrected){let f=Object.keys(o),p=Object.keys(r.corrected),m=f.filter(g=>!p.includes(g));m.length&&console.log(`${h.dim} \u2713 ${n}: corrected args (${m.join(", ")})${h.reset}`)}if(fo()&&!
|
|
986
|
+
[SYSTEM: This is argument error #${f} 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:p,tool_call_id:s}}}let i=r.corrected||o;if(r.corrected){let f=Object.keys(o),p=Object.keys(r.corrected),m=f.filter(g=>!p.includes(g));m.length&&console.log(`${h.dim} \u2713 ${n}: corrected args (${m.join(", ")})${h.reset}`)}if(fo()&&!Ww.has(n))return console.log(`${h.yellow} \u2717 ${n}: blocked in plan mode${h.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(f=>f.background===!0);if(ue&&$e==="plan"&&!a.has(n)&&!n.startsWith("skill_")&&!c)return Es++,lr=n,M(`${h.yellow} \u2717 ${n}: blocked in plan phase (read-only, block #${Es})${h.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(ue&&$e==="verify"&&!l.has(n)&&!n.startsWith("skill_"))return M(`${h.yellow} \u2717 ${n}: blocked in verify phase (read + bash only)${h.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}};if(new Set(["write_file","edit_file","patch_file"]).has(n)&&process.env.NEX_SCOPE){let f=i.path||i.file_path||"";if(f){let p=process.env.NEX_SCOPE.split(",").map(w=>w.trim()),m=f.replace(/\\/g,"/");if(!p.some(w=>new RegExp("^"+w.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___DOUBLESTAR___").replace(/\*/g,"[^/]*").replace(/___DOUBLESTAR___/g,".*")+"$").test(m)||m.endsWith(w)||m===w))return M(`${h.yellow} \u2717 ${n}: ${f} outside scope (--scope ${process.env.NEX_SCOPE})${h.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`SCOPE BLOCKED: '${f}' is outside the allowed scope. Only these files may be edited: ${process.env.NEX_SCOPE}. Use read_file to inspect other files, but do not edit them.`,tool_call_id:s}}}}let d=KC(n);if(d==="deny")return console.log(`${h.red} \u2717 ${n}: denied by permissions${h.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(d==="ask"){let f=` Allow ${n}?`;return n==="bash"&&i.command&&(f=` bash: \`${i.command.substring(0,80)}${i.command.length>80?"\u2026":""}\`?`),await Uw(f,{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 DA(t,e,n={}){let o=await cA(t,e);if(o!==null)return o;let s=await rA(t,e);return s!==null?s:af(t,e,n)}function qA(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 jd(t,e=!1){e||console.log(EC(t.fnName,t.args));let n=kw("pre-tool",{tool_name:t.fnName}),o=n.results;if(n.blocked){let w=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${n.blockReason}`;e||console.log(`${h.yellow} [hook pre-tool] BLOCKED: ${n.blockReason}${h.reset}`);let k=vi(t.fnName,t.args,w,!0);return e||console.log(k),{msg:{role:"tool",content:w,tool_call_id:t.callId},summary:k}}if(!e&&o.length>0)for(let w of o)w.success?console.log(`${h.dim} [hook pre-tool] ${w.command} \u2192 ${w.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook pre-tool] ${w.command} \u2192 ERROR: ${w.error}${h.reset}`);dt?.onToolStart&&dt.onToolStart(t.fnName,t.args);let s=await DA(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)+`
|
|
987
987
|
...(truncated ${i.length-5e4} chars)`:i,l=a.split(`
|
|
988
|
-
`)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=
|
|
988
|
+
`)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=vi(t.fnName,t.args,a,c);e||console.log(u),dt?.onToolEnd&&dt.onToolEnd(t.fnName,u,!c);let f=kw("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let w of f)w.success?console.log(`${h.dim} [hook post-tool] ${w.command} \u2192 ${w.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook post-tool] ${w.command} \u2192 ERROR: ${w.error}${h.reset}`);let m=OA(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let w=t.args.command.trim();!/cat\s*>|<</.test(w)&&/\bcat\s+\S/.test(w)?m+=`
|
|
989
989
|
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(w)&&!/npm|yarn|pnpm|make|git\b/.test(w)?m+=`
|
|
990
990
|
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(w)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(w)&&(m+=`
|
|
991
|
-
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(w=>({type:"image",media_type:w.media_type,data:w.base64}))]:m,tool_call_id:t.callId},summary:u}}var
|
|
992
|
-
`)}function Lt(t){return String(t||"").replace(/^\.\/+/,"").replace(/\/+$/,"")}function
|
|
993
|
-
`).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
|
|
994
|
-
...(truncated ${n.length-e} chars)`:"(no output)"}async function
|
|
991
|
+
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(w=>({type:"image",media_type:w.media_type,data:w.base64}))]:m,tool_call_id:t.callId},summary:u}}var FA=[{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 Dd(t){for(let{re:e,label:n}of FA){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=qA(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 tr(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await jd(t[l],e);o[l]=c,s.push(u)}else{let l=r.map(u=>jd(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(vi(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 jd(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 x=[],Lw=300,Jw=900*1e3;function Un(t,e){let n=t.get(e);return n?Date.now()-n.ts>Jw?(t.delete(e),0):n.count:0}function io(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=Jw?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function qd(t,e,n){t.set(e,{count:n,ts:Date.now()})}var lf=new Map,Zw=new Map,El=new Map,wi=new Set,Qw=new Map,Tl=new Map,_i=new Set,Yn=new Map,is=new Map,$i=new Map,xt=new Map,po=new Map,Iw=new Map,Dl=new Map,Kd=new Map,yn=0,fi=0,Rl=0,Vd="",Cl=0,tn=!1,bl=0,Al=0,xs=-1,Xd=!1,Ol=0,Pl=!1,wn=0,sn=!1,_n=0,$n=0,Ot=!1,Yt="",pi=0,$s=0,Ml="",lo=0,co=0,Nl="",li=0,An=!1,Jd=!1,Ei=new Map,Ti=new Set,hi=null,Zo=!1,ci=0,jw=!1,Le=null,nn=!1,cf=null,Zd=!1,Qd=!1,Ll=!1,Ss="",uo="",mi="",$e="plan",ql=0,ue=!1,Es=0,lr=null,On=null,Ri=null,ef=null,rr=0,cr=0,ur=0,vs=0,gi=0,ir=0,wl=0,zn=!1,Kn=0,ho=null,as=[],ks=new Set,De=!1,Vt=0,Ci=0,Ut=new Set,mo=new Set,St=!1,Hl="",Il=!1,Hn=0,rn=0,ki=0,Fl=0,Bl=0,dr=new Set,xi=new Map,Ul=8,ar=10,Dw=3,UA=3,WA=4,HA=new Set(["read_file","grep","search_files","glob","list_directory","find_files"]),qw=null;function GA(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function tf(t){let e=String(t||"");if(!e||Oi(e)||Si(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 Oi(t){let e=String(t||"");return e?Gl(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 e0(t){let e=String(t||"");return!e||!Oi(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 Gn({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.","For UI work, choose only controls, labels, handlers, or component names that were actually visible in the evidence already read. Do not infer a button exists from the product domain; if the exact target is delegated to a child component, name that existing child component/file as the target instead.","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 ${Ul}-${ar} read/search tools, you must choose one scoped task or stop cleanly with \`no safe task found\`; do not keep exploring.`].join(`
|
|
992
|
+
`)}function Lt(t){return String(t||"").replace(/^\.\/+/,"").replace(/\/+$/,"")}function YA(t){let e=String(t||"");if(!e)return null;let n=[/\b(?:work|operate|run)\s+(?:only\s+)?(?:in|inside|within|from)\s+[`"']?(\/[^\s`"',;:)]+)/i,/\bworking\s+directory\s*:\s*[`"']?(\/[^\s`"',;:)]+)/i,/\bcwd\s*:\s*[`"']?(\/[^\s`"',;:)]+)/i];for(let o of n){let s=e.match(o);if(!s)continue;let r=String(s[1]||"").replace(/[.]+$/,"");if(r)try{let i=Ge.resolve(r);if(Be.existsSync(i)&&Be.statSync(i).isDirectory())return Be.realpathSync(i)}catch{}}return null}function zA(t,e={}){if(!De||Ut.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(Lt);for(let s of Ut){let r=Lt(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=>[...Ut].some(r=>s.includes(Lt(r)))):!1}function KA(t,e={}){if(t!=="grep"&&t!=="search_files"&&t!=="glob"&&t!=="list_directory"&&t!=="find_files")return!1;let n=Lt(e.path||e.cwd||"");if(n&&Ut.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![...Ut].some(i=>{let a=Lt(i);return a&&r.includes(a)})}function t0(t){if(!De)return!1;let e=String(t||"");if(!e.trim())return!1;let n=String(Hl||"");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(Lt(i[1]));let a=0,l=0;for(let c of s){if(Ut.has(c))continue;a++;let u=Ge.resolve(process.cwd(),c);Be.existsSync(u)&&l++}return!1}function n0(t){let e=new Set,n=/[`'"]?((?:[A-Za-z0-9_.@-]+\/)+[A-Za-z0-9_.@-]+\.(?:tsx|jsx|mjs|cjs|mdx|json|scss|html|yaml|yml|css|ts|js|md))[`'"]?/g,o;for(;o=n.exec(String(t||""));)e.add(Lt(o[1]));return[...e]}function VA(t){if(!De||mo.size===0)return!1;let e=n0(t).filter(o=>o&&!/\.(md|mdx|txt|rst|adoc)$/i.test(o));return e.length===0?!1:e.filter(o=>Be.existsSync(Ge.resolve(process.cwd(),o))).length===0}function _l(t,e){let n=String(e||"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:^|\\n)\\s*(?:[-*]\\s*)?(?:\\*\\*)?${n}\\s*:(?:\\*\\*)?`,"i").test(String(t||""))}function yi(t){let e=String(t||"");return!e.trim()||t0(e)||s0(e)?!1:/\bno safe task found\b/i.test(e)?!0:_l(e,"Selected improvement")&&_l(e,"Selection rationale")&&_l(e,"Files")&&_l(e,"Verification plan")}function s0(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)||/\b(need|must|will|should|let'?s|attempt|going)\b.{0,80}\b(run|check|use)\b.{0,80}\b(git status|bash|grep|glob|search)\b/i.test(e)||/\{\s*["']tool["']\s*:\s*["'](?:read_file|grep|search_files|glob)["']/i.test(e):!1}function ao(t,e){return De&&St&&(rn>0||xt.size>0)&&t.size===0&&e===0}function o0(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=Ut.size===0||Ci>0;return Vt>=Ul?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 nf(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)||Le?.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)?o0(e):!0}function Gl(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 JA(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(`
|
|
993
|
+
`).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 ZA(t){let e=String(t||"");return!e||!Oi(e)?!1:Gl(e)?!0:/\b(git status|current branch|worktree|dirty|pull\/rebase|rebase|commit|push)\b/i.test(e)}function QA(t,e=2500){let n=String(t??"");return n.trim()?n.length<=e?n:n.slice(0,e)+`
|
|
994
|
+
...(truncated ${n.length-e} chars)`:"(no output)"}async function eO(t,e,n){if(Le?.ran)return Le;let o=cf||Gl(t),s="git status --short --branch",r="preflight-git-status";Le={required:!0,ran:!0,ok:!1,command:s,requiredBranch:o,branch:null,dirty:null,changedFiles:[],raw:""};let i="",a=!1;try{let w={role:"assistant",content:"",tool_calls:[{id:r,type:"function",function:{name:"bash",arguments:JSON.stringify({command:s})}}]};n.push(w),e.push(w),dt?.onToolStart&&(dt.onToolStart("bash",{command:s}),a=!0),i=await af("bash",{command:s},{silent:!0,autoConfirm:!0})}catch(w){i=`ERROR: failed to run preflight: ${w?.message||String(w)}`}let l=String(i??"");if(a&&dt?.onToolEnd){let w=l.length>5e4?l.substring(0,5e4)+`
|
|
995
995
|
...(truncated ${l.length-5e4} chars)`:l,k=w.split(`
|
|
996
|
-
`)[0]||"",T=k.startsWith("ERROR")||k.includes("CANCELLED")||k.includes("BLOCKED");try{dt.onToolEnd("bash",
|
|
997
|
-
|
|
998
|
-
${p}`,g={role:"assistant",content:m};if(n.push(g),e.push(g),!
|
|
999
|
-
`):console.log(m)}catch{}return!l||/^ERROR:/i.test(l)||/^fatal:/i.test(l)||!u||d.dirty||o&&(!d.branch||d.branch!==o)?(Le.ok=!1,Le):(Le.ok=!0,Le)}async function
|
|
1000
|
-
`):console.log(o)}catch{}let r=new Map;async function i(u,d,f,{named:p=!1}={}){let m={role:"assistant",content:"",tool_calls:[{id:f,type:"function",function:{name:u,arguments:JSON.stringify(d)}}]};e.push(m),t.push(m);let g="";try{dt?.onToolStart&&dt.onToolStart(u,d),g=await
|
|
1001
|
-
`)[0]||"",$=/^ERROR:/i.test(T)||T.includes("CANCELLED")||T.includes("BLOCKED");try{dt.onToolEnd(u,
|
|
1002
|
-
`)):(
|
|
1003
|
-
`)}function
|
|
996
|
+
`)[0]||"",T=k.startsWith("ERROR")||k.includes("CANCELLED")||k.includes("BLOCKED");try{dt.onToolEnd("bash",vi("bash",{command:s},w,T),!T)}catch{}}let c=l.trim(),u=/^\s*##\s+\S+/.test(c),d=JA(l);Le.branch=d.branch,Le.dirty=d.dirty,Le.changedFiles=d.changedFiles,Le.raw=l;let f={role:"tool",tool_call_id:r,content:l||"(no output)"};n.push(f),e.push(f);let p=QA(l),m=`[PRECHECK] Preflight ran: \`${s}\`.`+(o?` Required branch: ${o}.`:"")+`
|
|
997
|
+
|
|
998
|
+
${p}`,g={role:"assistant",content:m};if(n.push(g),e.push(g),!ff)try{dt?.onToken?dt.onToken(m+`
|
|
999
|
+
`):console.log(m)}catch{}return!l||/^ERROR:/i.test(l)||/^fatal:/i.test(l)||!u||d.dirty||o&&(!d.branch||d.branch!==o)?(Le.ok=!1,Le):(Le.ok=!0,Le)}async function tO(t,e){if(St||!De||Ut.size===0)return;let n=[...Ut].filter(u=>/\.(md|mdx|txt|rst|adoc|tsx?|jsx?)$/i.test(u)).slice(0,4);if(n.length===0)return;St=!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),!ff)try{dt?.onToken?dt.onToken(o+`
|
|
1000
|
+
`):console.log(o)}catch{}let r=new Map;async function i(u,d,f,{named:p=!1}={}){let m={role:"assistant",content:"",tool_calls:[{id:f,type:"function",function:{name:u,arguments:JSON.stringify(d)}}]};e.push(m),t.push(m);let g="";try{dt?.onToolStart&&dt.onToolStart(u,d),g=await af(u,d,{silent:!0,autoConfirm:!0})}catch(T){g=`ERROR: failed to read backlog evidence ${d.path||u}: ${T?.message||String(T)}`}let w=String(g||"");if(dt?.onToolEnd){let T=w.split(`
|
|
1001
|
+
`)[0]||"",$=/^ERROR:/i.test(T)||T.includes("CANCELLED")||T.includes("BLOCKED");try{dt.onToolEnd(u,vi(u,d,w.slice(0,5e4),$),!$)}catch{}}let k={role:"tool",tool_call_id:f,content:w||"(no output)"};return e.push(k),t.push(k),u==="read_file"&&d.path&&r.set(Lt(d.path),w),Vt++,p&&Ci++,w}for(let u=0;u<n.length;u++){let d=n[u];await i("read_file",{path:d,line_start:1,line_end:140},`bounded-backlog-evidence-${u}`,{named:!0})}if(/\b(current UI|UI\/components|components?|toolbar|palette|inspector|command center|menus?)\b/i.test(Hl)){let u=["components","src","app"].filter(p=>Be.existsSync(Ge.resolve(process.cwd(),p)));for(let p=0;p<Math.min(u.length,2);p++)await i("list_directory",{path:u[p],max_depth:2},`bounded-backlog-ui-tree-${p}`);let d=["components/NotationToolbar.tsx","components/CommandCenter.tsx","components/EditPalette.tsx","components/Inspector.tsx"].filter(p=>Be.existsSync(Ge.resolve(process.cwd(),p)));for(let p=0;p<Math.min(d.length,2);p++)mo.add(d[p]),await i("read_file",{path:d[p],line_start:1,line_end:180},`bounded-backlog-ui-evidence-${p}`);let f=[];for(let[p,m]of r.entries()){if(!p.startsWith("components/"))continue;let g=/from\s+['"](?:@\/components\/|\.\/)([A-Za-z][A-Za-z0-9_-]*)['"]/g,w;for(;w=g.exec(m);){let k=`components/${w[1]}.tsx`;Be.existsSync(Ge.resolve(process.cwd(),k))&&!r.has(k)&&!f.includes(k)&&f.push(k)}}for(let p=0;p<Math.min(f.length,2);p++){let m=f[p];mo.add(m),await i("read_file",{path:m,line_start:1,line_end:180},`bounded-backlog-ui-child-evidence-${p}`)}}let c={role:"user",content:"[BACKLOG PREFLIGHT] The prompt-named backlog/reference files and any requested UI/component evidence 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:`). Choose only controls, handlers, labels, and files that are visible in that evidence; do not invent toolbar buttons or src/components paths. Do not request or describe more read_file calls."};e.push(c),t.push(c)}function nO(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 sf(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function Si(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=>sf(o)))]:[]}function Qo(t,e){t===Vd?(Cl++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Cl})${h.reset}
|
|
1002
|
+
`)):(Vd=t,Cl=1,M(`${e} \u26A0 ${t}${h.reset}`))}var jl=[];function sO(t){jl.push(t.trim())}function oO(){return jl.length===0?null:jl.splice(0,jl.length).join(`
|
|
1003
|
+
`)}function rO(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,n=e!==null?`
|
|
1004
1004
|
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?`
|
|
1005
1005
|
Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
|
|
1006
1006
|
Job: ${t.jobId}
|
|
1007
1007
|
Task: "${t.agentDef.task}"`+n+`
|
|
1008
1008
|
Status: ${t.result.status||"done"}`+s+`
|
|
1009
|
-
Result: ${o}`}function
|
|
1010
|
-
`)}}function
|
|
1011
|
-
`).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
|
|
1012
|
-
`)}function
|
|
1009
|
+
Result: ${o}`}function $l(t,e){let{getCompletedJobs:n}=Jo(),o=n();for(let s of o){let r={role:"user",content:rO(s)};t.push(r),e.push(r);let i=s.result?.status||"done",a=i==="failed"?h.red+" \u2717":h.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${s.agentDef.task.slice(0,50)} \u2014 ${String(s.result?.result||"").slice(0,80)}${h.reset}
|
|
1010
|
+
`)}}function r0(t,e){let n=[],o=new Set([...e.keys(),...wi,..._i]);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(`
|
|
1011
|
+
`).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 iO(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 aO(){return Be.existsSync(Ge.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":Be.existsSync(Ge.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function Wn(t){let e=aO();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 Fw(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}.`,"Verification is mandatory before further exploration \u2014 do not read other files. STEP 1: read_file the modified file(s) to confirm the edit was applied correctly. Do not trust memory \u2014 verify the actual file content on disk. STEP 2: run the narrowest relevant verification command (lint, test, typecheck)."];return s.length>0&&i.push(`Suggested verification commands: ${s.join(" | ")}`),r.length>0&&i.push(`Likely related tests: ${r.join(", ")}`),i.push('If verification passes: report "Verification passed" and you may continue. If verification fails: fix the issue before any other work.'),i.push("MULTI-STEP CHECK: If you created a new file or extracted code into a module, verify that all files that should import/require it have been updated. If the task mentions multiple files, check that each one has been handled."),i.join(`
|
|
1012
|
+
`)}function Bw(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 i0(t){let e=iO(t);if(e.length===0)return[];let{searchContentIndex:n}=In(),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 a0(t){let e=await i0(t);if(e.length===0)return"";let{getRelatedFiles:n,findSymbolReferences:o}=In(),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(`
|
|
1013
1013
|
`)}
|
|
1014
1014
|
Use these exact targeted reads before broader searching.
|
|
1015
1015
|
|
|
1016
|
-
`}async function
|
|
1016
|
+
`}async function Ai(t){let{getFileIndex:e}=In(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=In(),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=Ge.basename(u).replace(/\.[^.]+$/,"");if(d.length<3)continue;for(let m of i)if(m.includes(d)&&a.add(m),a.size>=4)return[...a];try{let m=await s(u,process.cwd(),4);for(let g of m){let w=Ge.basename(g).replace(/\.[^.]+$/,"");if(!(w.length<3)){for(let k of i)if(k.includes(w)&&a.add(k),a.size>=4)return[...a]}}}catch{}let p=(Array.isArray(l.files?.[u]?.defs)?l.files[u].defs:[]).filter(m=>["function","class","export"].includes(m.type)).map(m=>m.name).filter((m,g,w)=>m&&w.indexOf(m)===g).slice(0,3);for(let m of p)try{let g=await o(m,process.cwd(),{excludeFile:u,limit:8});for(let w of g)if(i.includes(w.file)&&a.add(w.file),a.size>=4)return[...a]}catch{}}return[...a]}function lO(t,e={}){if(!Array.isArray(t)||t.length===0)return[];let n=t.slice(0,4).join(" "),o=[],s=String(e.test||"");return/vitest/.test(s)||Be.existsSync(Ge.join(process.cwd(),"vitest.config.ts"))||Be.existsSync(Ge.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${n}`):(/jest/.test(s)||Be.existsSync(Ge.join(process.cwd(),"jest.config.js"))||Be.existsSync(Ge.join(process.cwd(),"jest.config.cjs"))||Be.existsSync(Ge.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${n}`),(Be.existsSync(Ge.join(process.cwd(),"pytest.ini"))||Be.existsSync(Ge.join(process.cwd(),"pyproject.toml")))&&t.some(r=>/\.py$/i.test(r))&&o.push(`pytest ${t.filter(r=>/\.py$/i.test(r)).slice(0,4).join(" ")}`),o}async function er(t,e,n,o){if(!ue)return null;let s=$e;$e=t,ql=0,On=Bd(t,ho),t==="implement"&&(vs=0,De&&(rn=0,ki=0,Fl=0,Bl=0,dr.clear(),xi.clear())),t==="verify"&&(cr=0,ur=0,zn=!1,Kn=0),wn=0,sn=!1,_n=0,$n=0,po.clear(),Dl.clear(),lf.clear(),$i.clear(),t==="implement"&&(as=r0(e||"",Yn));let r=as.length>0?`
|
|
1017
1017
|
|
|
1018
1018
|
ACTION ITEMS (execute these in order; use one targeted read if code context is needed):
|
|
1019
1019
|
`+as.map((l,c)=>`${c+1}. ${l.file} \u2014 ${l.action}`).join(`
|
|
1020
|
-
`):"",i=await
|
|
1020
|
+
`):"",i=await a0(t==="verify"?o:e||o||""),a;if(t==="implement"){Ri=e?.slice(0,2e3)||"";let l=De&&mo.size>0?` Known existing UI files from the preflight evidence: ${[...mo].slice(0,4).join(", ")}. If a planned path does not exist, use the closest known existing UI file instead of searching invented src/components paths.`:"",c=De?`
|
|
1021
1021
|
|
|
1022
1022
|
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.`+l:"";a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
|
|
1023
|
-
${
|
|
1023
|
+
${Ri}
|
|
1024
1024
|
|
|
1025
|
-
${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+c+r}else if(t==="verify"){
|
|
1025
|
+
${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+c+r}else if(t==="verify"){ef=e?.slice(0,500)||"";let l=n?[...n].join(", "):"none",c=await Wl(n),u=await Ai(n),d=c.length>0?`Suggested checks (run the narrowest ones that fit the change):
|
|
1026
1026
|
${c.map((p,m)=>`${m+1}. ${p}`).join(`
|
|
1027
1027
|
`)}
|
|
1028
1028
|
|
|
@@ -1039,7 +1039,7 @@ Prefer these before broader suites when a targeted run is possible.
|
|
|
1039
1039
|
Report PASS (all good) or FAIL (list specific issues).
|
|
1040
1040
|
|
|
1041
1041
|
Files modified: ${l}
|
|
1042
|
-
${i}${d}${f}Summary: ${
|
|
1042
|
+
${i}${d}${f}Summary: ${ef}`}return M(`${h.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${On||"default"})${h.reset}`),a?{role:"user",content:a}:null}async function Wl(t){let e=[],o=[...t||[]].map(l=>String(l).toLowerCase()),s={};try{let l=Ge.join(process.cwd(),"package.json");if(Be.existsSync(l)){s=JSON.parse(Be.readFileSync(l,"utf-8")).scripts||{};let u=[["test",Wn("test")],["lint",Wn("lint")],["typecheck",Wn("typecheck")],["check",Wn("check")],["build",Wn("build")]];for(let[d,f]of u)s[d]&&e.push(f)}}catch{}e.length===0&&(Be.existsSync(Ge.join(process.cwd(),"package.json"))&&e.push(Wn("test")),(Be.existsSync(Ge.join(process.cwd(),"pytest.ini"))||Be.existsSync(Ge.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await Ai(t);e.unshift(...lO(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(Wn("typecheck"))&&e.push(Wn("typecheck")),a&&!e.includes(Wn("lint"))&&e.push(Wn("lint")),[...new Set(e)].slice(0,4)}function uf(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(df())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 cO(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 uO(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 l0(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 dO(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(`
|
|
1043
1043
|
`):/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(`
|
|
1044
1044
|
`):/\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(`
|
|
1045
1045
|
`):/\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(`
|
|
@@ -1054,24 +1054,24 @@ ${i}${d}${f}Summary: ${Qd}`}return M(`${h.cyan} \u21B3 Phase transition: ${s} \
|
|
|
1054
1054
|
`):/\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(`
|
|
1055
1055
|
`):/\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(`
|
|
1056
1056
|
`):/\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(`
|
|
1057
|
-
`):null}function
|
|
1058
|
-
`];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"),
|
|
1057
|
+
`):null}function fO(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,o=df(),s=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
1058
|
+
`];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"),Kt()?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(`
|
|
1059
1059
|
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(`
|
|
1060
1060
|
`)+`
|
|
1061
1061
|
|
|
1062
|
-
`}function
|
|
1062
|
+
`}function pO(t){let e=uf(t);return df()?`# Current Turn Language (CRITICAL \u2014 enforce strictly)
|
|
1063
1063
|
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.
|
|
1064
1064
|
|
|
1065
1065
|
`:`# Current Turn Language (CRITICAL \u2014 enforce strictly)
|
|
1066
1066
|
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.
|
|
1067
1067
|
|
|
1068
|
-
`}function
|
|
1068
|
+
`}function hO(){if(nr!==null)return nr;try{let e=pA().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:fA(r.id,s.name),name:r.name})));if(e.length<2)return nr="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
|
|
1069
1069
|
# Sub-Agent Model Routing
|
|
1070
1070
|
|
|
1071
1071
|
`;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 |
|
|
1072
1072
|
|---|---|---|
|
|
1073
1073
|
`;for(let s of e)o+=`| ${s.spec} | ${s.tier} | ${n[s.tier]||s.tier} |
|
|
1074
|
-
`;return nr=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),nr="",""}}var
|
|
1074
|
+
`;return nr=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),nr="",""}}var of="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function mO(t){let e=t.indexOf(of);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+of.length).trimStart()}}async function rf(){let t=await Xw()+":"+on();if(ui!==null&&t===Gd)return ui;let e=await AC(process.cwd()),n=HC(),o=aA(),s=fo()?ZC():"",r=fO(),i=GC(),a=mA(on());return ui=`${a?`## Model Briefing
|
|
1075
1075
|
${a}
|
|
1076
1076
|
|
|
1077
1077
|
---
|
|
@@ -1094,7 +1094,7 @@ ${s}
|
|
|
1094
1094
|
${r?`${r}
|
|
1095
1095
|
`:""}${i?`${i}
|
|
1096
1096
|
|
|
1097
|
-
`:""}${
|
|
1097
|
+
`:""}${Kt()?`# YOLO Mode \u2014 Auto-Execute
|
|
1098
1098
|
|
|
1099
1099
|
You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
|
|
1100
1100
|
- NEVER ask for confirmation \u2014 just execute tasks directly
|
|
@@ -1112,7 +1112,7 @@ You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
|
|
|
1112
1112
|
- **File creation override** (only for implementation tasks): In auto mode, ALWAYS use write_file to create files on disk. Do NOT just paste file content in your text response \u2014 nobody reads it. Makefiles, Dockerfiles, documentation, config files, scripts \u2014 write_file is mandatory. Your text output is invisible in this mode.
|
|
1113
1113
|
|
|
1114
1114
|
`:""}
|
|
1115
|
-
${
|
|
1115
|
+
${Kt()?`# Direct Answer Override
|
|
1116
1116
|
|
|
1117
1117
|
For self-contained tasks asking for a SQL query, cron expression, regex explanation/refactor, small Makefile, Dockerfile snippet, or small JS/Python function, this overrides the file creation rule above: answer in text only. Do not inspect the workspace, create files, run commands, or install packages unless the user explicitly asks for those actions. Never install Node.js built-in modules such as fs, path, events, http, https, crypto, stream, util, or os.
|
|
1118
1118
|
|
|
@@ -1370,7 +1370,7 @@ Aim for ~30 tool calls per task. Sessions with >40 tool calls risk lower quality
|
|
|
1370
1370
|
- Do NOT re-verify with git status/diff/log after a successful commit
|
|
1371
1371
|
- Do NOT re-read files you just edited (the edit response confirms the change)
|
|
1372
1372
|
- Do NOT repeat searches with slight variations \u2014 refine your approach instead
|
|
1373
|
-
${
|
|
1373
|
+
${hO()}
|
|
1374
1374
|
|
|
1375
1375
|
# Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
|
|
1376
1376
|
|
|
@@ -1562,69 +1562,69 @@ class ErrorBoundary extends React.Component {
|
|
|
1562
1562
|
- Use migrations for schema changes, never manual ALTER TABLE
|
|
1563
1563
|
- Add database-level constraints (unique, foreign key, check) not just app-level
|
|
1564
1564
|
|
|
1565
|
-
`,
|
|
1565
|
+
`,Gd=t,ui}function c0(){lf.clear(),Zw.clear(),El.clear(),wi.clear(),Qw.clear(),Tl.clear(),_i.clear(),Yn.clear(),is.clear(),$i.clear(),xt.clear(),po.clear(),Dl.clear(),Kd.clear(),yn=0,fi=0,Rl=0,tn=!1,Al=0,xs=-1,Xd=!1,Ol=0,Pl=!1,wn=0,sn=!1,_n=0,$n=0,Ot=!1,Yt="",pi=0,Ml="",lo=0,Nl="",co=0,An=!1,Jd=!1,$e="plan",ql=0,ue=!1,On=null,Ri=null,ef=null,as=[],rr=0,cr=0,ur=0,vs=0,gi=0,ir=0,zn=!1,Kn=0,Es=0,lr=null,ho=null,De=!1,Vt=0,Ci=0,Ut.clear(),St=!1,Hl="",Il=!1,Hn=0,rn=0,ki=0,Fl=0,Bl=0,dr.clear(),xi.clear(),Ei.clear(),Ti.clear(),Le=null,nn=!1,cf=null,Zd=!1,Qd=!1,Ll=!1,Ss="",uo="",mi="",Vd="",Cl=0}function gO(){x=[],hi=null,sr="",or=0,Yd="",zd=0,c0();try{let{resetCompactionFailures:t}=Bu();t()}catch{}try{let{cancelAllJobs:t}=Jo();t()}catch{}}function yO(){x.length>Lw&&x.splice(0,x.length-Lw)}function df(){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 Fd(t,e,n,o=1500){return!t||!e?!1:t===e&&Date.now()-n<o}function bO(){return x.length}function wO(){return x}function _O(t){x=t}async function $O(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),o=(d,f)=>new Promise(p=>{t(d,f,{cwd:n,timeout:3e3},(m,g)=>{p(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(`
|
|
1566
1566
|
`):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let c=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=Ge.join(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 p=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";c+=`
|
|
1567
|
-
\u{1F4E6} ${p}${m}`}}catch{}return c}function
|
|
1568
|
-
${h.dim} ${a}${h.reset}`);try{let{getActiveProviderName:c,getActiveModelId:u}=Tt(),d=c(),f=u(),p=typeof
|
|
1569
|
-
`),f==="")return a({action:"quit"});let m=i.find(g=>g.key===p);!m||m.key==="q"||!m.model&&m.key!=="r"?a({action:"quit"}):m.key==="r"?a({action:"retry"}):a({action:"switch",model:m.model,provider:t})};l.on("data",d)})}function
|
|
1567
|
+
\u{1F4E6} ${p}${m}`}}catch{}return c}function kO(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(`
|
|
1568
|
+
${h.dim} ${a}${h.reset}`);try{let{getActiveProviderName:c,getActiveModelId:u}=Tt(),d=c(),f=u(),p=typeof Ew=="function"?Ew(d).label:"cost unknown",m=typeof vw=="function"?vw():null;if(d&&f&&m){let g=m.totalCost>0?`$${m.totalCost.toFixed(4)}`:"free";console.log(`${h.dim} model ${d}:${f} \xB7 ${p} \xB7 ${m.totalInput.toLocaleString()} in / ${m.totalOutput.toLocaleString()} out \xB7 ${g}${h.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`;kO(c)}if(Ti.size>0&&Ei.size>0)for(let c of Ti){let u=Ei.get(c);u&&console.log(`${h.dim} \u2714 task #${c} auto-matched: ${u.slice(0,60)}${h.reset}`)}n.size>0?console.log(`${h.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${h.reset}`):!r&&o.size>=5&&n.size===0&&t>=3?console.log(`${h.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${h.reset}`):o.size>0&&t>=2&&console.log(`${h.dim} \u{1F4A1} /save \xB7 /clear${h.reset}`)}async function xO(){if(!process.stdout.isTTY)return{action:"quit"};let t=bn(),e=on(),n=bi.fast?.[t],o=bi.strong?.[t],s=n&&n!==e,r=o&&o!==e&&o!==n,i=[];i.push({key:"r",label:`Retry with current model ${h.dim}(${e})${h.reset}`}),s&&i.push({key:"f",label:`Switch to ${h.bold}${n}${h.reset} ${h.dim}\u2014 fast, low latency${h.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${h.bold}${o}${h.reset} ${h.dim}\u2014 reliable tool-calling, medium speed${h.reset}`,model:o}),i.push({key:"q",label:`${h.dim}Quit${h.reset}`}),console.log(),console.log(`${h.yellow} Stream stale \u2014 all retries exhausted.${h.reset} What would you like to do?`);for(let a of i)console.log(` ${h.cyan}[${a.key}]${h.reset} ${a.label}`);return process.stdout.write(` ${h.yellow}> ${h.reset}`),new Promise(a=>{let l=process.stdin,c=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,l.removeListener("data",d),l.setRawMode(c||!1),l.pause();let p=f.toLowerCase().trim();if(process.stdout.write(`${p}
|
|
1569
|
+
`),f==="")return a({action:"quit"});let m=i.find(g=>g.key===p);!m||m.key==="q"||!m.model&&m.key!=="r"?a({action:"quit"}):m.key==="r"?a({action:"retry"}):a({action:"switch",model:m.model,provider:t})};l.on("data",d)})}function SO(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 vO(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 dt=null,ff=!1;async function EO(t,e=null,n={}){let o=hA(on());Mw=o.staleWarn,Id=o.staleAbort,dt=e,ff=!!n.silent;let s=t;hi&&typeof t=="string"&&(s=`${hi}
|
|
1570
1570
|
|
|
1571
|
-
${t}`,
|
|
1571
|
+
${t}`,hi=null);let r=typeof s=="string"?YA(s):null;if(r){let le=null;try{le=Be.realpathSync(process.cwd())}catch{le=Ge.resolve(process.cwd())}le!==r&&(process.chdir(r),vl())}if(typeof s=="string"){let le=SO(s),we=vO(s);(le.length>0||we.length>0)&&(s+=`
|
|
1572
1572
|
|
|
1573
1573
|
[System Note for Assistant: To resolve this task faster, consider these hints:
|
|
1574
1574
|
`,le.length>0&&(s+=`- The user mentioned URLs containing the paths/folders: ${le.join(", ")}. Prioritize searching these folder names using glob or grep first.
|
|
1575
1575
|
`),we.length>0&&we.forEach(Ne=>{s+=`- ${Ne}
|
|
1576
|
-
`}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&
|
|
1576
|
+
`}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&Kw(s)&&(s+=`
|
|
1577
1577
|
|
|
1578
|
-
[Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let i=typeof t=="string"
|
|
1578
|
+
[Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let i=typeof t=="string"?$w(t):null,a=typeof t=="string"&&l0(t),l=typeof t=="string"?uf(t):"English",c=zw(s);if(c&&typeof c.then=="function"&&(c=await c),x.push({role:"user",content:c}),yO(),a){let le=dO(t);if(le){let we={role:"assistant",content:le};return x.push(we),be(x),Qe(x),console.log(le),{success:!0,deterministic:!0,content:le}}}let u=fo(),d=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false"&&!u,f=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10),p=typeof c=="string"?c:typeof t=="string"?t:"";if(Oi(p)&&(Qd=!0),ZA(p)){nn=!0;let le=Gl(p);le&&(cf=le)}let w=nn,k=Qd;try{let{detectComplexPrompt:le,runOrchestrated:we}=_w(),Ne=le(typeof t=="string"?t:"");if(!d&&u&&Ne.isComplex&&console.log(`${h.dim}Plan mode active: auto-orchestrate disabled until /plan approve${h.reset}`),!k&&u0(d,Ne,f,u)){console.log(`${h.yellow}\u26A1 Auto-orchestrate: ${Ne.estimatedGoals} goals \u2192 parallel agents${h.reset}`);let Te=await we(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});if(Te&&Te.synthesis){let ke=Te.synthesis.summary||"",cn=Te.synthesis.filesChanged?.length?`
|
|
1579
1579
|
|
|
1580
1580
|
Files changed: ${Te.synthesis.filesChanged.join(", ")}`:"",Je=Te.synthesis.conflicts?.length?`
|
|
1581
1581
|
|
|
1582
1582
|
Conflicts:
|
|
1583
1583
|
${Te.synthesis.conflicts.map(ut=>`- ${ut}`).join(`
|
|
1584
|
-
`)}`:"";x.push({role:"assistant",content:ke+
|
|
1584
|
+
`)}`:"";x.push({role:"assistant",content:ke+cn+Je}),be(x),Qe(x)}return Te}Ne.isComplex&&process.stdout.isTTY&&console.log(`${h.dim}Hint: ~${Ne.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${h.reset}`)}catch{}let{setOnChange:T}=qu(),$=null,R=0;T((le,we)=>{le==="create"?($&&$.stop(),$=new vC(we.name,we.tasks),$.setStats({tokens:R}),$.start()):le==="update"&&$?$.updateTask(we.id,we.status):le==="clear"&&$&&($.stop(),$=null)});let O=await rf(),N=O;try{let{getBrainContext:le}=Ju(),we=await le(t);we&&(N=O+`
|
|
1585
1585
|
`+we+`
|
|
1586
|
-
`)}catch(le){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",le.message)}let K=
|
|
1586
|
+
`)}catch(le){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",le.message)}let K=uA(typeof t=="string"?t:"");if(K.length>0){let le=K.map(we=>`[Triggered: ${we.name}]
|
|
1587
1587
|
${we.instructions}`).join(`
|
|
1588
1588
|
`);N+=`
|
|
1589
1589
|
`+le+`
|
|
1590
1590
|
`}N+=`
|
|
1591
|
-
`+
|
|
1591
|
+
`+pO(t),a&&(N+=`
|
|
1592
1592
|
# Current Turn Direct Answer Mode
|
|
1593
1593
|
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.
|
|
1594
|
-
`);let V=[{role:"system",content:N},...x];
|
|
1594
|
+
`);let V=[{role:"system",content:N},...x];Rd(on());let ie=new tr(Td());ie.start();let J=x.length===1,ne=J&&!a?$O().catch(()=>null):Promise.resolve(null),Ke=J?YC(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),ve=a?[]:zt(),[{messages:H,compressed:oe,compacted:et,tokensRemoved:Ve},Ce,Ae]=await Promise.all([OC(V,ve),ne,Ke]),E=Cn(V,ve);if(ie.stop(),Ce&&console.log(`${h.dim}${Ce}${h.reset}`),et)console.log(`${h.dim} [context compacted \u2014 summary (~${Ve} tokens freed)]${h.reset}`);else if(oe){let le=E.limit>0?Math.round(Ve/E.limit*100):0;M(`${h.dim} [context compressed \u2014 ~${Ve} tokens freed (${le}%)]${h.reset}`)}E.percentage>85&&M(`${h.yellow} \u26A0 Context ${Math.round(E.percentage)}% used (${Math.round(100-E.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${h.reset}`);let _=H;if(Ae&&J&&(_=[_[0],{role:"user",content:`[Server probe at task start]
|
|
1595
1595
|
${Ae}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},..._.slice(1)]),i&&J){let le=i.shouldPreferSsh?`[Runtime URL detected]
|
|
1596
1596
|
The user linked a live app URL (${i.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 "${i.matchedName}", prefer ssh_exec/service_logs on that server for investigation before local repo inspection.`:`[Runtime URL detected]
|
|
1597
|
-
The user linked a live app URL (${i.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.`;_=[_[0],{role:"user",content:le},{role:"assistant",content:"Understood \u2014 I will inspect the live app/runtime first."},..._.slice(1)]}if(J&&!k){let le=
|
|
1597
|
+
The user linked a live app URL (${i.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.`;_=[_[0],{role:"user",content:le},{role:"assistant",content:"Understood \u2014 I will inspect the live app/runtime first."},..._.slice(1)]}if(J&&!k){let le=zC(typeof t=="string"?t:"");le&&(_=[_[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
|
|
1598
1598
|
`+le.user},{role:"assistant",content:le.assistant+`
|
|
1599
|
-
[END EXAMPLE \u2014 wait for the real user request below]`},..._.slice(1)])}if(
|
|
1600
|
-
`),we=
|
|
1599
|
+
[END EXAMPLE \u2014 wait for the real user request below]`},..._.slice(1)])}if(Cn(_,ve).percentage>=65){let{messages:we,tokensRemoved:Ne}=Bn(_,ve);Ne>0&&(_=we,console.log(`${h.dim} [pre-flight compress \u2014 ${Ne} tokens freed, now ${Math.round(Cn(_,ve).percentage)}% used]${h.reset}`))}let W=0,se=0,te=0,P=0,pe=0,Xe=9,_e=0,tt=new Set,ln=(()=>{let le=x.find(we=>we.role==="user");return typeof le?.content=="string"?le.content:""})(),kn=typeof ln=="string"?$w(ln):null,_f=Si(ln),$f=/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(ln)||!!kn?.shouldPreferSsh,D0=!!kn,Ni=0;if(!Ot){let le=x.filter(Ne=>Ne.role==="user"||Ne.role==="tool").map(Ne=>typeof Ne.content=="string"?Ne.content:"").join(`
|
|
1600
|
+
`),we=Dd(le);we&&(Ot=!0,Yt=we.slice(0,120),M(`${h.yellow} \u26A1 Root cause in briefing: ${Yt} \u2014 fix phase active from start (read budget: 3)${h.reset}`))}!Ot&&!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(ln)&&(An=!0,M(`${h.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${h.reset}`));let Ts=p||ln;if(!n.skipPhaseRouting&&!nO(Ts)&&(x.length<=1||k&&!ue)&&(ue=k?!0:FC(),ue)){ho=qC(Ts)?.id||"coding";let we=tf(Ts);if($e=we?"implement":"plan",On=Bd($e,ho),ql=0,rr=0,Es=0,lr=null,De=$e==="plan"&&e0(Ts),Vt=0,Ci=0,Ut.clear(),mo.clear(),St=!1,Hl=De?Ts:"",De)for(let Te of Si(Ts))Ut.add(Lt(Te));Il=!1,Hn=0,ks.clear(),process.stdout.isTTY&&console.log(we?`${h.dim} \u21B3 Phase routing: implement(${On||"default"}) \u2192 verify ${h.yellow}[plan skipped: direct file task]${h.reset}`:`${h.dim} \u21B3 Phase routing: plan(${On||"default"}) \u2192 implement \u2192 verify${h.reset}`),M(we?`${h.cyan} \u26A1 Phase routing enabled \u2014 skipping plan phase for direct file task, starting in implement with ${On||"default model"} (category: ${ho})${h.reset}`:`${h.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${On||"default model"} (category: ${ho})${h.reset}`);let Ne=Si(Ts);if(we&&Ne.length>0){let ke={role:"user",content:`[SYSTEM] This is a direct file task targeting: ${Ne.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.`};x.push(ke),_.push(ke)}if(De){let Te={role:"user",content:Gn()};x.push(Te),_.push(Te)}}if(nn){Le=null;let le=await eO(p,_,x);if(!le.ok){let we=le.requiredBranch,Ne=le.branch?`Current branch: ${le.branch}. `:"",Te=we?`Required branch: ${we}. `:"",ke=le.dirty===!0?`Worktree is dirty (${le.changedFiles.length} changed file${le.changedFiles.length===1?"":"s"}). `:"",Je="[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). ":""}${Ne}${Te}${ke}`.trim()+`
|
|
1601
1601
|
|
|
1602
|
-
Next step: make the worktree clean and be on the required branch, then re-run the automation.`,ut={role:"assistant",content:Je};x.push(ut),be(x),Qe(x),console.log(Je);return}if(!
|
|
1603
|
-
`);we()&&Date.now()<Ne;)await new Promise(Te=>setTimeout(Te,500).unref())
|
|
1604
|
-
`+G.map(
|
|
1605
|
-
`));let he=x.filter(
|
|
1602
|
+
Next step: make the worktree clean and be on the required branch, then re-run the automation.`,ut={role:"assistant",content:Je};x.push(ut),be(x),Qe(x),console.log(Je);return}if(!Zd){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."};x.push(we),_.push(we),Zd=!0}}await tO(_,x);let de=0,xn=0,Pe=new Map,B=new Set,Ee=new Set,yo=[],bo=[],fr=new Set,cs=0,kf=0,Jl=0,qe=0,Me=Date.now(),q0=new RC(gA),Zl=()=>yo.length>0||bo.length>0,F0=$i,bt=n.skillLoop?10:1,B0=3*bt,U0=5*bt,xf=lf,W0=5*bt,H0=8*bt,G0=Zw,Y0=(ue?6:4)*bt,z0=(ue?10:7)*bt,Ql=El,K0=(ue?5:3)*bt,Li=(ue?8:5)*bt,V0=Qw,X0=(ue?4:3)*bt,J0=(ue?6:4)*bt,Z0=3*bt,Q0=4*bt,wo=Yn,e_=(ue?6:4)*bt,t_=(ue?10:8)*bt,_o=(ue?12:10)*bt,n_=25,Rs=0,s_=10*bt,o_=15*bt,Cs=0,Ii=5*bt,$o=()=>De&&ue&&$e==="implement"&&B.size===0&&qe===0&&xt.size===0&&rn>0,As=0,r_=2*bt,i_=3,ji=!1,ec=0,Di=!1,Sf=0,tc=0,pr=10,a_=16,vf=n.skillLoop?999:o.investigationCap,qi=async()=>{let{hasPendingOrCompletedJobs:le,getPendingJobSummary:we}=Jo();if(le()){if(we()){let Ne=Date.now()+45e3;for(process.stderr.write(`${h.cyan} \u23F3 Waiting for background agents to finish\u2026${h.reset}
|
|
1603
|
+
`);we()&&Date.now()<Ne;)await new Promise(Te=>setTimeout(Te,500).unref()),$l(x,_)}$l(x,_),x.length>0&&be(x)}},us=typeof t=="string"?t.trim():"",Ef=us.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(us)&&!/\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(us),Fi=us.length>0&&/\b(analyze|analyse|explain|describe|review|audit|summari[sz]e|understand|document|scan|count|inventory|map|list|identify)\b/i.test(us)&&/\b(create|write|generate|produce|output)\b/i.test(us)&&/\b([A-Z0-9_-]+\.md|markdown|report|summary|overview|architecture|audit|table|documentation|docs|inventory|catalog)\b/i.test(us)&&!/\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(us),ct,It=n.maxIterations||(ue?_s($e):kl);Ef&&(It=Math.min(It,4),M(`${h.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${It}${h.reset}`));let nc=0,Tf=3,Bi=!1,Ui=0,sc=!1;e:for(;;){for(Bi=!1,ct=0;ct<It&&!xl()?.aborted;ct++){$l(x,_);{let b=zt(),y=Cn(_,b),q=de===0?65:78;if(y.percentage>=q){if(B.size>0||ue&&$e!=="plan"){let ce=MC(x,{filesModified:B,currentPhase:ue?$e:null});if(ce){let Q=_.findIndex(C=>C._progressSnapshot);Q!==-1&&_.splice(Q,1);let I=_.findIndex(C=>C.role==="system");_.splice(I+1,0,ce)}}let{messages:F,tokensRemoved:Y}=Bn(_,b,de===0);if(Y>0&&(_=F,Y>50&&console.log(`${h.dim} [auto-compressed \u2014 ~${Y} tokens freed, now ${Math.round(Cn(_,b).percentage)}%]${h.reset}`),An&&B.size>=3)){let ce=[...B].map(I=>I.split("/").pop()).slice(0,10).join(", "),Q={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${B.size} files: ${ce}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};_.push(Q)}}}if(tn&&!Ot&&pi<2){pi++;let b={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."};_.push(b),x.push(b),M(`${h.yellow} \u26A0 Pre-call SSH-blocked nudge #${pi} injected \u2014 model told to synthesize${h.reset}`)}tn||(pi=0);let we=!0;de>0&&nA();let Ne=null;if($&&$.isActive())$._paused&&$.resume();else if(!$){let b,y=sA();if(y&&y.total>1){let Y=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;b=`Plan step ${y.current}/${y.total}: ${Y}`}else b=de>0?`${Td()} (step ${de+1})`:Td();let{getPendingJobSummary:q}=Jo(),F=q();F&&(b+=` [${F}]`),Ne=new tr(b),Ne.start()}let Te=!0,ke="",cn=!1,Je=new oA,ut,Os=Date.now(),Wi=!1,Rf=!1,hr=new AbortController,oc=setInterval(async()=>{let b=Date.now()-Os;if(b>=Id&&!Rf){Rf=!0,Je._clearCursorLine();let y=bi.fast?.[bn()];if(y&&y!==on()&&Nw){M(`${h.green} \u{1F504} Stream stale for ${Math.round(b/1e3)}s \u2014 auto-switching to ${y}${h.reset}`);try{let{setActiveModel:q}=br();q(y),Rd(y),hr.abort()}catch(q){M(`${h.red} \u26A0 Model switch failed: ${q.message}${h.reset}`),hr.abort()}}else M(`${h.yellow} \u26A0 Stream stale for ${Math.round(b/1e3)}s \u2014 aborting and retrying${h.reset}`),hr.abort()}else if(b>=Mw&&!Wi){Wi=!0,Je._clearCursorLine();let y=bi.fast?.[bn()],q=Math.round((Id-b)/1e3);M(`${h.yellow} \u26A0 No tokens received for ${Math.round(b/1e3)}s \u2014 waiting...${h.reset}`),y&&y!==on()?console.log(`${h.dim} \u{1F4A1} Will auto-switch to ${y} in ~${q}s if no tokens arrive${h.reset}`):console.log(`${h.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${q}s${h.reset}`)}},5e3);oc.unref?.();let un="",Pn=null;try{let b=a?[]:Vw(zt()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),q=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),F;ji?F=[]:fo()?F=b.filter(Q=>Ww.has(Q.function.name)):ue&&$e==="plan"?(F=b.filter(Q=>y.has(Q.function.name)),De&&(St||Vt>=ar)&&(F=[])):ue&&$e==="verify"?F=b.filter(Q=>q.has(Q.function.name)):F=b;let Y=xl(),ce=new AbortController;if(Y&&Y.addEventListener("abort",()=>ce.abort(),{once:!0}),hr.signal.addEventListener("abort",()=>ce.abort(),{once:!0}),ut=await ml(_,F,{signal:ce.signal,...On?{model:On}:{},onThinkingToken:()=>{Os=Date.now(),Wi=!1,dt?.onThinkingToken&&dt.onThinkingToken()},onToken:Q=>{if(Os=Date.now(),Wi=!1,dt?.onToken){dt.onToken(Q),ke+=Q;return}if(ke+=Q,!cn&&ke.length>400&&ke.length%250<Q.length+1){let I=Hd(ke,3);I.truncated&&(cn=!0,Je._clearCursorLine?.(),M(`${h.yellow} \u26A0 LLM stream loop detected (${I.repeatCount}\xD7 repeated) \u2014 suppressing display${h.reset}`))}cn||(un+=Q,process.stdout.isTTY?Pn||(Pn=setTimeout(()=>{un&&Je&&Je.push(un),un="",Pn=null},50),Pn.unref?.()):(Je.push(un),un=""),Te&&($&&!$._paused?$.pause():Ne&&Ne.stop(),we||(we=!0),Je.startCursor(),Te=!1))}}),!ut||typeof ut!="object")throw new Error("Provider returned an empty response (no content/tool_calls)")}catch(b){if(clearInterval(oc),Pn&&(clearTimeout(Pn),Pn=null),un&&Je&&(Je.push(un),un=""),$&&!$._paused&&$.pause(),Ne&&Ne.stop(),Je.stopCursor(),hr.signal.aborted&&!xl()?.aborted){if(te++,te>Ld){if(P<1){P++,Qo("Stale retries exhausted \u2014 last-resort force-compress...",h.yellow);let C=zt(),{messages:L,tokensRemoved:A}=Bn(_,C);_=L,A>50&&M(`${h.dim} [force-compressed \u2014 ~${A} tokens freed]${h.reset}`),te=0,ct--;continue}$&&($.stop(),$=null);let I=await xO();if(I.action==="quit"){T(null),je(de,Pe,B,Ee,Me),be(x);break}I.action==="switch"&&(yl(`${I.provider}:${I.model}`),console.log(`${h.green} \u2713 Switched to ${I.provider}:${I.model}${h.reset}`)),te=0,ct--;continue}let ce=te===1?3e3:5e3;if(te>=1&&_e<1){_e++,Qo(`Stale retry ${te}/${Ld} \u2014 force-compressing before retry...`,h.yellow);let I=zt(),{messages:C,tokensRemoved:L}=Bn(_,I,!0);if(_=C,L>0&&L>50&&M(`${h.dim} [force-compressed \u2014 ~${L} tokens freed]${h.reset}`),Nw){let A=bi.fast?.[bn()];A&&A!==on()&&(yl(`${bn()}:${A}`),console.log(`${h.cyan} \u26A1 Auto-switched to ${A} to avoid further stale timeouts${h.reset}`),console.log(`${h.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${h.reset}`))}}else M(`${h.yellow} \u26A0 Stale retry ${te}/${Ld} \u2014 retrying in ${ce/1e3}s...${h.reset}`);let Q=new tr(`Waiting ${ce/1e3}s before retry...`);Q.start(),await new Promise(I=>setTimeout(I,ce)),Q.stop(),ct--;continue}if(b.name==="AbortError"||b.name==="CanceledError"||b.message?.includes("canceled")||b.message?.includes("aborted")){$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x);break}let y=b.message.includes("Provider returned an empty response"),q=b.message;if(b.code==="ECONNREFUSED"||b.message.includes("ECONNREFUSED"))q="Connection refused \u2014 please check your internet connection or API endpoint";else if(b.code==="ENOTFOUND"||b.message.includes("ENOTFOUND"))q="Network error \u2014 could not reach the API server. Please check your connection";else if(b.code==="ETIMEDOUT"||b.message.includes("timeout"))q="Request timed out \u2014 the API server took too long to respond. Please try again";else if(b.message.includes("401")||b.message.includes("Unauthorized"))q="Authentication failed \u2014 please check your API key in the .env file";else if(b.message.includes("403")||b.message.includes("Forbidden"))q="Access denied \u2014 your API key may not have permission for this model";else if(b.message.includes("404")){let ce=on?on():"unknown",Q=L=>L.includes(":")&&L.split(":")[0].match(/^[a-z]+$/)&&!L.split(":")[1].includes(":")?L.split(":").slice(1).join(":"):L;tt.add(Q(ce));let C=(()=>{let L=[];process.env.NEX_FALLBACK_MODEL&&L.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:A}=ni(),D=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let G of D){let he=A(G);he&&!L.includes(he)&&L.push(he)}}catch{}return L.filter(A=>!tt.has(Q(A)))})()[0];if(C){console.log(`${h.yellow} \u26A0 Model ${ce} unavailable (404) \u2014 switching to ${C}${h.reset}`),yl(C),Rd(C),ct--;continue}q=`Model not found (404): ${ce} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${h.red} \u2717 ${q}${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x);break}else if(b.message.includes("400")){if(P<3&&pe<Xe){P++,pe++;let ce=de===0&&P===1,Q=ce||P===3||_e>0;if(ce){P=3;let A=b.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);Qo(`Bad request (400) \u2014 ${A||"system prompt too large"}, compressing...`,h.yellow)}else Qo(Q?`Bad request (400) \u2014 nuclear compression (attempt ${P}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${P}/3)`,h.yellow);let I=zt(),{messages:C,tokensRemoved:L}=Bn(_,I,Q);_=C,L>50&&M(`${h.dim} [force-compressed \u2014 ~${L} tokens freed]${h.reset}`),ct--;continue}{let ce=_.find(D=>D.role==="system"),Q=_.find(D=>D.role==="user"&&!String(D.content).startsWith("[SYSTEM")&&!String(D.content).startsWith("BLOCKED:")),I=[ce,Q].filter(Boolean),{getUsage:C}=Fn(),L=Fn().estimateMessagesTokens(I),A=Fn().estimateMessagesTokens(_);if(L<A){let D=[],G=x.filter(j=>j.role==="assistant"&&typeof j.content=="string"&&j.content.trim().length>30).slice(-5).map(j=>j.content.trim().slice(0,300).replace(/\n+/g," "));G.length>0&&D.push(`Key findings:
|
|
1604
|
+
`+G.map(j=>`- ${j}`).join(`
|
|
1605
|
+
`));let he=x.filter(j=>j.role==="tool"&&typeof j.content=="string"&&!j.content.startsWith("BLOCKED:")&&j.content.trim().length>10).slice(-5).map(j=>j.content.trim().split(`
|
|
1606
1606
|
`).slice(0,8).join(`
|
|
1607
|
-
`).slice(0,500));if(he.length>0&&
|
|
1608
|
-
`+he.map(
|
|
1609
|
-
`)),B.size>0){let
|
|
1610
|
-
${JSON.stringify(
|
|
1611
|
-
${
|
|
1607
|
+
`).slice(0,500));if(he.length>0&&D.push(`Tool results summary:
|
|
1608
|
+
`+he.map(j=>`- ${j}`).join(`
|
|
1609
|
+
`)),B.size>0){let j=[...B].map(fe=>fe.split("/").slice(-2).join("/")).join(", ");D.unshift(`Already modified: ${j} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(Ee.size>0){let j=[...Ee].map(fe=>fe.split("/").slice(-2).join("/")).join(", ");D.push(`Files already investigated: ${j}`)}let me=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(me,JSON.stringify({filesWritten:[...B].map(j=>j.split("/").slice(-2).join("/")),filesRead:[...Ee].map(j=>j.split("/").slice(-2).join("/")),isCreationTask:An,wipeNumber:fi+1,timestamp:Date.now()},null,2)),D.push(`Session checkpoint: ${me} \u2014 read it for exact file list`)}catch{}let re=0;{let fe=((typeof Q?.content=="string"?Q.content:Array.isArray(Q?.content)?Q.content.filter(ft=>ft.type==="text").map(ft=>ft.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(ft=>ft.trim()).filter(Boolean),Ie=[...B],Ue=fe.filter(ft=>!Ie.some(Mn=>Mn.endsWith(ft)||ft.endsWith(Mn.split("/").pop())));re=Ue.length;let rt=[...x].reverse().find(ft=>ft.role==="tool"&&typeof ft.content=="string"&&!ft.content.startsWith("BLOCKED:")&&ft.content.length>5),Xt={completed:Ie.map(ft=>ft.split("/").slice(-2).join("/")),pending:Ue.length>0?Ue:Ie.length===0?["(task files not yet identified)"]:[],lastEdit:rt?rt.content.trim().slice(0,120):null};(Xt.completed.length>0||Xt.pending.length>0)&&D.unshift(`Work manifest:
|
|
1610
|
+
${JSON.stringify(Xt,null,2)}`)}if(D.length>0){let j={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
1611
|
+
${D.join(`
|
|
1612
1612
|
`)}
|
|
1613
|
-
Continue implementing the fixes based on these findings.`};
|
|
1614
|
-
Files modified so far: ${[...B].map(fe=>fe.split("/").slice(-1)[0]).join(", ")}`:"";M(`${h.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${h.reset}`),console.log(`${h.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${
|
|
1613
|
+
Continue implementing the fixes based on these findings.`};I.push(j)}if(fi>=3){let j=B.size>0?`
|
|
1614
|
+
Files modified so far: ${[...B].map(fe=>fe.split("/").slice(-1)[0]).join(", ")}`:"";M(`${h.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${h.reset}`),console.log(`${h.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${j?h.dim+j:""}${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);break}_=I,fi++,xs=10+Math.min(re*3,7),Xd=!0,Ol=B.size,Pl=!1,yn=0,Ni=0;for(let[j,fe]of Yn){let Ie=fe?.count??fe??0;qd(Yn,j,Ie>=2?Ie:1)}for(let[j]of is)Un(Yn,j)<2&&is.delete(j);xt.clear(),po.clear(),An&&$n>0&&(sn=!0,M(`${h.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${$n} edits already made)${h.reset}`));for(let[j]of El)qd(El,j,Li-1);if(Qo(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${A-L} tokens freed)`,h.yellow),fi>=1){let j=[...Yn.entries()].filter(([,rt])=>rt>=_o).map(([rt])=>rt.split("/").slice(-1)[0]),fe=j.length>0?`
|
|
1615
1615
|
|
|
1616
|
-
Files already at read cap \u2014 use grep_search instead: ${
|
|
1617
|
-
Use /undo to revert changes made during this session.${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x);break e}let ce=Math.min(2e3*Math.pow(2,se-1),3e4),Q=new tr(`API temporarily unavailable \u2014 retrying in ${Math.round(ce/1e3)}s (${se}/${
|
|
1616
|
+
Files already at read cap \u2014 use grep_search instead: ${j.join(", ")}`:"",Ue={role:"user",content:tn&&!Ot?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${fe}`};x.push(Ue),_.push(Ue)}P=0,ct--;continue}}q="Context too large to compress \u2014 use /clear to start fresh"}else b.message.includes("500")||b.message.includes("502")||b.message.includes("503")||b.message.includes("504")?q="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(b.message.includes("fetch failed")||b.message.includes("fetch"))&&(q="Network request failed \u2014 please check your internet connection");if(console.log(`${h.red} \u2717 ${q}${h.reset}`),y){$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x);break e}if(b.message.includes("429")){if(W++,W>Md){console.log(`${h.red} Rate limit: max retries (${Md}) exceeded. Try again later or use /budget to check your limits.${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x);break e}let ce=Math.min(1e4*Math.pow(2,W-1),12e4),Q=new tr(`Rate limit \u2014 waiting ${Math.round(ce/1e3)}s (retry ${W}/${Md})`);Q.start(),await new Promise(I=>setTimeout(I,ce)),Q.stop();continue}let F=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return Tt().getActiveProviderName()==="ollama"}catch{return!1}})();if(b.message.includes("socket disconnected")||b.message.includes("TLS")||b.message.includes("ECONNRESET")||b.message.includes("ECONNABORTED")||b.message.includes("ETIMEDOUT")||F&&(b.message.includes("500")||b.message.includes("502")||b.message.includes("503")||b.message.includes("504")||b.message.includes("401")||b.message.includes("Unauthorized"))||b.code==="ECONNRESET"||b.code==="ECONNABORTED"){if(se++,se>Nd){console.log(`${h.red} Network error: max retries (${Nd}) exceeded. Check your connection and try again.
|
|
1617
|
+
Use /undo to revert changes made during this session.${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x);break e}let ce=Math.min(2e3*Math.pow(2,se-1),3e4),Q=new tr(`API temporarily unavailable \u2014 retrying in ${Math.round(ce/1e3)}s (${se}/${Nd}). Your changes are safe.`);Q.start(),await new Promise(I=>setTimeout(I,ce)),Q.stop(),ct--;continue}$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x);break}if(clearInterval(oc),W=0,se=0,Te&&($&&!$._paused&&$.pause(),Ne&&Ne.stop()),Pn&&(clearTimeout(Pn),Pn=null),un&&Je&&(Je.push(un),un=""),ke&&Je.flush(),se=0,te=0,ut&&ut.usage){let b=ut.usage.prompt_tokens||0,y=ut.usage.completion_tokens||0;xw(bn(),on(),b,y),R+=b+y,$&&$.setStats({tokens:R})}else if(ut&&!ut.usage){let b=_.map(F=>typeof F.content=="string"?F.content:Array.isArray(F.content)?F.content.map(Y=>typeof Y=="string"?Y:Y.text||"").join(""):"").join(" "),y=Tw(b),q=Tw(ut.content||ke||"");xw(bn(),on(),y,q),R+=y+q,$&&$.setStats({tokens:R})}let{content:Cf,tool_calls:ko}=ut,ot=ko,rc=!1;if(Array.isArray(ko)&&ko.length>0){let b=ko.filter(y=>y?.function?.name==="ask_user");b.length>0&&(ot=[b[0]],rc=ko.length!==1,rc&&M(`${h.yellow} \u26A0 ask_user must run alone \u2014 deferring ${ko.length-1} other tool call(s) until the user replies${h.reset}`))}let Hi=Hd(Cf||""),Af=Hi.truncated?Hi.text:Cf;Hi.truncated&&M(`${h.yellow} \u26A0 LLM output loop detected (${Hi.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${h.reset}`);let Gi=kA(Af||""),nt=Gi.truncated?Gi.text:Af;if(Gi.truncated&&M(`${h.yellow} \u26A0 LLM output loop detected (${Gi.repeatCount}\xD7 repeated window) \u2014 response truncated${h.reset}`),Array.isArray(ot)&&ot.length>0&&UC(nt||"")&&(M(`${h.yellow} \u26A0 Assistant asked the user a direct question in text \u2014 dropping tool calls and waiting for user input${h.reset}`),ot=[]),Di=!1,Array.isArray(ot)&&ot.length>0){let b=Pd(bn());if(Number.isFinite(b)){let y=b-xn;if(y<=0){if(ec++,M(`${h.yellow} \u26A0 Tool-call budget reached (${xn}/${b}) \u2014 forcing final answer${h.reset}`),ue&&$e==="implement"&&B.size===0&&qe===0||ao(B,qe)){let F=`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.`,Y={role:"assistant",content:
|
|
1620
|
-
${
|
|
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.`,Y={role:"assistant",content:F};x.push(Y),_.push(Y),console.log(`
|
|
1620
|
+
${F}`),be(x),Qe(x);break e}let q={role:"user",content:Pw(xn,b)};if(x.push(q),_.push(q),ji=!0,ec>=2){if(De&&St&&B.size===0&&qe===0){let Y=`Implementation stalled before edits.
|
|
1621
1621
|
|
|
1622
1622
|
The implementation phase reached the tool-call budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,ce={role:"assistant",content:Y};x.push(ce),_.push(ce),console.log(`
|
|
1623
|
-
${Y}`),be(x),Qe(x);break e}let
|
|
1624
|
-
${
|
|
1623
|
+
${Y}`),be(x),Qe(x);break e}let F={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."};x.push(F),console.log(`
|
|
1624
|
+
${F.content}`),be(x),Qe(x),await qi();return}continue}ot.length>y&&(M(`${h.yellow} \u26A0 Tool-call batch trimmed from ${ot.length} to ${y} (budget ${xn}/${b})${h.reset}`),ot=ot.slice(0,y),Di=!0)}}let xo={role:"assistant",content:nt||""};if(ot&&ot.length>0&&(xo.tool_calls=ot,ir=0),x.push(xo),_.push(xo),ue&&$e==="plan"&&De&&ot&&ot.length>0&&(St&&String(nt||ke||"").trim()||yi(nt||ke||""))&&(delete xo.tool_calls,ot=[]),Ef&&!gl(nt||ke||"")&&B.size===0&&qe===0){M(`${h.green} \u2713 Analysis-only early exit: ${(nt||"").length} chars produced, no file changes${h.reset}`),xo.tool_calls&&delete xo.tool_calls,je(de,Pe,B,Ee,Me),be(x);break e}if(!Ot&&nt&&ot&&ot.length>0){let b=Dd(nt);if(b){Ot=!0,Yt=b.slice(0,120),wn=0,sn=!1,_n=0,M(`${h.yellow} \u26A1 Root cause in model analysis: ${Yt} \u2014 fix phase (read budget: 3)${h.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${Yt}. Read only the file that needs fixing, then edit it. Do not read other files.`};x.push(y),_.push(y)}}if(!ot||ot.length===0){if(Kt()&&ir<3&&ir++,Kt()&&ir>=3&&xn===0&&!De){let I=on(),C="devstral-2:123b";if(I&&!I.includes("123b")&&!I.includes("480b")&&!I.includes("1t")){yl(`${bn()}:${C}`),ir=0,M(`${h.yellow} \u26A1 Auto-escalate: 0 tool calls in 3 turns \u2192 switching to ${C}${h.reset}`);continue}}let b=(nt||"").trim().length>0||ke.trim().length>0;if(!b&&De&&St&&ao(B,qe)&&(ji||ct>=It-1)){let I=`Implementation stalled before edits.
|
|
1625
1625
|
|
|
1626
|
-
The bounded backlog workflow reached the response budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,C={role:"assistant",content:
|
|
1627
|
-
${
|
|
1626
|
+
The bounded backlog workflow reached the response budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,C={role:"assistant",content:I};x.push(C),_.push(C),console.log(`
|
|
1627
|
+
${I}`),be(x),Qe(x);break e}if(a&&b&&(l==="English"&&cO(nt||ke||"")!=="English"||uO(t,nt||ke||"")))try{let C=[_[0],{role:"user",content:`Rewrite the text below to be a clean, direct answer.
|
|
1628
1628
|
- Keep any code blocks exactly the same (do not change code).
|
|
1629
1629
|
- Remove any claims about inspecting the workspace, running commands, searching files, creating files, installing packages, or other internal process.
|
|
1630
1630
|
- If any prose is not in English, translate the prose to English.
|
|
@@ -1632,98 +1632,98 @@ ${F}`),be(x),Qe(x);break e}if(a&&b&&(l==="English"&&lO(nt||ke||"")!=="English"||
|
|
|
1632
1632
|
|
|
1633
1633
|
---
|
|
1634
1634
|
|
|
1635
|
-
`+(nt||ke||"")}],A=((await
|
|
1635
|
+
`+(nt||ke||"")}],A=((await ml(C,[],{}))?.content||"").trim();if(A){let D=x[x.length-1];D&&D.role==="assistant"&&(D.content=A);let G=_[_.length-1];G&&G.role==="assistant"&&(G.content=A),console.log(`\\n${A}`)}}catch{}let y=!1;if(tn&&b&&(bl>=2?M(`${h.yellow} \u26A0 SSH permanently blocked after ${bl} storm warnings \u2014 no further SSH calls allowed${h.reset}`):(tn=!1,yn=pr-4,y=!0)),y&&b){let I=(nt||"").trim();if(I.endsWith("?")||/\b(Where |Please |Can you|Should I)\b/.test(I.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."};_.push(L),x.push(L);continue}}if(!b&&de>0&&ct<kl-1){let I={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."};_.push(I),x.push(I);continue}if(!b&&De&&St&&ct<kl-1){if(Sf++,Sf<=2){let A={role:"user",content:(ue&&$e==="implement"?"implementation":"planning")==="implementation"?"[SYSTEM] Empty implementation response is not progress. Continue now with a concrete tool call: read the implementation file from the accepted plan with a targeted range, or edit/patch/write the scoped change. Do not stop without edits.":"[SYSTEM] Empty planning response is not a valid result. The backlog and UI evidence has already been read. Respond now with the required labels: Selected improvement:, Selection rationale:, Files:, Implementation outline:, Verification plan:, Browser/UI applicability:."};_.push(A),x.push(A);continue}let I=(ue&&$e==="implement"?"Implementation stalled before edits.":"Planning stalled before selecting an improvement.")+`
|
|
1636
1636
|
|
|
1637
|
-
The model returned repeated empty responses after the gated backlog evidence was available. Stopping without commit or push so the workflow does not falsely report success.`,C={role:"assistant",content:
|
|
1638
|
-
${
|
|
1637
|
+
The model returned repeated empty responses after the gated backlog evidence was available. Stopping without commit or push so the workflow does not falsely report success.`,C={role:"assistant",content:I};x.push(C),_.push(C),console.log(`
|
|
1638
|
+
${I}`),be(x),Qe(x);break e}if(b&&De&&Kt()&&B.size===0&&qe===0){let I=nt||ke||"";if(Ud(I)&&!Wd(I)&&!yi(I)){let C=`Implementation stalled before edits.
|
|
1639
1639
|
|
|
1640
1640
|
The implementation phase claimed changes, verification, or a clean worktree without any successful file edit or verification evidence. Stopping without commit or push so the workflow does not falsely report success.`,L={role:"assistant",content:C};x.push(L),_.push(L),console.log(`
|
|
1641
|
-
${C}`),je(de,Pe,B,Ee,Me),be(x),Qe(x);break e}}let
|
|
1641
|
+
${C}`),je(de,Pe,B,Ee,Me),be(x),Qe(x);break e}}let q=/can.?t use.*tool|Tool.?Budget|cannot.*access|no.*tool.*access|unable to run (?:any )?(?:git )?commands?|system instructions?.{0,80}\bblock.{0,80}(?:git|tool|command)|(?:git|bash|tools?).{0,80}\b(blocked|forbidden|not allowed)\b/i;if(b&&ct<3&&q.test((nt||"").slice(0,600)))if(Xd&&xs<=0||tn){M(`${h.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${h.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."};_.push(C),x.push(C);continue}else{M(`${h.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${h.reset}`);let C={role:"user",content:De&&ue&&$e==="implement"?"[SYSTEM] You are in implementation phase and the initial git preflight is already complete. Do not claim git/tools are unavailable, and do not re-run git status before editing. Locate the concrete implementation file with targeted read/search/list_directory if needed, then call edit_file/patch_file/write_file for the scoped change.":"[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."};_.push(C),x.push(C);continue}if(n.skillLoop&&b&&de>3&&Ui<5){let I=(nt||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(I.slice(-600))){Ui=(Ui||0)+1,M(`${h.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Ui}${h.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."};_.push(L),x.push(L);continue}}if((ue&&$e==="implement"||ao(B,qe))&&Kt()&&b&&B.size===0&&qe===0){if(vs<3){vs++;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."};x.push(L),_.push(L),M(`${h.yellow} \u26A0 Implement phase made no progress \u2014 nudging for concrete tool use (${vs}/3)${h.reset}`);continue}let I=`Implementation stalled before edits.
|
|
1642
1642
|
|
|
1643
|
-
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:
|
|
1644
|
-
${
|
|
1645
|
-
Do not write a final completion summary until this verification evidence exists.`};x.push(L),_.push(L),M(`${h.yellow} \u26A0 Headless completion blocked \u2014 verification required (${Kn}/2)${h.reset}`);continue}if(
|
|
1643
|
+
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:I};x.push(C),_.push(C),console.log(`
|
|
1644
|
+
${I}`),je(de,Pe,B,Ee,Me),be(x),Qe(x);break e}if(b&&BC(nt||ke||"")&&!n.skillLoop&&!fo()&&!ue&&!nn){M(`${h.green} \u2713 Explicit final summary exit: no follow-up provider call needed${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x),Qe(x),await qi();return}if(Kt()&&!n.skillLoop&&B.size===0&&qe===0&&Ee.size===0&&de===0&&b&&!ue){M(`${h.green} \u2713 Headless direct response exit: text-only response received${h.reset}`),be(x);break e}if(Kt()&&!n.skillLoop&&!ue&&(B.size>0||qe>0)&&zn&&!Zl()&&Kn<2){Kn++;let I=await Wl(B),C=await Ai(B),L={role:"user",content:Fw(B,I,C)+`
|
|
1645
|
+
Do not write a final completion summary until this verification evidence exists.`};x.push(L),_.push(L),M(`${h.yellow} \u26A0 Headless completion blocked \u2014 verification required (${Kn}/2)${h.reset}`);continue}if(Kt()&&!n.skillLoop&&(B.size>0||qe>0)&&b&&!gl(nt||ke||"")&&de>=1&&(!zn||Zl())&&!ue){M(`${h.green} \u2713 Headless early exit: ${B.size} file(s) modified (+ ${qe} bash writes), substantive text response received${h.reset}`),je(de,Pe,B,Ee,Me),be(x);break e}let Y=GA(lr)?1:2;if(ue&&$e==="plan"&&Es>=Y){M(`${h.cyan} \u21B3 Plan phase: ${Es} consecutive blocks (last: ${lr||"unknown"}) \u2014 auto-advancing to implement${h.reset}`),Es=0,lr=null;let I=await er("implement","[auto-advance: task only requires direct action]");if(I){x.push(I),_.push(I),ct=0,It=_s("implement");continue}}if(ue&&b){let I=(nt||ke||"").trim();if($e==="plan"){if(De&&/\bno safe task found\b/i.test(I)){if(!o0(I)){Hn++;let me={role:"user",content:Gn()+"\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."};x.push(me),_.push(me),M(`${h.yellow} \u26A0 Bounded backlog plan: premature no-safe-task response \u2014 requiring backlog evidence${h.reset}`);continue}M(`${h.yellow} \u26A0 Bounded backlog plan: no safe task found \u2014 exiting gracefully${h.reset}`),je(de,Pe,B,Ee,Me),be(x);break e}if(De&&!yi(I)){if(St&&XA(I)){Hn++;let j={role:"user",content:Gn({blocked:!0})+`
|
|
1646
1646
|
|
|
1647
|
-
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.`};x.push(
|
|
1647
|
+
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.`};x.push(j),_.push(j),M(`${h.yellow} \u26A0 Bounded backlog plan: textual tool-call attempt after evidence prefetch${h.reset}`);continue}if(s0(I)){Hn++;let j={role:"user",content:Gn({blocked:St})+"\n\nYour previous plan used markdown headings. Rewrite the same plan using exact label lines, for example `Selected improvement:` instead of `### Selected improvement`."};x.push(j),_.push(j),M(`${h.yellow} \u26A0 Bounded backlog plan: heading labels rejected \u2014 requesting exact labels${h.reset}`);continue}if(t0(I)){Hn++;let j={role:"user",content:Gn({blocked:Vt>=ar})+`
|
|
1648
1648
|
|
|
1649
|
-
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.`};x.push(
|
|
1649
|
+
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.`};x.push(j),_.push(j),M(`${h.yellow} \u26A0 Bounded backlog plan: rejected off-topic selected improvement${h.reset}`);continue}if(Hn++,Hn>=(St?4:2)||Vt>=ar){let j=`no safe task found
|
|
1650
1650
|
|
|
1651
|
-
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:
|
|
1652
|
-
${
|
|
1651
|
+
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:j};x.push(fe),console.log(`
|
|
1652
|
+
${j}`),be(x),Qe(x);break e}let re={role:"user",content:Gn({blocked:Vt>=ar})};x.push(re),_.push(re),M(`${h.yellow} \u26A0 Bounded backlog plan: missing selected-improvement decision \u2014 re-prompting in plan phase${h.reset}`);continue}if(De&&Hn<1&&VA(I)){Hn++;let me=[...mo].slice(0,4).join(", "),re={role:"user",content:Gn({blocked:St})+`
|
|
1653
1653
|
|
|
1654
|
-
Your previous plan named implementation files that do not exist in this repository. Use an existing file from the UI evidence already read above, such as: ${me}. Do not invent src/components paths when the actual files are at the repository root.`};x.push(re),_.push(re),M(`${h.yellow} \u26A0 Bounded backlog plan: correcting nonexistent implementation paths${h.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=
|
|
1655
|
-
`),je(de,Pe,B,Ee,Me),be(x);break e}let he=await er("implement",
|
|
1656
|
-
${uo}`:"(not checked in this run)",rt=["Write a final automation report using EXACT labels (one per line):",`Preflight: ${he}`,"Preflight output: (paste exactly; do not paraphrase)",me,`Branch: ${re}`,"Chosen task: (what you actually did; or `no safe task found`)",`Files changed: ${
|
|
1657
|
-
`),
|
|
1654
|
+
Your previous plan named implementation files that do not exist in this repository. Use an existing file from the UI evidence already read above, such as: ${me}. Do not invent src/components paths when the actual files are at the repository root.`};x.push(re),_.push(re),M(`${h.yellow} \u26A0 Bounded backlog plan: correcting nonexistent implementation paths${h.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=r0(I,Yn).length===0,A=wi.size>0,D=_i.size>0,G=I.length>1500;if(Kt()&&L&&!A&&!D&&!G&&C.test(I)){M(`${h.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${h.reset}
|
|
1655
|
+
`),je(de,Pe,B,Ee,Me),be(x);break e}let he=await er("implement",I);if(he){x.push(he),_.push(he),ct=0,It=_s("implement");continue}}else if($e==="implement"&&(B.size>0||qe>0)){let C=x.find(D=>D.role==="user"),L=typeof C?.content=="string"?C.content:"",A=await er("verify",I,B,L);if(A){x.push(A),_.push(A),ct=0,It=Math.min(_s("verify")+Math.max(0,(B.size-2)*2),20);continue}}else if($e==="verify"){let C=/\bPASS\b/i.test(I.slice(0,500)),A=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(I.slice(0,500)),D=cr>0||_.some(G=>G.role==="assistant"&&typeof G.content=="string"&&/\bPASS\b/i.test(G.content.slice(0,500)));if(Kt()&&!n.skillLoop&&D&&!A&&!gl(I)){if(M(`${h.green} \u2713 Verification phase complete (headless substantive summary)${h.reset}`),nn&&!nf(I))try{let G=yo.length>0?yo.join(" | "):bo.length>0?`post-edit read: ${bo.slice(0,8).join(", ")}`:"not run; state this explicitly and do not claim tests/build/checks passed",he=Le&&Le.command||"git status --short --branch",me=Le&&String(Le.raw||"").trim()||"(missing preflight output)",re=Le&&Le.branch||qw||"(unknown)",j=[...B].slice(0,24).join(", ")||(qe>0?"files changed by shell commands":"(none)"),fe=Zo?"detected (git commit succeeded per bash output)":"not detected",Ie=Ll?"detected (git push succeeded per bash output)":Ss?"attempted (see tool output)":"not detected",Ue=uo?`${mi}
|
|
1656
|
+
${uo}`:"(not checked in this run)",rt=["Write a final automation report using EXACT labels (one per line):",`Preflight: ${he}`,"Preflight output: (paste exactly; do not paraphrase)",me,`Branch: ${re}`,"Chosen task: (what you actually did; or `no safe task found`)",`Files changed: ${j}`,`Verification: ${G}`,`Commit: ${fe}`,`Push: ${Ie}`,`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(`
|
|
1657
|
+
`),Xt=[..._,{role:"user",content:rt}],Mn=((await ml(Xt,[],{}))?.content||"").trim();Mn&&(console.log(`
|
|
1658
1658
|
${Mn}`),x.push({role:"user",content:rt},{role:"assistant",content:Mn}),_.push({role:"user",content:rt},{role:"assistant",content:Mn}))}catch{}je(de,Pe,B,Ee,Me),be(x),Qe(x);break e}if(A&&rr<3){rr++;let G={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
|
|
1659
|
-
${
|
|
1659
|
+
${I.slice(0,400)}
|
|
1660
1660
|
|
|
1661
|
-
Fix the identified issues. This is attempt ${rr}/3.`};$e="implement",
|
|
1661
|
+
Fix the identified issues. This is attempt ${rr}/3.`};$e="implement",On=Bd("implement",ho),x.push(G),_.push(G),ct=0,It=_s("implement"),M(`${h.yellow} \u21B3 Verify \u2192 implement loop-back #${rr} (issues found)${h.reset}`);continue}if(!A&&(!C||cr===0)){if(ur<2){ur++;let G=[];cr===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.`};x.push(he),_.push(he),M(`${h.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${ur}/2)${h.reset}`);continue}M(`${h.yellow} \u26A0 Verify phase completion accepted without full markers after ${ur} nudges${h.reset}`)}if(M(`${h.green} \u2713 Verification phase complete${A?" (loop-back exhausted)":" (PASS)"}${h.reset}`),!A){je(de,Pe,B,Ee,Me),be(x),Qe(x);break e}}}if(fo()&&b&&de===0)if(Rl++,Rl>2)M(`${h.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${h.reset}`);else{let I={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.).
|
|
1662
1662
|
|
|
1663
|
-
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.`};x.push(
|
|
1664
|
-
${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${C.length} ${
|
|
1665
|
-
`),Ie==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(Ie==="e")console.log(`${h.yellow}Type /plan edit to open in editor, or give feedback.${h.reset}`);else if(me()){re(),
|
|
1663
|
+
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.`};x.push(I),_.push(I),M(`${h.yellow} \u26A0 Plan rejected (${Rl}/2): no files read \u2014 forcing investigation${h.reset}`);continue}if(fo()&&b){let I=(nt||ke||"").trim();QC(I),IA(I);let C=eA(I);if(C.length>0){let L=x.find(me=>me.role==="user"),A=typeof L?.content=="string"?L.content.slice(0,120):"Task";tA(A,C);let D=C.length===1?"step":"steps",G=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:me,startExecution:re,setPlanMode:j}=dl();process.stdout.write(`
|
|
1664
|
+
${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${C.length} ${D})${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.yellow}[E]${h.reset}${h.dim}dit${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let fe=process.stdin.isRaw,Ie=await new Promise(Ue=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",rt=>{try{process.stdin.setRawMode(fe||!1)}catch{}let Xt=rt.toString().toLowerCase()[0]||"\r";Ue(Xt)})});if(process.stdout.write(`
|
|
1665
|
+
`),Ie==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(Ie==="e")console.log(`${h.yellow}Type /plan edit to open in editor, or give feedback.${h.reset}`);else if(me()){re(),j(!1),vl(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing ${C.length} ${D}...`);let Ue=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1666
1666
|
|
|
1667
1667
|
Implement the following plan step by step. All tools are now available.
|
|
1668
1668
|
|
|
1669
|
-
${
|
|
1670
|
-
${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${C.length} ${
|
|
1671
|
-
${h.cyan}${h.bold}Plan ready.${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let me=process.stdin.isRaw,re=await new Promise(
|
|
1672
|
-
`),re==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(
|
|
1669
|
+
${I}`;x.push({role:"user",content:Ue}),_.push({role:"user",content:Ue}),G=!0}}else console.log(`
|
|
1670
|
+
${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${C.length} ${D} extracted).${h.reset} Type ${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ${h.reset}${h.cyan}/plan edit${h.reset}${h.dim} to review.${h.reset}`);if(G){$&&($.stop(),$=null),ct--;continue}}else{let L=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:D,startExecution:G,setPlanMode:he}=dl();process.stdout.write(`
|
|
1671
|
+
${h.cyan}${h.bold}Plan ready.${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let me=process.stdin.isRaw,re=await new Promise(j=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",fe=>{try{process.stdin.setRawMode(me||!1)}catch{}j(fe.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
|
|
1672
|
+
`),re==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(D()){G(),he(!1),vl(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing...`);let fe=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1673
1673
|
|
|
1674
1674
|
Implement the following plan step by step. All tools are now available.
|
|
1675
1675
|
|
|
1676
1676
|
${getPlanContent()||ut.content}`;x.push({role:"user",content:fe}),_.push({role:"user",content:fe}),L=!0}}else console.log(`
|
|
1677
|
-
${h.cyan}${h.bold}Plan ready.${h.reset} ${h.dim}Type ${h.reset}${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ask follow-up questions to refine.${h.reset}`);if(L){$&&($.stop(),$=null),ct--;continue}}}if($&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),
|
|
1678
|
-
${uo}`:"(not checked in this run)",re=
|
|
1679
|
-
`):B.size>0||
|
|
1680
|
-
`):"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.",
|
|
1681
|
-
${Ie}`),x.push({role:"user",content:re},{role:"assistant",content:Ie}))}catch{}be(x),Qe(x),await ji();return}de++,jl++,de>=1&&(we=!1),On+=ot.length;{let b=Od(Cn());Number.isFinite(b)&&On>=b&&(Ii=!0)}for(let b of ot){let y=b.function.name;Pe.set(y,(Pe.get(y)||0)+1)}if(On>=30&&!Iw){Iw=!0,M(`${h.yellow} \u26A0 Tool budget warning: ${On} tool calls used \u2014 nudging model to wrap up${h.reset}`);let b={role:"user",content:"[SYSTEM] \u26A0 You have used "+On+" 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."};x.push(b),_.push(b)}let Re=await Promise.all(ot.map(b=>IA(b)));if(tc){let b=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let y of Re)!y.canExecute||!b.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(Fe&&ue&&$e==="plan"&&(St||Kt>=ir))for(let b of Re)b.canExecute&&(b.canExecute=!1,b.errorResult={role:"tool",content:Gn({blocked:!0}),tool_call_id:b.callId});if(zn&&ue&&$e==="implement"){let b=new Set(["read_file","grep","search_files","glob","list_directory","find_files"]);for(let y of Re)y.canExecute&&(Fw(y)||b.has(y.fnName)&&(y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: code was already edited. Run a narrow verification command now, such as npm test, npm run build, npm run lint, or the focused test from the plan. Do not read or search more files before verification.",tool_call_id:y.callId}))}if(Fe&&ue&&$e==="implement"&&St&&B.size===0)for(let b of Re){if(!b.canExecute)continue;let y=Lt(b.args?.path||""),D=b.fnName==="write_file"||b.fnName==="edit_file"||b.fnName==="patch_file",q=y&&(as.some(vt=>Lt(vt.file)===y)||Ei.includes(y)),Y=new Set(as.map(vt=>Lt(vt.file)).filter(Boolean));for(let vt of t0(Ei)){let Ps=Lt(vt);Ps&&!Ut.has(Ps)&&!/\.(md|mdx|txt|rst|adoc)$/i.test(Ps)&&Y.add(Ps)}q&&Y.add(y);let ce=b.fnName==="read_file"&&y&&(q||!Ut.has(y))&&(b.args?.line_start||b.args?.line_end),Q=ce?`${y}:${b.args?.line_start||""}:${b.args?.line_end||""}`:"",F=ce&&(xt.get(b.args?.path)||0)>0,C=zA(b.fnName,b.args||{}),L=[...xt.keys()].map(vt=>Lt(vt)),A=String(b.args?.command||""),j=b.fnName==="bash"&&/^grep\s+-n\b/.test(A.trim())&&L.some(vt=>vt&&A.includes(vt))&&!/[;&|`$]/.test(A)&&!/(^|\s)[<>]/.test(A),G=xt.size>0&&(C||j),he=Lt(b.args?.path||b.args?.cwd||""),me=String(b.args?.pattern||b.args?.glob||b.args?.query||b.args?.search||b.args?.include||b.args?.file_pattern||""),re=sn>0&&(b.fnName==="grep"||b.fnName==="search_files")&&he&&Y.has(he)&&me.trim().length>0,I=sn>0&&b.fnName==="bash"&&/^grep\s+-n\b/.test(A.trim())&&[...Y].some(vt=>vt&&A.includes(vt))&&!/[;&|`$]/.test(A)&&!/(^|\s)[<>]/.test(A),fe=ce&&sn>0&&Y.has(y)&&Q&&!ur.has(Q),Ie=fe&&($i.get(y)||0)>0&&ql<UA,Ue=sn>0&&Dl<BA&&(re||I||fe);if(D)continue;if(ce&&sn<1||F){F||(sn++,Q&&ur.add(Q));continue}if(Ie){ql++,b._boundedBacklogPostGrepRead=!0,Q&&ur.add(Q);continue}if(Ue){Dl++,Q&&ur.add(Q);continue}if(G)continue;if(C&&sn===0&&_i<jw){_i++;continue}let rt=b.fnName==="read_file"&&y&&Ut.has(y)&&!q,Vt=ce&&sn>=1,ft=C&&_i>=jw;b.canExecute=!1;let Mn=sn>0;b.errorResult={role:"tool",content:Mn?"BLOCKED: the planned implementation file has already been read. Make the scoped edit now with edit_file or patch_file; do not run git, search, or read more before editing.":rt?"BLOCKED: implementation phase has already completed backlog review. Do not re-read backlog files. Edit the concrete implementation file from the accepted plan now.":Vt?"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.":ft?"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:b.callId}}{let b=Tn(_,zt()),y=b.percentage,D=Re.some(Q=>Q.canExecute&&Q.fnName==="read_file"&&!Q.args?.line_end),q=Re.filter(Q=>Q.canExecute&&Q.fnName==="read_file"&&Q.args?.path&&Un(wo,Q.args.path)>=1&&!Q.args?.line_start).map(Q=>Q.args.path.split("/").slice(-2).join("/")),Y=q.length>0;if(y>=70&&D&&Ql<70||y>=85&&Ql<85||Y){Ql=y;let Q=y>=85?"URGENT":"WARNING",F;Y?(Q="WARNING",F=`Full-file read of ${q.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):D?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 (${b.used}/${b.limit} tokens). ${F}`};if(x.push(C),_.push(C),y>=85){let L=Y?` (re-read of: ${q.join(", ")})`:"";M(`${h.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${L}${h.reset}`)}}}let oc=new Map;for(let b of Re){if(!b.canExecute||b.fnName!=="read_file")continue;let y=b.args?.path;if(!y)continue;let D=Un(wo,y),q=oc.get(y)||0,Y=D+q,ce=ks.has(y),Q=b.args?.line_start!=null,F=xt.get(y)||0,C=F>0,L=2;if(!ce&&Y>=_o){let A=y.split("/").slice(-2).join("/"),j=(po.get(y)||0)+1;if(po.set(y,j),j===1)M(`${h.red} \u2716 Blocked: "${A}" read ${Y}\xD7 \u2014 hard cap (${_o}) reached${h.reset}`);else if(j===2){M(`${h.red} \u2716 Escalated block: "${A}" \u2014 model ignored BLOCKED, injecting system warning${h.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 (${_o}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};x.push(G),_.push(G)}b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${Y}\xD7 (hard cap: ${_o}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:b.callId}}else if(!ce&&Y>=1&&Q)if(C&&F<=L){let A=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Targeted re-read: "${A}" (line_start=${b.args.line_start}) \u2014 edit recovery #${F}${h.reset}`),xt.set(y,F-1)}else if(C&&F>L){let A=y.split("/").slice(-2).join("/");M(`${h.red} \u2716 Edit recovery blocked: "${A}" \u2014 ${L} recovery reads already used. Use grep to find the exact line numbers, then retry.${h.reset}`),b.canExecute=!1,b.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:b.callId}}else{let A=parseInt(b.args.line_start,10)||1,j=parseInt(b.args.line_end,10)||A+350,G=is.get(y)||[],he=!1;for(let[me,re]of G){let I=Math.max(A,me),fe=Math.min(j,re);if(fe>I){let Ie=fe-I,Ue=j-A||1,rt=re-me||1,Vt=Ie/rt>=.7&&Ie/Ue<.7,ft=j-A<=t_;if(Ie>=Ue||!ft&&(Ie/Ue>=.7||Ie/rt>=.7)){let vt=y.split("/").slice(-2).join("/"),Ps=`${y}:${A}-${j}`,vo=(Il.get(Ps)||0)+1;if(Il.set(Ps,vo),M(Vt?`${h.red} \u2716 Blocked superread: "${vt}" lines ${A}-${j} subsumes already-read ${me}-${re} \u2014 use line_start=${re+1} to skip known content (block #${vo})${h.reset}`:`${h.red} \u2716 Blocked duplicate read: "${vt}" lines ${A}-${j} (\u226570% overlap with lines ${me}-${re} already in context, block #${vo})${h.reset}`),vo>=2){M(`${h.red} \u2716 Escalated range-block: "${vt}" lines ${A}-${j} \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let Nf={role:"user",content:Vt?`[SYSTEM] Read blocked ${vo}\xD7 for read_file("${y}", lines ${A}-${j}). Lines ${me}-${re} were already read. Use line_start=${re+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${vo}\xD7 for read_file("${y}", lines ${A}-${j}). Lines ${me}-${re} were already read and will NOT change. Use grep_search to find specific content instead.`};x.push(Nf),_.push(Nf)}b.canExecute=!1,b.errorResult={role:"tool",content:Vt?`BLOCKED: read_file("${y}", lines ${A}-${j}) re-reads lines ${me}-${re} already in context. Use line_start=${re+1} to read only the new content beyond line ${re}.`:`BLOCKED: read_file("${y}", lines ${A}-${j}) is a duplicate \u2014 lines ${me}-${re} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:b.callId},he=!0;break}}}if(!he){let me=G.length,re=2;if(me>=3&&!b._boundedBacklogPostGrepRead){let fe=y.split("/").slice(-2).join("/");M(`${h.red} \u2716 Blocked file-scroll: "${fe}" \u2014 ${me} sections already read. Use grep to find specific content.${h.reset}`);let Ie=Un(Jl,y)>=Mi;b.canExecute=!1,b.errorResult={role:"tool",content:Ie?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${me} 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 ${me} 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:b.callId}}else me>=re&&(b._scrollWarn={sectionCount:me+1,path:y})}}else if(!ce&&Y>=1){let A=xt.get(y)||0;if(A>0){let j=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Full re-read: "${j}" \u2014 test-failure recovery (${A} remaining)${h.reset}`);let G=A-1;G<=0?xt.delete(y):xt.set(y,G)}else{let j=y.split("/").slice(-2).join("/"),G=(po.get(y)||0)+1;if(po.set(y,G),G===1)M(`${h.red} \u2716 Blocked unbounded re-read: "${j}" \u2014 already in context. Use line_start/line_end for specific sections.${h.reset}`);else if(G===2){M(`${h.red} \u2716 Escalated block: "${j}" \u2014 model ignored unbounded re-read block, injecting system warning${h.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.`};x.push(he),_.push(he)}b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${Y}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:b.callId}}}b.canExecute&&oc.set(y,(oc.get(y)||0)+1)}if($s>=3)for(let b of Re)b.canExecute&&(b.fnName!=="read_file"&&b.fnName!=="edit_file"||(M(`${h.red} \u2716 Blocked ${b.fnName} \u2014 ${$s} consecutive file-not-found errors, must search first${h.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ${$s} 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:b.callId}));for(let b of Re){if(!b.canExecute||b.fnName!=="bash")continue;let y=(b.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){M(`${h.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${h.reset}`),b.canExecute=!1,b.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:b.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(M(`${h.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${h.reset}`),b.canExecute=!1,b.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:b.callId})}for(let b of Re)b.canExecute&&(b.fnName!=="ssh_exec"&&b.fnName!=="bash"||/\bsed\s+-n\b/.test(b.args?.command||"")&&(M(`${h.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${h.reset}`),b.canExecute=!1,b.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:b.callId}));for(let b of Re){if(!b.canExecute||b.fnName!=="write_file")continue;let y=b.args?.path,D=b.args?.content||"";if(y)try{let q=require("fs"),Y=require("path").resolve(process.cwd(),y);if(q.existsSync(Y)){let ce=q.statSync(Y).size,Q=Buffer.byteLength(D,"utf8"),F=ce>0?Q/ce:1,C=nf(rn),L=nf(y);if(ef(rn)&&(C.includes(L)||C.includes(`./${L}`)))continue;if(F<.6&&ce>200){let j=y.split("/").slice(-2).join("/");console.log(`${h.red} \u2716 write_file shrink guard: "${j}" would shrink to ${Math.round(F*100)}% of original \u2014 likely context loss${h.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(F*100)}% of current file size (${ce} \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:b.callId}}}}catch{}}let Af=new Map;for(let b of Re){if(!b.canExecute||b.fnName!=="grep")continue;let y=b.args?.path;if(!y)continue;let D=Af.get(y)||0,q=Un(Jl,y)+D,Y=Un(wo,y)>=1,ce=Y?Math.min(3,Mi):Mi;if(q>=ce){let Q=y.split("/").slice(-2).join("/");M(`${h.red} \u2716 Blocked grep: "${Q}" grepped ${q}\xD7 with different patterns \u2014 flood threshold exceeded${h.reset}`);let F=Un(wo,y),C=F>=_o;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 ${q} 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.`};x.push(L),_.push(L),M(`${h.red} \u2716 Deadlock detected: "${Q}" \u2014 both read and grep blocked, injecting deadlock-break${h.reset}`)}b.canExecute=!1,b.errorResult={role:"tool",content:C?`BLOCKED: grep("${y}") denied \u2014 ${q} 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.`:Y?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${q} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${q} patterns already tried. Work with the grep results already in your context.`,tool_call_id:b.callId}}b.canExecute&&Af.set(y,D+1)}let a_=5,Of=new Map;for(let b of Re){if(!b.canExecute||b.fnName!=="ssh_exec")continue;let D=(b.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),q=Of.get(D)||0,Y=Un(kf,D)+q;Y>=a_&&(M(`${h.yellow} \u26A0 Blocked ssh_exec: same command run ${Y}\xD7 \u2014 result already in context${h.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${Y} 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:b.callId}),b.canExecute&&Of.set(D,q+1)}if(en){let b=Re.filter(q=>q.canExecute&&q.fnName==="ssh_exec"),y=Re.some(q=>q.canExecute&&q.fnName!=="ssh_exec"),D=_f&&Pi<3;if(b.length>0&&!y&&D&&Rl<1)en=!1,Rl++,mn=Math.max(0,fr-2),M(`${h.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Rl}/1)]${h.reset}`);else for(let q of b)q.canExecute=!1,q.errorResult={role:"tool",content:Ot?`BLOCKED: ssh_exec denied \u2014 SSH paused (${fr}+ calls). Root cause is known (${Yt}). 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 (${fr}+ 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:q.callId}}let l_=PA(x,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((_f||j0)&&!l_&&Pi<3&&!en)for(let b of Re){if(!b.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(b.fnName))continue;Pi++;{let q=zt(),{messages:Y}=Bn(_,q);_=Y}let y=$n?.matchedName?`${$n.matchedName} (${$n.matchedProfile?.host||"server"})`:$n?.url,D=$n?.shouldPreferSsh?`BLOCKED: ${b.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${$n?.url} with browser_open or use ssh_exec on ${y} first, then return to local code if needed.`:`BLOCKED: ${b.fnName} denied \u2014 this looks like a live app issue. Inspect ${$n?.url} with browser_open first, then return to local code if needed.`;M(`${h.yellow} \u26A0 Runtime guard: blocking local ${b.fnName} \u2014 inspect the live app first${h.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:D,tool_call_id:b.callId};break}if(!ue&&nn&&Rn&&bn>=1){let b=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of Re)y.canExecute&&b.includes(y.fnName)&&(M(`${h.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(xs>=0){let b=Re.filter(y=>y.canExecute).length;if(b>0&&(xs-=b,xs<0))if(!Al&&B.size>Cl){Al=!0,xs=5,M(`${h.green} \u2713 Post-wipe progress detected (${B.size-Cl} files modified) \u2014 granting 5 bonus tool calls${h.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};x.push(y),_.push(y)}else{M(`${h.yellow} \u26A0 Post-wipe tool budget exhausted (advisory) \u2014 nudging model to wrap up${h.reset}`);let y={role:"user",content:"[SYSTEM] You've used your post-wipe tool call budget. Consider wrapping up and summarizing what was accomplished, or continue if you need a few more steps to finish."};x.push(y),_.push(y),xs=-2}}let c_=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 b of Re){if(!b.canExecute||c_.has(b.fnName))continue;let y=JSON.stringify(b.args||{}),D=`${b.fnName}|${y}`,q=Un(zd,D);q>=2?(M(`${h.red} \u2716 Blocked duplicate: ${b.fnName}(${y.substring(0,80)}) \u2014 called ${q+1}\xD7 with identical args${h.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ${b.fnName}() with these exact arguments has already been called ${q}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:b.callId}):q===1&&M(`${h.yellow} \u26A0 Duplicate tool call: ${b.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${h.reset}`),io(zd,D)}{let b=new Set;for(let y of Re){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let D=y.args?.path;D&&(b.has(D)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${D}" 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},M(`${h.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${D.split("/").slice(-1)[0]}"${h.reset}`)):dr.has(D)&&!ks.has(D)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${D}" 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},M(`${h.yellow} \u26A0 Map-first gate: blocked re-edit of "${D.split("/").slice(-1)[0]}" \u2014 re-read required${h.reset}`)):b.add(D))}}let hr=$?{skipSpinner:!0,skipSummaries:!0}:{},u_=Re.some(b=>b.fnName==="ask_user"),Pf=!hr.skipSummaries&&!we,cn=null,So=null;if(Pf&&!u_){if(we=!0,hr.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(So=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let b=ii(Re,de,!1,0),y=ii(Re,de,!1);process.stdout.write(`${de>1?`
|
|
1682
|
-
`:""}${b}`),sr=y,or=Date.now(),
|
|
1677
|
+
${h.cyan}${h.bold}Plan ready.${h.reset} ${h.dim}Type ${h.reset}${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ask follow-up questions to refine.${h.reset}`);if(L){$&&($.stop(),$=null),ct--;continue}}}if($&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),An&&B.size>=3){let I=[...B].map(G=>G.split("/").pop()).slice(0,8).join(", "),C=[...B].some(G=>G.endsWith("package.json")),L=[...B].some(G=>G.endsWith("requirements.txt")),A=[...B].some(G=>G.endsWith("package-lock.json")||G.endsWith("yarn.lock")||G.endsWith("pnpm-lock.yaml")),D=C&&!A?"npm install not yet run":L?"pip install not yet run":null;hi=`[Previous session created ${B.size} files: ${I}`+(D?` \u2014 ${D}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(An&&!Jd&&de>0){let I=[...B].some(j=>j.endsWith("package.json")),C=[...B].some(j=>j.endsWith("requirements.txt")||j.endsWith("Pipfile")||j.endsWith("pyproject.toml")),L=[...B].some(j=>j.endsWith("package-lock.json")||j.endsWith("yarn.lock")||j.endsWith("pnpm-lock.yaml")),A=x.flatMap(j=>{let fe=Array.isArray(j.tool_calls)?j.tool_calls:[],Ie=Array.isArray(j.content)?j.content.filter(Ue=>Ue?.type==="tool_use"):[];return[...fe,...Ie]}).filter(j=>{let fe=j.function?.name||j.name||"";return fe==="bash"||fe==="Bash"}).map(j=>{try{let fe=j.function?.arguments??j.input??{};return(typeof fe=="string"?JSON.parse(fe):fe)?.command||""}catch{return""}}),D=A.some(j=>/pip\s+install|python\s+-m\s+venv/.test(j)),G=A.some(j=>/npm\s+install/.test(j)),me=[...B].some(j=>/\/App\.(js|ts|jsx|tsx)$/.test(j))&&!I&&!G;if(C&&!D||I&&!L&&!G||me){Jd=!0;let j=[];C&&!D&&j.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),me?j.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):I&&!L&&!G&&j.push("npm install");let fe=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${j.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;M(`${h.dim} [post-creation] bootstrapping environment (${j.join(", ")})${h.reset}`),x.push({role:"user",content:fe}),_.push({role:"user",content:fe});continue}}let ce=(B.size>0||qe>0)&&!Zl()&&Ud(nt||ke||"")&&!Wd(nt||ke||""),Q=nn&&!nf(nt||ke||"");if(de>0&&!n._isSummaryTurn&&(gl(nt)||ce||Q))try{M(`${h.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${h.reset}`);let I=yo.length>0?yo.join(" | "):bo.length>0?`post-edit read: ${bo.slice(0,8).join(", ")}`:"not run; state this explicitly and do not claim tests/build/checks passed",C=Le&&Le.command||"git status --short --branch",L=Le&&String(Le.raw||"").trim()||"(missing preflight output)",A=Le&&Le.branch||qw||"(unknown)",D=[...B].slice(0,24).join(", ")||(qe>0?"files changed by shell commands":"(none)"),G=Zo?"detected (git commit succeeded per bash output)":"not detected",he=Ll?"detected (git push succeeded per bash output)":Ss?"attempted (see tool output)":"not detected",me=uo?`${mi}
|
|
1678
|
+
${uo}`:"(not checked in this run)",re=nn?["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: ${D}`,`Verification: ${I}`,`Commit: ${G}`,`Push: ${he}`,`Final git status: ${me}`,"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(`
|
|
1679
|
+
`):B.size>0||qe>0?["Write a closing summary (3+ sentences) with:",`- changed files: ${[...B].slice(0,8).join(", ")||"files changed by shell commands"}`,`- verification: ${I}`,"- remaining risk or follow-up, if any."].join(`
|
|
1680
|
+
`):"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",j=[..._,{role:"user",content:re}],Ie=((await ml(j,[],{}))?.content||"").trim();Ie&&(console.log(`
|
|
1681
|
+
${Ie}`),x.push({role:"user",content:re},{role:"assistant",content:Ie}))}catch{}be(x),Qe(x),await qi();return}de++,ql++,de>=1&&(we=!1),xn+=ot.length;{let b=Pd(bn());Number.isFinite(b)&&xn>=b&&(Di=!0)}for(let b of ot){let y=b.function.name;Pe.set(y,(Pe.get(y)||0)+1)}if(xn>=30&&!jw){jw=!0,M(`${h.yellow} \u26A0 Tool budget warning: ${xn} tool calls used \u2014 nudging model to wrap up${h.reset}`);let b={role:"user",content:"[SYSTEM] \u26A0 You have used "+xn+" 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."};x.push(b),_.push(b)}let Re=await Promise.all(ot.map(b=>jA(b)));if(sc){let b=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let y of Re)!y.canExecute||!b.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(De&&ue&&$e==="plan"&&(St||Vt>=ar))for(let b of Re)b.canExecute&&(b.canExecute=!1,b.errorResult={role:"tool",content:Gn({blocked:!0}),tool_call_id:b.callId});if(zn&&ue&&$e==="implement"){let b=new Set(["read_file","grep","search_files","glob","list_directory","find_files"]);for(let y of Re)y.canExecute&&(Bw(y)||b.has(y.fnName)&&(y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: code was already edited. Run a narrow verification command now, such as npm test, npm run build, npm run lint, or the focused test from the plan. Do not read or search more files before verification.",tool_call_id:y.callId}))}if(De&&ue&&$e==="implement"&&St&&B.size===0)for(let b of Re){if(!b.canExecute)continue;let y=Lt(b.args?.path||""),q=b.fnName==="write_file"||b.fnName==="edit_file"||b.fnName==="patch_file",F=y&&(as.some(vt=>Lt(vt.file)===y)||Ri.includes(y)),Y=new Set(as.map(vt=>Lt(vt.file)).filter(Boolean));for(let vt of n0(Ri)){let Ps=Lt(vt);Ps&&!Ut.has(Ps)&&!/\.(md|mdx|txt|rst|adoc)$/i.test(Ps)&&Y.add(Ps)}F&&Y.add(y);let ce=b.fnName==="read_file"&&y&&(F||!Ut.has(y))&&(b.args?.line_start||b.args?.line_end),Q=ce?`${y}:${b.args?.line_start||""}:${b.args?.line_end||""}`:"",I=ce&&(xt.get(b.args?.path)||0)>0,C=KA(b.fnName,b.args||{}),L=[...xt.keys()].map(vt=>Lt(vt)),A=String(b.args?.command||""),D=b.fnName==="bash"&&/^grep\s+-n\b/.test(A.trim())&&L.some(vt=>vt&&A.includes(vt))&&!/[;&|`$]/.test(A)&&!/(^|\s)[<>]/.test(A),G=xt.size>0&&(C||D),he=Lt(b.args?.path||b.args?.cwd||""),me=String(b.args?.pattern||b.args?.glob||b.args?.query||b.args?.search||b.args?.include||b.args?.file_pattern||""),re=rn>0&&(b.fnName==="grep"||b.fnName==="search_files")&&he&&Y.has(he)&&me.trim().length>0,j=rn>0&&b.fnName==="bash"&&/^grep\s+-n\b/.test(A.trim())&&[...Y].some(vt=>vt&&A.includes(vt))&&!/[;&|`$]/.test(A)&&!/(^|\s)[<>]/.test(A),fe=ce&&rn>0&&Y.has(y)&&Q&&!dr.has(Q),Ie=fe&&(xi.get(y)||0)>0&&Bl<WA,Ue=rn>0&&Fl<UA&&(re||j||fe);if(q)continue;if(ce&&rn<1||I){I||(rn++,Q&&dr.add(Q));continue}if(Ie){Bl++,b._boundedBacklogPostGrepRead=!0,Q&&dr.add(Q);continue}if(Ue){Fl++,Q&&dr.add(Q);continue}if(G)continue;if(C&&rn===0&&ki<Dw){ki++;continue}let rt=b.fnName==="read_file"&&y&&Ut.has(y)&&!F,Xt=ce&&rn>=1,ft=C&&ki>=Dw;b.canExecute=!1;let Mn=rn>0;b.errorResult={role:"tool",content:Mn?"BLOCKED: the planned implementation file has already been read. Make the scoped edit now with edit_file or patch_file; do not run git, search, or read more before editing.":rt?"BLOCKED: implementation phase has already completed backlog review. Do not re-read backlog files. Edit the concrete implementation file from the accepted plan now.":Xt?"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.":ft?"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:b.callId}}{let b=Cn(_,zt()),y=b.percentage,q=Re.some(Q=>Q.canExecute&&Q.fnName==="read_file"&&!Q.args?.line_end),F=Re.filter(Q=>Q.canExecute&&Q.fnName==="read_file"&&Q.args?.path&&Un(wo,Q.args.path)>=1&&!Q.args?.line_start).map(Q=>Q.args.path.split("/").slice(-2).join("/")),Y=F.length>0;if(y>=70&&q&&tc<70||y>=85&&tc<85||Y){tc=y;let Q=y>=85?"URGENT":"WARNING",I;Y?(Q="WARNING",I=`Full-file read of ${F.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):q?I=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:I="Use targeted reads (line_start/line_end) to save space.";let C={role:"user",content:`[SYSTEM ${Q}] Context ${Math.round(y)}% used (${b.used}/${b.limit} tokens). ${I}`};if(x.push(C),_.push(C),y>=85){let L=Y?` (re-read of: ${F.join(", ")})`:"";M(`${h.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${L}${h.reset}`)}}}let ic=new Map;for(let b of Re){if(!b.canExecute||b.fnName!=="read_file")continue;let y=b.args?.path;if(!y)continue;let q=Un(wo,y),F=ic.get(y)||0,Y=q+F,ce=ks.has(y),Q=b.args?.line_start!=null,I=xt.get(y)||0,C=I>0,L=2;if(!ce&&Y>=_o){let A=y.split("/").slice(-2).join("/"),D=(po.get(y)||0)+1;if(po.set(y,D),D===1)M(`${h.red} \u2716 Blocked: "${A}" read ${Y}\xD7 \u2014 hard cap (${_o}) reached${h.reset}`);else if(D===2){M(`${h.red} \u2716 Escalated block: "${A}" \u2014 model ignored BLOCKED, injecting system warning${h.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 (${_o}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};x.push(G),_.push(G)}b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${Y}\xD7 (hard cap: ${_o}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:b.callId}}else if(!ce&&Y>=1&&Q)if(C&&I<=L){let A=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Targeted re-read: "${A}" (line_start=${b.args.line_start}) \u2014 edit recovery #${I}${h.reset}`),xt.set(y,I-1)}else if(C&&I>L){let A=y.split("/").slice(-2).join("/");M(`${h.red} \u2716 Edit recovery blocked: "${A}" \u2014 ${L} recovery reads already used. Use grep to find the exact line numbers, then retry.${h.reset}`),b.canExecute=!1,b.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:b.callId}}else{let A=parseInt(b.args.line_start,10)||1,D=parseInt(b.args.line_end,10)||A+350,G=is.get(y)||[],he=!1;for(let[me,re]of G){let j=Math.max(A,me),fe=Math.min(D,re);if(fe>j){let Ie=fe-j,Ue=D-A||1,rt=re-me||1,Xt=Ie/rt>=.7&&Ie/Ue<.7,ft=D-A<=n_;if(Ie>=Ue||!ft&&(Ie/Ue>=.7||Ie/rt>=.7)){let vt=y.split("/").slice(-2).join("/"),Ps=`${y}:${A}-${D}`,vo=(Dl.get(Ps)||0)+1;if(Dl.set(Ps,vo),M(Xt?`${h.red} \u2716 Blocked superread: "${vt}" lines ${A}-${D} subsumes already-read ${me}-${re} \u2014 use line_start=${re+1} to skip known content (block #${vo})${h.reset}`:`${h.red} \u2716 Blocked duplicate read: "${vt}" lines ${A}-${D} (\u226570% overlap with lines ${me}-${re} already in context, block #${vo})${h.reset}`),vo>=2){M(`${h.red} \u2716 Escalated range-block: "${vt}" lines ${A}-${D} \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let Lf={role:"user",content:Xt?`[SYSTEM] Read blocked ${vo}\xD7 for read_file("${y}", lines ${A}-${D}). Lines ${me}-${re} were already read. Use line_start=${re+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${vo}\xD7 for read_file("${y}", lines ${A}-${D}). Lines ${me}-${re} were already read and will NOT change. Use grep_search to find specific content instead.`};x.push(Lf),_.push(Lf)}b.canExecute=!1,b.errorResult={role:"tool",content:Xt?`BLOCKED: read_file("${y}", lines ${A}-${D}) re-reads lines ${me}-${re} already in context. Use line_start=${re+1} to read only the new content beyond line ${re}.`:`BLOCKED: read_file("${y}", lines ${A}-${D}) is a duplicate \u2014 lines ${me}-${re} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:b.callId},he=!0;break}}}if(!he){let me=G.length,re=2;if(me>=3&&!b._boundedBacklogPostGrepRead){let fe=y.split("/").slice(-2).join("/");M(`${h.red} \u2716 Blocked file-scroll: "${fe}" \u2014 ${me} sections already read. Use grep to find specific content.${h.reset}`);let Ie=Un(Ql,y)>=Li;b.canExecute=!1,b.errorResult={role:"tool",content:Ie?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${me} 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 ${me} 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:b.callId}}else me>=re&&(b._scrollWarn={sectionCount:me+1,path:y})}}else if(!ce&&Y>=1){let A=xt.get(y)||0;if(A>0){let D=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Full re-read: "${D}" \u2014 test-failure recovery (${A} remaining)${h.reset}`);let G=A-1;G<=0?xt.delete(y):xt.set(y,G)}else{let D=y.split("/").slice(-2).join("/"),G=(po.get(y)||0)+1;if(po.set(y,G),G===1)M(`${h.red} \u2716 Blocked unbounded re-read: "${D}" \u2014 already in context. Use line_start/line_end for specific sections.${h.reset}`);else if(G===2){M(`${h.red} \u2716 Escalated block: "${D}" \u2014 model ignored unbounded re-read block, injecting system warning${h.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.`};x.push(he),_.push(he)}b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${Y}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:b.callId}}}b.canExecute&&ic.set(y,(ic.get(y)||0)+1)}if($s>=3)for(let b of Re)b.canExecute&&(b.fnName!=="read_file"&&b.fnName!=="edit_file"||(M(`${h.red} \u2716 Blocked ${b.fnName} \u2014 ${$s} consecutive file-not-found errors, must search first${h.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ${$s} 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:b.callId}));for(let b of Re){if(!b.canExecute||b.fnName!=="bash")continue;let y=(b.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){M(`${h.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${h.reset}`),b.canExecute=!1,b.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:b.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(M(`${h.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${h.reset}`),b.canExecute=!1,b.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:b.callId})}for(let b of Re)b.canExecute&&(b.fnName!=="ssh_exec"&&b.fnName!=="bash"||/\bsed\s+-n\b/.test(b.args?.command||"")&&(M(`${h.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${h.reset}`),b.canExecute=!1,b.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:b.callId}));for(let b of Re){if(!b.canExecute||b.fnName!=="write_file")continue;let y=b.args?.path,q=b.args?.content||"";if(y)try{let F=require("fs"),Y=require("path").resolve(process.cwd(),y);if(F.existsSync(Y)){let ce=F.statSync(Y).size,Q=Buffer.byteLength(q,"utf8"),I=ce>0?Q/ce:1,C=sf(ln),L=sf(y);if(tf(ln)&&(C.includes(L)||C.includes(`./${L}`)))continue;if(I<.6&&ce>200){let D=y.split("/").slice(-2).join("/");console.log(`${h.red} \u2716 write_file shrink guard: "${D}" would shrink to ${Math.round(I*100)}% of original \u2014 likely context loss${h.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(I*100)}% of current file size (${ce} \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:b.callId}}}}catch{}}let Of=new Map;for(let b of Re){if(!b.canExecute||b.fnName!=="grep")continue;let y=b.args?.path;if(!y)continue;let q=Of.get(y)||0,F=Un(Ql,y)+q,Y=Un(wo,y)>=1,ce=Y?Math.min(3,Li):Li;if(F>=ce){let Q=y.split("/").slice(-2).join("/");M(`${h.red} \u2716 Blocked grep: "${Q}" grepped ${F}\xD7 with different patterns \u2014 flood threshold exceeded${h.reset}`);let I=Un(wo,y),C=I>=_o;if(C){let L={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${I} sections and tried ${F} 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.`};x.push(L),_.push(L),M(`${h.red} \u2716 Deadlock detected: "${Q}" \u2014 both read and grep blocked, injecting deadlock-break${h.reset}`)}b.canExecute=!1,b.errorResult={role:"tool",content:C?`BLOCKED: grep("${y}") denied \u2014 ${F} 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.`:Y?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${F} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${F} patterns already tried. Work with the grep results already in your context.`,tool_call_id:b.callId}}b.canExecute&&Of.set(y,q+1)}let l_=5,Pf=new Map;for(let b of Re){if(!b.canExecute||b.fnName!=="ssh_exec")continue;let q=(b.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),F=Pf.get(q)||0,Y=Un(xf,q)+F;Y>=l_&&(M(`${h.yellow} \u26A0 Blocked ssh_exec: same command run ${Y}\xD7 \u2014 result already in context${h.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${Y} 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:b.callId}),b.canExecute&&Pf.set(q,F+1)}if(tn){let b=Re.filter(F=>F.canExecute&&F.fnName==="ssh_exec"),y=Re.some(F=>F.canExecute&&F.fnName!=="ssh_exec"),q=$f&&Ni<3;if(b.length>0&&!y&&q&&Al<1)tn=!1,Al++,yn=Math.max(0,pr-2),M(`${h.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Al}/1)]${h.reset}`);else for(let F of b)F.canExecute=!1,F.errorResult={role:"tool",content:Ot?`BLOCKED: ssh_exec denied \u2014 SSH paused (${pr}+ calls). Root cause is known (${Yt}). 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 (${pr}+ 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:F.callId}}let c_=MA(x,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if(($f||D0)&&!c_&&Ni<3&&!tn)for(let b of Re){if(!b.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(b.fnName))continue;Ni++;{let F=zt(),{messages:Y}=Bn(_,F);_=Y}let y=kn?.matchedName?`${kn.matchedName} (${kn.matchedProfile?.host||"server"})`:kn?.url,q=kn?.shouldPreferSsh?`BLOCKED: ${b.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${kn?.url} with browser_open or use ssh_exec on ${y} first, then return to local code if needed.`:`BLOCKED: ${b.fnName} denied \u2014 this looks like a live app issue. Inspect ${kn?.url} with browser_open first, then return to local code if needed.`;M(`${h.yellow} \u26A0 Runtime guard: blocking local ${b.fnName} \u2014 inspect the live app first${h.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:q,tool_call_id:b.callId};break}if(!ue&&sn&&An&&$n>=1){let b=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of Re)y.canExecute&&b.includes(y.fnName)&&(M(`${h.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(xs>=0){let b=Re.filter(y=>y.canExecute).length;if(b>0&&(xs-=b,xs<0))if(!Pl&&B.size>Ol){Pl=!0,xs=5,M(`${h.green} \u2713 Post-wipe progress detected (${B.size-Ol} files modified) \u2014 granting 5 bonus tool calls${h.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};x.push(y),_.push(y)}else{M(`${h.yellow} \u26A0 Post-wipe tool budget exhausted (advisory) \u2014 nudging model to wrap up${h.reset}`);let y={role:"user",content:"[SYSTEM] You've used your post-wipe tool call budget. Consider wrapping up and summarizing what was accomplished, or continue if you need a few more steps to finish."};x.push(y),_.push(y),xs=-2}}let u_=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 b of Re){if(!b.canExecute||u_.has(b.fnName))continue;let y=JSON.stringify(b.args||{}),q=`${b.fnName}|${y}`,F=Un(Kd,q);F>=2?(M(`${h.red} \u2716 Blocked duplicate: ${b.fnName}(${y.substring(0,80)}) \u2014 called ${F+1}\xD7 with identical args${h.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ${b.fnName}() with these exact arguments has already been called ${F}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:b.callId}):F===1&&M(`${h.yellow} \u26A0 Duplicate tool call: ${b.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${h.reset}`),io(Kd,q)}{let b=new Set;for(let y of Re){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let q=y.args?.path;q&&(b.has(q)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${q}" 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},M(`${h.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${q.split("/").slice(-1)[0]}"${h.reset}`)):fr.has(q)&&!ks.has(q)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${q}" 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},M(`${h.yellow} \u26A0 Map-first gate: blocked re-edit of "${q.split("/").slice(-1)[0]}" \u2014 re-read required${h.reset}`)):b.add(q))}}let mr=$?{skipSpinner:!0,skipSummaries:!0}:{},d_=Re.some(b=>b.fnName==="ask_user"),Mf=!mr.skipSummaries&&!we,dn=null,So=null;if(Mf&&!d_){if(we=!0,mr.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(So=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let b=ai(Re,de,!1,0),y=ai(Re,de,!1);process.stdout.write(`${de>1?`
|
|
1682
|
+
`:""}${b}`),sr=y,or=Date.now(),dn={start:Date.now(),frame:0,timer:null}}else if(!dt){let b=ai(Re,de,!1);Fd(b,sr,or)||(process.stdout.write(`${de>1?`
|
|
1683
1683
|
`:""}${b}
|
|
1684
|
-
`),sr=b,or=Date.now())}}else
|
|
1684
|
+
`),sr=b,or=Date.now())}}else Mf&&(we=!0,mr.skipSpinner=!0);$&&$._paused&&$.resume(),dn&&process.stdout.isTTY&&(dn.timer=setInterval(()=>{dn.frame++;let b=Math.round((Date.now()-dn.start)/1e3),y=b>=1?` ${h.dim}[${b}s]${h.reset}`:"",q=`${ai(Re,de,!1,dn.frame)}${y}`;So!==null?process.stdout.write(`\x1B[${So};1H\x1B[2K${q}`):process.stdout.write(`\r\x1B[2K${q}`)},120),dn.timer.unref?.());let{results:wt,summaries:f_}=await BA(Re,!0,{...mr,skipSummaries:!0});if(rc){let b={role:"user",content:"[SYSTEM] ask_user is exclusive. Wait for the user's answer before making any other tool calls."};x.push(b),_.push(b)}if(dn){dn.timer&&(clearInterval(dn.timer),dn.timer=null);let b=ai(Re,de,!1);Fd(b,sr,or)||(So!==null?process.stdout.write(`\x1B[${So};1H\x1B[2K${b}
|
|
1685
1685
|
`):process.stdout.write(`\r\x1B[2K${b}
|
|
1686
|
-
`),sr=b,or=Date.now()),So=null,
|
|
1686
|
+
`),sr=b,or=Date.now()),So=null,dn=null}if(!mr.skipSummaries){let b=f_.filter((F,Y)=>!(Re[Y]&&Re[Y].fnName==="ask_user"));for(let F of b)Fd(F,Yd,zd)||(console.log(F),Yd=F,zd=Date.now());let y=Re.filter(F=>F&&F.fnName!=="ask_user").map(F=>F.fnName),q=q0.record(0,y,Ee,B);q&&yA(q)}for(let b of Re){if(b.canExecute||!b.errorResult)continue;let y=typeof b.errorResult.content=="string"?b.errorResult.content:"";if(y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:")||y.startsWith("PLAN PHASE:")){if(Cs++,$o()&&y.includes("planned implementation file")){let F={role:"user",content:"[SYSTEM] The planned implementation file is already in context. Your next response must contain exactly one edit_file or patch_file tool call for the scoped change from the accepted plan. Do not run git, read_file, glob, search, or list_directory. Do not write prose before the tool call."};x.push(F),_.push(F)}let q=$o()?Math.min(Ii,3):Ii;if(Cs>=q){if(M(`${h.red} \u2716 Loop abort: ${Cs} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${h.reset}`),$o()){let F=`Implementation stalled before edits.
|
|
1687
1687
|
|
|
1688
|
-
The planned implementation file was already in context, but the model kept calling blocked read/search/git tools instead of editing. Stopping without commit or push so the workflow does not falsely report success.`,Y={role:"assistant",content:
|
|
1689
|
-
${
|
|
1690
|
-
`)[0],Y=!
|
|
1691
|
-
Do NOT re-read \u2014 apply the edit directly with edit_file.`};x.push(fe),_.push(fe),M(`${h.yellow} \u26A0 TODO nudge: ${
|
|
1692
|
-
`).map(
|
|
1693
|
-
`).map(
|
|
1694
|
-
`);for(let A of L){let
|
|
1695
|
-
`);for(let G of
|
|
1688
|
+
The planned implementation file was already in context, but the model kept calling blocked read/search/git tools instead of editing. Stopping without commit or push so the workflow does not falsely report success.`,Y={role:"assistant",content:F};x.push(Y),_.push(Y),console.log(`
|
|
1689
|
+
${F}`),be(x),Qe(x)}$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);return}}}let Yi=!1;for(let b=0;b<Re.length;b++){let y=Re[b];if(!y.canExecute)continue;let q=wt[b].content,F=q.split(`
|
|
1690
|
+
`)[0],Y=!F.startsWith("ERROR")&&!F.startsWith("CANCELLED")&&!F.startsWith("Command failed")&&!F.startsWith("EXIT")&&!/old_text not found/i.test(F);if(y.fnName==="git_status"&&Y&&(mi="git_status",uo=q),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)&&(mi="bash:git status --short --branch",uo=q),/git\s+push\b/.test(C)&&(Ss=q,Y&&!Ss.startsWith("EXIT")&&(/\bEverything up[- ]to[- ]date\b/i.test(Ss)||/\bTo\s+\S+/i.test(Ss)||/\bWriting objects\b/i.test(Ss))&&(Ll=!0))}if(!Y&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&F.includes("old_text not found")){let C=xt.get(y.args.path)||0;xt.set(y.args.path,C+1)}if(!Y&&y.fnName==="bash"&&$i.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 $i)xt.has(A)||(xt.set(A,1),M(`${h.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${A.split("/").pop()}"${h.reset}`))}if(!Y&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(F)){if($s++,$s>=2){M(`${h.yellow} \u26A0 File-not-found streak: ${$s} consecutive misses \u2014 forcing search${h.reset}`);let C={role:"user",content:`[SYSTEM] ${$s} 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.`};x.push(C),_.push(C)}}else Y&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&($s=0);if(Y&&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){M(`${h.yellow} \u26A0 Temp file: "${C}" \u2014 delete with bash rm when done to keep the workspace clean${h.reset}`);let D={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.`};x.push(D),_.push(D)}}if(Y&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){xt.delete(y.args.path),B.add(y.args.path);for(let A of as)!A.done&&y.args.path.endsWith(A.file.split("/").pop())&&(A.done=!0,M(`${h.green} \u2713 TODO done: ${A.file}${h.reset}`));let C=io(F0,y.args.path),L=y.args.path.split("/").slice(-2).join("/");if(C===B0){M(`${h.yellow} \u26A0 Loop warning: "${L}" edited ${C}\xD7 \u2014 possible edit loop${h.reset}`);let A={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${C}\xD7. One more edit max, then move on.`};x.push(A),_.push(A)}else if(C>=U0){M(`${h.red} \u2716 Loop abort: "${L}" edited ${C}\xD7 \u2014 aborting to prevent runaway loop${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);return}ue&&$e==="verify"||(zn=!0,Kn=0,Yi=!0)}if(Y&&y.canExecute&&ue&&(Es=0),Y&&y.canExecute&&De&&ue&&$e==="plan"&&HA.has(y.fnName)&&(Vt++,zA(y.fnName,y.args)&&Ci++,Vt>=Ul&&!Il)){Il=!0;let C={role:"user",content:Gn()};x.push(C),_.push(C),M(`${h.yellow} \u26A0 Bounded backlog plan: ${Vt} read/search tools used \u2014 requiring a decision${h.reset}`)}if(Y&&y.canExecute&&!(ue&&$e==="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)){wn=0,sn=!1,_n=0,$n++;let re=y.args?.path||y.args?.file_path;re&&(y.fnName==="write_file"?(ks.add(re),Yn.delete(re),is.delete(re),fr.delete(re)):(ks.delete(re),qd(Yn,re,1),is.delete(re),fr.add(re)))}else if(C.includes(y.fnName)){if(wn++,sn&&_n++,ue&&$e==="implement"&&y.fnName==="read_file"){let re=y.args?.path||y.args?.file_path||"";if(re&&ks.has(re)){let j={role:"user",content:`[SYSTEM] You just created and re-read "${re}". Do NOT analyze further. Apply the requested refactor now with edit_file.`};x.push(j),_.push(j),M(`${h.yellow} \u26A0 Fresh-write nudge: ${re} \u2014 refactor directly after re-read${h.reset}`)}}if(ue&&$e==="implement"&&y.fnName==="read_file"&&as.length>0){let re=y.args?.path||y.args?.file_path||"",j=as.find(fe=>!fe.done&&re.endsWith(fe.file.split("/").pop()));if(j){let fe={role:"user",content:`[TODO OBSERVER] You already analyzed "${j.file}" in the plan phase. Action: ${j.action}
|
|
1691
|
+
Do NOT re-read \u2014 apply the edit directly with edit_file.`};x.push(fe),_.push(fe),M(`${h.yellow} \u26A0 TODO nudge: ${j.file} \u2014 already analyzed, edit directly${h.reset}`)}}ue&&$e==="implement"&&zn&&Kn<1&&(Kn++,Yi=!0)}if(ue&&$e==="verify"&&cr++,Y&&Bw(y)){let re=String(y.args?.command||"").trim();if(re&&yo.push(re.slice(0,160)),zn=!1,Kn=0,nn&&(B.size>0||qe>0)&&!Zo){let j={role:"user",content:"[SYSTEM] \u2713 Verification command succeeded after your edit. The dirty worktree now contains your own intended changes, not a preflight blocker. Do not restart planning or re-read the changed file. Stage only the files you changed, commit with a terse English message, push if the prompt requires it, then run one final `git status --short --branch`."};x.push(j),_.push(j)}}let A=o.postEditCap,D=ue&&$e==="implement"?Math.min(vf,10):vf,G=Ot?8:Fi?$n>0?4:6:An?$n>0?6:10:$n>0?A:D,he=6,me=!ue&&sn&&(Ot&&_n>=he||An&&$n>=3&&_n>=he||_n>=he);if(li<2&&!sn&&wn>=3&&B.size===0){let re=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,j=Date.now()-Me,fe=li===0?.4:.65;if(re>0&&j>re*fe){li++;let Ie=Math.round(j/6e4),Ue=Math.round(j/re*100);M(`${h.yellow} \u26A0 Time nudge #${li}: ${Ie}m elapsed (${Ue}%), ${wn} reads, 0 edits${h.reset}`);let rt={role:"user",content:li===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.`};x.push(rt),_.push(rt)}}if(me&&C.includes(y.fnName)){let re=Ot?`root cause already identified (${Yt})`:_n>=he?`${wn} consecutive reads without an edit`:`${$n} file edit(s) already made`;M(`${h.yellow} \u26A0 Investigation cap soft-warn: ${re} \u2014 allowing but nudging${h.reset}`);let j={role:"user",content:Ot?`[SYSTEM] Root cause was already identified (${Yt}). Consider implementing the fix with edit_file rather than reading more files.`:_n>=he?`[SYSTEM] You've read ${wn} files without editing. Consider implementing your fix now \u2014 you likely have enough context.`:`[SYSTEM] ${$n} file edit(s) already made. Consider verifying or proceeding \u2014 further investigation may be unnecessary.`};x.push(j),_.push(j),_n=0,sn=!1}else if(wn>=G&&!sn){if(sn=!0,Fi&&(sc=!0),M(`${h.yellow} \u26A0 Investigation cap: ${wn} read-only calls without an edit \u2014 forcing implementation${h.reset}`),ue&&$e==="plan"){let fe=[..._].reverse().find(rt=>rt.role==="assistant"),Ie=typeof fe?.content=="string"?fe.content:"",Ue=await er("implement",Ie);Ue&&(x.push(Ue),_.push(Ue),ct=0,It=_s("implement"))}let re;Ot?re=`[SYSTEM] Root cause was already identified (${Yt}). Edit the file now \u2014 do not read more files.`:Fi?re="[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.":tn?re="[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.":re="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let j={role:"user",content:re};x.push(j),_.push(j)}}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=io(xf,C);if(L===W0){M(`${h.yellow} \u26A0 Loop warning: same bash command run ${L}\xD7 \u2014 possible debug loop${h.reset}`);let A={role:"user",content:`[SYSTEM WARNING] Same bash command ${L}\xD7. Debug loop detected \u2014 try a different approach.`};x.push(A),_.push(A)}else if(L>=H0){M(`${h.red} \u2716 Loop abort: same bash command run ${L}\xD7 \u2014 aborting runaway debug loop${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);return}}if(y.fnName==="ssh_exec"){yn++;{let A=(wt[b]?.content??"").split(`
|
|
1692
|
+
`).map(D=>D.trim()).find(D=>D.length>0&&!D.startsWith("**")&&(D.startsWith("EXIT")||/^[\w./-]+:\s/.test(D)||D.startsWith("bash:")||D.startsWith("sh:")))??"";if(A){if(A===Ml?lo++:(Ml=A,lo=1),lo===3&&!tn){M(`${h.yellow} \u26A0 SSH repeated-error: "${A.slice(0,60)}" returned ${lo}\xD7 \u2014 nudging to change approach${h.reset}`);let D={role:"user",content:`[SYSTEM WARNING] The last ${lo} 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).`};x.push(D),_.push(D)}}else Ml="",lo=0}if(yn>=a_){M(`${h.red} \u2716 SSH storm abort: ${yn} consecutive ssh_exec calls \u2014 aborting${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);return}else if(yn===pr){{let A=zt(),{messages:D}=Bn(_,A);_=D}tn=!0,bl++,M(`${h.yellow} \u26A0 SSH storm warning (#${bl}): ${yn} consecutive ssh_exec calls \u2014 blocking further SSH${h.reset}`);let L={role:"user",content:Ot?`[SYSTEM WARNING] ${yn} consecutive SSH calls. Root cause identified (${Yt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${yn} 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.`};x.push(L),_.push(L)}}else y.canExecute&&(yn=0);if(y.fnName==="bash"&&y.canExecute){let A=(wt[b]?.content??"").split(`
|
|
1693
|
+
`).map(D=>D.trim()).find(D=>D.length>0&&(D.startsWith("EXIT")||/^[\w./-]+:\s/.test(D)||D.startsWith("bash:")||D.startsWith("sh:")))??"";if(A){if(A===Nl?co++:(Nl=A,co=1),co===3){M(`${h.yellow} \u26A0 Bash repeated-error: "${A.slice(0,60)}" returned ${co}\xD7 \u2014 nudging to change approach${h.reset}`);let D={role:"user",content:`[SYSTEM WARNING] The last ${co} 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).`};x.push(D),_.push(D)}}else Nl="",co=0}if(y.fnName==="bash"&&y.canExecute&&!Zo&&y.args?.command){let C=wt[b]?.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"))){Zo=!0,ci=0;let D=nn?4:2;M(`${h.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max ${D} git status/diff/log)${h.reset}`);let G=nn?{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."};x.push(G),_.push(G)}}if(Zo&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(ci++,ci>(nn?4:2))){M(`${h.yellow} \u26A0 Post-commit git verification blocked (call ${ci})${h.reset}`);let A={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(ci-1)+" git verification commands after committing. "+(nn?"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.")};x.push(A),_.push(A)}if(Y&&y.fnName==="grep"&&q&&!q.startsWith("(no matches)")){let C=Lt(y.args?.path||"");De&&ue&&$e==="implement"&&C&&xi.set(C,(xi.get(C)||0)+1);let L=q.split(`
|
|
1694
|
+
`);for(let A of L){let D=A.indexOf(":");if(D>0){let G=A.substring(0,D);G.startsWith("/")&&!G.includes(" ")&&wi.add(G)}else A.startsWith("/")&&!A.includes(" ")&&wi.add(A.trim())}}{let C=["grep","search_files","glob","glob_files"].includes(y.fnName);if(C&&Y&&q&&(q.startsWith("(no matches)")||q.trim()===""||/^No matches found/.test(q.trim())||/^\(0 results\)/.test(q.trim()))){if(Jl++,Jl===3){M(`${h.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${h.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."};x.push(A),_.push(A)}}else C&&Y&&q&&q.trim().length>0&&(Jl=0)}if(Y&&y.fnName==="grep"&&y.args&&y.args.pattern){let C=`${y.args.pattern}|${y.args.path||""}`,L=io(G0,C);if(L===Y0){M(`${h.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${L}\xD7 \u2014 possible search loop${h.reset}`);let A={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${L}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};x.push(A),_.push(A)}else if(L>=z0){M(`${h.red} \u2716 Loop abort: grep pattern run ${L}\xD7 \u2014 aborting runaway search loop${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);return}if(y.args.path){let A=io(Ql,y.args.path),D=Un(wo,y.args.path)>=1;if(A===(D?1:K0)){let he=y.args.path.split("/").slice(-2).join("/");M(`${h.yellow} \u26A0 Loop warning: "${he}" grepped ${A}\xD7 with different patterns \u2014 context flood risk${h.reset}`);let me={role:"user",content:D?`[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.`};x.push(me),_.push(me)}}}if(Y&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(q&&!q.startsWith("(no matches)")){let D=q.split(`
|
|
1695
|
+
`);for(let G of D)(G.startsWith("/")&&!G.includes(" ")||!G.includes(":")&&!G.startsWith("["))&&_i.add(G.trim())}let C=y.args.pattern||y.args.query||y.args.path||"",L=io(V0,C);if(L===X0){M(`${h.yellow} \u26A0 Loop warning: glob pattern "${C.slice(0,40)}" run ${L}\xD7 \u2014 possible search loop${h.reset}`);let D={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${L}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};x.push(D),_.push(D)}else if(L>=J0){M(`${h.red} \u2716 Loop abort: glob pattern run ${L}\xD7 \u2014 aborting runaway search loop${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);return}let A=C.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(D=>D.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(D));for(let D of A){let G=D.toLowerCase();Tl.has(G)||Tl.set(G,new Set);let he=Tl.get(G);if(he.add(C),he.size===Q0){M(`${h.red} \u2716 Glob core-term block: ${he.size} different patterns all searching for "${G}" \u2014 search loop${h.reset}`);let me={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.`};x.push(me),_.push(me)}else if(he.size===Z0){M(`${h.yellow} \u26A0 Glob core-term warning: ${he.size} different patterns searching for "${G}"${h.reset}`);let me={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.`};x.push(me),_.push(me)}}}let ce=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),Q=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(ce)||/\/(health|status|ping|ready|alive)\b/.test(ce);if(Y&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&Q&&q.includes('"valid":true')){{let L=zt();if(Cn(_,L).percentage>=60){let{messages:D,tokensRemoved:G}=Bn(_,L);G>0&&(_=D,console.log(`${h.dim} [pre-stop-compress \u2014 ~${G} tokens freed before STOP injection, now ${Math.round(Cn(_,L).percentage)}%]${h.reset}`))}}let C={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};x.push(C),_.push(C),console.log(`${h.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${h.reset}`)}if(Y&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&ce&&/\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(ce)&&(qe++,M(`${h.dim} [bash write detected: _bashModifiedFiles=${qe}]${h.reset}`)),q.startsWith("BLOCKED:")){if(Cs++,$o()&&q.includes("planned implementation file")){let L={role:"user",content:"[SYSTEM] The planned implementation file is already in context. Your next response must contain exactly one edit_file or patch_file tool call for the scoped change from the accepted plan. Do not run git, read_file, glob, search, or list_directory. Do not write prose before the tool call."};x.push(L),_.push(L)}let C=$o()?Math.min(Ii,3):Ii;if(Cs>=C){if(M(`${h.red} \u2716 Loop abort: ${Cs} consecutive blocked calls \u2014 model not heeding BLOCKED messages${h.reset}`),$o()){let L=`Implementation stalled before edits.
|
|
1696
1696
|
|
|
1697
1697
|
The planned implementation file was already in context, but the model kept calling blocked read/search/git tools instead of editing. Stopping without commit or push so the workflow does not falsely report success.`,A={role:"assistant",content:L};x.push(A),_.push(A),console.log(`
|
|
1698
|
-
${L}`),be(x),Qe(x)}$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);return}}else Cs=0;if(Y)Rs=0,
|
|
1698
|
+
${L}`),be(x),Qe(x)}$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);return}}else Cs=0;if(Y)Rs=0,Bi=!0;else if(Rs++,Rs===s_){M(`${h.yellow} \u26A0 Loop warning: ${Rs} consecutive tool errors \u2014 possible stuck loop${h.reset}`);let C={role:"user",content:`[SYSTEM WARNING] ${Rs} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};x.push(C),_.push(C)}else if(Rs>=o_){M(`${h.red} \u2716 Loop abort: ${Rs} consecutive errors \u2014 aborting stuck loop${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);return}if(Y&&y.fnName==="read_file"&&y.args&&y.args.path){Ee.add(y.args.path),(B.has(y.args.path)||ks.has(y.args.path)||fr.has(y.args.path))&&(bo.push(y.args.path),zn=!1,Kn=0),ks.delete(y.args.path),fr.delete(y.args.path);let C=io(wo,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;is.has(y.args.path)||is.set(y.args.path,[]),is.get(y.args.path).push([G,he])}if(y._scrollWarn){let{sectionCount:G,path:he}=y._scrollWarn,me={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.`};x.push(me),_.push(me),M(`${h.yellow} \u26A0 Scroll warning: "${he.split("/").slice(-2).join("/")}" \u2014 ${G} sections read \u2014 use grep instead${h.reset}`)}let L=y.args.path.split("/").slice(-2).join("/"),A=!y.args?.line_start&&!y.args?.line_end,D=ue&&$e==="plan";if(!D&&A&&C===e_){{let he=zt();if(Cn(_,he).percentage>=60){let{messages:re}=Bn(_,he);_=re}}M(`${h.yellow} \u26A0 Loop warning: "${L}" read unbounded ${C}\xD7 \u2014 use line_start/line_end${h.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.`};x.push(G),_.push(G)}else if(!D&&A&&C>=t_){M(`${h.red} \u2716 Loop abort: "${L}" read unbounded ${C}\xD7 \u2014 aborting runaway read loop${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);return}}if(y.fnName==="spawn_agents"){let C=(q.match(/\bStatus: done\b/g)||[]).length;if((q.match(/\bStatus: truncated\b/g)||[]).length>0&&C===0){if(As++,As===r_){M(`${h.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${As}\xD7 in a row${h.reset}`);let A={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${As}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};x.push(A),_.push(A)}else if(As>=i_){console.log(`${h.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${As}\xD7 \u2014 aborting stuck swarm${h.reset}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me,{suppressHint:!0}),be(x);return}}else C>0&&(As=0)}}if(Yi&&zn&&!(ue&&$e==="verify")){Yi=!1;let b=await Wl(B),y=await Ai(B),q={role:"user",content:Fw(B,b,y)};x.push(q),_.push(q),M(`${h.cyan} \u21B3 Post-edit verify prompt injected (${b.length} checks, ${y.length} tests)${h.reset}`)}let p_=[...xt.values()].reduce((b,y)=>b+y,0);if(ao(B,qe)&&p_>=2){let b=`Implementation stalled before edits.
|
|
1699
1699
|
|
|
1700
1700
|
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:b};x.push(y),_.push(y),console.log(`
|
|
1701
|
-
${b}`),be(x),Qe(x);break e}{let y=wt.reduce((
|
|
1702
|
-
...(truncated ${Y-Q} chars \u2014 per-message budget)`},y-=Y-Q)}}}for(let b of wt)x.push(b),_.push(b);if(
|
|
1701
|
+
${b}`),be(x),Qe(x);break e}{let y=wt.reduce((q,F)=>q+(typeof F.content=="string"?F.content.length:0),0);if(y>2e5){let q=wt.map((F,Y)=>({i:Y,len:typeof F.content=="string"?F.content.length:0})).sort((F,Y)=>Y.len-F.len);for(let{i:F,len:Y}of q){if(y<=2e5)break;let ce=y-2e5,Q=Math.max(Y-ce,500);Q<Y&&typeof wt[F].content=="string"&&(wt[F]={...wt[F],content:wt[F].content.substring(0,Q)+`
|
|
1702
|
+
...(truncated ${Y-Q} chars \u2014 per-message budget)`},y-=Y-Q)}}}for(let b of wt)x.push(b),_.push(b);if(Di){let b=Pd(bn());if(ue&&$e==="implement"&&B.size===0&&qe===0||ao(B,qe)){let q=`Implementation stalled before edits.
|
|
1703
1703
|
|
|
1704
|
-
The implementation phase reached the tool-call budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,
|
|
1705
|
-
${
|
|
1704
|
+
The implementation phase reached the tool-call budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,F={role:"assistant",content:q};x.push(F),_.push(F),console.log(`
|
|
1705
|
+
${q}`),be(x),Qe(x);break e}let y={role:"user",content:Pw(xn,b)};x.push(y),_.push(y),ji=!0,ec++}let h_=Fi&&Re.some((b,y)=>{if(!b||!["write_file","edit_file","patch_file"].includes(b.fnName))return!1;let q=b.args?.path||b.args?.file_path;return WC(q)&&typeof wt[y]?.content=="string"&&!wt[y].content.startsWith("ERROR")&&!wt[y].content.startsWith("BLOCKED:")});if(Kt()&&!n.skillLoop&&sc&&h_){M(`${h.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${h.reset}`),je(de,Pe,B,Ee,Me),be(x);break e}if($l(x,_),!Ot)for(let b=0;b<wt.length;b++){if(!Re[b]||Re[b].fnName!=="ssh_exec")continue;let y=wt[b];if(!y||typeof y.content!="string")continue;let q=Dd(y.content);if(q){Ot=!0,Yt=q.slice(0,120),wn=0,sn=!1,_n=0,M(`${h.yellow} \u26A1 Root cause detected: ${Yt} \u2014 fix phase (read budget: 3)${h.reset}`);let F={role:"user",content:`[SYSTEM] Root cause identified: ${Yt}. Read only the file that needs fixing, then edit it. Do not read other files.`};x.push(F),_.push(F);break}}for(let b=0;b<wt.length;b++){let y=Re[b];if(!y)continue;let q=typeof wt[b]?.content=="string"?wt[b].content:"";if(y.fnName==="create_task"){let F=q.match(/Task #(\d+) created/),Y=typeof y.args?.subject=="string"?y.args.subject:"";F&&Y&&Ei.set(F[1],Y)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!q.startsWith("BLOCKED:")&&q.trim().length>0){let Y=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),ce=Y.split(/[._\-/]/).filter(Q=>Q.length>2);for(let[Q,I]of Ei){if(Ti.has(Q))continue;let C=I.toLowerCase().split(/\W+/).filter(A=>A.length>3);ce.filter(A=>C.some(D=>D.includes(A)||A.includes(D))).length>=1&&(Ti.add(Q),M(`${h.green} \u2714 Auto-matched task #${Q} to ${Y}: ${I.slice(0,60)}${h.reset}`))}}}{let b=zt();if(Cn(_,b).percentage>=78){let{messages:q,tokensRemoved:F}=Bn(_,b);F>0&&(_=q,console.log(`${h.dim} [auto-compressed \u2014 ~${F} tokens freed, now ${Math.round(Cn(_,b).percentage)}%]${h.reset}`))}}if(Kt()&&!n.skillLoop&&(Re.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?(cs=0,gi=0):(cs===0&&(kf=B.size),cs++),cs>=9&&de>=4&&B.size===kf)){if(ue&&$e==="implement"&&B.size===0&&qe===0||ao(B,qe)){if(vs<3){vs++,cs=0;let F={role:"user",content:"[SYSTEM] You have enough targeted implementation context. Your next response must contain exactly one edit_file or patch_file tool call for the scoped change from the accepted plan. Do not call read_file, grep, glob, list_directory, bash, or git. Do not write prose before the tool call."};x.push(F),_.push(F),M(`${h.yellow} \u26A0 Implement phase read-only streak \u2014 nudging for edit (${vs}/3)${h.reset}`);continue}let y=`Implementation stalled before edits.
|
|
1706
1706
|
|
|
1707
|
-
The implementation phase kept reading/searching without changing files. Stopping without commit or push so the workflow does not falsely report success.`,
|
|
1708
|
-
${y}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x),Qe(x);break e}if(
|
|
1709
|
-
`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x);break e}let
|
|
1707
|
+
The implementation phase kept reading/searching without changing files. Stopping without commit or push so the workflow does not falsely report success.`,q={role:"assistant",content:y};x.push(q),_.push(q),console.log(`
|
|
1708
|
+
${y}`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x),Qe(x);break e}if(gi<2){gi++,cs=0;let y={role:"user",content:"[SYSTEM] You have spent several iterations investigating without making changes. If you have enough information: summarize findings and ask the user what to do next. If the task requires file edits: make them now instead of continuing to read. Do not invent facts \u2014 if blocked, state the blocker plainly."};x.push(y),_.push(y),M(`${h.yellow} \u26A0 Stagnation nudge ${gi}/2 \u2014 ${wl||cs} read-only iterations, no new file changes${h.reset}`),wl=cs;continue}M(`${h.yellow} \u26A0 Stagnation persistence: ${wl||9}+ read-only iterations \u2014 exiting with summary${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Investigation stalled: ${wl||9}+ iterations without edits. Exiting so you can adjust the task or provide feedback.${h.reset}
|
|
1709
|
+
`),$&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x);break e}let Nf=oO();if(Nf){let b={role:"user",content:`[User note mid-run]: ${Nf}`};x.push(b),_.push(b),console.log(`${h.cyan} \u270E Context added${h.reset}`)}}if(ct>=It){if($&&($.stop(),$=null),T(null),je(de,Pe,B,Ee,Me),be(x),Qe(x),ue&&$e==="plan"){let Te=[...x].reverse().find(Je=>Je.role==="assistant"),ke=typeof Te?.content=="string"?Te.content:"";if(De&&Vt>=Ul&&!yi(ke)){let Je=`no safe task found
|
|
1710
1710
|
|
|
1711
|
-
The bounded backlog plan phase used ${
|
|
1712
|
-
${Je}`),be(x),Qe(x);break e}let
|
|
1711
|
+
The bounded backlog plan phase used ${Vt} 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.`,ut={role:"assistant",content:Je};x.push(ut),console.log(`
|
|
1712
|
+
${Je}`),be(x),Qe(x);break e}let cn=await er("implement",ke);if(cn){x.push(cn),_=[{role:"system",content:await rf()},...x],It=_s("implement"),M(`${h.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${h.reset}`);continue e}}else if(ue&&$e==="verify"){M(`${h.yellow} \u26A0 Verify budget exhausted \u2014 completing session${h.reset}`);break e}else if(ue&&$e==="implement"&&(B.size>0||qe>0)){let Te=[...x].reverse().find(Os=>Os.role==="assistant"),ke=typeof Te?.content=="string"?Te.content:"",cn=x.find(Os=>Os.role==="user"),Je=typeof cn?.content=="string"?cn.content:"",ut=await er("verify",ke,B,Je);if(ut){x.push(ut),_.push(ut),It=Math.min(_s("verify")+Math.max(0,(B.size-2)*2),20),M(`${h.yellow} \u26A0 Implement budget exhausted after edits \u2014 auto-transitioning to verify${h.reset}`);continue e}}else if(ue&&$e==="implement"&&B.size===0&&qe===0||ao(B,qe)){let Te=`Implementation stalled before edits.
|
|
1713
1713
|
|
|
1714
1714
|
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:Te};x.push(ke),_.push(ke),console.log(`
|
|
1715
|
-
${Te}`),be(x),Qe(x);break e}let{getActiveProviderName:le}=Tt(),we=le();if(
|
|
1715
|
+
${Te}`),be(x),Qe(x);break e}let{getActiveProviderName:le}=Tt(),we=le();if(De&&St&&B.size===0&&qe===0&&!Bi){let Te=`Implementation stalled before edits.
|
|
1716
1716
|
|
|
1717
1717
|
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:Te};x.push(ke),_.push(ke),console.log(`
|
|
1718
|
-
${Te}`),be(x),Qe(x);break e}if(we==="ollama"&&
|
|
1719
|
-
${h.yellow}\u26A0 Max iterations reached.${h.reset}`),await
|
|
1718
|
+
${Te}`),be(x),Qe(x);break e}if(we==="ollama"&&nc<Tf){if(B.size===0&&!Bi){console.log(`${h.yellow} \u26A0 Max iterations reached with no progress. Stopping.${h.reset}`);break e}nc++,It=20,console.log(`${h.dim} \u2500\u2500 auto-extending (+20 turns, ext ${nc}/${Tf}) \u2500\u2500${h.reset}`);continue e}if(console.log(`
|
|
1719
|
+
${h.yellow}\u26A0 Max iterations reached.${h.reset}`),await Uw(" Continue for 20 more turns?")){It=20;continue e}console.log(`${h.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${h.reset}`)}break e}if(De&&St&&B.size===0&&qe===0){let le=[...x].reverse().find(Te=>Te.role==="assistant"),we=typeof le?.content=="string"?le.content:"";if(!/\b(no safe task found|implementation stalled before edits)\b/i.test(we)){let Te=`Implementation stalled before edits.
|
|
1720
1720
|
|
|
1721
1721
|
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:Te};x.push(ke),_.push(ke),console.log(`
|
|
1722
|
-
${Te}`),je(de,Pe,B,Ee,Me),be(x),Qe(x)}}await
|
|
1723
|
-
`)}var lt={},Pt=null,$t=null,go=[];function
|
|
1724
|
-
`)}return await t(a,i,u)}catch(d){if(n=d,!
|
|
1725
|
-
`),await t(a,i,p)}catch(m){if(n=m,!
|
|
1726
|
-
`+
|
|
1722
|
+
${Te}`),je(de,Pe,B,Ee,Me),be(x),Qe(x)}}await qi()}function u0(t,e,n,o=!1){return!o&&t&&e&&e.isComplex&&e.estimatedGoals>=n}d0.exports={processInput:EO,clearConversation:gO,getConversationLength:bO,getConversationMessages:wO,setConversationMessages:_O,setAbortSignalGetter:SA,setMaxIterations:xA,invalidateSystemPromptCache:vl,clearToolFilterCache:PA,getCachedFilteredTools:Vw,buildSystemPrompt:rf,splitSystemPrompt:mO,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:of,getProjectContextHash:Xw,_inferVerificationCommands:Wl,_inferRelevantTests:Ai,_inferSymbolTargets:i0,_buildSymbolHintBlock:a0,_detectResponseLanguage:uf,_isSimpleDirectAnswerPrompt:l0,_claimsVerificationOrCompletion:Ud,_statesVerificationGap:Wd,_shouldAutoOrchestrate:u0,_shouldSkipPlanPhaseForDirectCreation:tf,_hasAutomationOrPreflightGate:Oi,_extractDirectTaskPaths:Si,_isBoundedBacklogPlanningPrompt:e0,_buildBoundedBacklogPlanInstruction:Gn,_looksLikeBoundedBacklogDecision:yi,_looksLikeGatedAutomationFinalSummary:nf,buildUserContent:zw,_detectImageURLs:Hw,_downloadImageURL:Gw,_grabClipboardImage:Yw,detectFrustration:Kw,detectAndTruncateLoop:Hd,injectMidRunNote:sO,resetSessionTracking:c0}});var Tt=ee((tN,g0)=>{var{OllamaProvider:TO,getOllamaRecommendations:RO}=Ff(),{OpenAIProvider:CO}=pc(),{DeepSeekProvider:AO}=Yf(),{AnthropicProvider:OO}=Xf(),{GeminiProvider:PO}=ep(),{LocalProvider:MO}=sp(),{checkBudget:NO,formatProviderCostMode:LO,getProviderCostMode:IO}=aa(),hf={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"}},pf=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),p0={};for(let[t,e]of Object.entries(hf))for(let n of Object.values(e))p0[n]=t;function h0(t,e){let n=p0[t];return n&&hf[n][e]||t}function Yl(){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(`
|
|
1723
|
+
`)}var lt={},Pt=null,$t=null,go=[];function an(){let t=process.env.NEX_MOCK_PROVIDER==="1";if(Object.keys(lt).length>0){if(t&&!lt.mock){let{MockProvider:s}=$c();ls("mock",new s)}t&<.mock&&Pt!=="mock"&&(Pt="mock",$t=lt.mock.defaultModel||"mock-model",go=[],Pi());return}if(ls("ollama",new TO),ls("openai",new CO),ls("deepseek",new AO),ls("anthropic",new OO),ls("gemini",new PO),ls("local",new MO),t){let{MockProvider:s}=$c();ls("mock",new s)}let e=process.env.DEFAULT_PROVIDER||"ollama",n=process.env.DEFAULT_MODEL||null;t?(Pt="mock",$t=lt.mock?.defaultModel||"mock-model",go=[]):lt[e]?(Pt=e,$t=n||lt[e].defaultModel):(Pt="ollama",$t="kimi-k2.5");let o=process.env.FALLBACK_CHAIN;o&&(go=o.split(",").map(s=>s.trim()).filter(Boolean))}function ls(t,e){lt[t]=e}function jO(t){return an(),lt[t]||null}function mf(){return an(),lt[Pt]||null}function DO(){return an(),Pt}function qO(){return an(),$t}function FO(){an();let t=mf();if(!t)return{id:$t,name:$t,provider:Pt};let e=t.getModel($t);return e?{...e,provider:Pt}:{id:$t,name:$t,provider:Pt}}function gf(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(lt[n]||["ollama","openai","deepseek","anthropic","gemini","local","mock"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function BO(t){an();let{provider:e,model:n}=gf(t);if(e){let s=lt[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(Pt=e,$t=n,Pi(),!0):!1}let o=mf();if(o&&o.getModel(n))return $t=n,Pi(),!0;for(let[s,r]of Object.entries(lt))if(r.getModel(n))return Pt=s,$t=n,Pi(),!0;return!1}function Pi(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ud();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Fn();t()}catch{}}function UO(){an();let t=new Set;for(let e of Object.values(lt))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function WO(){return an(),Object.entries(lt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===Pt&&n.id===$t}))}))}function HO(){an();let t=[];for(let[e,n]of Object.entries(lt)){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 GO(t="coding",e={}){an();let n=e.limit||5,o=e.configuredOnly!==!1,s=[],r=lt.ollama;if(r&&(!o||r.isConfigured()))for(let i of RO(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(lt)){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 YO(t){go=Array.isArray(t)?t:[]}function zO(){return[...go]}function f0(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 m0(t){let e=[Pt,...go.filter(r=>r!==Pt)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],a=lt[i];if(!a||!a.isConfigured())continue;s++;let l=NO(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?h0($t,i):$t;try{if(c){let d=IO(i).label;process.stderr.write(` [fallback: ${i}:${u} \xB7 ${d}]
|
|
1724
|
+
`)}return await t(a,i,u)}catch(d){if(n=d,!f0(d)||r>=e.length-1)throw d;if(i==="ollama"&&pf.length>0){let f=u;for(let p of pf)if(p!==f)try{return process.stderr.write(` [ollama fallback: ${p}]
|
|
1725
|
+
`),await t(a,i,p)}catch(m){if(n=m,!f0(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(Yl()):n||new Error(Yl())}async function KO(t,e,n={}){an();let o=n.model,s=o?(()=>{let{model:i}=gf(o);return i||o})():void 0,r=s!==o?{...n,model:s}:n;return m0((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function VO(t,e,n={}){if(an(),n.provider){let o=lt[n.provider];if(!o||!o.isConfigured()){let r=LO(n.provider);throw new Error(`Provider '${n.provider}' is not available (${r}).
|
|
1726
|
+
`+Yl())}let s={model:n.model||$t,...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 m0(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 XO(){an();let t=[];for(let[e,n]of Object.entries(lt))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function JO(){for(let t of Object.keys(lt))delete lt[t];Pt=null,$t=null,go=[]}g0.exports={registerProvider:ls,getProvider:jO,getActiveProvider:mf,getActiveProviderName:DO,getActiveModelId:qO,getActiveModel:FO,setActiveModel:BO,getModelNames:UO,parseModelSpec:gf,listProviders:WO,listAllModels:HO,recommendModels:GO,callStream:KO,callChat:VO,getConfiguredProviders:XO,setFallbackChain:YO,getFallbackChain:zO,resolveModelForProvider:h0,buildNoConfiguredProviderError:Yl,MODEL_EQUIVALENTS:hf,OLLAMA_FALLBACK_MODELS:pf,_reset:JO}});var nl=ee((sN,j0)=>{var{callStream:ZO,getActiveProviderName:Kl,getActiveModelId:y0,getConfiguredProviders:QO,getProvider:b0,getActiveProvider:w0,parseModelSpec:_0}=Tt(),{parseToolArgs:$0}=br(),{filterToolsForModel:eP,getModelTier:zl}=Or(),{getModelBriefing:tP}=pl(),{trackUsage:k0,estimateTokens:x0}=aa(),{MultiProgress:nP,C:nN}=Et();function S0(t){return!t||typeof t!="string"?0:typeof x0=="function"?x0(t):Math.ceil(t.length/4)}var T0=15,sP=parseInt(process.env.NEX_MAX_PARALLEL||"10",10),v0=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),R0=8,oP=2,Vl=new Map,C0=600*1e3;function rP(t,e){let n=Vl.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<C0?!1:(Vl.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Mi(t){Vl.delete(t)}function yf(){Vl.clear()}function bf(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 A0(t){let e=bf(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function O0(t,e,n){let o;for(let s=0;s<=v0;s++)try{return await ZO(t,e,n)}catch(r){o=r;let i=bf(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<v0&&A0(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 E0=new Set(["ask_user","task_list"]);function P0(t){return t>=2?new Set([...E0,"spawn_agents"]):E0}var iP=new Set(["write_file","edit_file","patch_file"]),M0={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:""}},aP=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,lP=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function N0(t){return lP.test(t)?"full":aP.test(t)?"essential":t.length>300?"full":"standard"}function L0(t){let e=QO(),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(zl(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var cP={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Xl(t){if(t.model){let{provider:s,model:r}=_0(t.model),i=s?b0(s):w0(),a=s||Kl();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=zl(r,a);return{provider:a,model:r,tier:l}}}let e=N0(t.task),n=cP[e];if(n){let{provider:s,model:r}=_0(n),i=s?b0(s):w0(),a=s||Kl();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=zl(r,a);return{provider:a,model:r,tier:l}}}let o=L0(e);if(o){let s=zl(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function I0(t,e={},n=0){let o=n===0?T0:R0,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.
|
|
1727
1727
|
|
|
1728
1728
|
TASK: ${t.task}
|
|
1729
1729
|
${t.context?`
|
|
@@ -1749,19 +1749,19 @@ TOOL STRATEGY:
|
|
|
1749
1749
|
ERROR RECOVERY:
|
|
1750
1750
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
1751
1751
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
1752
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&
|
|
1752
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&M0[t.type],f=d&&d.systemSuffix?`
|
|
1753
1753
|
|
|
1754
|
-
${d.systemSuffix}`:"",p=
|
|
1754
|
+
${d.systemSuffix}`:"",p=Xl(t),m=p.provider,g=p.model,w=p.tier,k=tP(g||y0()),$=[{role:"system",content:(k?`## Model Briefing
|
|
1755
1755
|
${k}
|
|
1756
1756
|
|
|
1757
1757
|
---
|
|
1758
1758
|
|
|
1759
|
-
`:"")+u+f}];$.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:R,executeTool:O}=
|
|
1760
|
-
`)}let K={};m&&(K.provider=m),g&&(K.model=g);let V=new Set;try{for(let J=0;J<s;J++){let ne=await
|
|
1761
|
-
...(truncated)`:P,tool_call_id:_}}).catch(te=>(W&&(
|
|
1762
|
-
`)}catch(u){return c.stop(),
|
|
1759
|
+
`:"")+u+f}];$.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:R,executeTool:O}=vr(),N=P0(n),z=eP(R.filter(ie=>!N.has(ie.function.name)),w);if(d&&d.allowedTools&&(z=z.filter(ie=>d.allowedTools.has(ie.function.name))),g&&!t._skipLog){let ie=w?` (${w})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${ie}]
|
|
1760
|
+
`)}let K={};m&&(K.provider=m),g&&(K.model=g);let V=new Set;try{for(let J=0;J<s;J++){let ne=await O0($,z,K);if(!ne||typeof ne!="object")throw new Error("Empty or invalid response from provider");{let Ce=m||Kl(),Ae=g||y0();if(ne.usage){let E=ne.usage.prompt_tokens||0,_=ne.usage.completion_tokens||0;a.input+=E,a.output+=_,k0(Ce,Ae,E,_)}else{let E=ne.content||"",_=$.map(te=>typeof te.content=="string"?te.content:Array.isArray(te.content)?te.content.map(P=>typeof P=="string"?P:P.text||"").join(""):"").join(" "),W=S0(_),se=S0(E);a.input+=W,a.output+=se,a._estimated=!0,k0(Ce,Ae,W,se)}}let Ke=ne.content||"",ve=ne.tool_calls,H={role:"assistant",content:Ke||""};if(ve&&ve.length>0&&(H.tool_calls=ve),$.push(H),!ve||ve.length===0){for(let Ce of l)Mi(Ce);return{task:t.task,status:"done",result:Ke||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let oe=new Set,et=ve.map(Ce=>{let Ae=Ce.function.name,E=$0(Ce.function.arguments),_=Ce.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!E)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${Ae}`,tool_call_id:_});if(["edit_file","patch_file"].includes(Ae)&&E.path){if(V.has(E.path)||oe.has(E.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${E.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:_});oe.add(E.path)}let W=null;if(iP.has(Ae)&&E.path){let te=require("path"),P=te.isAbsolute(E.path)?E.path:te.resolve(process.cwd(),E.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let pe=te.relative(process.cwd(),P);if(t._readOnlyFiles.some(_e=>pe===_e||pe.startsWith(_e+"/")||P===_e||P.startsWith(_e+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${E.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:_})}if(l.has(P)||!rP(P,r))return Promise.resolve({role:"tool",content:`ERROR: File '${E.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:_});l.add(P),W=P}return i.push(Ae),e.onUpdate&&e.onUpdate({type:"tool_call",tool:Ae,agentId:r}),(Ae==="spawn_agents"?wf(E,n+1):O(Ae,E,{autoConfirm:!0,silent:!0})).then(te=>{W&&(Mi(W),l.delete(W));let P=String(te??"");return E&&E.path&&(["edit_file","patch_file","write_file"].includes(Ae)&&P.startsWith("Edited:")?V.add(E.path):Ae==="read_file"&&!P.startsWith("ERROR")&&V.delete(E.path)),{role:"tool",content:P.length>2e4?P.substring(0,2e4)+`
|
|
1761
|
+
...(truncated)`:P,tool_call_id:_}}).catch(te=>(W&&(Mi(W),l.delete(W)),{role:"tool",content:`ERROR: ${te.message}`,tool_call_id:_}))}),Ve=await Promise.all(et);if($.push(...Ve),J>=7&&$.length>12)try{let{compressMessage:Ce}=Fn(),Ae=$.length-6;for(let E=1;E<Ae;E++)$[E]._subAgentCompressed||($[E]={...Ce($[E],"light"),_subAgentCompressed:!0})}catch{}for(let Ce=0;Ce<ve.length;Ce++){let Ae=ve[Ce];if(Ae.function.name==="bash_exec"){let E=$0(Ae.function.arguments);if((Ve[Ce]?.content||"").startsWith("ERROR")&&E&&E.command){let W=E.command.replace(/\s+/g," ").trim().slice(0,100);c.set(W,(c.get(W)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${J+1}/${s}`)}for(let J of l)Mi(J);let ie=[...c.entries()].filter(([,J])=>J>=3).sort((J,ne)=>ne[1]-J[1]).slice(0,3).map(([J,ne])=>`"${J}" (failed ${ne}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ie,result:$[$.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(ie){for(let J of l)Mi(J);return{task:t.task,status:"failed",result:`Error: ${ie.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function wf(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?sP:oP,o=e===0?T0:R0,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=>Xl(u)),l=s.map((u,d)=>{let f=a[d],p=f.model?` [${f.model}]`:"",m=u.task.substring(0,i-p.length);return`${r}Agent ${d+1}${p}: ${m}${u.task.length>m.length?"...":""}`}),c=new nP(l);c.start();try{let u=s.map((g,w)=>{let k=a[w],T=Math.min(g.max_iterations||o,o),$=k.model?{...g,model:`${k.provider}:${k.model}`,_skipLog:!0,max_iterations:T}:{...g,_skipLog:!0,max_iterations:T};return I0($,{onUpdate:()=>{}},e).then(R=>(c.update(w,R.status==="failed"?"error":"done"),R)).catch(R=>(c.update(w,"error"),{task:g.task,status:"failed",result:`Error: ${R.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),yf();let f=["Sub-agent results:",""],p=0,m=0;for(let g=0;g<d.length;g++){let w=d[g],k=w.status==="done"?"\u2713":w.status==="truncated"?"\u26A0":"\u2717",T=w.modelSpec?` [${w.modelSpec}]`:"";f.push(`${k} Agent ${g+1}${T}: ${w.task}`),f.push(` Status: ${w.status}`),f.push(` Tools used: ${w.toolsUsed.length>0?w.toolsUsed.join(", "):"none"}`),f.push(` Result: ${w.result}`),w.repeatedFailures&&w.repeatedFailures.length>0&&f.push(` Repeated failures: ${w.repeatedFailures.join("; ")}`),f.push(""),p+=w.tokensUsed.input,m+=w.tokensUsed.output}return f.push(`Total sub-agent tokens: ${p} input + ${m} output`),f.join(`
|
|
1762
|
+
`)}catch(u){return c.stop(),yf(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function uP(t){let{createJob:e}=Jo(),n=(t.agents||[]).filter(i=>i.background),o=(t.agents||[]).filter(i=>!i.background),s=n.map(i=>{let a=Xl(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(", ")}]
|
|
1763
1763
|
`+n.map((i,a)=>` ${s[a]}: ${i.task}`).join(`
|
|
1764
1764
|
`)+`
|
|
1765
|
-
Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await
|
|
1765
|
+
Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await wf({agents:o});r.push(i)}return r.join(`
|
|
1766
1766
|
|
|
1767
|
-
`)||"No agents specified."}
|
|
1767
|
+
`)||"No agents specified."}j0.exports={runSubAgent:I0,executeSpawnAgents:wf,executeSpawnAgentsBackground:uP,clearAllLocks:yf,classifyTask:N0,pickModelForTier:L0,resolveSubAgentModel:Xl,classifyError:bf,isRetryableError:A0,callWithRetry:O0,getExcludedTools:P0,LOCK_TIMEOUT_MS:C0,SUB_AGENT_TYPES:M0}});var{runSubAgent:dP}=nl();process.on("message",async({jobId:t,agentDef:e})=>{try{let n=await dP({...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)}});
|