hablas-ai 1.3.10 → 1.3.11

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.
Files changed (2) hide show
  1. package/dist/index.js +8 -8
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -20,7 +20,7 @@ Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
20
20
  `),this.outputHelp({error:!0}));let s=t||{},r=s.exitCode||1,i=s.code||"commander.error";this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in de.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,de.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new fy(this.options),t=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&t(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(r=>!t(r)).forEach(r=>{this.setOptionValueWithSource(r,s.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let s=o=>{let a=o.attributeName(),l=this.getOptionValue(a),u=this.options.find(f=>f.negate&&a===f.attributeName()),d=this.options.find(f=>!f.negate&&a===f.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:d||o},r=o=>{let a=s(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);r=r.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=tc(e,r)}let s=`error: unknown option '${e}'${t}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,s=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${s} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(i=>{r.push(i.name()),i.alias()&&r.push(i.alias())}),t=tc(e,r)}let s=`error: unknown command '${e}'${t}`;this.error(s,{code:"commander.unknownCommand"})}version(e,t,s){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",s=s||"output the version number";let r=this.createOption(t,s);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
21
  `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let r=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(s=>uy(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=At.basename(e,At.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},s;return t.error?s=r=>this._outputConfiguration.writeErr(r):s=r=>this._outputConfiguration.writeOut(r),t.write=e.write||s,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let s=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let r=this.helpInformation(s);if(t&&(r=t(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",s))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=de.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let s=["beforeAll","before","after","afterAll"];if(!s.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
22
  Expecting one of '${s.join("', '")}'`);let r=`${e}Help`;return this.on(r,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
23
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function nc(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,s="127.0.0.1",r="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?r=i[3]:s=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],s=i[3],r=i[4]),t&&r!=="0"?`${t}=${s}:${parseInt(r)+1}`:e})}sc.Command=ci});var lc=N(We=>{var{Argument:ic}=Cs(),{Command:ui}=rc(),{CommanderError:py,InvalidArgumentError:oc}=Ln(),{Help:hy}=ti(),{Option:ac}=ii();We.program=new ui;We.createCommand=n=>new ui(n);We.createOption=(n,e)=>new ac(n,e);We.createArgument=(n,e)=>new ic(n,e);We.Command=ui;We.Option=ac;We.Argument=ic;We.Help=hy;We.CommanderError=py;We.InvalidArgumentError=oc;We.InvalidOptionArgumentError=oc});var dc={};Fe(dc,{DEFAULT_CONFIG:()=>Fn,NVIDIA_PROVIDER:()=>Nt});var Fn,Nt,Nn=L(()=>{"use strict";Fn={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",contextBudget:32e3,streamingEnabled:!0,autoConfirmSafe:!0,autoMode:!1,workingDirectory:".",historySize:800,timeout:12e4,maxRetries:3,tools:{runCommand:{allowedCommands:[],blocklist:[],timeout:12e4}},ui:{theme:"dark",showTokenCount:!0,diffPreview:!0,compactMode:!1,dashboard:!1},cache:{enabled:!0,maxEntries:100,ttlMs:3e5},logging:{level:"info",file:!0},plugins:{enabled:!0,directory:"~/.hablas/plugins",marketplace:"https://registry.hablas.dev/plugins"},agents:{enabled:!0,orchestration:"auto",maxConcurrent:3},context:{astParsing:!0,projectGraph:!0,longTermMemory:!0,fileWatcher:!0},workspace:{frameworkDetection:!0,gitAwareness:!0,envParsing:!0,autoPush:!1},security:{scanOnCommit:!1,secretDetection:!0,dependencyAudit:!0},analytics:{enabled:!0,trackUsage:!0,weeklyReports:!1},collaboration:{enabled:!1,teamConfigPath:".hablas/team.json",sharedMemory:!1},team:{enabled:!1,user:"",key:""},api:{enabled:!1,port:8080,host:"0.0.0.0",apiKey:""},license:{tier:"free",key:""}},Nt={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.1-nemotron-70b-instruct","nvidia/nemotron-4-340b-instruct","meta/llama-3.1-405b-instruct","meta/llama-3.1-70b-instruct","meta/llama-3.1-8b-instruct","mistralai/mixtral-8x22b-instruct-v0.1","mistralai/mistral-large-latest","google/gemma-2-27b-it","microsoft/phi-3-medium-128k-instruct","deepseek-ai/deepseek-coder-33b-instruct","nvidia/llama-3.1-nemotron-51b-instruct","qwen/qwen2.5-coder-32b-instruct"]}});var Es,fc=L(()=>{"use strict";Es=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(s=>s.name):[]}catch{return[]}}async chatWithTools(e,t,s){let r={model:this.model,messages:e,stream:!1};t.length>0&&(r.tools=t);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)};s&&(i.signal=s);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,t){let s=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:t});if(!s.ok)throw new Error(`Ollama error: ${s.status} ${s.statusText}`);let r=s.body?.getReader();if(!r)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await r.read();if(a)break;o+=i.decode(l,{stream:!0});let u=o.split(`
23
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function nc(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,s="127.0.0.1",r="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?r=i[3]:s=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],s=i[3],r=i[4]),t&&r!=="0"?`${t}=${s}:${parseInt(r)+1}`:e})}sc.Command=ci});var lc=N(We=>{var{Argument:ic}=Cs(),{Command:ui}=rc(),{CommanderError:py,InvalidArgumentError:oc}=Ln(),{Help:hy}=ti(),{Option:ac}=ii();We.program=new ui;We.createCommand=n=>new ui(n);We.createOption=(n,e)=>new ac(n,e);We.createArgument=(n,e)=>new ic(n,e);We.Command=ui;We.Option=ac;We.Argument=ic;We.Help=hy;We.CommanderError=py;We.InvalidArgumentError=oc;We.InvalidOptionArgumentError=oc});var dc={};Fe(dc,{DEFAULT_CONFIG:()=>Fn,NVIDIA_PROVIDER:()=>Nt});var Fn,Nt,Nn=L(()=>{"use strict";Fn={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",contextBudget:2e5,streamingEnabled:!0,autoConfirmSafe:!0,autoMode:!1,workingDirectory:".",historySize:1e4,timeout:12e4,maxRetries:3,tools:{runCommand:{allowedCommands:[],blocklist:[],timeout:12e4}},ui:{theme:"dark",showTokenCount:!0,diffPreview:!0,compactMode:!1,dashboard:!1},cache:{enabled:!0,maxEntries:100,ttlMs:3e5},logging:{level:"info",file:!0},plugins:{enabled:!0,directory:"~/.hablas/plugins",marketplace:"https://registry.hablas.dev/plugins"},agents:{enabled:!0,orchestration:"auto",maxConcurrent:3},context:{astParsing:!0,projectGraph:!0,longTermMemory:!0,fileWatcher:!0},workspace:{frameworkDetection:!0,gitAwareness:!0,envParsing:!0,autoPush:!1},security:{scanOnCommit:!1,secretDetection:!0,dependencyAudit:!0},analytics:{enabled:!0,trackUsage:!0,weeklyReports:!1},collaboration:{enabled:!1,teamConfigPath:".hablas/team.json",sharedMemory:!1},team:{enabled:!1,user:"",key:""},api:{enabled:!1,port:8080,host:"0.0.0.0",apiKey:""},license:{tier:"free",key:""}},Nt={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.1-nemotron-70b-instruct","nvidia/nemotron-4-340b-instruct","meta/llama-3.1-405b-instruct","meta/llama-3.1-70b-instruct","meta/llama-3.1-8b-instruct","mistralai/mixtral-8x22b-instruct-v0.1","mistralai/mistral-large-latest","google/gemma-2-27b-it","microsoft/phi-3-medium-128k-instruct","deepseek-ai/deepseek-coder-33b-instruct","nvidia/llama-3.1-nemotron-51b-instruct","qwen/qwen2.5-coder-32b-instruct"]}});var Es,fc=L(()=>{"use strict";Es=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(s=>s.name):[]}catch{return[]}}async chatWithTools(e,t,s){let r={model:this.model,messages:e,stream:!1};t.length>0&&(r.tools=t);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)};s&&(i.signal=s);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,t){let s=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:t});if(!s.ok)throw new Error(`Ollama error: ${s.status} ${s.statusText}`);let r=s.body?.getReader();if(!r)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await r.read();if(a)break;o+=i.decode(l,{stream:!0});let u=o.split(`
24
24
  `);o=u.pop()||"";for(let d of u)if(d.trim())try{let f=JSON.parse(d);f.message?.content&&(yield f.message.content)}catch{}}}}});function mc(n){return n.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let t=e.tool_calls.filter(s=>s?.function?.name);if(t.length>0)return{role:"assistant",content:e.content||null,tool_calls:t.map((s,r)=>({id:`call_${r}`,type:"function",function:{name:s.function?.name||"",arguments:JSON.stringify(s.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function yy(n){return n.map(e=>({type:"function",function:e.function}))}function by(n){return n.filter(e=>e?.function?.name).map(e=>{let t={};try{t=JSON.parse(e.function?.arguments||"{}")}catch{t={_raw:e.function?.arguments}}return{function:{name:e.function?.name||"",arguments:t}}})}function gc(n){return new Promise(e=>setTimeout(e,n))}function yc(n,e){return!(n.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var pc,my,Ts,hc,gy,Gt,di=L(()=>{"use strict";pc=12e4,my=6e4,Ts=3,hc=1e3,gy=20;Gt=class{apiUrl;apiKey;model;constructor(e){this.apiUrl=e.apiUrl||"https://api.openai.com/v1",this.apiKey=e.apiKey,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}setApiUrl(e){this.apiUrl=e}getApiUrl(){return this.apiUrl}setApiKey(e){this.apiKey=e}async checkConnection(){try{let e=this.apiUrl.replace(/\/+$/,"")+"/models";return(await fetch(e,{headers:this.getHeaders(),signal:AbortSignal.timeout(15e3)})).ok}catch{return!1}}async listModels(){try{let e=[],t=!0,s,r=0;for(;t&&r<gy;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;s&&o.set("after",s),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let l=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(my)});if(!l.ok)break;let u=await l.json();if(Array.isArray(u))e.push(...u.map(d=>d.id||d.name||d).filter(Boolean)),t=!1;else if(u.data&&Array.isArray(u.data)){let d=u.data.map(f=>f.id||f.name).filter(Boolean);e.push(...d),u.has_more&&d.length>0?(s=d[d.length-1],r++):t=!1}else u.models&&Array.isArray(u.models)&&e.push(...u.models.map(d=>d.name||d.id).filter(Boolean)),t=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,t,s){let r=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:mc(e)};t.length>0&&(i.tools=yy(t),i.tool_choice="auto");let o=null;for(let a=0;a<=Ts;a++)try{let l=new AbortController,u=setTimeout(()=>l.abort(),pc),d={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:s||l.signal};try{let f=await fetch(r,d);if(clearTimeout(u),!f.ok){let g=await f.text().catch(()=>"");if(!yc(null,f.status))throw new Error(`API error: ${f.status} ${f.statusText} \u2014 ${g}`);if(o=new Error(`API error: ${f.status} ${f.statusText} \u2014 ${g}`),a<Ts){let x=hc*Math.pow(2,a);await gc(x);continue}throw o}let m=(await f.json()).choices?.[0];if(!m)throw new Error("API returned empty response");let p=m.message.tool_calls?by(m.message.tool_calls):void 0;return{message:{role:m.message.role||"assistant",content:m.message.content||"",tool_calls:p},done:!0,done_reason:m.finish_reason}}catch(f){if(clearTimeout(u),f.name==="AbortError"&&s?.aborted)throw f;if(yc(f)&&(o=f,a<Ts)){let h=hc*Math.pow(2,a);await gc(h);continue}throw f}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Ts)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,t){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:mc(e),stream:!0}),signal:t||AbortSignal.timeout(pc)});if(!r.ok)throw new Error(`API error: ${r.status} ${r.statusText}`);let i=r.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:u}=await i.read();if(l)break;a+=o.decode(u,{stream:!0});let d=a.split(`
25
25
  `);a=d.pop()||"";for(let f of d){let h=f.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let p=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;p&&(yield p)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}}});function Me(n){if(n.provider==="nvidia"){let e={...n,provider:"custom",apiUrl:Nt.apiUrl};return new Gt(e)}return n.provider==="custom"&&n.apiUrl?new Gt(n):new Es(n)}function Rs(n){if(n.provider==="nvidia")return"NVIDIA NIM";if(n.provider==="custom")try{return`Custom (${new URL(n.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var jn=L(()=>{"use strict";Nn();fc();di()});var bc=L(()=>{"use strict"});function Vt(){let n={providers:[],activeProvider:null,activeModel:null};try{if($t.existsSync(pi)){let e=$t.readFileSync(pi,"utf-8"),t=JSON.parse(e);return{...n,...t}}}catch{}return n}function mi(n){$t.existsSync(fi)||$t.mkdirSync(fi,{recursive:!0}),$t.writeFileSync(pi,JSON.stringify(n,null,2),"utf-8")}function tt(n){let e=Vt();e.providers=e.providers.filter(t=>t.name!==n.name),e.providers.push(n),mi(e)}function wc(n){let e=Vt(),t=e.providers.length;return e.providers=e.providers.filter(s=>s.name!==n),e.providers.length<t?(e.activeProvider===n&&(e.activeProvider=null,e.activeModel=null),mi(e),!0):!1}function xc(n){return Vt().providers.find(t=>t.name.toLowerCase()===n.toLowerCase())}function Os(){return Vt().providers}function Sc(n,e){let t=Vt(),s=t.providers.find(r=>r.name===n);s&&(t.activeProvider=n,t.activeModel=e||s.defaultModel,mi(t))}function _c(n,e){if(n.length===0)return" No saved providers. Use /addmodel to add one.";let t=[];t.push(" Saved Providers:"),t.push("");for(let s of n){let r=s.name===e,i=r?" \u25CF active":"",o=s.apiKey?"***"+s.apiKey.slice(-4):"no key";t.push(` ${r?"\u25B8":"\xB7"} ${s.name}${i}`),t.push(` URL: ${s.apiUrl}`),t.push(` Key: ${o}`),t.push(` Model: ${s.defaultModel}`),t.push(` Added: ${new Date(s.addedAt).toLocaleDateString()}`),t.push("")}return t.join(`
26
26
  `)}var $t,hi,vc,fi,pi,gi=L(()=>{"use strict";$t=O(require("fs")),hi=O(require("path")),vc=O(require("os"));bc();fi=hi.join(vc.homedir(),".hablas"),pi=hi.join(fi,"models.json")});function Is(){try{if(Ct.existsSync(Ps))return JSON.parse(Ct.readFileSync(Ps,"utf-8"))}catch{}return{}}function Ac(n){let e=Ms.dirname(Ps);Ct.existsSync(e)||Ct.mkdirSync(e,{recursive:!0}),Ct.writeFileSync(Ps,JSON.stringify(n,null,2),"utf-8")}function $c(n,e){let t=Is();t[n]=e,Ac(t)}function Cc(n){let e=Is();return e[n]?(delete e[n],Ac(e),!0):!1}function Ec(n){let e=Is(),t=n.trim();for(let[s,r]of Object.entries(e))if(t===s||t.startsWith(s+" "))return t.replace(s,r);return n}function Tc(){let n=Is(),e=Object.entries(n);return e.length===0?` No aliases defined.
@@ -963,7 +963,7 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
963
963
  `)}getTurnSummary(){let e=this.turnSteps.length,t=this.turnSteps.filter(r=>r.action).length,s=this.turnSteps.filter(r=>r.reflection).length;return`${e} steps, ${t} actions, ${s} reflections`}}});function gs(n=3){return new Il(n)}var N$,Il,Dl=L(()=>{"use strict";N$=[{test:n=>/ENOENT|no such file|not found|does not exist/i.test(n),errorClass:"file_not_found",strategy:"read_first",explanation:"The file or directory does not exist.",suggestion:"Use list_dir to check what files exist, then retry with the correct path.",alternatives:["list_dir","search_codebase"],autoRetry:!1},{test:n=>/EACCES|permission denied/i.test(n),errorClass:"permission_denied",strategy:"graceful_fail",explanation:"Permission denied \u2014 the process lacks access rights.",suggestion:"Check file ownership or try a different path. Do NOT use sudo.",alternatives:[],autoRetry:!1},{test:n=>/EISDIR|is a directory/i.test(n),errorClass:"path_is_directory",strategy:"retry_fixed",explanation:"The path points to a directory, not a file.",suggestion:"Append the filename to the path. Use list_dir to see contents.",alternatives:["list_dir"],autoRetry:!1},{test:n=>/EEXIST|already exists/i.test(n),errorClass:"file_already_exists",strategy:"read_first",explanation:"A file or directory already exists at that path.",suggestion:"Read the existing file first, then decide whether to overwrite or edit it.",alternatives:["read_file","edit_file"],autoRetry:!1},{test:n=>/no match|not found in file|search string not found/i.test(n),errorClass:"search_no_match",strategy:"read_first",explanation:"The search string was not found in the file.",suggestion:"Read the file first to see its actual content, then use the exact text for search/replace.",alternatives:["read_file","search_codebase"],autoRetry:!1},{test:n=>/command not found|not recognized/i.test(n),errorClass:"command_not_found",strategy:"alternative_tool",explanation:"The command does not exist on this system.",suggestion:"Check if the program is installed, or use a different command that achieves the same goal.",alternatives:["run_command"],autoRetry:!1},{test:n=>/timeout|timed out|ETIMEDOUT/i.test(n),errorClass:"command_timeout",strategy:"retry_fixed",explanation:"The command took too long and was terminated.",suggestion:"Try a simpler version of the command, or increase the timeout, or run it in background.",alternatives:[],autoRetry:!1},{test:n=>/exit code|exited with|non-zero/i.test(n),errorClass:"command_exit_error",strategy:"retry_fixed",explanation:"The command executed but returned an error.",suggestion:"Read the error output carefully. Fix the root cause (missing dependency, wrong syntax, etc.).",alternatives:[],autoRetry:!1},{test:n=>/syntax error|unexpected token|parse error|SyntaxError/i.test(n),errorClass:"syntax_error",strategy:"retry_fixed",explanation:"The content has a syntax error.",suggestion:"Review the generated code for syntax issues, fix them, and retry.",alternatives:[],autoRetry:!1},{test:n=>/ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(n),errorClass:"network_error",strategy:"retry_same",explanation:"Network connection failed.",suggestion:"This may be transient. Retry the same operation, or check connectivity.",alternatives:[],autoRetry:!0},{test:n=>/invalid argument|missing required|expected.*but got|type error/i.test(n),errorClass:"invalid_arguments",strategy:"retry_fixed",explanation:"The tool was called with invalid or missing arguments.",suggestion:"Check the tool's parameter requirements and provide correct values.",alternatives:[],autoRetry:!1},{test:n=>/ENOMEM|out of memory|resource|too large|max.*exceeded/i.test(n),errorClass:"resource_limit",strategy:"decompose_task",explanation:"Resource limit exceeded (memory, file size, etc.).",suggestion:"Break the task into smaller pieces, or process less data at once.",alternatives:[],autoRetry:!1}],Il=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,t,s){let r=this.failures.get(e),i=r?r.count+1:1,o={tool:e,count:i,lastError:t,lastStrategy:"retry_same"};if(i>this.maxRetriesPerTool)return o.lastStrategy="ask_user",this.failures.set(e,o),{errorClass:"unknown",strategy:"ask_user",explanation:`Tool "${e}" has failed ${i} times in this turn.`,suggestion:`Stop retrying "${e}". Ask the user for clarification or try a completely different approach.`,alternatives:this.suggestAlternatives(e),autoRetry:!1};for(let a of N$)if(a.test(t)){let l=r?.lastStrategy===a.strategy&&i>=2,u=l?"decompose_task":a.strategy;return o.lastStrategy=u,this.failures.set(e,o),{errorClass:a.errorClass,strategy:u,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,t){let s=[`ERROR: ${t}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&s.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":s.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":s.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":s.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":s.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":s.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":s.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return s.join(`
964
964
  `)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let t=this.failures.get(e);return t?t.count<=1&&t.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}}});function j$(){try{if(Lt.existsSync(jr))return JSON.parse(Lt.readFileSync(jr,"utf-8"))}catch{}return{}}function H$(n){try{let e=Hr.dirname(jr);Lt.existsSync(e)||Lt.mkdirSync(e,{recursive:!0}),Lt.writeFileSync(jr,JSON.stringify(n,null,2),"utf-8")}catch{}}function Zm(n,e){let t=0,s=!1,r=!1;for(let i=e;i<n.length;i++){let o=n[i];if(r){r=!1;continue}if(o==="\\"&&s){r=!0;continue}if(o==='"'){s=!s;continue}if(!s&&(o==="{"&&t++,o==="}"&&(t--,t===0)))return n.slice(e,i+1)}return null}function ys(n){if(typeof n.name=="string"&&n.arguments&&typeof n.arguments=="object")return{tool:n.name,args:n.arguments};if(typeof n.tool=="string"&&n.args&&typeof n.args=="object")return{tool:n.tool,args:n.args};if(typeof n.name=="string"&&n.parameters&&typeof n.parameters=="object")return{tool:n.name,args:n.parameters};if(n.function&&typeof n.function=="object"){let e=n.function;if(typeof e.name=="string"){let t={};if(typeof e.arguments=="string")try{t=JSON.parse(e.arguments)}catch{t={}}else e.arguments&&typeof e.arguments=="object"&&(t=e.arguments);return{tool:e.name,args:t}}}return null}function B$(n){return n.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function U$(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim()),i=ys(r);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function K$(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim());if(r.parameters||r.name){let i=ys(r);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function q$(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;){let r=s[1],i=eg(r);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function eg(n){let e=[],t=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info"];for(let s of t){let r=new RegExp(`<<?${s}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${s}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=r.exec(n))!==null;){let o=i[1]||"",a=i[2]||"",l={},u=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,d;for(;(d=u.exec(o))!==null;){let h=d[1].toLowerCase(),m=d[2]??d[3]??d[4];l[h]=B$(m)}let f=a.trim();f&&(s==="write_file"||s==="append_to_file"?l.content=a:s==="run_command"?l.command=f:s==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),s==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:s,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function W$(n){return eg(n)}function G$(n){let e=[],t=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim()),i=ys(r);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function V$(n){let e=[],t=/\{\s*"function"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Zm(n,s.index);if(r)try{let i=JSON.parse(r),o=ys(i);o&&e.push({...o,format:"function_call",rawMatch:r})}catch{}}return e}function z$(n){let e=[],t=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Zm(n,s.index);if(r)try{let i=JSON.parse(r),o=ys(i);o&&e.push({...o,format:"json_object",rawMatch:r})}catch{}}return e}function Y$(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,s,r=!1;for(;(s=t.exec(n))!==null;){let i=s[1],o=/<function=([^>]+)>/i.exec(i);if(o){r=!0;let a=o[1].trim(),l={},u=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,d;for(;(d=u.exec(i))!==null;){let f=d[1].trim(),h=d[2].trim();h==="true"?h=!0:h==="false"?h=!1:!isNaN(Number(h))&&h!==""&&(h=Number(h)),l[f]=h}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:s[0]})}}if(!r&&/<function=([^>]+)>/i.test(n)){let i=/<function=([^>]+)>/i.exec(n);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=l.exec(n))!==null;){let d=u[1].trim(),f=u[2].trim();f==="true"?f=!0:f==="false"?f=!1:!isNaN(Number(f))&&f!==""&&(f=Number(f)),a[d]=f}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:n})}}return e}function tg(){return Fl||(Fl=new Nl),Fl}var Lt,Hr,Qm,jr,Ll,Nl,Fl,ng=L(()=>{"use strict";Lt=O(require("fs")),Hr=O(require("path")),Qm=O(require("os")),jr=Hr.join(Qm.homedir(),".hablas","model-formats.json");Ll=[{format:"xml_tool_call_wrapper",parse:q$},{format:"xml_prompt",parse:W$},{format:"xml_tags",parse:U$},{format:"xml_parameters",parse:Y$},{format:"hermes",parse:K$},{format:"markdown_json",parse:G$},{format:"function_call",parse:V$},{format:"json_object",parse:z$}],Nl=class{registry;constructor(){this.registry=j$()}parse(e,t,s){if(t&&Array.isArray(t)&&t.length>0){let i=t.filter(o=>o?.function?.name&&typeof o.function.name=="string");if(i.length>0){let o=i.map(a=>({function:{name:a.function.name,arguments:a.function.arguments||{}}}));return s&&this.learnFormat(s,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let r=e||"";if(!r.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(s){let i=this.registry[s];if(i&&i.format!=="native"){let o=Ll.find(a=>a.format===i.format);if(o){let a=o.parse(r);if(a.length>0)return this.learnFormat(s,i.format),this.buildResult(a,r)}}}for(let{parse:i}of Ll){let o=i(r);if(o.length>0){let a=o[0].format;return s&&this.learnFormat(s,a),this.buildResult(o,r)}}return{toolCalls:[],displayContent:r.trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let t=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(t)||/<function=/i.test(t)||t.includes("```tool_call")||t.includes("```json")&&t.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info)[\s>]/i.test(t)||t.startsWith("{")&&(t.includes('"name"')||t.includes('"tool"'))&&(t.includes('"arguments"')||t.includes('"args"')||t.includes('"parameters"'))||t.includes('"function"')&&t.includes('"name"'))}detectFormat(e){for(let{format:t,parse:s}of Ll)if(s(e).length>0)return t;return"unknown"}learnFormat(e,t){let s=this.registry[e];s&&s.format===t?(s.successCount++,s.lastUsed=new Date().toISOString()):this.registry[e]={format:t,successCount:1,lastUsed:new Date().toISOString()},H$(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[t,s]of Object.entries(this.registry))e[t]={format:s.format,successCount:s.successCount};return e}buildResult(e,t){let s=e.map(o=>({function:{name:o.tool,arguments:o.args}})),r=t,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)r=r.replace(o.rawMatch,"");return r=r.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),r=r.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),r=r.replace(/\n{3,}/g,`
965
965
 
966
- `),{toolCalls:s,displayContent:r.trim(),format:e[0]?.format??"unknown"}}},Fl=null});function X$(n,e,t){let r=tg().parse(e,n,t);return{toolCalls:r.toolCalls,displayContent:r.displayContent}}function Q$(n,e){return n==="write_file"&&typeof e.path=="string"?`create ${e.path}`:(n==="edit_file"||n==="patch_file"||n==="search_and_replace")&&typeof e.path=="string"?`modify ${e.path}`:n==="read_file"&&typeof e.path=="string"?`read ${e.path}`:n==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):typeof e.path=="string"?String(e.path):n.replace(/_/g," ")}function Z$(n){let e=(n||"").toLowerCase();return e.includes("eacces")||e.includes("permission")||e.includes("enospc")||e.includes("readonly")||e.includes("security")||e.includes("[write_file]")||e.includes("[delete_file]")||e.includes("[move_file]")||e.includes("[search_and_replace]")}async function ig(n,e,t,s){let r=0,i=Date.now();for(;r<=rg;){let o=await n.execute({name:e,arguments:t});if(o.success||r>=rg)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:r};r++,s.info({tool:e,retry:r,error:o.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-i,retries:r}}async function Br(n){let{identity:e,client:t,registry:s,session:r,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:u,skipTools:d}=n,f=n.reactEngine??ms(),h=n.errorRecovery??gs(),m=d?[]:s.getOllamaTools(),p=t.getModel(),g=n.maxIterations??J$,x=[],w=[],$=[],A="",y=0,v=!1;for(;y<g;){if(y++,u?.aborted)return{output:A,toolsUsed:qt(x),toolResults:w,touchedFiles:qt($),iterations:y,success:!1,error:"Aborted",completedNaturally:v};let b=f.buildBudgetWarningPrompt();b&&r.addUserMessage(b,{priority:"critical",tags:["system-budget"]});let S;try{S=await t.chatWithTools(r.getMessages(),m,u)}catch(G){let E=G;if(E.name==="AbortError"||u?.aborted)return{output:A,toolsUsed:qt(x),toolResults:w,touchedFiles:qt($),iterations:y,success:!1,error:"Aborted",completedNaturally:v};if(y<=1){a.onNotice?.(`Transient model error: ${E.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(k=>setTimeout(k,1e3)),y--;continue}return a.onError?.(E.message??"Model request failed"),{output:A,toolsUsed:qt(x),toolResults:w,touchedFiles:qt($),iterations:y,success:!1,error:E.message,completedNaturally:v}}let _=S.message?.content||"",T=S.message?.tool_calls,I=f.parseThinking(_);I.hasThinking&&(f.recordStep({thought:I.thinking}),o.debug({thinking:I.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:C,displayContent:F}=X$(T,_,p);if(F&&F.trim()&&(A=F,await a.onAssistantText?.(F,e)),C.length===0){r.addAssistantMessage(_,void 0,e.role),v=!0;break}r.addAssistantMessage(_,C,e.role);let H=C.length;for(let G=0;G<C.length;G++){let E=C[G];if(!E?.function?.name)continue;let k=E.function.name,Y=E.function.arguments||{},K=s.getSafetyLevel(k)??"confirm";if(!s.get(k)){a.onNotice?.(`Unknown tool: ${k} \u2014 skipping`,"warn"),r.addToolMessage(`Error: Unknown tool "${k}". Available: ${s.getAll().map(Oe=>Oe.name).join(", ")}`);continue}if(await l(k,K,Y)==="skip"){r.addToolMessage(`Tool ${k} was skipped by policy/user.`);break}x.push(k),typeof Y.path=="string"&&$.push(Y.path);let ee=Q$(k,Y);a.onToolStart?.(k,ee,Y),a.onToolCall?.(),f.recordStep({thought:I.hasThinking?`Executing: ${k}`:"",action:k,actionInput:Y});let X=await ig(s,k,Y,o);a.onToolEnd?.(k,X.success,X.error||X.output,X.duration,Y);let ue;if(X.success)ue=os(X.output,sg),f.recordObservation(ue.slice(0,300)),w.push({tool:k,success:!0,summary:X.output.slice(0,150)});else{let Oe=X.error||"Unknown error",qe=h.analyze(k,Oe,Y);if(ue=h.buildRecoveryMessage(qe,Oe),f.recordObservation(`FAILED: ${Oe}`,`Recovery: ${qe.strategy} \u2014 ${qe.suggestion}`),o.info({tool:k,errorClass:qe.errorClass,strategy:qe.strategy},"Error recovery analysis"),w.push({tool:k,success:!1,summary:Oe.slice(0,150)}),qe.autoRetry&&!f.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let te=await ig(s,k,Y,o);a.onToolEnd?.(k,te.success,te.output,te.duration,Y),te.success&&(ue=os(te.output,sg),f.recordObservation(ue.slice(0,300),"Auto-retry succeeded"),w[w.length-1]={tool:k,success:!0,summary:te.output.slice(0,150)})}}if(r.addToolMessage(ue),X.success&&k==="read_file"&&typeof Y.path=="string"&&i?.addFile(Y.path,X.output),o.info({tool:k,success:X.success,durationMs:X.duration,retries:X.retries},"Tool executed"),!X.success&&Z$(X.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}H>1&&G<H-1}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return y>=g&&!v&&a.onNotice?.(`Reached max iterations (${g}). Stopping.`,"warn"),o.info({summary:f.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:A,toolsUsed:qt(x),toolResults:w,touchedFiles:qt($),iterations:y,success:!0,completedNaturally:v}}function qt(n){return[...new Set(n)]}function og(n){return async(e,t)=>{let s=e.replace(/_/g," ");return!n.autoMode&&n.interactive?t==="confirm"&&n.confirm?await n.confirm(`Proceed with ${s}?`)?"allow":"skip":t==="dangerous"&&n.confirmDangerous?await n.confirmDangerous(`Dangerous: ${s}`)?"allow":"skip":"allow":!n.autoMode&&t==="dangerous"?"skip":"allow"}}function ag(){return(n,e)=>e==="dangerous"?"skip":"allow"}var J$,sg,rg,jl=L(()=>{"use strict";da();Ml();Dl();ng();J$=150,sg=2e3,rg=2});var cg,e0,t0,n0,lg,bs,ug=L(()=>{"use strict";cg=O(Ol());jn();pa();fa();Ns();Ri();Fa();jl();e0={hablas:"planner",bob:"architect",alex:"coder",david:"researcher",emma:"product-manager",gate:"gate"},t0=(0,cg.default)({level:"silent"}),n0=40,lg={hablas:{role:"hablas",model:"stepfun-ai/step-3.7-flash",temperature:.7},bob:{role:"bob",model:"stepfun-ai/step-3.7-flash",temperature:.4},alex:{role:"alex",model:"stepfun-ai/step-3.7-flash",temperature:.2},david:{role:"david",model:"stepfun-ai/step-3.7-flash",temperature:.5},emma:{role:"emma",model:"stepfun-ai/step-3.7-flash",temperature:.6},gate:{role:"gate",model:"stepfun-ai/step-3.5-flash",temperature:.3}},bs=class{baseConfig;agentModels;toolRegistry=null;onOutput=null;channel=null;mindsetRegistry=br();sharedContext=null;contextManager;constructor(e){this.baseConfig=e,this.agentModels=zt(),this.contextManager=new tn(e)}setSharedContext(e){this.sharedContext=e}setChannel(e){this.channel=e}setToolRegistry(e){this.toolRegistry=e}setOutputCallback(e){this.onOutput=e}reloadModels(){this.agentModels=zt()}getAgentModel(e){let t=this.agentModels[e];if(t)return{model:t.model,temperature:t.temperature??lg[e]?.temperature??.5};let s=lg[e];return{model:s.model,temperature:s.temperature??.5}}async runAgent(e,t,s,r,i){let o=Date.now(),a;e==="gate"?a={name:"Gate",title:"Hidden Executive Layer",role:"gate"}:a=we.find($=>$.role===e);let l=this.getAgentModel(e),u=i?.maxIterations||n0,d={...this.baseConfig,model:l.model},f=Me(d),h=this.buildAgentPrompt(a,s),m=new nn(h,30,this.baseConfig.contextBudget);m.addUserMessage(t);let p={name:a.name,title:a.title,role:e};this.emit(a.name,"thinking",`\u2605 Hablas \u2192 Delegating to @${a.name} (${a.title})...`);let g={onAssistantText:$=>{this.emit(a.name,"speaking",$.slice(0,200))},onToolStart:($,A,y)=>{this.emit(a.name,"tool",A),this.channel&&this.channel.emitEvent({type:"act",agent:a.name,toolName:$,toolArgs:this.safeArgs(y),content:A})},onToolEnd:($,A,y)=>{this.channel&&this.channel.emitEvent({type:"observe",agent:a.name,toolName:$,success:A,content:A?this.summarizeOk($,y):`error: ${y.slice(0,120)}`})},onError:$=>this.emit(a.name,"error",$)},x=await Br({identity:p,client:f,registry:this.toolRegistry,session:m,contextManager:this.contextManager,logger:t0,io:g,safetyPolicy:ag(),abortSignal:i?.abortSignal,skipTools:(!r||r.length===0,!1),maxIterations:u});if(this.sharedContext&&x.touchedFiles.length)try{this.sharedContext.set(`files:@${a.name}`,x.touchedFiles.join(", "))}catch{}let w=x.touchedFiles.length?[`@${a.name} touched: ${x.touchedFiles.join(", ")}`]:[];return{agent:e,agentName:a.name,output:x.output||(x.success?"Done.":x.error??"No output"),toolsUsed:x.toolsUsed,toolResults:x.toolResults,duration:Date.now()-o,iterations:x.iterations,success:x.success,error:x.error,discoveries:w,touchedFiles:x.touchedFiles}}async runSequential(e,t,s){let r=[],i="",o=[];for(let a=0;a<e.length;a++){let{role:l,task:u}=e[a];if(s?.abortSignal?.aborted)break;let d=[];if(i&&(d.push("## Previous Agent Results"),d.push(i)),o.length>0){d.push(`
966
+ `),{toolCalls:s,displayContent:r.trim(),format:e[0]?.format??"unknown"}}},Fl=null});function X$(n,e,t){let r=tg().parse(e,n,t);return{toolCalls:r.toolCalls,displayContent:r.displayContent}}function Q$(n,e){return n==="write_file"&&typeof e.path=="string"?`create ${e.path}`:(n==="edit_file"||n==="patch_file"||n==="search_and_replace")&&typeof e.path=="string"?`modify ${e.path}`:n==="read_file"&&typeof e.path=="string"?`read ${e.path}`:n==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):typeof e.path=="string"?String(e.path):n.replace(/_/g," ")}function Z$(n){let e=(n||"").toLowerCase();return e.includes("eacces")||e.includes("permission")||e.includes("enospc")||e.includes("readonly")||e.includes("security")||e.includes("[write_file]")||e.includes("[delete_file]")||e.includes("[move_file]")||e.includes("[search_and_replace]")}async function ig(n,e,t,s){let r=0,i=Date.now();for(;r<=rg;){let o=await n.execute({name:e,arguments:t});if(o.success||r>=rg)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:r};r++,s.info({tool:e,retry:r,error:o.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-i,retries:r}}async function Br(n){let{identity:e,client:t,registry:s,session:r,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:u,skipTools:d}=n,f=n.reactEngine??ms(),h=n.errorRecovery??gs(),m=d?[]:s.getOllamaTools(),p=t.getModel(),g=n.maxIterations??J$,x=[],w=[],$=[],A="",y=0,v=!1;for(;y<g;){if(y++,u?.aborted)return{output:A,toolsUsed:qt(x),toolResults:w,touchedFiles:qt($),iterations:y,success:!1,error:"Aborted",completedNaturally:v};let b=f.buildBudgetWarningPrompt();b&&r.addUserMessage(b,{priority:"critical",tags:["system-budget"]});let S;try{S=await t.chatWithTools(r.getMessages(),m,u)}catch(G){let E=G;if(E.name==="AbortError"||u?.aborted)return{output:A,toolsUsed:qt(x),toolResults:w,touchedFiles:qt($),iterations:y,success:!1,error:"Aborted",completedNaturally:v};if(y<=1){a.onNotice?.(`Transient model error: ${E.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(k=>setTimeout(k,1e3)),y--;continue}return a.onError?.(E.message??"Model request failed"),{output:A,toolsUsed:qt(x),toolResults:w,touchedFiles:qt($),iterations:y,success:!1,error:E.message,completedNaturally:v}}let _=S.message?.content||"",T=S.message?.tool_calls,I=f.parseThinking(_);I.hasThinking&&(f.recordStep({thought:I.thinking}),o.debug({thinking:I.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:C,displayContent:F}=X$(T,_,p);if(F&&F.trim()&&(A=F,await a.onAssistantText?.(F,e)),C.length===0){r.addAssistantMessage(_,void 0,e.role),v=!0;break}r.addAssistantMessage(_,C,e.role);let H=C.length;for(let G=0;G<C.length;G++){let E=C[G];if(!E?.function?.name)continue;let k=E.function.name,Y=E.function.arguments||{},K=s.getSafetyLevel(k)??"confirm";if(!s.get(k)){a.onNotice?.(`Unknown tool: ${k} \u2014 skipping`,"warn"),r.addToolMessage(`Error: Unknown tool "${k}". Available: ${s.getAll().map(Oe=>Oe.name).join(", ")}`);continue}if(await l(k,K,Y)==="skip"){r.addToolMessage(`Tool ${k} was skipped by policy/user.`);break}x.push(k),typeof Y.path=="string"&&$.push(Y.path);let ee=Q$(k,Y);a.onToolStart?.(k,ee,Y),a.onToolCall?.(),f.recordStep({thought:I.hasThinking?`Executing: ${k}`:"",action:k,actionInput:Y});let X=await ig(s,k,Y,o);a.onToolEnd?.(k,X.success,X.error||X.output,X.duration,Y);let ue;if(X.success)ue=os(X.output,sg),f.recordObservation(ue.slice(0,300)),w.push({tool:k,success:!0,summary:X.output.slice(0,150)});else{let Oe=X.error||"Unknown error",qe=h.analyze(k,Oe,Y);if(ue=h.buildRecoveryMessage(qe,Oe),f.recordObservation(`FAILED: ${Oe}`,`Recovery: ${qe.strategy} \u2014 ${qe.suggestion}`),o.info({tool:k,errorClass:qe.errorClass,strategy:qe.strategy},"Error recovery analysis"),w.push({tool:k,success:!1,summary:Oe.slice(0,150)}),qe.autoRetry&&!f.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let te=await ig(s,k,Y,o);a.onToolEnd?.(k,te.success,te.output,te.duration,Y),te.success&&(ue=os(te.output,sg),f.recordObservation(ue.slice(0,300),"Auto-retry succeeded"),w[w.length-1]={tool:k,success:!0,summary:te.output.slice(0,150)})}}if(r.addToolMessage(ue),X.success&&k==="read_file"&&typeof Y.path=="string"&&i?.addFile(Y.path,X.output),o.info({tool:k,success:X.success,durationMs:X.duration,retries:X.retries},"Tool executed"),!X.success&&Z$(X.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}H>1&&G<H-1}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return y>=g&&!v&&a.onNotice?.(`Reached max iterations (${g}). Stopping.`,"warn"),o.info({summary:f.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:A,toolsUsed:qt(x),toolResults:w,touchedFiles:qt($),iterations:y,success:!0,completedNaturally:v}}function qt(n){return[...new Set(n)]}function og(n){return async(e,t)=>{let s=e.replace(/_/g," ");return!n.autoMode&&n.interactive?t==="confirm"&&n.confirm?await n.confirm(`Proceed with ${s}?`)?"allow":"skip":t==="dangerous"&&n.confirmDangerous?await n.confirmDangerous(`Dangerous: ${s}`)?"allow":"skip":"allow":!n.autoMode&&t==="dangerous"?"skip":"allow"}}function ag(){return(n,e)=>e==="dangerous"?"skip":"allow"}var J$,sg,rg,jl=L(()=>{"use strict";da();Ml();Dl();ng();J$=600,sg=2e3,rg=2});var cg,e0,t0,n0,lg,bs,ug=L(()=>{"use strict";cg=O(Ol());jn();pa();fa();Ns();Ri();Fa();jl();e0={hablas:"planner",bob:"architect",alex:"coder",david:"researcher",emma:"product-manager",gate:"gate"},t0=(0,cg.default)({level:"silent"}),n0=200,lg={hablas:{role:"hablas",model:"stepfun-ai/step-3.7-flash",temperature:.7},bob:{role:"bob",model:"stepfun-ai/step-3.7-flash",temperature:.4},alex:{role:"alex",model:"stepfun-ai/step-3.7-flash",temperature:.2},david:{role:"david",model:"stepfun-ai/step-3.7-flash",temperature:.5},emma:{role:"emma",model:"stepfun-ai/step-3.7-flash",temperature:.6},gate:{role:"gate",model:"stepfun-ai/step-3.5-flash",temperature:.3}},bs=class{baseConfig;agentModels;toolRegistry=null;onOutput=null;channel=null;mindsetRegistry=br();sharedContext=null;contextManager;constructor(e){this.baseConfig=e,this.agentModels=zt(),this.contextManager=new tn(e)}setSharedContext(e){this.sharedContext=e}setChannel(e){this.channel=e}setToolRegistry(e){this.toolRegistry=e}setOutputCallback(e){this.onOutput=e}reloadModels(){this.agentModels=zt()}getAgentModel(e){let t=this.agentModels[e];if(t)return{model:t.model,temperature:t.temperature??lg[e]?.temperature??.5};let s=lg[e];return{model:s.model,temperature:s.temperature??.5}}async runAgent(e,t,s,r,i){let o=Date.now(),a;e==="gate"?a={name:"Gate",title:"Hidden Executive Layer",role:"gate"}:a=we.find($=>$.role===e);let l=this.getAgentModel(e),u=i?.maxIterations||n0,d={...this.baseConfig,model:l.model},f=Me(d),h=this.buildAgentPrompt(a,s),m=new nn(h,200,this.baseConfig.contextBudget);m.addUserMessage(t);let p={name:a.name,title:a.title,role:e};this.emit(a.name,"thinking",`\u2605 Hablas \u2192 Delegating to @${a.name} (${a.title})...`);let g={onAssistantText:$=>{this.emit(a.name,"speaking",$.slice(0,200))},onToolStart:($,A,y)=>{this.emit(a.name,"tool",A),this.channel&&this.channel.emitEvent({type:"act",agent:a.name,toolName:$,toolArgs:this.safeArgs(y),content:A})},onToolEnd:($,A,y)=>{this.channel&&this.channel.emitEvent({type:"observe",agent:a.name,toolName:$,success:A,content:A?this.summarizeOk($,y):`error: ${y.slice(0,120)}`})},onError:$=>this.emit(a.name,"error",$)},x=await Br({identity:p,client:f,registry:this.toolRegistry,session:m,contextManager:this.contextManager,logger:t0,io:g,safetyPolicy:ag(),abortSignal:i?.abortSignal,skipTools:(!r||r.length===0,!1),maxIterations:u});if(this.sharedContext&&x.touchedFiles.length)try{this.sharedContext.set(`files:@${a.name}`,x.touchedFiles.join(", "))}catch{}let w=x.touchedFiles.length?[`@${a.name} touched: ${x.touchedFiles.join(", ")}`]:[];return{agent:e,agentName:a.name,output:x.output||(x.success?"Done.":x.error??"No output"),toolsUsed:x.toolsUsed,toolResults:x.toolResults,duration:Date.now()-o,iterations:x.iterations,success:x.success,error:x.error,discoveries:w,touchedFiles:x.touchedFiles}}async runSequential(e,t,s){let r=[],i="",o=[];for(let a=0;a<e.length;a++){let{role:l,task:u}=e[a];if(s?.abortSignal?.aborted)break;let d=[];if(i&&(d.push("## Previous Agent Results"),d.push(i)),o.length>0){d.push(`
967
967
  ## Handoff Chain`);for(let p of o)d.push(`- @${p.from} \u2192 @${p.to}: ${p.context.slice(0,100)}`)}let f=d.join(`
968
968
  `),h=we.find(p=>p.role===l);if(h&&a>0){let p=e[a-1].role,g=we.find(x=>x.role===p);this.emit(h.name,"thinking",`\u2605 Handoff: @${g?.name||p} \u2192 @${h.name} (${h.title})`)}let m=await this.runAgent(l,u,f,t,s);if(r.push(m),m.success&&m.output){let p=m.output.length>600?m.output.slice(0,600)+"...":m.output;i+=`
969
969
 
@@ -1040,7 +1040,7 @@ Never output raw tool XML in text.
1040
1040
  ${t}`),this.sharedContext){let a=this.sharedContext.getSummary();a&&(o+=`
1041
1041
 
1042
1042
  ## Shared Team Context
1043
- ${a}`)}return o}emit(e,t,s){if(this.onOutput&&this.onOutput(e,t,s),this.channel){let r=t==="speaking"?"speak":t==="tool"?"act":t;this.channel.emitEvent({type:r,agent:e,content:s})}}safeArgs(e){let t={};for(let[s,r]of Object.entries(e||{}))typeof r=="string"?t[s]=r.length>160?r.slice(0,160)+"\u2026":r:(typeof r=="number"||typeof r=="boolean")&&(t[s]=r);return t}summarizeOk(e,t){let s=t.split(/\r?\n/).length;return e==="write_file"||e==="edit_file"||e==="patch_file"?`ok \xB7 ${s} line${s===1?"":"s"}`:e==="run_command"?`ok \xB7 ${t.split(/\r?\n/).find(i=>i.trim())?.slice(0,80)||"ok"}`:e==="read_file"?`ok \xB7 ${s} line${s===1?"":"s"} read`:"ok"}}});var dg,vs,fg=L(()=>{"use strict";dg=require("events"),vs=class extends dg.EventEmitter{events=[];maxHistory;constructor(e=500){super(),this.setMaxListeners(50),this.maxHistory=e,this.on("error",t=>{process.env.DEBUG&&console.error("[AgentChannel internal error swallowed]",t)})}emitEvent(e){let t={...e,timestamp:Date.now()};return this.events.push(t),this.events.length>this.maxHistory&&this.events.splice(0,this.events.length-this.maxHistory),this.emit("event",t),t.type!=="error"&&this.emit(t.type,t),t}history(){return[...this.events]}reset(){this.events=[]}onEvent(e){return this.on("event",e),this}offEvent(e){return this.off("event",e),this}}});var s0,St,Ur,ws,pg=L(()=>{"use strict";jn();s0={hablas:"Hablas \u2014 INTJ Team Leader. Authoritative, terse, engineering-precise. Speaks in short systemic statements. No pleasantries.",emma:"Emma \u2014 Product Manager. Calm, user-focused, structured. Clarifies scope and outcomes in plain language.",bob:"Bob \u2014 System Architect. Methodical, principled, slightly formal. Talks in terms of boundaries, trade-offs, contracts.",alex:"Alex \u2014 Senior Engineer. Pragmatic, concise, action-biased. Confirms intent, then ships.",david:"David \u2014 Data & Research Analyst. Factual, evidence-driven, neutral tone. Cites context, not opinions."},St={hablas:"Hablas",emma:"Emma",bob:"Bob",alex:"Alex",david:"David"},Ur={handoff:(n,e,t)=>{let s=St[e];return{hablas:`Routing this to you, @${s}.`,emma:`@${s}, I need the requirements framed before we move.`,bob:`@${s}, design the structure for this. Keep boundaries clean.`,alex:`@${s}, you have the implementation. Stay surgical.`,david:`@${s}, gather the context we need on this.`}[e]||`@${s}, taking this from here.`},ack:(n,e)=>`Acknowledged, @${St[e]}. Proceeding.`,review:(n,e)=>`@${St[e]}, structurally sound. Watch the boundaries on the next pass.`,reviewAck:(n,e)=>`Noted, @${St[e]}. Integrating.`},ws=class{client;spent=0;cache=new Map;opts;constructor(e,t={}){this.opts={tokenBudget:t.tokenBudget??500,maxChars:t.maxChars??140,lightModel:t.lightModel,abortSignal:t.abortSignal};let s={...e,model:this.opts.lightModel||e.model};this.client=Me(s)}resetBudget(){this.spent=0,this.cache.clear()}setAbortSignal(e){this.opts.abortSignal=e}async generateHandoffLine(e,t,s){return this.generate(`handoff:${e}:${t}:${this.hash(s)}`,this.buildPrompt(e,t,"handoff",s),()=>Ur.handoff(e,t,s))}async generateAckLine(e,t){return this.generate(`ack:${e}:${t}`,this.buildPrompt(e,t,"ack"),()=>Ur.ack(e,t))}async generateReviewLine(e,t,s){return this.generate(`review:${e}:${t}:${this.hash(s.slice(0,200))}`,this.buildPrompt(e,t,"review",s.slice(0,400)),()=>Ur.review(e,t))}async generateReviewAck(e,t){return this.generate(`reviewAck:${e}:${t}`,this.buildPrompt(e,t,"reviewAck"),()=>Ur.reviewAck(e,t))}async generate(e,t,s){let r=this.cache.get(e);if(r)return r;if(this.spent>=this.opts.tokenBudget||this.opts.abortSignal?.aborted)return s();try{let o=((await this.client.chatWithTools(t,[],this.opts.abortSignal)).message?.content||"").trim(),a=this.cleanLine(o);return a?(this.spent+=Math.ceil(a.length/4)+40,this.cache.set(e,a),a):s()}catch{return s()}}buildPrompt(e,t,s,r){let i=`You are ${St[e]}, speaking in your own voice.
1043
+ ${a}`)}return o}emit(e,t,s){if(this.onOutput&&this.onOutput(e,t,s),this.channel){let r=t==="speaking"?"speak":t==="tool"?"act":t;this.channel.emitEvent({type:r,agent:e,content:s})}}safeArgs(e){let t={};for(let[s,r]of Object.entries(e||{}))typeof r=="string"?t[s]=r.length>160?r.slice(0,160)+"\u2026":r:(typeof r=="number"||typeof r=="boolean")&&(t[s]=r);return t}summarizeOk(e,t){let s=t.split(/\r?\n/).length;return e==="write_file"||e==="edit_file"||e==="patch_file"?`ok \xB7 ${s} line${s===1?"":"s"}`:e==="run_command"?`ok \xB7 ${t.split(/\r?\n/).find(i=>i.trim())?.slice(0,80)||"ok"}`:e==="read_file"?`ok \xB7 ${s} line${s===1?"":"s"} read`:"ok"}}});var dg,vs,fg=L(()=>{"use strict";dg=require("events"),vs=class extends dg.EventEmitter{events=[];maxHistory;constructor(e=3e3){super(),this.setMaxListeners(50),this.maxHistory=e,this.on("error",t=>{process.env.DEBUG&&console.error("[AgentChannel internal error swallowed]",t)})}emitEvent(e){let t={...e,timestamp:Date.now()};return this.events.push(t),this.events.length>this.maxHistory&&this.events.splice(0,this.events.length-this.maxHistory),this.emit("event",t),t.type!=="error"&&this.emit(t.type,t),t}history(){return[...this.events]}reset(){this.events=[]}onEvent(e){return this.on("event",e),this}offEvent(e){return this.off("event",e),this}}});var s0,St,Ur,ws,pg=L(()=>{"use strict";jn();s0={hablas:"Hablas \u2014 INTJ Team Leader. Authoritative, terse, engineering-precise. Speaks in short systemic statements. No pleasantries.",emma:"Emma \u2014 Product Manager. Calm, user-focused, structured. Clarifies scope and outcomes in plain language.",bob:"Bob \u2014 System Architect. Methodical, principled, slightly formal. Talks in terms of boundaries, trade-offs, contracts.",alex:"Alex \u2014 Senior Engineer. Pragmatic, concise, action-biased. Confirms intent, then ships.",david:"David \u2014 Data & Research Analyst. Factual, evidence-driven, neutral tone. Cites context, not opinions."},St={hablas:"Hablas",emma:"Emma",bob:"Bob",alex:"Alex",david:"David"},Ur={handoff:(n,e,t)=>{let s=St[e];return{hablas:`Routing this to you, @${s}.`,emma:`@${s}, I need the requirements framed before we move.`,bob:`@${s}, design the structure for this. Keep boundaries clean.`,alex:`@${s}, you have the implementation. Stay surgical.`,david:`@${s}, gather the context we need on this.`}[e]||`@${s}, taking this from here.`},ack:(n,e)=>`Acknowledged, @${St[e]}. Proceeding.`,review:(n,e)=>`@${St[e]}, structurally sound. Watch the boundaries on the next pass.`,reviewAck:(n,e)=>`Noted, @${St[e]}. Integrating.`},ws=class{client;spent=0;cache=new Map;opts;constructor(e,t={}){this.opts={tokenBudget:t.tokenBudget??500,maxChars:t.maxChars??140,lightModel:t.lightModel,abortSignal:t.abortSignal};let s={...e,model:this.opts.lightModel||e.model};this.client=Me(s)}resetBudget(){this.spent=0,this.cache.clear()}setAbortSignal(e){this.opts.abortSignal=e}async generateHandoffLine(e,t,s){return this.generate(`handoff:${e}:${t}:${this.hash(s)}`,this.buildPrompt(e,t,"handoff",s),()=>Ur.handoff(e,t,s))}async generateAckLine(e,t){return this.generate(`ack:${e}:${t}`,this.buildPrompt(e,t,"ack"),()=>Ur.ack(e,t))}async generateReviewLine(e,t,s){return this.generate(`review:${e}:${t}:${this.hash(s.slice(0,200))}`,this.buildPrompt(e,t,"review",s.slice(0,400)),()=>Ur.review(e,t))}async generateReviewAck(e,t){return this.generate(`reviewAck:${e}:${t}`,this.buildPrompt(e,t,"reviewAck"),()=>Ur.reviewAck(e,t))}async generate(e,t,s){let r=this.cache.get(e);if(r)return r;if(this.spent>=this.opts.tokenBudget||this.opts.abortSignal?.aborted)return s();try{let o=((await this.client.chatWithTools(t,[],this.opts.abortSignal)).message?.content||"").trim(),a=this.cleanLine(o);return a?(this.spent+=Math.ceil(a.length/4)+40,this.cache.set(e,a),a):s()}catch{return s()}}buildPrompt(e,t,s,r){let i=`You are ${St[e]}, speaking in your own voice.
1044
1044
  ${s0[e]}
1045
1045
 
1046
1046
  Hard constraints:
@@ -1197,11 +1197,11 @@ ${d.output}`}).join(`
1197
1197
 
1198
1198
  ## Dependency Notes
1199
1199
  <!-- Important notes about dependencies and versions -->
1200
- `,f0={"HABLAS.md":a0,"PROGRESS.md":l0,"ARCHITECTURE.md":c0,"AGENTS.md":u0,"MEMORY.md":d0},Wr=class{contextDir;sessionDelegations=[];sessionDiscoveries=[];constructor(e){this.contextDir=dt.join(e,o0)}init(){let e=dt.join(dt.dirname(this.contextDir),".hablas-legacy");if(ce.existsSync(e)&&!ce.existsSync(this.contextDir))try{ce.renameSync(e,this.contextDir);let t=dt.join(this.contextDir,"LEGACY.md"),s=dt.join(this.contextDir,"HABLAS.md");ce.existsSync(t)&&!ce.existsSync(s)&&ce.renameSync(t,s)}catch{}ce.existsSync(this.contextDir)||ce.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(f0)){let r=dt.join(this.contextDir,t);ce.existsSync(r)||ce.writeFileSync(r,s,"utf-8")}}exists(){return ce.existsSync(this.contextDir)}readContext(e){let t=dt.join(this.contextDir,e);return ce.existsSync(t)?ce.readFileSync(t,"utf-8"):null}updateProgress(e){let t=new Date().toISOString().split("T")[0],s=new Date().toISOString().split("T")[1].split(".")[0],r=`- [${t} ${s}] ${e}`;this.appendToSection("PROGRESS.md","## Progress Log",r)}addTask(e,t){let s=new Date().toISOString().split("T")[0],r=`| ${e} | @${t} | \u{1F535} pending | ${s} | \u2014 |`;this.appendToSection("PROGRESS.md","## Task Breakdown",r)}updateSprint(e){this.updateSection("PROGRESS.md","## Current Sprint",e)}recordDecision(e,t,s,r="medium"){let o=`| ${new Date().toISOString().split("T")[0]} | ${e} | ${t} | ${s} | ${r} |`;this.appendToSection("HABLAS.md","## Key Decisions",o)}updateArchitecture(e,t){this.updateSection("ARCHITECTURE.md",e,t)}recordADR(e,t,s="accepted"){let r=new Date().toISOString().split("T")[0],a=`| ${((this.readContext("ARCHITECTURE.md")||"").match(/^\|/gm)||[]).length} | ${e} | ${s} | ${r} | ${t} |`;this.appendToSection("ARCHITECTURE.md","## Architecture Decision Records (ADRs)",a)}logDelegation(e){this.sessionDelegations.push(e);let t=`| ${e.time} | ${e.from} | ${e.to} | ${e.task.slice(0,50)} | ${e.model} | ${e.result} | ${e.durationMs}ms |`;this.appendToSection("AGENTS.md","## Delegation Log",t)}logSession(e){let t=`| ${e.sessionId} | ${e.date} | ${Math.round(e.duration/1e3)}s | ${e.agentsUsed.join(", ")} | ${e.tasksCompleted} |`;this.appendToSection("AGENTS.md","## Session History",t)}updateAgentPerformance(e,t,s,r,i){let o=`| @${e} | ${t} | ${Math.round(s*100)}% | ${Math.round(r)}ms | ${i.join(", ")} |`;this.appendToSection("AGENTS.md","## Agent Performance",o)}logAgentComm(e,t,s){let i=`- [${new Date().toISOString()}] **@${e}** \u2192 **@${t}**: ${s.slice(0,200)}`;this.appendToSection("AGENTS.md","## Inter-Agent Communication",i)}addConvention(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Project Conventions",r),this.sessionDiscoveries.push({type:"convention",description:e,source:t,date:s})}addPattern(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Discovered Patterns",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}addGotcha(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u26A0\uFE0F ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Known Gotchas",r),this.sessionDiscoveries.push({type:"gotcha",description:e,source:t,date:s})}addAutoDiscovery(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u{1F50D} ${e} *(by ${t})*`;this.appendToSection("MEMORY.md","## Auto-Discoveries",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}getSummary(e=8e3){let t=["HABLAS.md","PROGRESS.md","ARCHITECTURE.md","MEMORY.md"],s=[],r=0;for(let i of t){let o=this.readContext(i);if(o&&o.trim().length>0){let a=e-r;if(a<=200)break;let l=o.length>a?o.slice(0,a)+`
1200
+ `,f0={"HABLAS.md":a0,"PROGRESS.md":l0,"ARCHITECTURE.md":c0,"AGENTS.md":u0,"MEMORY.md":d0},Wr=class{contextDir;sessionDelegations=[];sessionDiscoveries=[];constructor(e){this.contextDir=dt.join(e,o0)}init(){let e=dt.join(dt.dirname(this.contextDir),".hablas-legacy");if(ce.existsSync(e)&&!ce.existsSync(this.contextDir))try{ce.renameSync(e,this.contextDir);let t=dt.join(this.contextDir,"LEGACY.md"),s=dt.join(this.contextDir,"HABLAS.md");ce.existsSync(t)&&!ce.existsSync(s)&&ce.renameSync(t,s)}catch{}ce.existsSync(this.contextDir)||ce.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(f0)){let r=dt.join(this.contextDir,t);ce.existsSync(r)||ce.writeFileSync(r,s,"utf-8")}}exists(){return ce.existsSync(this.contextDir)}readContext(e){let t=dt.join(this.contextDir,e);return ce.existsSync(t)?ce.readFileSync(t,"utf-8"):null}updateProgress(e){let t=new Date().toISOString().split("T")[0],s=new Date().toISOString().split("T")[1].split(".")[0],r=`- [${t} ${s}] ${e}`;this.appendToSection("PROGRESS.md","## Progress Log",r)}addTask(e,t){let s=new Date().toISOString().split("T")[0],r=`| ${e} | @${t} | \u{1F535} pending | ${s} | \u2014 |`;this.appendToSection("PROGRESS.md","## Task Breakdown",r)}updateSprint(e){this.updateSection("PROGRESS.md","## Current Sprint",e)}recordDecision(e,t,s,r="medium"){let o=`| ${new Date().toISOString().split("T")[0]} | ${e} | ${t} | ${s} | ${r} |`;this.appendToSection("HABLAS.md","## Key Decisions",o)}updateArchitecture(e,t){this.updateSection("ARCHITECTURE.md",e,t)}recordADR(e,t,s="accepted"){let r=new Date().toISOString().split("T")[0],a=`| ${((this.readContext("ARCHITECTURE.md")||"").match(/^\|/gm)||[]).length} | ${e} | ${s} | ${r} | ${t} |`;this.appendToSection("ARCHITECTURE.md","## Architecture Decision Records (ADRs)",a)}logDelegation(e){this.sessionDelegations.push(e);let t=`| ${e.time} | ${e.from} | ${e.to} | ${e.task.slice(0,50)} | ${e.model} | ${e.result} | ${e.durationMs}ms |`;this.appendToSection("AGENTS.md","## Delegation Log",t)}logSession(e){let t=`| ${e.sessionId} | ${e.date} | ${Math.round(e.duration/1e3)}s | ${e.agentsUsed.join(", ")} | ${e.tasksCompleted} |`;this.appendToSection("AGENTS.md","## Session History",t)}updateAgentPerformance(e,t,s,r,i){let o=`| @${e} | ${t} | ${Math.round(s*100)}% | ${Math.round(r)}ms | ${i.join(", ")} |`;this.appendToSection("AGENTS.md","## Agent Performance",o)}logAgentComm(e,t,s){let i=`- [${new Date().toISOString()}] **@${e}** \u2192 **@${t}**: ${s.slice(0,200)}`;this.appendToSection("AGENTS.md","## Inter-Agent Communication",i)}addConvention(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Project Conventions",r),this.sessionDiscoveries.push({type:"convention",description:e,source:t,date:s})}addPattern(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Discovered Patterns",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}addGotcha(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u26A0\uFE0F ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Known Gotchas",r),this.sessionDiscoveries.push({type:"gotcha",description:e,source:t,date:s})}addAutoDiscovery(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u{1F50D} ${e} *(by ${t})*`;this.appendToSection("MEMORY.md","## Auto-Discoveries",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}getSummary(e=3e4){let t=["HABLAS.md","PROGRESS.md","ARCHITECTURE.md","MEMORY.md"],s=[],r=0;for(let i of t){let o=this.readContext(i);if(o&&o.trim().length>0){let a=e-r;if(a<=200)break;let l=o.length>a?o.slice(0,a)+`
1201
1201
  ...(truncated)`:o;s.push(`### ${i}
1202
1202
  ${l}`),r+=l.length}}return s.length>0?s.join(`
1203
1203
 
1204
- `):""}getAgentContext(e,t=4e3){let s=[],r=0,i=this.readContext("HABLAS.md");if(i){let o=this.extractSection(i,"## Project Overview"),a=this.extractSection(i,"## Key Decisions");o&&s.push(`## Project Overview
1204
+ `):""}getAgentContext(e,t=15e3){let s=[],r=0,i=this.readContext("HABLAS.md");if(i){let o=this.extractSection(i,"## Project Overview"),a=this.extractSection(i,"## Key Decisions");o&&s.push(`## Project Overview
1205
1205
  ${o}`),a&&s.push(`## Key Decisions
1206
1206
  ${a}`),r=s.join(`
1207
1207
  `).length}switch(e){case"emma":this.addContextFromFile(s,"PROGRESS.md",["## Requirements Overview","## User Stories","## Current Sprint"],t-r);break;case"bob":this.addContextFromFile(s,"ARCHITECTURE.md",["## System Overview","## Tech Stack","## Module Design","## Architecture Decision Records (ADRs)"],t-r),this.addContextFromFile(s,"MEMORY.md",["## Discovered Patterns","## Project Conventions"],t-r);break;case"alex":this.addContextFromFile(s,"ARCHITECTURE.md",["## Module Design","## File Tree Plan","## Implementation Guide"],t-r),this.addContextFromFile(s,"MEMORY.md",["## Project Conventions","## Known Gotchas"],t-r),this.addContextFromFile(s,"PROGRESS.md",["## Current Sprint","## Task Breakdown"],t-r);break;case"david":this.addContextFromFile(s,"MEMORY.md",["## Auto-Discoveries","## Dependency Notes"],t-r);break;default:let o=this.getSummary(t-r);o&&s.push(o)}return s.join(`
@@ -1230,7 +1230,7 @@ ${d}`),o+=d.length}}}extractSection(e,t){let s=e.split(`
1230
1230
  ${c.accent("\u2726")} ${c.strong("Team Mode Strategy Required")}`),console.log(` ${c.muted("Collaboration requires a stable Git repository root.")}
1231
1231
  `);let ee=await new ls(t).prompt(` ${c.primary("\u203A")} Specify repo path OR type 'init' to start here: `);if(ee.trim().toLowerCase()==="init")try{(0,Lg.execSync)("git init",{cwd:t,stdio:"ignore"}),console.log(` ${c.success("\u2713")} Git repository initialized in ${c.highlight(t)}
1232
1232
  `)}catch{console.log(_e("Failed to initialize Git. Please run git init manually.")),process.exit(1)}else{let X=Ft.resolve(t,ee.trim());mt.existsSync(X)&&s(X)?(t=X,n.workingDirectory=t,console.log(` ${c.success("\u2713")} Context switched to repository: ${c.highlight(t)}
1233
- `)):(console.log(_e(`Path "${X}" is not a valid Git repository.`)),process.exit(1))}}let r=Me(n),i=new En(t,n),o=new tn(n),a=new ls(t),l=br(),u=new vr,d=new us(t),f=new Dn(t),h=new qr,m=new bs(n);m.setToolRegistry(i);let p=new vs,g=new _s(p,{hideActs:!0}).attach(),x=new ws(n,{tokenBudget:500,maxChars:140});if(m.setChannel(p),n.team?.enabled){let Z=n.team.user||"developer",ee=n.team.key||"default-key";Re=new rs(t,n,Z,ee),await Re.init()&&console.log(` ${c.success("\u2713")} ${c.muted("[Team]")} Scoped cooperative sync initialized successfully.
1233
+ `)):(console.log(_e(`Path "${X}" is not a valid Git repository.`)),process.exit(1))}}let r=Me(n),i=new En(t,n),o=new tn(n),a=new ls(t),l=br(),u=new vr,d=new us(t),f=new Dn(t),h=new qr,m=new bs(n);m.setToolRegistry(i);let p=new vs,g=new _s(p,{hideActs:!0}).attach(),x=new ws(n,{tokenBudget:3e3,maxChars:400});if(m.setChannel(p),n.team?.enabled){let Z=n.team.user||"developer",ee=n.team.key||"default-key";Re=new rs(t,n,Z,ee),await Re.init()&&console.log(` ${c.success("\u2713")} ${c.muted("[Team]")} Scoped cooperative sync initialized successfully.
1234
1234
  `)}let w=new Vr(t);f.init();let $=null;n.context?.hablasCoreEnabled&&($=new Wr(t),$.init());let A=await bn(t,n),y=l.getActive(),v=y?y.systemPrompt:Wn,b=vn(v,A,d,f),S=ms({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:150,minConfidence:.6}),_=gs(3),T=new nn(b,n.historySize),I=Bn();I=Ii(I),dn(I);let C=0,F=0,H=Date.now(),G=n.autoMode||!1,E=0,k=new AbortController;process.on("SIGINT",()=>{let Z=Date.now();if(Z-E<S0){console.log(Yi({turns:C,duration:Date.now()-H,toolCalls:F}));let ee=Re?Re.shutdown():Promise.resolve();Promise.resolve(ee).finally(()=>process.exit(0)),setTimeout(()=>process.exit(0),2e3);return}E=Z,k.abort(),k=new AbortController,process.stdout.write(`
1235
1235
  `),console.log(j("Operation cancelled \u2014 press Ctrl+C again to exit"))});let Y=Rs(n);if(console.log(ru(n.model,t)),n.provider==="custom"&&console.log(pe(`Provider: ${Y}`)),G&&console.log(pe("Auto mode enabled \u2014 tool confirmations skipped (plan approval still required)")),(_0()||!Ig())&&(console.log(au()),console.log(""),console.log(pe("First run detected \u2014 launching setup wizard...")),console.log(""),a.close(),await Ul(n),k0(),r=Me(n),a.reinitialize()),Ig()){let Z=new Ge("Connecting");Z.start();let ee=await r.checkConnection();if(Z.stop(ee?"ready":void 0),ee){let X=await r.listModels();console.log(z(`Connected \xB7 ${X.length} models available`)),n.provider==="ollama"&&!X.includes(n.model)&&console.log(j(`Model "${n.model}" not found. Pull: ollama pull ${n.model}`))}else n.provider==="custom"?console.log(He(`Cannot connect to ${n.apiUrl}`,"Check your --api-url and --api-key, or run /provider test")):n.provider==="nvidia"?console.log(He("Cannot connect to NVIDIA NIM","Check your API key or run: hablas --setup")):console.log(He("Cannot connect to Ollama","Start it with: ollama serve \u2014 or switch provider: /provider"))}console.log(iu()),console.log(),console.log(` ${c.accent("\u2605")} ${c.strong("CURRENT MODE: BUILD")} \u2014 Full Multi-Agent Team at Maximum Power`),console.log(` ${c.muted("Hablas + Bob + Alex + David + Emma \u2022 rich live theatre \u2022 no classifier")}`),console.log(` ${c.muted('Switch inside: /mode design or /mode ask | One-shot: hablas build "..."')}`),console.log();let K=!0;for(;K;)try{let ee=(await a.prompt(` ${c.primary("\u203A")} `)).trim();if(!ee)continue;if(ee.startsWith("/")){if(await Fu(ee,n,r,i,o,T,t,a,C,l,u,d,U=>{r=U},f,h,w,m)==="quit"){K=!1;break}continue}e.info({input:ee},"Processing user input");let X=Ec(ee),ue=Ng(X,t);if(C++,console.log(fu(C)),I=Di(I),dn(I),!G){let te=Sg(ue);if(te){console.log(gu(te));let U=await a.prompt(` ${c.muted("\u203A")} `),Ee=_g(U,te);ue=`${ue}
1236
1236
  [Clarification: ${Ee.join(", ")}]`}}let Oe=Tg(ue,t,{maxFiles:8,maxTokens:6e3});if(Oe.files.length>0){let te=Rg(Oe);T.addUserMessage(`[Auto-loaded ${Oe.files.length} file(s): ${Oe.mentionedPaths.join(", ")}]
@@ -1242,7 +1242,7 @@ ${te}`,{priority:"low",tags:["auto-inject"]})}if(n.team?.enabled&&Re){let te=n.t
1242
1242
  `);continue}}Re.setActivity(ue.slice(0,80))}let qe=te=>{let U=te.trim().toLowerCase();return U.length<12||["hi","hey","\u0627\u0647","ok","thanks","\u0634\u0643\u0631\u0627","yo","hello","\u0635\u0628\u0627\u062D","\u0645\u0633\u0627\u0621","how are","what's up","\u0643\u064A\u0641\u0643","\u062A\u0645\u0627\u0645","\u0627\u064A\u0647","\u0627\u0647","lol","haha"].some(P=>U.includes(P))?!0:!["build","create","fix","add","implement","design","make","write","update","remove","deploy","test","plan","generate","complete","setup"].some(P=>U.includes(P))&&U.length<40};try{if(m&&n.agents.enabled){let te=m.channel;m.setChannel(null),console.log(` ${c.muted("\u25C9 Thinking and determining execution mode...")}`);let U=`User input: "${ue}"
1243
1243
 
1244
1244
  Decide the professional routing for this engineering interaction.`,Ee=await m.runAgent("gate",U,void 0,i.getOllamaTools(),{abortSignal:k?.signal});if(te&&m.setChannel(te),Ee.success&&Ee.output){let Pe=Ee.output.toLowerCase();Pe.includes("mode: casual")||Pe.includes("casual")?effectiveFullTeam=!1:(Pe.includes("mode: build")||Pe.includes("build")||Pe.includes("mode: design"))&&(effectiveFullTeam=!0)}}}catch{}if(effectiveFullTeam){let te=["hablas","bob","alex","david","emma"];for(let q of te)I=Fi(I,q);dn(I),p.reset(),x.resetBudget();let U={id:"build-"+Date.now(),description:ue.substring(0,100),tasks:[{role:"emma",description:"Analyze the request from product/requirements perspective and clarify if needed."},{role:"bob",description:"Provide architecture, design or structural guidance."},{role:"alex",description:"Execute the core implementation, coding or action based on the input."},{role:"david",description:"Research, data analysis or supporting information."}],strategy:"mixed",createdAt:new Date,approved:!0},Ee=i.getOllamaTools(),Pe=new xs(p,m,x,n),P=[],Q="The team operation completed.",D=!1;try{let q=await Pe.run(ue,U,Ee,{abortSignal:k?.signal,peerReview:!0,centralizedToLeader:!0});P=q.results||[],Q=q.finalSynthesis||Q,D=!!q.synthesisOk}catch(q){let ie=q?.message||String(q);ie.includes("Aborted")||q?.name==="AbortError"?(console.log(` ${c.warning("Operation aborted.")}`),Q="Team operation was aborted. Provide more details or try a focused request."):(console.log(_e(`Team error: ${ie}`)),Q="The team encountered an error during execution. Please review logs and retry."),D=!1}console.log(mn("Hablas","Team Leader")),console.log(gn(Q)),T.addAssistantMessage(D?Q:`[Team Summary]
1245
- `+Q),await Dg(n,t);continue}else T.addUserMessage(ue);k=new AbortController,S.startTurn(),_.resetTurn(),await Fg(T,r,i,o,{interactive:!0,autoMode:G,input:a,logger:e,config:n,abortSignal:k.signal,reactEngine:S,errorRecovery:_,skipTools:!1,onToolCall:()=>{F++,I=Li(I,"tool_call"),dn(I)}}),await Dg(n,t)}catch(Z){if(Z.code==="ERR_USE_AFTER_CLOSE")break;if(Z.name==="AbortError")continue;console.log(_e(Z.message)),e.error(Z,"REPL error")}a.close(),Re&&await Re.shutdown(),console.log(Yi({turns:C,duration:Date.now()-H,toolCalls:F}))}async function $0(n,e,t,s="build"){let r=e.workingDirectory==="."?process.cwd():e.workingDirectory;e.agents.enabled=!0;let i=Me(e),o=new En(r,e),a=new bs(e);a.setToolRegistry(o);let l=new vs,u=new _s(l,{hideActs:!0}).attach(),d=new ws(e,{tokenBudget:500,maxChars:140});a.setChannel(l),l.onEvent(w=>{w.type==="phase"?console.log(`
1245
+ `+Q),await Dg(n,t);continue}else T.addUserMessage(ue);k=new AbortController,S.startTurn(),_.resetTurn(),await Fg(T,r,i,o,{interactive:!0,autoMode:G,input:a,logger:e,config:n,abortSignal:k.signal,reactEngine:S,errorRecovery:_,skipTools:!1,onToolCall:()=>{F++,I=Li(I,"tool_call"),dn(I)}}),await Dg(n,t)}catch(Z){if(Z.code==="ERR_USE_AFTER_CLOSE")break;if(Z.name==="AbortError")continue;console.log(_e(Z.message)),e.error(Z,"REPL error")}a.close(),Re&&await Re.shutdown(),console.log(Yi({turns:C,duration:Date.now()-H,toolCalls:F}))}async function $0(n,e,t,s="build"){let r=e.workingDirectory==="."?process.cwd():e.workingDirectory;e.agents.enabled=!0;let i=Me(e),o=new En(r,e),a=new bs(e);a.setToolRegistry(o);let l=new vs,u=new _s(l,{hideActs:!0}).attach(),d=new ws(e,{tokenBudget:3e3,maxChars:400});a.setChannel(l),l.onEvent(w=>{w.type==="phase"?console.log(`
1246
1246
  ${c.accent("\u25C6")} ${c.strong(w.content)}`):w.type==="handoff"?console.log(` ${c.muted("\u2605")} ${w.agent} \u2501\u2501\u25B6 ${w.to}`):w.type==="speak"?console.log(` ${c.primary(w.agent)}: ${w.content}`):w.type==="act"||w.type==="tool"?console.log(` ${c.warning("\u{1F527}")} [${w.agent}] ${w.content||w.toolName}`):w.type==="summary"||w.type==="observe"?console.log(` ${c.success("\u2713")} ${w.agent||""} ${w.content||""}`):w.type==="error"&&console.log(` ${c.error("\u2717")} ${w.agent}: ${w.content}`)}),console.log(`
1247
1247
  ${c.accent("\u2605")} ${c.strong("FULL TEAM "+s.toUpperCase())} \u2014 ${e.model} (classification deleted, max power)`);let f={id:`${s}-`+Date.now(),description:n.substring(0,100),tasks:[{role:"emma",description:"Analyze the request from product/requirements perspective and clarify if needed."},{role:"bob",description:"Provide architecture, design or structural guidance."},{role:"alex",description:"Execute the core implementation, coding or action based on the input."},{role:"david",description:"Research, data analysis or supporting information."}],strategy:"mixed",createdAt:new Date,approved:!0},h=o.getOllamaTools(),m=new xs(l,a,d,e),{results:p,finalSynthesis:g,synthesisOk:x}=await m.run(n,f,h,{peerReview:!0,centralizedToLeader:!0});console.log(`
1248
1248
  ${mn("Hablas","Team Leader")}`),console.log(gn(g||"Team completed the task.")),console.log(`
@@ -1257,7 +1257,7 @@ ${mn("Hablas","Team Leader")}`),console.log(gn(g||"Team completed the task.")),c
1257
1257
  `),s("git add -A"),s('git commit -m "sync(team): automatic updates via @Consul" --no-verify');return}console.log(`
1258
1258
  ${c.success("\u{1F4C1}")} ${c.muted("[Git]")} ${c.strong("@Consul")} committing & pushing to ${c.highlight(i)} \u2192 ${c.muted(o)} ...`),s("git add -A"),s('git commit -m "sync(team): automatic updates via @Consul" --no-verify');try{s(`git push origin ${i}`)}catch{s(`git push --set-upstream origin ${i}`)}console.log(` ${c.success("\u2713")} ${c.strong("@Consul")}: "Pushed to ${i}. Teammates can pull the latest."
1259
1259
  `)}catch(r){let i=r.stderr||r.message||"unknown error",o=/authentication|permission|denied|403|401/i.test(i)?"Check your Git credentials / token for this remote.":/non-fast-forward|rejected|behind/i.test(i)?"Remote has newer commits \u2014 pull/rebase first, then push.":"Resolve the issue and push manually.";console.log(` ${c.warning("\u26A0")} ${c.strong("@Consul")}: auto-push failed. ${c.muted(o)}
1260
- `)}}var mt,Lg,Ft,Wl,Re,ql,w0,x0,S0,Ve=L(()=>{"use strict";Nu();ia();mt=O(require("fs")),Lg=require("child_process"),Ft=O(require("path")),Wl=O(require("os"));jn();Pp();fa();pa();Lp();yr();Fa();jp();Up();yi();ug();fg();pg();yg();bg();Un();Hl();vg();wg();kg();yn();Ag();Og();Kl();Ml();Dl();jl();Re=null,ql=Ft.join(Wl.homedir(),".hablas",".first_run_done"),w0=Ft.join(Wl.homedir(),".hablas","config.json"),x0=150,S0=1500});function et(n){let e=zl.join(jg.homedir(),".hablas","logs");Yr.existsSync(e)||Yr.mkdirSync(e,{recursive:!0});let t=zl.join(e,`session-${Date.now()}.log`);return(0,Vl.default)({level:"info"},Vl.default.destination({dest:t,sync:!1}))}var Vl,zl,jg,Yr,Yl=L(()=>{"use strict";Vl=O(Ol()),zl=O(require("path")),jg=O(require("os")),Yr=O(require("fs"))});var qg={};Fe(qg,{createApiServer:()=>Kg,startApiServer:()=>O0});function E0(){try{return JSON.parse(Bg.readFileSync(Ug.resolve(__dirname,"..","..","package.json"),"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function Kg(n){let e=et(n),t=R0(n);return Hg.createServer(async(r,i)=>{if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.setHeader("Content-Type","application/json"),r.method==="OPTIONS"){i.writeHead(204),i.end();return}if(n.api.apiKey&&(r.headers.authorization||"").replace("Bearer ","")!==n.api.apiKey){i.writeHead(401),i.end(JSON.stringify({error:"Unauthorized",message:"Invalid API key"}));return}let o={};if(r.method==="POST"||r.method==="PUT")try{let l=[];for await(let d of r)l.push(d);let u=Buffer.concat(l).toString();u&&(o=JSON.parse(u))}catch{i.writeHead(400),i.end(JSON.stringify({error:"Bad Request",message:"Invalid JSON body"}));return}let a=t.find(l=>l.method===r.method&&r.url?.startsWith(l.path));if(!a){i.writeHead(404),i.end(JSON.stringify({error:"Not Found",message:`No route for ${r.method} ${r.url}`}));return}try{let l={method:r.method||"GET",path:r.url||"/",body:o,headers:r.headers},u=await a.handler(l);i.writeHead(u.status),i.end(JSON.stringify(u.body))}catch(l){e.error({err:l},"API error"),i.writeHead(500),i.end(JSON.stringify({error:"Internal Server Error",message:String(l)}))}})}function R0(n){return[{method:"GET",path:"/api/v1/health",handler:async()=>({status:200,body:{status:"ok",version:T0,uptime:process.uptime()}})},{method:"GET",path:"/api/v1/agents",handler:async()=>({status:200,body:{agents:[{name:"coder",description:"Code generation and modification",status:"available"},{name:"reviewer",description:"Code review and quality analysis",status:"available"},{name:"architect",description:"System architecture design",status:"available"},{name:"devops",description:"Deployment and infrastructure",status:"available"},{name:"researcher",description:"Documentation and research",status:"available"},{name:"planner",description:"Task decomposition and planning",status:"available"},{name:"debugger",description:"Error analysis and fixing",status:"available"}]}})},{method:"GET",path:"/api/v1/models",handler:async()=>({status:200,body:{current:n.model,provider:n.provider,host:n.ollamaHost}})},{method:"POST",path:"/api/v1/chat",handler:async e=>{let{message:t,agent:s}=e.body;return t?{status:200,body:{response:`[${s||"coder"}] Received: ${t}`,agent:s||"coder",model:n.model}}:{status:400,body:{error:"message field is required"}}}},{method:"POST",path:"/api/v1/plan",handler:async e=>{let{task:t}=e.body;return t?{status:200,body:{plan:{task:t,steps:[{step:1,description:"Analyze requirements",agent:"researcher"},{step:2,description:"Design architecture",agent:"architect"},{step:3,description:"Implement code",agent:"coder"},{step:4,description:"Review and test",agent:"reviewer"}]}}}:{status:400,body:{error:"task field is required"}}}},{method:"POST",path:"/api/v1/execute",handler:async e=>{let{command:t}=e.body;return t?n.api.enabled?{status:200,body:{message:"Command queued for execution",command:t}}:{status:403,body:{error:"API execution not enabled"}}:{status:400,body:{error:"command field is required"}}}},{method:"GET",path:"/api/v1/stats",handler:async()=>({status:200,body:{sessions:0,messages:0,uptime:process.uptime(),model:n.model,provider:n.provider}})}]}function O0(n){return new Promise((e,t)=>{let s=Kg(n);s.on("error",t),s.listen(n.api.port,n.api.host,()=>{e(s)})})}var Hg,Bg,Ug,T0,Wg=L(()=>{"use strict";Hg=O(require("http")),Bg=O(require("fs")),Ug=O(require("path"));Yl();T0=E0()});var M0={};Fe(M0,{CLI_VERSION:()=>ks});module.exports=Zg(M0);var cc=O(lc(),1),{program:U0,createCommand:K0,createArgument:q0,createOption:W0,CommanderError:G0,InvalidArgumentError:V0,InvalidOptionArgumentError:z0,Command:uc,Argument:Y0,Option:J0,Help:X0}=cc.default;Ve();yr();Yl();var Gg=O(require("fs")),Vg=O(require("path"));function P0(){try{let n=Vg.resolve(__dirname,"..","package.json");return JSON.parse(Gg.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}var ks=P0(),ne=new uc;ne.name("hablas").description(`hablas CLI v${ks} by Abdulmoin Hablas \u2014 Multi-agent AI development system. Local-first via Ollama, NVIDIA NIM, or any OpenAI-compatible API.`).version(ks).option("-m, --model <model>","Model to use").option("-p, --project <path>","Working directory").option("--host <url>","Ollama host URL").option("--provider <type>","LLM provider: ollama | custom | nvidia").option("--api-url <url>","Custom API base URL (OpenAI-compatible)").option("--api-key <key>","API key for custom/nvidia provider").option("--auto","Auto mode \u2014 skip all tool confirmations").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--theme <name>","UI theme: dark | light | galaxy | ocean | forest").option("--dashboard","Launch TUI dashboard mode").option("--team","Enable hybrid cooperative sync mode with teammates").option("--user <name>","Teammate username for coordination").option("--team-key <password>","Teammate password/key for secure connection encryption").option("--setup","Run first-time setup wizard");ne.command("build <task>").description("FULL BUILD: complete work with the full multi-agent team at MAXIMUM POWER (rich theatre, no classification). Always Hablas + Bob + Alex + David + Emma.").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(t.autoMode=!0),e.timeout&&(t.timeout=parseInt(e.timeout,10));let s=et(t),{runFullTeamCommand:r}=await Promise.resolve().then(()=>(Ve(),rt));await r(n,t,s,"build")});ne.command("design <task>").description("Design/Architecture mode: focused team (Emma + Bob + David + Hablas) with rich output for blueprints and requirements.").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(t.autoMode=!0);let s=et(t),{runFullTeamCommand:r}=await Promise.resolve().then(()=>(Ve(),rt));await r(n,t,s,"design")});ne.command("ask <question>").description("Quick solo ask (minimal team, fast response, no full theatre).").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(t.autoMode=!0);let s=et(t),{runSingleCommand:r}=await Promise.resolve().then(()=>(Ve(),rt));await r(n,t,s)});ne.command("create <description>").description("Generate a full project from a description (uses full team)").option("--stack <stack>","Tech stack preference").option("--with-tests","Include test generation").option("--with-docker","Include Docker setup").action(async(n,e)=>{let t=ne.opts(),s=Te({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey});t.auto&&(s.autoMode=!0);let r=et(s),{runFullTeamCommand:i}=await Promise.resolve().then(()=>(Ve(),rt)),o=`Generate a complete project: ${n}${e.stack?` using ${e.stack}`:""}${e.withTests?" with comprehensive tests":""}${e.withDocker?" with Docker setup":""}. Create all necessary files.`;await i(o,s,r,"build")});ne.command("commit").description("Generate a smart commit message from staged changes").action(async()=>{let n=ne.opts(),e=Te({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),t=et(e),{getGitStatus:s,getDetailedDiff:r,generateCommitPrompt:i}=await Promise.resolve().then(()=>(pn(),Kn)),o=e.workingDirectory||process.cwd(),a=await s(o);if(!a||a.staged.length===0){console.log(" \u26A0 No staged changes. Use `git add` first.");return}let l=await r(o),u=i(l,a.staged),{runSingleCommand:d}=await Promise.resolve().then(()=>(Ve(),rt));await d(u,e,t)});ne.command("pr").description("Generate a PR description from branch commits").option("--base <branch>","Base branch","main").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=et(t),{getGitStatus:r,getRecentCommits:i,generatePRPrompt:o}=await Promise.resolve().then(()=>(pn(),Kn)),a=t.workingDirectory||process.cwd(),l=await r(a),u=await i(a,20),d=o(u,n.base,l?.branch||"feature"),{runSingleCommand:f}=await Promise.resolve().then(()=>(Ve(),rt));await f(d,t,s)});ne.command("changelog").description("Generate changelog from recent commits").option("--version <ver>","Version number",ks).option("-n, --count <n>","Number of commits to include","30").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=et(t),{getRecentCommits:r,generateChangelogPrompt:i}=await Promise.resolve().then(()=>(pn(),Kn)),o=t.workingDirectory||process.cwd(),a=await r(o,parseInt(n.count)),l=i(a,n.version),{runSingleCommand:u}=await Promise.resolve().then(()=>(Ve(),rt));await u(l,t,s)});ne.command("security").description("Run security scan on the project").option("--fix","Auto-fix issues where possible").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),{runSecurityScan:s,formatScanResults:r}=await Promise.resolve().then(()=>(Bi(),Uc)),i=t.workingDirectory||process.cwd();console.log(`
1260
+ `)}}var mt,Lg,Ft,Wl,Re,ql,w0,x0,S0,Ve=L(()=>{"use strict";Nu();ia();mt=O(require("fs")),Lg=require("child_process"),Ft=O(require("path")),Wl=O(require("os"));jn();Pp();fa();pa();Lp();yr();Fa();jp();Up();yi();ug();fg();pg();yg();bg();Un();Hl();vg();wg();kg();yn();Ag();Og();Kl();Ml();Dl();jl();Re=null,ql=Ft.join(Wl.homedir(),".hablas",".first_run_done"),w0=Ft.join(Wl.homedir(),".hablas","config.json"),x0=600,S0=1500});function et(n){let e=zl.join(jg.homedir(),".hablas","logs");Yr.existsSync(e)||Yr.mkdirSync(e,{recursive:!0});let t=zl.join(e,`session-${Date.now()}.log`);return(0,Vl.default)({level:"info"},Vl.default.destination({dest:t,sync:!1}))}var Vl,zl,jg,Yr,Yl=L(()=>{"use strict";Vl=O(Ol()),zl=O(require("path")),jg=O(require("os")),Yr=O(require("fs"))});var qg={};Fe(qg,{createApiServer:()=>Kg,startApiServer:()=>O0});function E0(){try{return JSON.parse(Bg.readFileSync(Ug.resolve(__dirname,"..","..","package.json"),"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function Kg(n){let e=et(n),t=R0(n);return Hg.createServer(async(r,i)=>{if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.setHeader("Content-Type","application/json"),r.method==="OPTIONS"){i.writeHead(204),i.end();return}if(n.api.apiKey&&(r.headers.authorization||"").replace("Bearer ","")!==n.api.apiKey){i.writeHead(401),i.end(JSON.stringify({error:"Unauthorized",message:"Invalid API key"}));return}let o={};if(r.method==="POST"||r.method==="PUT")try{let l=[];for await(let d of r)l.push(d);let u=Buffer.concat(l).toString();u&&(o=JSON.parse(u))}catch{i.writeHead(400),i.end(JSON.stringify({error:"Bad Request",message:"Invalid JSON body"}));return}let a=t.find(l=>l.method===r.method&&r.url?.startsWith(l.path));if(!a){i.writeHead(404),i.end(JSON.stringify({error:"Not Found",message:`No route for ${r.method} ${r.url}`}));return}try{let l={method:r.method||"GET",path:r.url||"/",body:o,headers:r.headers},u=await a.handler(l);i.writeHead(u.status),i.end(JSON.stringify(u.body))}catch(l){e.error({err:l},"API error"),i.writeHead(500),i.end(JSON.stringify({error:"Internal Server Error",message:String(l)}))}})}function R0(n){return[{method:"GET",path:"/api/v1/health",handler:async()=>({status:200,body:{status:"ok",version:T0,uptime:process.uptime()}})},{method:"GET",path:"/api/v1/agents",handler:async()=>({status:200,body:{agents:[{name:"coder",description:"Code generation and modification",status:"available"},{name:"reviewer",description:"Code review and quality analysis",status:"available"},{name:"architect",description:"System architecture design",status:"available"},{name:"devops",description:"Deployment and infrastructure",status:"available"},{name:"researcher",description:"Documentation and research",status:"available"},{name:"planner",description:"Task decomposition and planning",status:"available"},{name:"debugger",description:"Error analysis and fixing",status:"available"}]}})},{method:"GET",path:"/api/v1/models",handler:async()=>({status:200,body:{current:n.model,provider:n.provider,host:n.ollamaHost}})},{method:"POST",path:"/api/v1/chat",handler:async e=>{let{message:t,agent:s}=e.body;return t?{status:200,body:{response:`[${s||"coder"}] Received: ${t}`,agent:s||"coder",model:n.model}}:{status:400,body:{error:"message field is required"}}}},{method:"POST",path:"/api/v1/plan",handler:async e=>{let{task:t}=e.body;return t?{status:200,body:{plan:{task:t,steps:[{step:1,description:"Analyze requirements",agent:"researcher"},{step:2,description:"Design architecture",agent:"architect"},{step:3,description:"Implement code",agent:"coder"},{step:4,description:"Review and test",agent:"reviewer"}]}}}:{status:400,body:{error:"task field is required"}}}},{method:"POST",path:"/api/v1/execute",handler:async e=>{let{command:t}=e.body;return t?n.api.enabled?{status:200,body:{message:"Command queued for execution",command:t}}:{status:403,body:{error:"API execution not enabled"}}:{status:400,body:{error:"command field is required"}}}},{method:"GET",path:"/api/v1/stats",handler:async()=>({status:200,body:{sessions:0,messages:0,uptime:process.uptime(),model:n.model,provider:n.provider}})}]}function O0(n){return new Promise((e,t)=>{let s=Kg(n);s.on("error",t),s.listen(n.api.port,n.api.host,()=>{e(s)})})}var Hg,Bg,Ug,T0,Wg=L(()=>{"use strict";Hg=O(require("http")),Bg=O(require("fs")),Ug=O(require("path"));Yl();T0=E0()});var M0={};Fe(M0,{CLI_VERSION:()=>ks});module.exports=Zg(M0);var cc=O(lc(),1),{program:U0,createCommand:K0,createArgument:q0,createOption:W0,CommanderError:G0,InvalidArgumentError:V0,InvalidOptionArgumentError:z0,Command:uc,Argument:Y0,Option:J0,Help:X0}=cc.default;Ve();yr();Yl();var Gg=O(require("fs")),Vg=O(require("path"));function P0(){try{let n=Vg.resolve(__dirname,"..","package.json");return JSON.parse(Gg.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}var ks=P0(),ne=new uc;ne.name("hablas").description(`hablas CLI v${ks} by Abdulmoin Hablas \u2014 Multi-agent AI development system. Local-first via Ollama, NVIDIA NIM, or any OpenAI-compatible API.`).version(ks).option("-m, --model <model>","Model to use").option("-p, --project <path>","Working directory").option("--host <url>","Ollama host URL").option("--provider <type>","LLM provider: ollama | custom | nvidia").option("--api-url <url>","Custom API base URL (OpenAI-compatible)").option("--api-key <key>","API key for custom/nvidia provider").option("--auto","Auto mode \u2014 skip all tool confirmations").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--theme <name>","UI theme: dark | light | galaxy | ocean | forest").option("--dashboard","Launch TUI dashboard mode").option("--team","Enable hybrid cooperative sync mode with teammates").option("--user <name>","Teammate username for coordination").option("--team-key <password>","Teammate password/key for secure connection encryption").option("--setup","Run first-time setup wizard");ne.command("build <task>").description("FULL BUILD: complete work with the full multi-agent team at MAXIMUM POWER (rich theatre, no classification). Always Hablas + Bob + Alex + David + Emma.").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(t.autoMode=!0),e.timeout&&(t.timeout=parseInt(e.timeout,10));let s=et(t),{runFullTeamCommand:r}=await Promise.resolve().then(()=>(Ve(),rt));await r(n,t,s,"build")});ne.command("design <task>").description("Design/Architecture mode: focused team (Emma + Bob + David + Hablas) with rich output for blueprints and requirements.").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(t.autoMode=!0);let s=et(t),{runFullTeamCommand:r}=await Promise.resolve().then(()=>(Ve(),rt));await r(n,t,s,"design")});ne.command("ask <question>").description("Quick solo ask (minimal team, fast response, no full theatre).").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(t.autoMode=!0);let s=et(t),{runSingleCommand:r}=await Promise.resolve().then(()=>(Ve(),rt));await r(n,t,s)});ne.command("create <description>").description("Generate a full project from a description (uses full team)").option("--stack <stack>","Tech stack preference").option("--with-tests","Include test generation").option("--with-docker","Include Docker setup").action(async(n,e)=>{let t=ne.opts(),s=Te({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey});t.auto&&(s.autoMode=!0);let r=et(s),{runFullTeamCommand:i}=await Promise.resolve().then(()=>(Ve(),rt)),o=`Generate a complete project: ${n}${e.stack?` using ${e.stack}`:""}${e.withTests?" with comprehensive tests":""}${e.withDocker?" with Docker setup":""}. Create all necessary files.`;await i(o,s,r,"build")});ne.command("commit").description("Generate a smart commit message from staged changes").action(async()=>{let n=ne.opts(),e=Te({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),t=et(e),{getGitStatus:s,getDetailedDiff:r,generateCommitPrompt:i}=await Promise.resolve().then(()=>(pn(),Kn)),o=e.workingDirectory||process.cwd(),a=await s(o);if(!a||a.staged.length===0){console.log(" \u26A0 No staged changes. Use `git add` first.");return}let l=await r(o),u=i(l,a.staged),{runSingleCommand:d}=await Promise.resolve().then(()=>(Ve(),rt));await d(u,e,t)});ne.command("pr").description("Generate a PR description from branch commits").option("--base <branch>","Base branch","main").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=et(t),{getGitStatus:r,getRecentCommits:i,generatePRPrompt:o}=await Promise.resolve().then(()=>(pn(),Kn)),a=t.workingDirectory||process.cwd(),l=await r(a),u=await i(a,20),d=o(u,n.base,l?.branch||"feature"),{runSingleCommand:f}=await Promise.resolve().then(()=>(Ve(),rt));await f(d,t,s)});ne.command("changelog").description("Generate changelog from recent commits").option("--version <ver>","Version number",ks).option("-n, --count <n>","Number of commits to include","30").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=et(t),{getRecentCommits:r,generateChangelogPrompt:i}=await Promise.resolve().then(()=>(pn(),Kn)),o=t.workingDirectory||process.cwd(),a=await r(o,parseInt(n.count)),l=i(a,n.version),{runSingleCommand:u}=await Promise.resolve().then(()=>(Ve(),rt));await u(l,t,s)});ne.command("security").description("Run security scan on the project").option("--fix","Auto-fix issues where possible").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),{runSecurityScan:s,formatScanResults:r}=await Promise.resolve().then(()=>(Bi(),Uc)),i=t.workingDirectory||process.cwd();console.log(`
1261
1261
  \u{1F512} Running security scan...
1262
1262
  `);let o=s(i);console.log(r(o))});ne.command("stats").description("Show developer analytics and usage statistics").action(async()=>{let{loadStats:n,formatStats:e}=await Promise.resolve().then(()=>(Un(),Ni)),t=n();console.log(e(t))});ne.command("team").description("Manage team configuration").option("--init <name>","Initialize team config").option("--add <email>","Add team member").option("--share","Share current session").action(async n=>{let e=ne.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),{loadTeamConfig:s,initTeamConfig:r,addTeamMember:i,saveTeamConfig:o,formatTeamConfig:a}=await Promise.resolve().then(()=>(ia(),Uf)),l=t.workingDirectory||process.cwd();if(n.init)r(l,n.init),console.log(`
1263
1263
  \u2713 Team "${n.init}" initialized.`),console.log(` Config saved to: .hablas/team.json
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hablas-ai",
3
- "version": "1.3.10",
3
+ "version": "1.3.11",
4
4
  "description": "Premium multi-agent AI coding agent for your terminal — local-first via Ollama, NVIDIA NIM, or any OpenAI-compatible API. Watch the team work in front of you.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {