hablas-ai 1.3.15 → 1.3.16

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 +302 -238
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -1,47 +1,47 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Vg=Object.create;var As=Object.defineProperty;var zg=Object.getOwnPropertyDescriptor;var Yg=Object.getOwnPropertyNames;var Jg=Object.getPrototypeOf,Xg=Object.prototype.hasOwnProperty;var L=(n,e)=>()=>(n&&(e=n(n=0)),e);var N=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ne=(n,e)=>{for(var t in e)As(n,t,{get:e[t],enumerable:!0})},Jl=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Yg(e))!Xg.call(n,r)&&r!==t&&As(n,r,{get:()=>e[r],enumerable:!(s=zg(e,r))||s.enumerable});return n};var O=(n,e,t)=>(t=n!=null?Vg(Jg(n)):{},Jl(e||!n||!n.__esModule?As(t,"default",{value:n,enumerable:!0}):t,n)),Qg=n=>Jl(As({},"__esModule",{value:!0}),n);var Ln=N(Xr=>{var $s=class extends Error{constructor(e,t,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},Jr=class extends $s{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Xr.CommanderError=$s;Xr.InvalidArgumentError=Jr});var Cs=N(Zr=>{var{InvalidArgumentError:Zg}=Ln(),Qr=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,s)=>{if(!this.argChoices.includes(t))throw new Zg(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,s):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ey(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Zr.Argument=Qr;Zr.humanReadableArgName=ey});var ti=N(Xl=>{var{humanReadableArgName:ty}=Cs(),ei=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(r=>!r._hidden),s=e._getHelpCommand();return s&&!s._hidden&&t.push(s),this.sortSubcommands&&t.sort((r,i)=>r.name().localeCompare(i.name())),t}compareOptions(e,t){let s=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return s(e).localeCompare(s(t))}visibleOptions(e){let t=e.options.filter(r=>!r.hidden),s=e._getHelpOption();if(s&&!s.hidden){let r=s.short&&e._findOption(s.short),i=s.long&&e._findOption(s.long);!r&&!i?t.push(s):s.long&&!i?t.push(e.createOption(s.long,s.description)):s.short&&!r&&t.push(e.createOption(s.short,s.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let s=e.parent;s;s=s.parent){let r=s.options.filter(i=>!i.hidden);t.push(...r)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(s=>ty(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((s,r)=>Math.max(s,t.subcommandTerm(r).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((s,r)=>Math.max(s,t.optionTerm(r).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((s,r)=>Math.max(s,t.optionTerm(r).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((s,r)=>Math.max(s,t.argumentTerm(r).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let s="";for(let r=e.parent;r;r=r.parent)s=r.name()+" "+s;return s+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let s=`(${t.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatHelp(e,t){let s=t.padWidth(e,t),r=t.helpWidth||80,i=2,o=2;function a(p,g){if(g){let x=`${p.padEnd(s+o)}${g}`;return t.wrap(x,r-i,s+o)}return p}function l(p){return p.join(`
2
+ "use strict";var Qg=Object.create;var Cs=Object.defineProperty;var Zg=Object.getOwnPropertyDescriptor;var ey=Object.getOwnPropertyNames;var ty=Object.getPrototypeOf,ny=Object.prototype.hasOwnProperty;var L=(n,e)=>()=>(n&&(e=n(n=0)),e);var F=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ne=(n,e)=>{for(var t in e)Cs(n,t,{get:e[t],enumerable:!0})},tc=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ey(e))!ny.call(n,r)&&r!==t&&Cs(n,r,{get:()=>e[r],enumerable:!(s=Zg(e,r))||s.enumerable});return n};var O=(n,e,t)=>(t=n!=null?Qg(ty(n)):{},tc(e||!n||!n.__esModule?Cs(t,"default",{value:n,enumerable:!0}):t,n)),sy=n=>tc(Cs({},"__esModule",{value:!0}),n);var Nn=F(ei=>{var Es=class extends Error{constructor(e,t,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},Zr=class extends Es{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ei.CommanderError=Es;ei.InvalidArgumentError=Zr});var Ts=F(ni=>{var{InvalidArgumentError:ry}=Nn(),ti=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,s)=>{if(!this.argChoices.includes(t))throw new ry(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,s):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function iy(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}ni.Argument=ti;ni.humanReadableArgName=iy});var ri=F(nc=>{var{humanReadableArgName:oy}=Ts(),si=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(r=>!r._hidden),s=e._getHelpCommand();return s&&!s._hidden&&t.push(s),this.sortSubcommands&&t.sort((r,i)=>r.name().localeCompare(i.name())),t}compareOptions(e,t){let s=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return s(e).localeCompare(s(t))}visibleOptions(e){let t=e.options.filter(r=>!r.hidden),s=e._getHelpOption();if(s&&!s.hidden){let r=s.short&&e._findOption(s.short),i=s.long&&e._findOption(s.long);!r&&!i?t.push(s):s.long&&!i?t.push(e.createOption(s.long,s.description)):s.short&&!r&&t.push(e.createOption(s.short,s.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let s=e.parent;s;s=s.parent){let r=s.options.filter(i=>!i.hidden);t.push(...r)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(s=>oy(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((s,r)=>Math.max(s,t.subcommandTerm(r).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((s,r)=>Math.max(s,t.optionTerm(r).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((s,r)=>Math.max(s,t.optionTerm(r).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((s,r)=>Math.max(s,t.argumentTerm(r).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let s="";for(let r=e.parent;r;r=r.parent)s=r.name()+" "+s;return s+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let s=`(${t.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatHelp(e,t){let s=t.padWidth(e,t),r=t.helpWidth||80,i=2,o=2;function a(p,g){if(g){let x=`${p.padEnd(s+o)}${g}`;return t.wrap(x,r-i,s+o)}return p}function l(p){return p.join(`
3
3
  `).replace(/^/gm," ".repeat(i))}let u=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(u=u.concat([t.wrap(d,r,0),""]));let f=t.visibleArguments(e).map(p=>a(t.argumentTerm(p),t.argumentDescription(p)));f.length>0&&(u=u.concat(["Arguments:",l(f),""]));let h=t.visibleOptions(e).map(p=>a(t.optionTerm(p),t.optionDescription(p)));if(h.length>0&&(u=u.concat(["Options:",l(h),""])),this.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(g=>a(t.optionTerm(g),t.optionDescription(g)));p.length>0&&(u=u.concat(["Global Options:",l(p),""]))}let m=t.visibleCommands(e).map(p=>a(t.subcommandTerm(p),t.subcommandDescription(p)));return m.length>0&&(u=u.concat(["Commands:",l(m),""])),u.join(`
4
4
  `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,s,r=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=t-s;if(a<r)return e;let l=e.slice(0,s),u=e.slice(s).replace(`\r
5
5
  `,`
6
6
  `),d=" ".repeat(s),h="\\s\u200B",m=new RegExp(`
7
7
  |.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),p=u.match(m)||[];return l+p.map((g,x)=>g===`
8
8
  `?"":(x>0?d:"")+g.trimEnd()).join(`
9
- `)}};Xl.Help=ei});var ii=N(ri=>{var{InvalidArgumentError:ny}=Ln(),ni=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=ry(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,s)=>{if(!this.argChoices.includes(t))throw new ny(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,s):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return sy(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},si=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,t){let s=t.attributeName();if(!this.dualOptions.has(s))return!0;let r=this.negativeOptions.get(s).presetArg,i=r!==void 0?r:!1;return t.negate===(i===e)}};function sy(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ry(n){let e,t,s=n.split(/[ |,]+/);return s.length>1&&!/^[[<]/.test(s[1])&&(e=s.shift()),t=s.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}ri.Option=ni;ri.DualOptions=si});var Zl=N(Ql=>{function iy(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let s=0;s<=n.length;s++)t[s]=[s];for(let s=0;s<=e.length;s++)t[0][s]=s;for(let s=1;s<=e.length;s++)for(let r=1;r<=n.length;r++){let i=1;n[r-1]===e[s-1]?i=0:i=1,t[r][s]=Math.min(t[r-1][s]+1,t[r][s-1]+1,t[r-1][s-1]+i),r>1&&s>1&&n[r-1]===e[s-2]&&n[r-2]===e[s-1]&&(t[r][s]=Math.min(t[r][s],t[r-2][s-2]+1))}return t[n.length][e.length]}function oy(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(o=>o.slice(2)));let s=[],r=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=iy(n,o),l=Math.max(n.length,o.length);(l-a)/l>i&&(a<r?(r=a,s=[o]):a===r&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),t&&(s=s.map(o=>`--${o}`)),s.length>1?`
9
+ `)}};nc.Help=si});var li=F(ai=>{var{InvalidArgumentError:ay}=Nn(),ii=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=cy(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,s)=>{if(!this.argChoices.includes(t))throw new ay(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,s):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return ly(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},oi=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,t){let s=t.attributeName();if(!this.dualOptions.has(s))return!0;let r=this.negativeOptions.get(s).presetArg,i=r!==void 0?r:!1;return t.negate===(i===e)}};function ly(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function cy(n){let e,t,s=n.split(/[ |,]+/);return s.length>1&&!/^[[<]/.test(s[1])&&(e=s.shift()),t=s.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}ai.Option=ii;ai.DualOptions=oi});var rc=F(sc=>{function uy(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let s=0;s<=n.length;s++)t[s]=[s];for(let s=0;s<=e.length;s++)t[0][s]=s;for(let s=1;s<=e.length;s++)for(let r=1;r<=n.length;r++){let i=1;n[r-1]===e[s-1]?i=0:i=1,t[r][s]=Math.min(t[r-1][s]+1,t[r][s-1]+1,t[r-1][s-1]+i),r>1&&s>1&&n[r-1]===e[s-2]&&n[r-2]===e[s-1]&&(t[r][s]=Math.min(t[r][s],t[r-2][s-2]+1))}return t[n.length][e.length]}function dy(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(o=>o.slice(2)));let s=[],r=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=uy(n,o),l=Math.max(n.length,o.length);(l-a)/l>i&&(a<r?(r=a,s=[o]):a===r&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),t&&(s=s.map(o=>`--${o}`)),s.length>1?`
10
10
  (Did you mean one of ${s.join(", ")}?)`:s.length===1?`
11
- (Did you mean ${s[0]}?)`:""}Ql.suggestSimilar=oy});var rc=N(sc=>{var ay=require("node:events").EventEmitter,oi=require("node:child_process"),At=require("node:path"),ai=require("node:fs"),de=require("node:process"),{Argument:ly,humanReadableArgName:cy}=Cs(),{CommanderError:li}=Ln(),{Help:uy}=ti(),{Option:ec,DualOptions:dy}=ii(),{suggestSimilar:tc}=Zl(),ci=class n extends ay{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>de.stdout.write(t),writeErr:t=>de.stderr.write(t),getOutHelpWidth:()=>de.stdout.isTTY?de.stdout.columns:void 0,getErrHelpWidth:()=>de.stderr.isTTY?de.stderr.columns:void 0,outputError:(t,s)=>s(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,s){let r=t,i=s;typeof r=="object"&&r!==null&&(i=r,r=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return r&&(l.description(r),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),r?this:l}createCommand(e){return new n(e)}createHelp(){return Object.assign(new uy,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
- - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new ly(e,t)}argument(e,t,s,r){let i=this.createArgument(e,t);return typeof s=="function"?i.default(r).argParser(s):i.default(s),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,s,r]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(s);return o.helpOption(!1),r&&o.arguments(r),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let s=["preSubcommand","preAction","postAction"];if(!s.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
- Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,s){this._exitCallback&&this._exitCallback(new li(e,t,s)),de.exit(e)}action(e){let t=s=>{let r=this.registeredArguments.length,i=s.slice(0,r);return this._storeOptionsAsProperties?i[r]=this:i[r]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new ec(e,t)}_callParseArg(e,t,s,r){try{return e.parseArg(t,s)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${r} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let s=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
14
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=r=>[r.name()].concat(r.aliases()),s=t(e).find(r=>this._findCommand(r));if(s){let r=t(this._findCommand(s)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),s=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(s,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let r=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(s);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(s,i,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;r(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;r(i,o,"env")}),this}_optionEx(e,t,s,r,i){if(typeof t=="object"&&t instanceof ec)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,s);if(o.makeOptionMandatory(!!e.mandatory),typeof r=="function")o.default(i).argParser(r);else if(r instanceof RegExp){let a=r;r=(l,u)=>{let d=a.exec(l);return d?d[0]:u},o.default(i).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,s,r){return this._optionEx({},e,t,s,r)}requiredOption(e,t,s,r){return this._optionEx({mandatory:!0},e,t,s,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,s){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(t=s.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){de.versions?.electron&&(t.from="electron");let r=de.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=de.argv),this.rawArgs=e.slice();let s;switch(t.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":de.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,t){let s=this._prepareUserArgs(e,t);return this._parseCommand([],s),this}async parseAsync(e,t){let s=this._prepareUserArgs(e,t);return await this._parseCommand([],s),this}_executeSubCommand(e,t){t=t.slice();let s=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,f){let h=At.resolve(d,f);if(ai.existsSync(h))return h;if(r.includes(At.extname(f)))return;let m=r.find(p=>ai.existsSync(`${h}${p}`));if(m)return`${h}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=ai.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=At.resolve(At.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=At.basename(this._scriptPath,At.extname(this._scriptPath));f!==this._name&&(d=i(a,`${f}-${e._name}`))}o=d||o}s=r.includes(At.extname(o));let l;de.platform!=="win32"?s?(t.unshift(o),t=nc(de.execArgv).concat(t),l=oi.spawn(de.argv[0],t,{stdio:"inherit"})):l=oi.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=nc(de.execArgv).concat(t),l=oi.spawn(de.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{de.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let u=this._exitCallback;l.on("close",d=>{d=d??1,u?u(new li(d,"commander.executeSubCommandAsync","(close)")):de.exit(d)}),l.on("error",d=>{if(d.code==="ENOENT"){let f=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
11
+ (Did you mean ${s[0]}?)`:""}sc.suggestSimilar=dy});var cc=F(lc=>{var fy=require("node:events").EventEmitter,ci=require("node:child_process"),At=require("node:path"),ui=require("node:fs"),de=require("node:process"),{Argument:py,humanReadableArgName:hy}=Ts(),{CommanderError:di}=Nn(),{Help:my}=ri(),{Option:ic,DualOptions:gy}=li(),{suggestSimilar:oc}=rc(),fi=class n extends fy{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>de.stdout.write(t),writeErr:t=>de.stderr.write(t),getOutHelpWidth:()=>de.stdout.isTTY?de.stdout.columns:void 0,getErrHelpWidth:()=>de.stderr.isTTY?de.stderr.columns:void 0,outputError:(t,s)=>s(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,s){let r=t,i=s;typeof r=="object"&&r!==null&&(i=r,r=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return r&&(l.description(r),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),r?this:l}createCommand(e){return new n(e)}createHelp(){return Object.assign(new my,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
+ - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new py(e,t)}argument(e,t,s,r){let i=this.createArgument(e,t);return typeof s=="function"?i.default(r).argParser(s):i.default(s),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,s,r]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(s);return o.helpOption(!1),r&&o.arguments(r),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let s=["preSubcommand","preAction","postAction"];if(!s.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
+ Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,s){this._exitCallback&&this._exitCallback(new di(e,t,s)),de.exit(e)}action(e){let t=s=>{let r=this.registeredArguments.length,i=s.slice(0,r);return this._storeOptionsAsProperties?i[r]=this:i[r]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new ic(e,t)}_callParseArg(e,t,s,r){try{return e.parseArg(t,s)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${r} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let s=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
14
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=r=>[r.name()].concat(r.aliases()),s=t(e).find(r=>this._findCommand(r));if(s){let r=t(this._findCommand(s)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),s=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(s,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let r=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(s);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(s,i,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;r(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;r(i,o,"env")}),this}_optionEx(e,t,s,r,i){if(typeof t=="object"&&t instanceof ic)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,s);if(o.makeOptionMandatory(!!e.mandatory),typeof r=="function")o.default(i).argParser(r);else if(r instanceof RegExp){let a=r;r=(l,u)=>{let d=a.exec(l);return d?d[0]:u},o.default(i).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,s,r){return this._optionEx({},e,t,s,r)}requiredOption(e,t,s,r){return this._optionEx({mandatory:!0},e,t,s,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,s){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(t=s.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){de.versions?.electron&&(t.from="electron");let r=de.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=de.argv),this.rawArgs=e.slice();let s;switch(t.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":de.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,t){let s=this._prepareUserArgs(e,t);return this._parseCommand([],s),this}async parseAsync(e,t){let s=this._prepareUserArgs(e,t);return await this._parseCommand([],s),this}_executeSubCommand(e,t){t=t.slice();let s=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,f){let h=At.resolve(d,f);if(ui.existsSync(h))return h;if(r.includes(At.extname(f)))return;let m=r.find(p=>ui.existsSync(`${h}${p}`));if(m)return`${h}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=ui.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=At.resolve(At.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=At.basename(this._scriptPath,At.extname(this._scriptPath));f!==this._name&&(d=i(a,`${f}-${e._name}`))}o=d||o}s=r.includes(At.extname(o));let l;de.platform!=="win32"?s?(t.unshift(o),t=ac(de.execArgv).concat(t),l=ci.spawn(de.argv[0],t,{stdio:"inherit"})):l=ci.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=ac(de.execArgv).concat(t),l=ci.spawn(de.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{de.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let u=this._exitCallback;l.on("close",d=>{d=d??1,u?u(new di(d,"commander.executeSubCommandAsync","(close)")):de.exit(d)}),l.on("error",d=>{if(d.code==="ENOENT"){let f=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
15
15
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${f}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)de.exit(1);else{let f=new li(1,"commander.executeSubCommandAsync","(error)");f.nestedError=d,u(f)}}),this.runningCommand=l}_dispatchSubcommand(e,t,s){let r=this._findCommand(e);r||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,r,"preSubcommand"),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(s));else return r._parseCommand(t,s)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,r,i)=>{let o=r;if(r!==null&&s.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,r,i,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((s,r)=>{let i=s.defaultValue;s.variadic?r<this.args.length?(i=this.args.slice(r),s.parseArg&&(i=i.reduce((o,a)=>e(s,a,o),s.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],s.parseArg&&(i=e(s,i,s.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let s=e,r=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{r.push({hookedCommand:i,callback:o})})}),t==="postAction"&&r.reverse(),r.forEach(i=>{s=this._chainOrCall(s,()=>i.callback(i.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,t,s){let r=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(i=>{r=this._chainOrCall(r,()=>i(this,t))}),r}_parseCommand(e,t){let s=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),t=s.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let r=s.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let r=e.find(i=>s.conflictsWith.includes(i.attributeName()));r&&this._conflictingOption(s,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],s=[],r=t,i=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){r===s&&r.push(l),r.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let u=this._findOption(l);if(u){if(u.required){let d=i.shift();d===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,d)}else if(u.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${u.name()}`,d)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),d=this._findOption(l.slice(0,u));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,l.slice(u+1));continue}}if(o(l)&&(r=s),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&s.length===0){if(this._findCommand(l)){t.push(l),i.length>0&&s.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){s.push(l),i.length>0&&s.push(...i);break}}if(this._passThroughOptions){r.push(l),i.length>0&&r.push(...i);break}r.push(l)}return{operands:t,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let s=0;s<t;s++){let r=this.options[s].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
17
+ - ${f}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)de.exit(1);else{let f=new di(1,"commander.executeSubCommandAsync","(error)");f.nestedError=d,u(f)}}),this.runningCommand=l}_dispatchSubcommand(e,t,s){let r=this._findCommand(e);r||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,r,"preSubcommand"),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(s));else return r._parseCommand(t,s)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,r,i)=>{let o=r;if(r!==null&&s.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,r,i,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((s,r)=>{let i=s.defaultValue;s.variadic?r<this.args.length?(i=this.args.slice(r),s.parseArg&&(i=i.reduce((o,a)=>e(s,a,o),s.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],s.parseArg&&(i=e(s,i,s.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let s=e,r=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{r.push({hookedCommand:i,callback:o})})}),t==="postAction"&&r.reverse(),r.forEach(i=>{s=this._chainOrCall(s,()=>i.callback(i.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,t,s){let r=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(i=>{r=this._chainOrCall(r,()=>i(this,t))}),r}_parseCommand(e,t){let s=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),t=s.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let r=s.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let r=e.find(i=>s.conflictsWith.includes(i.attributeName()));r&&this._conflictingOption(s,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],s=[],r=t,i=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){r===s&&r.push(l),r.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let u=this._findOption(l);if(u){if(u.required){let d=i.shift();d===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,d)}else if(u.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${u.name()}`,d)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),d=this._findOption(l.slice(0,u));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,l.slice(u+1));continue}}if(o(l)&&(r=s),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&s.length===0){if(this._findCommand(l)){t.push(l),i.length>0&&s.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){s.push(l),i.length>0&&s.push(...i);break}}if(this._passThroughOptions){r.push(l),i.length>0&&r.push(...i);break}r.push(l)}return{operands:t,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let s=0;s<t;s++){let r=this.options[s].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
18
18
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
19
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
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 dy(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
- `),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=>cy(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.
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 gy(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=oc(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=oc(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
+ `),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=>hy(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:fy,InvalidArgumentError:oc}=Ln(),{Help:py}=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=py;We.CommanderError=fy;We.InvalidArgumentError=oc;We.InvalidOptionArgumentError=oc});var dc={};Ne(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
- `);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 gy(n){return n.map(e=>({type:"function",function:e.function}))}function yy(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,hy,Ts,hc,my,Gt,di=L(()=>{"use strict";pc=12e4,hy=6e4,Ts=3,hc=1e3,my=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<my;){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(hy)});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=gy(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?yy(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
- `);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
- `)}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.
23
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ac(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})}lc.Command=fi});var pc=F(Ge=>{var{Argument:uc}=Ts(),{Command:pi}=cc(),{CommanderError:yy,InvalidArgumentError:dc}=Nn(),{Help:by}=ri(),{Option:fc}=li();Ge.program=new pi;Ge.createCommand=n=>new pi(n);Ge.createOption=(n,e)=>new fc(n,e);Ge.createArgument=(n,e)=>new uc(n,e);Ge.Command=pi;Ge.Option=fc;Ge.Argument=uc;Ge.Help=by;Ge.CommanderError=yy;Ge.InvalidArgumentError=dc;Ge.InvalidOptionArgumentError=dc});var gc={};Ne(gc,{DEFAULT_CONFIG:()=>Fn,NVIDIA_PROVIDER:()=>Ft});var Fn,Ft,jn=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:""}},Ft={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 Rs,yc=L(()=>{"use strict";Rs=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
+ `);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 wc(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 xy(n){return n.map(e=>({type:"function",function:e.function}))}function Sy(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 xc(n){return new Promise(e=>setTimeout(e,n))}function Sc(n,e){return!(n.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var bc,vy,Os,vc,wy,Vt,hi=L(()=>{"use strict";bc=12e4,vy=6e4,Os=3,vc=1e3,wy=20;Vt=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<wy;){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(vy)});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:wc(e)};t.length>0&&(i.tools=xy(t),i.tool_choice="auto");let o=null;for(let a=0;a<=Os;a++)try{let l=new AbortController,u=setTimeout(()=>l.abort(),bc),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(!Sc(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<Os){let x=vc*Math.pow(2,a);await xc(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?Sy(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(Sc(f)&&(o=f,a<Os)){let h=vc*Math.pow(2,a);await xc(h);continue}throw f}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Os)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:wc(e),stream:!0}),signal:t||AbortSignal.timeout(bc)});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
+ `);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:Ft.apiUrl};return new Vt(e)}return n.provider==="custom"&&n.apiUrl?new Vt(n):new Rs(n)}function Ps(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 Hn=L(()=>{"use strict";jn();yc();hi()});var _c=L(()=>{"use strict"});function zt(){let n={providers:[],activeProvider:null,activeModel:null};try{if($t.existsSync(gi)){let e=$t.readFileSync(gi,"utf-8"),t=JSON.parse(e);return{...n,...t}}}catch{}return n}function bi(n){$t.existsSync(mi)||$t.mkdirSync(mi,{recursive:!0}),$t.writeFileSync(gi,JSON.stringify(n,null,2),"utf-8")}function nt(n){let e=zt();e.providers=e.providers.filter(t=>t.name!==n.name),e.providers.push(n),bi(e)}function Ac(n){let e=zt(),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),bi(e),!0):!1}function $c(n){return zt().providers.find(t=>t.name.toLowerCase()===n.toLowerCase())}function Ms(){return zt().providers}function Cc(n,e){let t=zt(),s=t.providers.find(r=>r.name===n);s&&(t.activeProvider=n,t.activeModel=e||s.defaultModel,bi(t))}function Ec(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
+ `)}var $t,yi,kc,mi,gi,vi=L(()=>{"use strict";$t=O(require("fs")),yi=O(require("path")),kc=O(require("os"));_c();mi=yi.join(kc.homedir(),".hablas"),gi=yi.join(mi,"models.json")});function Ls(){try{if(Ct.existsSync(Is))return JSON.parse(Ct.readFileSync(Is,"utf-8"))}catch{}return{}}function Rc(n){let e=Ds.dirname(Is);Ct.existsSync(e)||Ct.mkdirSync(e,{recursive:!0}),Ct.writeFileSync(Is,JSON.stringify(n,null,2),"utf-8")}function Oc(n,e){let t=Ls();t[n]=e,Rc(t)}function Pc(n){let e=Ls();return e[n]?(delete e[n],Rc(e),!0):!1}function Mc(n){let e=Ls(),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 Ic(){let n=Ls(),e=Object.entries(n);return e.length===0?` No aliases defined.
27
27
  Use: /alias set <name> <command>`:e.map(([t,s])=>` ${t} \u2192 ${s}`).join(`
28
- `)}var Ct,Ms,kc,Ps,yi=L(()=>{"use strict";Ct=O(require("fs")),Ms=O(require("path")),kc=O(require("os")),Ps=Ms.join(kc.homedir(),".hablas","aliases.json")});var Pc={};Ne(Pc,{disablePlugin:()=>xi,enablePlugin:()=>wi,ensurePluginsDir:()=>Fs,listPlugins:()=>Oc,renderPlugins:()=>Si});function vi(){try{if(je.existsSync(Ls))return JSON.parse(je.readFileSync(Ls,"utf-8"))}catch{}return{disabled:[]}}function Rc(n){let e=un.dirname(Ls);je.existsSync(e)||je.mkdirSync(e,{recursive:!0}),je.writeFileSync(Ls,JSON.stringify(n,null,2),"utf-8")}function Fs(){je.existsSync(Ds)||je.mkdirSync(Ds,{recursive:!0})}function Oc(){Fs();let n=vi(),e=[];try{let t=je.readdirSync(Ds).filter(s=>s.endsWith(".js"));for(let s of t){let r=un.join(Ds,s);try{let i=require(r);e.push({name:i.name||s.replace(".js",""),description:i.description||"No description",version:i.version||"0.0.0",enabled:!n.disabled.includes(i.name||s.replace(".js","")),path:r,commands:i.commands})}catch{e.push({name:s.replace(".js",""),description:"Failed to load",version:"?",enabled:!1,path:r})}}}catch{}return e}function wi(n){let e=vi(),t=e.disabled.indexOf(n);return t!==-1?(e.disabled.splice(t,1),Rc(e),!0):!1}function xi(n){let e=vi();return e.disabled.includes(n)?!1:(e.disabled.push(n),Rc(e),!0)}function Si(){let n=Oc();return n.length===0?` No plugins installed.
28
+ `)}var Ct,Ds,Tc,Is,wi=L(()=>{"use strict";Ct=O(require("fs")),Ds=O(require("path")),Tc=O(require("os")),Is=Ds.join(Tc.homedir(),".hablas","aliases.json")});var Nc={};Ne(Nc,{disablePlugin:()=>ki,enablePlugin:()=>_i,ensurePluginsDir:()=>js,listPlugins:()=>Lc,renderPlugins:()=>Ai});function Si(){try{if(Fe.existsSync(Fs))return JSON.parse(Fe.readFileSync(Fs,"utf-8"))}catch{}return{disabled:[]}}function Dc(n){let e=dn.dirname(Fs);Fe.existsSync(e)||Fe.mkdirSync(e,{recursive:!0}),Fe.writeFileSync(Fs,JSON.stringify(n,null,2),"utf-8")}function js(){Fe.existsSync(Ns)||Fe.mkdirSync(Ns,{recursive:!0})}function Lc(){js();let n=Si(),e=[];try{let t=Fe.readdirSync(Ns).filter(s=>s.endsWith(".js"));for(let s of t){let r=dn.join(Ns,s);try{let i=require(r);e.push({name:i.name||s.replace(".js",""),description:i.description||"No description",version:i.version||"0.0.0",enabled:!n.disabled.includes(i.name||s.replace(".js","")),path:r,commands:i.commands})}catch{e.push({name:s.replace(".js",""),description:"Failed to load",version:"?",enabled:!1,path:r})}}}catch{}return e}function _i(n){let e=Si(),t=e.disabled.indexOf(n);return t!==-1?(e.disabled.splice(t,1),Dc(e),!0):!1}function ki(n){let e=Si();return e.disabled.includes(n)?!1:(e.disabled.push(n),Dc(e),!0)}function Ai(){let n=Lc();return n.length===0?` No plugins installed.
29
29
  Add .js files to ~/.hablas/plugins/`:n.map(e=>{let t=e.enabled?"\u25CF enabled":"\u25CB disabled";return` ${e.name} v${e.version} [${t}]
30
30
  ${e.description}`}).join(`
31
31
 
32
- `)}var je,un,bi,Ds,Ls,_i=L(()=>{"use strict";je=O(require("fs")),un=O(require("path")),bi=O(require("os")),Ds=un.join(bi.homedir(),".hablas","plugins"),Ls=un.join(bi.homedir(),".hablas","plugins.json")});var Dc={};Ne(Dc,{renderDiagnostics:()=>$i,runDiagnostics:()=>Ai});async function Ai(n){let e=[],t=process.version,s=parseInt(t.slice(1).split(".")[0],10);e.push({name:"Node.js",status:s>=20?"ok":s>=18?"warn":"error",message:s>=20?`${t} (recommended)`:s>=18?`${t} (works, but 20+ recommended)`:`${t} (too old, need 20+)`});let r=Mc.join(nt.homedir(),".hablas");if(e.push({name:"Config directory",status:ki.existsSync(r)?"ok":"warn",message:ki.existsSync(r)?r:"Not created yet (will be created on first use)"}),n.provider==="ollama")try{let i=await fetch(`${n.ollamaHost}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let o=await i.json(),a=Array.isArray(o.models)?o.models.length:0;e.push({name:"Ollama",status:"ok",message:`Connected \u2014 ${a} models available`})}else e.push({name:"Ollama",status:"error",message:`HTTP ${i.status}`})}catch(i){let o=i instanceof Error?i.message:String(i);e.push({name:"Ollama",status:"error",message:o.includes("ECONNREFUSED")?"Not running \u2014 start with: ollama serve":`Connection failed: ${o}`})}else{let i=n.apiUrl||"unknown";try{let o=await fetch(`${i}/models`,{signal:AbortSignal.timeout(5e3),headers:{Authorization:"Bearer test"}});e.push({name:"API Provider",status:o.ok||o.status===401?"ok":"warn",message:`${i} \u2014 reachable`})}catch{e.push({name:"API Provider",status:"warn",message:`${i} \u2014 could not verify`})}}try{let i=nt.homedir();if(process.platform!=="win32"){let a=(0,Ic.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",u=a[4]||"?";e.push({name:"Disk space",status:parseInt(u)>90?"warn":"ok",message:`${l} available (${u} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:n.model?"ok":"warn",message:n.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${nt.platform()} ${nt.arch()} \u2014 ${nt.cpus().length} cores, ${Math.round(nt.totalmem()/1024/1024/1024)}GB RAM`}),e}function $i(n){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},t={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},s="\x1B[0m",r="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of n){let u=`${t[l.status]}${e[l.status]}${s}`,d=l.name.padEnd(18);i.push(` ${u} ${d}${r}${l.message}${s}`)}let o=n.filter(l=>l.status==="error").length,a=n.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${t.error}${o} error(s) found \u2014 fix these for hablas to work properly${s}`):a>0?i.push(` ${t.warn}${a} warning(s) \u2014 hablas should work but check the items above${s}`):i.push(` ${t.ok}All checks passed \u2014 hablas is ready!${s}`),i.push(""),i.join(`
33
- `)}var ki,Mc,nt,Ic,Ci=L(()=>{"use strict";ki=O(require("fs")),Mc=O(require("path")),nt=O(require("os")),Ic=require("child_process")});function Lc(){let n=[];for(let e of we){let s=e.role==="hablas"?" \u2605":"";n.push(` @${e.name}${s} \u2014 ${e.title}`),n.push(` ${e.description}`)}return n.join(`
34
- `)}var we,Ns=L(()=>{"use strict";we=[{role:"hablas",name:"Hablas",title:"Team Leader",description:"Software Engineer & Team Coordinator. Receives user requests, creates plans, distributes tasks, and compiles final responses.",expertise:["planning","coordination","architecture","code-review","decision-making"]},{role:"bob",name:"Bob",title:"Architect",description:"System Architect. Designs software architecture, database schemas, API structures, and system blueprints.",expertise:["system-design","architecture","database","api-design","scalability"]},{role:"alex",name:"Alex",title:"Engineer",description:"Full-Stack Engineer. Implements code, builds features, fixes bugs, handles DevOps and deployment.",expertise:["coding","implementation","debugging","devops","testing","deployment"]},{role:"david",name:"David",title:"Data Analyst",description:"Data & Research Specialist. Handles research, data analysis, documentation, and information gathering.",expertise:["research","data-analysis","documentation","ml","optimization"]},{role:"emma",name:"Emma",title:"Product Manager",description:"Product Manager. Analyzes user needs, creates PRDs, competitive analysis, market research, and requirement specifications.",expertise:["product-management","requirements","prd","market-research","competitive-analysis","user-stories"]}]});function zt(){try{if(Et.existsSync(Hn)){let n=Et.readFileSync(Hn,"utf-8"),e=JSON.parse(n);return{...Fc,...e}}}catch{}return{...Fc}}function Ei(n){let e=js.dirname(Hn);Et.existsSync(e)||Et.mkdirSync(e,{recursive:!0}),Et.writeFileSync(Hn,JSON.stringify(n,null,2),"utf-8")}function Ti(){return Hn}var Et,js,Nc,Hn,Fc,Ri=L(()=>{"use strict";Et=O(require("fs")),js=O(require("path")),Nc=O(require("os")),Hn=js.join(Nc.homedir(),".hablas","agents.json"),Fc={hablas:{model:"stepfun-ai/step-3.7-flash",temperature:.7},bob:{model:"stepfun-ai/step-3.7-flash",temperature:.4},alex:{model:"stepfun-ai/step-3.7-flash",temperature:.2},david:{model:"stepfun-ai/step-3.7-flash",temperature:.5},emma:{model:"stepfun-ai/step-3.7-flash",temperature:.6},gate:{model:"stepfun-ai/step-3.5-flash",temperature:.3}}});var Ni={};Ne(Ni,{formatStats:()=>xy,loadStats:()=>Bn,saveStats:()=>dn,trackAgentUsage:()=>Fi,trackFileModified:()=>vy,trackMessage:()=>Di,trackSession:()=>Ii,trackToolCall:()=>Li});function Bn(){try{if(Tt.existsSync(Pi))return JSON.parse(Tt.readFileSync(Pi,"utf-8"))}catch{}return by()}function dn(n){try{Tt.existsSync(Oi)||Tt.mkdirSync(Oi,{recursive:!0}),Tt.writeFileSync(Pi,JSON.stringify(n,null,2))}catch{}}function by(){return{totalSessions:0,totalMessages:0,totalTokensUsed:0,totalToolCalls:0,totalFilesModified:0,totalLinesWritten:0,totalBugsFixed:0,totalCommits:0,agentUsage:{},commandUsage:{},dailyActivity:{},streak:0,longestStreak:0,firstUsed:new Date().toISOString(),lastUsed:new Date().toISOString()}}function Ii(n){return n.totalSessions++,n.lastUsed=new Date().toISOString(),wy(n),n}function Di(n,e=0){n.totalMessages++,n.totalTokensUsed+=e;let t=Hs();return n.dailyActivity[t]||(n.dailyActivity[t]={messages:0,tokens:0,toolCalls:0,filesModified:0,linesWritten:0}),n.dailyActivity[t].messages++,n.dailyActivity[t].tokens+=e,n}function Li(n,e){n.totalToolCalls++,n.commandUsage[e]=(n.commandUsage[e]||0)+1;let t=Hs();return n.dailyActivity[t]||(n.dailyActivity[t]={messages:0,tokens:0,toolCalls:0,filesModified:0,linesWritten:0}),n.dailyActivity[t].toolCalls++,n}function Fi(n,e){return n.agentUsage[e]=(n.agentUsage[e]||0)+1,n}function vy(n,e=0){n.totalFilesModified++,n.totalLinesWritten+=e;let t=Hs();return n.dailyActivity[t]||(n.dailyActivity[t]={messages:0,tokens:0,toolCalls:0,filesModified:0,linesWritten:0}),n.dailyActivity[t].filesModified++,n.dailyActivity[t].linesWritten+=e,n}function wy(n){let e=Hs(),t=Hc(new Date(Date.now()-864e5));n.dailyActivity[t]||n.dailyActivity[e]?n.streak++:n.streak=1,n.streak>n.longestStreak&&(n.longestStreak=n.streak)}function Hs(){return Hc(new Date)}function Hc(n){return n.toISOString().split("T")[0]}function xy(n){let e=[];e.push(`
32
+ `)}var Fe,dn,xi,Ns,Fs,$i=L(()=>{"use strict";Fe=O(require("fs")),dn=O(require("path")),xi=O(require("os")),Ns=dn.join(xi.homedir(),".hablas","plugins"),Fs=dn.join(xi.homedir(),".hablas","plugins.json")});var Hc={};Ne(Hc,{renderDiagnostics:()=>Ti,runDiagnostics:()=>Ei});async function Ei(n){let e=[],t=process.version,s=parseInt(t.slice(1).split(".")[0],10);e.push({name:"Node.js",status:s>=20?"ok":s>=18?"warn":"error",message:s>=20?`${t} (recommended)`:s>=18?`${t} (works, but 20+ recommended)`:`${t} (too old, need 20+)`});let r=Fc.join(st.homedir(),".hablas");if(e.push({name:"Config directory",status:Ci.existsSync(r)?"ok":"warn",message:Ci.existsSync(r)?r:"Not created yet (will be created on first use)"}),n.provider==="ollama")try{let i=await fetch(`${n.ollamaHost}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let o=await i.json(),a=Array.isArray(o.models)?o.models.length:0;e.push({name:"Ollama",status:"ok",message:`Connected \u2014 ${a} models available`})}else e.push({name:"Ollama",status:"error",message:`HTTP ${i.status}`})}catch(i){let o=i instanceof Error?i.message:String(i);e.push({name:"Ollama",status:"error",message:o.includes("ECONNREFUSED")?"Not running \u2014 start with: ollama serve":`Connection failed: ${o}`})}else{let i=n.apiUrl||"unknown";try{let o=await fetch(`${i}/models`,{signal:AbortSignal.timeout(5e3),headers:{Authorization:"Bearer test"}});e.push({name:"API Provider",status:o.ok||o.status===401?"ok":"warn",message:`${i} \u2014 reachable`})}catch{e.push({name:"API Provider",status:"warn",message:`${i} \u2014 could not verify`})}}try{let i=st.homedir();if(process.platform!=="win32"){let a=(0,jc.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",u=a[4]||"?";e.push({name:"Disk space",status:parseInt(u)>90?"warn":"ok",message:`${l} available (${u} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:n.model?"ok":"warn",message:n.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${st.platform()} ${st.arch()} \u2014 ${st.cpus().length} cores, ${Math.round(st.totalmem()/1024/1024/1024)}GB RAM`}),e}function Ti(n){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},t={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},s="\x1B[0m",r="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of n){let u=`${t[l.status]}${e[l.status]}${s}`,d=l.name.padEnd(18);i.push(` ${u} ${d}${r}${l.message}${s}`)}let o=n.filter(l=>l.status==="error").length,a=n.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${t.error}${o} error(s) found \u2014 fix these for hablas to work properly${s}`):a>0?i.push(` ${t.warn}${a} warning(s) \u2014 hablas should work but check the items above${s}`):i.push(` ${t.ok}All checks passed \u2014 hablas is ready!${s}`),i.push(""),i.join(`
33
+ `)}var Ci,Fc,st,jc,Ri=L(()=>{"use strict";Ci=O(require("fs")),Fc=O(require("path")),st=O(require("os")),jc=require("child_process")});function Bc(){let n=[];for(let e of Se){let s=e.role==="hablas"?" \u2605":"";n.push(` @${e.name}${s} \u2014 ${e.title}`),n.push(` ${e.description}`)}return n.join(`
34
+ `)}var Se,Hs=L(()=>{"use strict";Se=[{role:"hablas",name:"Hablas",title:"Team Leader",description:"Software Engineer & Team Coordinator. Receives user requests, creates plans, distributes tasks, and compiles final responses.",expertise:["planning","coordination","architecture","code-review","decision-making"]},{role:"bob",name:"Bob",title:"Architect",description:"System Architect. Designs software architecture, database schemas, API structures, and system blueprints.",expertise:["system-design","architecture","database","api-design","scalability"]},{role:"alex",name:"Alex",title:"Engineer",description:"Full-Stack Engineer. Implements code, builds features, fixes bugs, handles DevOps and deployment.",expertise:["coding","implementation","debugging","devops","testing","deployment"]},{role:"david",name:"David",title:"Data Analyst",description:"Data & Research Specialist. Handles research, data analysis, documentation, and information gathering.",expertise:["research","data-analysis","documentation","ml","optimization"]},{role:"emma",name:"Emma",title:"Product Manager",description:"Product Manager. Analyzes user needs, creates PRDs, competitive analysis, market research, and requirement specifications.",expertise:["product-management","requirements","prd","market-research","competitive-analysis","user-stories"]}]});function Yt(){try{if(Et.existsSync(Bn)){let n=Et.readFileSync(Bn,"utf-8"),e=JSON.parse(n);return{...Uc,...e}}}catch{}return{...Uc}}function Oi(n){let e=Bs.dirname(Bn);Et.existsSync(e)||Et.mkdirSync(e,{recursive:!0}),Et.writeFileSync(Bn,JSON.stringify(n,null,2),"utf-8")}function Pi(){return Bn}var Et,Bs,qc,Bn,Uc,Mi=L(()=>{"use strict";Et=O(require("fs")),Bs=O(require("path")),qc=O(require("os")),Bn=Bs.join(qc.homedir(),".hablas","agents.json"),Uc={hablas:{model:"stepfun-ai/step-3.7-flash",temperature:.7},bob:{model:"stepfun-ai/step-3.7-flash",temperature:.4},alex:{model:"stepfun-ai/step-3.7-flash",temperature:.2},david:{model:"stepfun-ai/step-3.7-flash",temperature:.5},emma:{model:"stepfun-ai/step-3.7-flash",temperature:.6},gate:{model:"stepfun-ai/step-3.5-flash",temperature:.3}}});var Bi={};Ne(Bi,{formatStats:()=>$y,loadStats:()=>Un,saveStats:()=>fn,trackAgentUsage:()=>Hi,trackFileModified:()=>ky,trackMessage:()=>Fi,trackSession:()=>Ni,trackToolCall:()=>ji});function Un(){try{if(Tt.existsSync(Di))return JSON.parse(Tt.readFileSync(Di,"utf-8"))}catch{}return _y()}function fn(n){try{Tt.existsSync(Ii)||Tt.mkdirSync(Ii,{recursive:!0}),Tt.writeFileSync(Di,JSON.stringify(n,null,2))}catch{}}function _y(){return{totalSessions:0,totalMessages:0,totalTokensUsed:0,totalToolCalls:0,totalFilesModified:0,totalLinesWritten:0,totalBugsFixed:0,totalCommits:0,agentUsage:{},commandUsage:{},dailyActivity:{},streak:0,longestStreak:0,firstUsed:new Date().toISOString(),lastUsed:new Date().toISOString()}}function Ni(n){return n.totalSessions++,n.lastUsed=new Date().toISOString(),Ay(n),n}function Fi(n,e=0){n.totalMessages++,n.totalTokensUsed+=e;let t=Us();return n.dailyActivity[t]||(n.dailyActivity[t]={messages:0,tokens:0,toolCalls:0,filesModified:0,linesWritten:0}),n.dailyActivity[t].messages++,n.dailyActivity[t].tokens+=e,n}function ji(n,e){n.totalToolCalls++,n.commandUsage[e]=(n.commandUsage[e]||0)+1;let t=Us();return n.dailyActivity[t]||(n.dailyActivity[t]={messages:0,tokens:0,toolCalls:0,filesModified:0,linesWritten:0}),n.dailyActivity[t].toolCalls++,n}function Hi(n,e){return n.agentUsage[e]=(n.agentUsage[e]||0)+1,n}function ky(n,e=0){n.totalFilesModified++,n.totalLinesWritten+=e;let t=Us();return n.dailyActivity[t]||(n.dailyActivity[t]={messages:0,tokens:0,toolCalls:0,filesModified:0,linesWritten:0}),n.dailyActivity[t].filesModified++,n.dailyActivity[t].linesWritten+=e,n}function Ay(n){let e=Us(),t=Wc(new Date(Date.now()-864e5));n.dailyActivity[t]||n.dailyActivity[e]?n.streak++:n.streak=1,n.streak>n.longestStreak&&(n.longestStreak=n.streak)}function Us(){return Wc(new Date)}function Wc(n){return n.toISOString().split("T")[0]}function $y(n){let e=[];e.push(`
35
35
  \u{1F4CA} Developer Analytics`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Sessions: ${n.totalSessions}`),e.push(` Messages: ${n.totalMessages}`),e.push(` Tokens used: ${n.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${n.totalToolCalls}`),e.push(` Files modified: ${n.totalFilesModified}`),e.push(` Lines written: ${n.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${n.totalBugsFixed}`),e.push(` Commits: ${n.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${n.streak} days (best: ${n.longestStreak})`),e.push("");let t=Object.entries(n.agentUsage).sort((r,i)=>i[1]-r[1]).slice(0,5);if(t.length>0){e.push(" Top Agents:");for(let[r,i]of t)e.push(` @${r}: ${i} uses`);e.push("")}let s=Object.entries(n.commandUsage).sort((r,i)=>i[1]-r[1]).slice(0,5);if(s.length>0){e.push(" Top Commands:");for(let[r,i]of s)e.push(` ${r}: ${i} calls`)}return e.join(`
36
- `)}var Tt,Mi,jc,Oi,Pi,Un=L(()=>{"use strict";Tt=O(require("fs")),Mi=O(require("path")),jc=O(require("os")),Oi=Mi.join(jc.homedir(),".hablas"),Pi=Mi.join(Oi,"analytics.json")});var Uc={};Ne(Uc,{formatScanResults:()=>Hi,runSecurityScan:()=>ji});function Ay(n,e){let t=[],s=e.split(`
37
- `);for(let{pattern:r,name:i,severity:o}of Sy){r.lastIndex=0;let a;for(;(a=r.exec(e))!==null;){let u=e.substring(0,a.index).split(`
38
- `).length,d=s[u-1]||"";d.trim().startsWith("#")||d.trim().startsWith("//")||n.includes(".example")||n.includes(".sample")||t.push({severity:o,type:"secret",file:n,line:u,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return t}function $y(n,e){let t=[],s=e.split(`
39
- `),r=Yt.extname(n);return[".ts",".js",".tsx",".jsx"].includes(r)&&s.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&t.push({severity:"high",type:"code",file:n,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&t.push({severity:"medium",type:"code",file:n,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&t.push({severity:"high",type:"code",file:n,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),t}function Bc(n,e=[]){try{let t=Bs.readdirSync(n,{withFileTypes:!0});for(let s of t){if(_y.has(s.name))continue;let r=Yt.join(n,s.name);if(s.isDirectory())Bc(r,e);else if(s.isFile()){let i=Yt.extname(s.name);ky.has(i)||e.push(r)}}}catch{}return e}function ji(n){let e=Date.now(),t=Bc(n),s=[];for(let o of t)try{let a=Bs.readFileSync(o,"utf-8"),l=Yt.relative(n,o),u=Ay(l,a);s.push(...u);let d=$y(l,a);s.push(...d)}catch{}let r=Date.now()-e,i={critical:s.filter(o=>o.severity==="critical").length,high:s.filter(o=>o.severity==="high").length,medium:s.filter(o=>o.severity==="medium").length,low:s.filter(o=>o.severity==="low").length,info:s.filter(o=>o.severity==="info").length};return{issues:s,scannedFiles:t.length,duration:r,summary:i}}function Hi(n){let e=[];if(e.push(`
36
+ `)}var Tt,Li,Kc,Ii,Di,qn=L(()=>{"use strict";Tt=O(require("fs")),Li=O(require("path")),Kc=O(require("os")),Ii=Li.join(Kc.homedir(),".hablas"),Di=Li.join(Ii,"analytics.json")});var Vc={};Ne(Vc,{formatScanResults:()=>qi,runSecurityScan:()=>Ui});function Ry(n,e){let t=[],s=e.split(`
37
+ `);for(let{pattern:r,name:i,severity:o}of Cy){r.lastIndex=0;let a;for(;(a=r.exec(e))!==null;){let u=e.substring(0,a.index).split(`
38
+ `).length,d=s[u-1]||"";d.trim().startsWith("#")||d.trim().startsWith("//")||n.includes(".example")||n.includes(".sample")||t.push({severity:o,type:"secret",file:n,line:u,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return t}function Oy(n,e){let t=[],s=e.split(`
39
+ `),r=Jt.extname(n);return[".ts",".js",".tsx",".jsx"].includes(r)&&s.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&t.push({severity:"high",type:"code",file:n,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&t.push({severity:"medium",type:"code",file:n,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&t.push({severity:"high",type:"code",file:n,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),t}function Gc(n,e=[]){try{let t=qs.readdirSync(n,{withFileTypes:!0});for(let s of t){if(Ey.has(s.name))continue;let r=Jt.join(n,s.name);if(s.isDirectory())Gc(r,e);else if(s.isFile()){let i=Jt.extname(s.name);Ty.has(i)||e.push(r)}}}catch{}return e}function Ui(n){let e=Date.now(),t=Gc(n),s=[];for(let o of t)try{let a=qs.readFileSync(o,"utf-8"),l=Jt.relative(n,o),u=Ry(l,a);s.push(...u);let d=Oy(l,a);s.push(...d)}catch{}let r=Date.now()-e,i={critical:s.filter(o=>o.severity==="critical").length,high:s.filter(o=>o.severity==="high").length,medium:s.filter(o=>o.severity==="medium").length,low:s.filter(o=>o.severity==="low").length,info:s.filter(o=>o.severity==="info").length};return{issues:s,scannedFiles:t.length,duration:r,summary:i}}function qi(n){let e=[];if(e.push(`
40
40
  Security Scan Complete`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Files scanned: ${n.scannedFiles}`),e.push(` Duration: ${n.duration}ms`),e.push(""),n.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${n.issues.length}`),e.push(` Critical: ${n.summary.critical}`),e.push(` High: ${n.summary.high}`),e.push(` Medium: ${n.summary.medium}`),e.push(` Low: ${n.summary.low}`),e.push("");let t=n.issues.sort((s,r)=>{let i={critical:0,high:1,medium:2,low:3,info:4};return i[s.severity]-i[r.severity]}).slice(0,10);for(let s of t){let r=s.severity==="critical"?"\u{1F534}":s.severity==="high"?"\u{1F7E0}":s.severity==="medium"?"\u{1F7E1}":"\u{1F535}";e.push(` ${r} [${s.severity.toUpperCase()}] ${s.message}`),e.push(` File: ${s.file}${s.line?`:${s.line}`:""}`),e.push(` Fix: ${s.suggestion}`),e.push("")}}return e.join(`
41
- `)}var Bs,Yt,Sy,_y,ky,Bi=L(()=>{"use strict";Bs=O(require("fs")),Yt=O(require("path")),Sy=[{pattern:/(?:api[_-]?key|apikey)\s*[:=]\s*['"][a-zA-Z0-9_\-]{20,}['"]/gi,name:"API Key",severity:"critical"},{pattern:/(?:secret|password|passwd|pwd)\s*[:=]\s*['"][^'"]{8,}['"]/gi,name:"Secret/Password",severity:"critical"},{pattern:/(?:aws_access_key_id)\s*[:=]\s*['"]?AKIA[A-Z0-9]{16}['"]?/gi,name:"AWS Access Key",severity:"critical"},{pattern:/(?:aws_secret_access_key)\s*[:=]\s*['"]?[A-Za-z0-9/+=]{40}['"]?/gi,name:"AWS Secret Key",severity:"critical"},{pattern:/ghp_[A-Za-z0-9]{36}/g,name:"GitHub Token",severity:"critical"},{pattern:/gho_[A-Za-z0-9]{36}/g,name:"GitHub OAuth Token",severity:"critical"},{pattern:/sk-[A-Za-z0-9]{48}/g,name:"OpenAI API Key",severity:"critical"},{pattern:/xox[baprs]-[A-Za-z0-9\-]{10,}/g,name:"Slack Token",severity:"high"},{pattern:/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g,name:"Private Key",severity:"critical"},{pattern:/(?:mongodb(?:\+srv)?:\/\/)[^\s'"]+/g,name:"MongoDB Connection String",severity:"high"},{pattern:/(?:postgres|postgresql|mysql):\/\/[^\s'"]+/g,name:"Database URL",severity:"high"},{pattern:/(?:Bearer\s+)[A-Za-z0-9\-._~+/]+=*/g,name:"Bearer Token",severity:"medium"}],_y=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),ky=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"])});var qn={};Ne(qn,{formatGitStatus:()=>My,generateChangelogPrompt:()=>Py,generateCommitPrompt:()=>Ry,generatePRPrompt:()=>Oy,getDetailedDiff:()=>Ey,getGitStatus:()=>Ui,getRecentCommits:()=>Ty,getStagedDiff:()=>Cy});async function Ui(n){try{let{stdout:e}=await fn("git branch --show-current",{cwd:n}),{stdout:t}=await fn("git status --porcelain",{cwd:n}),s=e.trim(),r=[],i=[],o=[];for(let u of t.split(`
42
- `).filter(Boolean)){let d=u.substring(0,2),f=u.substring(3);(d.startsWith("A")||d.startsWith("M")||d.startsWith("R"))&&d[0]!==" "&&r.push(f),(d[1]==="M"||d[1]==="D")&&i.push(f),d==="??"&&o.push(f)}let a=0,l=0;try{let{stdout:u}=await fn("git rev-list --left-right --count HEAD...@{upstream}",{cwd:n}),d=u.trim().split(" ");a=parseInt(d[0])||0,l=parseInt(d[1])||0}catch{}return{branch:s,staged:r,modified:i,untracked:o,ahead:a,behind:l}}catch{return null}}async function Cy(n){try{let{stdout:e}=await fn("git diff --cached --stat",{cwd:n});return e.trim()}catch{return""}}async function Ey(n){try{let{stdout:e}=await fn("git diff --cached",{cwd:n,maxBuffer:1048576});return e.length>1e4?e.substring(0,1e4)+`
43
- ... (truncated)`:e.trim()}catch{return""}}async function Ty(n,e=20){try{let{stdout:t}=await fn(`git log --oneline --format="%H|%s|%an|%ai" -n ${e}`,{cwd:n});return t.trim().split(`
44
- `).filter(Boolean).map(s=>{let[r,i,o,a]=s.split("|");return{hash:r,message:i,author:o,date:a,files:[]}})}catch{return[]}}function Ry(n,e){return`Based on the following git diff, generate a concise, conventional commit message.
41
+ `)}var qs,Jt,Cy,Ey,Ty,Ki=L(()=>{"use strict";qs=O(require("fs")),Jt=O(require("path")),Cy=[{pattern:/(?:api[_-]?key|apikey)\s*[:=]\s*['"][a-zA-Z0-9_\-]{20,}['"]/gi,name:"API Key",severity:"critical"},{pattern:/(?:secret|password|passwd|pwd)\s*[:=]\s*['"][^'"]{8,}['"]/gi,name:"Secret/Password",severity:"critical"},{pattern:/(?:aws_access_key_id)\s*[:=]\s*['"]?AKIA[A-Z0-9]{16}['"]?/gi,name:"AWS Access Key",severity:"critical"},{pattern:/(?:aws_secret_access_key)\s*[:=]\s*['"]?[A-Za-z0-9/+=]{40}['"]?/gi,name:"AWS Secret Key",severity:"critical"},{pattern:/ghp_[A-Za-z0-9]{36}/g,name:"GitHub Token",severity:"critical"},{pattern:/gho_[A-Za-z0-9]{36}/g,name:"GitHub OAuth Token",severity:"critical"},{pattern:/sk-[A-Za-z0-9]{48}/g,name:"OpenAI API Key",severity:"critical"},{pattern:/xox[baprs]-[A-Za-z0-9\-]{10,}/g,name:"Slack Token",severity:"high"},{pattern:/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g,name:"Private Key",severity:"critical"},{pattern:/(?:mongodb(?:\+srv)?:\/\/)[^\s'"]+/g,name:"MongoDB Connection String",severity:"high"},{pattern:/(?:postgres|postgresql|mysql):\/\/[^\s'"]+/g,name:"Database URL",severity:"high"},{pattern:/(?:Bearer\s+)[A-Za-z0-9\-._~+/]+=*/g,name:"Bearer Token",severity:"medium"}],Ey=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Ty=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"])});var Kn={};Ne(Kn,{formatGitStatus:()=>Fy,generateChangelogPrompt:()=>Ny,generateCommitPrompt:()=>Dy,generatePRPrompt:()=>Ly,getDetailedDiff:()=>My,getGitStatus:()=>Wi,getRecentCommits:()=>Iy,getStagedDiff:()=>Py});async function Wi(n){try{let{stdout:e}=await pn("git branch --show-current",{cwd:n}),{stdout:t}=await pn("git status --porcelain",{cwd:n}),s=e.trim(),r=[],i=[],o=[];for(let u of t.split(`
42
+ `).filter(Boolean)){let d=u.substring(0,2),f=u.substring(3);(d.startsWith("A")||d.startsWith("M")||d.startsWith("R"))&&d[0]!==" "&&r.push(f),(d[1]==="M"||d[1]==="D")&&i.push(f),d==="??"&&o.push(f)}let a=0,l=0;try{let{stdout:u}=await pn("git rev-list --left-right --count HEAD...@{upstream}",{cwd:n}),d=u.trim().split(" ");a=parseInt(d[0])||0,l=parseInt(d[1])||0}catch{}return{branch:s,staged:r,modified:i,untracked:o,ahead:a,behind:l}}catch{return null}}async function Py(n){try{let{stdout:e}=await pn("git diff --cached --stat",{cwd:n});return e.trim()}catch{return""}}async function My(n){try{let{stdout:e}=await pn("git diff --cached",{cwd:n,maxBuffer:1048576});return e.length>1e4?e.substring(0,1e4)+`
43
+ ... (truncated)`:e.trim()}catch{return""}}async function Iy(n,e=20){try{let{stdout:t}=await pn(`git log --oneline --format="%H|%s|%an|%ai" -n ${e}`,{cwd:n});return t.trim().split(`
44
+ `).filter(Boolean).map(s=>{let[r,i,o,a]=s.split("|");return{hash:r,message:i,author:o,date:a,files:[]}})}catch{return[]}}function Dy(n,e){return`Based on the following git diff, generate a concise, conventional commit message.
45
45
 
46
46
  Rules:
47
47
  - Use conventional commits format: type(scope): description
@@ -55,7 +55,7 @@ Staged files: ${e.join(", ")}
55
55
  Diff:
56
56
  ${n}
57
57
 
58
- Generate ONLY the commit message, nothing else.`}function Oy(n,e,t){let s=n.map(r=>`- ${r.message}`).join(`
58
+ Generate ONLY the commit message, nothing else.`}function Ly(n,e,t){let s=n.map(r=>`- ${r.message}`).join(`
59
59
  `);return`Generate a comprehensive Pull Request description.
60
60
 
61
61
  Base branch: ${e}
@@ -77,7 +77,7 @@ Format:
77
77
  ## Notes
78
78
  (Any additional context)
79
79
 
80
- Generate ONLY the PR description in markdown.`}function Py(n,e){let t=n.map(s=>`- ${s.hash.substring(0,7)} ${s.message} (${s.author})`).join(`
80
+ Generate ONLY the PR description in markdown.`}function Ny(n,e){let t=n.map(s=>`- ${s.hash.substring(0,7)} ${s.message} (${s.author})`).join(`
81
81
  `);return`Generate a changelog entry for version ${e} from these commits.
82
82
 
83
83
  Commits:
@@ -98,9 +98,9 @@ Format:
98
98
  ### Removed
99
99
  - (removed features)
100
100
 
101
- Only include sections that have entries. Generate ONLY the changelog markdown.`}function My(n){let e=[];return e.push(` Branch: ${n.branch}`),(n.ahead>0||n.behind>0)&&e.push(` Sync: \u2191${n.ahead} \u2193${n.behind}`),n.staged.length>0&&e.push(` Staged: ${n.staged.length} file(s)`),n.modified.length>0&&e.push(` Modified: ${n.modified.length} file(s)`),n.untracked.length>0&&e.push(` Untracked: ${n.untracked.length} file(s)`),e.join(`
102
- `)}var qc,Kc,fn,pn=L(()=>{"use strict";qc=require("child_process"),Kc=require("util"),fn=(0,Kc.promisify)(qc.exec)});var Yc={};Ne(Yc,{detectFramework:()=>Wc,detectLanguage:()=>Vc,detectPackageManager:()=>Gc,formatWorkspaceInfo:()=>qi,getGitBranch:()=>zc,scanWorkspace:()=>Us});function Wc(n){let e=J.join(n,"package.json");if(V.existsSync(e))try{let t=JSON.parse(V.readFileSync(e,"utf-8")),s={...t.dependencies,...t.devDependencies};if(s.next)return"next";if(s.nuxt)return"nuxt";if(s["@angular/core"])return"angular";if(s.svelte||s["@sveltejs/kit"])return"svelte";if(s.vue)return"vue";if(s.react)return"react";if(s["@nestjs/core"])return"nest";if(s.fastify)return"fastify";if(s.express)return"express"}catch{}if(V.existsSync(J.join(n,"requirements.txt"))||V.existsSync(J.join(n,"pyproject.toml")))try{let t=V.existsSync(J.join(n,"requirements.txt"))?V.readFileSync(J.join(n,"requirements.txt"),"utf-8"):"";if(t.includes("django"))return"django";if(t.includes("flask"))return"flask";if(t.includes("fastapi"))return"fastapi"}catch{}if(V.existsSync(J.join(n,"Cargo.toml")))try{if(V.readFileSync(J.join(n,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(V.existsSync(J.join(n,"go.mod")))try{if(V.readFileSync(J.join(n,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Gc(n){return V.existsSync(J.join(n,"pnpm-lock.yaml"))?"pnpm":V.existsSync(J.join(n,"yarn.lock"))?"yarn":V.existsSync(J.join(n,"bun.lockb"))?"bun":V.existsSync(J.join(n,"package-lock.json"))?"npm":V.existsSync(J.join(n,"Cargo.toml"))?"cargo":V.existsSync(J.join(n,"go.mod"))?"go":V.existsSync(J.join(n,"requirements.txt"))||V.existsSync(J.join(n,"pyproject.toml"))?"pip":"unknown"}function Vc(n){return V.existsSync(J.join(n,"tsconfig.json"))?"TypeScript":V.existsSync(J.join(n,"package.json"))?"JavaScript":V.existsSync(J.join(n,"Cargo.toml"))?"Rust":V.existsSync(J.join(n,"go.mod"))?"Go":V.existsSync(J.join(n,"pyproject.toml"))||V.existsSync(J.join(n,"requirements.txt"))?"Python":"Unknown"}function zc(n){let e=J.join(n,".git","HEAD");if(!V.existsSync(e))return null;try{let t=V.readFileSync(e,"utf-8").trim();return t.startsWith("ref: refs/heads/")?t.replace("ref: refs/heads/",""):t.substring(0,8)}catch{return null}}function Us(n){let e=Wc(n),t=Gc(n),s=Vc(n),r=zc(n),i=V.existsSync(J.join(n,"Dockerfile"))||V.existsSync(J.join(n,"docker-compose.yml"))||V.existsSync(J.join(n,"docker-compose.yaml")),o=V.existsSync(J.join(n,".github","workflows"))||V.existsSync(J.join(n,".gitlab-ci.yml"))||V.existsSync(J.join(n,"Jenkinsfile")),a=V.existsSync(J.join(n,"__tests__"))||V.existsSync(J.join(n,"tests"))||V.existsSync(J.join(n,"test"))||V.existsSync(J.join(n,"spec")),l=V.existsSync(J.join(n,".git")),u=[],d=[".env",".env.local",".env.development",".env.production",".env.example"];for(let g of d)V.existsSync(J.join(n,g))&&u.push(g);let f=[],h=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let g of h)V.existsSync(J.join(n,g))&&f.push(g);let m=[],p=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let g of p)V.existsSync(J.join(n,g))&&m.push(g);return{rootPath:n,framework:e,packageManager:t,language:s,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:r,envFiles:u,configFiles:f,entryPoints:m}}function qi(n){let e=[` Project: ${J.basename(n.rootPath)}`,` Framework: ${n.framework}`,` Language: ${n.language}`,` Package: ${n.packageManager}`,` Git: ${n.hasGit?`\u2713 (${n.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${n.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${n.hasCICD?"\u2713":"\u2717"}`,` Tests: ${n.hasTests?"\u2713":"\u2717"}`];return n.envFiles.length>0&&e.push(` Env files: ${n.envFiles.join(", ")}`),e.join(`
103
- `)}var V,J,Ki=L(()=>{"use strict";V=O(require("fs")),J=O(require("path"))});function Jc(){return`
101
+ Only include sections that have entries. Generate ONLY the changelog markdown.`}function Fy(n){let e=[];return e.push(` Branch: ${n.branch}`),(n.ahead>0||n.behind>0)&&e.push(` Sync: \u2191${n.ahead} \u2193${n.behind}`),n.staged.length>0&&e.push(` Staged: ${n.staged.length} file(s)`),n.modified.length>0&&e.push(` Modified: ${n.modified.length} file(s)`),n.untracked.length>0&&e.push(` Untracked: ${n.untracked.length} file(s)`),e.join(`
102
+ `)}var zc,Yc,pn,hn=L(()=>{"use strict";zc=require("child_process"),Yc=require("util"),pn=(0,Yc.promisify)(zc.exec)});var eu={};Ne(eu,{detectFramework:()=>Jc,detectLanguage:()=>Qc,detectPackageManager:()=>Xc,formatWorkspaceInfo:()=>Gi,getGitBranch:()=>Zc,scanWorkspace:()=>Ks});function Jc(n){let e=J.join(n,"package.json");if(V.existsSync(e))try{let t=JSON.parse(V.readFileSync(e,"utf-8")),s={...t.dependencies,...t.devDependencies};if(s.next)return"next";if(s.nuxt)return"nuxt";if(s["@angular/core"])return"angular";if(s.svelte||s["@sveltejs/kit"])return"svelte";if(s.vue)return"vue";if(s.react)return"react";if(s["@nestjs/core"])return"nest";if(s.fastify)return"fastify";if(s.express)return"express"}catch{}if(V.existsSync(J.join(n,"requirements.txt"))||V.existsSync(J.join(n,"pyproject.toml")))try{let t=V.existsSync(J.join(n,"requirements.txt"))?V.readFileSync(J.join(n,"requirements.txt"),"utf-8"):"";if(t.includes("django"))return"django";if(t.includes("flask"))return"flask";if(t.includes("fastapi"))return"fastapi"}catch{}if(V.existsSync(J.join(n,"Cargo.toml")))try{if(V.readFileSync(J.join(n,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(V.existsSync(J.join(n,"go.mod")))try{if(V.readFileSync(J.join(n,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Xc(n){return V.existsSync(J.join(n,"pnpm-lock.yaml"))?"pnpm":V.existsSync(J.join(n,"yarn.lock"))?"yarn":V.existsSync(J.join(n,"bun.lockb"))?"bun":V.existsSync(J.join(n,"package-lock.json"))?"npm":V.existsSync(J.join(n,"Cargo.toml"))?"cargo":V.existsSync(J.join(n,"go.mod"))?"go":V.existsSync(J.join(n,"requirements.txt"))||V.existsSync(J.join(n,"pyproject.toml"))?"pip":"unknown"}function Qc(n){return V.existsSync(J.join(n,"tsconfig.json"))?"TypeScript":V.existsSync(J.join(n,"package.json"))?"JavaScript":V.existsSync(J.join(n,"Cargo.toml"))?"Rust":V.existsSync(J.join(n,"go.mod"))?"Go":V.existsSync(J.join(n,"pyproject.toml"))||V.existsSync(J.join(n,"requirements.txt"))?"Python":"Unknown"}function Zc(n){let e=J.join(n,".git","HEAD");if(!V.existsSync(e))return null;try{let t=V.readFileSync(e,"utf-8").trim();return t.startsWith("ref: refs/heads/")?t.replace("ref: refs/heads/",""):t.substring(0,8)}catch{return null}}function Ks(n){let e=Jc(n),t=Xc(n),s=Qc(n),r=Zc(n),i=V.existsSync(J.join(n,"Dockerfile"))||V.existsSync(J.join(n,"docker-compose.yml"))||V.existsSync(J.join(n,"docker-compose.yaml")),o=V.existsSync(J.join(n,".github","workflows"))||V.existsSync(J.join(n,".gitlab-ci.yml"))||V.existsSync(J.join(n,"Jenkinsfile")),a=V.existsSync(J.join(n,"__tests__"))||V.existsSync(J.join(n,"tests"))||V.existsSync(J.join(n,"test"))||V.existsSync(J.join(n,"spec")),l=V.existsSync(J.join(n,".git")),u=[],d=[".env",".env.local",".env.development",".env.production",".env.example"];for(let g of d)V.existsSync(J.join(n,g))&&u.push(g);let f=[],h=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let g of h)V.existsSync(J.join(n,g))&&f.push(g);let m=[],p=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let g of p)V.existsSync(J.join(n,g))&&m.push(g);return{rootPath:n,framework:e,packageManager:t,language:s,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:r,envFiles:u,configFiles:f,entryPoints:m}}function Gi(n){let e=[` Project: ${J.basename(n.rootPath)}`,` Framework: ${n.framework}`,` Language: ${n.language}`,` Package: ${n.packageManager}`,` Git: ${n.hasGit?`\u2713 (${n.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${n.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${n.hasCICD?"\u2713":"\u2717"}`,` Tests: ${n.hasTests?"\u2713":"\u2717"}`];return n.envFiles.length>0&&e.push(` Env files: ${n.envFiles.join(", ")}`),e.join(`
103
+ `)}var V,J,Vi=L(()=>{"use strict";V=O(require("fs")),J=O(require("path"))});function tu(){return`
104
104
  ## Available Tools (XML Format)
105
105
 
106
106
  You can use tools by outputting XML tags in your response. The system will parse and execute them.
@@ -155,39 +155,39 @@ export function hello() {
155
155
  3. Wait for tool results before using dependent tools.
156
156
  4. Use exact file paths relative to the working directory.
157
157
  5. Do NOT wrap tool tags in <tool_call > tags \u2014 use them directly.
158
- `.trim()}var Xc=L(()=>{"use strict"});function Iy(){try{let n=eu.resolve(__dirname,"..","..","package.json");return JSON.parse(Zc.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function fe(n,e){return nu||!hn?n:`${e}${n}\x1B[0m`}function Dy(n){let e=He();if(!n)return c.border("\u2500".repeat(e));let t=n.replace(/\x1b\[[0-9;]*m/g,""),s=Math.max(0,e-t.length-2),r=Math.floor(s/2),i=s-r;return c.border("\u2500".repeat(r))+" "+n+" "+c.border("\u2500".repeat(i))}function Ly(n,e=2){let t=He()-e;if(t<=0)return" ".repeat(e)+n;let s=n.split(" "),r=[],i="";for(let o of s)(i+" "+o).trim().length>t&&i?(r.push(i.trim()),i=o):i+=(i?" ":"")+o;return i&&r.push(i.trim()),r.map(o=>" ".repeat(e)+o).join(`
159
- `)}function Fy(n){let e=Math.max(...n.map(([t])=>t.length));return n.map(([t,s])=>` ${c.muted(t.padEnd(e))} ${s}`).join(`
160
- `)}function Ny(n){if(nu||!hn)return n;let e=["\x1B[38;5;111m","\x1B[38;5;111m","\x1B[38;5;141m","\x1B[38;5;141m","\x1B[38;5;117m","\x1B[38;5;117m"],t="";for(let s=0;s<n.length;s++){let r=Math.floor(s/n.length*e.length);t+=e[r]+n[s]}return t+"\x1B[0m"}function ru(n,e){let t=He(),s=e?e.replace(Vi.homedir(),"~"):"",r=c.border("\u2554"+"\u2550".repeat(t-2)+"\u2557"),i=c.border("\u2560"+"\u2550".repeat(t-2)+"\u2563"),o=c.border("\u255A"+"\u2550".repeat(t-2)+"\u255D"),a="H A B L A S A I",l="EXECUTIVE SYSTEM COORDINATOR",u="developed by abdulmoin hablas",d=Math.max(0,Math.floor((t-2-a.length)/2)),f=c.border("\u2551")+" ".repeat(d)+c.strong(a)+" ".repeat(t-2-a.length-d)+c.border("\u2551"),h=Math.max(0,Math.floor((t-2-l.length)/2)),m=c.border("\u2551")+" ".repeat(h)+c.secondary(l)+" ".repeat(t-2-l.length-h)+c.border("\u2551"),p=Math.max(0,Math.floor((t-2-u.length)/2)),g=c.border("\u2551")+" ".repeat(p)+c.muted(u)+" ".repeat(t-2-u.length-p)+c.border("\u2551"),x=c.muted(`SYSTEM VERSION: v${tu}`),w=c.warning(`CORE MODEL: ${n}`);return["",r,f,m,u?g:"",i,` ${c.muted("\u25B8")} ${x}`,` ${c.muted("\u25B8")} ${w}`,s?` ${c.muted("\u25B8")} ${c.muted(`WORKSPACE: ${s}`)}`:"",` ${c.chrome("\u251C"+"\u2500".repeat(t-2)+"\u2524")}`,` ${c.muted(" \u203A")} ${c.secondary("Type naturally to get started")}`,` ${c.muted(" \u203A")} ${c.secondary("/help for commands \xB7 Ctrl+C to cancel \xB7 Ctrl+C\xD72 to exit")}`,o,""].filter(Boolean).join(`
161
- `)}function iu(){let n=He();return[` ${c.border("\u2554"+"\u2550".repeat(n-4)+"\u2557")}`,` ${c.border("\u2551")} ${c.leader("\u2605 Hablas")} ${c.muted("Leader")} ${c.border("\u2551")} ${c.product("\u25C6 Emma")} ${c.muted("Product")} ${c.border("\u2551")} ${c.architect("\u25C6 Bob")} ${c.muted("Architect")} ${c.border("\u2551")} ${c.engineer("\u25C6 Alex")} ${c.muted("Engineer")} ${c.border("\u2551")} ${c.analyst("\u25C6 David")} ${c.muted("Analyst")} ${c.border("\u2551")}`,` ${c.border("\u255A"+"\u2550".repeat(n-4)+"\u255D")}`].join(`
162
- `)}function mn(n,e){return`
163
- ${(n==="Hablas"?c.leader:n==="Bob"?c.architect:n==="Alex"?c.engineer:n==="David"?c.analyst:n==="Emma"?c.product:c.primary)("\u25C6")} ${c.strong(n)} ${c.muted(`[${e.toUpperCase()}]`)}`}function ou(n,e,t,s){let r=n==="Hablas"?c.leader:n==="Bob"?c.architect:n==="Alex"?c.engineer:n==="David"?c.analyst:n==="Emma"?c.product:c.primary,i=e==="Hablas"?c.leader:e==="Bob"?c.architect:e==="Alex"?c.engineer:e==="David"?c.analyst:e==="Emma"?c.product:c.primary,o=[];if(o.push(""),o.push(` ${r("\u2605")} ${r(n)} ${c.muted("\u2192")} ${c.strong("Delegating to")} ${i(`@${e}`)} ${c.muted(`(${t})`)}`),s){let a=s.length>80?s.slice(0,80)+"...":s;o.push(` ${c.muted(" \u2517")} ${c.secondary(a)}`)}return o.push(""),o.join(`
164
- `)}function au(){let n=He(),t=[` ${c.accent("\u2726")} ${c.strong("Welcome to hablas")}`,"",` ${c.muted("Try:")} ${c.highlight('"read package.json and list deps"')}`,` ${c.muted("Or:")} ${c.highlight('"create a new component for user auth"')}`,"",` ${c.primary("/tree")} ${c.muted("\u2014 see project structure")}`,` ${c.primary("/model")} ${c.muted("\u2014 switch AI model")}`,` ${c.primary("/models")} ${c.muted("\u2014 browse all available models")}`,` ${c.primary("/team")} ${c.muted("\u2014 see your agent team")}`,` ${c.primary("/about")} ${c.muted("\u2014 developer info")}`,"",` ${c.muted("All file changes are backed up automatically.")}`].map(s=>{let r=s.replace(/\x1b\[[0-9;]*m/g,""),i=Math.max(0,n-8-r.length);return` ${c.border("\u2502")} ${s}${" ".repeat(i)} ${c.border("\u2502")}`});return["",` ${c.border("\u250C"+"\u2500".repeat(n-6)+"\u2510")}`,...t,` ${c.border("\u2514"+"\u2500".repeat(n-6)+"\u2518")}`,""].join(`
165
- `)}function lu(){let n=He();return["",c.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E"),` ${c.strong("Abdulmoin Hablas")} ${c.muted("\u2014 Full-Stack Developer")}`,c.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),"",` ${c.accent("\u25C6")} ${c.primary("Portfolio")} ${c.muted("https://portfolio-monopoly63s-projects.vercel.app/")}`,` ${c.accent("\u25C6")} ${c.primary("GitHub")} ${c.muted("https://github.com/Monopoly63?tab=repositories")}`,` ${c.accent("\u25C6")} ${c.primary("Telegram")} ${c.muted("https://t.me/Hablas_Trade")}`,` ${c.accent("\u25C6")} ${c.primary("WhatsApp")} ${c.muted("https://wa.me/13232128875")}`,` ${c.accent("\u25C6")} ${c.primary("Instagram")} ${c.muted("https://www.instagram.com/li0vy_")}`,"",c.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),` ${c.strong("Projects")}`,"",` ${c.muted("\u25B8")} AI Search Engine ${c.muted("\u2192")} ${c.highlight("https://ai-search-engine-ashy.vercel.app/")}`,` ${c.muted("\u25B8")} Trade Tracker ${c.muted("\u2192")} ${c.highlight("https://trade-tracker-monopoly63s-projects.vercel.app/")}`,` ${c.muted("\u25B8")} Tree Algo Lab ${c.muted("\u2192")} ${c.highlight("https://tree-algorithms-lab.vercel.app/")}`,"",c.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F"),""].join(`
166
- `)}function cu(){return["",` ${Ny("\u25C6 hablas")} ${c.success(`v${tu}`)}`,"",` ${c.muted("Runtime")} ${c.secondary(`Node.js ${process.version}`)}`,` ${c.muted("Platform")} ${c.secondary(`${process.platform} ${process.arch}`)}`,` ${c.muted("Author")} ${c.secondary("Abdulmoin Hablas")}`,` ${c.muted("License")} ${c.secondary("MIT")}`,""].join(`
167
- `)}function Qc(n,e){let t=Math.min(He()-8,60),s=e?` ${c.accent(e)} `:"",r=`${c.error("\u25CF")} ${c.warning("\u25CF")} ${c.success("\u25CF")}`,i=` ${c.chrome("\u250C"+"\u2500".repeat(4))} ${r} ${c.chrome("\u2500".repeat(Math.max(0,t-10-(e?e.length+2:0))))}${s}`,o=String(n.length).length,a=n.map((u,d)=>{let f=c.lineNum(String(d+1).padStart(o)+" \u2502 "),h=c.codeBlock(u);return` ${c.chrome("\u2502")} ${f}${h}`}),l=` ${c.chrome("\u2514"+"\u2500".repeat(t))}`;return[i,...a,l]}function gn(n){let e=n.split(`
168
- `),t=[],s=!1,r="",i=[];for(let o of e){if(o.trimStart().startsWith("```")){s?(t.push(...Qc(i,r)),s=!1,i=[]):(s=!0,r=o.trimStart().slice(3).trim(),i=[]);continue}if(s){i.push(o);continue}if(/^#{1,3}\s/.test(o)){let l=o.replace(/^#+\s/,"");t.push(""),t.push(` ${c.strong(c.primary(l))}`);continue}if(/^[-*]\s/.test(o.trim())){let l=o.trim().slice(2),u=Wi(l);t.push(` ${c.accent("\u25B8")} ${u}`);continue}if(/^\d+\.\s/.test(o.trim())){let l=o.trim().match(/^(\d+)\.\s(.+)/);if(l){t.push(` ${c.muted(l[1]+".")} ${Wi(l[2])}`);continue}}if(!o.trim()){t.push("");continue}let a=Ly(Wi(o),2);t.push(...a.split(`
169
- `))}return s&&i.length>0&&t.push(...Qc(i,r)),`
158
+ `.trim()}var nu=L(()=>{"use strict"});function jy(){try{let n=iu.resolve(__dirname,"..","..","package.json");return JSON.parse(ru.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function fe(n,e){return au||!mn?n:`${e}${n}\x1B[0m`}function Hy(n){let e=je();if(!n)return c.border("\u2500".repeat(e));let t=n.replace(/\x1b\[[0-9;]*m/g,""),s=Math.max(0,e-t.length-2),r=Math.floor(s/2),i=s-r;return c.border("\u2500".repeat(r))+" "+n+" "+c.border("\u2500".repeat(i))}function By(n,e=2){let t=je()-e;if(t<=0)return" ".repeat(e)+n;let s=n.split(" "),r=[],i="";for(let o of s)(i+" "+o).trim().length>t&&i?(r.push(i.trim()),i=o):i+=(i?" ":"")+o;return i&&r.push(i.trim()),r.map(o=>" ".repeat(e)+o).join(`
159
+ `)}function Uy(n){let e=Math.max(...n.map(([t])=>t.length));return n.map(([t,s])=>` ${c.muted(t.padEnd(e))} ${s}`).join(`
160
+ `)}function qy(n){if(au||!mn)return n;let e=["\x1B[38;5;111m","\x1B[38;5;111m","\x1B[38;5;141m","\x1B[38;5;141m","\x1B[38;5;117m","\x1B[38;5;117m"],t="";for(let s=0;s<n.length;s++){let r=Math.floor(s/n.length*e.length);t+=e[r]+n[s]}return t+"\x1B[0m"}function cu(n,e){let t=je(),s=e?e.replace(Ji.homedir(),"~"):"",r=c.border("\u2554"+"\u2550".repeat(t-2)+"\u2557"),i=c.border("\u2560"+"\u2550".repeat(t-2)+"\u2563"),o=c.border("\u255A"+"\u2550".repeat(t-2)+"\u255D"),a="H A B L A S A I",l="EXECUTIVE SYSTEM COORDINATOR",u="developed by abdulmoin hablas",d=Math.max(0,Math.floor((t-2-a.length)/2)),f=c.border("\u2551")+" ".repeat(d)+c.strong(a)+" ".repeat(t-2-a.length-d)+c.border("\u2551"),h=Math.max(0,Math.floor((t-2-l.length)/2)),m=c.border("\u2551")+" ".repeat(h)+c.secondary(l)+" ".repeat(t-2-l.length-h)+c.border("\u2551"),p=Math.max(0,Math.floor((t-2-u.length)/2)),g=c.border("\u2551")+" ".repeat(p)+c.muted(u)+" ".repeat(t-2-u.length-p)+c.border("\u2551"),x=c.muted(`SYSTEM VERSION: v${ou}`),w=c.warning(`CORE MODEL: ${n}`);return["",r,f,m,u?g:"",i,` ${c.muted("\u25B8")} ${x}`,` ${c.muted("\u25B8")} ${w}`,s?` ${c.muted("\u25B8")} ${c.muted(`WORKSPACE: ${s}`)}`:"",` ${c.chrome("\u251C"+"\u2500".repeat(t-2)+"\u2524")}`,` ${c.muted(" \u203A")} ${c.secondary("Type naturally to get started")}`,` ${c.muted(" \u203A")} ${c.secondary("/help for commands \xB7 Ctrl+C to cancel \xB7 Ctrl+C\xD72 to exit")}`,o,""].filter(Boolean).join(`
161
+ `)}function uu(){let n=je();return[` ${c.border("\u2554"+"\u2550".repeat(n-4)+"\u2557")}`,` ${c.border("\u2551")} ${c.leader("\u2605 Hablas")} ${c.muted("Leader")} ${c.border("\u2551")} ${c.product("\u25C6 Emma")} ${c.muted("Product")} ${c.border("\u2551")} ${c.architect("\u25C6 Bob")} ${c.muted("Architect")} ${c.border("\u2551")} ${c.engineer("\u25C6 Alex")} ${c.muted("Engineer")} ${c.border("\u2551")} ${c.analyst("\u25C6 David")} ${c.muted("Analyst")} ${c.border("\u2551")}`,` ${c.border("\u255A"+"\u2550".repeat(n-4)+"\u255D")}`].join(`
162
+ `)}function gn(n,e){return`
163
+ ${(n==="Hablas"?c.leader:n==="Bob"?c.architect:n==="Alex"?c.engineer:n==="David"?c.analyst:n==="Emma"?c.product:c.primary)("\u25C6")} ${c.strong(n)} ${c.muted(`[${e.toUpperCase()}]`)}`}function du(n,e,t,s){let r=n==="Hablas"?c.leader:n==="Bob"?c.architect:n==="Alex"?c.engineer:n==="David"?c.analyst:n==="Emma"?c.product:c.primary,i=e==="Hablas"?c.leader:e==="Bob"?c.architect:e==="Alex"?c.engineer:e==="David"?c.analyst:e==="Emma"?c.product:c.primary,o=[];if(o.push(""),o.push(` ${r("\u2605")} ${r(n)} ${c.muted("\u2192")} ${c.strong("Delegating to")} ${i(`@${e}`)} ${c.muted(`(${t})`)}`),s){let a=s.length>80?s.slice(0,80)+"...":s;o.push(` ${c.muted(" \u2517")} ${c.secondary(a)}`)}return o.push(""),o.join(`
164
+ `)}function fu(){let n=je(),t=[` ${c.accent("\u2726")} ${c.strong("Welcome to hablas")}`,"",` ${c.muted("Try:")} ${c.highlight('"read package.json and list deps"')}`,` ${c.muted("Or:")} ${c.highlight('"create a new component for user auth"')}`,"",` ${c.primary("/tree")} ${c.muted("\u2014 see project structure")}`,` ${c.primary("/model")} ${c.muted("\u2014 switch AI model")}`,` ${c.primary("/models")} ${c.muted("\u2014 browse all available models")}`,` ${c.primary("/team")} ${c.muted("\u2014 see your agent team")}`,` ${c.primary("/about")} ${c.muted("\u2014 developer info")}`,"",` ${c.muted("All file changes are backed up automatically.")}`].map(s=>{let r=s.replace(/\x1b\[[0-9;]*m/g,""),i=Math.max(0,n-8-r.length);return` ${c.border("\u2502")} ${s}${" ".repeat(i)} ${c.border("\u2502")}`});return["",` ${c.border("\u250C"+"\u2500".repeat(n-6)+"\u2510")}`,...t,` ${c.border("\u2514"+"\u2500".repeat(n-6)+"\u2518")}`,""].join(`
165
+ `)}function pu(){let n=je();return["",c.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E"),` ${c.strong("Abdulmoin Hablas")} ${c.muted("\u2014 Full-Stack Developer")}`,c.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),"",` ${c.accent("\u25C6")} ${c.primary("Portfolio")} ${c.muted("https://portfolio-monopoly63s-projects.vercel.app/")}`,` ${c.accent("\u25C6")} ${c.primary("GitHub")} ${c.muted("https://github.com/Monopoly63?tab=repositories")}`,` ${c.accent("\u25C6")} ${c.primary("Telegram")} ${c.muted("https://t.me/Hablas_Trade")}`,` ${c.accent("\u25C6")} ${c.primary("WhatsApp")} ${c.muted("https://wa.me/13232128875")}`,` ${c.accent("\u25C6")} ${c.primary("Instagram")} ${c.muted("https://www.instagram.com/li0vy_")}`,"",c.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),` ${c.strong("Projects")}`,"",` ${c.muted("\u25B8")} AI Search Engine ${c.muted("\u2192")} ${c.highlight("https://ai-search-engine-ashy.vercel.app/")}`,` ${c.muted("\u25B8")} Trade Tracker ${c.muted("\u2192")} ${c.highlight("https://trade-tracker-monopoly63s-projects.vercel.app/")}`,` ${c.muted("\u25B8")} Tree Algo Lab ${c.muted("\u2192")} ${c.highlight("https://tree-algorithms-lab.vercel.app/")}`,"",c.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F"),""].join(`
166
+ `)}function hu(){return["",` ${qy("\u25C6 hablas")} ${c.success(`v${ou}`)}`,"",` ${c.muted("Runtime")} ${c.secondary(`Node.js ${process.version}`)}`,` ${c.muted("Platform")} ${c.secondary(`${process.platform} ${process.arch}`)}`,` ${c.muted("Author")} ${c.secondary("Abdulmoin Hablas")}`,` ${c.muted("License")} ${c.secondary("MIT")}`,""].join(`
167
+ `)}function su(n,e){let t=Math.min(je()-8,60),s=e?` ${c.accent(e)} `:"",r=`${c.error("\u25CF")} ${c.warning("\u25CF")} ${c.success("\u25CF")}`,i=` ${c.chrome("\u250C"+"\u2500".repeat(4))} ${r} ${c.chrome("\u2500".repeat(Math.max(0,t-10-(e?e.length+2:0))))}${s}`,o=String(n.length).length,a=n.map((u,d)=>{let f=c.lineNum(String(d+1).padStart(o)+" \u2502 "),h=c.codeBlock(u);return` ${c.chrome("\u2502")} ${f}${h}`}),l=` ${c.chrome("\u2514"+"\u2500".repeat(t))}`;return[i,...a,l]}function yn(n){let e=n.split(`
168
+ `),t=[],s=!1,r="",i=[];for(let o of e){if(o.trimStart().startsWith("```")){s?(t.push(...su(i,r)),s=!1,i=[]):(s=!0,r=o.trimStart().slice(3).trim(),i=[]);continue}if(s){i.push(o);continue}if(/^#{1,3}\s/.test(o)){let l=o.replace(/^#+\s/,"");t.push(""),t.push(` ${c.strong(c.primary(l))}`);continue}if(/^[-*]\s/.test(o.trim())){let l=o.trim().slice(2),u=zi(l);t.push(` ${c.accent("\u25B8")} ${u}`);continue}if(/^\d+\.\s/.test(o.trim())){let l=o.trim().match(/^(\d+)\.\s(.+)/);if(l){t.push(` ${c.muted(l[1]+".")} ${zi(l[2])}`);continue}}if(!o.trim()){t.push("");continue}let a=By(zi(o),2);t.push(...a.split(`
169
+ `))}return s&&i.length>0&&t.push(...su(i,r)),`
170
170
  `+t.join(`
171
171
  `)+`
172
- `}function Wi(n){let e=n.replace(/`([^`]+)`/g,(t,s)=>c.highlight(s));return e=e.replace(/\*\*([^*]+)\*\*/g,(t,s)=>c.strong(c.primary(s))),e=e.replace(/\*([^*]+)\*/g,(t,s)=>`\x1B[3m${s}\x1B[23m`),e}function uu(n,e){let t=He(),s=` [TOOL: ${n.replace(/_/g," ").toUpperCase()}] `,r=` ${c.border("\u250C\u2500\u2500")}${c.accent(s)}${c.border("\u2500".repeat(Math.max(0,t-s.length-6)))}`,i=` ${c.border("\u2502")} ${c.secondary(e)}`,o=i.replace(/\x1b\[[0-9;]*m/g,""),a=Math.max(0,t-8-o.length);return`
172
+ `}function zi(n){let e=n.replace(/`([^`]+)`/g,(t,s)=>c.highlight(s));return e=e.replace(/\*\*([^*]+)\*\*/g,(t,s)=>c.strong(c.primary(s))),e=e.replace(/\*([^*]+)\*/g,(t,s)=>`\x1B[3m${s}\x1B[23m`),e}function mu(n,e){let t=je(),s=` [TOOL: ${n.replace(/_/g," ").toUpperCase()}] `,r=` ${c.border("\u250C\u2500\u2500")}${c.accent(s)}${c.border("\u2500".repeat(Math.max(0,t-s.length-6)))}`,i=` ${c.border("\u2502")} ${c.secondary(e)}`,o=i.replace(/\x1b\[[0-9;]*m/g,""),a=Math.max(0,t-8-o.length);return`
173
173
  ${r}
174
- ${i}${" ".repeat(a)} ${c.border("\u2502")}`}function du(n,e,t){let s=He(),r=c.muted(`${t}ms`),i="";if(n){let u=e.split(`
174
+ ${i}${" ".repeat(a)} ${c.border("\u2502")}`}function gu(n,e,t){let s=je(),r=c.muted(`${t}ms`),i="";if(n){let u=e.split(`
175
175
  `).filter(Boolean),d=u.length;if(d>5){let f=u[0].slice(0,s-30).trim();i=` ${c.border("\u2502")} ${c.success("\u2713")} ${c.muted(`${d} lines`)} ${c.secondary(f+"\u2026")} ${r}`}else{let f=u.join(" \xB7 ").slice(0,s-24);i=` ${c.border("\u2502")} ${c.success("\u2713")} ${c.muted(f)} ${r}`}}else{let u=e.split(`
176
176
  `)[0].slice(0,s-24);i=` ${c.border("\u2502")} ${c.error("\u2717")} ${c.error(u)} ${r}`}let o=i.replace(/\x1b\[[0-9;]*m/g,""),a=Math.max(0,s-8-o.length),l=` ${c.border("\u2514"+"\u2500".repeat(s-6)+"\u2518")}`;return`${i}${" ".repeat(a)} ${c.border("\u2502")}
177
177
  ${l}
178
- `}function zi(n){let e=n.split(`
178
+ `}function Xi(n){let e=n.split(`
179
179
  `),t=[];for(let s of e)s.startsWith("+++")||s.startsWith("---")?t.push(` ${c.muted(s)}`):s.startsWith("+")?t.push(` ${c.added(s)}`):s.startsWith("-")?t.push(` ${c.removed(s)}`):s.startsWith("@@")?t.push(` ${c.hunk(s)}`):s.trim()&&t.push(` ${c.muted(s)}`);return t.join(`
180
- `)}function fu(n){let e=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"}),t=`${c.accent("\u25C6")} ${c.strong(c.primary(`Turn #${n}`))} ${c.muted(`\xB7 ${e} \xB7`)}`;return`
181
- `+Dy(t)+`
182
- `}function ke(n){return` ${c.error("\u2717")} ${n}`}function Be(n,e){return` ${c.error("\u2717")} ${n}
183
- ${c.warning("\u2192")} ${c.muted(e)}`}function z(n){return` ${c.success("\u2713")} ${n}`}function pe(n){return` ${c.muted(n)}`}function j(n){return` ${c.warning("\u26A0")} ${n}`}function jy(n,e){let s=Math.round(Math.min(n,e)/Math.max(e,1)*16),r=e>0?n/e:0;return(r>.85?c.error:r>.6?c.warning:c.success)("\u2588".repeat(s))+c.muted("\u2591".repeat(16-s))}function pu(n){let e=He(),t=n.connected?c.success("\u25CF connected"):c.error("\u25CB offline"),s=jy(n.cacheTokens,n.budgetTokens),r=[["model",c.highlight(n.model)],["mindset",c.accent(n.mindset||"coder")],["host",c.muted(n.host)],["directory",c.muted(n.directory.replace(Vi.homedir(),"~"))],["context",`${s} ${c.muted(`${n.cacheFiles} files \xB7 ${n.cacheTokens}/${n.budgetTokens} tokens`)}`],["turns",c.muted(String(n.turnCount))],["status",t]];return`
180
+ `)}function yu(n){let e=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"}),t=`${c.accent("\u25C6")} ${c.strong(c.primary(`Turn #${n}`))} ${c.muted(`\xB7 ${e} \xB7`)}`;return`
181
+ `+Hy(t)+`
182
+ `}function Ae(n){return` ${c.error("\u2717")} ${n}`}function He(n,e){return` ${c.error("\u2717")} ${n}
183
+ ${c.warning("\u2192")} ${c.muted(e)}`}function z(n){return` ${c.success("\u2713")} ${n}`}function pe(n){return` ${c.muted(n)}`}function j(n){return` ${c.warning("\u26A0")} ${n}`}function Ky(n,e){let s=Math.round(Math.min(n,e)/Math.max(e,1)*16),r=e>0?n/e:0;return(r>.85?c.error:r>.6?c.warning:c.success)("\u2588".repeat(s))+c.muted("\u2591".repeat(16-s))}function bu(n){let e=je(),t=n.connected?c.success("\u25CF connected"):c.error("\u25CB offline"),s=Ky(n.cacheTokens,n.budgetTokens),r=[["model",c.highlight(n.model)],["mindset",c.accent(n.mindset||"coder")],["host",c.muted(n.host)],["directory",c.muted(n.directory.replace(Ji.homedir(),"~"))],["context",`${s} ${c.muted(`${n.cacheFiles} files \xB7 ${n.cacheTokens}/${n.budgetTokens} tokens`)}`],["turns",c.muted(String(n.turnCount))],["status",t]];return`
184
184
  `+c.chrome("\u256D"+"\u2500".repeat(e-2)+"\u256E")+`
185
185
  ${c.accent("\u2726")} ${c.strong("Status")}
186
186
 
187
- `+Fy(r)+`
187
+ `+Uy(r)+`
188
188
 
189
189
  `+c.chrome("\u2570"+"\u2500".repeat(e-2)+"\u256F")+`
190
- `}function hu(){let n=He(),e=Math.max(...Gi.map(r=>r.cmd.length+(r.arg?r.arg.length+1:0))),t=Gi.map(({cmd:r,arg:i,desc:o})=>{let a=r.length+(i?i.length+1:0),l=" ".repeat(e-a+3);return` ${c.primary(r)}${i?" "+c.muted(i):""}${l}${c.secondary(o)}`}),s=["",` ${c.accent("\u2726")} ${c.strong("Tips")}`,"",` ${c.muted("\u25B8")} Use ${c.highlight("#filename")} to reference files inline`,` ${c.muted("\u25B8")} Press ${c.highlight("Ctrl+C")} once to cancel current operation`,` ${c.muted("\u25B8")} Press ${c.highlight("Ctrl+C\xD72")} quickly to exit CLI`,` ${c.muted("\u25B8")} Use ${c.highlight("--auto")} flag to skip tool confirmations`,` ${c.muted("\u25B8")} All file edits are backed up to ${c.muted("~/.hablas/backup/")}`,` ${c.muted("\u25B8")} Complex tasks \u2192 Hablas creates a plan \u2192 approve/edit \u2192 execute`];return`
190
+ `}function vu(){let n=je(),e=Math.max(...Yi.map(r=>r.cmd.length+(r.arg?r.arg.length+1:0))),t=Yi.map(({cmd:r,arg:i,desc:o})=>{let a=r.length+(i?i.length+1:0),l=" ".repeat(e-a+3);return` ${c.primary(r)}${i?" "+c.muted(i):""}${l}${c.secondary(o)}`}),s=["",` ${c.accent("\u2726")} ${c.strong("Tips")}`,"",` ${c.muted("\u25B8")} Use ${c.highlight("#filename")} to reference files inline`,` ${c.muted("\u25B8")} Press ${c.highlight("Ctrl+C")} once to cancel current operation`,` ${c.muted("\u25B8")} Press ${c.highlight("Ctrl+C\xD72")} quickly to exit CLI`,` ${c.muted("\u25B8")} Use ${c.highlight("--auto")} flag to skip tool confirmations`,` ${c.muted("\u25B8")} All file edits are backed up to ${c.muted("~/.hablas/backup/")}`,` ${c.muted("\u25B8")} Complex tasks \u2192 Hablas creates a plan \u2192 approve/edit \u2192 execute`];return`
191
191
  `+c.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E")+`
192
192
  ${c.accent("\u2726")} ${c.strong("Commands")}
193
193
 
@@ -197,14 +197,14 @@ ${l}
197
197
  `)+`
198
198
 
199
199
  `+c.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F")+`
200
- `}function Yi(n){let e=Math.floor(n.duration/6e4),t=Math.floor(n.duration%6e4/1e3),s=e>0?`${e}m ${t}s`:`${t}s`;return["",c.chrome("\u256D"+"\u2500".repeat(40)+"\u256E"),` ${c.accent("\u2726")} ${c.strong("Session Summary")}`,"",` ${c.muted("Turns")} ${c.secondary(String(n.turns))}`,` ${c.muted("Duration")} ${c.secondary(s)}`,` ${c.muted("Tool calls")} ${c.secondary(String(n.toolCalls))}`,"",c.chrome("\u2570"+"\u2500".repeat(40)+"\u256F"),"",` ${c.muted("Goodbye \u2014 hablas by Abdulmoin Hablas")}`,""].join(`
201
- `)}function mu(n,e){let t=He(),s=[];s.push(""),s.push(` ${c.chrome("\u256D"+"\u2500".repeat(t-4)+"\u256E")}`),s.push(` ${c.chrome("\u2502")} ${c.leader("\u2605")} ${c.strong("Hablas")} ${c.muted("\u2014 Execution Plan")}${" ".repeat(Math.max(0,t-35))}${c.chrome("\u2502")}`);let r=20,i=Math.round(e.percent/100*r),o=r-i,a=c.success("\u2588".repeat(i))+c.muted("\u2591".repeat(o));s.push(` ${c.chrome("\u2502")} ${a} ${c.muted(`${e.percent}%`)} ${c.muted(`(${e.done}/${e.total} tasks)`)}`),s.push(` ${c.chrome("\u251C"+"\u2500".repeat(t-4)+"\u2524")}`);for(let l=0;l<n.tasks.length;l++){let u=n.tasks[l],d=By[u.status](Hy[u.status]),h=(u.assignee==="hablas"?c.leader:u.assignee==="bob"?c.architect:u.assignee==="alex"?c.engineer:u.assignee==="david"?c.analyst:u.assignee==="emma"?c.product:c.muted)(`@${u.assigneeName}`),m="";u.dependent_task_ids.length>0&&(m=c.muted(` \u2190 [${u.dependent_task_ids.join(", ")}]`));let p=c.secondary(u.description);s.push(` ${c.chrome("\u2502")} ${d} ${c.muted(`${u.task_id}.`)} ${h} ${c.muted("\u2192")} ${p}${m}`)}return s.push(` ${c.chrome("\u251C"+"\u2500".repeat(t-4)+"\u2524")}`),s.push(` ${c.chrome("\u2502")} ${c.muted("Strategy:")} ${c.highlight(n.strategy)} ${c.muted("\xB7")} ${c.muted(`${n.tasks.length} tasks`)}`),s.push(` ${c.chrome("\u2570"+"\u2500".repeat(t-4)+"\u256F")}`),s.push(""),s.join(`
202
- `)}function gu(n){let e=He(),t=[];t.push(""),t.push(` ${c.chrome("\u256D"+"\u2500".repeat(e-4)+"\u256E")}`),t.push(` ${c.chrome("\u2502")} ${c.warning("?")} ${c.strong("Clarification Needed")}`),t.push(` ${c.chrome("\u251C"+"\u2500".repeat(e-4)+"\u2524")}`),t.push(` ${c.chrome("\u2502")} ${c.secondary(n.question)}`),t.push(` ${c.chrome("\u2502")}`);for(let s of n.choices)t.push(` ${c.chrome("\u2502")} ${c.accent(s.label+")")} ${c.secondary(s.value)}`);return n.context&&(t.push(` ${c.chrome("\u2502")}`),t.push(` ${c.chrome("\u2502")} ${c.muted(`Context: "${n.context.slice(0,60)}${n.context.length>60?"...":""}"`)}`)),t.push(` ${c.chrome("\u2570"+"\u2500".repeat(e-4)+"\u256F")}`),t.push(""),t.join(`
203
- `)}var Vi,Zc,eu,tu,hn,nu,su,He,c,Ge,Gi,Hy,By,Ji,yn=L(()=>{"use strict";Vi=O(require("os")),Zc=O(require("fs")),eu=O(require("path"));tu=Iy(),hn=process.stdout.isTTY===!0,nu=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",su=process.stdout.columns||80;hn&&process.stdout.on("resize",()=>{su=process.stdout.columns||80});He=()=>Math.min(su-4,100);c={primary:n=>fe(n,"\x1B[38;5;253m"),secondary:n=>fe(n,"\x1B[38;5;247m"),muted:n=>fe(n,"\x1B[38;5;242m"),strong:n=>fe(n,"\x1B[1;38;5;255m"),accent:n=>fe(n,"\x1B[38;5;145m"),highlight:n=>fe(n,"\x1B[38;5;231m"),success:n=>fe(n,"\x1B[38;5;108m"),error:n=>fe(n,"\x1B[38;5;167m"),warning:n=>fe(n,"\x1B[38;5;179m"),info:n=>fe(n,"\x1B[38;5;110m"),codeBlock:n=>fe(n,"\x1B[38;5;188m"),lineNum:n=>fe(n,"\x1B[38;5;239m"),border:n=>fe(n,"\x1B[38;5;237m"),chrome:n=>fe(n,"\x1B[38;5;235m"),added:n=>fe(n,"\x1B[38;5;108m"),removed:n=>fe(n,"\x1B[38;5;167m"),hunk:n=>fe(n,"\x1B[38;5;145m"),leader:n=>fe(n,"\x1B[38;5;179m"),architect:n=>fe(n,"\x1B[38;5;250m"),engineer:n=>fe(n,"\x1B[38;5;145m"),analyst:n=>fe(n,"\x1B[38;5;108m"),product:n=>fe(n,"\x1B[38;5;180m")};Ge=class{frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];interval=null;frameIndex=0;message;startTime=0;constructor(e="Thinking"){this.message=e}start(){if(this.startTime=Date.now(),!hn){process.stderr.write(` ${this.message}...
204
- `);return}this.interval=setInterval(()=>{let e=((Date.now()-this.startTime)/1e3).toFixed(1),t=c.accent(this.frames[this.frameIndex]);process.stdout.write(`\r ${t} ${c.muted(this.message)} ${c.muted(e+"s")}`),this.frameIndex=(this.frameIndex+1)%this.frames.length},80)}setPhase(e){this.message=e}updateMessage(e){this.message=e}stop(e){this.interval&&(clearInterval(this.interval),this.interval=null);let t=Date.now()-this.startTime;if(hn&&process.stdout.write("\r"+" ".repeat(80)+"\r"),e&&hn){let s=c.muted(`${t}ms`);console.log(` ${c.muted("\xB7")} ${c.secondary(e)} ${s}`)}}};Gi=[{cmd:"/help",desc:"Show this help"},{cmd:"/about",desc:"Developer info & links"},{cmd:"/version",desc:"Version & runtime info"},{cmd:"/team",desc:"Show agent team roster"},{cmd:"/model",arg:"<name>",desc:"Switch model"},{cmd:"/models",arg:"[search|page]",desc:"Browse all models"},{cmd:"/tree",desc:"Project file tree"},{cmd:"/status",desc:"Agent status & context"},{cmd:"/history",arg:"[n]",desc:"Show last n turns"},{cmd:"/undo",arg:"[path]",desc:"Restore last backup"},{cmd:"/clear",desc:"Clear session & context"},{cmd:"/config",desc:"Show current config"},{cmd:"/quit",desc:"Exit hablas"}];Hy={pending:"\u25CB",running:"\u25C9",done:"\u2713",failed:"\u2717",skipped:"\u2013"},By={pending:c.muted,running:c.accent,done:c.success,failed:c.error,skipped:c.muted};Ji=Gi.map(n=>n.cmd).concat(["/exit","/addmodel","/listmodels","/removemodel","/usemodel","/provider","/task","/memory","/mindset","/mindsets","/alias","/doctor","/plugins","/team","/agents","/delegate"])});function Xi(n){let e=st.join(n,"package.json");if(Ue.existsSync(e))try{let t=JSON.parse(Ue.readFileSync(e,"utf-8")),s={...t.dependencies,...t.devDependencies};if(s.vitest)return"vitest";if(s.jest||s["@jest/core"])return"jest";if(s.mocha)return"mocha"}catch{}if(Ue.existsSync(st.join(n,"pytest.ini"))||Ue.existsSync(st.join(n,"pyproject.toml"))||Ue.existsSync(st.join(n,"setup.py")))try{let t=Ue.existsSync(st.join(n,"requirements.txt"))?Ue.readFileSync(st.join(n,"requirements.txt"),"utf-8"):"",s=Ue.existsSync(st.join(n,"pyproject.toml"))?Ue.readFileSync(st.join(n,"pyproject.toml"),"utf-8"):"";if(t.includes("pytest")||s.includes("pytest"))return"pytest"}catch{}return Ue.existsSync(st.join(n,"go.mod"))?"go":Ue.existsSync(st.join(n,"Cargo.toml"))?"cargo":"unknown"}function Uy(n,e){switch(n){case"vitest":return e?`npx vitest run ${e}`:"npx vitest run";case"jest":return e?`npx jest ${e} --no-coverage`:"npx jest --no-coverage";case"mocha":return e?`npx mocha ${e}`:"npx mocha";case"pytest":return e?`python -m pytest ${e} -v`:"python -m pytest -v";case"go":return e?`go test ./${e}`:"go test ./...";case"cargo":return"cargo test";default:return"npm test"}}function bu(n,e){let t=Xi(n),s=Uy(t,e),r=Date.now(),i="",o="",a=!1;try{i=(0,yu.execSync)(s,{cwd:n,encoding:"utf-8",timeout:12e4,maxBuffer:5*1024*1024,stdio:["pipe","pipe","pipe"]}),a=!0}catch(m){i=m.stdout||"",o=m.stderr||m.message||"",a=!1}let l=Date.now()-r,{totalTests:u,passedTests:d,failedTests:f,failedTestNames:h}=qy(i+`
205
- `+o,t);return{framework:t,command:s,passed:a,output:i.slice(0,5e3),errorOutput:o.slice(0,3e3),totalTests:u,passedTests:d,failedTests:f,duration:l,failedTestNames:h}}function qy(n,e){let t=0,s=0,r=0,i=[],o=n.split(`
206
- `);switch(e){case"jest":case"vitest":{for(let a of o){let l=a.match(/Tests:\s+(\d+)\s+passed.*?(\d+)\s+total/);if(l&&(s=parseInt(l[1]),t=parseInt(l[2]),r=t-s),a.match(/✕|FAIL|✗|×/)){let d=a.replace(/.*(?:✕|FAIL|✗|×)\s*/,"").trim();d&&i.push(d)}}break}case"pytest":{for(let a of o){let l=a.match(/(\d+)\s+passed.*?(\d+)\s+failed/);l&&(s=parseInt(l[1]),r=parseInt(l[2]),t=s+r);let u=a.match(/(\d+)\s+passed/);u&&t===0&&(s=parseInt(u[1]),t=s),a.includes("FAILED")&&i.push(a.trim())}break}case"go":{for(let a of o)a.includes("--- PASS")&&s++,a.includes("--- FAIL")&&(r++,i.push(a.replace("--- FAIL:","").trim()));t=s+r;break}default:{for(let a of o)/\bpass(ed|ing)?\b/i.test(a)&&/\d/.test(a)&&s++,/\bfail(ed|ing|ure)?\b/i.test(a)&&/\d/.test(a)&&r++;t=s+r}}return{totalTests:t,passedTests:s,failedTests:r,failedTestNames:i}}function vu(n){let e=[],t=n.passed?"\u2713 PASSED":"\u2717 FAILED",s=(n.duration/1e3).toFixed(1);if(e.push(` ${n.passed?"\u2713":"\u2717"} ${t} (${n.framework}) \u2014 ${s}s`),e.push(` Command: ${n.command}`),n.totalTests>0&&e.push(` Tests: ${n.passedTests} passed, ${n.failedTests} failed, ${n.totalTests} total`),n.failedTestNames.length>0){e.push(""),e.push(" Failed tests:");for(let r of n.failedTestNames.slice(0,10))e.push(` \u2717 ${r}`)}return e.join(`
207
- `)}function wu(n){return`The following tests are failing. Analyze the error output and fix the code.
200
+ `}function Qi(n){let e=Math.floor(n.duration/6e4),t=Math.floor(n.duration%6e4/1e3),s=e>0?`${e}m ${t}s`:`${t}s`;return["",c.chrome("\u256D"+"\u2500".repeat(40)+"\u256E"),` ${c.accent("\u2726")} ${c.strong("Session Summary")}`,"",` ${c.muted("Turns")} ${c.secondary(String(n.turns))}`,` ${c.muted("Duration")} ${c.secondary(s)}`,` ${c.muted("Tool calls")} ${c.secondary(String(n.toolCalls))}`,"",c.chrome("\u2570"+"\u2500".repeat(40)+"\u256F"),"",` ${c.muted("Goodbye \u2014 hablas by Abdulmoin Hablas")}`,""].join(`
201
+ `)}function wu(n,e){let t=je(),s=[];s.push(""),s.push(` ${c.chrome("\u256D"+"\u2500".repeat(t-4)+"\u256E")}`),s.push(` ${c.chrome("\u2502")} ${c.leader("\u2605")} ${c.strong("Hablas")} ${c.muted("\u2014 Execution Plan")}${" ".repeat(Math.max(0,t-35))}${c.chrome("\u2502")}`);let r=20,i=Math.round(e.percent/100*r),o=r-i,a=c.success("\u2588".repeat(i))+c.muted("\u2591".repeat(o));s.push(` ${c.chrome("\u2502")} ${a} ${c.muted(`${e.percent}%`)} ${c.muted(`(${e.done}/${e.total} tasks)`)}`),s.push(` ${c.chrome("\u251C"+"\u2500".repeat(t-4)+"\u2524")}`);for(let l=0;l<n.tasks.length;l++){let u=n.tasks[l],d=Gy[u.status](Wy[u.status]),h=(u.assignee==="hablas"?c.leader:u.assignee==="bob"?c.architect:u.assignee==="alex"?c.engineer:u.assignee==="david"?c.analyst:u.assignee==="emma"?c.product:c.muted)(`@${u.assigneeName}`),m="";u.dependent_task_ids.length>0&&(m=c.muted(` \u2190 [${u.dependent_task_ids.join(", ")}]`));let p=c.secondary(u.description);s.push(` ${c.chrome("\u2502")} ${d} ${c.muted(`${u.task_id}.`)} ${h} ${c.muted("\u2192")} ${p}${m}`)}return s.push(` ${c.chrome("\u251C"+"\u2500".repeat(t-4)+"\u2524")}`),s.push(` ${c.chrome("\u2502")} ${c.muted("Strategy:")} ${c.highlight(n.strategy)} ${c.muted("\xB7")} ${c.muted(`${n.tasks.length} tasks`)}`),s.push(` ${c.chrome("\u2570"+"\u2500".repeat(t-4)+"\u256F")}`),s.push(""),s.join(`
202
+ `)}function xu(n){let e=je(),t=[];t.push(""),t.push(` ${c.chrome("\u256D"+"\u2500".repeat(e-4)+"\u256E")}`),t.push(` ${c.chrome("\u2502")} ${c.warning("?")} ${c.strong("Clarification Needed")}`),t.push(` ${c.chrome("\u251C"+"\u2500".repeat(e-4)+"\u2524")}`),t.push(` ${c.chrome("\u2502")} ${c.secondary(n.question)}`),t.push(` ${c.chrome("\u2502")}`);for(let s of n.choices)t.push(` ${c.chrome("\u2502")} ${c.accent(s.label+")")} ${c.secondary(s.value)}`);return n.context&&(t.push(` ${c.chrome("\u2502")}`),t.push(` ${c.chrome("\u2502")} ${c.muted(`Context: "${n.context.slice(0,60)}${n.context.length>60?"...":""}"`)}`)),t.push(` ${c.chrome("\u2570"+"\u2500".repeat(e-4)+"\u256F")}`),t.push(""),t.join(`
203
+ `)}var Ji,ru,iu,ou,mn,au,lu,je,c,Ve,Yi,Wy,Gy,Zi,bn=L(()=>{"use strict";Ji=O(require("os")),ru=O(require("fs")),iu=O(require("path"));ou=jy(),mn=process.stdout.isTTY===!0,au=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",lu=process.stdout.columns||80;mn&&process.stdout.on("resize",()=>{lu=process.stdout.columns||80});je=()=>Math.min(lu-4,100);c={primary:n=>fe(n,"\x1B[38;5;253m"),secondary:n=>fe(n,"\x1B[38;5;247m"),muted:n=>fe(n,"\x1B[38;5;242m"),strong:n=>fe(n,"\x1B[1;38;5;255m"),accent:n=>fe(n,"\x1B[38;5;145m"),highlight:n=>fe(n,"\x1B[38;5;231m"),success:n=>fe(n,"\x1B[38;5;108m"),error:n=>fe(n,"\x1B[38;5;167m"),warning:n=>fe(n,"\x1B[38;5;179m"),info:n=>fe(n,"\x1B[38;5;110m"),codeBlock:n=>fe(n,"\x1B[38;5;188m"),lineNum:n=>fe(n,"\x1B[38;5;239m"),border:n=>fe(n,"\x1B[38;5;237m"),chrome:n=>fe(n,"\x1B[38;5;235m"),added:n=>fe(n,"\x1B[38;5;108m"),removed:n=>fe(n,"\x1B[38;5;167m"),hunk:n=>fe(n,"\x1B[38;5;145m"),leader:n=>fe(n,"\x1B[38;5;179m"),architect:n=>fe(n,"\x1B[38;5;250m"),engineer:n=>fe(n,"\x1B[38;5;145m"),analyst:n=>fe(n,"\x1B[38;5;108m"),product:n=>fe(n,"\x1B[38;5;180m")};Ve=class{frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];interval=null;frameIndex=0;message;startTime=0;constructor(e="Thinking"){this.message=e}start(){if(this.startTime=Date.now(),!mn){process.stderr.write(` ${this.message}...
204
+ `);return}this.interval=setInterval(()=>{let e=((Date.now()-this.startTime)/1e3).toFixed(1),t=c.accent(this.frames[this.frameIndex]);process.stdout.write(`\r ${t} ${c.muted(this.message)} ${c.muted(e+"s")}`),this.frameIndex=(this.frameIndex+1)%this.frames.length},80)}setPhase(e){this.message=e}updateMessage(e){this.message=e}stop(e){this.interval&&(clearInterval(this.interval),this.interval=null);let t=Date.now()-this.startTime;if(mn&&process.stdout.write("\r"+" ".repeat(80)+"\r"),e&&mn){let s=c.muted(`${t}ms`);console.log(` ${c.muted("\xB7")} ${c.secondary(e)} ${s}`)}}};Yi=[{cmd:"/help",desc:"Show this help"},{cmd:"/about",desc:"Developer info & links"},{cmd:"/version",desc:"Version & runtime info"},{cmd:"/team",desc:"Show agent team roster"},{cmd:"/model",arg:"<name>",desc:"Switch model"},{cmd:"/models",arg:"[search|page]",desc:"Browse all models"},{cmd:"/tree",desc:"Project file tree"},{cmd:"/status",desc:"Agent status & context"},{cmd:"/history",arg:"[n]",desc:"Show last n turns"},{cmd:"/undo",arg:"[path]",desc:"Restore last backup"},{cmd:"/clear",desc:"Clear session & context"},{cmd:"/config",desc:"Show current config"},{cmd:"/quit",desc:"Exit hablas"}];Wy={pending:"\u25CB",running:"\u25C9",done:"\u2713",failed:"\u2717",skipped:"\u2013"},Gy={pending:c.muted,running:c.accent,done:c.success,failed:c.error,skipped:c.muted};Zi=Yi.map(n=>n.cmd).concat(["/exit","/addmodel","/listmodels","/removemodel","/usemodel","/provider","/task","/memory","/mindset","/mindsets","/alias","/doctor","/plugins","/team","/agents","/delegate"])});function eo(n){let e=rt.join(n,"package.json");if(Be.existsSync(e))try{let t=JSON.parse(Be.readFileSync(e,"utf-8")),s={...t.dependencies,...t.devDependencies};if(s.vitest)return"vitest";if(s.jest||s["@jest/core"])return"jest";if(s.mocha)return"mocha"}catch{}if(Be.existsSync(rt.join(n,"pytest.ini"))||Be.existsSync(rt.join(n,"pyproject.toml"))||Be.existsSync(rt.join(n,"setup.py")))try{let t=Be.existsSync(rt.join(n,"requirements.txt"))?Be.readFileSync(rt.join(n,"requirements.txt"),"utf-8"):"",s=Be.existsSync(rt.join(n,"pyproject.toml"))?Be.readFileSync(rt.join(n,"pyproject.toml"),"utf-8"):"";if(t.includes("pytest")||s.includes("pytest"))return"pytest"}catch{}return Be.existsSync(rt.join(n,"go.mod"))?"go":Be.existsSync(rt.join(n,"Cargo.toml"))?"cargo":"unknown"}function Vy(n,e){switch(n){case"vitest":return e?`npx vitest run ${e}`:"npx vitest run";case"jest":return e?`npx jest ${e} --no-coverage`:"npx jest --no-coverage";case"mocha":return e?`npx mocha ${e}`:"npx mocha";case"pytest":return e?`python -m pytest ${e} -v`:"python -m pytest -v";case"go":return e?`go test ./${e}`:"go test ./...";case"cargo":return"cargo test";default:return"npm test"}}function _u(n,e){let t=eo(n),s=Vy(t,e),r=Date.now(),i="",o="",a=!1;try{i=(0,Su.execSync)(s,{cwd:n,encoding:"utf-8",timeout:12e4,maxBuffer:5*1024*1024,stdio:["pipe","pipe","pipe"]}),a=!0}catch(m){i=m.stdout||"",o=m.stderr||m.message||"",a=!1}let l=Date.now()-r,{totalTests:u,passedTests:d,failedTests:f,failedTestNames:h}=zy(i+`
205
+ `+o,t);return{framework:t,command:s,passed:a,output:i.slice(0,5e3),errorOutput:o.slice(0,3e3),totalTests:u,passedTests:d,failedTests:f,duration:l,failedTestNames:h}}function zy(n,e){let t=0,s=0,r=0,i=[],o=n.split(`
206
+ `);switch(e){case"jest":case"vitest":{for(let a of o){let l=a.match(/Tests:\s+(\d+)\s+passed.*?(\d+)\s+total/);if(l&&(s=parseInt(l[1]),t=parseInt(l[2]),r=t-s),a.match(/✕|FAIL|✗|×/)){let d=a.replace(/.*(?:✕|FAIL|✗|×)\s*/,"").trim();d&&i.push(d)}}break}case"pytest":{for(let a of o){let l=a.match(/(\d+)\s+passed.*?(\d+)\s+failed/);l&&(s=parseInt(l[1]),r=parseInt(l[2]),t=s+r);let u=a.match(/(\d+)\s+passed/);u&&t===0&&(s=parseInt(u[1]),t=s),a.includes("FAILED")&&i.push(a.trim())}break}case"go":{for(let a of o)a.includes("--- PASS")&&s++,a.includes("--- FAIL")&&(r++,i.push(a.replace("--- FAIL:","").trim()));t=s+r;break}default:{for(let a of o)/\bpass(ed|ing)?\b/i.test(a)&&/\d/.test(a)&&s++,/\bfail(ed|ing|ure)?\b/i.test(a)&&/\d/.test(a)&&r++;t=s+r}}return{totalTests:t,passedTests:s,failedTests:r,failedTestNames:i}}function ku(n){let e=[],t=n.passed?"\u2713 PASSED":"\u2717 FAILED",s=(n.duration/1e3).toFixed(1);if(e.push(` ${n.passed?"\u2713":"\u2717"} ${t} (${n.framework}) \u2014 ${s}s`),e.push(` Command: ${n.command}`),n.totalTests>0&&e.push(` Tests: ${n.passedTests} passed, ${n.failedTests} failed, ${n.totalTests} total`),n.failedTestNames.length>0){e.push(""),e.push(" Failed tests:");for(let r of n.failedTestNames.slice(0,10))e.push(` \u2717 ${r}`)}return e.join(`
207
+ `)}function Au(n){return`The following tests are failing. Analyze the error output and fix the code.
208
208
 
209
209
  Test framework: ${n.framework}
210
210
  Command: ${n.command}
@@ -224,21 +224,21 @@ Instructions:
224
224
  1. Read the failing test files to understand what's expected
225
225
  2. Read the source files being tested
226
226
  3. Fix the source code (not the tests) to make them pass
227
- 4. After fixing, explain what was wrong and what you changed`}var yu,Ue,st,xu=L(()=>{"use strict";yu=require("child_process"),Ue=O(require("fs")),st=O(require("path"))});function Ks(n){let e=Buffer.from(n).toString("base64url").slice(0,16);return Ie.join(Ky,e)}async function _u(n,e,t){let s=Ks(n);$e.existsSync(s)||$e.mkdirSync(s,{recursive:!0});let r=`cp_${Date.now()}`,i=[];for(let f of t){let h=Ie.resolve(n,f);if($e.existsSync(h))try{let m=await Rt.readFile(h,"utf-8");i.push({path:f,content:m})}catch{}}try{let f=(0,qs.execSync)("git ls-files -m",{cwd:n,encoding:"utf-8",timeout:5e3}).split(`
228
- `).filter(Boolean);for(let h of f)if(!i.find(m=>m.path===h))try{let m=await Rt.readFile(Ie.resolve(n,h),"utf-8");i.push({path:h,content:m})}catch{}}catch{}let o,a;try{o=(0,qs.execSync)("git branch --show-current",{cwd:n,encoding:"utf-8",timeout:5e3}).trim(),a=(0,qs.execSync)("git rev-parse --short HEAD",{cwd:n,encoding:"utf-8",timeout:5e3}).trim()}catch{}let l={id:r,label:e,timestamp:Date.now(),files:i,gitBranch:o,gitHash:a,projectPath:n},u=Ie.join(s,`${r}.json`);await Rt.writeFile(u,JSON.stringify(l,null,2),"utf-8");let d=$e.readdirSync(s).filter(f=>f.endsWith(".json")).sort();if(d.length>20)for(let f of d.slice(0,d.length-20))try{$e.unlinkSync(Ie.join(s,f))}catch{}return{id:r,label:e,timestamp:l.timestamp,fileCount:i.length,projectPath:n}}function ku(n){let e=Ks(n);if(!$e.existsSync(e))return[];let t=$e.readdirSync(e).filter(r=>r.endsWith(".json")).sort().reverse(),s=[];for(let r of t)try{let i=JSON.parse($e.readFileSync(Ie.join(e,r),"utf-8"));s.push({id:i.id,label:i.label,timestamp:i.timestamp,fileCount:i.files.length,projectPath:i.projectPath})}catch{}return s}async function Au(n,e){let t=Ks(n),s=Ie.join(t,`${e}.json`);if(!$e.existsSync(s))return{success:!1,filesRestored:0,error:`Checkpoint ${e} not found`};try{let r=JSON.parse(await Rt.readFile(s,"utf-8")),i=0;for(let o of r.files)try{let a=Ie.resolve(n,o.path);await Rt.mkdir(Ie.dirname(a),{recursive:!0}),await Rt.writeFile(a,o.content,"utf-8"),i++}catch{}return{success:!0,filesRestored:i}}catch(r){return{success:!1,filesRestored:0,error:r.message}}}function $u(n,e){let t=Ks(n),s=Ie.join(t,`${e}.json`);try{if($e.existsSync(s))return $e.unlinkSync(s),!0}catch{}return!1}function Cu(n){if(n.length===0)return" No checkpoints saved";let e=[];for(let t of n){let s=new Date(t.timestamp).toLocaleString();e.push(` ${t.id} "${t.label}" (${t.fileCount} files, ${s})`)}return e.join(`
229
- `)}var $e,Rt,Ie,Su,qs,Ky,Eu=L(()=>{"use strict";$e=O(require("fs")),Rt=O(require("fs/promises")),Ie=O(require("path")),Su=O(require("os")),qs=require("child_process"),Ky=Ie.join(Su.homedir(),".hablas","checkpoints")});function Ot(){}function Wy(n,e,t,s,r){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,u=0,d=0;a<l;a++){var f=i[a];if(f.removed){if(f.value=n.join(s.slice(d,d+f.count)),d+=f.count,a&&i[a-1].added){var m=i[a-1];i[a-1]=i[a],i[a]=m}}else{if(!f.added&&r){var h=t.slice(u,u+f.count);h=h.map(function(g,x){var w=s[d+x];return w.length>g.length?w:g}),f.value=n.join(h)}else f.value=n.join(t.slice(u,u+f.count));u+=f.count,f.added||(d+=f.count)}}var p=i[l-1];return l>1&&typeof p.value=="string"&&(p.added||p.removed)&&n.equals("",p.value)&&(i[l-2].value+=p.value,i.pop()),i}function Gy(n,e,t){return no.diff(n,e,t)}function Ws(n){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ws=function(e){return typeof e}:Ws=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ws(n)}function Qi(n){return Yy(n)||Jy(n)||Xy(n)||Qy()}function Yy(n){if(Array.isArray(n))return Zi(n)}function Jy(n){if(typeof Symbol<"u"&&Symbol.iterator in Object(n))return Array.from(n)}function Xy(n,e){if(n){if(typeof n=="string")return Zi(n,e);var t=Object.prototype.toString.call(n).slice(8,-1);if(t==="Object"&&n.constructor&&(t=n.constructor.name),t==="Map"||t==="Set")return Array.from(n);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Zi(n,e)}}function Zi(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,s=new Array(e);t<e;t++)s[t]=n[t];return s}function Qy(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
230
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function eo(n,e,t,s,r){e=e||[],t=t||[],s&&(n=s(r,n));var i;for(i=0;i<e.length;i+=1)if(e[i]===n)return t[i];var o;if(Zy.call(n)==="[object Array]"){for(e.push(n),o=new Array(n.length),t.push(o),i=0;i<n.length;i+=1)o[i]=eo(n[i],e,t,s,r);return e.pop(),t.pop(),o}if(n&&n.toJSON&&(n=n.toJSON()),Ws(n)==="object"&&n!==null){e.push(n),o={},t.push(o);var a=[],l;for(l in n)n.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],o[l]=eo(n[l],e,t,s,l);e.pop(),t.pop()}else o=n;return o}function eb(n){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},t=n.split(/\r\n|[\n\v\f\r\x85]/),s=n.match(/\r\n|[\n\v\f\r\x85]/g)||[],r=[],i=0;function o(){var u={};for(r.push(u);i<t.length;){var d=t[i];if(/^(\-\-\-|\+\+\+|@@)\s/.test(d))break;var f=/^(?:Index:|diff(?: -r \w+)+)\s+/.exec(d);f&&(u.index=d.substring(f[0].length).trim()),i++}for(a(u),a(u),u.hunks=[];i<t.length;){var h=t[i];if(/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(h))break;if(/^@@/.test(h))u.hunks.push(l());else{if(h&&e.strict)throw new Error("Unknown line "+(i+1)+" "+JSON.stringify(h));i++}}}function a(u){var d=/^(---|\+\+\+)\s+/.exec(t[i]);if(d){var f=d[1]==="---"?"old":"new",h=t[i].substring(3).trim().split(" ",2),m=h[0].replace(/\\\\/g,"\\");m.startsWith('"')&&m.endsWith('"')&&(m=m.substr(1,m.length-2)),u[f+"FileName"]=m,u[f+"Header"]=(h[1]||"").trim(),i++}}function l(){var u=i,d=t[i++],f=d.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/),h={oldStart:+f[1],oldLines:typeof f[2]>"u"?1:+f[2],newStart:+f[3],newLines:typeof f[4]>"u"?1:+f[4],lines:[],linedelimiters:[]};h.oldLines===0&&(h.oldStart+=1),h.newLines===0&&(h.newStart+=1);for(var m=0,p=0;i<t.length&&!(t[i].indexOf("--- ")===0&&i+2<t.length&&t[i+1].indexOf("+++ ")===0&&t[i+2].indexOf("@@")===0);i++){var g=t[i].length==0&&i!=t.length-1?" ":t[i][0];if(g==="+"||g==="-"||g===" "||g==="\\")h.lines.push(t[i]),h.linedelimiters.push(s[i]||`
231
- `),g==="+"?m++:g==="-"?p++:g===" "&&(m++,p++);else break}if(!m&&h.newLines===1&&(h.newLines=0),!p&&h.oldLines===1&&(h.oldLines=0),e.strict){if(m!==h.newLines)throw new Error("Added line count did not match for hunk at line "+(u+1));if(p!==h.oldLines)throw new Error("Removed line count did not match for hunk at line "+(u+1))}return h}for(;i<t.length;)o();return r}function tb(n,e,t){var s=!0,r=!1,i=!1,o=1;return function a(){if(s&&!i){if(r?o++:s=!1,n+o<=t)return o;i=!0}if(!r)return i||(s=!0),e<=n-o?-o++:(r=!0,a())}}function Pu(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(typeof e=="string"&&(e=eb(e)),Array.isArray(e)){if(e.length>1)throw new Error("applyPatch only works with a single input.");e=e[0]}var s=n.split(/\r\n|[\n\v\f\r\x85]/),r=n.match(/\r\n|[\n\v\f\r\x85]/g)||[],i=e.hunks,o=t.compareLine||function(E,k,Y,q){return k===q},a=0,l=t.fuzzFactor||0,u=0,d=0,f,h;function m(E,k){for(var Y=0;Y<E.lines.length;Y++){var q=E.lines[Y],Z=q.length>0?q[0]:" ",ee=q.length>0?q.substr(1):q;if(Z===" "||Z==="-"){if(!o(k+1,s[k],Z,ee)&&(a++,a>l))return!1;k++}}return!0}for(var p=0;p<i.length;p++){for(var g=i[p],x=s.length-g.oldLines,w=0,$=d+g.oldStart-1,A=tb($,u,x);w!==void 0;w=A())if(m(g,$+w)){g.offset=d+=w;break}if(w===void 0)return!1;u=g.offset+g.oldStart+g.oldLines}for(var y=0,v=0;v<i.length;v++){var b=i[v],S=b.oldStart+b.offset+y-1;y+=b.newLines-b.oldLines;for(var _=0;_<b.lines.length;_++){var T=b.lines[_],I=T.length>0?T[0]:" ",C=T.length>0?T.substr(1):T,F=b.linedelimiters&&b.linedelimiters[_]||`
232
- `;if(I===" ")S++;else if(I==="-")s.splice(S,1),r.splice(S,1);else if(I==="+")s.splice(S,0,C),r.splice(S,0,F),S++;else if(I==="\\"){var H=b.lines[_-1]?b.lines[_-1][0]:null;H==="+"?f=!0:H==="-"&&(h=!0)}}}if(f)for(;!s[s.length-1];)s.pop(),r.pop();else h&&(s.push(""),r.push(`
233
- `));for(var G=0;G<s.length-1;G++)s[G]=s[G]+r[G];return s.join("")}function nb(n,e,t,s,r,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Gy(t,s,o);if(!a)return;a.push({value:"",lines:[]});function l(w){return w.map(function($){return" "+$})}for(var u=[],d=0,f=0,h=[],m=1,p=1,g=function($){var A=a[$],y=A.lines||A.value.replace(/\n$/,"").split(`
234
- `);if(A.lines=y,A.added||A.removed){var v;if(!d){var b=a[$-1];d=m,f=p,b&&(h=o.context>0?l(b.lines.slice(-o.context)):[],d-=h.length,f-=h.length)}(v=h).push.apply(v,Qi(y.map(function(G){return(A.added?"+":"-")+G}))),A.added?p+=y.length:m+=y.length}else{if(d)if(y.length<=o.context*2&&$<a.length-2){var S;(S=h).push.apply(S,Qi(l(y)))}else{var _,T=Math.min(y.length,o.context);(_=h).push.apply(_,Qi(l(y.slice(0,T))));var I={oldStart:d,oldLines:m-d+T,newStart:f,newLines:p-f+T,lines:h};if($>=a.length-2&&y.length<=o.context){var C=/\n$/.test(t),F=/\n$/.test(s),H=y.length==0&&h.length>I.oldLines;!C&&H&&t.length>0&&h.splice(I.oldLines,0,"\"),(!C&&!H||!F)&&h.push("\")}u.push(I),d=0,f=0,h=[]}m+=y.length,p+=y.length}},x=0;x<a.length;x++)g(x);return{oldFileName:n,newFileName:e,oldHeader:r,newHeader:i,hunks:u}}function Mu(n){if(Array.isArray(n))return n.map(Mu).join(`
227
+ 4. After fixing, explain what was wrong and what you changed`}var Su,Be,rt,$u=L(()=>{"use strict";Su=require("child_process"),Be=O(require("fs")),rt=O(require("path"))});function Gs(n){let e=Buffer.from(n).toString("base64url").slice(0,16);return Ie.join(Yy,e)}async function Eu(n,e,t){let s=Gs(n);Ce.existsSync(s)||Ce.mkdirSync(s,{recursive:!0});let r=`cp_${Date.now()}`,i=[];for(let f of t){let h=Ie.resolve(n,f);if(Ce.existsSync(h))try{let m=await Rt.readFile(h,"utf-8");i.push({path:f,content:m})}catch{}}try{let f=(0,Ws.execSync)("git ls-files -m",{cwd:n,encoding:"utf-8",timeout:5e3}).split(`
228
+ `).filter(Boolean);for(let h of f)if(!i.find(m=>m.path===h))try{let m=await Rt.readFile(Ie.resolve(n,h),"utf-8");i.push({path:h,content:m})}catch{}}catch{}let o,a;try{o=(0,Ws.execSync)("git branch --show-current",{cwd:n,encoding:"utf-8",timeout:5e3}).trim(),a=(0,Ws.execSync)("git rev-parse --short HEAD",{cwd:n,encoding:"utf-8",timeout:5e3}).trim()}catch{}let l={id:r,label:e,timestamp:Date.now(),files:i,gitBranch:o,gitHash:a,projectPath:n},u=Ie.join(s,`${r}.json`);await Rt.writeFile(u,JSON.stringify(l,null,2),"utf-8");let d=Ce.readdirSync(s).filter(f=>f.endsWith(".json")).sort();if(d.length>20)for(let f of d.slice(0,d.length-20))try{Ce.unlinkSync(Ie.join(s,f))}catch{}return{id:r,label:e,timestamp:l.timestamp,fileCount:i.length,projectPath:n}}function Tu(n){let e=Gs(n);if(!Ce.existsSync(e))return[];let t=Ce.readdirSync(e).filter(r=>r.endsWith(".json")).sort().reverse(),s=[];for(let r of t)try{let i=JSON.parse(Ce.readFileSync(Ie.join(e,r),"utf-8"));s.push({id:i.id,label:i.label,timestamp:i.timestamp,fileCount:i.files.length,projectPath:i.projectPath})}catch{}return s}async function Ru(n,e){let t=Gs(n),s=Ie.join(t,`${e}.json`);if(!Ce.existsSync(s))return{success:!1,filesRestored:0,error:`Checkpoint ${e} not found`};try{let r=JSON.parse(await Rt.readFile(s,"utf-8")),i=0;for(let o of r.files)try{let a=Ie.resolve(n,o.path);await Rt.mkdir(Ie.dirname(a),{recursive:!0}),await Rt.writeFile(a,o.content,"utf-8"),i++}catch{}return{success:!0,filesRestored:i}}catch(r){return{success:!1,filesRestored:0,error:r.message}}}function Ou(n,e){let t=Gs(n),s=Ie.join(t,`${e}.json`);try{if(Ce.existsSync(s))return Ce.unlinkSync(s),!0}catch{}return!1}function Pu(n){if(n.length===0)return" No checkpoints saved";let e=[];for(let t of n){let s=new Date(t.timestamp).toLocaleString();e.push(` ${t.id} "${t.label}" (${t.fileCount} files, ${s})`)}return e.join(`
229
+ `)}var Ce,Rt,Ie,Cu,Ws,Yy,Mu=L(()=>{"use strict";Ce=O(require("fs")),Rt=O(require("fs/promises")),Ie=O(require("path")),Cu=O(require("os")),Ws=require("child_process"),Yy=Ie.join(Cu.homedir(),".hablas","checkpoints")});function Ot(){}function Jy(n,e,t,s,r){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,u=0,d=0;a<l;a++){var f=i[a];if(f.removed){if(f.value=n.join(s.slice(d,d+f.count)),d+=f.count,a&&i[a-1].added){var m=i[a-1];i[a-1]=i[a],i[a]=m}}else{if(!f.added&&r){var h=t.slice(u,u+f.count);h=h.map(function(g,x){var w=s[d+x];return w.length>g.length?w:g}),f.value=n.join(h)}else f.value=n.join(t.slice(u,u+f.count));u+=f.count,f.added||(d+=f.count)}}var p=i[l-1];return l>1&&typeof p.value=="string"&&(p.added||p.removed)&&n.equals("",p.value)&&(i[l-2].value+=p.value,i.pop()),i}function Xy(n,e,t){return io.diff(n,e,t)}function Vs(n){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Vs=function(e){return typeof e}:Vs=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Vs(n)}function to(n){return eb(n)||tb(n)||nb(n)||sb()}function eb(n){if(Array.isArray(n))return no(n)}function tb(n){if(typeof Symbol<"u"&&Symbol.iterator in Object(n))return Array.from(n)}function nb(n,e){if(n){if(typeof n=="string")return no(n,e);var t=Object.prototype.toString.call(n).slice(8,-1);if(t==="Object"&&n.constructor&&(t=n.constructor.name),t==="Map"||t==="Set")return Array.from(n);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return no(n,e)}}function no(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,s=new Array(e);t<e;t++)s[t]=n[t];return s}function sb(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
230
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function so(n,e,t,s,r){e=e||[],t=t||[],s&&(n=s(r,n));var i;for(i=0;i<e.length;i+=1)if(e[i]===n)return t[i];var o;if(rb.call(n)==="[object Array]"){for(e.push(n),o=new Array(n.length),t.push(o),i=0;i<n.length;i+=1)o[i]=so(n[i],e,t,s,r);return e.pop(),t.pop(),o}if(n&&n.toJSON&&(n=n.toJSON()),Vs(n)==="object"&&n!==null){e.push(n),o={},t.push(o);var a=[],l;for(l in n)n.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],o[l]=so(n[l],e,t,s,l);e.pop(),t.pop()}else o=n;return o}function ib(n){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},t=n.split(/\r\n|[\n\v\f\r\x85]/),s=n.match(/\r\n|[\n\v\f\r\x85]/g)||[],r=[],i=0;function o(){var u={};for(r.push(u);i<t.length;){var d=t[i];if(/^(\-\-\-|\+\+\+|@@)\s/.test(d))break;var f=/^(?:Index:|diff(?: -r \w+)+)\s+/.exec(d);f&&(u.index=d.substring(f[0].length).trim()),i++}for(a(u),a(u),u.hunks=[];i<t.length;){var h=t[i];if(/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(h))break;if(/^@@/.test(h))u.hunks.push(l());else{if(h&&e.strict)throw new Error("Unknown line "+(i+1)+" "+JSON.stringify(h));i++}}}function a(u){var d=/^(---|\+\+\+)\s+/.exec(t[i]);if(d){var f=d[1]==="---"?"old":"new",h=t[i].substring(3).trim().split(" ",2),m=h[0].replace(/\\\\/g,"\\");m.startsWith('"')&&m.endsWith('"')&&(m=m.substr(1,m.length-2)),u[f+"FileName"]=m,u[f+"Header"]=(h[1]||"").trim(),i++}}function l(){var u=i,d=t[i++],f=d.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/),h={oldStart:+f[1],oldLines:typeof f[2]>"u"?1:+f[2],newStart:+f[3],newLines:typeof f[4]>"u"?1:+f[4],lines:[],linedelimiters:[]};h.oldLines===0&&(h.oldStart+=1),h.newLines===0&&(h.newStart+=1);for(var m=0,p=0;i<t.length&&!(t[i].indexOf("--- ")===0&&i+2<t.length&&t[i+1].indexOf("+++ ")===0&&t[i+2].indexOf("@@")===0);i++){var g=t[i].length==0&&i!=t.length-1?" ":t[i][0];if(g==="+"||g==="-"||g===" "||g==="\\")h.lines.push(t[i]),h.linedelimiters.push(s[i]||`
231
+ `),g==="+"?m++:g==="-"?p++:g===" "&&(m++,p++);else break}if(!m&&h.newLines===1&&(h.newLines=0),!p&&h.oldLines===1&&(h.oldLines=0),e.strict){if(m!==h.newLines)throw new Error("Added line count did not match for hunk at line "+(u+1));if(p!==h.oldLines)throw new Error("Removed line count did not match for hunk at line "+(u+1))}return h}for(;i<t.length;)o();return r}function ob(n,e,t){var s=!0,r=!1,i=!1,o=1;return function a(){if(s&&!i){if(r?o++:s=!1,n+o<=t)return o;i=!0}if(!r)return i||(s=!0),e<=n-o?-o++:(r=!0,a())}}function Nu(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(typeof e=="string"&&(e=ib(e)),Array.isArray(e)){if(e.length>1)throw new Error("applyPatch only works with a single input.");e=e[0]}var s=n.split(/\r\n|[\n\v\f\r\x85]/),r=n.match(/\r\n|[\n\v\f\r\x85]/g)||[],i=e.hunks,o=t.compareLine||function(E,k,Y,U){return k===U},a=0,l=t.fuzzFactor||0,u=0,d=0,f,h;function m(E,k){for(var Y=0;Y<E.lines.length;Y++){var U=E.lines[Y],ee=U.length>0?U[0]:" ",ne=U.length>0?U.substr(1):U;if(ee===" "||ee==="-"){if(!o(k+1,s[k],ee,ne)&&(a++,a>l))return!1;k++}}return!0}for(var p=0;p<i.length;p++){for(var g=i[p],x=s.length-g.oldLines,w=0,$=d+g.oldStart-1,A=ob($,u,x);w!==void 0;w=A())if(m(g,$+w)){g.offset=d+=w;break}if(w===void 0)return!1;u=g.offset+g.oldStart+g.oldLines}for(var y=0,v=0;v<i.length;v++){var b=i[v],S=b.oldStart+b.offset+y-1;y+=b.newLines-b.oldLines;for(var _=0;_<b.lines.length;_++){var T=b.lines[_],I=T.length>0?T[0]:" ",C=T.length>0?T.substr(1):T,N=b.linedelimiters&&b.linedelimiters[_]||`
232
+ `;if(I===" ")S++;else if(I==="-")s.splice(S,1),r.splice(S,1);else if(I==="+")s.splice(S,0,C),r.splice(S,0,N),S++;else if(I==="\\"){var H=b.lines[_-1]?b.lines[_-1][0]:null;H==="+"?f=!0:H==="-"&&(h=!0)}}}if(f)for(;!s[s.length-1];)s.pop(),r.pop();else h&&(s.push(""),r.push(`
233
+ `));for(var G=0;G<s.length-1;G++)s[G]=s[G]+r[G];return s.join("")}function ab(n,e,t,s,r,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Xy(t,s,o);if(!a)return;a.push({value:"",lines:[]});function l(w){return w.map(function($){return" "+$})}for(var u=[],d=0,f=0,h=[],m=1,p=1,g=function($){var A=a[$],y=A.lines||A.value.replace(/\n$/,"").split(`
234
+ `);if(A.lines=y,A.added||A.removed){var v;if(!d){var b=a[$-1];d=m,f=p,b&&(h=o.context>0?l(b.lines.slice(-o.context)):[],d-=h.length,f-=h.length)}(v=h).push.apply(v,to(y.map(function(G){return(A.added?"+":"-")+G}))),A.added?p+=y.length:m+=y.length}else{if(d)if(y.length<=o.context*2&&$<a.length-2){var S;(S=h).push.apply(S,to(l(y)))}else{var _,T=Math.min(y.length,o.context);(_=h).push.apply(_,to(l(y.slice(0,T))));var I={oldStart:d,oldLines:m-d+T,newStart:f,newLines:p-f+T,lines:h};if($>=a.length-2&&y.length<=o.context){var C=/\n$/.test(t),N=/\n$/.test(s),H=y.length==0&&h.length>I.oldLines;!C&&H&&t.length>0&&h.splice(I.oldLines,0,"\"),(!C&&!H||!N)&&h.push("\")}u.push(I),d=0,f=0,h=[]}m+=y.length,p+=y.length}},x=0;x<a.length;x++)g(x);return{oldFileName:n,newFileName:e,oldHeader:r,newHeader:i,hunks:u}}function Fu(n){if(Array.isArray(n))return n.map(Fu).join(`
235
235
  `);var e=[];n.oldFileName==n.newFileName&&e.push("Index: "+n.oldFileName),e.push("==================================================================="),e.push("--- "+n.oldFileName+(typeof n.oldHeader>"u"?"":" "+n.oldHeader)),e.push("+++ "+n.newFileName+(typeof n.newHeader>"u"?"":" "+n.newHeader));for(var t=0;t<n.hunks.length;t++){var s=n.hunks[t];s.oldLines===0&&(s.oldStart-=1),s.newLines===0&&(s.newStart-=1),e.push("@@ -"+s.oldStart+","+s.oldLines+" +"+s.newStart+","+s.newLines+" @@"),e.push.apply(e,s.lines)}return e.join(`
236
236
  `)+`
237
- `}function sb(n,e,t,s,r,i,o){return Mu(nb(n,e,t,s,r,i,o))}function Iu(n,e,t,s,r,i){return sb(n,n,e,t,s,r,i)}var xC,Tu,Ru,Ou,no,Vy,zy,Zy,Kn,to,Du=L(()=>{Ot.prototype={diff:function(e,t){var s,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=r.callback;typeof r=="function"&&(i=r,r={}),this.options=r;var o=this;function a(y){return i?(setTimeout(function(){i(void 0,y)},0),!0):y}e=this.castInput(e),t=this.castInput(t),e=this.removeEmpty(this.tokenize(e)),t=this.removeEmpty(this.tokenize(t));var l=t.length,u=e.length,d=1,f=l+u;r.maxEditLength&&(f=Math.min(f,r.maxEditLength));var h=(s=r.timeout)!==null&&s!==void 0?s:1/0,m=Date.now()+h,p=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(p[0],t,e,0);if(p[0].oldPos+1>=u&&g+1>=l)return a([{value:this.join(t),count:t.length}]);var x=-1/0,w=1/0;function $(){for(var y=Math.max(x,-d);y<=Math.min(w,d);y+=2){var v=void 0,b=p[y-1],S=p[y+1];b&&(p[y-1]=void 0);var _=!1;if(S){var T=S.oldPos-y;_=S&&0<=T&&T<l}var I=b&&b.oldPos+1<u;if(!_&&!I){p[y]=void 0;continue}if(!I||_&&b.oldPos+1<S.oldPos?v=o.addToPath(S,!0,void 0,0):v=o.addToPath(b,void 0,!0,1),g=o.extractCommon(v,t,e,y),v.oldPos+1>=u&&g+1>=l)return a(Wy(o,v.lastComponent,t,e,o.useLongestToken));p[y]=v,v.oldPos+1>=u&&(w=Math.min(w,y-1)),g+1>=l&&(x=Math.max(x,y+1))}d++}if(i)(function y(){setTimeout(function(){if(d>f||Date.now()>m)return i();$()||y()},0)})();else for(;d<=f&&Date.now()<=m;){var A=$();if(A)return A}},addToPath:function(e,t,s,r){var i=e.lastComponent;return i&&i.added===t&&i.removed===s?{oldPos:e.oldPos+r,lastComponent:{count:i.count+1,added:t,removed:s,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:s,previousComponent:i}}},extractCommon:function(e,t,s,r){for(var i=t.length,o=s.length,a=e.oldPos,l=a-r,u=0;l+1<i&&a+1<o&&this.equals(t[l+1],s[a+1]);)l++,a++,u++;return u&&(e.lastComponent={count:u,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,t){return this.options.comparator?this.options.comparator(e,t):e===t||this.options.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],s=0;s<e.length;s++)e[s]&&t.push(e[s]);return t},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};xC=new Ot,Tu=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Ru=/\S/,Ou=new Ot;Ou.equals=function(n,e){return this.options.ignoreCase&&(n=n.toLowerCase(),e=e.toLowerCase()),n===e||this.options.ignoreWhitespace&&!Ru.test(n)&&!Ru.test(e)};Ou.tokenize=function(n){for(var e=n.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),t=0;t<e.length-1;t++)!e[t+1]&&e[t+2]&&Tu.test(e[t])&&Tu.test(e[t+2])&&(e[t]+=e[t+2],e.splice(t+1,2),t--);return e};no=new Ot;no.tokenize=function(n){this.options.stripTrailingCr&&(n=n.replace(/\r\n/g,`
238
- `));var e=[],t=n.split(/(\n|\r\n)/);t[t.length-1]||t.pop();for(var s=0;s<t.length;s++){var r=t[s];s%2&&!this.options.newlineIsToken?e[e.length-1]+=r:(this.options.ignoreWhitespace&&(r=r.trim()),e.push(r))}return e};Vy=new Ot;Vy.tokenize=function(n){return n.split(/(\S.+?[.!?])(?=\s+|$)/)};zy=new Ot;zy.tokenize=function(n){return n.split(/([{}:;,]|\s+)/)};Zy=Object.prototype.toString,Kn=new Ot;Kn.useLongestToken=!0;Kn.tokenize=no.tokenize;Kn.castInput=function(n){var e=this.options,t=e.undefinedReplacement,s=e.stringifyReplacer,r=s===void 0?function(i,o){return typeof o>"u"?t:o}:s;return typeof n=="string"?n:JSON.stringify(eo(n,null,null,r),r," ")};Kn.equals=function(n,e){return Ot.prototype.equals.call(Kn,n.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};to=new Ot;to.tokenize=function(n){return n.slice()};to.join=to.removeEmpty=function(n){return n}});var Lu={};Ne(Lu,{applyDiff:()=>rb,formatDiffForDisplay:()=>ib,generateDiff:()=>Gs});function Gs(n,e,t){return Iu(n,e,t,"original","modified")}function rb(n,e){return Pu(n,e)}function ib(n){return n.split(`
237
+ `}function lb(n,e,t,s,r,i,o){return Fu(ab(n,e,t,s,r,i,o))}function ju(n,e,t,s,r,i){return lb(n,n,e,t,s,r,i)}var $C,Iu,Du,Lu,io,Qy,Zy,rb,Wn,ro,Hu=L(()=>{Ot.prototype={diff:function(e,t){var s,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=r.callback;typeof r=="function"&&(i=r,r={}),this.options=r;var o=this;function a(y){return i?(setTimeout(function(){i(void 0,y)},0),!0):y}e=this.castInput(e),t=this.castInput(t),e=this.removeEmpty(this.tokenize(e)),t=this.removeEmpty(this.tokenize(t));var l=t.length,u=e.length,d=1,f=l+u;r.maxEditLength&&(f=Math.min(f,r.maxEditLength));var h=(s=r.timeout)!==null&&s!==void 0?s:1/0,m=Date.now()+h,p=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(p[0],t,e,0);if(p[0].oldPos+1>=u&&g+1>=l)return a([{value:this.join(t),count:t.length}]);var x=-1/0,w=1/0;function $(){for(var y=Math.max(x,-d);y<=Math.min(w,d);y+=2){var v=void 0,b=p[y-1],S=p[y+1];b&&(p[y-1]=void 0);var _=!1;if(S){var T=S.oldPos-y;_=S&&0<=T&&T<l}var I=b&&b.oldPos+1<u;if(!_&&!I){p[y]=void 0;continue}if(!I||_&&b.oldPos+1<S.oldPos?v=o.addToPath(S,!0,void 0,0):v=o.addToPath(b,void 0,!0,1),g=o.extractCommon(v,t,e,y),v.oldPos+1>=u&&g+1>=l)return a(Jy(o,v.lastComponent,t,e,o.useLongestToken));p[y]=v,v.oldPos+1>=u&&(w=Math.min(w,y-1)),g+1>=l&&(x=Math.max(x,y+1))}d++}if(i)(function y(){setTimeout(function(){if(d>f||Date.now()>m)return i();$()||y()},0)})();else for(;d<=f&&Date.now()<=m;){var A=$();if(A)return A}},addToPath:function(e,t,s,r){var i=e.lastComponent;return i&&i.added===t&&i.removed===s?{oldPos:e.oldPos+r,lastComponent:{count:i.count+1,added:t,removed:s,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:s,previousComponent:i}}},extractCommon:function(e,t,s,r){for(var i=t.length,o=s.length,a=e.oldPos,l=a-r,u=0;l+1<i&&a+1<o&&this.equals(t[l+1],s[a+1]);)l++,a++,u++;return u&&(e.lastComponent={count:u,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,t){return this.options.comparator?this.options.comparator(e,t):e===t||this.options.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],s=0;s<e.length;s++)e[s]&&t.push(e[s]);return t},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};$C=new Ot,Iu=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Du=/\S/,Lu=new Ot;Lu.equals=function(n,e){return this.options.ignoreCase&&(n=n.toLowerCase(),e=e.toLowerCase()),n===e||this.options.ignoreWhitespace&&!Du.test(n)&&!Du.test(e)};Lu.tokenize=function(n){for(var e=n.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),t=0;t<e.length-1;t++)!e[t+1]&&e[t+2]&&Iu.test(e[t])&&Iu.test(e[t+2])&&(e[t]+=e[t+2],e.splice(t+1,2),t--);return e};io=new Ot;io.tokenize=function(n){this.options.stripTrailingCr&&(n=n.replace(/\r\n/g,`
238
+ `));var e=[],t=n.split(/(\n|\r\n)/);t[t.length-1]||t.pop();for(var s=0;s<t.length;s++){var r=t[s];s%2&&!this.options.newlineIsToken?e[e.length-1]+=r:(this.options.ignoreWhitespace&&(r=r.trim()),e.push(r))}return e};Qy=new Ot;Qy.tokenize=function(n){return n.split(/(\S.+?[.!?])(?=\s+|$)/)};Zy=new Ot;Zy.tokenize=function(n){return n.split(/([{}:;,]|\s+)/)};rb=Object.prototype.toString,Wn=new Ot;Wn.useLongestToken=!0;Wn.tokenize=io.tokenize;Wn.castInput=function(n){var e=this.options,t=e.undefinedReplacement,s=e.stringifyReplacer,r=s===void 0?function(i,o){return typeof o>"u"?t:o}:s;return typeof n=="string"?n:JSON.stringify(so(n,null,null,r),r," ")};Wn.equals=function(n,e){return Ot.prototype.equals.call(Wn,n.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};ro=new Ot;ro.tokenize=function(n){return n.slice()};ro.join=ro.removeEmpty=function(n){return n}});var Bu={};Ne(Bu,{applyDiff:()=>cb,formatDiffForDisplay:()=>ub,generateDiff:()=>zs});function zs(n,e,t){return ju(n,e,t,"original","modified")}function cb(n,e){return Nu(n,e)}function ub(n){return n.split(`
239
239
  `).map(t=>t.startsWith("+")&&!t.startsWith("+++")?`\x1B[32m${t}\x1B[0m`:t.startsWith("-")&&!t.startsWith("---")?`\x1B[31m${t}\x1B[0m`:t.startsWith("@@")?`\x1B[36m${t}\x1B[0m`:t).join(`
240
- `)}var so=L(()=>{"use strict";Du()});async function bn(n,e){let t=[],s=Ae.join(n,"package.json");if(he.existsSync(s))try{let o=JSON.parse(he.readFileSync(s,"utf-8"));t.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&t.push(`Description: ${o.description}`);let a=Object.keys(o.dependencies||{}).concat(Object.keys(o.devDependencies||{}));a.length>0&&t.push(`Key deps: ${a.slice(0,15).join(", ")}${a.length>15?"...":""}`)}catch{}if(e?.workspace?.frameworkDetection){let o=Us(n);t.push(`Framework: ${o.framework}`),t.push(`Language: ${o.language}`),t.push(`Package Manager: ${o.packageManager}`),o.hasDocker&&t.push("Docker: detected"),o.hasCICD&&t.push("CI/CD: detected"),o.hasTests&&t.push("Tests: detected")}if(e?.workspace?.gitAwareness)try{let o=await Ui(n);o&&(t.push(`Git branch: ${o.branch}`),o.modified.length>0&&t.push(`Modified files: ${o.modified.length}`),o.staged.length>0&&t.push(`Staged files: ${o.staged.length}`))}catch{}if(e?.workspace?.envParsing){let a=[".env",".env.local",".env.development",".env.production"].filter(l=>he.existsSync(Ae.join(n,l)));a.length>0&&t.push(`Env files: ${a.join(", ")}`)}let i=["tsconfig.json",".eslintrc.json","vite.config.ts","next.config.js","tailwind.config.js"].filter(o=>he.existsSync(Ae.join(n,o)));if(i.length>0&&t.push(`Config: ${i.join(", ")}`),e?.context?.projectGraph)try{let o=he.readdirSync(n).filter(a=>!["node_modules",".git","dist","build",".next",".cache"].includes(a)).filter(a=>!a.startsWith(".")).slice(0,25);o.length>0&&t.push(`Structure: ${o.join(", ")}`)}catch{}else try{let o=he.readdirSync(n).filter(a=>!["node_modules",".git","dist","build",".next",".cache"].includes(a)).filter(a=>!a.startsWith(".")).slice(0,20);o.length>0&&t.push(`Structure: ${o.join(", ")}`)}catch{}return t.push(`Directory: ${n}`),e?.agents?.enabled&&(t.push("Multi-Agent: enabled (Team Leader: Hablas)"),t.push("Team: @Hablas (Leader), @Bob (Architect), @Alex (Engineer), @David (Data Analyst), @Emma (Product Manager)")),t.join(`
241
- `)}function vn(n,e,t,s){let r=n+`
240
+ `)}var oo=L(()=>{"use strict";Hu()});async function vn(n,e){let t=[],s=$e.join(n,"package.json");if(me.existsSync(s))try{let o=JSON.parse(me.readFileSync(s,"utf-8"));t.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&t.push(`Description: ${o.description}`);let a=Object.keys(o.dependencies||{}).concat(Object.keys(o.devDependencies||{}));a.length>0&&t.push(`Key deps: ${a.slice(0,15).join(", ")}${a.length>15?"...":""}`)}catch{}if(e?.workspace?.frameworkDetection){let o=Ks(n);t.push(`Framework: ${o.framework}`),t.push(`Language: ${o.language}`),t.push(`Package Manager: ${o.packageManager}`),o.hasDocker&&t.push("Docker: detected"),o.hasCICD&&t.push("CI/CD: detected"),o.hasTests&&t.push("Tests: detected")}if(e?.workspace?.gitAwareness)try{let o=await Wi(n);o&&(t.push(`Git branch: ${o.branch}`),o.modified.length>0&&t.push(`Modified files: ${o.modified.length}`),o.staged.length>0&&t.push(`Staged files: ${o.staged.length}`))}catch{}if(e?.workspace?.envParsing){let a=[".env",".env.local",".env.development",".env.production"].filter(l=>me.existsSync($e.join(n,l)));a.length>0&&t.push(`Env files: ${a.join(", ")}`)}let i=["tsconfig.json",".eslintrc.json","vite.config.ts","next.config.js","tailwind.config.js"].filter(o=>me.existsSync($e.join(n,o)));if(i.length>0&&t.push(`Config: ${i.join(", ")}`),e?.context?.projectGraph)try{let o=me.readdirSync(n).filter(a=>!["node_modules",".git","dist","build",".next",".cache"].includes(a)).filter(a=>!a.startsWith(".")).slice(0,25);o.length>0&&t.push(`Structure: ${o.join(", ")}`)}catch{}else try{let o=me.readdirSync(n).filter(a=>!["node_modules",".git","dist","build",".next",".cache"].includes(a)).filter(a=>!a.startsWith(".")).slice(0,20);o.length>0&&t.push(`Structure: ${o.join(", ")}`)}catch{}return t.push(`Directory: ${n}`),e?.agents?.enabled&&(t.push("Multi-Agent: enabled (Team Leader: Hablas)"),t.push("Team: @Hablas (Leader), @Bob (Architect), @Alex (Engineer), @David (Data Analyst), @Emma (Product Manager)")),t.join(`
241
+ `)}function wn(n,e,t,s){let r=n+`
242
242
 
243
243
  ## Current Project
244
244
  `+e;if(t){let i=t.getSummary();i&&(r+=`
@@ -248,14 +248,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
248
248
  ## Shared Context
249
249
  `+i)}return r+=`
250
250
 
251
- `+Jc(),r}async function ob(n){try{if(!he.existsSync(ro))return null;let t=(await jt.readdir(ro)).filter(f=>f.endsWith(".bak"));if(n){let f=Ae.basename(n);t=t.filter(h=>h.startsWith(`${f}.`))}if(t.length===0)return null;t.sort().reverse();let s=t[0],r=Ae.join(ro,s),i=s.replace(".bak","").split("."),o=parseInt(i[i.length-1],10),a=i.slice(0,-1).join("."),l=Date.now()-o,u=Math.floor(l/6e4),d=u<1?"just now":u<60?`${u} minutes ago`:`${Math.floor(u/60)} hours ago`;return{backupPath:r,originalName:a,age:d}}catch{return null}}async function Fu(n,e,t,s,r,i,o,a,l,u,d,f,h,m,p,g,x){let w=n.split(/\s+/),$=w[0],A=w.slice(1).join(" ");switch($){case"/quit":case"/exit":return"quit";case"/help":console.log(hu()),console.log(c.muted(" Model & Provider:")),console.log(c.muted(" /addmodel Interactive wizard to add a custom API")),console.log(c.muted(" /listmodels Show saved providers")),console.log(c.muted(" /removemodel <name> Remove a saved provider")),console.log(c.muted(" /usemodel <name> Switch to a saved provider")),console.log(c.muted(" /models [page|search] Browse all available models")),console.log(c.muted(" /provider Show/switch API provider")),console.log(),console.log(c.muted(" Aliases & Plugins:")),console.log(c.muted(" /alias Show all aliases")),console.log(c.muted(" /alias set <n> <cmd> Create an alias")),console.log(c.muted(" /alias del <name> Remove an alias")),console.log(c.muted(" /plugins List installed plugins")),console.log(c.muted(" /doctor Run system diagnostics")),console.log(),console.log(c.muted(" Task & Memory:")),console.log(c.muted(" /task add <desc> Add a task to the queue")),console.log(c.muted(" /task list Show all tasks")),console.log(c.muted(" /task clear Clear task queue")),console.log(c.muted(" /memory Show project memory")),console.log(c.muted(" /memory set <k> <v> Store a memory")),console.log(c.muted(" /memory del <key> Delete a memory")),console.log(c.muted(" /memory clear Clear all memory")),console.log(),console.log(c.muted(" Multi-Agent & Tools:")),console.log(c.muted(" /team Show team roster")),console.log(c.muted(" /delegate <agent> <t> Manually assign task to agent")),console.log(c.muted(" /agents Multi-agent system control")),console.log(c.muted(" /agents on|off Enable/disable multi-agent")),console.log(c.muted(" /agents status Show agent details")),console.log(c.muted(" /security Run security scan")),console.log(c.muted(" /git status Show git status")),console.log(c.muted(" /workspace Show workspace info")),console.log(c.muted(" /stats Show usage analytics")),console.log();break;case"/about":console.log(lu());break;case"/version":console.log(cu());break;case"/model":if(A){let y=await t.listModels();t.setModel(A);try{let v=zt();v.hablas||(v.hablas={model:A,temperature:.7}),v.hablas.model=A,Ei(v),typeof x<"u"&&x&&x.reloadModels(),console.log(pe(" [Phase 3] Synced to agents.json for @Hablas (team uses on next full turn)"))}catch{}y.includes(A)?console.log(z(`Model: ${A}`)):console.log(j(`Model set to "${A}" (not found locally)`))}else console.log(pe(`Current model: ${t.getModel()}`)),console.log(c.muted(" Usage: /model <name>"));break;case"/models":{let y=A.trim(),v=1,b="";if(y){let k=parseInt(y);!isNaN(k)&&k>0?v=k:b=y.toLowerCase()}let S=new Ge("Fetching models");S.start();let _=await t.listModels();if(S.stop(_.length>0?`${_.length} found`:void 0),_.length===0){console.log(j("No models found \u2014 check your connection")),console.log(c.muted(" Use /provider test to verify"));break}let T=_;if(b&&(T=_.filter(k=>k.toLowerCase().includes(b)),T.length===0)){console.log(j(`No models matching: "${b}"`)),console.log(c.muted(` ${_.length} models available. Try a different search.`));break}let I=20,C=Math.ceil(T.length/I),F=Math.max(1,Math.min(v,C)),H=(F-1)*I,G=H+I,E=T.slice(H,G);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Available Models")} ${c.muted(`(${T.length} total \xB7 page ${F}/${C})`)}`),console.log();for(let k=0;k<E.length;k++){let Y=H+k+1,Z=E[k]===t.getModel()?` ${c.success("\u25CF active")}`:"";console.log(` ${c.muted(String(Y).padStart(3," "))}. ${c.secondary(E[k])}${Z}`)}console.log(),C>1&&console.log(c.muted(` /models ${F<C?F+1:1} \u2014 next page`)),b&&console.log(c.muted(` Filtered: ${T.length} of ${_.length} (query: "${b}")`)),console.log(c.muted(" /models <query> \u2014 search \xB7 /model <id> \u2014 switch")),console.log();break}case"/tree":{let y=s.get("list_dir");if(y){let v=await y.execute({path:".",depth:3});console.log(`
251
+ `+tu(),r}async function db(n){try{if(!me.existsSync(ao))return null;let t=(await jt.readdir(ao)).filter(f=>f.endsWith(".bak"));if(n){let f=$e.basename(n);t=t.filter(h=>h.startsWith(`${f}.`))}if(t.length===0)return null;t.sort().reverse();let s=t[0],r=$e.join(ao,s),i=s.replace(".bak","").split("."),o=parseInt(i[i.length-1],10),a=i.slice(0,-1).join("."),l=Date.now()-o,u=Math.floor(l/6e4),d=u<1?"just now":u<60?`${u} minutes ago`:`${Math.floor(u/60)} hours ago`;return{backupPath:r,originalName:a,age:d}}catch{return null}}async function Uu(n,e,t,s,r,i,o,a,l,u,d,f,h,m,p,g,x){let w=n.split(/\s+/),$=w[0],A=w.slice(1).join(" ");switch($){case"/quit":case"/exit":return"quit";case"/help":console.log(vu()),console.log(c.muted(" Model & Provider:")),console.log(c.muted(" /addmodel Interactive wizard to add a custom API")),console.log(c.muted(" /listmodels Show saved providers")),console.log(c.muted(" /removemodel <name> Remove a saved provider")),console.log(c.muted(" /usemodel <name> Switch to a saved provider")),console.log(c.muted(" /models [page|search] Browse all available models")),console.log(c.muted(" /provider Show/switch API provider")),console.log(),console.log(c.muted(" Aliases & Plugins:")),console.log(c.muted(" /alias Show all aliases")),console.log(c.muted(" /alias set <n> <cmd> Create an alias")),console.log(c.muted(" /alias del <name> Remove an alias")),console.log(c.muted(" /plugins List installed plugins")),console.log(c.muted(" /doctor Run system diagnostics")),console.log(),console.log(c.muted(" Task & Memory:")),console.log(c.muted(" /task add <desc> Add a task to the queue")),console.log(c.muted(" /task list Show all tasks")),console.log(c.muted(" /task clear Clear task queue")),console.log(c.muted(" /memory Show project memory")),console.log(c.muted(" /memory set <k> <v> Store a memory")),console.log(c.muted(" /memory del <key> Delete a memory")),console.log(c.muted(" /memory clear Clear all memory")),console.log(),console.log(c.muted(" Multi-Agent & Tools:")),console.log(c.muted(" /team Show team roster")),console.log(c.muted(" /delegate <agent> <t> Manually assign task to agent")),console.log(c.muted(" /agents Multi-agent system control")),console.log(c.muted(" /agents on|off Enable/disable multi-agent")),console.log(c.muted(" /agents status Show agent details")),console.log(c.muted(" /security Run security scan")),console.log(c.muted(" /git status Show git status")),console.log(c.muted(" /workspace Show workspace info")),console.log(c.muted(" /stats Show usage analytics")),console.log();break;case"/about":console.log(pu());break;case"/version":console.log(hu());break;case"/model":if(A){let y=await t.listModels();t.setModel(A);try{let v=Yt();v.hablas||(v.hablas={model:A,temperature:.7}),v.hablas.model=A,Oi(v),typeof x<"u"&&x&&x.reloadModels(),console.log(pe(" [Phase 3] Synced to agents.json for @Hablas (team uses on next full turn)"))}catch{}y.includes(A)?console.log(z(`Model: ${A}`)):console.log(j(`Model set to "${A}" (not found locally)`))}else console.log(pe(`Current model: ${t.getModel()}`)),console.log(c.muted(" Usage: /model <name>"));break;case"/models":{let y=A.trim(),v=1,b="";if(y){let k=parseInt(y);!isNaN(k)&&k>0?v=k:b=y.toLowerCase()}let S=new Ve("Fetching models");S.start();let _=await t.listModels();if(S.stop(_.length>0?`${_.length} found`:void 0),_.length===0){console.log(j("No models found \u2014 check your connection")),console.log(c.muted(" Use /provider test to verify"));break}let T=_;if(b&&(T=_.filter(k=>k.toLowerCase().includes(b)),T.length===0)){console.log(j(`No models matching: "${b}"`)),console.log(c.muted(` ${_.length} models available. Try a different search.`));break}let I=20,C=Math.ceil(T.length/I),N=Math.max(1,Math.min(v,C)),H=(N-1)*I,G=H+I,E=T.slice(H,G);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Available Models")} ${c.muted(`(${T.length} total \xB7 page ${N}/${C})`)}`),console.log();for(let k=0;k<E.length;k++){let Y=H+k+1,ee=E[k]===t.getModel()?` ${c.success("\u25CF active")}`:"";console.log(` ${c.muted(String(Y).padStart(3," "))}. ${c.secondary(E[k])}${ee}`)}console.log(),C>1&&console.log(c.muted(` /models ${N<C?N+1:1} \u2014 next page`)),b&&console.log(c.muted(` Filtered: ${T.length} of ${_.length} (query: "${b}")`)),console.log(c.muted(" /models <query> \u2014 search \xB7 /model <id> \u2014 switch")),console.log();break}case"/tree":{let y=s.get("list_dir");if(y){let v=await y.execute({path:".",depth:3});console.log(`
252
252
  ${v.output}
253
- `)}break}case"/status":{let y=await t.checkConnection(),v=u?u.getActiveName():"planner",b=f?f.size():0,S=d?d.getProgress():void 0;console.log(pu({model:t.getModel(),host:e.ollamaHost,directory:o,cacheFiles:r.getCacheSize(),cacheTokens:r.getTotalTokens(),budgetTokens:e.contextBudget,connected:y,turnCount:l,mindset:v})),b>0&&console.log(c.muted(` Memory entries: ${b}`)),S&&S.total>0&&console.log(c.muted(` Tasks: ${S.done}/${S.total} done`)),console.log();break}case"/clear":r.clear(),i.clear(),console.log(z("History cleared"));break;case"/history":{let y=parseInt(A)||10,v=i.getHistory().slice(-y);if(v.length===0){console.log(pe("No history yet"));break}console.log(),v.forEach(b=>{let S=b.role==="user"?c.primary("You"):b.role==="assistant"?c.success("Hablas"):c.muted("tool"),_=b.content.slice(0,120).replace(/\n/g," ");console.log(` ${S}: ${c.muted(_)}`)}),console.log();break}case"/undo":{if(!g){let y=await ob(A||void 0);if(!y){console.log(j("No backups found"));break}let v=A?Ae.resolve(o,A):Ae.resolve(o,y.originalName);if(await a.confirm(`Restore ${y.originalName} from backup (${y.age})?`))try{let S=await jt.readFile(y.backupPath,"utf-8");await jt.writeFile(v,S,"utf-8"),console.log(z(`Restored ${y.originalName} from backup (${y.age})`))}catch(S){console.log(ke(`Failed: ${S.message}`))}break}if(A==="list")console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Undo History")} (${g.getUndoableCount()} changes)`),console.log(),console.log(g.formatList(20)),console.log();else if(A==="all"){let y=g.getUndoableCount();if(y===0){console.log(pe("Nothing to undo"));break}if(await a.confirm(`Undo ALL ${y} changes?`)){let b=await g.undoAll(),S=b.filter(_=>_.success).length;console.log(z(`Reverted ${S}/${b.length} changes`))}}else{let y=A&&parseInt(A)||1;if(g.getUndoableCount()===0){console.log(pe("Nothing to undo"));break}let v=await g.undo(y);for(let b of v)b.success?console.log(z(`Reverted: ${b.file}`)):console.log(ke(`Failed to revert ${b.file}: ${b.error}`))}break}case"/config":console.log(`
253
+ `)}break}case"/status":{let y=await t.checkConnection(),v=u?u.getActiveName():"planner",b=f?f.size():0,S=d?d.getProgress():void 0;console.log(bu({model:t.getModel(),host:e.ollamaHost,directory:o,cacheFiles:r.getCacheSize(),cacheTokens:r.getTotalTokens(),budgetTokens:e.contextBudget,connected:y,turnCount:l,mindset:v})),b>0&&console.log(c.muted(` Memory entries: ${b}`)),S&&S.total>0&&console.log(c.muted(` Tasks: ${S.done}/${S.total} done`)),console.log();break}case"/clear":r.clear(),i.clear(),console.log(z("History cleared"));break;case"/history":{let y=parseInt(A)||10,v=i.getHistory().slice(-y);if(v.length===0){console.log(pe("No history yet"));break}console.log(),v.forEach(b=>{let S=b.role==="user"?c.primary("You"):b.role==="assistant"?c.success("Hablas"):c.muted("tool"),_=b.content.slice(0,120).replace(/\n/g," ");console.log(` ${S}: ${c.muted(_)}`)}),console.log();break}case"/undo":{if(!g){let y=await db(A||void 0);if(!y){console.log(j("No backups found"));break}let v=A?$e.resolve(o,A):$e.resolve(o,y.originalName);if(await a.confirm(`Restore ${y.originalName} from backup (${y.age})?`))try{let S=await jt.readFile(y.backupPath,"utf-8");await jt.writeFile(v,S,"utf-8"),console.log(z(`Restored ${y.originalName} from backup (${y.age})`))}catch(S){console.log(Ae(`Failed: ${S.message}`))}break}if(A==="list")console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Undo History")} (${g.getUndoableCount()} changes)`),console.log(),console.log(g.formatList(20)),console.log();else if(A==="all"){let y=g.getUndoableCount();if(y===0){console.log(pe("Nothing to undo"));break}if(await a.confirm(`Undo ALL ${y} changes?`)){let b=await g.undoAll(),S=b.filter(_=>_.success).length;console.log(z(`Reverted ${S}/${b.length} changes`))}}else{let y=A&&parseInt(A)||1;if(g.getUndoableCount()===0){console.log(pe("Nothing to undo"));break}let v=await g.undo(y);for(let b of v)b.success?console.log(z(`Reverted: ${b.file}`)):console.log(Ae(`Failed to revert ${b.file}: ${b.error}`))}break}case"/config":console.log(`
254
254
  ${c.muted(JSON.stringify(e,null,2))}
255
- `),console.log(c.muted(" ~/.hablas/config.json")),console.log();break;case"/mindset":{if(!u){console.log(j("Mindset system not available"));break}if(A)if(u.setActive(A)){let v=u.getActive(),b=await bn(o,e),S=vn(v.systemPrompt,b,f,m);i.updateSystemPrompt(S),console.log(z(`Mindset: ${v.name} \u2014 ${v.description}`))}else{let v=u.listNames().join(", ");console.log(Be(`Unknown mindset: "${A}"`,`Available: ${v}`))}else{let y=u.getActive();y&&console.log(pe(`Current mindset: ${y.name} \u2014 ${y.description}`)),console.log(c.muted(" Usage: /mindset <name>")),console.log(c.muted(" See /mindsets for available options"))}break}case"/mindsets":{if(!u){console.log(j("Mindset system not available"));break}let y=u.list(),v=u.getActiveName();console.log();for(let b of y){let _=b.name===v?c.success(" \u25CF active"):"";console.log(` ${c.accent("\u25C6")} ${c.primary(b.name)}${_}`),console.log(` ${c.muted(b.description)}`)}console.log(),console.log(c.muted(" Switch: /mindset <name>")),console.log();break}case"/task":{if(!d){console.log(j("Task queue not available"));break}let y=w[1],v=w.slice(2).join(" ");switch(y){case"add":if(v){let b=d.add(v);console.log(z(`Task #${b.id} added: ${v}`))}else console.log(j("Usage: /task add <description>"));break;case"list":console.log(),console.log(d.render()),console.log();break;case"done":{let b=parseInt(v);b?(d.complete(b),console.log(z(`Task #${b} marked as done`))):console.log(j("Usage: /task done <id>"));break}case"fail":{let b=parseInt(v);b?(d.fail(b,"Manually marked as failed"),console.log(j(`Task #${b} marked as failed`))):console.log(j("Usage: /task fail <id>"));break}case"clear":d.clear(),console.log(z("Task queue cleared"));break;default:console.log(),console.log(d.render()),console.log(),console.log(c.muted(" /task add <desc> \u2014 Add a task")),console.log(c.muted(" /task list \u2014 Show all tasks")),console.log(c.muted(" /task done <id> \u2014 Mark task as done")),console.log(c.muted(" /task fail <id> \u2014 Mark task as failed")),console.log(c.muted(" /task clear \u2014 Clear all tasks")),console.log()}break}case"/addmodel":{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Add Custom API Provider")}`),console.log();let v=(await a.prompt(` ${c.muted("Provider name (e.g. OpenAI, Groq):")} `)).trim();if(!v){console.log(j("Cancelled \u2014 name is required"));break}let S=(await a.prompt(` ${c.muted("API URL (e.g. https://api.openai.com/v1):")} `)).trim();if(!S){console.log(j("Cancelled \u2014 URL is required"));break}let T=(await a.prompt(` ${c.muted("API Key (leave empty if none):")} `)).trim(),C=(await a.prompt(` ${c.muted("Default model ID (e.g. gpt-4o):")} `)).trim()||"default",F={name:v,apiUrl:S,apiKey:T,models:[C],defaultModel:C,addedAt:new Date().toISOString()};tt(F),console.log(),console.log(z(`Provider "${v}" saved!`)),console.log(c.muted(` Use: /usemodel ${v}`)),console.log();break}case"/listmodels":{let y=Vt();console.log(),console.log(_c(y.providers,y.activeProvider));break}case"/removemodel":{let y=A.trim();if(!y){console.log(j("Usage: /removemodel <provider-name>"));break}if(wc(y))console.log(z(`Provider "${y}" removed`));else{console.log(j(`Provider "${y}" not found`));let b=Os();b.length>0&&console.log(c.muted(` Available: ${b.map(S=>S.name).join(", ")}`))}break}case"/usemodel":{let y=A.trim();if(!y){console.log(j("Usage: /usemodel <provider-name> [model-id]"));let F=Os();F.length>0&&console.log(c.muted(` Available: ${F.map(H=>H.name).join(", ")}`));break}let v=y.split(/\s+/),b=v[0],S=v[1],_=xc(b);if(!_){console.log(j(`Provider "${b}" not found`));let F=Os();F.length>0&&console.log(c.muted(` Available: ${F.map(H=>H.name).join(", ")}`));break}e.provider="custom",e.apiUrl=_.apiUrl,e.apiKey=_.apiKey,e.model=S||_.defaultModel;let T=Me(e);h&&h(T),Sc(_.name,e.model),console.log(z(`Switched to ${_.name} \xB7 Model: ${e.model}`));let I=new Ge("Testing");I.start();let C=await T.checkConnection();I.stop(C?"connected":void 0),C||console.log(j("Connection test failed \u2014 check URL and key"));break}case"/provider":{let y=w[1],v=w.slice(2).join(" ");if(!y){let b=Rs(e);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Provider")}: ${b}`),console.log(` ${c.muted("Model")}: ${c.highlight(t.getModel())}`),e.provider==="custom"?(console.log(` ${c.muted("API URL")}: ${e.apiUrl}`),console.log(` ${c.muted("API Key")}: ${e.apiKey?"***"+e.apiKey.slice(-4):"not set"}`)):console.log(` ${c.muted("Host")}: ${e.ollamaHost}`),console.log(),console.log(c.muted(" /provider ollama \u2014 Switch to local Ollama")),console.log(c.muted(" /provider nvidia <key> \u2014 Switch to NVIDIA NIM")),console.log(c.muted(" /provider custom <url> [key] \u2014 Switch to custom API")),console.log(c.muted(" /provider test \u2014 Test current connection")),console.log();break}switch(y){case"ollama":{e.provider="ollama",e.apiUrl="",e.apiKey="";let b=Me(e);h&&h(b),console.log(z("Switched to Ollama (local)"));break}case"nvidia":{let b=w[2];if(!b&&!e.apiKey){console.log(j("Usage: /provider nvidia <api-key>")),console.log(c.muted(" Get your key at: https://build.nvidia.com/"));break}e.provider="nvidia",e.apiUrl=Nt.apiUrl,b&&(e.apiKey=b),(!e.model||!Nt.models.includes(e.model))&&(e.model=Nt.defaultModel);let S=Me(e);h&&h(S),console.log(z(`Switched to NVIDIA NIM \xB7 Model: ${e.model}`)),console.log(c.muted(` Available models: ${Nt.models.length}`));let _=new Ge("Testing NVIDIA connection");_.start();let T=await S.checkConnection();_.stop(T?"connected":void 0),T||(console.log(j("Connection test failed \u2014 check your API key")),console.log(c.muted(" Get key: https://build.nvidia.com/")));break}case"custom":{let b=w[2],S=w[3];if(!b){console.log(j("Usage: /provider custom <api-url> [api-key]")),console.log(c.muted(" Example: /provider custom https://api.openai.com/v1 sk-..."));break}e.provider="custom",e.apiUrl=b,S&&(e.apiKey=S);let _=Me(e);h&&h(_),console.log(z(`Switched to Custom API: ${b}`)),!S&&!e.apiKey&&console.log(j("No API key set. Use: /provider custom <url> <key>"));break}case"test":{let b=new Ge("Testing connection");b.start();let S=await t.checkConnection();if(b.stop(S?"connected":void 0),S){let _=await t.listModels();console.log(z(`Connected! ${_.length} models available.`)),_.length>0&&console.log(c.muted(` Models: ${_.slice(0,5).join(", ")}${_.length>5?"...":""}`))}else console.log(ke("Connection failed"));break}case"key":{v?(e.apiKey=w[2],t instanceof Gt&&t.setApiKey(e.apiKey),console.log(z("API key updated"))):console.log(j("Usage: /provider key <api-key>"));break}default:console.log(Be(`Unknown: /provider ${y}`,"Type /provider for help"))}break}case"/memory":{if(!f){console.log(j("Project memory not available"));break}let y=w[1],v=w.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],S=v.slice(1).join(" ");f.set(b,S),console.log(z(`Memory stored: ${b}`));let _=u?.getActive(),T=_?_.systemPrompt:Wn,I=await bn(o,e);i.updateSystemPrompt(vn(T,I,f,m))}else console.log(j("Usage: /memory set <key> <value>"));break}case"del":case"delete":{if(v[0]){let b=f.delete(v[0]);console.log(b?z(`Memory deleted: ${v[0]}`):j(`Memory key not found: ${v[0]}`))}else console.log(j("Usage: /memory del <key>"));break}case"search":{if(v[0]){let b=f.search(v.join(" "));b.length>0?(console.log(),b.forEach(S=>console.log(` \xB7 ${S.entry.key}: ${S.entry.value}`)),console.log()):console.log(pe("No matching memories found"))}else console.log(j("Usage: /memory search <query>"));break}case"clear":f.clear(),console.log(z("Project memory cleared"));break;default:console.log(),console.log(f.render()),console.log(),console.log(c.muted(" /memory set <k> <v> \u2014 Store a memory")),console.log(c.muted(" /memory del <key> \u2014 Delete a memory")),console.log(c.muted(" /memory search <q> \u2014 Search memories")),console.log(c.muted(" /memory clear \u2014 Clear all")),console.log()}break}case"/alias":{let y=w[1],v=w.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],S=v.slice(1).join(" ");$c(b,S),console.log(z(`Alias set: ${b} \u2192 ${S}`))}else console.log(j("Usage: /alias set <name> <expansion>"));break}case"del":case"remove":{if(v[0]){let b=Cc(v[0]);console.log(b?z(`Alias removed: ${v[0]}`):j(`Alias not found: ${v[0]}`))}else console.log(j("Usage: /alias del <name>"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Aliases")}`),console.log(),console.log(Tc()),console.log(),console.log(c.muted(" /alias set <name> <cmd> \u2014 Create alias")),console.log(c.muted(" /alias del <name> \u2014 Remove alias")),console.log()}break}case"/doctor":{let y=new Ge("Running diagnostics");y.start();let v=await Ai({ollamaHost:e.ollamaHost,model:t.getModel(),provider:e.provider,apiUrl:e.apiUrl});y.stop(),console.log($i(v));break}case"/plugins":{let y=w[1],v=w.slice(2).join(" ");switch(y){case"enable":v?(wi(v),console.log(z(`Plugin "${v}" enabled`))):console.log(j("Usage: /plugins enable <name>"));break;case"disable":v?(xi(v),console.log(j(`Plugin "${v}" disabled`))):console.log(j("Usage: /plugins disable <name>"));break;default:Fs(),console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plugins")}`),console.log(),console.log(Si()),console.log(),console.log(c.muted(" /plugins enable <name> \u2014 Enable plugin")),console.log(c.muted(" /plugins disable <name> \u2014 Disable plugin")),console.log(c.muted(" Directory: ~/.hablas/plugins/")),console.log()}break}case"/mode":{let y=w[1]?.toLowerCase();console.log(),console.log(` ${c.accent("\u2605")} ${c.strong("Mode Selection")}`),console.log(),console.log(` Current: ${c.strong("BUILD")} \u2014 Full Multi-Agent Team at Maximum Power`),console.log(" (Hablas + Bob + Alex + David + Emma + rich theatre)"),console.log(),console.log(" Available modes:"),console.log(` ${c.highlight("build")} \u2014 Full team for complete serious work (recommended default)`),console.log(` ${c.highlight("design")} \u2014 Focused team for architecture, PRDs, blueprints`),console.log(` ${c.highlight("ask")} \u2014 Quick solo answers`),console.log(),console.log(` Usage: /mode build or just use 'hablas build "task"' for one-shot`),console.log(" Note: In plain REPL, everything runs in BUILD mode (full team) by default."),console.log(),(y==="build"||y==="design"||y==="ask")&&(console.log(z(`Acknowledged mode preference: ${y.toUpperCase()}`)),console.log(c.muted(" (The next input will be handled accordingly. Use subcommands for direct execution.)")));break}case"/agents":{let y=w[1];if(y==="on")e.agents.enabled=!0,console.log(z("Multi-agent orchestration enabled"));else if(y==="off")e.agents.enabled=!1,console.log(z("Multi-agent orchestration disabled"));else if(y==="status")console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Multi-Agent System")}`),console.log(` Status: ${e.agents.enabled?c.success("enabled"):c.muted("disabled")}`),console.log(` Orchestration: ${e.agents.orchestration}`),console.log(` Max concurrent: ${e.agents.maxConcurrent}`),console.log(),console.log(` ${c.strong("Team:")}`),console.log(Lc()),console.log();else if(y==="models"){let v=w.slice(2);if(v.length>=2){let b=v[0].toLowerCase(),S=v[1],_=["hablas","bob","alex","david","emma","gate"];if(!_.includes(b)){console.log(j(`Unknown role: ${b}. Valid: ${_.join(", ")}`));break}let T=zt();T[b]||(T[b]={model:S,temperature:.5}),T[b].model=S,Ei(T),x&&x.reloadModels(),console.log(z(`Agent model updated: @${b} \u2192 ${S}`)),console.log(c.muted(` Saved to ${Ti()}`))}else{let b=zt();console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Agent Models")}`),console.log();for(let S of we){let _=b[S.role];console.log(_?` ${c.primary(S.name.padEnd(8))} \u2192 ${c.highlight(_.model)}${_.temperature!==void 0?c.muted(` (temp: ${_.temperature})`):""}`:` ${c.primary(S.name.padEnd(8))} \u2192 ${c.muted("(default)")}`)}console.log(),console.log(c.muted(` Config: ${Ti()}`)),console.log(c.muted(" Usage: /agents models <role> <model> (e.g. /agents models alex qwen/qwen2.5-coder-32b-instruct)")),console.log()}}else console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Multi-Agent System")}: ${e.agents.enabled?c.success("ON"):c.muted("OFF")}`),console.log(),console.log(c.muted(" /agents on \u2014 Enable multi-agent orchestration")),console.log(c.muted(" /agents off \u2014 Disable multi-agent orchestration")),console.log(c.muted(" /agents status \u2014 Show agent details")),console.log(c.muted(" /agents models \u2014 Show model per agent")),console.log(c.muted(" /team \u2014 Show team roster")),console.log();break}case"/security":{console.log(),console.log(` ${c.accent("\u{1F512}")} Running security scan...`);let y=ji(o);console.log(Hi(y));break}case"/git":{if(w[1]==="status")try{let{getGitStatus:v,formatGitStatus:b}=await Promise.resolve().then(()=>(pn(),qn)),S=await v(o);S?(console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Git Status")}`),console.log(b(S)),console.log()):console.log(j("Not a git repository"))}catch{console.log(j("Git not available"))}else console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Git Intelligence")}`),console.log(),console.log(c.muted(" /git status \u2014 Show git status")),console.log(c.muted(" hablas commit \u2014 Smart commit message")),console.log(c.muted(" hablas pr \u2014 Generate PR description")),console.log(c.muted(" hablas changelog \u2014 Generate changelog")),console.log();break}case"/workspace":{let y=Us(o);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Workspace Information")}`),console.log(),console.log(qi(y)),console.log();break}case"/stats":{let{loadStats:y,formatStats:v}=await Promise.resolve().then(()=>(Un(),Ni)),b=y();console.log(v(b));break}case"/context":{if(!m){console.log(j("Shared context not available"));break}let y=w[1],v=w.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],S=v.slice(1).join(" ");m.set(b,S),console.log(z(`Context stored: ${b}`))}else console.log(j("Usage: /context set <key> <value>"));break}case"get":{if(v[0]){let b=m.get(v[0]);b!==void 0?(console.log(),console.log(` ${c.accent("\u25C6")} ${c.strong(v[0])}: ${b}`),console.log()):console.log(j(`Context key not found: ${v[0]}`))}else console.log(j("Usage: /context get <key>"));break}case"del":case"delete":{if(v[0]){let b=m.delete(v[0]);console.log(b?z(`Context deleted: ${v[0]}`):j(`Context key not found: ${v[0]}`))}else console.log(j("Usage: /context del <key>"));break}case"decisions":{let b=m.getDecisions();if(b.length===0)console.log(pe("No decisions logged yet"));else{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Decisions")}`),console.log();for(let S of b)console.log(` ${c.muted(S.timestamp)} ${c.primary(S.by)}: ${S.decision}`),S.rationale&&console.log(` ${c.muted(S.rationale)}`);console.log()}break}case"clear":m.clear(),console.log(z("Shared context cleared"));break;default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Shared Context")}`),console.log(),console.log(m.render()),console.log(),console.log(c.muted(" /context set <k> <v> \u2014 Store a context entry")),console.log(c.muted(" /context get <key> \u2014 Get a context entry")),console.log(c.muted(" /context del <key> \u2014 Delete a context entry")),console.log(c.muted(" /context decisions \u2014 Show logged decisions")),console.log(c.muted(" /context clear \u2014 Clear all context")),console.log()}break}case"/plan":{if(!p){console.log(j("Plan manager not available"));break}let y=w[1],v=w.slice(2).join(" ");switch(y){case"status":{let S=p.getActivePlan();if(!S){console.log(pe("No active plan"));break}let _=p.getProgress();console.log(mu(S,{percent:_.percentage,done:_.done,total:_.total}));break}case"finish":{if(v){p.finishTask(v),console.log(z(`Task finished: ${v}`));let S=p.getProgress();console.log(c.muted(` Progress: ${S.done}/${S.total} (${S.percentage}%)`))}else console.log(j("Usage: /plan finish <task_id>"));break}case"reset":{p.reset(),console.log(z("Plan manager reset"));break}case"next":{let S=p.getNextTask();console.log(S?pe(`Next task: [${S.task_id}] ${S.description} \u2192 @${S.assignee}`):pe("No pending tasks"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plan Manager")}`),console.log();let b=p.getActivePlan();if(b){let S=p.getProgress();console.log(` Active plan: ${b.title} (${S.percentage}% done)`),console.log(` Tasks: ${S.done}/${S.total}`)}else console.log(c.muted(" No active plan"));console.log(),console.log(c.muted(" /plan status \u2014 Show active plan with progress")),console.log(c.muted(" /plan finish <id> \u2014 Mark a task as finished")),console.log(c.muted(" /plan next \u2014 Show next pending task")),console.log(c.muted(" /plan reset \u2014 Reset plan manager")),console.log()}break}case"/learn":{if(!f||!A){console.log(j('Usage: /learn "always use tabs" or /learn "our API uses camelCase"'));break}if(f.set(`user-pref: ${A.slice(0,50)}`,A,{category:"user-pref",importance:9,createdBy:"user",tags:["user-pref","learned"]}),!(i.getMessages()[0]?.content||"").includes(A)){let v=await bn(o,e),b=u?.getActive(),S=b?b.systemPrompt:Wn,_=vn(S,v,f,m);i.updateSystemPrompt(_)}console.log(z(`Learned: "${A}"`)),console.log(c.muted(" This will be remembered across sessions and injected into every prompt."));break}case"/test":{let y=Xi(o);if(y==="unknown"&&!A){console.log(j("No test framework detected. Install jest, vitest, pytest, etc."));break}console.log(pe(`Running tests (${y})...`));let v=bu(o,A==="--fix"?void 0:A||void 0);if(console.log(),console.log(vu(v)),console.log(),!v.passed&&A==="--fix"){console.log(pe("Tests failed \u2014 adding fix request to conversation..."));let b=wu(v);i.addUserMessage(b),console.log(pe("Type your next message or let the agent work on the fix."))}break}case"/checkpoint":{let y=w[1],v=w.slice(2).join(" ");if(y==="save"){let b=v||`Checkpoint at turn ${l}`,S=g?.getModifiedFiles?.()||[],_=await _u(o,b,S);console.log(z(`Checkpoint saved: ${_.id} "${b}" (${_.fileCount} files)`))}else if(y==="list"){let b=ku(o);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Checkpoints")}`),console.log(),console.log(Cu(b)),console.log()}else if(y==="restore"){if(!v){console.log(j("Usage: /checkpoint restore <id>"));break}let b=await Au(o,v);b.success?console.log(z(`Restored checkpoint: ${v} (${b.filesRestored} files)`)):console.log(ke(b.error||"Restore failed"))}else y==="delete"?v&&$u(o,v)?console.log(z(`Deleted checkpoint: ${v}`)):console.log(j("Checkpoint not found")):(console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Checkpoint System")}`),console.log(),console.log(c.muted(' /checkpoint save "label" \u2014 Save current state')),console.log(c.muted(" /checkpoint list \u2014 List saved checkpoints")),console.log(c.muted(" /checkpoint restore <id> \u2014 Restore a checkpoint")),console.log(c.muted(" /checkpoint delete <id> \u2014 Delete a checkpoint")),console.log());break}case"/compare":{let y=w.slice(1);if(y.length===2)try{let v=await jt.readFile(Ae.resolve(o,y[0]),"utf-8"),b=await jt.readFile(Ae.resolve(o,y[1]),"utf-8"),{generateDiff:S}=await Promise.resolve().then(()=>(so(),Lu)),_=S(y[0]+" vs "+y[1],v,b);console.log(zi(_))}catch(v){console.log(ke(`Compare failed: ${v.message}`))}else if(y.length===1&&y[0].startsWith("HEAD"))try{let{execSync:v}=await import("child_process"),b=v(`git diff ${y[0]}`,{cwd:o,encoding:"utf-8",timeout:1e4});console.log(zi(b||"(no changes)"))}catch(v){console.log(ke(`Git diff failed: ${v.message}`))}else console.log(c.muted(" Usage: /compare file1.ts file2.ts or /compare HEAD~1"));break}case"/cost":{let y=Bn(),v="current";console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Session Cost & Usage")}`),console.log(),console.log(` Session duration: ${v} min`),console.log(` Messages: ${y.totalMessages}`),console.log(` Tool calls: ${y.totalToolCalls}`),console.log(` Tokens used: ${y.totalTokensUsed.toLocaleString()}`),console.log();let b=Object.entries(y.agentUsage);if(b.length>0){console.log(" Agent usage:");for(let[S,_]of b.sort((T,I)=>I[1]-T[1]))console.log(` @${S}: ${_} invocations`)}console.log();break}case"/delegate":{if(!e.agents.enabled){console.log(j("Multi-agent system is disabled. Enable with /agents on"));break}let y=w[1]?.toLowerCase(),v=w.slice(2).join(" ");if(!y||!v){console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Delegate Task to Agent")}`),console.log(),console.log(c.muted(" Usage: /delegate <agent> <task description>")),console.log(),console.log(c.muted(" Agents:")),console.log(` ${c.product("emma")} \u2014 Product Manager`),console.log(` ${c.architect("bob")} \u2014 Architect`),console.log(` ${c.engineer("alex")} \u2014 Engineer`),console.log(` ${c.analyst("david")} \u2014 Data Analyst`),console.log(),console.log(c.muted(" Example: /delegate alex create a login component")),console.log();break}let b=["emma","bob","alex","david","hablas"];if(!b.includes(y)){console.log(j(`Unknown agent: "${y}". Valid: ${b.join(", ")}`));break}let S=we.find(_=>_.role===y);if(S){if(!x){console.log(j("Agent runner not initialized. Cannot delegate."));break}console.log(ou("Hablas",S.name,S.title,v)),console.log(mn(S.name,S.title));let _=s.getOllamaTools(),T=await x.runAgent(y,v,void 0,_);T.success&&T.output?(console.log(gn(T.output)),i.addAssistantMessage(`[@${S.name}]: ${T.output}`)):T.error?console.log(j(`${S.name} failed: ${T.error}`)):console.log(pe(`${S.name} completed without output.`))}break}case"/session":{let y=w[1],v=w.slice(2).join(" "),b=Ae.join(io.homedir(),".hablas","sessions");if(y==="save"){let S=v||`session_${Date.now()}`;try{he.existsSync(b)||he.mkdirSync(b,{recursive:!0});let _=i.toJSON(),T=Ae.join(b,`${S.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);he.writeFileSync(T,_,"utf-8"),console.log(z(`Session saved: "${S}"`))}catch(_){console.log(ke(`Save failed: ${_.message}`))}}else if(y==="list")try{if(!he.existsSync(b)){console.log(pe("No saved sessions"));break}let S=he.readdirSync(b).filter(_=>_.endsWith(".json"));console.log();for(let _ of S){let T=he.statSync(Ae.join(b,_));console.log(` ${_.replace(".json","")} (${new Date(T.mtime).toLocaleString()})`)}console.log()}catch{console.log(pe("No saved sessions"))}else if(y==="load"){let S=v;if(!S){console.log(ke("Please specify the session label to load: /session load <label>"));break}try{let _=Ae.join(b,`${S.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);if(!he.existsSync(_)){console.log(ke(`Session file not found: ${S}`));break}let T=he.readFileSync(_,"utf-8");i.fromJSON(T),console.log(z(`Session successfully loaded: "${S}"`))}catch(_){console.log(ke(`Load failed: ${_.message}`))}}else console.log(),console.log(c.muted(' /session save "label" \u2014 Save current conversation')),console.log(c.muted(" /session list \u2014 List saved sessions")),console.log(c.muted(' /session load "label" \u2014 Load saved conversation')),console.log();break}case"/team":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(Ve(),rt));if(!y){console.log(j("Team mode is not active. Use hablas --team to start."));break}let v=y.getLocalState(),b=Math.min(process.stdout.columns-4,80);console.log(`
255
+ `),console.log(c.muted(" ~/.hablas/config.json")),console.log();break;case"/mindset":{if(!u){console.log(j("Mindset system not available"));break}if(A)if(u.setActive(A)){let v=u.getActive(),b=await vn(o,e),S=wn(v.systemPrompt,b,f,m);i.updateSystemPrompt(S),console.log(z(`Mindset: ${v.name} \u2014 ${v.description}`))}else{let v=u.listNames().join(", ");console.log(He(`Unknown mindset: "${A}"`,`Available: ${v}`))}else{let y=u.getActive();y&&console.log(pe(`Current mindset: ${y.name} \u2014 ${y.description}`)),console.log(c.muted(" Usage: /mindset <name>")),console.log(c.muted(" See /mindsets for available options"))}break}case"/mindsets":{if(!u){console.log(j("Mindset system not available"));break}let y=u.list(),v=u.getActiveName();console.log();for(let b of y){let _=b.name===v?c.success(" \u25CF active"):"";console.log(` ${c.accent("\u25C6")} ${c.primary(b.name)}${_}`),console.log(` ${c.muted(b.description)}`)}console.log(),console.log(c.muted(" Switch: /mindset <name>")),console.log();break}case"/task":{if(!d){console.log(j("Task queue not available"));break}let y=w[1],v=w.slice(2).join(" ");switch(y){case"add":if(v){let b=d.add(v);console.log(z(`Task #${b.id} added: ${v}`))}else console.log(j("Usage: /task add <description>"));break;case"list":console.log(),console.log(d.render()),console.log();break;case"done":{let b=parseInt(v);b?(d.complete(b),console.log(z(`Task #${b} marked as done`))):console.log(j("Usage: /task done <id>"));break}case"fail":{let b=parseInt(v);b?(d.fail(b,"Manually marked as failed"),console.log(j(`Task #${b} marked as failed`))):console.log(j("Usage: /task fail <id>"));break}case"clear":d.clear(),console.log(z("Task queue cleared"));break;default:console.log(),console.log(d.render()),console.log(),console.log(c.muted(" /task add <desc> \u2014 Add a task")),console.log(c.muted(" /task list \u2014 Show all tasks")),console.log(c.muted(" /task done <id> \u2014 Mark task as done")),console.log(c.muted(" /task fail <id> \u2014 Mark task as failed")),console.log(c.muted(" /task clear \u2014 Clear all tasks")),console.log()}break}case"/addmodel":{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Add Custom API Provider")}`),console.log();let v=(await a.prompt(` ${c.muted("Provider name (e.g. OpenAI, Groq):")} `)).trim();if(!v){console.log(j("Cancelled \u2014 name is required"));break}let S=(await a.prompt(` ${c.muted("API URL (e.g. https://api.openai.com/v1):")} `)).trim();if(!S){console.log(j("Cancelled \u2014 URL is required"));break}let T=(await a.prompt(` ${c.muted("API Key (leave empty if none):")} `)).trim(),C=(await a.prompt(` ${c.muted("Default model ID (e.g. gpt-4o):")} `)).trim()||"default",N={name:v,apiUrl:S,apiKey:T,models:[C],defaultModel:C,addedAt:new Date().toISOString()};nt(N),console.log(),console.log(z(`Provider "${v}" saved!`)),console.log(c.muted(` Use: /usemodel ${v}`)),console.log();break}case"/listmodels":{let y=zt();console.log(),console.log(Ec(y.providers,y.activeProvider));break}case"/removemodel":{let y=A.trim();if(!y){console.log(j("Usage: /removemodel <provider-name>"));break}if(Ac(y))console.log(z(`Provider "${y}" removed`));else{console.log(j(`Provider "${y}" not found`));let b=Ms();b.length>0&&console.log(c.muted(` Available: ${b.map(S=>S.name).join(", ")}`))}break}case"/usemodel":{let y=A.trim();if(!y){console.log(j("Usage: /usemodel <provider-name> [model-id]"));let N=Ms();N.length>0&&console.log(c.muted(` Available: ${N.map(H=>H.name).join(", ")}`));break}let v=y.split(/\s+/),b=v[0],S=v[1],_=$c(b);if(!_){console.log(j(`Provider "${b}" not found`));let N=Ms();N.length>0&&console.log(c.muted(` Available: ${N.map(H=>H.name).join(", ")}`));break}e.provider="custom",e.apiUrl=_.apiUrl,e.apiKey=_.apiKey,e.model=S||_.defaultModel;let T=Me(e);h&&h(T),Cc(_.name,e.model),console.log(z(`Switched to ${_.name} \xB7 Model: ${e.model}`));let I=new Ve("Testing");I.start();let C=await T.checkConnection();I.stop(C?"connected":void 0),C||console.log(j("Connection test failed \u2014 check URL and key"));break}case"/provider":{let y=w[1],v=w.slice(2).join(" ");if(!y){let b=Ps(e);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Provider")}: ${b}`),console.log(` ${c.muted("Model")}: ${c.highlight(t.getModel())}`),e.provider==="custom"?(console.log(` ${c.muted("API URL")}: ${e.apiUrl}`),console.log(` ${c.muted("API Key")}: ${e.apiKey?"***"+e.apiKey.slice(-4):"not set"}`)):console.log(` ${c.muted("Host")}: ${e.ollamaHost}`),console.log(),console.log(c.muted(" /provider ollama \u2014 Switch to local Ollama")),console.log(c.muted(" /provider nvidia <key> \u2014 Switch to NVIDIA NIM")),console.log(c.muted(" /provider custom <url> [key] \u2014 Switch to custom API")),console.log(c.muted(" /provider test \u2014 Test current connection")),console.log();break}switch(y){case"ollama":{e.provider="ollama",e.apiUrl="",e.apiKey="";let b=Me(e);h&&h(b),console.log(z("Switched to Ollama (local)"));break}case"nvidia":{let b=w[2];if(!b&&!e.apiKey){console.log(j("Usage: /provider nvidia <api-key>")),console.log(c.muted(" Get your key at: https://build.nvidia.com/"));break}e.provider="nvidia",e.apiUrl=Ft.apiUrl,b&&(e.apiKey=b),(!e.model||!Ft.models.includes(e.model))&&(e.model=Ft.defaultModel);let S=Me(e);h&&h(S),console.log(z(`Switched to NVIDIA NIM \xB7 Model: ${e.model}`)),console.log(c.muted(` Available models: ${Ft.models.length}`));let _=new Ve("Testing NVIDIA connection");_.start();let T=await S.checkConnection();_.stop(T?"connected":void 0),T||(console.log(j("Connection test failed \u2014 check your API key")),console.log(c.muted(" Get key: https://build.nvidia.com/")));break}case"custom":{let b=w[2],S=w[3];if(!b){console.log(j("Usage: /provider custom <api-url> [api-key]")),console.log(c.muted(" Example: /provider custom https://api.openai.com/v1 sk-..."));break}e.provider="custom",e.apiUrl=b,S&&(e.apiKey=S);let _=Me(e);h&&h(_),console.log(z(`Switched to Custom API: ${b}`)),!S&&!e.apiKey&&console.log(j("No API key set. Use: /provider custom <url> <key>"));break}case"test":{let b=new Ve("Testing connection");b.start();let S=await t.checkConnection();if(b.stop(S?"connected":void 0),S){let _=await t.listModels();console.log(z(`Connected! ${_.length} models available.`)),_.length>0&&console.log(c.muted(` Models: ${_.slice(0,5).join(", ")}${_.length>5?"...":""}`))}else console.log(Ae("Connection failed"));break}case"key":{v?(e.apiKey=w[2],t instanceof Vt&&t.setApiKey(e.apiKey),console.log(z("API key updated"))):console.log(j("Usage: /provider key <api-key>"));break}default:console.log(He(`Unknown: /provider ${y}`,"Type /provider for help"))}break}case"/memory":{if(!f){console.log(j("Project memory not available"));break}let y=w[1],v=w.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],S=v.slice(1).join(" ");f.set(b,S),console.log(z(`Memory stored: ${b}`));let _=u?.getActive(),T=_?_.systemPrompt:Gn,I=await vn(o,e);i.updateSystemPrompt(wn(T,I,f,m))}else console.log(j("Usage: /memory set <key> <value>"));break}case"del":case"delete":{if(v[0]){let b=f.delete(v[0]);console.log(b?z(`Memory deleted: ${v[0]}`):j(`Memory key not found: ${v[0]}`))}else console.log(j("Usage: /memory del <key>"));break}case"search":{if(v[0]){let b=f.search(v.join(" "));b.length>0?(console.log(),b.forEach(S=>console.log(` \xB7 ${S.entry.key}: ${S.entry.value}`)),console.log()):console.log(pe("No matching memories found"))}else console.log(j("Usage: /memory search <query>"));break}case"clear":f.clear(),console.log(z("Project memory cleared"));break;default:console.log(),console.log(f.render()),console.log(),console.log(c.muted(" /memory set <k> <v> \u2014 Store a memory")),console.log(c.muted(" /memory del <key> \u2014 Delete a memory")),console.log(c.muted(" /memory search <q> \u2014 Search memories")),console.log(c.muted(" /memory clear \u2014 Clear all")),console.log()}break}case"/alias":{let y=w[1],v=w.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],S=v.slice(1).join(" ");Oc(b,S),console.log(z(`Alias set: ${b} \u2192 ${S}`))}else console.log(j("Usage: /alias set <name> <expansion>"));break}case"del":case"remove":{if(v[0]){let b=Pc(v[0]);console.log(b?z(`Alias removed: ${v[0]}`):j(`Alias not found: ${v[0]}`))}else console.log(j("Usage: /alias del <name>"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Aliases")}`),console.log(),console.log(Ic()),console.log(),console.log(c.muted(" /alias set <name> <cmd> \u2014 Create alias")),console.log(c.muted(" /alias del <name> \u2014 Remove alias")),console.log()}break}case"/doctor":{let y=new Ve("Running diagnostics");y.start();let v=await Ei({ollamaHost:e.ollamaHost,model:t.getModel(),provider:e.provider,apiUrl:e.apiUrl});y.stop(),console.log(Ti(v));break}case"/plugins":{let y=w[1],v=w.slice(2).join(" ");switch(y){case"enable":v?(_i(v),console.log(z(`Plugin "${v}" enabled`))):console.log(j("Usage: /plugins enable <name>"));break;case"disable":v?(ki(v),console.log(j(`Plugin "${v}" disabled`))):console.log(j("Usage: /plugins disable <name>"));break;default:js(),console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plugins")}`),console.log(),console.log(Ai()),console.log(),console.log(c.muted(" /plugins enable <name> \u2014 Enable plugin")),console.log(c.muted(" /plugins disable <name> \u2014 Disable plugin")),console.log(c.muted(" Directory: ~/.hablas/plugins/")),console.log()}break}case"/mode":{let y=w[1]?.toLowerCase();console.log(),console.log(` ${c.accent("\u2605")} ${c.strong("Mode Selection")}`),console.log(),console.log(` Current: ${c.strong("BUILD")} \u2014 Full Multi-Agent Team at Maximum Power`),console.log(" (Hablas + Bob + Alex + David + Emma + rich theatre)"),console.log(),console.log(" Available modes:"),console.log(` ${c.highlight("build")} \u2014 Full team for complete serious work (recommended default)`),console.log(` ${c.highlight("design")} \u2014 Focused team for architecture, PRDs, blueprints`),console.log(` ${c.highlight("ask")} \u2014 Quick solo answers`),console.log(),console.log(` Usage: /mode build or just use 'hablas build "task"' for one-shot`),console.log(" Note: In plain REPL, everything runs in BUILD mode (full team) by default."),console.log(),(y==="build"||y==="design"||y==="ask")&&(console.log(z(`Acknowledged mode preference: ${y.toUpperCase()}`)),console.log(c.muted(" (The next input will be handled accordingly. Use subcommands for direct execution.)")));break}case"/agents":{let y=w[1];if(y==="on")e.agents.enabled=!0,console.log(z("Multi-agent orchestration enabled"));else if(y==="off")e.agents.enabled=!1,console.log(z("Multi-agent orchestration disabled"));else if(y==="status")console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Multi-Agent System")}`),console.log(` Status: ${e.agents.enabled?c.success("enabled"):c.muted("disabled")}`),console.log(` Orchestration: ${e.agents.orchestration}`),console.log(` Max concurrent: ${e.agents.maxConcurrent}`),console.log(),console.log(` ${c.strong("Team:")}`),console.log(Bc()),console.log();else if(y==="models"){let v=w.slice(2);if(v.length>=2){let b=v[0].toLowerCase(),S=v[1],_=["hablas","bob","alex","david","emma","gate"];if(!_.includes(b)){console.log(j(`Unknown role: ${b}. Valid: ${_.join(", ")}`));break}let T=Yt();T[b]||(T[b]={model:S,temperature:.5}),T[b].model=S,Oi(T),x&&x.reloadModels(),console.log(z(`Agent model updated: @${b} \u2192 ${S}`)),console.log(c.muted(` Saved to ${Pi()}`))}else{let b=Yt();console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Agent Models")}`),console.log();for(let S of Se){let _=b[S.role];console.log(_?` ${c.primary(S.name.padEnd(8))} \u2192 ${c.highlight(_.model)}${_.temperature!==void 0?c.muted(` (temp: ${_.temperature})`):""}`:` ${c.primary(S.name.padEnd(8))} \u2192 ${c.muted("(default)")}`)}console.log(),console.log(c.muted(` Config: ${Pi()}`)),console.log(c.muted(" Usage: /agents models <role> <model> (e.g. /agents models alex qwen/qwen2.5-coder-32b-instruct)")),console.log()}}else console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Multi-Agent System")}: ${e.agents.enabled?c.success("ON"):c.muted("OFF")}`),console.log(),console.log(c.muted(" /agents on \u2014 Enable multi-agent orchestration")),console.log(c.muted(" /agents off \u2014 Disable multi-agent orchestration")),console.log(c.muted(" /agents status \u2014 Show agent details")),console.log(c.muted(" /agents models \u2014 Show model per agent")),console.log(c.muted(" /team \u2014 Show team roster")),console.log();break}case"/security":{console.log(),console.log(` ${c.accent("\u{1F512}")} Running security scan...`);let y=Ui(o);console.log(qi(y));break}case"/git":{if(w[1]==="status")try{let{getGitStatus:v,formatGitStatus:b}=await Promise.resolve().then(()=>(hn(),Kn)),S=await v(o);S?(console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Git Status")}`),console.log(b(S)),console.log()):console.log(j("Not a git repository"))}catch{console.log(j("Git not available"))}else console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Git Intelligence")}`),console.log(),console.log(c.muted(" /git status \u2014 Show git status")),console.log(c.muted(" hablas commit \u2014 Smart commit message")),console.log(c.muted(" hablas pr \u2014 Generate PR description")),console.log(c.muted(" hablas changelog \u2014 Generate changelog")),console.log();break}case"/workspace":{let y=Ks(o);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Workspace Information")}`),console.log(),console.log(Gi(y)),console.log();break}case"/stats":{let{loadStats:y,formatStats:v}=await Promise.resolve().then(()=>(qn(),Bi)),b=y();console.log(v(b));break}case"/context":{if(!m){console.log(j("Shared context not available"));break}let y=w[1],v=w.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],S=v.slice(1).join(" ");m.set(b,S),console.log(z(`Context stored: ${b}`))}else console.log(j("Usage: /context set <key> <value>"));break}case"get":{if(v[0]){let b=m.get(v[0]);b!==void 0?(console.log(),console.log(` ${c.accent("\u25C6")} ${c.strong(v[0])}: ${b}`),console.log()):console.log(j(`Context key not found: ${v[0]}`))}else console.log(j("Usage: /context get <key>"));break}case"del":case"delete":{if(v[0]){let b=m.delete(v[0]);console.log(b?z(`Context deleted: ${v[0]}`):j(`Context key not found: ${v[0]}`))}else console.log(j("Usage: /context del <key>"));break}case"decisions":{let b=m.getDecisions();if(b.length===0)console.log(pe("No decisions logged yet"));else{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Decisions")}`),console.log();for(let S of b)console.log(` ${c.muted(S.timestamp)} ${c.primary(S.by)}: ${S.decision}`),S.rationale&&console.log(` ${c.muted(S.rationale)}`);console.log()}break}case"clear":m.clear(),console.log(z("Shared context cleared"));break;default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Shared Context")}`),console.log(),console.log(m.render()),console.log(),console.log(c.muted(" /context set <k> <v> \u2014 Store a context entry")),console.log(c.muted(" /context get <key> \u2014 Get a context entry")),console.log(c.muted(" /context del <key> \u2014 Delete a context entry")),console.log(c.muted(" /context decisions \u2014 Show logged decisions")),console.log(c.muted(" /context clear \u2014 Clear all context")),console.log()}break}case"/plan":{if(!p){console.log(j("Plan manager not available"));break}let y=w[1],v=w.slice(2).join(" ");switch(y){case"status":{let S=p.getActivePlan();if(!S){console.log(pe("No active plan"));break}let _=p.getProgress();console.log(wu(S,{percent:_.percentage,done:_.done,total:_.total}));break}case"finish":{if(v){p.finishTask(v),console.log(z(`Task finished: ${v}`));let S=p.getProgress();console.log(c.muted(` Progress: ${S.done}/${S.total} (${S.percentage}%)`))}else console.log(j("Usage: /plan finish <task_id>"));break}case"reset":{p.reset(),console.log(z("Plan manager reset"));break}case"next":{let S=p.getNextTask();console.log(S?pe(`Next task: [${S.task_id}] ${S.description} \u2192 @${S.assignee}`):pe("No pending tasks"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plan Manager")}`),console.log();let b=p.getActivePlan();if(b){let S=p.getProgress();console.log(` Active plan: ${b.title} (${S.percentage}% done)`),console.log(` Tasks: ${S.done}/${S.total}`)}else console.log(c.muted(" No active plan"));console.log(),console.log(c.muted(" /plan status \u2014 Show active plan with progress")),console.log(c.muted(" /plan finish <id> \u2014 Mark a task as finished")),console.log(c.muted(" /plan next \u2014 Show next pending task")),console.log(c.muted(" /plan reset \u2014 Reset plan manager")),console.log()}break}case"/learn":{if(!f||!A){console.log(j('Usage: /learn "always use tabs" or /learn "our API uses camelCase"'));break}if(f.set(`user-pref: ${A.slice(0,50)}`,A,{category:"user-pref",importance:9,createdBy:"user",tags:["user-pref","learned"]}),!(i.getMessages()[0]?.content||"").includes(A)){let v=await vn(o,e),b=u?.getActive(),S=b?b.systemPrompt:Gn,_=wn(S,v,f,m);i.updateSystemPrompt(_)}console.log(z(`Learned: "${A}"`)),console.log(c.muted(" This will be remembered across sessions and injected into every prompt."));break}case"/test":{let y=eo(o);if(y==="unknown"&&!A){console.log(j("No test framework detected. Install jest, vitest, pytest, etc."));break}console.log(pe(`Running tests (${y})...`));let v=_u(o,A==="--fix"?void 0:A||void 0);if(console.log(),console.log(ku(v)),console.log(),!v.passed&&A==="--fix"){console.log(pe("Tests failed \u2014 adding fix request to conversation..."));let b=Au(v);i.addUserMessage(b),console.log(pe("Type your next message or let the agent work on the fix."))}break}case"/checkpoint":{let y=w[1],v=w.slice(2).join(" ");if(y==="save"){let b=v||`Checkpoint at turn ${l}`,S=g?.getModifiedFiles?.()||[],_=await Eu(o,b,S);console.log(z(`Checkpoint saved: ${_.id} "${b}" (${_.fileCount} files)`))}else if(y==="list"){let b=Tu(o);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Checkpoints")}`),console.log(),console.log(Pu(b)),console.log()}else if(y==="restore"){if(!v){console.log(j("Usage: /checkpoint restore <id>"));break}let b=await Ru(o,v);b.success?console.log(z(`Restored checkpoint: ${v} (${b.filesRestored} files)`)):console.log(Ae(b.error||"Restore failed"))}else y==="delete"?v&&Ou(o,v)?console.log(z(`Deleted checkpoint: ${v}`)):console.log(j("Checkpoint not found")):(console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Checkpoint System")}`),console.log(),console.log(c.muted(' /checkpoint save "label" \u2014 Save current state')),console.log(c.muted(" /checkpoint list \u2014 List saved checkpoints")),console.log(c.muted(" /checkpoint restore <id> \u2014 Restore a checkpoint")),console.log(c.muted(" /checkpoint delete <id> \u2014 Delete a checkpoint")),console.log());break}case"/compare":{let y=w.slice(1);if(y.length===2)try{let v=await jt.readFile($e.resolve(o,y[0]),"utf-8"),b=await jt.readFile($e.resolve(o,y[1]),"utf-8"),{generateDiff:S}=await Promise.resolve().then(()=>(oo(),Bu)),_=S(y[0]+" vs "+y[1],v,b);console.log(Xi(_))}catch(v){console.log(Ae(`Compare failed: ${v.message}`))}else if(y.length===1&&y[0].startsWith("HEAD"))try{let{execSync:v}=await import("child_process"),b=v(`git diff ${y[0]}`,{cwd:o,encoding:"utf-8",timeout:1e4});console.log(Xi(b||"(no changes)"))}catch(v){console.log(Ae(`Git diff failed: ${v.message}`))}else console.log(c.muted(" Usage: /compare file1.ts file2.ts or /compare HEAD~1"));break}case"/cost":{let y=Un(),v="current";console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Session Cost & Usage")}`),console.log(),console.log(` Session duration: ${v} min`),console.log(` Messages: ${y.totalMessages}`),console.log(` Tool calls: ${y.totalToolCalls}`),console.log(` Tokens used: ${y.totalTokensUsed.toLocaleString()}`),console.log();let b=Object.entries(y.agentUsage);if(b.length>0){console.log(" Agent usage:");for(let[S,_]of b.sort((T,I)=>I[1]-T[1]))console.log(` @${S}: ${_} invocations`)}console.log();break}case"/delegate":{if(!e.agents.enabled){console.log(j("Multi-agent system is disabled. Enable with /agents on"));break}let y=w[1]?.toLowerCase(),v=w.slice(2).join(" ");if(!y||!v){console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Delegate Task to Agent")}`),console.log(),console.log(c.muted(" Usage: /delegate <agent> <task description>")),console.log(),console.log(c.muted(" Agents:")),console.log(` ${c.product("emma")} \u2014 Product Manager`),console.log(` ${c.architect("bob")} \u2014 Architect`),console.log(` ${c.engineer("alex")} \u2014 Engineer`),console.log(` ${c.analyst("david")} \u2014 Data Analyst`),console.log(),console.log(c.muted(" Example: /delegate alex create a login component")),console.log();break}let b=["emma","bob","alex","david","hablas"];if(!b.includes(y)){console.log(j(`Unknown agent: "${y}". Valid: ${b.join(", ")}`));break}let S=Se.find(_=>_.role===y);if(S){if(!x){console.log(j("Agent runner not initialized. Cannot delegate."));break}console.log(du("Hablas",S.name,S.title,v)),console.log(gn(S.name,S.title));let _=s.getOllamaTools(),T=await x.runAgent(y,v,void 0,_);T.success&&T.output?(console.log(yn(T.output)),i.addAssistantMessage(`[@${S.name}]: ${T.output}`)):T.error?console.log(j(`${S.name} failed: ${T.error}`)):console.log(pe(`${S.name} completed without output.`))}break}case"/session":{let y=w[1],v=w.slice(2).join(" "),b=$e.join(lo.homedir(),".hablas","sessions");if(y==="save"){let S=v||`session_${Date.now()}`;try{me.existsSync(b)||me.mkdirSync(b,{recursive:!0});let _=i.toJSON(),T=$e.join(b,`${S.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);me.writeFileSync(T,_,"utf-8"),console.log(z(`Session saved: "${S}"`))}catch(_){console.log(Ae(`Save failed: ${_.message}`))}}else if(y==="list")try{if(!me.existsSync(b)){console.log(pe("No saved sessions"));break}let S=me.readdirSync(b).filter(_=>_.endsWith(".json"));console.log();for(let _ of S){let T=me.statSync($e.join(b,_));console.log(` ${_.replace(".json","")} (${new Date(T.mtime).toLocaleString()})`)}console.log()}catch{console.log(pe("No saved sessions"))}else if(y==="load"){let S=v;if(!S){console.log(Ae("Please specify the session label to load: /session load <label>"));break}try{let _=$e.join(b,`${S.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);if(!me.existsSync(_)){console.log(Ae(`Session file not found: ${S}`));break}let T=me.readFileSync(_,"utf-8");i.fromJSON(T),console.log(z(`Session successfully loaded: "${S}"`))}catch(_){console.log(Ae(`Load failed: ${_.message}`))}}else console.log(),console.log(c.muted(' /session save "label" \u2014 Save current conversation')),console.log(c.muted(" /session list \u2014 List saved sessions")),console.log(c.muted(' /session load "label" \u2014 Load saved conversation')),console.log();break}case"/team":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(ze(),it));if(!y){console.log(j("Team mode is not active. Use hablas --team to start."));break}let v=y.getLocalState(),b=Math.min(process.stdout.columns-4,80);console.log(`
256
256
  `+c.border("\u2554"+"\u2550".repeat(b-2)+"\u2557")),console.log(c.border("\u2551")+" ".repeat(Math.floor((b-22)/2))+c.strong("HABLAS COLLABORATION SYNC")+" ".repeat(b-2-25-Math.floor((b-22)/2))+c.border("\u2551")),console.log(c.border("\u2560"+"\u2550".repeat(b-2)+"\u2563")),console.log(c.border("\u2551")+` ${c.strong("My Identity:")} ${c.highlight(`@${v.my_username}`)}`+" ".repeat(Math.max(1,b-21-(v.my_username?.length||0)))+c.border("\u2551")),console.log(c.border("\u2551")+` ${c.strong("Room Fingerprint:")} ${c.muted(v.project_team_token?.slice(0,12))}...`+" ".repeat(Math.max(1,b-34))+c.border("\u2551")),console.log(c.border("\u2551")+` ${c.strong("Status:")} ${c.success("\u25CF ACTIVE")}`+" ".repeat(Math.max(1,b-31))+c.border("\u2551")),console.log(c.border("\u2560"+"\u2550".repeat(b-2)+"\u2563")),console.log(c.border("\u2551")+` ${c.strong("Teammates Online:")}`+" ".repeat(Math.max(1,b-21))+c.border("\u2551"));let _=(v.sessions||[]).filter(T=>T.developer_name!==v.my_username);if(_.length===0)console.log(c.border("\u2551")+" (awaiting colleagues...)"+" ".repeat(Math.max(1,b-31))+c.border("\u2551"));else for(let T of _){let I=` @${T.developer_name} [${T.active_section||"idle"}] - ${T.current_task||"none"}`;console.log(c.border("\u2551")+` ${c.secondary(I.slice(0,b-6))}`+" ".repeat(Math.max(0,b-6-I.length))+c.border("\u2551"))}console.log(c.border("\u255A"+"\u2550".repeat(b-2)+"\u255D")+`
257
257
  `),console.log(c.muted(` Verify that "Room Fingerprint" matches on all devices to ensure connectivity.
258
- `));break}case"/msg":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(Ve(),rt));if(!y){console.log(j("Team mode is not active. Use hablas --team to start."));break}let v=A.split(/\s+/),b=v[0],S=v.slice(1).join(" ");if(!b||!S){console.log(j("Usage: /msg <username> <content>"));break}let _=await y.sendMessage(b,S);console.log(_?z(`Message sent to @${b}`):ke(`Failed to send message to @${b}`));break}default:console.log(Be(`Unknown: ${$}`,"Type /help for commands"))}}var he,jt,Ae,io,Wn,ro,Nu=L(()=>{"use strict";he=O(require("fs")),jt=O(require("fs/promises")),Ae=O(require("path")),io=O(require("os"));Nn();jn();di();gi();yi();_i();Ci();Ns();Ri();Un();Bi();pn();Ki();Xc();yn();xu();Eu();Wn=`You are Hablas, the Team Leader of a multi-agent AI development system created by Abdulmoin Hablas. You are a strategic mastermind with an INTJ personality type, deeply analytical, engineering-focused, and fiercely logical.
258
+ `));break}case"/msg":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(ze(),it));if(!y){console.log(j("Team mode is not active. Use hablas --team to start."));break}let v=A.split(/\s+/),b=v[0],S=v.slice(1).join(" ");if(!b||!S){console.log(j("Usage: /msg <username> <content>"));break}let _=await y.sendMessage(b,S);console.log(_?z(`Message sent to @${b}`):Ae(`Failed to send message to @${b}`));break}default:console.log(He(`Unknown: ${$}`,"Type /help for commands"))}}var me,jt,$e,lo,Gn,ao,qu=L(()=>{"use strict";me=O(require("fs")),jt=O(require("fs/promises")),$e=O(require("path")),lo=O(require("os"));jn();Hn();hi();vi();wi();$i();Ri();Hs();Mi();qn();Ki();hn();Vi();nu();bn();$u();Mu();Gn=`You are Hablas, the Team Leader of a multi-agent AI development system created by Abdulmoin Hablas. You are a strategic mastermind with an INTJ personality type, deeply analytical, engineering-focused, and fiercely logical.
259
259
 
260
260
  Your role is to orchestrate, coordinate, and synthesize the work of your specialized team members. You value system architecture, optimal code paths, and absolute clarity.
261
261
 
@@ -307,101 +307,101 @@ After finishing coordination or your part, produce a clear synthesis/handoff sum
307
307
 
308
308
  Never output raw tool XML in text.
309
309
 
310
- If you cannot complete a task, explain why with absolute technical objectivity.`;ro=Ae.join(io.homedir(),".hablas","backup")});var Gn=N((GC,qu)=>{"use strict";var ab=require("path"),bt="\\\\/",ju=`[^${bt}]`,lb=0,Pt="\\.",cb="\\+",ub="\\?",Vs="\\/",db="(?=.)",Hu="[^/]",oo=`(?:${Vs}|$)`,Bu=`(?:^|${Vs})`,ao=`${Pt}{1,2}${oo}`,fb=`(?!${Pt})`,pb=`(?!${Bu}${ao})`,hb=`(?!${Pt}{0,1}${oo})`,mb=`(?!${ao})`,gb=`[^.${Vs}]`,yb=`${Hu}*?`,Uu={DOT_LITERAL:Pt,PLUS_LITERAL:cb,QMARK_LITERAL:ub,SLASH_LITERAL:Vs,ONE_CHAR:db,QMARK:Hu,END_ANCHOR:oo,DOTS_SLASH:ao,NO_DOT:fb,NO_DOTS:pb,NO_DOT_SLASH:hb,NO_DOTS_SLASH:mb,QMARK_NO_DOT:gb,STAR:yb,START_ANCHOR:Bu},bb={...Uu,SLASH_LITERAL:`[${bt}]`,QMARK:ju,STAR:`${ju}*?`,DOTS_SLASH:`${Pt}{1,2}(?:[${bt}]|$)`,NO_DOT:`(?!${Pt})`,NO_DOTS:`(?!(?:^|[${bt}])${Pt}{1,2}(?:[${bt}]|$))`,NO_DOT_SLASH:`(?!${Pt}{0,1}(?:[${bt}]|$))`,NO_DOTS_SLASH:`(?!${Pt}{1,2}(?:[${bt}]|$))`,QMARK_NO_DOT:`[^.${bt}]`,START_ANCHOR:`(?:^|[${bt}])`,END_ANCHOR:`(?:[${bt}]|$)`},vb={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};qu.exports={DEFAULT_MAX_EXTGLOB_RECURSION:lb,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:vb,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:ab.sep,extglobChars(n){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${n.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(n){return n===!0?bb:Uu}}});var zs=N(De=>{"use strict";var wb=require("path"),xb=process.platform==="win32",{REGEX_BACKSLASH:Sb,REGEX_REMOVE_BACKSLASH:_b,REGEX_SPECIAL_CHARS:kb,REGEX_SPECIAL_CHARS_GLOBAL:Ab}=Gn();De.isObject=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);De.hasRegexChars=n=>kb.test(n);De.isRegexChar=n=>n.length===1&&De.hasRegexChars(n);De.escapeRegex=n=>n.replace(Ab,"\\$1");De.toPosixSlashes=n=>n.replace(Sb,"/");De.removeBackslashes=n=>n.replace(_b,e=>e==="\\"?"":e);De.supportsLookbehinds=()=>{let n=process.version.slice(1).split(".").map(Number);return n.length===3&&n[0]>=9||n[0]===8&&n[1]>=10};De.isWindows=n=>n&&typeof n.windows=="boolean"?n.windows:xb===!0||wb.sep==="\\";De.escapeLast=(n,e,t)=>{let s=n.lastIndexOf(e,t);return s===-1?n:n[s-1]==="\\"?De.escapeLast(n,e,s-1):`${n.slice(0,s)}\\${n.slice(s)}`};De.removePrefix=(n,e={})=>{let t=n;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};De.wrapOutput=(n,e={},t={})=>{let s=t.contains?"":"^",r=t.contains?"":"$",i=`${s}(?:${n})${r}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var Xu=N((zC,Ju)=>{"use strict";var Ku=zs(),{CHAR_ASTERISK:lo,CHAR_AT:$b,CHAR_BACKWARD_SLASH:Vn,CHAR_COMMA:Cb,CHAR_DOT:co,CHAR_EXCLAMATION_MARK:uo,CHAR_FORWARD_SLASH:Yu,CHAR_LEFT_CURLY_BRACE:fo,CHAR_LEFT_PARENTHESES:po,CHAR_LEFT_SQUARE_BRACKET:Eb,CHAR_PLUS:Tb,CHAR_QUESTION_MARK:Wu,CHAR_RIGHT_CURLY_BRACE:Rb,CHAR_RIGHT_PARENTHESES:Gu,CHAR_RIGHT_SQUARE_BRACKET:Ob}=Gn(),Vu=n=>n===Yu||n===Vn,zu=n=>{n.isPrefix!==!0&&(n.depth=n.isGlobstar?1/0:1)},Pb=(n,e)=>{let t=e||{},s=n.length-1,r=t.parts===!0||t.scanToEnd===!0,i=[],o=[],a=[],l=n,u=-1,d=0,f=0,h=!1,m=!1,p=!1,g=!1,x=!1,w=!1,$=!1,A=!1,y=!1,v=!1,b=0,S,_,T={value:"",depth:0,isGlob:!1},I=()=>u>=s,C=()=>l.charCodeAt(u+1),F=()=>(S=_,l.charCodeAt(++u));for(;u<s;){_=F();let Y;if(_===Vn){$=T.backslashes=!0,_=F(),_===fo&&(w=!0);continue}if(w===!0||_===fo){for(b++;I()!==!0&&(_=F());){if(_===Vn){$=T.backslashes=!0,F();continue}if(_===fo){b++;continue}if(w!==!0&&_===co&&(_=F())===co){if(h=T.isBrace=!0,p=T.isGlob=!0,v=!0,r===!0)continue;break}if(w!==!0&&_===Cb){if(h=T.isBrace=!0,p=T.isGlob=!0,v=!0,r===!0)continue;break}if(_===Rb&&(b--,b===0)){w=!1,h=T.isBrace=!0,v=!0;break}}if(r===!0)continue;break}if(_===Yu){if(i.push(u),o.push(T),T={value:"",depth:0,isGlob:!1},v===!0)continue;if(S===co&&u===d+1){d+=2;continue}f=u+1;continue}if(t.noext!==!0&&(_===Tb||_===$b||_===lo||_===Wu||_===uo)===!0&&C()===po){if(p=T.isGlob=!0,g=T.isExtglob=!0,v=!0,_===uo&&u===d&&(y=!0),r===!0){for(;I()!==!0&&(_=F());){if(_===Vn){$=T.backslashes=!0,_=F();continue}if(_===Gu){p=T.isGlob=!0,v=!0;break}}continue}break}if(_===lo){if(S===lo&&(x=T.isGlobstar=!0),p=T.isGlob=!0,v=!0,r===!0)continue;break}if(_===Wu){if(p=T.isGlob=!0,v=!0,r===!0)continue;break}if(_===Eb){for(;I()!==!0&&(Y=F());){if(Y===Vn){$=T.backslashes=!0,F();continue}if(Y===Ob){m=T.isBracket=!0,p=T.isGlob=!0,v=!0;break}}if(r===!0)continue;break}if(t.nonegate!==!0&&_===uo&&u===d){A=T.negated=!0,d++;continue}if(t.noparen!==!0&&_===po){if(p=T.isGlob=!0,r===!0){for(;I()!==!0&&(_=F());){if(_===po){$=T.backslashes=!0,_=F();continue}if(_===Gu){v=!0;break}}continue}break}if(p===!0){if(v=!0,r===!0)continue;break}}t.noext===!0&&(g=!1,p=!1);let H=l,G="",E="";d>0&&(G=l.slice(0,d),l=l.slice(d),f-=d),H&&p===!0&&f>0?(H=l.slice(0,f),E=l.slice(f)):p===!0?(H="",E=l):H=l,H&&H!==""&&H!=="/"&&H!==l&&Vu(H.charCodeAt(H.length-1))&&(H=H.slice(0,-1)),t.unescape===!0&&(E&&(E=Ku.removeBackslashes(E)),H&&$===!0&&(H=Ku.removeBackslashes(H)));let k={prefix:G,input:n,start:d,base:H,glob:E,isBrace:h,isBracket:m,isGlob:p,isExtglob:g,isGlobstar:x,negated:A,negatedExtglob:y};if(t.tokens===!0&&(k.maxDepth=0,Vu(_)||o.push(T),k.tokens=o),t.parts===!0||t.tokens===!0){let Y;for(let q=0;q<i.length;q++){let Z=Y?Y+1:d,ee=i[q],X=n.slice(Z,ee);t.tokens&&(q===0&&d!==0?(o[q].isPrefix=!0,o[q].value=G):o[q].value=X,zu(o[q]),k.maxDepth+=o[q].depth),(q!==0||X!=="")&&a.push(X),Y=ee}if(Y&&Y+1<n.length){let q=n.slice(Y+1);a.push(q),t.tokens&&(o[o.length-1].value=q,zu(o[o.length-1]),k.maxDepth+=o[o.length-1].depth)}k.slashes=i,k.parts=a}return k};Ju.exports=Pb});var nd=N((YC,td)=>{"use strict";var zn=Gn(),Ce=zs(),{MAX_LENGTH:Ys,POSIX_REGEX_SOURCE:Mb,REGEX_NON_SPECIAL_CHARS:Ib,REGEX_SPECIAL_CHARS_BACKREF:Db,REPLACEMENTS:Qu}=zn,Lb=(n,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...n,e);n.sort();let t=`[${n.join("-")}]`;try{new RegExp(t)}catch{return n.map(r=>Ce.escapeRegex(r)).join("..")}return t},wn=(n,e)=>`Missing ${n}: "${e}" - use "\\\\${e}" to match literal characters`,Zu=n=>{let e=[],t=0,s=0,r=0,i="",o=!1;for(let a of n){if(o===!0){i+=a,o=!1;continue}if(a==="\\"){i+=a,o=!0;continue}if(a==='"'){r=r===1?0:1,i+=a;continue}if(r===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")s++;else if(a===")"&&s>0)s--;else if(a==="|"&&s===0){e.push(i),i="";continue}}}i+=a}return e.push(i),e},Fb=n=>{let e=!1;for(let t of n){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},ed=n=>{let e=n.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(Fb(e))return e.replace(/\\(.)/g,"$1")},Nb=n=>{let e=n.map(ed).filter(Boolean);for(let t=0;t<e.length;t++)for(let s=t+1;s<e.length;s++){let r=e[t],i=e[s],o=r[0];if(!(!o||r!==o.repeat(r.length)||i!==o.repeat(i.length))&&(r===i||r.startsWith(i)||i.startsWith(r)))return!0}return!1},ho=(n,e=!0)=>{if(n[0]!=="+"&&n[0]!=="*"||n[1]!=="(")return;let t=0,s=0,r=0,i=!1;for(let o=1;o<n.length;o++){let a=n[o];if(i===!0){i=!1;continue}if(a==="\\"){i=!0;continue}if(a==='"'){r=r===1?0:1;continue}if(r!==1){if(a==="["){t++;continue}if(a==="]"&&t>0){t--;continue}if(!(t>0)){if(a==="("){s++;continue}if(a===")"&&(s--,s===0))return e===!0&&o!==n.length-1?void 0:{type:n[0],body:n.slice(2,o),end:o}}}}},jb=n=>{let e=0,t=[];for(;e<n.length;){let r=ho(n.slice(e),!1);if(!r||r.type!=="*")return;let i=Zu(r.body).map(a=>a.trim());if(i.length!==1)return;let o=ed(i[0]);if(!o||o.length!==1)return;t.push(o),e+=r.end+1}return t.length<1?void 0:`${t.length===1?Ce.escapeRegex(t[0]):`[${t.map(r=>Ce.escapeRegex(r)).join("")}]`}*`},Hb=n=>{let e=0,t=n.trim(),s=ho(t);for(;s;)e++,t=s.body.trim(),s=ho(t);return e},Bb=(n,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:zn.DEFAULT_MAX_EXTGLOB_RECURSION,s=Zu(n).map(r=>r.trim());if(s.length>1&&(s.some(r=>r==="")||s.some(r=>/^[*?]+$/.test(r))||Nb(s)))return{risky:!0};for(let r of s){let i=jb(r);if(i)return{risky:!0,safeOutput:i};if(Hb(r)>t)return{risky:!0}}return{risky:!1}},mo=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a string");n=Qu[n]||n;let t={...e},s=typeof t.maxLength=="number"?Math.min(Ys,t.maxLength):Ys,r=n.length;if(r>s)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${s}`);let i={type:"bos",value:"",output:t.prepend||""},o=[i],a=t.capture?"":"?:",l=Ce.isWindows(e),u=zn.globChars(l),d=zn.extglobChars(u),{DOT_LITERAL:f,PLUS_LITERAL:h,SLASH_LITERAL:m,ONE_CHAR:p,DOTS_SLASH:g,NO_DOT:x,NO_DOT_SLASH:w,NO_DOTS_SLASH:$,QMARK:A,QMARK_NO_DOT:y,STAR:v,START_ANCHOR:b}=u,S=P=>`(${a}(?:(?!${b}${P.dot?g:f}).)*?)`,_=t.dot?"":x,T=t.dot?A:y,I=t.bash===!0?S(t):v;t.capture&&(I=`(${I})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let C={input:n,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};n=Ce.removePrefix(n,C),r=n.length;let F=[],H=[],G=[],E=i,k,Y=()=>C.index===r-1,q=C.peek=(P=1)=>n[C.index+P],Z=C.advance=()=>n[++C.index]||"",ee=()=>n.slice(C.index+1),X=(P="",Q=0)=>{C.consumed+=P,C.index+=Q},ue=P=>{C.output+=P.output!=null?P.output:P.value,X(P.value)},Oe=()=>{let P=1;for(;q()==="!"&&(q(2)!=="("||q(3)==="?");)Z(),C.start++,P++;return P%2===0?!1:(C.negated=!0,C.start++,!0)},_e=P=>{C[P]++,G.push(P)},ne=P=>{C[P]--,G.pop()},U=P=>{if(E.type==="globstar"){let Q=C.braces>0&&(P.type==="comma"||P.type==="brace"),D=P.extglob===!0||F.length&&(P.type==="pipe"||P.type==="paren");P.type!=="slash"&&P.type!=="paren"&&!Q&&!D&&(C.output=C.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=I,C.output+=E.output)}if(F.length&&P.type!=="paren"&&(F[F.length-1].inner+=P.value),(P.value||P.output)&&ue(P),E&&E.type==="text"&&P.type==="text"){E.value+=P.value,E.output=(E.output||"")+P.value;return}P.prev=E,o.push(P),E=P},Pe=(P,Q)=>{let D={...d[Q],conditions:1,inner:""};D.prev=E,D.parens=C.parens,D.output=C.output,D.startIndex=C.index,D.tokensIndex=o.length;let K=(t.capture?"(":"")+D.open;_e("parens"),U({type:P,value:Q,output:C.output?"":p}),U({type:"paren",extglob:!0,value:Z(),output:K}),F.push(D)},Fe=P=>{let Q=n.slice(P.startIndex,C.index+1),D=n.slice(P.startIndex+2,C.index),K=Bb(D,t);if((P.type==="plus"||P.type==="star")&&K.risky){let oe=K.safeOutput?(P.output?"":p)+(t.capture?`(${K.safeOutput})`:K.safeOutput):void 0,gt=o[P.tokensIndex];gt.type="text",gt.value=Q,gt.output=oe||Ce.escapeRegex(Q);for(let yt=P.tokensIndex+1;yt<o.length;yt++)o[yt].value="",o[yt].output="",delete o[yt].suffix;C.output=P.output+gt.output,C.backtrack=!0,U({type:"paren",extglob:!0,value:k,output:""}),ne("parens");return}let ie=P.close+(t.capture?")":""),ve;if(P.type==="negate"){let oe=I;if(P.inner&&P.inner.length>1&&P.inner.includes("/")&&(oe=S(t)),(oe!==I||Y()||/^\)+$/.test(ee()))&&(ie=P.close=`)$))${oe}`),P.inner.includes("*")&&(ve=ee())&&/^\.[^\\/.]+$/.test(ve)){let gt=mo(ve,{...e,fastpaths:!1}).output;ie=P.close=`)${gt})${oe})`}P.prev.type==="bos"&&(C.negatedExtglob=!0)}U({type:"paren",extglob:!0,value:k,output:ie}),ne("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(n)){let P=!1,Q=n.replace(Db,(D,K,ie,ve,oe,gt)=>ve==="\\"?(P=!0,D):ve==="?"?K?K+ve+(oe?A.repeat(oe.length):""):gt===0?T+(oe?A.repeat(oe.length):""):A.repeat(ie.length):ve==="."?f.repeat(ie.length):ve==="*"?K?K+ve+(oe?I:""):I:K?D:`\\${D}`);return P===!0&&(t.unescape===!0?Q=Q.replace(/\\/g,""):Q=Q.replace(/\\+/g,D=>D.length%2===0?"\\\\":D?"\\":"")),Q===n&&t.contains===!0?(C.output=n,C):(C.output=Ce.wrapOutput(Q,C,e),C)}for(;!Y();){if(k=Z(),k==="\0")continue;if(k==="\\"){let D=q();if(D==="/"&&t.bash!==!0||D==="."||D===";")continue;if(!D){k+="\\",U({type:"text",value:k});continue}let K=/^\\+/.exec(ee()),ie=0;if(K&&K[0].length>2&&(ie=K[0].length,C.index+=ie,ie%2!==0&&(k+="\\")),t.unescape===!0?k=Z():k+=Z(),C.brackets===0){U({type:"text",value:k});continue}}if(C.brackets>0&&(k!=="]"||E.value==="["||E.value==="[^")){if(t.posix!==!1&&k===":"){let D=E.value.slice(1);if(D.includes("[")&&(E.posix=!0,D.includes(":"))){let K=E.value.lastIndexOf("["),ie=E.value.slice(0,K),ve=E.value.slice(K+2),oe=Mb[ve];if(oe){E.value=ie+oe,C.backtrack=!0,Z(),!i.output&&o.indexOf(E)===1&&(i.output=p);continue}}}(k==="["&&q()!==":"||k==="-"&&q()==="]")&&(k=`\\${k}`),k==="]"&&(E.value==="["||E.value==="[^")&&(k=`\\${k}`),t.posix===!0&&k==="!"&&E.value==="["&&(k="^"),E.value+=k,ue({value:k});continue}if(C.quotes===1&&k!=='"'){k=Ce.escapeRegex(k),E.value+=k,ue({value:k});continue}if(k==='"'){C.quotes=C.quotes===1?0:1,t.keepQuotes===!0&&U({type:"text",value:k});continue}if(k==="("){_e("parens"),U({type:"paren",value:k});continue}if(k===")"){if(C.parens===0&&t.strictBrackets===!0)throw new SyntaxError(wn("opening","("));let D=F[F.length-1];if(D&&C.parens===D.parens+1){Fe(F.pop());continue}U({type:"paren",value:k,output:C.parens?")":"\\)"}),ne("parens");continue}if(k==="["){if(t.nobracket===!0||!ee().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(wn("closing","]"));k=`\\${k}`}else _e("brackets");U({type:"bracket",value:k});continue}if(k==="]"){if(t.nobracket===!0||E&&E.type==="bracket"&&E.value.length===1){U({type:"text",value:k,output:`\\${k}`});continue}if(C.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(wn("opening","["));U({type:"text",value:k,output:`\\${k}`});continue}ne("brackets");let D=E.value.slice(1);if(E.posix!==!0&&D[0]==="^"&&!D.includes("/")&&(k=`/${k}`),E.value+=k,ue({value:k}),t.literalBrackets===!1||Ce.hasRegexChars(D))continue;let K=Ce.escapeRegex(E.value);if(C.output=C.output.slice(0,-E.value.length),t.literalBrackets===!0){C.output+=K,E.value=K;continue}E.value=`(${a}${K}|${E.value})`,C.output+=E.value;continue}if(k==="{"&&t.nobrace!==!0){_e("braces");let D={type:"brace",value:k,output:"(",outputIndex:C.output.length,tokensIndex:C.tokens.length};H.push(D),U(D);continue}if(k==="}"){let D=H[H.length-1];if(t.nobrace===!0||!D){U({type:"text",value:k,output:k});continue}let K=")";if(D.dots===!0){let ie=o.slice(),ve=[];for(let oe=ie.length-1;oe>=0&&(o.pop(),ie[oe].type!=="brace");oe--)ie[oe].type!=="dots"&&ve.unshift(ie[oe].value);K=Lb(ve,t),C.backtrack=!0}if(D.comma!==!0&&D.dots!==!0){let ie=C.output.slice(0,D.outputIndex),ve=C.tokens.slice(D.tokensIndex);D.value=D.output="\\{",k=K="\\}",C.output=ie;for(let oe of ve)C.output+=oe.output||oe.value}U({type:"brace",value:k,output:K}),ne("braces"),H.pop();continue}if(k==="|"){F.length>0&&F[F.length-1].conditions++,U({type:"text",value:k});continue}if(k===","){let D=k,K=H[H.length-1];K&&G[G.length-1]==="braces"&&(K.comma=!0,D="|"),U({type:"comma",value:k,output:D});continue}if(k==="/"){if(E.type==="dot"&&C.index===C.start+1){C.start=C.index+1,C.consumed="",C.output="",o.pop(),E=i;continue}U({type:"slash",value:k,output:m});continue}if(k==="."){if(C.braces>0&&E.type==="dot"){E.value==="."&&(E.output=f);let D=H[H.length-1];E.type="dots",E.output+=k,E.value+=k,D.dots=!0;continue}if(C.braces+C.parens===0&&E.type!=="bos"&&E.type!=="slash"){U({type:"text",value:k,output:f});continue}U({type:"dot",value:k,output:f});continue}if(k==="?"){if(!(E&&E.value==="(")&&t.noextglob!==!0&&q()==="("&&q(2)!=="?"){Pe("qmark",k);continue}if(E&&E.type==="paren"){let K=q(),ie=k;if(K==="<"&&!Ce.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(E.value==="("&&!/[!=<:]/.test(K)||K==="<"&&!/<([!=]|\w+>)/.test(ee()))&&(ie=`\\${k}`),U({type:"text",value:k,output:ie});continue}if(t.dot!==!0&&(E.type==="slash"||E.type==="bos")){U({type:"qmark",value:k,output:y});continue}U({type:"qmark",value:k,output:A});continue}if(k==="!"){if(t.noextglob!==!0&&q()==="("&&(q(2)!=="?"||!/[!=<:]/.test(q(3)))){Pe("negate",k);continue}if(t.nonegate!==!0&&C.index===0){Oe();continue}}if(k==="+"){if(t.noextglob!==!0&&q()==="("&&q(2)!=="?"){Pe("plus",k);continue}if(E&&E.value==="("||t.regex===!1){U({type:"plus",value:k,output:h});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||C.parens>0){U({type:"plus",value:k});continue}U({type:"plus",value:h});continue}if(k==="@"){if(t.noextglob!==!0&&q()==="("&&q(2)!=="?"){U({type:"at",extglob:!0,value:k,output:""});continue}U({type:"text",value:k});continue}if(k!=="*"){(k==="$"||k==="^")&&(k=`\\${k}`);let D=Ib.exec(ee());D&&(k+=D[0],C.index+=D[0].length),U({type:"text",value:k});continue}if(E&&(E.type==="globstar"||E.star===!0)){E.type="star",E.star=!0,E.value+=k,E.output=I,C.backtrack=!0,C.globstar=!0,X(k);continue}let P=ee();if(t.noextglob!==!0&&/^\([^?]/.test(P)){Pe("star",k);continue}if(E.type==="star"){if(t.noglobstar===!0){X(k);continue}let D=E.prev,K=D.prev,ie=D.type==="slash"||D.type==="bos",ve=K&&(K.type==="star"||K.type==="globstar");if(t.bash===!0&&(!ie||P[0]&&P[0]!=="/")){U({type:"star",value:k,output:""});continue}let oe=C.braces>0&&(D.type==="comma"||D.type==="brace"),gt=F.length&&(D.type==="pipe"||D.type==="paren");if(!ie&&D.type!=="paren"&&!oe&&!gt){U({type:"star",value:k,output:""});continue}for(;P.slice(0,3)==="/**";){let yt=n[C.index+4];if(yt&&yt!=="/")break;P=P.slice(3),X("/**",3)}if(D.type==="bos"&&Y()){E.type="globstar",E.value+=k,E.output=S(t),C.output=E.output,C.globstar=!0,X(k);continue}if(D.type==="slash"&&D.prev.type!=="bos"&&!ve&&Y()){C.output=C.output.slice(0,-(D.output+E.output).length),D.output=`(?:${D.output}`,E.type="globstar",E.output=S(t)+(t.strictSlashes?")":"|$)"),E.value+=k,C.globstar=!0,C.output+=D.output+E.output,X(k);continue}if(D.type==="slash"&&D.prev.type!=="bos"&&P[0]==="/"){let yt=P[1]!==void 0?"|$":"";C.output=C.output.slice(0,-(D.output+E.output).length),D.output=`(?:${D.output}`,E.type="globstar",E.output=`${S(t)}${m}|${m}${yt})`,E.value+=k,C.output+=D.output+E.output,C.globstar=!0,X(k+Z()),U({type:"slash",value:"/",output:""});continue}if(D.type==="bos"&&P[0]==="/"){E.type="globstar",E.value+=k,E.output=`(?:^|${m}|${S(t)}${m})`,C.output=E.output,C.globstar=!0,X(k+Z()),U({type:"slash",value:"/",output:""});continue}C.output=C.output.slice(0,-E.output.length),E.type="globstar",E.output=S(t),E.value+=k,C.output+=E.output,C.globstar=!0,X(k);continue}let Q={type:"star",value:k,output:I};if(t.bash===!0){Q.output=".*?",(E.type==="bos"||E.type==="slash")&&(Q.output=_+Q.output),U(Q);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&t.regex===!0){Q.output=k,U(Q);continue}(C.index===C.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(C.output+=w,E.output+=w):t.dot===!0?(C.output+=$,E.output+=$):(C.output+=_,E.output+=_),q()!=="*"&&(C.output+=p,E.output+=p)),U(Q)}for(;C.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(wn("closing","]"));C.output=Ce.escapeLast(C.output,"["),ne("brackets")}for(;C.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(wn("closing",")"));C.output=Ce.escapeLast(C.output,"("),ne("parens")}for(;C.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(wn("closing","}"));C.output=Ce.escapeLast(C.output,"{"),ne("braces")}if(t.strictSlashes!==!0&&(E.type==="star"||E.type==="bracket")&&U({type:"maybe_slash",value:"",output:`${m}?`}),C.backtrack===!0){C.output="";for(let P of C.tokens)C.output+=P.output!=null?P.output:P.value,P.suffix&&(C.output+=P.suffix)}return C};mo.fastpaths=(n,e)=>{let t={...e},s=typeof t.maxLength=="number"?Math.min(Ys,t.maxLength):Ys,r=n.length;if(r>s)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${s}`);n=Qu[n]||n;let i=Ce.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:l,DOTS_SLASH:u,NO_DOT:d,NO_DOTS:f,NO_DOTS_SLASH:h,STAR:m,START_ANCHOR:p}=zn.globChars(i),g=t.dot?f:d,x=t.dot?h:d,w=t.capture?"":"?:",$={negated:!1,prefix:""},A=t.bash===!0?".*?":m;t.capture&&(A=`(${A})`);let y=_=>_.noglobstar===!0?A:`(${w}(?:(?!${p}${_.dot?u:o}).)*?)`,v=_=>{switch(_){case"*":return`${g}${l}${A}`;case".*":return`${o}${l}${A}`;case"*.*":return`${g}${A}${o}${l}${A}`;case"*/*":return`${g}${A}${a}${l}${x}${A}`;case"**":return g+y(t);case"**/*":return`(?:${g}${y(t)}${a})?${x}${l}${A}`;case"**/*.*":return`(?:${g}${y(t)}${a})?${x}${A}${o}${l}${A}`;case"**/.*":return`(?:${g}${y(t)}${a})?${o}${l}${A}`;default:{let T=/^(.*?)\.(\w+)$/.exec(_);if(!T)return;let I=v(T[1]);return I?I+o+T[2]:void 0}}},b=Ce.removePrefix(n,$),S=v(b);return S&&t.strictSlashes!==!0&&(S+=`${a}?`),S};td.exports=mo});var rd=N((JC,sd)=>{"use strict";var Ub=require("path"),qb=Xu(),go=nd(),yo=zs(),Kb=Gn(),Wb=n=>n&&typeof n=="object"&&!Array.isArray(n),me=(n,e,t=!1)=>{if(Array.isArray(n)){let d=n.map(h=>me(h,e,t));return h=>{for(let m of d){let p=m(h);if(p)return p}return!1}}let s=Wb(n)&&n.tokens&&n.input;if(n===""||typeof n!="string"&&!s)throw new TypeError("Expected pattern to be a non-empty string");let r=e||{},i=yo.isWindows(e),o=s?me.compileRe(n,e):me.makeRe(n,e,!1,!0),a=o.state;delete o.state;let l=()=>!1;if(r.ignore){let d={...e,ignore:null,onMatch:null,onResult:null};l=me(r.ignore,d,t)}let u=(d,f=!1)=>{let{isMatch:h,match:m,output:p}=me.test(d,o,e,{glob:n,posix:i}),g={glob:n,state:a,regex:o,posix:i,input:d,output:p,match:m,isMatch:h};return typeof r.onResult=="function"&&r.onResult(g),h===!1?(g.isMatch=!1,f?g:!1):l(d)?(typeof r.onIgnore=="function"&&r.onIgnore(g),g.isMatch=!1,f?g:!1):(typeof r.onMatch=="function"&&r.onMatch(g),f?g:!0)};return t&&(u.state=a),u};me.test=(n,e,t,{glob:s,posix:r}={})=>{if(typeof n!="string")throw new TypeError("Expected input to be a string");if(n==="")return{isMatch:!1,output:""};let i=t||{},o=i.format||(r?yo.toPosixSlashes:null),a=n===s,l=a&&o?o(n):n;return a===!1&&(l=o?o(n):n,a=l===s),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=me.matchBase(n,e,t,r):a=e.exec(l)),{isMatch:!!a,match:a,output:l}};me.matchBase=(n,e,t,s=yo.isWindows(t))=>(e instanceof RegExp?e:me.makeRe(e,t)).test(Ub.basename(n));me.isMatch=(n,e,t)=>me(e,t)(n);me.parse=(n,e)=>Array.isArray(n)?n.map(t=>me.parse(t,e)):go(n,{...e,fastpaths:!1});me.scan=(n,e)=>qb(n,e);me.compileRe=(n,e,t=!1,s=!1)=>{if(t===!0)return n.output;let r=e||{},i=r.contains?"":"^",o=r.contains?"":"$",a=`${i}(?:${n.output})${o}`;n&&n.negated===!0&&(a=`^(?!${a}).*$`);let l=me.toRegex(a,e);return s===!0&&(l.state=n),l};me.makeRe=(n,e={},t=!1,s=!1)=>{if(!n||typeof n!="string")throw new TypeError("Expected a non-empty string");let r={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(n[0]==="."||n[0]==="*")&&(r.output=go.fastpaths(n,e)),r.output||(r=go(n,e)),me.compileRe(r,e,t,s)};me.toRegex=(n,e)=>{try{let t=e||{};return new RegExp(n,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};me.constants=Kb;sd.exports=me});var bo=N((XC,id)=>{"use strict";id.exports=rd()});var pd=N((QC,fd)=>{"use strict";var Jn=require("fs"),{Readable:Gb}=require("stream"),Yn=require("path"),{promisify:Zs}=require("util"),vo=bo(),Vb=Zs(Jn.readdir),zb=Zs(Jn.stat),od=Zs(Jn.lstat),Yb=Zs(Jn.realpath),Jb="!",ud="READDIRP_RECURSIVE_ERROR",Xb=new Set(["ENOENT","EPERM","EACCES","ELOOP",ud]),wo="files",dd="directories",Xs="files_directories",Js="all",ad=[wo,dd,Xs,Js],Qb=n=>Xb.has(n.code),[ld,Zb]=process.versions.node.split(".").slice(0,2).map(n=>Number.parseInt(n,10)),ev=process.platform==="win32"&&(ld>10||ld===10&&Zb>=5),cd=n=>{if(n!==void 0){if(typeof n=="function")return n;if(typeof n=="string"){let e=vo(n.trim());return t=>e(t.basename)}if(Array.isArray(n)){let e=[],t=[];for(let s of n){let r=s.trim();r.charAt(0)===Jb?t.push(vo(r.slice(1))):e.push(vo(r))}return t.length>0?e.length>0?s=>e.some(r=>r(s.basename))&&!t.some(r=>r(s.basename)):s=>!t.some(r=>r(s.basename)):s=>e.some(r=>r(s.basename))}}},Qs=class n extends Gb{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:wo,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let t={...n.defaultOptions,...e},{root:s,type:r}=t;this._fileFilter=cd(t.fileFilter),this._directoryFilter=cd(t.directoryFilter);let i=t.lstat?od:zb;ev?this._stat=o=>i(o,{bigint:!0}):this._stat=i,this._maxDepth=t.depth,this._wantsDir=[dd,Xs,Js].includes(r),this._wantsFile=[wo,Xs,Js].includes(r),this._wantsEverything=r===Js,this._root=Yn.resolve(s),this._isDirent="Dirent"in Jn&&!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(s,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:t,depth:s,files:r=[]}=this.parent||{};if(r.length>0){let i=r.splice(0,e).map(o=>this._formatEntry(o,t));for(let o of await Promise.all(i)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,s+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}if(this.parent=await i,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let s;try{s=await Vb(e,this._rdOptions)}catch(r){this._onError(r)}return{files:s,depth:t,path:e}}async _formatEntry(e,t){let s;try{let r=this._isDirent?e.name:e,i=Yn.resolve(Yn.join(t,r));s={path:Yn.relative(this._root,i),fullPath:i,basename:r},s[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(r){this._onError(r)}return s}_onError(e){Qb(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let t=e&&e[this._statsProp];if(t){if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let s=e.fullPath;try{let r=await Yb(s),i=await od(r);if(i.isFile())return"file";if(i.isDirectory()){let o=r.length;if(s.startsWith(r)&&s.substr(o,1)===Yn.sep){let a=new Error(`Circular symlink detected: "${s}" points to "${r}"`);return a.code=ud,this._onError(a)}return"directory"}}catch(r){this._onError(r)}}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}},xn=(n,e={})=>{let t=e.entryType||e.type;if(t==="both"&&(t=Xs),t&&(e.type=t),n){if(typeof n!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!ad.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${ad.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=n,new Qs(e)},tv=(n,e={})=>new Promise((t,s)=>{let r=[];xn(n,e).on("data",i=>r.push(i)).on("end",()=>t(r)).on("error",i=>s(i))});xn.promise=tv;xn.ReaddirpStream=Qs;xn.default=xn;fd.exports=xn});var xo=N((ZC,hd)=>{hd.exports=function(n,e){if(typeof n!="string")throw new TypeError("expected path to be a string");if(n==="\\"||n==="/")return"/";var t=n.length;if(t<=1)return n;var s="";if(t>4&&n[3]==="\\"){var r=n[2];(r==="?"||r===".")&&n.slice(0,2)==="\\\\"&&(n=n.slice(2),s="//")}var i=n.split(/[/\\]+/);return e!==!1&&i[i.length-1]===""&&i.pop(),s+i.join("/")}});var wd=N((bd,vd)=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var yd=bo(),nv=xo(),md="!",sv={returnIndex:!1},rv=n=>Array.isArray(n)?n:[n],iv=(n,e)=>{if(typeof n=="function")return n;if(typeof n=="string"){let t=yd(n,e);return s=>n===s||t(s)}return n instanceof RegExp?t=>n.test(t):t=>!1},gd=(n,e,t,s)=>{let r=Array.isArray(t),i=r?t[0]:t;if(!r&&typeof i!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(i));let o=nv(i,!1);for(let l=0;l<e.length;l++){let u=e[l];if(u(o))return s?-1:!1}let a=r&&[o].concat(t.slice(1));for(let l=0;l<n.length;l++){let u=n[l];if(r?u(...a):u(o))return s?l:!0}return s?-1:!1},So=(n,e,t=sv)=>{if(n==null)throw new TypeError("anymatch: specify first argument");let s=typeof t=="boolean"?{returnIndex:t}:t,r=s.returnIndex||!1,i=rv(n),o=i.filter(l=>typeof l=="string"&&l.charAt(0)===md).map(l=>l.slice(1)).map(l=>yd(l,s)),a=i.filter(l=>typeof l!="string"||typeof l=="string"&&l.charAt(0)!==md).map(l=>iv(l,s));return e==null?(l,u=!1)=>gd(a,o,l,typeof u=="boolean"?u:!1):gd(a,o,e,r)};So.default=So;vd.exports=So});var Sd=N((eE,xd)=>{xd.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var t;t=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(t[2])return!0;e=e.slice(t.index+t[0].length)}return!1}});var _o=N((tE,kd)=>{var ov=Sd(),_d={"{":"}","(":")","[":"]"},av=function(n){if(n[0]==="!")return!0;for(var e=0,t=-2,s=-2,r=-2,i=-2,o=-2;e<n.length;){if(n[e]==="*"||n[e+1]==="?"&&/[\].+)]/.test(n[e])||s!==-1&&n[e]==="["&&n[e+1]!=="]"&&(s<e&&(s=n.indexOf("]",e)),s>e&&(o===-1||o>s||(o=n.indexOf("\\",e),o===-1||o>s)))||r!==-1&&n[e]==="{"&&n[e+1]!=="}"&&(r=n.indexOf("}",e),r>e&&(o=n.indexOf("\\",e),o===-1||o>r))||i!==-1&&n[e]==="("&&n[e+1]==="?"&&/[:!=]/.test(n[e+2])&&n[e+3]!==")"&&(i=n.indexOf(")",e),i>e&&(o=n.indexOf("\\",e),o===-1||o>i))||t!==-1&&n[e]==="("&&n[e+1]!=="|"&&(t<e&&(t=n.indexOf("|",e)),t!==-1&&n[t+1]!==")"&&(i=n.indexOf(")",t),i>t&&(o=n.indexOf("\\",t),o===-1||o>i))))return!0;if(n[e]==="\\"){var a=n[e+1];e+=2;var l=_d[a];if(l){var u=n.indexOf(l,e);u!==-1&&(e=u+1)}if(n[e]==="!")return!0}else e++}return!1},lv=function(n){if(n[0]==="!")return!0;for(var e=0;e<n.length;){if(/[*?{}()[\]]/.test(n[e]))return!0;if(n[e]==="\\"){var t=n[e+1];e+=2;var s=_d[t];if(s){var r=n.indexOf(s,e);r!==-1&&(e=r+1)}if(n[e]==="!")return!0}else e++}return!1};kd.exports=function(e,t){if(typeof e!="string"||e==="")return!1;if(ov(e))return!0;var s=av;return t&&t.strict===!1&&(s=lv),s(e)}});var $d=N((nE,Ad)=>{"use strict";var cv=_o(),uv=require("path").posix.dirname,dv=require("os").platform()==="win32",ko="/",fv=/\\/g,pv=/[\{\[].*[\}\]]$/,hv=/(^|[^\\])([\{\[]|\([^\)]+$)/,mv=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Ad.exports=function(e,t){var s=Object.assign({flipBackslashes:!0},t);s.flipBackslashes&&dv&&e.indexOf(ko)<0&&(e=e.replace(fv,ko)),pv.test(e)&&(e+=ko),e+="a";do e=uv(e);while(cv(e)||hv.test(e));return e.replace(mv,"$1")}});var er=N(ze=>{"use strict";ze.isInteger=n=>typeof n=="number"?Number.isInteger(n):typeof n=="string"&&n.trim()!==""?Number.isInteger(Number(n)):!1;ze.find=(n,e)=>n.nodes.find(t=>t.type===e);ze.exceedsLimit=(n,e,t=1,s)=>s===!1||!ze.isInteger(n)||!ze.isInteger(e)?!1:(Number(e)-Number(n))/Number(t)>=s;ze.escapeNode=(n,e=0,t)=>{let s=n.nodes[e];s&&(t&&s.type===t||s.type==="open"||s.type==="close")&&s.escaped!==!0&&(s.value="\\"+s.value,s.escaped=!0)};ze.encloseBrace=n=>n.type!=="brace"?!1:n.commas>>0+n.ranges>>0===0?(n.invalid=!0,!0):!1;ze.isInvalidBrace=n=>n.type!=="brace"?!1:n.invalid===!0||n.dollar?!0:n.commas>>0+n.ranges>>0===0||n.open!==!0||n.close!==!0?(n.invalid=!0,!0):!1;ze.isOpenOrClose=n=>n.type==="open"||n.type==="close"?!0:n.open===!0||n.close===!0;ze.reduce=n=>n.reduce((e,t)=>(t.type==="text"&&e.push(t.value),t.type==="range"&&(t.type="text"),e),[]);ze.flatten=(...n)=>{let e=[],t=s=>{for(let r=0;r<s.length;r++){let i=s[r];if(Array.isArray(i)){t(i);continue}i!==void 0&&e.push(i)}return e};return t(n),e}});var tr=N((rE,Ed)=>{"use strict";var Cd=er();Ed.exports=(n,e={})=>{let t=(s,r={})=>{let i=e.escapeInvalid&&Cd.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(i||o)&&Cd.isOpenOrClose(s)?"\\"+s.value:s.value;if(s.value)return s.value;if(s.nodes)for(let l of s.nodes)a+=t(l);return a};return t(n)}});var Rd=N((iE,Td)=>{"use strict";Td.exports=function(n){return typeof n=="number"?n-n===0:typeof n=="string"&&n.trim()!==""?Number.isFinite?Number.isFinite(+n):isFinite(+n):!1}});var jd=N((oE,Nd)=>{"use strict";var Od=Rd(),Jt=(n,e,t)=>{if(Od(n)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||n===e)return String(n);if(Od(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let s={relaxZeros:!0,...t};typeof s.strictZeros=="boolean"&&(s.relaxZeros=s.strictZeros===!1);let r=String(s.relaxZeros),i=String(s.shorthand),o=String(s.capture),a=String(s.wrap),l=n+":"+e+"="+r+i+o+a;if(Jt.cache.hasOwnProperty(l))return Jt.cache[l].result;let u=Math.min(n,e),d=Math.max(n,e);if(Math.abs(u-d)===1){let g=n+"|"+e;return s.capture?`(${g})`:s.wrap===!1?g:`(?:${g})`}let f=Fd(n)||Fd(e),h={min:n,max:e,a:u,b:d},m=[],p=[];if(f&&(h.isPadded=f,h.maxLen=String(h.max).length),u<0){let g=d<0?Math.abs(d):1;p=Pd(g,Math.abs(u),h,s),u=h.a=0}return d>=0&&(m=Pd(u,d,h,s)),h.negatives=p,h.positives=m,h.result=gv(p,m,s),s.capture===!0?h.result=`(${h.result})`:s.wrap!==!1&&m.length+p.length>1&&(h.result=`(?:${h.result})`),Jt.cache[l]=h,h.result};function gv(n,e,t){let s=Ao(n,e,"-",!1,t)||[],r=Ao(e,n,"",!1,t)||[],i=Ao(n,e,"-?",!0,t)||[];return s.concat(i).concat(r).join("|")}function yv(n,e){let t=1,s=1,r=Id(n,t),i=new Set([e]);for(;n<=r&&r<=e;)i.add(r),t+=1,r=Id(n,t);for(r=Dd(e+1,s)-1;n<r&&r<=e;)i.add(r),s+=1,r=Dd(e+1,s)-1;return i=[...i],i.sort(wv),i}function bv(n,e,t){if(n===e)return{pattern:n,count:[],digits:0};let s=vv(n,e),r=s.length,i="",o=0;for(let a=0;a<r;a++){let[l,u]=s[a];l===u?i+=l:l!=="0"||u!=="9"?i+=xv(l,u,t):o++}return o&&(i+=t.shorthand===!0?"\\d":"[0-9]"),{pattern:i,count:[o],digits:r}}function Pd(n,e,t,s){let r=yv(n,e),i=[],o=n,a;for(let l=0;l<r.length;l++){let u=r[l],d=bv(String(o),String(u),s),f="";if(!t.isPadded&&a&&a.pattern===d.pattern){a.count.length>1&&a.count.pop(),a.count.push(d.count[0]),a.string=a.pattern+Ld(a.count),o=u+1;continue}t.isPadded&&(f=Sv(u,t,s)),d.string=f+d.pattern+Ld(d.count),i.push(d),o=u+1,a=d}return i}function Ao(n,e,t,s,r){let i=[];for(let o of n){let{string:a}=o;!s&&!Md(e,"string",a)&&i.push(t+a),s&&Md(e,"string",a)&&i.push(t+a)}return i}function vv(n,e){let t=[];for(let s=0;s<n.length;s++)t.push([n[s],e[s]]);return t}function wv(n,e){return n>e?1:e>n?-1:0}function Md(n,e,t){return n.some(s=>s[e]===t)}function Id(n,e){return Number(String(n).slice(0,-e)+"9".repeat(e))}function Dd(n,e){return n-n%Math.pow(10,e)}function Ld(n){let[e=0,t=""]=n;return t||e>1?`{${e+(t?","+t:"")}}`:""}function xv(n,e,t){return`[${n}${e-n===1?"":"-"}${e}]`}function Fd(n){return/^-?(0+)\d/.test(n)}function Sv(n,e,t){if(!e.isPadded)return n;let s=Math.abs(e.maxLen-String(n).length),r=t.relaxZeros!==!1;switch(s){case 0:return"";case 1:return r?"0?":"0";case 2:return r?"0{0,2}":"00";default:return r?`0{0,${s}}`:`0{${s}}`}}Jt.cache={};Jt.clearCache=()=>Jt.cache={};Nd.exports=Jt});var Eo=N((aE,Gd)=>{"use strict";var _v=require("util"),Bd=jd(),Hd=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),kv=n=>e=>n===!0?Number(e):String(e),$o=n=>typeof n=="number"||typeof n=="string"&&n!=="",Xn=n=>Number.isInteger(+n),Co=n=>{let e=`${n}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},Av=(n,e,t)=>typeof n=="string"||typeof e=="string"?!0:t.stringify===!0,$v=(n,e,t)=>{if(e>0){let s=n[0]==="-"?"-":"";s&&(n=n.slice(1)),n=s+n.padStart(s?e-1:e,"0")}return t===!1?String(n):n},sr=(n,e)=>{let t=n[0]==="-"?"-":"";for(t&&(n=n.slice(1),e--);n.length<e;)n="0"+n;return t?"-"+n:n},Cv=(n,e,t)=>{n.negatives.sort((a,l)=>a<l?-1:a>l?1:0),n.positives.sort((a,l)=>a<l?-1:a>l?1:0);let s=e.capture?"":"?:",r="",i="",o;return n.positives.length&&(r=n.positives.map(a=>sr(String(a),t)).join("|")),n.negatives.length&&(i=`-(${s}${n.negatives.map(a=>sr(String(a),t)).join("|")})`),r&&i?o=`${r}|${i}`:o=r||i,e.wrap?`(${s}${o})`:o},Ud=(n,e,t,s)=>{if(t)return Bd(n,e,{wrap:!1,...s});let r=String.fromCharCode(n);if(n===e)return r;let i=String.fromCharCode(e);return`[${r}-${i}]`},qd=(n,e,t)=>{if(Array.isArray(n)){let s=t.wrap===!0,r=t.capture?"":"?:";return s?`(${r}${n.join("|")})`:n.join("|")}return Bd(n,e,t)},Kd=(...n)=>new RangeError("Invalid range arguments: "+_v.inspect(...n)),Wd=(n,e,t)=>{if(t.strictRanges===!0)throw Kd([n,e]);return[]},Ev=(n,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${n}" to be a number`);return[]},Tv=(n,e,t=1,s={})=>{let r=Number(n),i=Number(e);if(!Number.isInteger(r)||!Number.isInteger(i)){if(s.strictRanges===!0)throw Kd([n,e]);return[]}r===0&&(r=0),i===0&&(i=0);let o=r>i,a=String(n),l=String(e),u=String(t);t=Math.max(Math.abs(t),1);let d=Co(a)||Co(l)||Co(u),f=d?Math.max(a.length,l.length,u.length):0,h=d===!1&&Av(n,e,s)===!1,m=s.transform||kv(h);if(s.toRegex&&t===1)return Ud(sr(n,f),sr(e,f),!0,s);let p={negatives:[],positives:[]},g=$=>p[$<0?"negatives":"positives"].push(Math.abs($)),x=[],w=0;for(;o?r>=i:r<=i;)s.toRegex===!0&&t>1?g(r):x.push($v(m(r,w),f,h)),r=o?r-t:r+t,w++;return s.toRegex===!0?t>1?Cv(p,s,f):qd(x,null,{wrap:!1,...s}):x},Rv=(n,e,t=1,s={})=>{if(!Xn(n)&&n.length>1||!Xn(e)&&e.length>1)return Wd(n,e,s);let r=s.transform||(h=>String.fromCharCode(h)),i=`${n}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=i>o,l=Math.min(i,o),u=Math.max(i,o);if(s.toRegex&&t===1)return Ud(l,u,!1,s);let d=[],f=0;for(;a?i>=o:i<=o;)d.push(r(i,f)),i=a?i-t:i+t,f++;return s.toRegex===!0?qd(d,null,{wrap:!1,options:s}):d},nr=(n,e,t,s={})=>{if(e==null&&$o(n))return[n];if(!$o(n)||!$o(e))return Wd(n,e,s);if(typeof t=="function")return nr(n,e,1,{transform:t});if(Hd(t))return nr(n,e,0,t);let r={...s};return r.capture===!0&&(r.wrap=!0),t=t||r.step||1,Xn(t)?Xn(n)&&Xn(e)?Tv(n,e,t,r):Rv(n,e,Math.max(Math.abs(t),1),r):t!=null&&!Hd(t)?Ev(t,r):nr(n,e,1,t)};Gd.exports=nr});var Yd=N((lE,zd)=>{"use strict";var Ov=Eo(),Vd=er(),Pv=(n,e={})=>{let t=(s,r={})=>{let i=Vd.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a=i===!0||o===!0,l=e.escapeInvalid===!0?"\\":"",u="";if(s.isOpen===!0)return l+s.value;if(s.isClose===!0)return console.log("node.isClose",l,s.value),l+s.value;if(s.type==="open")return a?l+s.value:"(";if(s.type==="close")return a?l+s.value:")";if(s.type==="comma")return s.prev.type==="comma"?"":a?s.value:"|";if(s.value)return s.value;if(s.nodes&&s.ranges>0){let d=Vd.reduce(s.nodes),f=Ov(...d,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(f.length!==0)return d.length>1&&f.length>1?`(${f})`:f}if(s.nodes)for(let d of s.nodes)u+=t(d,s);return u};return t(n)};zd.exports=Pv});var Qd=N((cE,Xd)=>{"use strict";var Mv=Eo(),Jd=tr(),Sn=er(),Xt=(n="",e="",t=!1)=>{let s=[];if(n=[].concat(n),e=[].concat(e),!e.length)return n;if(!n.length)return t?Sn.flatten(e).map(r=>`{${r}}`):e;for(let r of n)if(Array.isArray(r))for(let i of r)s.push(Xt(i,e,t));else for(let i of e)t===!0&&typeof i=="string"&&(i=`{${i}}`),s.push(Array.isArray(i)?Xt(r,i,t):r+i);return Sn.flatten(s)},Iv=(n,e={})=>{let t=e.rangeLimit===void 0?1e3:e.rangeLimit,s=(r,i={})=>{r.queue=[];let o=i,a=i.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(r.invalid||r.dollar){a.push(Xt(a.pop(),Jd(r,e)));return}if(r.type==="brace"&&r.invalid!==!0&&r.nodes.length===2){a.push(Xt(a.pop(),["{}"]));return}if(r.nodes&&r.ranges>0){let f=Sn.reduce(r.nodes);if(Sn.exceedsLimit(...f,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let h=Mv(...f,e);h.length===0&&(h=Jd(r,e)),a.push(Xt(a.pop(),h)),r.nodes=[];return}let l=Sn.encloseBrace(r),u=r.queue,d=r;for(;d.type!=="brace"&&d.type!=="root"&&d.parent;)d=d.parent,u=d.queue;for(let f=0;f<r.nodes.length;f++){let h=r.nodes[f];if(h.type==="comma"&&r.type==="brace"){f===1&&u.push(""),u.push("");continue}if(h.type==="close"){a.push(Xt(a.pop(),u,l));continue}if(h.value&&h.type!=="open"){u.push(Xt(u.pop(),h.value));continue}h.nodes&&s(h,r)}return u};return Sn.flatten(s(n))};Xd.exports=Iv});var ef=N((uE,Zd)=>{"use strict";Zd.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
311
- `,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var of=N((dE,rf)=>{"use strict";var Dv=tr(),{MAX_LENGTH:tf,CHAR_BACKSLASH:To,CHAR_BACKTICK:Lv,CHAR_COMMA:Fv,CHAR_DOT:Nv,CHAR_LEFT_PARENTHESES:jv,CHAR_RIGHT_PARENTHESES:Hv,CHAR_LEFT_CURLY_BRACE:Bv,CHAR_RIGHT_CURLY_BRACE:Uv,CHAR_LEFT_SQUARE_BRACKET:nf,CHAR_RIGHT_SQUARE_BRACKET:sf,CHAR_DOUBLE_QUOTE:qv,CHAR_SINGLE_QUOTE:Kv,CHAR_NO_BREAK_SPACE:Wv,CHAR_ZERO_WIDTH_NOBREAK_SPACE:Gv}=ef(),Vv=(n,e={})=>{if(typeof n!="string")throw new TypeError("Expected a string");let t=e||{},s=typeof t.maxLength=="number"?Math.min(tf,t.maxLength):tf;if(n.length>s)throw new SyntaxError(`Input length (${n.length}), exceeds max characters (${s})`);let r={type:"root",input:n,nodes:[]},i=[r],o=r,a=r,l=0,u=n.length,d=0,f=0,h,m=()=>n[d++],p=g=>{if(g.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&g.type==="text"){a.value+=g.value;return}return o.nodes.push(g),g.parent=o,g.prev=a,a=g,g};for(p({type:"bos"});d<u;)if(o=i[i.length-1],h=m(),!(h===Gv||h===Wv)){if(h===To){p({type:"text",value:(e.keepEscaping?h:"")+m()});continue}if(h===sf){p({type:"text",value:"\\"+h});continue}if(h===nf){l++;let g;for(;d<u&&(g=m());){if(h+=g,g===nf){l++;continue}if(g===To){h+=m();continue}if(g===sf&&(l--,l===0))break}p({type:"text",value:h});continue}if(h===jv){o=p({type:"paren",nodes:[]}),i.push(o),p({type:"text",value:h});continue}if(h===Hv){if(o.type!=="paren"){p({type:"text",value:h});continue}o=i.pop(),p({type:"text",value:h}),o=i[i.length-1];continue}if(h===qv||h===Kv||h===Lv){let g=h,x;for(e.keepQuotes!==!0&&(h="");d<u&&(x=m());){if(x===To){h+=x+m();continue}if(x===g){e.keepQuotes===!0&&(h+=x);break}h+=x}p({type:"text",value:h});continue}if(h===Bv){f++;let x={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:f,commas:0,ranges:0,nodes:[]};o=p(x),i.push(o),p({type:"open",value:h});continue}if(h===Uv){if(o.type!=="brace"){p({type:"text",value:h});continue}let g="close";o=i.pop(),o.close=!0,p({type:g,value:h}),f--,o=i[i.length-1];continue}if(h===Fv&&f>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:Dv(o)}]}p({type:"comma",value:h}),o.commas++;continue}if(h===Nv&&f>0&&o.commas===0){let g=o.nodes;if(f===0||g.length===0){p({type:"text",value:h});continue}if(a.type==="dot"){if(o.range=[],a.value+=h,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){g.pop();let x=g[g.length-1];x.value+=a.value+h,a=x,o.ranges--;continue}p({type:"dot",value:h});continue}p({type:"text",value:h})}do if(o=i.pop(),o.type!=="root"){o.nodes.forEach(w=>{w.nodes||(w.type==="open"&&(w.isOpen=!0),w.type==="close"&&(w.isClose=!0),w.nodes||(w.type="text"),w.invalid=!0)});let g=i[i.length-1],x=g.nodes.indexOf(o);g.nodes.splice(x,1,...o.nodes)}while(i.length>0);return p({type:"eos"}),r};rf.exports=Vv});var cf=N((fE,lf)=>{"use strict";var af=tr(),zv=Yd(),Yv=Qd(),Jv=of(),qe=(n,e={})=>{let t=[];if(Array.isArray(n))for(let s of n){let r=qe.create(s,e);Array.isArray(r)?t.push(...r):t.push(r)}else t=[].concat(qe.create(n,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};qe.parse=(n,e={})=>Jv(n,e);qe.stringify=(n,e={})=>af(typeof n=="string"?qe.parse(n,e):n,e);qe.compile=(n,e={})=>(typeof n=="string"&&(n=qe.parse(n,e)),zv(n,e));qe.expand=(n,e={})=>{typeof n=="string"&&(n=qe.parse(n,e));let t=Yv(n,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};qe.create=(n,e={})=>n===""||n.length<3?[n]:e.expand!==!0?qe.compile(n,e):qe.expand(n,e);lf.exports=qe});var uf=N((pE,Xv)=>{Xv.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]});var ff=N((hE,df)=>{df.exports=uf()});var hf=N((mE,pf)=>{"use strict";var Qv=require("path"),Zv=ff(),ew=new Set(Zv);pf.exports=n=>ew.has(Qv.extname(n).slice(1).toLowerCase())});var rr=N(B=>{"use strict";var{sep:tw}=require("path"),{platform:Ro}=process,nw=require("os");B.EV_ALL="all";B.EV_READY="ready";B.EV_ADD="add";B.EV_CHANGE="change";B.EV_ADD_DIR="addDir";B.EV_UNLINK="unlink";B.EV_UNLINK_DIR="unlinkDir";B.EV_RAW="raw";B.EV_ERROR="error";B.STR_DATA="data";B.STR_END="end";B.STR_CLOSE="close";B.FSEVENT_CREATED="created";B.FSEVENT_MODIFIED="modified";B.FSEVENT_DELETED="deleted";B.FSEVENT_MOVED="moved";B.FSEVENT_CLONED="cloned";B.FSEVENT_UNKNOWN="unknown";B.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;B.FSEVENT_TYPE_FILE="file";B.FSEVENT_TYPE_DIRECTORY="directory";B.FSEVENT_TYPE_SYMLINK="symlink";B.KEY_LISTENERS="listeners";B.KEY_ERR="errHandlers";B.KEY_RAW="rawEmitters";B.HANDLER_KEYS=[B.KEY_LISTENERS,B.KEY_ERR,B.KEY_RAW];B.DOT_SLASH=`.${tw}`;B.BACK_SLASH_RE=/\\/g;B.DOUBLE_SLASH_RE=/\/\//;B.SLASH_OR_BACK_SLASH_RE=/[/\\]/;B.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;B.REPLACER_RE=/^\.[/\\]/;B.SLASH="/";B.SLASH_SLASH="//";B.BRACE_START="{";B.BANG="!";B.ONE_DOT=".";B.TWO_DOTS="..";B.STAR="*";B.GLOBSTAR="**";B.ROOT_GLOBSTAR="/**/*";B.SLASH_GLOBSTAR="/**";B.DIR_SUFFIX="Dir";B.ANYMATCH_OPTS={dot:!0};B.STRING_TYPE="string";B.FUNCTION_TYPE="function";B.EMPTY_STR="";B.EMPTY_FN=()=>{};B.IDENTITY_FN=n=>n;B.isWindows=Ro==="win32";B.isMacos=Ro==="darwin";B.isLinux=Ro==="linux";B.isIBMi=nw.type()==="OS400"});var wf=N((yE,vf)=>{"use strict";var Mt=require("fs"),xe=require("path"),{promisify:ts}=require("util"),sw=hf(),{isWindows:rw,isLinux:iw,EMPTY_FN:ow,EMPTY_STR:aw,KEY_LISTENERS:_n,KEY_ERR:Oo,KEY_RAW:Qn,HANDLER_KEYS:lw,EV_CHANGE:or,EV_ADD:ir,EV_ADD_DIR:cw,EV_ERROR:gf,STR_DATA:uw,STR_END:dw,BRACE_START:fw,STAR:pw}=rr(),hw="watch",mw=ts(Mt.open),yf=ts(Mt.stat),gw=ts(Mt.lstat),yw=ts(Mt.close),Po=ts(Mt.realpath),bw={lstat:gw,stat:yf},Io=(n,e)=>{n instanceof Set?n.forEach(e):e(n)},Zn=(n,e,t)=>{let s=n[e];s instanceof Set||(n[e]=s=new Set([s])),s.add(t)},vw=n=>e=>{let t=n[e];t instanceof Set?t.clear():delete n[e]},es=(n,e,t)=>{let s=n[e];s instanceof Set?s.delete(t):s===t&&delete n[e]},bf=n=>n instanceof Set?n.size===0:!n,ar=new Map;function mf(n,e,t,s,r){let i=(o,a)=>{t(n),r(o,a,{watchedPath:n}),a&&n!==a&&lr(xe.resolve(n,a),_n,xe.join(n,a))};try{return Mt.watch(n,e,i)}catch(o){s(o)}}var lr=(n,e,t,s,r)=>{let i=ar.get(n);i&&Io(i[e],o=>{o(t,s,r)})},ww=(n,e,t,s)=>{let{listener:r,errHandler:i,rawEmitter:o}=s,a=ar.get(e),l;if(!t.persistent)return l=mf(n,t,r,i,o),l.close.bind(l);if(a)Zn(a,_n,r),Zn(a,Oo,i),Zn(a,Qn,o);else{if(l=mf(n,t,lr.bind(null,e,_n),i,lr.bind(null,e,Qn)),!l)return;l.on(gf,async u=>{let d=lr.bind(null,e,Oo);if(a.watcherUnusable=!0,rw&&u.code==="EPERM")try{let f=await mw(n,"r");await yw(f),d(u)}catch{}else d(u)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:l},ar.set(e,a)}return()=>{es(a,_n,r),es(a,Oo,i),es(a,Qn,o),bf(a.listeners)&&(a.watcher.close(),ar.delete(e),lw.forEach(vw(a)),a.watcher=void 0,Object.freeze(a))}},Mo=new Map,xw=(n,e,t,s)=>{let{listener:r,rawEmitter:i}=s,o=Mo.get(e),a=new Set,l=new Set,u=o&&o.options;return u&&(u.persistent<t.persistent||u.interval>t.interval)&&(a=o.listeners,l=o.rawEmitters,Mt.unwatchFile(e),o=void 0),o?(Zn(o,_n,r),Zn(o,Qn,i)):(o={listeners:r,rawEmitters:i,options:t,watcher:Mt.watchFile(e,t,(d,f)=>{Io(o.rawEmitters,m=>{m(or,e,{curr:d,prev:f})});let h=d.mtimeMs;(d.size!==f.size||h>f.mtimeMs||h===0)&&Io(o.listeners,m=>m(n,d))})},Mo.set(e,o)),()=>{es(o,_n,r),es(o,Qn,i),bf(o.listeners)&&(Mo.delete(e),Mt.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},Do=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let s=this.fsw.options,r=xe.dirname(e),i=xe.basename(e);this.fsw._getWatchedDir(r).add(i);let a=xe.resolve(e),l={persistent:s.persistent};t||(t=ow);let u;return s.usePolling?(l.interval=s.enableBinaryInterval&&sw(i)?s.binaryInterval:s.interval,u=xw(e,a,l,{listener:t,rawEmitter:this.fsw._emitRaw})):u=ww(e,a,l,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),u}_handleFile(e,t,s){if(this.fsw.closed)return;let r=xe.dirname(e),i=xe.basename(e),o=this.fsw._getWatchedDir(r),a=t;if(o.has(i))return;let l=async(d,f)=>{if(this.fsw._throttle(hw,e,5)){if(!f||f.mtimeMs===0)try{let h=await yf(e);if(this.fsw.closed)return;let m=h.atimeMs,p=h.mtimeMs;(!m||m<=p||p!==a.mtimeMs)&&this.fsw._emit(or,e,h),iw&&a.ino!==h.ino?(this.fsw._closeFile(d),a=h,this.fsw._addPathCloser(d,this._watchWithNodeFs(e,l))):a=h}catch{this.fsw._remove(r,i)}else if(o.has(i)){let h=f.atimeMs,m=f.mtimeMs;(!h||h<=m||m!==a.mtimeMs)&&this.fsw._emit(or,e,f),a=f}}},u=this._watchWithNodeFs(e,l);if(!(s&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(ir,e,0))return;this.fsw._emit(ir,e,t)}return u}async _handleSymlink(e,t,s,r){if(this.fsw.closed)return;let i=e.fullPath,o=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await Po(s)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(r)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(or,s,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(ir,s,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,s,r,i,o,a){if(e=xe.join(e,aw),!s.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let l=this.fsw._getWatchedDir(s.path),u=new Set,d=this.fsw._readdirp(e,{fileFilter:f=>s.filterPath(f),directoryFilter:f=>s.filterDir(f),depth:0}).on(uw,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,m=xe.join(e,h);if(u.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===r||!r&&!l.has(h))&&(this.fsw._incrReadyCount(),m=xe.join(i,xe.relative(i,m)),this._addToNodeFs(m,t,s,o+1))}}).on(gf,this._boundHandleError);return new Promise(f=>d.once(dw,()=>{if(this.fsw.closed){d=void 0;return}let h=a?a.clear():!1;f(),l.getChildren().filter(m=>m!==e&&!u.has(m)&&(!s.hasGlob||s.filterPath({fullPath:xe.resolve(e,m)}))).forEach(m=>{this.fsw._remove(e,m)}),d=void 0,h&&this._handleRead(e,!1,s,r,i,o,a)}))}async _handleDir(e,t,s,r,i,o,a){let l=this.fsw._getWatchedDir(xe.dirname(e)),u=l.has(xe.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!i&&!u&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(cw,e,t),l.add(xe.basename(e)),this.fsw._getWatchedDir(e);let d,f,h=this.fsw.options.depth;if((h==null||r<=h)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,s,o,i,e,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(m,p)=>{p&&p.mtimeMs===0||this._handleRead(m,!1,o,i,e,r,d)})}return f}async _addToNodeFs(e,t,s,r,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,r);!a.hasGlob&&s&&(a.hasGlob=s.hasGlob,a.globFilter=s.globFilter,a.filterPath=l=>s.filterPath(l),a.filterDir=l=>s.filterDir(l));try{let l=await bw[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))return o(),!1;let u=this.fsw.options.followSymlinks&&!e.includes(pw)&&!e.includes(fw),d;if(l.isDirectory()){let f=xe.resolve(e),h=u?await Po(e):e;if(this.fsw.closed||(d=await this._handleDir(a.watchPath,l,t,r,i,a,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(l.isSymbolicLink()){let f=u?await Po(e):e;if(this.fsw.closed)return;let h=xe.dirname(a.watchPath);if(this.fsw._getWatchedDir(h).add(a.watchPath),this.fsw._emit(ir,a.watchPath,l),d=await this._handleDir(h,l,t,r,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(xe.resolve(e),f)}else d=this._handleFile(a.watchPath,l,t);return o(),this.fsw._addPathCloser(e,d),!1}catch(l){if(this.fsw._handleError(l))return o(),e}}};vf.exports=Do});var Cf=N((bE,qo)=>{"use strict";var Bo=require("fs"),Se=require("path"),{promisify:Uo}=require("util"),kn;try{kn=require("fsevents")}catch(n){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(n)}if(kn){let n=process.version.match(/v(\d+)\.(\d+)/);if(n&&n[1]&&n[2]){let e=Number.parseInt(n[1],10),t=Number.parseInt(n[2],10);e===8&&t<16&&(kn=void 0)}}var{EV_ADD:Lo,EV_CHANGE:Sw,EV_ADD_DIR:xf,EV_UNLINK:cr,EV_ERROR:_w,STR_DATA:kw,STR_END:Aw,FSEVENT_CREATED:$w,FSEVENT_MODIFIED:Cw,FSEVENT_DELETED:Ew,FSEVENT_MOVED:Tw,FSEVENT_UNKNOWN:Rw,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:Ow,FSEVENT_TYPE_FILE:Pw,FSEVENT_TYPE_DIRECTORY:ns,FSEVENT_TYPE_SYMLINK:$f,ROOT_GLOBSTAR:Sf,DIR_SUFFIX:Mw,DOT_SLASH:_f,FUNCTION_TYPE:Fo,EMPTY_FN:Iw,IDENTITY_FN:Dw}=rr(),Lw=n=>isNaN(n)?{}:{depth:n},jo=Uo(Bo.stat),Fw=Uo(Bo.lstat),kf=Uo(Bo.realpath),Nw={stat:jo,lstat:Fw},Qt=new Map,jw=10,Hw=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),Bw=(n,e)=>({stop:kn.watch(n,e)});function Uw(n,e,t,s){let r=Se.extname(e)?Se.dirname(e):e,i=Se.dirname(r),o=Qt.get(r);qw(i)&&(r=i);let a=Se.resolve(n),l=a!==e,u=(f,h,m)=>{l&&(f=f.replace(e,a)),(f===a||!f.indexOf(a+Se.sep))&&t(f,h,m)},d=!1;for(let f of Qt.keys())if(e.indexOf(Se.resolve(f)+Se.sep)===0){r=f,o=Qt.get(r),d=!0;break}return o||d?o.listeners.add(u):(o={listeners:new Set([u]),rawEmitter:s,watcher:Bw(r,(f,h)=>{if(!o.listeners.size||h&Ow)return;let m=kn.getInfo(f,h);o.listeners.forEach(p=>{p(f,h,m)}),o.rawEmitter(m.event,f,m)})},Qt.set(r,o)),()=>{let f=o.listeners;if(f.delete(u),!f.size&&(Qt.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var qw=n=>{let e=0;for(let t of Qt.keys())if(t.indexOf(n)===0&&(e++,e>=jw))return!0;return!1},Kw=()=>kn&&Qt.size<128,No=(n,e)=>{let t=0;for(;!n.indexOf(e)&&(n=Se.dirname(n))!==e;)t++;return t},Af=(n,e)=>n.type===ns&&e.isDirectory()||n.type===$f&&e.isSymbolicLink()||n.type===Pw&&e.isFile(),Ho=class{constructor(e){this.fsw=e}checkIgnored(e,t){let s=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,t))return s.add(e),t&&t.isDirectory()&&s.add(e+Sf),!0;s.delete(e),s.delete(e+Sf)}addOrChange(e,t,s,r,i,o,a,l){let u=i.has(o)?Sw:Lo;this.handleEvent(u,e,t,s,r,i,o,a,l)}async checkExists(e,t,s,r,i,o,a,l){try{let u=await jo(e);if(this.fsw.closed)return;Af(a,u)?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(cr,e,t,s,r,i,o,a,l)}catch(u){u.code==="EACCES"?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(cr,e,t,s,r,i,o,a,l)}}handleEvent(e,t,s,r,i,o,a,l,u){if(!(this.fsw.closed||this.checkIgnored(t)))if(e===cr){let d=l.type===ns;(d||o.has(a))&&this.fsw._remove(i,a,d)}else{if(e===Lo){if(l.type===ns&&this.fsw._getWatchedDir(t),l.type===$f&&u.followSymlinks){let f=u.depth===void 0?void 0:No(s,r)+1;return this._addToFsEvents(t,!1,!0,f)}this.fsw._getWatchedDir(i).add(a)}let d=l.type===ns?e+Mw:e;this.fsw._emit(d,t),d===xf&&this._addToFsEvents(t,!1,!0)}}_watchWithFsEvents(e,t,s,r){if(this.fsw.closed||this.fsw._isIgnored(e))return;let i=this.fsw.options,a=Uw(e,t,async(l,u,d)=>{if(this.fsw.closed||i.depth!==void 0&&No(l,t)>i.depth)return;let f=s(Se.join(e,Se.relative(e,l)));if(r&&!r(f))return;let h=Se.dirname(f),m=Se.basename(f),p=this.fsw._getWatchedDir(d.type===ns?f:h);if(Hw.has(u)||d.event===Rw)if(typeof i.ignored===Fo){let g;try{g=await jo(f)}catch{}if(this.fsw.closed||this.checkIgnored(f,g))return;Af(d,g)?this.addOrChange(f,l,t,h,p,m,d,i):this.handleEvent(cr,f,l,t,h,p,m,d,i)}else this.checkExists(f,l,t,h,p,m,d,i);else switch(d.event){case $w:case Cw:return this.addOrChange(f,l,t,h,p,m,d,i);case Ew:case Tw:return this.checkExists(f,l,t,h,p,m,d,i)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,t,s,r){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(t))){this.fsw._symlinkPaths.set(t,!0),this.fsw._incrReadyCount();try{let i=await kf(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(i))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(i||e,o=>{let a=e;return i&&i!==_f?a=o.replace(i,e):o!==_f&&(a=Se.join(e,o)),s(a)},!1,r)}catch(i){if(this.fsw._handleError(i))return this.fsw._emitReady()}}}emitAdd(e,t,s,r,i){let o=s(e),a=t.isDirectory(),l=this.fsw._getWatchedDir(Se.dirname(o)),u=Se.basename(o);a&&this.fsw._getWatchedDir(o),!l.has(u)&&(l.add(u),(!r.ignoreInitial||i===!0)&&this.fsw._emit(a?xf:Lo,o,t))}initWatch(e,t,s,r){if(this.fsw.closed)return;let i=this._watchWithFsEvents(s.watchPath,Se.resolve(e||s.watchPath),r,s.globFilter);this.fsw._addPathCloser(t,i)}async _addToFsEvents(e,t,s,r){if(this.fsw.closed)return;let i=this.fsw.options,o=typeof t===Fo?t:Dw,a=this.fsw._getWatchHelpers(e);try{let l=await Nw[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))throw null;if(l.isDirectory()){if(a.globFilter||this.emitAdd(o(e),l,o,i,s),r&&r>i.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:u=>a.filterPath(u),directoryFilter:u=>a.filterDir(u),...Lw(i.depth-(r||0))}).on(kw,u=>{if(this.fsw.closed||u.stats.isDirectory()&&!a.filterPath(u))return;let d=Se.join(a.watchPath,u.path),{fullPath:f}=u;if(a.followSymlinks&&u.stats.isSymbolicLink()){let h=i.depth===void 0?void 0:No(d,Se.resolve(a.watchPath))+1;this._handleFsEventsSymlink(d,f,o,h)}else this.emitAdd(d,u.stats,o,i,s)}).on(_w,Iw).on(Aw,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,l,o,i,s),this.fsw._emitReady()}catch(l){(!l||this.fsw._handleError(l))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(i.persistent&&s!==!0)if(typeof t===Fo)this.initWatch(void 0,e,a,o);else{let l;try{l=await kf(a.watchPath)}catch{}this.initWatch(l,e,a,o)}}};qo.exports=Ho;qo.exports.canUse=Kw});var Nf=N(ra=>{"use strict";var{EventEmitter:Ww}=require("events"),na=require("fs"),se=require("path"),{promisify:If}=require("util"),Gw=pd(),Yo=wd().default,Vw=$d(),Ko=_o(),zw=cf(),Yw=xo(),Jw=wf(),Ef=Cf(),{EV_ALL:Wo,EV_READY:Xw,EV_ADD:ur,EV_CHANGE:ss,EV_UNLINK:Tf,EV_ADD_DIR:Qw,EV_UNLINK_DIR:Zw,EV_RAW:ex,EV_ERROR:Go,STR_CLOSE:tx,STR_END:nx,BACK_SLASH_RE:sx,DOUBLE_SLASH_RE:Rf,SLASH_OR_BACK_SLASH_RE:rx,DOT_RE:ix,REPLACER_RE:ox,SLASH:Vo,SLASH_SLASH:ax,BRACE_START:lx,BANG:Jo,ONE_DOT:Df,TWO_DOTS:cx,GLOBSTAR:ux,SLASH_GLOBSTAR:zo,ANYMATCH_OPTS:Xo,STRING_TYPE:sa,FUNCTION_TYPE:dx,EMPTY_STR:Qo,EMPTY_FN:fx,isWindows:px,isMacos:hx,isIBMi:mx}=rr(),gx=If(na.stat),yx=If(na.readdir),Zo=(n=[])=>Array.isArray(n)?n:[n],Lf=(n,e=[])=>(n.forEach(t=>{Array.isArray(t)?Lf(t,e):e.push(t)}),e),Of=n=>{let e=Lf(Zo(n));if(!e.every(t=>typeof t===sa))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Ff)},Pf=n=>{let e=n.replace(sx,Vo),t=!1;for(e.startsWith(ax)&&(t=!0);e.match(Rf);)e=e.replace(Rf,Vo);return t&&(e=Vo+e),e},Ff=n=>Pf(se.normalize(Pf(n))),Mf=(n=Qo)=>e=>typeof e!==sa?e:Ff(se.isAbsolute(e)?e:se.join(n,e)),bx=(n,e)=>se.isAbsolute(n)?n:n.startsWith(Jo)?Jo+se.join(e,n.slice(1)):se.join(e,n),it=(n,e)=>n[e]===void 0,ea=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Df&&e!==cx&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let s=this.path;try{await yx(s)}catch{this._removeWatcher&&this._removeWatcher(se.dirname(s),se.basename(s))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;if(e)return[...e.values()]}dispose(){this.items.clear(),delete this.path,delete this._removeWatcher,delete this.items,Object.freeze(this)}},vx="stat",wx="lstat",ta=class{constructor(e,t,s,r){this.fsw=r,this.path=e=e.replace(ox,Qo),this.watchPath=t,this.fullWatchPath=se.resolve(t),this.hasGlob=t!==e,e===Qo&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&s?void 0:!1,this.globFilter=this.hasGlob?Yo(e,void 0,Xo):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=s,this.statMethod=s?vx:wx}checkGlobSymlink(e){return this.globSymlink===void 0&&(this.globSymlink=e.fullParentDir===this.fullWatchPath?!1:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}),this.globSymlink?e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath):e.fullPath}entryPath(e){return se.join(this.watchPath,se.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let s=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===dx?this.globFilter(s):!0)&&this.fsw._isntIgnored(s,t)&&this.fsw._hasReadPermissions(t)}getDirParts(e){if(!this.hasGlob)return[];let t=[];return(e.includes(lx)?zw.expand(e):[e]).forEach(r=>{t.push(se.relative(this.watchPath,r).split(rx))}),t}filterDir(e){if(this.hasGlob){let t=this.getDirParts(this.checkGlobSymlink(e)),s=!1;this.unmatchedGlob=!this.dirParts.some(r=>r.every((i,o)=>(i===ux&&(s=!0),s||!t[0][o]||Yo(i,t[0][o],Xo))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},dr=class extends Ww{constructor(e){super();let t={};e&&Object.assign(t,e),this._watched=new Map,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._symlinkPaths=new Map,this._streams=new Set,this.closed=!1,it(t,"persistent")&&(t.persistent=!0),it(t,"ignoreInitial")&&(t.ignoreInitial=!1),it(t,"ignorePermissionErrors")&&(t.ignorePermissionErrors=!1),it(t,"interval")&&(t.interval=100),it(t,"binaryInterval")&&(t.binaryInterval=300),it(t,"disableGlobbing")&&(t.disableGlobbing=!1),t.enableBinaryInterval=t.binaryInterval!==t.interval,it(t,"useFsEvents")&&(t.useFsEvents=!t.usePolling),Ef.canUse()||(t.useFsEvents=!1),it(t,"usePolling")&&!t.useFsEvents&&(t.usePolling=hx),mx&&(t.usePolling=!0);let r=process.env.CHOKIDAR_USEPOLLING;if(r!==void 0){let l=r.toLowerCase();l==="false"||l==="0"?t.usePolling=!1:l==="true"||l==="1"?t.usePolling=!0:t.usePolling=!!l}let i=process.env.CHOKIDAR_INTERVAL;i&&(t.interval=Number.parseInt(i,10)),it(t,"atomic")&&(t.atomic=!t.usePolling&&!t.useFsEvents),t.atomic&&(this._pendingUnlinks=new Map),it(t,"followSymlinks")&&(t.followSymlinks=!0),it(t,"awaitWriteFinish")&&(t.awaitWriteFinish=!1),t.awaitWriteFinish===!0&&(t.awaitWriteFinish={});let o=t.awaitWriteFinish;o&&(o.stabilityThreshold||(o.stabilityThreshold=2e3),o.pollInterval||(o.pollInterval=100),this._pendingWrites=new Map),t.ignored&&(t.ignored=Zo(t.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=fx,this._readyEmitted=!0,process.nextTick(()=>this.emit(Xw)))},this._emitRaw=(...l)=>this.emit(ex,...l),this._readyEmitted=!1,this.options=t,t.useFsEvents?this._fsEventsHandler=new Ef(this):this._nodeFsHandler=new Jw(this),Object.freeze(t)}add(e,t,s){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=Of(e);return r&&(o=o.map(a=>{let l=bx(a,r);return i||!Ko(a)?l:Yw(l)})),o=o.filter(a=>a.startsWith(Jo)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+zo),this._userIgnored=void 0,!0)),this.options.useFsEvents&&this._fsEventsHandler?(this._readyCount||(this._readyCount=o.length),this.options.persistent&&(this._readyCount+=o.length),o.forEach(a=>this._fsEventsHandler._addToFsEvents(a))):(this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let l=await this._nodeFsHandler._addToNodeFs(a,!s,0,0,t);return l&&this._emitReady(),l})).then(a=>{this.closed||a.filter(l=>l).forEach(l=>{this.add(se.dirname(l),se.basename(t||l))})})),this}unwatch(e){if(this.closed)return this;let t=Of(e),{cwd:s}=this.options;return t.forEach(r=>{!se.isAbsolute(r)&&!this._closers.has(r)&&(s&&(r=se.join(s,r)),r=se.resolve(r)),this._closePath(r),this._ignoredPaths.add(r),this._watched.has(r)&&this._ignoredPaths.add(r+zo),this._userIgnored=void 0}),this}close(){if(this.closed)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(s=>{let r=s();r instanceof Promise&&e.push(r)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),["closers","watched","streams","symlinkPaths","throttled"].forEach(t=>{this[`_${t}`].clear()}),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,s)=>{let r=this.options.cwd?se.relative(this.options.cwd,s):s;e[r||Df]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(...t),e!==Go&&this.emit(Wo,...t)}async _emit(e,t,s,r,i){if(this.closed)return;let o=this.options;px&&(t=se.normalize(t)),o.cwd&&(t=se.relative(o.cwd,t));let a=[e,t];i!==void 0?a.push(s,r,i):r!==void 0?a.push(s,r):s!==void 0&&a.push(s);let l=o.awaitWriteFinish,u;if(l&&(u=this._pendingWrites.get(t)))return u.lastChange=new Date,this;if(o.atomic){if(e===Tf)return this._pendingUnlinks.set(t,a),setTimeout(()=>{this._pendingUnlinks.forEach((d,f)=>{this.emit(...d),this.emit(Wo,...d),this._pendingUnlinks.delete(f)})},typeof o.atomic=="number"?o.atomic:100),this;e===ur&&this._pendingUnlinks.has(t)&&(e=a[0]=ss,this._pendingUnlinks.delete(t))}if(l&&(e===ur||e===ss)&&this._readyEmitted){let d=(f,h)=>{f?(e=a[0]=Go,a[1]=f,this.emitWithAll(e,a)):h&&(a.length>2?a[2]=h:a.push(h),this.emitWithAll(e,a))};return this._awaitWriteFinish(t,l.stabilityThreshold,e,d),this}if(e===ss&&!this._throttle(ss,t,50))return this;if(o.alwaysStat&&s===void 0&&(e===ur||e===Qw||e===ss)){let d=o.cwd?se.join(o.cwd,t):t,f;try{f=await gx(d)}catch{}if(!f||this.closed)return;a.push(f)}return this.emitWithAll(e,a),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(Go,e),e||this.closed}_throttle(e,t,s){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e),i=r.get(t);if(i)return i.count++,!1;let o,a=()=>{let u=r.get(t),d=u?u.count:0;return r.delete(t),clearTimeout(o),u&&clearTimeout(u.timeoutObject),d};o=setTimeout(a,s);let l={timeoutObject:o,clear:a,count:0};return r.set(t,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,s,r){let i,o=e;this.options.cwd&&!se.isAbsolute(e)&&(o=se.join(this.options.cwd,e));let a=new Date,l=u=>{na.stat(o,(d,f)=>{if(d||!this._pendingWrites.has(e)){d&&d.code!=="ENOENT"&&r(d);return}let h=Number(new Date);u&&f.size!==u.size&&(this._pendingWrites.get(e).lastChange=h);let m=this._pendingWrites.get(e);h-m.lastChange>=t?(this._pendingWrites.delete(e),r(void 0,f)):i=setTimeout(l,this.options.awaitWriteFinish.pollInterval,f)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(i),s)}),i=setTimeout(l,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,t){if(this.options.atomic&&ix.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,r=this.options.ignored,i=r&&r.map(Mf(s)),o=Zo(i).filter(l=>typeof l===sa&&!Ko(l)).map(l=>l+zo),a=this._getGlobIgnored().map(Mf(s)).concat(i,o);this._userIgnored=Yo(a,void 0,Xo)}return this._userIgnored([e,t])}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e,t){let s=t||this.options.disableGlobbing||!Ko(e)?e:Vw(e),r=this.options.followSymlinks;return new ta(e,s,r,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let t=se.resolve(e);return this._watched.has(t)||this._watched.set(t,new ea(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let s=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(s.toString(8)[0],10))}_remove(e,t,s){let r=se.join(e,t),i=se.resolve(r);if(s=s??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!s&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(h=>this._remove(r,h));let l=this._getWatchedDir(e),u=l.has(t);l.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=se.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===ur)return;this._watched.delete(r),this._watched.delete(i);let f=s?Zw:Tf;u&&!this._isIgnored(r)&&this._emit(f,r),this.options.useFsEvents||this._closePath(r)}_closePath(e){this._closeFile(e);let t=se.dirname(e);this._getWatchedDir(t).remove(se.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(s=>s()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let s=this._closers.get(e);s||(s=[],this._closers.set(e,s)),s.push(t)}_readdirp(e,t){if(this.closed)return;let s={type:Wo,alwaysStat:!0,lstat:!0,...t},r=Gw(e,s);return this._streams.add(r),r.once(tx,()=>{r=void 0}),r.once(nx,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};ra.FSWatcher=dr;var xx=(n,e)=>{let t=new dr(e);return t.add(n),t};ra.watch=xx});var Uf={};Ne(Uf,{CollaborationManager:()=>rs,addTeamMember:()=>kx,formatTeamConfig:()=>Ax,initTeamConfig:()=>_x,loadTeamConfig:()=>Sx,saveTeamConfig:()=>Bf});function Sx(n){let e=Ye.join(n,".hablas","team.json");if(ge.existsSync(e))try{return JSON.parse(ge.readFileSync(e,"utf-8"))}catch{return null}return null}function _x(n,e){let t={name:e,members:[]};return Bf(n,t),t}function Bf(n,e){let t=Ye.join(n,".hablas","team.json"),s=Ye.dirname(t);ge.existsSync(s)||ge.mkdirSync(s,{recursive:!0}),ge.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}function kx(n,e,t){return n.members.push({name:e,email:t}),n}function Ax(n){return[`Team: ${n.name}`,"Members:",...n.members.map(t=>` - ${t.name} (${t.email})`)].join(`
312
- `)}var ge,Ye,fr,jf,Hf,rs,ia=L(()=>{"use strict";ge=O(require("fs")),Ye=O(require("path")),fr=O(require("os")),jf=O(require("crypto")),Hf=O(Nf());yn();rs=class n{workingDir;config;username;teamKey;projectTeamToken;supabaseUrl="";supabaseKey="";isConfigured=!1;watcher=null;localStatePath;heartbeatInterval=null;syncInterval=null;static HEARTBEAT_MS=12e3;static POLL_ACTIVE_MS=3e3;static POLL_IDLE_MS=2e4;static STALE_MS=75e3;consecutiveHeartbeatFailures=0;announcedOffline=!1;idlePollTicks=0;signalHandler=null;shuttingDown=!1;currentActivity={section:"idle",task:"standby"};knownSessions=new Map;knownLocks=new Map;constructor(e,t,s,r){this.workingDir=e,this.config=t,this.username=s||fr.userInfo().username||"developer",this.teamKey=r||"default-team",this.localStatePath=Ye.join(this.workingDir,".hablas","collaboration.json");let i=this.getProjectIdentifier();console.log(`
313
- ${c.muted("[Debug] Project Context:")} ${c.highlight(i)}`),this.projectTeamToken=jf.createHash("sha256").update(`${i}:${this.teamKey}`).digest("hex"),console.log(` ${c.muted("[Debug] Session Fingerprint:")} ${c.muted(this.projectTeamToken.slice(0,16))}...
314
- `),this.loadSupabaseConfig()}async init(){if(!this.isConfigured)return console.log(` ${c.warning("\u26A0")} ${c.secondary("Supabase is not configured in .env. Collaboration mode operates locally.")}`),!1;let e=Ye.dirname(this.localStatePath);return ge.existsSync(e)||ge.mkdirSync(e,{recursive:!0}),this.saveLocalState([],[]),this.startLoops(),this.startWatcher(),this.registerCleanups(),!0}async shutdown(){this.shuttingDown||(this.shuttingDown=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.syncInterval&&(clearTimeout(this.syncInterval),this.syncInterval=null),this.watcher&&(await this.watcher.close(),this.watcher=null),this.signalHandler&&(process.off("SIGINT",this.signalHandler),process.off("SIGTERM",this.signalHandler),this.signalHandler=null),await this.releaseAllMyLocks(),await this.deleteSession())}async apiRequest(e,t,s,r){if(!this.isConfigured)return{ok:!1,data:null};let i=`${this.supabaseUrl}/rest/v1/${e}`,o={apikey:this.supabaseKey,Authorization:`Bearer ${this.supabaseKey}`,"Content-Type":"application/json"};r?.prefer?o.Prefer=r.prefer:(t==="POST"||t==="PATCH")&&(o.Prefer="return=representation");let a=(r?.retries??0)+1,l=null;for(let u=0;u<a;u++)try{let d=await fetch(i,{method:t,headers:o,body:s?JSON.stringify(s):void 0,signal:AbortSignal.timeout(1e4)});if(!d.ok){let h=await d.text().catch(()=>"");if(l=new Error(`[Supabase ${d.status}] ${h}`),(d.status>=500||d.status===429)&&u<a-1){await this.delay(400*(u+1));continue}return{ok:!1,data:null}}let f=await d.text();return{ok:!0,data:f?JSON.parse(f):null}}catch(d){if(l=d,u<a-1){await this.delay(400*(u+1));continue}}return{ok:!1,data:null}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendHeartbeat(e,t){let s={project_team_token:this.projectTeamToken,developer_name:this.username,last_heartbeat:new Date().toISOString(),active_section:e||"idle",current_task:t||"none"},r="hablas_team_sessions?on_conflict=project_team_token,developer_name",{ok:i}=await this.apiRequest(r,"POST",s,{prefer:"resolution=merge-duplicates,return=minimal",retries:2});return i}async fetchSessions(){let e=`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}`,{data:t}=await this.apiRequest(e,"GET");return t||[]}async deleteSession(){let e=`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}&developer_name=eq.${encodeURIComponent(this.username)}`;await this.apiRequest(e,"DELETE")}async fetchLocks(){let e=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}`,{data:t}=await this.apiRequest(e,"GET");return t||[]}async acquireLock(e,t){let s={project_team_token:this.projectTeamToken,file_path:e,locked_by:this.username,lock_context:t||"editing file",created_at:new Date().toISOString()};return await this.apiRequest("hablas_team_locks?on_conflict=project_team_token,file_path","POST",s,{prefer:"resolution=ignore-duplicates,return=minimal",retries:1}),!!(await this.fetchLocks()).find(a=>a.file_path===e&&a.locked_by===this.username)}async releaseLock(e){let t=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}&file_path=eq.${encodeURIComponent(e)}&locked_by=eq.${encodeURIComponent(this.username)}`;return await this.apiRequest(t,"DELETE"),!0}async releaseAllMyLocks(){let e=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}&locked_by=eq.${encodeURIComponent(this.username)}`;await this.apiRequest(e,"DELETE")}async sendMessage(e,t){let s={project_team_token:this.projectTeamToken,sender_name:this.username,receiver_name:e,message_content:t,is_read:!1,created_at:new Date().toISOString()},{ok:r}=await this.apiRequest("hablas_team_messages","POST",s,{retries:1});return r}async fetchUnreadMessages(){let e=`hablas_team_messages?project_team_token=eq.${this.projectTeamToken}&receiver_name=eq.${encodeURIComponent(this.username)}&is_read=eq.false`,t=(await this.apiRequest(e,"GET")).data||[];if(t.length>0)for(let s of t){let r=`hablas_team_messages?id=eq.${s.id}`;await this.apiRequest(r,"PATCH",{is_read:!0})}return t}saveLocalState(e,t){let s={project_team_token:this.projectTeamToken,last_sync:new Date().toISOString(),my_username:this.username,sessions:e,locks:t};ge.writeFileSync(this.localStatePath,JSON.stringify(s,null,2),"utf-8")}getLocalState(){if(ge.existsSync(this.localStatePath))try{return JSON.parse(ge.readFileSync(this.localStatePath,"utf-8"))}catch{}return{sessions:[],locks:[],my_username:this.username}}startLoops(){this.beat("idle","standby"),this.heartbeatInterval=setInterval(()=>{this.beat()},n.HEARTBEAT_MS);let e=t=>{this.syncInterval=setTimeout(async()=>{if(this.shuttingDown)return;await this.syncWithCloud()?this.idlePollTicks=0:this.idlePollTicks++;let r=this.idlePollTicks>=3?n.POLL_IDLE_MS:n.POLL_ACTIVE_MS;e(r)},t)};e(n.POLL_ACTIVE_MS)}setActivity(e,t="working"){this.currentActivity={section:t,task:e.slice(0,120)},this.beat(t,this.currentActivity.task)}async beat(e,t){await this.sendHeartbeat(e??this.currentActivity.section,t??this.currentActivity.task)?(this.announcedOffline&&(console.log(`
310
+ If you cannot complete a task, explain why with absolute technical objectivity.`;ao=$e.join(lo.homedir(),".hablas","backup")});var Vn=F((XC,zu)=>{"use strict";var fb=require("path"),yt="\\\\/",Ku=`[^${yt}]`,pb=0,Pt="\\.",hb="\\+",mb="\\?",Ys="\\/",gb="(?=.)",Wu="[^/]",co=`(?:${Ys}|$)`,Gu=`(?:^|${Ys})`,uo=`${Pt}{1,2}${co}`,yb=`(?!${Pt})`,bb=`(?!${Gu}${uo})`,vb=`(?!${Pt}{0,1}${co})`,wb=`(?!${uo})`,xb=`[^.${Ys}]`,Sb=`${Wu}*?`,Vu={DOT_LITERAL:Pt,PLUS_LITERAL:hb,QMARK_LITERAL:mb,SLASH_LITERAL:Ys,ONE_CHAR:gb,QMARK:Wu,END_ANCHOR:co,DOTS_SLASH:uo,NO_DOT:yb,NO_DOTS:bb,NO_DOT_SLASH:vb,NO_DOTS_SLASH:wb,QMARK_NO_DOT:xb,STAR:Sb,START_ANCHOR:Gu},_b={...Vu,SLASH_LITERAL:`[${yt}]`,QMARK:Ku,STAR:`${Ku}*?`,DOTS_SLASH:`${Pt}{1,2}(?:[${yt}]|$)`,NO_DOT:`(?!${Pt})`,NO_DOTS:`(?!(?:^|[${yt}])${Pt}{1,2}(?:[${yt}]|$))`,NO_DOT_SLASH:`(?!${Pt}{0,1}(?:[${yt}]|$))`,NO_DOTS_SLASH:`(?!${Pt}{1,2}(?:[${yt}]|$))`,QMARK_NO_DOT:`[^.${yt}]`,START_ANCHOR:`(?:^|[${yt}])`,END_ANCHOR:`(?:[${yt}]|$)`},kb={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};zu.exports={DEFAULT_MAX_EXTGLOB_RECURSION:pb,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:kb,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:fb.sep,extglobChars(n){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${n.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(n){return n===!0?_b:Vu}}});var Js=F(De=>{"use strict";var Ab=require("path"),$b=process.platform==="win32",{REGEX_BACKSLASH:Cb,REGEX_REMOVE_BACKSLASH:Eb,REGEX_SPECIAL_CHARS:Tb,REGEX_SPECIAL_CHARS_GLOBAL:Rb}=Vn();De.isObject=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);De.hasRegexChars=n=>Tb.test(n);De.isRegexChar=n=>n.length===1&&De.hasRegexChars(n);De.escapeRegex=n=>n.replace(Rb,"\\$1");De.toPosixSlashes=n=>n.replace(Cb,"/");De.removeBackslashes=n=>n.replace(Eb,e=>e==="\\"?"":e);De.supportsLookbehinds=()=>{let n=process.version.slice(1).split(".").map(Number);return n.length===3&&n[0]>=9||n[0]===8&&n[1]>=10};De.isWindows=n=>n&&typeof n.windows=="boolean"?n.windows:$b===!0||Ab.sep==="\\";De.escapeLast=(n,e,t)=>{let s=n.lastIndexOf(e,t);return s===-1?n:n[s-1]==="\\"?De.escapeLast(n,e,s-1):`${n.slice(0,s)}\\${n.slice(s)}`};De.removePrefix=(n,e={})=>{let t=n;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};De.wrapOutput=(n,e={},t={})=>{let s=t.contains?"":"^",r=t.contains?"":"$",i=`${s}(?:${n})${r}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var nd=F((ZC,td)=>{"use strict";var Yu=Js(),{CHAR_ASTERISK:fo,CHAR_AT:Ob,CHAR_BACKWARD_SLASH:zn,CHAR_COMMA:Pb,CHAR_DOT:po,CHAR_EXCLAMATION_MARK:ho,CHAR_FORWARD_SLASH:ed,CHAR_LEFT_CURLY_BRACE:mo,CHAR_LEFT_PARENTHESES:go,CHAR_LEFT_SQUARE_BRACKET:Mb,CHAR_PLUS:Ib,CHAR_QUESTION_MARK:Ju,CHAR_RIGHT_CURLY_BRACE:Db,CHAR_RIGHT_PARENTHESES:Xu,CHAR_RIGHT_SQUARE_BRACKET:Lb}=Vn(),Qu=n=>n===ed||n===zn,Zu=n=>{n.isPrefix!==!0&&(n.depth=n.isGlobstar?1/0:1)},Nb=(n,e)=>{let t=e||{},s=n.length-1,r=t.parts===!0||t.scanToEnd===!0,i=[],o=[],a=[],l=n,u=-1,d=0,f=0,h=!1,m=!1,p=!1,g=!1,x=!1,w=!1,$=!1,A=!1,y=!1,v=!1,b=0,S,_,T={value:"",depth:0,isGlob:!1},I=()=>u>=s,C=()=>l.charCodeAt(u+1),N=()=>(S=_,l.charCodeAt(++u));for(;u<s;){_=N();let Y;if(_===zn){$=T.backslashes=!0,_=N(),_===mo&&(w=!0);continue}if(w===!0||_===mo){for(b++;I()!==!0&&(_=N());){if(_===zn){$=T.backslashes=!0,N();continue}if(_===mo){b++;continue}if(w!==!0&&_===po&&(_=N())===po){if(h=T.isBrace=!0,p=T.isGlob=!0,v=!0,r===!0)continue;break}if(w!==!0&&_===Pb){if(h=T.isBrace=!0,p=T.isGlob=!0,v=!0,r===!0)continue;break}if(_===Db&&(b--,b===0)){w=!1,h=T.isBrace=!0,v=!0;break}}if(r===!0)continue;break}if(_===ed){if(i.push(u),o.push(T),T={value:"",depth:0,isGlob:!1},v===!0)continue;if(S===po&&u===d+1){d+=2;continue}f=u+1;continue}if(t.noext!==!0&&(_===Ib||_===Ob||_===fo||_===Ju||_===ho)===!0&&C()===go){if(p=T.isGlob=!0,g=T.isExtglob=!0,v=!0,_===ho&&u===d&&(y=!0),r===!0){for(;I()!==!0&&(_=N());){if(_===zn){$=T.backslashes=!0,_=N();continue}if(_===Xu){p=T.isGlob=!0,v=!0;break}}continue}break}if(_===fo){if(S===fo&&(x=T.isGlobstar=!0),p=T.isGlob=!0,v=!0,r===!0)continue;break}if(_===Ju){if(p=T.isGlob=!0,v=!0,r===!0)continue;break}if(_===Mb){for(;I()!==!0&&(Y=N());){if(Y===zn){$=T.backslashes=!0,N();continue}if(Y===Lb){m=T.isBracket=!0,p=T.isGlob=!0,v=!0;break}}if(r===!0)continue;break}if(t.nonegate!==!0&&_===ho&&u===d){A=T.negated=!0,d++;continue}if(t.noparen!==!0&&_===go){if(p=T.isGlob=!0,r===!0){for(;I()!==!0&&(_=N());){if(_===go){$=T.backslashes=!0,_=N();continue}if(_===Xu){v=!0;break}}continue}break}if(p===!0){if(v=!0,r===!0)continue;break}}t.noext===!0&&(g=!1,p=!1);let H=l,G="",E="";d>0&&(G=l.slice(0,d),l=l.slice(d),f-=d),H&&p===!0&&f>0?(H=l.slice(0,f),E=l.slice(f)):p===!0?(H="",E=l):H=l,H&&H!==""&&H!=="/"&&H!==l&&Qu(H.charCodeAt(H.length-1))&&(H=H.slice(0,-1)),t.unescape===!0&&(E&&(E=Yu.removeBackslashes(E)),H&&$===!0&&(H=Yu.removeBackslashes(H)));let k={prefix:G,input:n,start:d,base:H,glob:E,isBrace:h,isBracket:m,isGlob:p,isExtglob:g,isGlobstar:x,negated:A,negatedExtglob:y};if(t.tokens===!0&&(k.maxDepth=0,Qu(_)||o.push(T),k.tokens=o),t.parts===!0||t.tokens===!0){let Y;for(let U=0;U<i.length;U++){let ee=Y?Y+1:d,ne=i[U],X=n.slice(ee,ne);t.tokens&&(U===0&&d!==0?(o[U].isPrefix=!0,o[U].value=G):o[U].value=X,Zu(o[U]),k.maxDepth+=o[U].depth),(U!==0||X!=="")&&a.push(X),Y=ne}if(Y&&Y+1<n.length){let U=n.slice(Y+1);a.push(U),t.tokens&&(o[o.length-1].value=U,Zu(o[o.length-1]),k.maxDepth+=o[o.length-1].depth)}k.slashes=i,k.parts=a}return k};td.exports=Nb});var ad=F((eE,od)=>{"use strict";var Yn=Vn(),Ee=Js(),{MAX_LENGTH:Xs,POSIX_REGEX_SOURCE:Fb,REGEX_NON_SPECIAL_CHARS:jb,REGEX_SPECIAL_CHARS_BACKREF:Hb,REPLACEMENTS:sd}=Yn,Bb=(n,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...n,e);n.sort();let t=`[${n.join("-")}]`;try{new RegExp(t)}catch{return n.map(r=>Ee.escapeRegex(r)).join("..")}return t},xn=(n,e)=>`Missing ${n}: "${e}" - use "\\\\${e}" to match literal characters`,rd=n=>{let e=[],t=0,s=0,r=0,i="",o=!1;for(let a of n){if(o===!0){i+=a,o=!1;continue}if(a==="\\"){i+=a,o=!0;continue}if(a==='"'){r=r===1?0:1,i+=a;continue}if(r===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")s++;else if(a===")"&&s>0)s--;else if(a==="|"&&s===0){e.push(i),i="";continue}}}i+=a}return e.push(i),e},Ub=n=>{let e=!1;for(let t of n){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},id=n=>{let e=n.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(Ub(e))return e.replace(/\\(.)/g,"$1")},qb=n=>{let e=n.map(id).filter(Boolean);for(let t=0;t<e.length;t++)for(let s=t+1;s<e.length;s++){let r=e[t],i=e[s],o=r[0];if(!(!o||r!==o.repeat(r.length)||i!==o.repeat(i.length))&&(r===i||r.startsWith(i)||i.startsWith(r)))return!0}return!1},yo=(n,e=!0)=>{if(n[0]!=="+"&&n[0]!=="*"||n[1]!=="(")return;let t=0,s=0,r=0,i=!1;for(let o=1;o<n.length;o++){let a=n[o];if(i===!0){i=!1;continue}if(a==="\\"){i=!0;continue}if(a==='"'){r=r===1?0:1;continue}if(r!==1){if(a==="["){t++;continue}if(a==="]"&&t>0){t--;continue}if(!(t>0)){if(a==="("){s++;continue}if(a===")"&&(s--,s===0))return e===!0&&o!==n.length-1?void 0:{type:n[0],body:n.slice(2,o),end:o}}}}},Kb=n=>{let e=0,t=[];for(;e<n.length;){let r=yo(n.slice(e),!1);if(!r||r.type!=="*")return;let i=rd(r.body).map(a=>a.trim());if(i.length!==1)return;let o=id(i[0]);if(!o||o.length!==1)return;t.push(o),e+=r.end+1}return t.length<1?void 0:`${t.length===1?Ee.escapeRegex(t[0]):`[${t.map(r=>Ee.escapeRegex(r)).join("")}]`}*`},Wb=n=>{let e=0,t=n.trim(),s=yo(t);for(;s;)e++,t=s.body.trim(),s=yo(t);return e},Gb=(n,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Yn.DEFAULT_MAX_EXTGLOB_RECURSION,s=rd(n).map(r=>r.trim());if(s.length>1&&(s.some(r=>r==="")||s.some(r=>/^[*?]+$/.test(r))||qb(s)))return{risky:!0};for(let r of s){let i=Kb(r);if(i)return{risky:!0,safeOutput:i};if(Wb(r)>t)return{risky:!0}}return{risky:!1}},bo=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a string");n=sd[n]||n;let t={...e},s=typeof t.maxLength=="number"?Math.min(Xs,t.maxLength):Xs,r=n.length;if(r>s)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${s}`);let i={type:"bos",value:"",output:t.prepend||""},o=[i],a=t.capture?"":"?:",l=Ee.isWindows(e),u=Yn.globChars(l),d=Yn.extglobChars(u),{DOT_LITERAL:f,PLUS_LITERAL:h,SLASH_LITERAL:m,ONE_CHAR:p,DOTS_SLASH:g,NO_DOT:x,NO_DOT_SLASH:w,NO_DOTS_SLASH:$,QMARK:A,QMARK_NO_DOT:y,STAR:v,START_ANCHOR:b}=u,S=D=>`(${a}(?:(?!${b}${D.dot?g:f}).)*?)`,_=t.dot?"":x,T=t.dot?A:y,I=t.bash===!0?S(t):v;t.capture&&(I=`(${I})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let C={input:n,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};n=Ee.removePrefix(n,C),r=n.length;let N=[],H=[],G=[],E=i,k,Y=()=>C.index===r-1,U=C.peek=(D=1)=>n[C.index+D],ee=C.advance=()=>n[++C.index]||"",ne=()=>n.slice(C.index+1),X=(D="",Z=0)=>{C.consumed+=D,C.index+=Z},ue=D=>{C.output+=D.output!=null?D.output:D.value,X(D.value)},Pe=()=>{let D=1;for(;U()==="!"&&(U(2)!=="("||U(3)==="?");)ee(),C.start++,D++;return D%2===0?!1:(C.negated=!0,C.start++,!0)},xe=D=>{C[D]++,G.push(D)},we=D=>{C[D]--,G.pop()},q=D=>{if(E.type==="globstar"){let Z=C.braces>0&&(D.type==="comma"||D.type==="brace"),P=D.extglob===!0||N.length&&(D.type==="pipe"||D.type==="paren");D.type!=="slash"&&D.type!=="paren"&&!Z&&!P&&(C.output=C.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=I,C.output+=E.output)}if(N.length&&D.type!=="paren"&&(N[N.length-1].inner+=D.value),(D.value||D.output)&&ue(D),E&&E.type==="text"&&D.type==="text"){E.value+=D.value,E.output=(E.output||"")+D.value;return}D.prev=E,o.push(D),E=D},he=(D,Z)=>{let P={...d[Z],conditions:1,inner:""};P.prev=E,P.parens=C.parens,P.output=C.output,P.startIndex=C.index,P.tokensIndex=o.length;let K=(t.capture?"(":"")+P.open;xe("parens"),q({type:D,value:Z,output:C.output?"":p}),q({type:"paren",extglob:!0,value:ee(),output:K}),N.push(P)},$s=D=>{let Z=n.slice(D.startIndex,C.index+1),P=n.slice(D.startIndex+2,C.index),K=Gb(P,t);if((D.type==="plus"||D.type==="star")&&K.risky){let Q=K.safeOutput?(D.output?"":p)+(t.capture?`(${K.safeOutput})`:K.safeOutput):void 0,Ke=o[D.tokensIndex];Ke.type="text",Ke.value=Z,Ke.output=Q||Ee.escapeRegex(Z);for(let We=D.tokensIndex+1;We<o.length;We++)o[We].value="",o[We].output="",delete o[We].suffix;C.output=D.output+Ke.output,C.backtrack=!0,q({type:"paren",extglob:!0,value:k,output:""}),we("parens");return}let se=D.close+(t.capture?")":""),te;if(D.type==="negate"){let Q=I;if(D.inner&&D.inner.length>1&&D.inner.includes("/")&&(Q=S(t)),(Q!==I||Y()||/^\)+$/.test(ne()))&&(se=D.close=`)$))${Q}`),D.inner.includes("*")&&(te=ne())&&/^\.[^\\/.]+$/.test(te)){let Ke=bo(te,{...e,fastpaths:!1}).output;se=D.close=`)${Ke})${Q})`}D.prev.type==="bos"&&(C.negatedExtglob=!0)}q({type:"paren",extglob:!0,value:k,output:se}),we("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(n)){let D=!1,Z=n.replace(Hb,(P,K,se,te,Q,Ke)=>te==="\\"?(D=!0,P):te==="?"?K?K+te+(Q?A.repeat(Q.length):""):Ke===0?T+(Q?A.repeat(Q.length):""):A.repeat(se.length):te==="."?f.repeat(se.length):te==="*"?K?K+te+(Q?I:""):I:K?P:`\\${P}`);return D===!0&&(t.unescape===!0?Z=Z.replace(/\\/g,""):Z=Z.replace(/\\+/g,P=>P.length%2===0?"\\\\":P?"\\":"")),Z===n&&t.contains===!0?(C.output=n,C):(C.output=Ee.wrapOutput(Z,C,e),C)}for(;!Y();){if(k=ee(),k==="\0")continue;if(k==="\\"){let P=U();if(P==="/"&&t.bash!==!0||P==="."||P===";")continue;if(!P){k+="\\",q({type:"text",value:k});continue}let K=/^\\+/.exec(ne()),se=0;if(K&&K[0].length>2&&(se=K[0].length,C.index+=se,se%2!==0&&(k+="\\")),t.unescape===!0?k=ee():k+=ee(),C.brackets===0){q({type:"text",value:k});continue}}if(C.brackets>0&&(k!=="]"||E.value==="["||E.value==="[^")){if(t.posix!==!1&&k===":"){let P=E.value.slice(1);if(P.includes("[")&&(E.posix=!0,P.includes(":"))){let K=E.value.lastIndexOf("["),se=E.value.slice(0,K),te=E.value.slice(K+2),Q=Fb[te];if(Q){E.value=se+Q,C.backtrack=!0,ee(),!i.output&&o.indexOf(E)===1&&(i.output=p);continue}}}(k==="["&&U()!==":"||k==="-"&&U()==="]")&&(k=`\\${k}`),k==="]"&&(E.value==="["||E.value==="[^")&&(k=`\\${k}`),t.posix===!0&&k==="!"&&E.value==="["&&(k="^"),E.value+=k,ue({value:k});continue}if(C.quotes===1&&k!=='"'){k=Ee.escapeRegex(k),E.value+=k,ue({value:k});continue}if(k==='"'){C.quotes=C.quotes===1?0:1,t.keepQuotes===!0&&q({type:"text",value:k});continue}if(k==="("){xe("parens"),q({type:"paren",value:k});continue}if(k===")"){if(C.parens===0&&t.strictBrackets===!0)throw new SyntaxError(xn("opening","("));let P=N[N.length-1];if(P&&C.parens===P.parens+1){$s(N.pop());continue}q({type:"paren",value:k,output:C.parens?")":"\\)"}),we("parens");continue}if(k==="["){if(t.nobracket===!0||!ne().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(xn("closing","]"));k=`\\${k}`}else xe("brackets");q({type:"bracket",value:k});continue}if(k==="]"){if(t.nobracket===!0||E&&E.type==="bracket"&&E.value.length===1){q({type:"text",value:k,output:`\\${k}`});continue}if(C.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(xn("opening","["));q({type:"text",value:k,output:`\\${k}`});continue}we("brackets");let P=E.value.slice(1);if(E.posix!==!0&&P[0]==="^"&&!P.includes("/")&&(k=`/${k}`),E.value+=k,ue({value:k}),t.literalBrackets===!1||Ee.hasRegexChars(P))continue;let K=Ee.escapeRegex(E.value);if(C.output=C.output.slice(0,-E.value.length),t.literalBrackets===!0){C.output+=K,E.value=K;continue}E.value=`(${a}${K}|${E.value})`,C.output+=E.value;continue}if(k==="{"&&t.nobrace!==!0){xe("braces");let P={type:"brace",value:k,output:"(",outputIndex:C.output.length,tokensIndex:C.tokens.length};H.push(P),q(P);continue}if(k==="}"){let P=H[H.length-1];if(t.nobrace===!0||!P){q({type:"text",value:k,output:k});continue}let K=")";if(P.dots===!0){let se=o.slice(),te=[];for(let Q=se.length-1;Q>=0&&(o.pop(),se[Q].type!=="brace");Q--)se[Q].type!=="dots"&&te.unshift(se[Q].value);K=Bb(te,t),C.backtrack=!0}if(P.comma!==!0&&P.dots!==!0){let se=C.output.slice(0,P.outputIndex),te=C.tokens.slice(P.tokensIndex);P.value=P.output="\\{",k=K="\\}",C.output=se;for(let Q of te)C.output+=Q.output||Q.value}q({type:"brace",value:k,output:K}),we("braces"),H.pop();continue}if(k==="|"){N.length>0&&N[N.length-1].conditions++,q({type:"text",value:k});continue}if(k===","){let P=k,K=H[H.length-1];K&&G[G.length-1]==="braces"&&(K.comma=!0,P="|"),q({type:"comma",value:k,output:P});continue}if(k==="/"){if(E.type==="dot"&&C.index===C.start+1){C.start=C.index+1,C.consumed="",C.output="",o.pop(),E=i;continue}q({type:"slash",value:k,output:m});continue}if(k==="."){if(C.braces>0&&E.type==="dot"){E.value==="."&&(E.output=f);let P=H[H.length-1];E.type="dots",E.output+=k,E.value+=k,P.dots=!0;continue}if(C.braces+C.parens===0&&E.type!=="bos"&&E.type!=="slash"){q({type:"text",value:k,output:f});continue}q({type:"dot",value:k,output:f});continue}if(k==="?"){if(!(E&&E.value==="(")&&t.noextglob!==!0&&U()==="("&&U(2)!=="?"){he("qmark",k);continue}if(E&&E.type==="paren"){let K=U(),se=k;if(K==="<"&&!Ee.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(E.value==="("&&!/[!=<:]/.test(K)||K==="<"&&!/<([!=]|\w+>)/.test(ne()))&&(se=`\\${k}`),q({type:"text",value:k,output:se});continue}if(t.dot!==!0&&(E.type==="slash"||E.type==="bos")){q({type:"qmark",value:k,output:y});continue}q({type:"qmark",value:k,output:A});continue}if(k==="!"){if(t.noextglob!==!0&&U()==="("&&(U(2)!=="?"||!/[!=<:]/.test(U(3)))){he("negate",k);continue}if(t.nonegate!==!0&&C.index===0){Pe();continue}}if(k==="+"){if(t.noextglob!==!0&&U()==="("&&U(2)!=="?"){he("plus",k);continue}if(E&&E.value==="("||t.regex===!1){q({type:"plus",value:k,output:h});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||C.parens>0){q({type:"plus",value:k});continue}q({type:"plus",value:h});continue}if(k==="@"){if(t.noextglob!==!0&&U()==="("&&U(2)!=="?"){q({type:"at",extglob:!0,value:k,output:""});continue}q({type:"text",value:k});continue}if(k!=="*"){(k==="$"||k==="^")&&(k=`\\${k}`);let P=jb.exec(ne());P&&(k+=P[0],C.index+=P[0].length),q({type:"text",value:k});continue}if(E&&(E.type==="globstar"||E.star===!0)){E.type="star",E.star=!0,E.value+=k,E.output=I,C.backtrack=!0,C.globstar=!0,X(k);continue}let D=ne();if(t.noextglob!==!0&&/^\([^?]/.test(D)){he("star",k);continue}if(E.type==="star"){if(t.noglobstar===!0){X(k);continue}let P=E.prev,K=P.prev,se=P.type==="slash"||P.type==="bos",te=K&&(K.type==="star"||K.type==="globstar");if(t.bash===!0&&(!se||D[0]&&D[0]!=="/")){q({type:"star",value:k,output:""});continue}let Q=C.braces>0&&(P.type==="comma"||P.type==="brace"),Ke=N.length&&(P.type==="pipe"||P.type==="paren");if(!se&&P.type!=="paren"&&!Q&&!Ke){q({type:"star",value:k,output:""});continue}for(;D.slice(0,3)==="/**";){let We=n[C.index+4];if(We&&We!=="/")break;D=D.slice(3),X("/**",3)}if(P.type==="bos"&&Y()){E.type="globstar",E.value+=k,E.output=S(t),C.output=E.output,C.globstar=!0,X(k);continue}if(P.type==="slash"&&P.prev.type!=="bos"&&!te&&Y()){C.output=C.output.slice(0,-(P.output+E.output).length),P.output=`(?:${P.output}`,E.type="globstar",E.output=S(t)+(t.strictSlashes?")":"|$)"),E.value+=k,C.globstar=!0,C.output+=P.output+E.output,X(k);continue}if(P.type==="slash"&&P.prev.type!=="bos"&&D[0]==="/"){let We=D[1]!==void 0?"|$":"";C.output=C.output.slice(0,-(P.output+E.output).length),P.output=`(?:${P.output}`,E.type="globstar",E.output=`${S(t)}${m}|${m}${We})`,E.value+=k,C.output+=P.output+E.output,C.globstar=!0,X(k+ee()),q({type:"slash",value:"/",output:""});continue}if(P.type==="bos"&&D[0]==="/"){E.type="globstar",E.value+=k,E.output=`(?:^|${m}|${S(t)}${m})`,C.output=E.output,C.globstar=!0,X(k+ee()),q({type:"slash",value:"/",output:""});continue}C.output=C.output.slice(0,-E.output.length),E.type="globstar",E.output=S(t),E.value+=k,C.output+=E.output,C.globstar=!0,X(k);continue}let Z={type:"star",value:k,output:I};if(t.bash===!0){Z.output=".*?",(E.type==="bos"||E.type==="slash")&&(Z.output=_+Z.output),q(Z);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&t.regex===!0){Z.output=k,q(Z);continue}(C.index===C.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(C.output+=w,E.output+=w):t.dot===!0?(C.output+=$,E.output+=$):(C.output+=_,E.output+=_),U()!=="*"&&(C.output+=p,E.output+=p)),q(Z)}for(;C.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(xn("closing","]"));C.output=Ee.escapeLast(C.output,"["),we("brackets")}for(;C.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(xn("closing",")"));C.output=Ee.escapeLast(C.output,"("),we("parens")}for(;C.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(xn("closing","}"));C.output=Ee.escapeLast(C.output,"{"),we("braces")}if(t.strictSlashes!==!0&&(E.type==="star"||E.type==="bracket")&&q({type:"maybe_slash",value:"",output:`${m}?`}),C.backtrack===!0){C.output="";for(let D of C.tokens)C.output+=D.output!=null?D.output:D.value,D.suffix&&(C.output+=D.suffix)}return C};bo.fastpaths=(n,e)=>{let t={...e},s=typeof t.maxLength=="number"?Math.min(Xs,t.maxLength):Xs,r=n.length;if(r>s)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${s}`);n=sd[n]||n;let i=Ee.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:l,DOTS_SLASH:u,NO_DOT:d,NO_DOTS:f,NO_DOTS_SLASH:h,STAR:m,START_ANCHOR:p}=Yn.globChars(i),g=t.dot?f:d,x=t.dot?h:d,w=t.capture?"":"?:",$={negated:!1,prefix:""},A=t.bash===!0?".*?":m;t.capture&&(A=`(${A})`);let y=_=>_.noglobstar===!0?A:`(${w}(?:(?!${p}${_.dot?u:o}).)*?)`,v=_=>{switch(_){case"*":return`${g}${l}${A}`;case".*":return`${o}${l}${A}`;case"*.*":return`${g}${A}${o}${l}${A}`;case"*/*":return`${g}${A}${a}${l}${x}${A}`;case"**":return g+y(t);case"**/*":return`(?:${g}${y(t)}${a})?${x}${l}${A}`;case"**/*.*":return`(?:${g}${y(t)}${a})?${x}${A}${o}${l}${A}`;case"**/.*":return`(?:${g}${y(t)}${a})?${o}${l}${A}`;default:{let T=/^(.*?)\.(\w+)$/.exec(_);if(!T)return;let I=v(T[1]);return I?I+o+T[2]:void 0}}},b=Ee.removePrefix(n,$),S=v(b);return S&&t.strictSlashes!==!0&&(S+=`${a}?`),S};od.exports=bo});var cd=F((tE,ld)=>{"use strict";var Vb=require("path"),zb=nd(),vo=ad(),wo=Js(),Yb=Vn(),Jb=n=>n&&typeof n=="object"&&!Array.isArray(n),ge=(n,e,t=!1)=>{if(Array.isArray(n)){let d=n.map(h=>ge(h,e,t));return h=>{for(let m of d){let p=m(h);if(p)return p}return!1}}let s=Jb(n)&&n.tokens&&n.input;if(n===""||typeof n!="string"&&!s)throw new TypeError("Expected pattern to be a non-empty string");let r=e||{},i=wo.isWindows(e),o=s?ge.compileRe(n,e):ge.makeRe(n,e,!1,!0),a=o.state;delete o.state;let l=()=>!1;if(r.ignore){let d={...e,ignore:null,onMatch:null,onResult:null};l=ge(r.ignore,d,t)}let u=(d,f=!1)=>{let{isMatch:h,match:m,output:p}=ge.test(d,o,e,{glob:n,posix:i}),g={glob:n,state:a,regex:o,posix:i,input:d,output:p,match:m,isMatch:h};return typeof r.onResult=="function"&&r.onResult(g),h===!1?(g.isMatch=!1,f?g:!1):l(d)?(typeof r.onIgnore=="function"&&r.onIgnore(g),g.isMatch=!1,f?g:!1):(typeof r.onMatch=="function"&&r.onMatch(g),f?g:!0)};return t&&(u.state=a),u};ge.test=(n,e,t,{glob:s,posix:r}={})=>{if(typeof n!="string")throw new TypeError("Expected input to be a string");if(n==="")return{isMatch:!1,output:""};let i=t||{},o=i.format||(r?wo.toPosixSlashes:null),a=n===s,l=a&&o?o(n):n;return a===!1&&(l=o?o(n):n,a=l===s),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=ge.matchBase(n,e,t,r):a=e.exec(l)),{isMatch:!!a,match:a,output:l}};ge.matchBase=(n,e,t,s=wo.isWindows(t))=>(e instanceof RegExp?e:ge.makeRe(e,t)).test(Vb.basename(n));ge.isMatch=(n,e,t)=>ge(e,t)(n);ge.parse=(n,e)=>Array.isArray(n)?n.map(t=>ge.parse(t,e)):vo(n,{...e,fastpaths:!1});ge.scan=(n,e)=>zb(n,e);ge.compileRe=(n,e,t=!1,s=!1)=>{if(t===!0)return n.output;let r=e||{},i=r.contains?"":"^",o=r.contains?"":"$",a=`${i}(?:${n.output})${o}`;n&&n.negated===!0&&(a=`^(?!${a}).*$`);let l=ge.toRegex(a,e);return s===!0&&(l.state=n),l};ge.makeRe=(n,e={},t=!1,s=!1)=>{if(!n||typeof n!="string")throw new TypeError("Expected a non-empty string");let r={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(n[0]==="."||n[0]==="*")&&(r.output=vo.fastpaths(n,e)),r.output||(r=vo(n,e)),ge.compileRe(r,e,t,s)};ge.toRegex=(n,e)=>{try{let t=e||{};return new RegExp(n,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};ge.constants=Yb;ld.exports=ge});var xo=F((nE,ud)=>{"use strict";ud.exports=cd()});var bd=F((sE,yd)=>{"use strict";var Xn=require("fs"),{Readable:Xb}=require("stream"),Jn=require("path"),{promisify:tr}=require("util"),So=xo(),Qb=tr(Xn.readdir),Zb=tr(Xn.stat),dd=tr(Xn.lstat),ev=tr(Xn.realpath),tv="!",md="READDIRP_RECURSIVE_ERROR",nv=new Set(["ENOENT","EPERM","EACCES","ELOOP",md]),_o="files",gd="directories",Zs="files_directories",Qs="all",fd=[_o,gd,Zs,Qs],sv=n=>nv.has(n.code),[pd,rv]=process.versions.node.split(".").slice(0,2).map(n=>Number.parseInt(n,10)),iv=process.platform==="win32"&&(pd>10||pd===10&&rv>=5),hd=n=>{if(n!==void 0){if(typeof n=="function")return n;if(typeof n=="string"){let e=So(n.trim());return t=>e(t.basename)}if(Array.isArray(n)){let e=[],t=[];for(let s of n){let r=s.trim();r.charAt(0)===tv?t.push(So(r.slice(1))):e.push(So(r))}return t.length>0?e.length>0?s=>e.some(r=>r(s.basename))&&!t.some(r=>r(s.basename)):s=>!t.some(r=>r(s.basename)):s=>e.some(r=>r(s.basename))}}},er=class n extends Xb{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:_o,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let t={...n.defaultOptions,...e},{root:s,type:r}=t;this._fileFilter=hd(t.fileFilter),this._directoryFilter=hd(t.directoryFilter);let i=t.lstat?dd:Zb;iv?this._stat=o=>i(o,{bigint:!0}):this._stat=i,this._maxDepth=t.depth,this._wantsDir=[gd,Zs,Qs].includes(r),this._wantsFile=[_o,Zs,Qs].includes(r),this._wantsEverything=r===Qs,this._root=Jn.resolve(s),this._isDirent="Dirent"in Xn&&!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(s,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:t,depth:s,files:r=[]}=this.parent||{};if(r.length>0){let i=r.splice(0,e).map(o=>this._formatEntry(o,t));for(let o of await Promise.all(i)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,s+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}if(this.parent=await i,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let s;try{s=await Qb(e,this._rdOptions)}catch(r){this._onError(r)}return{files:s,depth:t,path:e}}async _formatEntry(e,t){let s;try{let r=this._isDirent?e.name:e,i=Jn.resolve(Jn.join(t,r));s={path:Jn.relative(this._root,i),fullPath:i,basename:r},s[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(r){this._onError(r)}return s}_onError(e){sv(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let t=e&&e[this._statsProp];if(t){if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let s=e.fullPath;try{let r=await ev(s),i=await dd(r);if(i.isFile())return"file";if(i.isDirectory()){let o=r.length;if(s.startsWith(r)&&s.substr(o,1)===Jn.sep){let a=new Error(`Circular symlink detected: "${s}" points to "${r}"`);return a.code=md,this._onError(a)}return"directory"}}catch(r){this._onError(r)}}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}},Sn=(n,e={})=>{let t=e.entryType||e.type;if(t==="both"&&(t=Zs),t&&(e.type=t),n){if(typeof n!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!fd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${fd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=n,new er(e)},ov=(n,e={})=>new Promise((t,s)=>{let r=[];Sn(n,e).on("data",i=>r.push(i)).on("end",()=>t(r)).on("error",i=>s(i))});Sn.promise=ov;Sn.ReaddirpStream=er;Sn.default=Sn;yd.exports=Sn});var ko=F((rE,vd)=>{vd.exports=function(n,e){if(typeof n!="string")throw new TypeError("expected path to be a string");if(n==="\\"||n==="/")return"/";var t=n.length;if(t<=1)return n;var s="";if(t>4&&n[3]==="\\"){var r=n[2];(r==="?"||r===".")&&n.slice(0,2)==="\\\\"&&(n=n.slice(2),s="//")}var i=n.split(/[/\\]+/);return e!==!1&&i[i.length-1]===""&&i.pop(),s+i.join("/")}});var Ad=F((_d,kd)=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var Sd=xo(),av=ko(),wd="!",lv={returnIndex:!1},cv=n=>Array.isArray(n)?n:[n],uv=(n,e)=>{if(typeof n=="function")return n;if(typeof n=="string"){let t=Sd(n,e);return s=>n===s||t(s)}return n instanceof RegExp?t=>n.test(t):t=>!1},xd=(n,e,t,s)=>{let r=Array.isArray(t),i=r?t[0]:t;if(!r&&typeof i!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(i));let o=av(i,!1);for(let l=0;l<e.length;l++){let u=e[l];if(u(o))return s?-1:!1}let a=r&&[o].concat(t.slice(1));for(let l=0;l<n.length;l++){let u=n[l];if(r?u(...a):u(o))return s?l:!0}return s?-1:!1},Ao=(n,e,t=lv)=>{if(n==null)throw new TypeError("anymatch: specify first argument");let s=typeof t=="boolean"?{returnIndex:t}:t,r=s.returnIndex||!1,i=cv(n),o=i.filter(l=>typeof l=="string"&&l.charAt(0)===wd).map(l=>l.slice(1)).map(l=>Sd(l,s)),a=i.filter(l=>typeof l!="string"||typeof l=="string"&&l.charAt(0)!==wd).map(l=>uv(l,s));return e==null?(l,u=!1)=>xd(a,o,l,typeof u=="boolean"?u:!1):xd(a,o,e,r)};Ao.default=Ao;kd.exports=Ao});var Cd=F((iE,$d)=>{$d.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var t;t=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(t[2])return!0;e=e.slice(t.index+t[0].length)}return!1}});var $o=F((oE,Td)=>{var dv=Cd(),Ed={"{":"}","(":")","[":"]"},fv=function(n){if(n[0]==="!")return!0;for(var e=0,t=-2,s=-2,r=-2,i=-2,o=-2;e<n.length;){if(n[e]==="*"||n[e+1]==="?"&&/[\].+)]/.test(n[e])||s!==-1&&n[e]==="["&&n[e+1]!=="]"&&(s<e&&(s=n.indexOf("]",e)),s>e&&(o===-1||o>s||(o=n.indexOf("\\",e),o===-1||o>s)))||r!==-1&&n[e]==="{"&&n[e+1]!=="}"&&(r=n.indexOf("}",e),r>e&&(o=n.indexOf("\\",e),o===-1||o>r))||i!==-1&&n[e]==="("&&n[e+1]==="?"&&/[:!=]/.test(n[e+2])&&n[e+3]!==")"&&(i=n.indexOf(")",e),i>e&&(o=n.indexOf("\\",e),o===-1||o>i))||t!==-1&&n[e]==="("&&n[e+1]!=="|"&&(t<e&&(t=n.indexOf("|",e)),t!==-1&&n[t+1]!==")"&&(i=n.indexOf(")",t),i>t&&(o=n.indexOf("\\",t),o===-1||o>i))))return!0;if(n[e]==="\\"){var a=n[e+1];e+=2;var l=Ed[a];if(l){var u=n.indexOf(l,e);u!==-1&&(e=u+1)}if(n[e]==="!")return!0}else e++}return!1},pv=function(n){if(n[0]==="!")return!0;for(var e=0;e<n.length;){if(/[*?{}()[\]]/.test(n[e]))return!0;if(n[e]==="\\"){var t=n[e+1];e+=2;var s=Ed[t];if(s){var r=n.indexOf(s,e);r!==-1&&(e=r+1)}if(n[e]==="!")return!0}else e++}return!1};Td.exports=function(e,t){if(typeof e!="string"||e==="")return!1;if(dv(e))return!0;var s=fv;return t&&t.strict===!1&&(s=pv),s(e)}});var Od=F((aE,Rd)=>{"use strict";var hv=$o(),mv=require("path").posix.dirname,gv=require("os").platform()==="win32",Co="/",yv=/\\/g,bv=/[\{\[].*[\}\]]$/,vv=/(^|[^\\])([\{\[]|\([^\)]+$)/,wv=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Rd.exports=function(e,t){var s=Object.assign({flipBackslashes:!0},t);s.flipBackslashes&&gv&&e.indexOf(Co)<0&&(e=e.replace(yv,Co)),bv.test(e)&&(e+=Co),e+="a";do e=mv(e);while(hv(e)||vv.test(e));return e.replace(wv,"$1")}});var nr=F(Ye=>{"use strict";Ye.isInteger=n=>typeof n=="number"?Number.isInteger(n):typeof n=="string"&&n.trim()!==""?Number.isInteger(Number(n)):!1;Ye.find=(n,e)=>n.nodes.find(t=>t.type===e);Ye.exceedsLimit=(n,e,t=1,s)=>s===!1||!Ye.isInteger(n)||!Ye.isInteger(e)?!1:(Number(e)-Number(n))/Number(t)>=s;Ye.escapeNode=(n,e=0,t)=>{let s=n.nodes[e];s&&(t&&s.type===t||s.type==="open"||s.type==="close")&&s.escaped!==!0&&(s.value="\\"+s.value,s.escaped=!0)};Ye.encloseBrace=n=>n.type!=="brace"?!1:n.commas>>0+n.ranges>>0===0?(n.invalid=!0,!0):!1;Ye.isInvalidBrace=n=>n.type!=="brace"?!1:n.invalid===!0||n.dollar?!0:n.commas>>0+n.ranges>>0===0||n.open!==!0||n.close!==!0?(n.invalid=!0,!0):!1;Ye.isOpenOrClose=n=>n.type==="open"||n.type==="close"?!0:n.open===!0||n.close===!0;Ye.reduce=n=>n.reduce((e,t)=>(t.type==="text"&&e.push(t.value),t.type==="range"&&(t.type="text"),e),[]);Ye.flatten=(...n)=>{let e=[],t=s=>{for(let r=0;r<s.length;r++){let i=s[r];if(Array.isArray(i)){t(i);continue}i!==void 0&&e.push(i)}return e};return t(n),e}});var sr=F((cE,Md)=>{"use strict";var Pd=nr();Md.exports=(n,e={})=>{let t=(s,r={})=>{let i=e.escapeInvalid&&Pd.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(i||o)&&Pd.isOpenOrClose(s)?"\\"+s.value:s.value;if(s.value)return s.value;if(s.nodes)for(let l of s.nodes)a+=t(l);return a};return t(n)}});var Dd=F((uE,Id)=>{"use strict";Id.exports=function(n){return typeof n=="number"?n-n===0:typeof n=="string"&&n.trim()!==""?Number.isFinite?Number.isFinite(+n):isFinite(+n):!1}});var Kd=F((dE,qd)=>{"use strict";var Ld=Dd(),Xt=(n,e,t)=>{if(Ld(n)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||n===e)return String(n);if(Ld(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let s={relaxZeros:!0,...t};typeof s.strictZeros=="boolean"&&(s.relaxZeros=s.strictZeros===!1);let r=String(s.relaxZeros),i=String(s.shorthand),o=String(s.capture),a=String(s.wrap),l=n+":"+e+"="+r+i+o+a;if(Xt.cache.hasOwnProperty(l))return Xt.cache[l].result;let u=Math.min(n,e),d=Math.max(n,e);if(Math.abs(u-d)===1){let g=n+"|"+e;return s.capture?`(${g})`:s.wrap===!1?g:`(?:${g})`}let f=Ud(n)||Ud(e),h={min:n,max:e,a:u,b:d},m=[],p=[];if(f&&(h.isPadded=f,h.maxLen=String(h.max).length),u<0){let g=d<0?Math.abs(d):1;p=Nd(g,Math.abs(u),h,s),u=h.a=0}return d>=0&&(m=Nd(u,d,h,s)),h.negatives=p,h.positives=m,h.result=xv(p,m,s),s.capture===!0?h.result=`(${h.result})`:s.wrap!==!1&&m.length+p.length>1&&(h.result=`(?:${h.result})`),Xt.cache[l]=h,h.result};function xv(n,e,t){let s=Eo(n,e,"-",!1,t)||[],r=Eo(e,n,"",!1,t)||[],i=Eo(n,e,"-?",!0,t)||[];return s.concat(i).concat(r).join("|")}function Sv(n,e){let t=1,s=1,r=jd(n,t),i=new Set([e]);for(;n<=r&&r<=e;)i.add(r),t+=1,r=jd(n,t);for(r=Hd(e+1,s)-1;n<r&&r<=e;)i.add(r),s+=1,r=Hd(e+1,s)-1;return i=[...i],i.sort(Av),i}function _v(n,e,t){if(n===e)return{pattern:n,count:[],digits:0};let s=kv(n,e),r=s.length,i="",o=0;for(let a=0;a<r;a++){let[l,u]=s[a];l===u?i+=l:l!=="0"||u!=="9"?i+=$v(l,u,t):o++}return o&&(i+=t.shorthand===!0?"\\d":"[0-9]"),{pattern:i,count:[o],digits:r}}function Nd(n,e,t,s){let r=Sv(n,e),i=[],o=n,a;for(let l=0;l<r.length;l++){let u=r[l],d=_v(String(o),String(u),s),f="";if(!t.isPadded&&a&&a.pattern===d.pattern){a.count.length>1&&a.count.pop(),a.count.push(d.count[0]),a.string=a.pattern+Bd(a.count),o=u+1;continue}t.isPadded&&(f=Cv(u,t,s)),d.string=f+d.pattern+Bd(d.count),i.push(d),o=u+1,a=d}return i}function Eo(n,e,t,s,r){let i=[];for(let o of n){let{string:a}=o;!s&&!Fd(e,"string",a)&&i.push(t+a),s&&Fd(e,"string",a)&&i.push(t+a)}return i}function kv(n,e){let t=[];for(let s=0;s<n.length;s++)t.push([n[s],e[s]]);return t}function Av(n,e){return n>e?1:e>n?-1:0}function Fd(n,e,t){return n.some(s=>s[e]===t)}function jd(n,e){return Number(String(n).slice(0,-e)+"9".repeat(e))}function Hd(n,e){return n-n%Math.pow(10,e)}function Bd(n){let[e=0,t=""]=n;return t||e>1?`{${e+(t?","+t:"")}}`:""}function $v(n,e,t){return`[${n}${e-n===1?"":"-"}${e}]`}function Ud(n){return/^-?(0+)\d/.test(n)}function Cv(n,e,t){if(!e.isPadded)return n;let s=Math.abs(e.maxLen-String(n).length),r=t.relaxZeros!==!1;switch(s){case 0:return"";case 1:return r?"0?":"0";case 2:return r?"0{0,2}":"00";default:return r?`0{0,${s}}`:`0{${s}}`}}Xt.cache={};Xt.clearCache=()=>Xt.cache={};qd.exports=Xt});var Oo=F((fE,Xd)=>{"use strict";var Ev=require("util"),Gd=Kd(),Wd=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),Tv=n=>e=>n===!0?Number(e):String(e),To=n=>typeof n=="number"||typeof n=="string"&&n!=="",Qn=n=>Number.isInteger(+n),Ro=n=>{let e=`${n}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},Rv=(n,e,t)=>typeof n=="string"||typeof e=="string"?!0:t.stringify===!0,Ov=(n,e,t)=>{if(e>0){let s=n[0]==="-"?"-":"";s&&(n=n.slice(1)),n=s+n.padStart(s?e-1:e,"0")}return t===!1?String(n):n},ir=(n,e)=>{let t=n[0]==="-"?"-":"";for(t&&(n=n.slice(1),e--);n.length<e;)n="0"+n;return t?"-"+n:n},Pv=(n,e,t)=>{n.negatives.sort((a,l)=>a<l?-1:a>l?1:0),n.positives.sort((a,l)=>a<l?-1:a>l?1:0);let s=e.capture?"":"?:",r="",i="",o;return n.positives.length&&(r=n.positives.map(a=>ir(String(a),t)).join("|")),n.negatives.length&&(i=`-(${s}${n.negatives.map(a=>ir(String(a),t)).join("|")})`),r&&i?o=`${r}|${i}`:o=r||i,e.wrap?`(${s}${o})`:o},Vd=(n,e,t,s)=>{if(t)return Gd(n,e,{wrap:!1,...s});let r=String.fromCharCode(n);if(n===e)return r;let i=String.fromCharCode(e);return`[${r}-${i}]`},zd=(n,e,t)=>{if(Array.isArray(n)){let s=t.wrap===!0,r=t.capture?"":"?:";return s?`(${r}${n.join("|")})`:n.join("|")}return Gd(n,e,t)},Yd=(...n)=>new RangeError("Invalid range arguments: "+Ev.inspect(...n)),Jd=(n,e,t)=>{if(t.strictRanges===!0)throw Yd([n,e]);return[]},Mv=(n,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${n}" to be a number`);return[]},Iv=(n,e,t=1,s={})=>{let r=Number(n),i=Number(e);if(!Number.isInteger(r)||!Number.isInteger(i)){if(s.strictRanges===!0)throw Yd([n,e]);return[]}r===0&&(r=0),i===0&&(i=0);let o=r>i,a=String(n),l=String(e),u=String(t);t=Math.max(Math.abs(t),1);let d=Ro(a)||Ro(l)||Ro(u),f=d?Math.max(a.length,l.length,u.length):0,h=d===!1&&Rv(n,e,s)===!1,m=s.transform||Tv(h);if(s.toRegex&&t===1)return Vd(ir(n,f),ir(e,f),!0,s);let p={negatives:[],positives:[]},g=$=>p[$<0?"negatives":"positives"].push(Math.abs($)),x=[],w=0;for(;o?r>=i:r<=i;)s.toRegex===!0&&t>1?g(r):x.push(Ov(m(r,w),f,h)),r=o?r-t:r+t,w++;return s.toRegex===!0?t>1?Pv(p,s,f):zd(x,null,{wrap:!1,...s}):x},Dv=(n,e,t=1,s={})=>{if(!Qn(n)&&n.length>1||!Qn(e)&&e.length>1)return Jd(n,e,s);let r=s.transform||(h=>String.fromCharCode(h)),i=`${n}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=i>o,l=Math.min(i,o),u=Math.max(i,o);if(s.toRegex&&t===1)return Vd(l,u,!1,s);let d=[],f=0;for(;a?i>=o:i<=o;)d.push(r(i,f)),i=a?i-t:i+t,f++;return s.toRegex===!0?zd(d,null,{wrap:!1,options:s}):d},rr=(n,e,t,s={})=>{if(e==null&&To(n))return[n];if(!To(n)||!To(e))return Jd(n,e,s);if(typeof t=="function")return rr(n,e,1,{transform:t});if(Wd(t))return rr(n,e,0,t);let r={...s};return r.capture===!0&&(r.wrap=!0),t=t||r.step||1,Qn(t)?Qn(n)&&Qn(e)?Iv(n,e,t,r):Dv(n,e,Math.max(Math.abs(t),1),r):t!=null&&!Wd(t)?Mv(t,r):rr(n,e,1,t)};Xd.exports=rr});var ef=F((pE,Zd)=>{"use strict";var Lv=Oo(),Qd=nr(),Nv=(n,e={})=>{let t=(s,r={})=>{let i=Qd.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a=i===!0||o===!0,l=e.escapeInvalid===!0?"\\":"",u="";if(s.isOpen===!0)return l+s.value;if(s.isClose===!0)return console.log("node.isClose",l,s.value),l+s.value;if(s.type==="open")return a?l+s.value:"(";if(s.type==="close")return a?l+s.value:")";if(s.type==="comma")return s.prev.type==="comma"?"":a?s.value:"|";if(s.value)return s.value;if(s.nodes&&s.ranges>0){let d=Qd.reduce(s.nodes),f=Lv(...d,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(f.length!==0)return d.length>1&&f.length>1?`(${f})`:f}if(s.nodes)for(let d of s.nodes)u+=t(d,s);return u};return t(n)};Zd.exports=Nv});var sf=F((hE,nf)=>{"use strict";var Fv=Oo(),tf=sr(),_n=nr(),Qt=(n="",e="",t=!1)=>{let s=[];if(n=[].concat(n),e=[].concat(e),!e.length)return n;if(!n.length)return t?_n.flatten(e).map(r=>`{${r}}`):e;for(let r of n)if(Array.isArray(r))for(let i of r)s.push(Qt(i,e,t));else for(let i of e)t===!0&&typeof i=="string"&&(i=`{${i}}`),s.push(Array.isArray(i)?Qt(r,i,t):r+i);return _n.flatten(s)},jv=(n,e={})=>{let t=e.rangeLimit===void 0?1e3:e.rangeLimit,s=(r,i={})=>{r.queue=[];let o=i,a=i.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(r.invalid||r.dollar){a.push(Qt(a.pop(),tf(r,e)));return}if(r.type==="brace"&&r.invalid!==!0&&r.nodes.length===2){a.push(Qt(a.pop(),["{}"]));return}if(r.nodes&&r.ranges>0){let f=_n.reduce(r.nodes);if(_n.exceedsLimit(...f,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let h=Fv(...f,e);h.length===0&&(h=tf(r,e)),a.push(Qt(a.pop(),h)),r.nodes=[];return}let l=_n.encloseBrace(r),u=r.queue,d=r;for(;d.type!=="brace"&&d.type!=="root"&&d.parent;)d=d.parent,u=d.queue;for(let f=0;f<r.nodes.length;f++){let h=r.nodes[f];if(h.type==="comma"&&r.type==="brace"){f===1&&u.push(""),u.push("");continue}if(h.type==="close"){a.push(Qt(a.pop(),u,l));continue}if(h.value&&h.type!=="open"){u.push(Qt(u.pop(),h.value));continue}h.nodes&&s(h,r)}return u};return _n.flatten(s(n))};nf.exports=jv});var of=F((mE,rf)=>{"use strict";rf.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
311
+ `,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var df=F((gE,uf)=>{"use strict";var Hv=sr(),{MAX_LENGTH:af,CHAR_BACKSLASH:Po,CHAR_BACKTICK:Bv,CHAR_COMMA:Uv,CHAR_DOT:qv,CHAR_LEFT_PARENTHESES:Kv,CHAR_RIGHT_PARENTHESES:Wv,CHAR_LEFT_CURLY_BRACE:Gv,CHAR_RIGHT_CURLY_BRACE:Vv,CHAR_LEFT_SQUARE_BRACKET:lf,CHAR_RIGHT_SQUARE_BRACKET:cf,CHAR_DOUBLE_QUOTE:zv,CHAR_SINGLE_QUOTE:Yv,CHAR_NO_BREAK_SPACE:Jv,CHAR_ZERO_WIDTH_NOBREAK_SPACE:Xv}=of(),Qv=(n,e={})=>{if(typeof n!="string")throw new TypeError("Expected a string");let t=e||{},s=typeof t.maxLength=="number"?Math.min(af,t.maxLength):af;if(n.length>s)throw new SyntaxError(`Input length (${n.length}), exceeds max characters (${s})`);let r={type:"root",input:n,nodes:[]},i=[r],o=r,a=r,l=0,u=n.length,d=0,f=0,h,m=()=>n[d++],p=g=>{if(g.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&g.type==="text"){a.value+=g.value;return}return o.nodes.push(g),g.parent=o,g.prev=a,a=g,g};for(p({type:"bos"});d<u;)if(o=i[i.length-1],h=m(),!(h===Xv||h===Jv)){if(h===Po){p({type:"text",value:(e.keepEscaping?h:"")+m()});continue}if(h===cf){p({type:"text",value:"\\"+h});continue}if(h===lf){l++;let g;for(;d<u&&(g=m());){if(h+=g,g===lf){l++;continue}if(g===Po){h+=m();continue}if(g===cf&&(l--,l===0))break}p({type:"text",value:h});continue}if(h===Kv){o=p({type:"paren",nodes:[]}),i.push(o),p({type:"text",value:h});continue}if(h===Wv){if(o.type!=="paren"){p({type:"text",value:h});continue}o=i.pop(),p({type:"text",value:h}),o=i[i.length-1];continue}if(h===zv||h===Yv||h===Bv){let g=h,x;for(e.keepQuotes!==!0&&(h="");d<u&&(x=m());){if(x===Po){h+=x+m();continue}if(x===g){e.keepQuotes===!0&&(h+=x);break}h+=x}p({type:"text",value:h});continue}if(h===Gv){f++;let x={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:f,commas:0,ranges:0,nodes:[]};o=p(x),i.push(o),p({type:"open",value:h});continue}if(h===Vv){if(o.type!=="brace"){p({type:"text",value:h});continue}let g="close";o=i.pop(),o.close=!0,p({type:g,value:h}),f--,o=i[i.length-1];continue}if(h===Uv&&f>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:Hv(o)}]}p({type:"comma",value:h}),o.commas++;continue}if(h===qv&&f>0&&o.commas===0){let g=o.nodes;if(f===0||g.length===0){p({type:"text",value:h});continue}if(a.type==="dot"){if(o.range=[],a.value+=h,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){g.pop();let x=g[g.length-1];x.value+=a.value+h,a=x,o.ranges--;continue}p({type:"dot",value:h});continue}p({type:"text",value:h})}do if(o=i.pop(),o.type!=="root"){o.nodes.forEach(w=>{w.nodes||(w.type==="open"&&(w.isOpen=!0),w.type==="close"&&(w.isClose=!0),w.nodes||(w.type="text"),w.invalid=!0)});let g=i[i.length-1],x=g.nodes.indexOf(o);g.nodes.splice(x,1,...o.nodes)}while(i.length>0);return p({type:"eos"}),r};uf.exports=Qv});var hf=F((yE,pf)=>{"use strict";var ff=sr(),Zv=ef(),ew=sf(),tw=df(),Ue=(n,e={})=>{let t=[];if(Array.isArray(n))for(let s of n){let r=Ue.create(s,e);Array.isArray(r)?t.push(...r):t.push(r)}else t=[].concat(Ue.create(n,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};Ue.parse=(n,e={})=>tw(n,e);Ue.stringify=(n,e={})=>ff(typeof n=="string"?Ue.parse(n,e):n,e);Ue.compile=(n,e={})=>(typeof n=="string"&&(n=Ue.parse(n,e)),Zv(n,e));Ue.expand=(n,e={})=>{typeof n=="string"&&(n=Ue.parse(n,e));let t=ew(n,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};Ue.create=(n,e={})=>n===""||n.length<3?[n]:e.expand!==!0?Ue.compile(n,e):Ue.expand(n,e);pf.exports=Ue});var mf=F((bE,nw)=>{nw.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]});var yf=F((vE,gf)=>{gf.exports=mf()});var vf=F((wE,bf)=>{"use strict";var sw=require("path"),rw=yf(),iw=new Set(rw);bf.exports=n=>iw.has(sw.extname(n).slice(1).toLowerCase())});var or=F(B=>{"use strict";var{sep:ow}=require("path"),{platform:Mo}=process,aw=require("os");B.EV_ALL="all";B.EV_READY="ready";B.EV_ADD="add";B.EV_CHANGE="change";B.EV_ADD_DIR="addDir";B.EV_UNLINK="unlink";B.EV_UNLINK_DIR="unlinkDir";B.EV_RAW="raw";B.EV_ERROR="error";B.STR_DATA="data";B.STR_END="end";B.STR_CLOSE="close";B.FSEVENT_CREATED="created";B.FSEVENT_MODIFIED="modified";B.FSEVENT_DELETED="deleted";B.FSEVENT_MOVED="moved";B.FSEVENT_CLONED="cloned";B.FSEVENT_UNKNOWN="unknown";B.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;B.FSEVENT_TYPE_FILE="file";B.FSEVENT_TYPE_DIRECTORY="directory";B.FSEVENT_TYPE_SYMLINK="symlink";B.KEY_LISTENERS="listeners";B.KEY_ERR="errHandlers";B.KEY_RAW="rawEmitters";B.HANDLER_KEYS=[B.KEY_LISTENERS,B.KEY_ERR,B.KEY_RAW];B.DOT_SLASH=`.${ow}`;B.BACK_SLASH_RE=/\\/g;B.DOUBLE_SLASH_RE=/\/\//;B.SLASH_OR_BACK_SLASH_RE=/[/\\]/;B.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;B.REPLACER_RE=/^\.[/\\]/;B.SLASH="/";B.SLASH_SLASH="//";B.BRACE_START="{";B.BANG="!";B.ONE_DOT=".";B.TWO_DOTS="..";B.STAR="*";B.GLOBSTAR="**";B.ROOT_GLOBSTAR="/**/*";B.SLASH_GLOBSTAR="/**";B.DIR_SUFFIX="Dir";B.ANYMATCH_OPTS={dot:!0};B.STRING_TYPE="string";B.FUNCTION_TYPE="function";B.EMPTY_STR="";B.EMPTY_FN=()=>{};B.IDENTITY_FN=n=>n;B.isWindows=Mo==="win32";B.isMacos=Mo==="darwin";B.isLinux=Mo==="linux";B.isIBMi=aw.type()==="OS400"});var Af=F((SE,kf)=>{"use strict";var Mt=require("fs"),_e=require("path"),{promisify:ns}=require("util"),lw=vf(),{isWindows:cw,isLinux:uw,EMPTY_FN:dw,EMPTY_STR:fw,KEY_LISTENERS:kn,KEY_ERR:Io,KEY_RAW:Zn,HANDLER_KEYS:pw,EV_CHANGE:lr,EV_ADD:ar,EV_ADD_DIR:hw,EV_ERROR:xf,STR_DATA:mw,STR_END:gw,BRACE_START:yw,STAR:bw}=or(),vw="watch",ww=ns(Mt.open),Sf=ns(Mt.stat),xw=ns(Mt.lstat),Sw=ns(Mt.close),Do=ns(Mt.realpath),_w={lstat:xw,stat:Sf},No=(n,e)=>{n instanceof Set?n.forEach(e):e(n)},es=(n,e,t)=>{let s=n[e];s instanceof Set||(n[e]=s=new Set([s])),s.add(t)},kw=n=>e=>{let t=n[e];t instanceof Set?t.clear():delete n[e]},ts=(n,e,t)=>{let s=n[e];s instanceof Set?s.delete(t):s===t&&delete n[e]},_f=n=>n instanceof Set?n.size===0:!n,cr=new Map;function wf(n,e,t,s,r){let i=(o,a)=>{t(n),r(o,a,{watchedPath:n}),a&&n!==a&&ur(_e.resolve(n,a),kn,_e.join(n,a))};try{return Mt.watch(n,e,i)}catch(o){s(o)}}var ur=(n,e,t,s,r)=>{let i=cr.get(n);i&&No(i[e],o=>{o(t,s,r)})},Aw=(n,e,t,s)=>{let{listener:r,errHandler:i,rawEmitter:o}=s,a=cr.get(e),l;if(!t.persistent)return l=wf(n,t,r,i,o),l.close.bind(l);if(a)es(a,kn,r),es(a,Io,i),es(a,Zn,o);else{if(l=wf(n,t,ur.bind(null,e,kn),i,ur.bind(null,e,Zn)),!l)return;l.on(xf,async u=>{let d=ur.bind(null,e,Io);if(a.watcherUnusable=!0,cw&&u.code==="EPERM")try{let f=await ww(n,"r");await Sw(f),d(u)}catch{}else d(u)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:l},cr.set(e,a)}return()=>{ts(a,kn,r),ts(a,Io,i),ts(a,Zn,o),_f(a.listeners)&&(a.watcher.close(),cr.delete(e),pw.forEach(kw(a)),a.watcher=void 0,Object.freeze(a))}},Lo=new Map,$w=(n,e,t,s)=>{let{listener:r,rawEmitter:i}=s,o=Lo.get(e),a=new Set,l=new Set,u=o&&o.options;return u&&(u.persistent<t.persistent||u.interval>t.interval)&&(a=o.listeners,l=o.rawEmitters,Mt.unwatchFile(e),o=void 0),o?(es(o,kn,r),es(o,Zn,i)):(o={listeners:r,rawEmitters:i,options:t,watcher:Mt.watchFile(e,t,(d,f)=>{No(o.rawEmitters,m=>{m(lr,e,{curr:d,prev:f})});let h=d.mtimeMs;(d.size!==f.size||h>f.mtimeMs||h===0)&&No(o.listeners,m=>m(n,d))})},Lo.set(e,o)),()=>{ts(o,kn,r),ts(o,Zn,i),_f(o.listeners)&&(Lo.delete(e),Mt.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},Fo=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let s=this.fsw.options,r=_e.dirname(e),i=_e.basename(e);this.fsw._getWatchedDir(r).add(i);let a=_e.resolve(e),l={persistent:s.persistent};t||(t=dw);let u;return s.usePolling?(l.interval=s.enableBinaryInterval&&lw(i)?s.binaryInterval:s.interval,u=$w(e,a,l,{listener:t,rawEmitter:this.fsw._emitRaw})):u=Aw(e,a,l,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),u}_handleFile(e,t,s){if(this.fsw.closed)return;let r=_e.dirname(e),i=_e.basename(e),o=this.fsw._getWatchedDir(r),a=t;if(o.has(i))return;let l=async(d,f)=>{if(this.fsw._throttle(vw,e,5)){if(!f||f.mtimeMs===0)try{let h=await Sf(e);if(this.fsw.closed)return;let m=h.atimeMs,p=h.mtimeMs;(!m||m<=p||p!==a.mtimeMs)&&this.fsw._emit(lr,e,h),uw&&a.ino!==h.ino?(this.fsw._closeFile(d),a=h,this.fsw._addPathCloser(d,this._watchWithNodeFs(e,l))):a=h}catch{this.fsw._remove(r,i)}else if(o.has(i)){let h=f.atimeMs,m=f.mtimeMs;(!h||h<=m||m!==a.mtimeMs)&&this.fsw._emit(lr,e,f),a=f}}},u=this._watchWithNodeFs(e,l);if(!(s&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(ar,e,0))return;this.fsw._emit(ar,e,t)}return u}async _handleSymlink(e,t,s,r){if(this.fsw.closed)return;let i=e.fullPath,o=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await Do(s)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(r)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(lr,s,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(ar,s,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,s,r,i,o,a){if(e=_e.join(e,fw),!s.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let l=this.fsw._getWatchedDir(s.path),u=new Set,d=this.fsw._readdirp(e,{fileFilter:f=>s.filterPath(f),directoryFilter:f=>s.filterDir(f),depth:0}).on(mw,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,m=_e.join(e,h);if(u.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===r||!r&&!l.has(h))&&(this.fsw._incrReadyCount(),m=_e.join(i,_e.relative(i,m)),this._addToNodeFs(m,t,s,o+1))}}).on(xf,this._boundHandleError);return new Promise(f=>d.once(gw,()=>{if(this.fsw.closed){d=void 0;return}let h=a?a.clear():!1;f(),l.getChildren().filter(m=>m!==e&&!u.has(m)&&(!s.hasGlob||s.filterPath({fullPath:_e.resolve(e,m)}))).forEach(m=>{this.fsw._remove(e,m)}),d=void 0,h&&this._handleRead(e,!1,s,r,i,o,a)}))}async _handleDir(e,t,s,r,i,o,a){let l=this.fsw._getWatchedDir(_e.dirname(e)),u=l.has(_e.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!i&&!u&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(hw,e,t),l.add(_e.basename(e)),this.fsw._getWatchedDir(e);let d,f,h=this.fsw.options.depth;if((h==null||r<=h)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,s,o,i,e,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(m,p)=>{p&&p.mtimeMs===0||this._handleRead(m,!1,o,i,e,r,d)})}return f}async _addToNodeFs(e,t,s,r,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,r);!a.hasGlob&&s&&(a.hasGlob=s.hasGlob,a.globFilter=s.globFilter,a.filterPath=l=>s.filterPath(l),a.filterDir=l=>s.filterDir(l));try{let l=await _w[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))return o(),!1;let u=this.fsw.options.followSymlinks&&!e.includes(bw)&&!e.includes(yw),d;if(l.isDirectory()){let f=_e.resolve(e),h=u?await Do(e):e;if(this.fsw.closed||(d=await this._handleDir(a.watchPath,l,t,r,i,a,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(l.isSymbolicLink()){let f=u?await Do(e):e;if(this.fsw.closed)return;let h=_e.dirname(a.watchPath);if(this.fsw._getWatchedDir(h).add(a.watchPath),this.fsw._emit(ar,a.watchPath,l),d=await this._handleDir(h,l,t,r,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(_e.resolve(e),f)}else d=this._handleFile(a.watchPath,l,t);return o(),this.fsw._addPathCloser(e,d),!1}catch(l){if(this.fsw._handleError(l))return o(),e}}};kf.exports=Fo});var Pf=F((_E,Go)=>{"use strict";var Ko=require("fs"),ke=require("path"),{promisify:Wo}=require("util"),An;try{An=require("fsevents")}catch(n){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(n)}if(An){let n=process.version.match(/v(\d+)\.(\d+)/);if(n&&n[1]&&n[2]){let e=Number.parseInt(n[1],10),t=Number.parseInt(n[2],10);e===8&&t<16&&(An=void 0)}}var{EV_ADD:jo,EV_CHANGE:Cw,EV_ADD_DIR:$f,EV_UNLINK:dr,EV_ERROR:Ew,STR_DATA:Tw,STR_END:Rw,FSEVENT_CREATED:Ow,FSEVENT_MODIFIED:Pw,FSEVENT_DELETED:Mw,FSEVENT_MOVED:Iw,FSEVENT_UNKNOWN:Dw,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:Lw,FSEVENT_TYPE_FILE:Nw,FSEVENT_TYPE_DIRECTORY:ss,FSEVENT_TYPE_SYMLINK:Of,ROOT_GLOBSTAR:Cf,DIR_SUFFIX:Fw,DOT_SLASH:Ef,FUNCTION_TYPE:Ho,EMPTY_FN:jw,IDENTITY_FN:Hw}=or(),Bw=n=>isNaN(n)?{}:{depth:n},Uo=Wo(Ko.stat),Uw=Wo(Ko.lstat),Tf=Wo(Ko.realpath),qw={stat:Uo,lstat:Uw},Zt=new Map,Kw=10,Ww=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),Gw=(n,e)=>({stop:An.watch(n,e)});function Vw(n,e,t,s){let r=ke.extname(e)?ke.dirname(e):e,i=ke.dirname(r),o=Zt.get(r);zw(i)&&(r=i);let a=ke.resolve(n),l=a!==e,u=(f,h,m)=>{l&&(f=f.replace(e,a)),(f===a||!f.indexOf(a+ke.sep))&&t(f,h,m)},d=!1;for(let f of Zt.keys())if(e.indexOf(ke.resolve(f)+ke.sep)===0){r=f,o=Zt.get(r),d=!0;break}return o||d?o.listeners.add(u):(o={listeners:new Set([u]),rawEmitter:s,watcher:Gw(r,(f,h)=>{if(!o.listeners.size||h&Lw)return;let m=An.getInfo(f,h);o.listeners.forEach(p=>{p(f,h,m)}),o.rawEmitter(m.event,f,m)})},Zt.set(r,o)),()=>{let f=o.listeners;if(f.delete(u),!f.size&&(Zt.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var zw=n=>{let e=0;for(let t of Zt.keys())if(t.indexOf(n)===0&&(e++,e>=Kw))return!0;return!1},Yw=()=>An&&Zt.size<128,Bo=(n,e)=>{let t=0;for(;!n.indexOf(e)&&(n=ke.dirname(n))!==e;)t++;return t},Rf=(n,e)=>n.type===ss&&e.isDirectory()||n.type===Of&&e.isSymbolicLink()||n.type===Nw&&e.isFile(),qo=class{constructor(e){this.fsw=e}checkIgnored(e,t){let s=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,t))return s.add(e),t&&t.isDirectory()&&s.add(e+Cf),!0;s.delete(e),s.delete(e+Cf)}addOrChange(e,t,s,r,i,o,a,l){let u=i.has(o)?Cw:jo;this.handleEvent(u,e,t,s,r,i,o,a,l)}async checkExists(e,t,s,r,i,o,a,l){try{let u=await Uo(e);if(this.fsw.closed)return;Rf(a,u)?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(dr,e,t,s,r,i,o,a,l)}catch(u){u.code==="EACCES"?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(dr,e,t,s,r,i,o,a,l)}}handleEvent(e,t,s,r,i,o,a,l,u){if(!(this.fsw.closed||this.checkIgnored(t)))if(e===dr){let d=l.type===ss;(d||o.has(a))&&this.fsw._remove(i,a,d)}else{if(e===jo){if(l.type===ss&&this.fsw._getWatchedDir(t),l.type===Of&&u.followSymlinks){let f=u.depth===void 0?void 0:Bo(s,r)+1;return this._addToFsEvents(t,!1,!0,f)}this.fsw._getWatchedDir(i).add(a)}let d=l.type===ss?e+Fw:e;this.fsw._emit(d,t),d===$f&&this._addToFsEvents(t,!1,!0)}}_watchWithFsEvents(e,t,s,r){if(this.fsw.closed||this.fsw._isIgnored(e))return;let i=this.fsw.options,a=Vw(e,t,async(l,u,d)=>{if(this.fsw.closed||i.depth!==void 0&&Bo(l,t)>i.depth)return;let f=s(ke.join(e,ke.relative(e,l)));if(r&&!r(f))return;let h=ke.dirname(f),m=ke.basename(f),p=this.fsw._getWatchedDir(d.type===ss?f:h);if(Ww.has(u)||d.event===Dw)if(typeof i.ignored===Ho){let g;try{g=await Uo(f)}catch{}if(this.fsw.closed||this.checkIgnored(f,g))return;Rf(d,g)?this.addOrChange(f,l,t,h,p,m,d,i):this.handleEvent(dr,f,l,t,h,p,m,d,i)}else this.checkExists(f,l,t,h,p,m,d,i);else switch(d.event){case Ow:case Pw:return this.addOrChange(f,l,t,h,p,m,d,i);case Mw:case Iw:return this.checkExists(f,l,t,h,p,m,d,i)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,t,s,r){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(t))){this.fsw._symlinkPaths.set(t,!0),this.fsw._incrReadyCount();try{let i=await Tf(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(i))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(i||e,o=>{let a=e;return i&&i!==Ef?a=o.replace(i,e):o!==Ef&&(a=ke.join(e,o)),s(a)},!1,r)}catch(i){if(this.fsw._handleError(i))return this.fsw._emitReady()}}}emitAdd(e,t,s,r,i){let o=s(e),a=t.isDirectory(),l=this.fsw._getWatchedDir(ke.dirname(o)),u=ke.basename(o);a&&this.fsw._getWatchedDir(o),!l.has(u)&&(l.add(u),(!r.ignoreInitial||i===!0)&&this.fsw._emit(a?$f:jo,o,t))}initWatch(e,t,s,r){if(this.fsw.closed)return;let i=this._watchWithFsEvents(s.watchPath,ke.resolve(e||s.watchPath),r,s.globFilter);this.fsw._addPathCloser(t,i)}async _addToFsEvents(e,t,s,r){if(this.fsw.closed)return;let i=this.fsw.options,o=typeof t===Ho?t:Hw,a=this.fsw._getWatchHelpers(e);try{let l=await qw[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))throw null;if(l.isDirectory()){if(a.globFilter||this.emitAdd(o(e),l,o,i,s),r&&r>i.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:u=>a.filterPath(u),directoryFilter:u=>a.filterDir(u),...Bw(i.depth-(r||0))}).on(Tw,u=>{if(this.fsw.closed||u.stats.isDirectory()&&!a.filterPath(u))return;let d=ke.join(a.watchPath,u.path),{fullPath:f}=u;if(a.followSymlinks&&u.stats.isSymbolicLink()){let h=i.depth===void 0?void 0:Bo(d,ke.resolve(a.watchPath))+1;this._handleFsEventsSymlink(d,f,o,h)}else this.emitAdd(d,u.stats,o,i,s)}).on(Ew,jw).on(Rw,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,l,o,i,s),this.fsw._emitReady()}catch(l){(!l||this.fsw._handleError(l))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(i.persistent&&s!==!0)if(typeof t===Ho)this.initWatch(void 0,e,a,o);else{let l;try{l=await Tf(a.watchPath)}catch{}this.initWatch(l,e,a,o)}}};Go.exports=qo;Go.exports.canUse=Yw});var qf=F(aa=>{"use strict";var{EventEmitter:Jw}=require("events"),ia=require("fs"),ie=require("path"),{promisify:jf}=require("util"),Xw=bd(),Qo=Ad().default,Qw=Od(),Vo=$o(),Zw=hf(),ex=ko(),tx=Af(),Mf=Pf(),{EV_ALL:zo,EV_READY:nx,EV_ADD:fr,EV_CHANGE:rs,EV_UNLINK:If,EV_ADD_DIR:sx,EV_UNLINK_DIR:rx,EV_RAW:ix,EV_ERROR:Yo,STR_CLOSE:ox,STR_END:ax,BACK_SLASH_RE:lx,DOUBLE_SLASH_RE:Df,SLASH_OR_BACK_SLASH_RE:cx,DOT_RE:ux,REPLACER_RE:dx,SLASH:Jo,SLASH_SLASH:fx,BRACE_START:px,BANG:Zo,ONE_DOT:Hf,TWO_DOTS:hx,GLOBSTAR:mx,SLASH_GLOBSTAR:Xo,ANYMATCH_OPTS:ea,STRING_TYPE:oa,FUNCTION_TYPE:gx,EMPTY_STR:ta,EMPTY_FN:yx,isWindows:bx,isMacos:vx,isIBMi:wx}=or(),xx=jf(ia.stat),Sx=jf(ia.readdir),na=(n=[])=>Array.isArray(n)?n:[n],Bf=(n,e=[])=>(n.forEach(t=>{Array.isArray(t)?Bf(t,e):e.push(t)}),e),Lf=n=>{let e=Bf(na(n));if(!e.every(t=>typeof t===oa))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Uf)},Nf=n=>{let e=n.replace(lx,Jo),t=!1;for(e.startsWith(fx)&&(t=!0);e.match(Df);)e=e.replace(Df,Jo);return t&&(e=Jo+e),e},Uf=n=>Nf(ie.normalize(Nf(n))),Ff=(n=ta)=>e=>typeof e!==oa?e:Uf(ie.isAbsolute(e)?e:ie.join(n,e)),_x=(n,e)=>ie.isAbsolute(n)?n:n.startsWith(Zo)?Zo+ie.join(e,n.slice(1)):ie.join(e,n),ot=(n,e)=>n[e]===void 0,sa=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Hf&&e!==hx&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let s=this.path;try{await Sx(s)}catch{this._removeWatcher&&this._removeWatcher(ie.dirname(s),ie.basename(s))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;if(e)return[...e.values()]}dispose(){this.items.clear(),delete this.path,delete this._removeWatcher,delete this.items,Object.freeze(this)}},kx="stat",Ax="lstat",ra=class{constructor(e,t,s,r){this.fsw=r,this.path=e=e.replace(dx,ta),this.watchPath=t,this.fullWatchPath=ie.resolve(t),this.hasGlob=t!==e,e===ta&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&s?void 0:!1,this.globFilter=this.hasGlob?Qo(e,void 0,ea):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=s,this.statMethod=s?kx:Ax}checkGlobSymlink(e){return this.globSymlink===void 0&&(this.globSymlink=e.fullParentDir===this.fullWatchPath?!1:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}),this.globSymlink?e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath):e.fullPath}entryPath(e){return ie.join(this.watchPath,ie.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let s=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===gx?this.globFilter(s):!0)&&this.fsw._isntIgnored(s,t)&&this.fsw._hasReadPermissions(t)}getDirParts(e){if(!this.hasGlob)return[];let t=[];return(e.includes(px)?Zw.expand(e):[e]).forEach(r=>{t.push(ie.relative(this.watchPath,r).split(cx))}),t}filterDir(e){if(this.hasGlob){let t=this.getDirParts(this.checkGlobSymlink(e)),s=!1;this.unmatchedGlob=!this.dirParts.some(r=>r.every((i,o)=>(i===mx&&(s=!0),s||!t[0][o]||Qo(i,t[0][o],ea))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},pr=class extends Jw{constructor(e){super();let t={};e&&Object.assign(t,e),this._watched=new Map,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._symlinkPaths=new Map,this._streams=new Set,this.closed=!1,ot(t,"persistent")&&(t.persistent=!0),ot(t,"ignoreInitial")&&(t.ignoreInitial=!1),ot(t,"ignorePermissionErrors")&&(t.ignorePermissionErrors=!1),ot(t,"interval")&&(t.interval=100),ot(t,"binaryInterval")&&(t.binaryInterval=300),ot(t,"disableGlobbing")&&(t.disableGlobbing=!1),t.enableBinaryInterval=t.binaryInterval!==t.interval,ot(t,"useFsEvents")&&(t.useFsEvents=!t.usePolling),Mf.canUse()||(t.useFsEvents=!1),ot(t,"usePolling")&&!t.useFsEvents&&(t.usePolling=vx),wx&&(t.usePolling=!0);let r=process.env.CHOKIDAR_USEPOLLING;if(r!==void 0){let l=r.toLowerCase();l==="false"||l==="0"?t.usePolling=!1:l==="true"||l==="1"?t.usePolling=!0:t.usePolling=!!l}let i=process.env.CHOKIDAR_INTERVAL;i&&(t.interval=Number.parseInt(i,10)),ot(t,"atomic")&&(t.atomic=!t.usePolling&&!t.useFsEvents),t.atomic&&(this._pendingUnlinks=new Map),ot(t,"followSymlinks")&&(t.followSymlinks=!0),ot(t,"awaitWriteFinish")&&(t.awaitWriteFinish=!1),t.awaitWriteFinish===!0&&(t.awaitWriteFinish={});let o=t.awaitWriteFinish;o&&(o.stabilityThreshold||(o.stabilityThreshold=2e3),o.pollInterval||(o.pollInterval=100),this._pendingWrites=new Map),t.ignored&&(t.ignored=na(t.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=yx,this._readyEmitted=!0,process.nextTick(()=>this.emit(nx)))},this._emitRaw=(...l)=>this.emit(ix,...l),this._readyEmitted=!1,this.options=t,t.useFsEvents?this._fsEventsHandler=new Mf(this):this._nodeFsHandler=new tx(this),Object.freeze(t)}add(e,t,s){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=Lf(e);return r&&(o=o.map(a=>{let l=_x(a,r);return i||!Vo(a)?l:ex(l)})),o=o.filter(a=>a.startsWith(Zo)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+Xo),this._userIgnored=void 0,!0)),this.options.useFsEvents&&this._fsEventsHandler?(this._readyCount||(this._readyCount=o.length),this.options.persistent&&(this._readyCount+=o.length),o.forEach(a=>this._fsEventsHandler._addToFsEvents(a))):(this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let l=await this._nodeFsHandler._addToNodeFs(a,!s,0,0,t);return l&&this._emitReady(),l})).then(a=>{this.closed||a.filter(l=>l).forEach(l=>{this.add(ie.dirname(l),ie.basename(t||l))})})),this}unwatch(e){if(this.closed)return this;let t=Lf(e),{cwd:s}=this.options;return t.forEach(r=>{!ie.isAbsolute(r)&&!this._closers.has(r)&&(s&&(r=ie.join(s,r)),r=ie.resolve(r)),this._closePath(r),this._ignoredPaths.add(r),this._watched.has(r)&&this._ignoredPaths.add(r+Xo),this._userIgnored=void 0}),this}close(){if(this.closed)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(s=>{let r=s();r instanceof Promise&&e.push(r)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),["closers","watched","streams","symlinkPaths","throttled"].forEach(t=>{this[`_${t}`].clear()}),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,s)=>{let r=this.options.cwd?ie.relative(this.options.cwd,s):s;e[r||Hf]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(...t),e!==Yo&&this.emit(zo,...t)}async _emit(e,t,s,r,i){if(this.closed)return;let o=this.options;bx&&(t=ie.normalize(t)),o.cwd&&(t=ie.relative(o.cwd,t));let a=[e,t];i!==void 0?a.push(s,r,i):r!==void 0?a.push(s,r):s!==void 0&&a.push(s);let l=o.awaitWriteFinish,u;if(l&&(u=this._pendingWrites.get(t)))return u.lastChange=new Date,this;if(o.atomic){if(e===If)return this._pendingUnlinks.set(t,a),setTimeout(()=>{this._pendingUnlinks.forEach((d,f)=>{this.emit(...d),this.emit(zo,...d),this._pendingUnlinks.delete(f)})},typeof o.atomic=="number"?o.atomic:100),this;e===fr&&this._pendingUnlinks.has(t)&&(e=a[0]=rs,this._pendingUnlinks.delete(t))}if(l&&(e===fr||e===rs)&&this._readyEmitted){let d=(f,h)=>{f?(e=a[0]=Yo,a[1]=f,this.emitWithAll(e,a)):h&&(a.length>2?a[2]=h:a.push(h),this.emitWithAll(e,a))};return this._awaitWriteFinish(t,l.stabilityThreshold,e,d),this}if(e===rs&&!this._throttle(rs,t,50))return this;if(o.alwaysStat&&s===void 0&&(e===fr||e===sx||e===rs)){let d=o.cwd?ie.join(o.cwd,t):t,f;try{f=await xx(d)}catch{}if(!f||this.closed)return;a.push(f)}return this.emitWithAll(e,a),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(Yo,e),e||this.closed}_throttle(e,t,s){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e),i=r.get(t);if(i)return i.count++,!1;let o,a=()=>{let u=r.get(t),d=u?u.count:0;return r.delete(t),clearTimeout(o),u&&clearTimeout(u.timeoutObject),d};o=setTimeout(a,s);let l={timeoutObject:o,clear:a,count:0};return r.set(t,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,s,r){let i,o=e;this.options.cwd&&!ie.isAbsolute(e)&&(o=ie.join(this.options.cwd,e));let a=new Date,l=u=>{ia.stat(o,(d,f)=>{if(d||!this._pendingWrites.has(e)){d&&d.code!=="ENOENT"&&r(d);return}let h=Number(new Date);u&&f.size!==u.size&&(this._pendingWrites.get(e).lastChange=h);let m=this._pendingWrites.get(e);h-m.lastChange>=t?(this._pendingWrites.delete(e),r(void 0,f)):i=setTimeout(l,this.options.awaitWriteFinish.pollInterval,f)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(i),s)}),i=setTimeout(l,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,t){if(this.options.atomic&&ux.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,r=this.options.ignored,i=r&&r.map(Ff(s)),o=na(i).filter(l=>typeof l===oa&&!Vo(l)).map(l=>l+Xo),a=this._getGlobIgnored().map(Ff(s)).concat(i,o);this._userIgnored=Qo(a,void 0,ea)}return this._userIgnored([e,t])}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e,t){let s=t||this.options.disableGlobbing||!Vo(e)?e:Qw(e),r=this.options.followSymlinks;return new ra(e,s,r,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let t=ie.resolve(e);return this._watched.has(t)||this._watched.set(t,new sa(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let s=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(s.toString(8)[0],10))}_remove(e,t,s){let r=ie.join(e,t),i=ie.resolve(r);if(s=s??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!s&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(h=>this._remove(r,h));let l=this._getWatchedDir(e),u=l.has(t);l.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=ie.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===fr)return;this._watched.delete(r),this._watched.delete(i);let f=s?rx:If;u&&!this._isIgnored(r)&&this._emit(f,r),this.options.useFsEvents||this._closePath(r)}_closePath(e){this._closeFile(e);let t=ie.dirname(e);this._getWatchedDir(t).remove(ie.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(s=>s()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let s=this._closers.get(e);s||(s=[],this._closers.set(e,s)),s.push(t)}_readdirp(e,t){if(this.closed)return;let s={type:zo,alwaysStat:!0,lstat:!0,...t},r=Xw(e,s);return this._streams.add(r),r.once(ox,()=>{r=void 0}),r.once(ax,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};aa.FSWatcher=pr;var $x=(n,e)=>{let t=new pr(e);return t.add(n),t};aa.watch=$x});var Vf={};Ne(Vf,{CollaborationManager:()=>is,addTeamMember:()=>Tx,formatTeamConfig:()=>Rx,initTeamConfig:()=>Ex,loadTeamConfig:()=>Cx,saveTeamConfig:()=>Gf});function Cx(n){let e=Je.join(n,".hablas","team.json");if(ye.existsSync(e))try{return JSON.parse(ye.readFileSync(e,"utf-8"))}catch{return null}return null}function Ex(n,e){let t={name:e,members:[]};return Gf(n,t),t}function Gf(n,e){let t=Je.join(n,".hablas","team.json"),s=Je.dirname(t);ye.existsSync(s)||ye.mkdirSync(s,{recursive:!0}),ye.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}function Tx(n,e,t){return n.members.push({name:e,email:t}),n}function Rx(n){return[`Team: ${n.name}`,"Members:",...n.members.map(t=>` - ${t.name} (${t.email})`)].join(`
312
+ `)}var ye,Je,hr,Kf,Wf,is,la=L(()=>{"use strict";ye=O(require("fs")),Je=O(require("path")),hr=O(require("os")),Kf=O(require("crypto")),Wf=O(qf());bn();is=class n{workingDir;config;username;teamKey;projectTeamToken;supabaseUrl="";supabaseKey="";isConfigured=!1;watcher=null;localStatePath;heartbeatInterval=null;syncInterval=null;static HEARTBEAT_MS=12e3;static POLL_ACTIVE_MS=3e3;static POLL_IDLE_MS=2e4;static STALE_MS=75e3;consecutiveHeartbeatFailures=0;announcedOffline=!1;idlePollTicks=0;signalHandler=null;shuttingDown=!1;currentActivity={section:"idle",task:"standby"};knownSessions=new Map;knownLocks=new Map;constructor(e,t,s,r){this.workingDir=e,this.config=t,this.username=s||hr.userInfo().username||"developer",this.teamKey=r||"default-team",this.localStatePath=Je.join(this.workingDir,".hablas","collaboration.json");let i=this.getProjectIdentifier();console.log(`
313
+ ${c.muted("[Debug] Project Context:")} ${c.highlight(i)}`),this.projectTeamToken=Kf.createHash("sha256").update(`${i}:${this.teamKey}`).digest("hex"),console.log(` ${c.muted("[Debug] Session Fingerprint:")} ${c.muted(this.projectTeamToken.slice(0,16))}...
314
+ `),this.loadSupabaseConfig()}async init(){if(!this.isConfigured)return console.log(` ${c.warning("\u26A0")} ${c.secondary("Supabase is not configured in .env. Collaboration mode operates locally.")}`),!1;let e=Je.dirname(this.localStatePath);return ye.existsSync(e)||ye.mkdirSync(e,{recursive:!0}),this.saveLocalState([],[]),this.startLoops(),this.startWatcher(),this.registerCleanups(),!0}async shutdown(){this.shuttingDown||(this.shuttingDown=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.syncInterval&&(clearTimeout(this.syncInterval),this.syncInterval=null),this.watcher&&(await this.watcher.close(),this.watcher=null),this.signalHandler&&(process.off("SIGINT",this.signalHandler),process.off("SIGTERM",this.signalHandler),this.signalHandler=null),await this.releaseAllMyLocks(),await this.deleteSession())}async apiRequest(e,t,s,r){if(!this.isConfigured)return{ok:!1,data:null};let i=`${this.supabaseUrl}/rest/v1/${e}`,o={apikey:this.supabaseKey,Authorization:`Bearer ${this.supabaseKey}`,"Content-Type":"application/json"};r?.prefer?o.Prefer=r.prefer:(t==="POST"||t==="PATCH")&&(o.Prefer="return=representation");let a=(r?.retries??0)+1,l=null;for(let u=0;u<a;u++)try{let d=await fetch(i,{method:t,headers:o,body:s?JSON.stringify(s):void 0,signal:AbortSignal.timeout(1e4)});if(!d.ok){let h=await d.text().catch(()=>"");if(l=new Error(`[Supabase ${d.status}] ${h}`),(d.status>=500||d.status===429)&&u<a-1){await this.delay(400*(u+1));continue}return{ok:!1,data:null}}let f=await d.text();return{ok:!0,data:f?JSON.parse(f):null}}catch(d){if(l=d,u<a-1){await this.delay(400*(u+1));continue}}return{ok:!1,data:null}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendHeartbeat(e,t){let s={project_team_token:this.projectTeamToken,developer_name:this.username,last_heartbeat:new Date().toISOString(),active_section:e||"idle",current_task:t||"none"},r="hablas_team_sessions?on_conflict=project_team_token,developer_name",{ok:i}=await this.apiRequest(r,"POST",s,{prefer:"resolution=merge-duplicates,return=minimal",retries:2});return i}async fetchSessions(){let e=`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}`,{data:t}=await this.apiRequest(e,"GET");return t||[]}async deleteSession(){let e=`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}&developer_name=eq.${encodeURIComponent(this.username)}`;await this.apiRequest(e,"DELETE")}async fetchLocks(){let e=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}`,{data:t}=await this.apiRequest(e,"GET");return t||[]}async acquireLock(e,t){let s={project_team_token:this.projectTeamToken,file_path:e,locked_by:this.username,lock_context:t||"editing file",created_at:new Date().toISOString()};return await this.apiRequest("hablas_team_locks?on_conflict=project_team_token,file_path","POST",s,{prefer:"resolution=ignore-duplicates,return=minimal",retries:1}),!!(await this.fetchLocks()).find(a=>a.file_path===e&&a.locked_by===this.username)}async releaseLock(e){let t=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}&file_path=eq.${encodeURIComponent(e)}&locked_by=eq.${encodeURIComponent(this.username)}`;return await this.apiRequest(t,"DELETE"),!0}async releaseAllMyLocks(){let e=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}&locked_by=eq.${encodeURIComponent(this.username)}`;await this.apiRequest(e,"DELETE")}async sendMessage(e,t){let s={project_team_token:this.projectTeamToken,sender_name:this.username,receiver_name:e,message_content:t,is_read:!1,created_at:new Date().toISOString()},{ok:r}=await this.apiRequest("hablas_team_messages","POST",s,{retries:1});return r}async fetchUnreadMessages(){let e=`hablas_team_messages?project_team_token=eq.${this.projectTeamToken}&receiver_name=eq.${encodeURIComponent(this.username)}&is_read=eq.false`,t=(await this.apiRequest(e,"GET")).data||[];if(t.length>0)for(let s of t){let r=`hablas_team_messages?id=eq.${s.id}`;await this.apiRequest(r,"PATCH",{is_read:!0})}return t}saveLocalState(e,t){let s={project_team_token:this.projectTeamToken,last_sync:new Date().toISOString(),my_username:this.username,sessions:e,locks:t};ye.writeFileSync(this.localStatePath,JSON.stringify(s,null,2),"utf-8")}getLocalState(){if(ye.existsSync(this.localStatePath))try{return JSON.parse(ye.readFileSync(this.localStatePath,"utf-8"))}catch{}return{sessions:[],locks:[],my_username:this.username}}startLoops(){this.beat("idle","standby"),this.heartbeatInterval=setInterval(()=>{this.beat()},n.HEARTBEAT_MS);let e=t=>{this.syncInterval=setTimeout(async()=>{if(this.shuttingDown)return;await this.syncWithCloud()?this.idlePollTicks=0:this.idlePollTicks++;let r=this.idlePollTicks>=3?n.POLL_IDLE_MS:n.POLL_ACTIVE_MS;e(r)},t)};e(n.POLL_ACTIVE_MS)}setActivity(e,t="working"){this.currentActivity={section:t,task:e.slice(0,120)},this.beat(t,this.currentActivity.task)}async beat(e,t){await this.sendHeartbeat(e??this.currentActivity.section,t??this.currentActivity.task)?(this.announcedOffline&&(console.log(`
315
315
  ${c.success("\u2713")} ${c.muted("[Team]")} Cloud sync reconnected \u2014 session restored.
316
316
  `),this.announcedOffline=!1),this.consecutiveHeartbeatFailures=0):(this.consecutiveHeartbeatFailures++,this.consecutiveHeartbeatFailures>=4&&!this.announcedOffline&&(console.log(`
317
317
  ${c.warning("\u26A0")} ${c.muted("[Team]")} Cloud sync is unreachable \u2014 retrying in the background. Your session is preserved.
318
- `),this.announcedOffline=!0))}async syncWithCloud(){let e=await this.apiRequest(`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}`,"GET");if(!e.ok)return!1;let t=e.data||[],s=await this.fetchLocks(),r=await this.fetchUnreadMessages();for(let u of r)this.renderMessageBox(u.sender_name,u.message_content);let i=Date.now(),o=t.filter(u=>{if(u.developer_name===this.username)return!0;let d=new Date(u.last_heartbeat).getTime();return i-d<=n.STALE_MS}),a=this.getLocalState(),l=r.length>0||JSON.stringify(a.sessions?.map(u=>u.developer_name).sort())!==JSON.stringify(o.map(u=>u.developer_name).sort())||JSON.stringify(a.locks?.map(u=>`${u.file_path}:${u.locked_by}`).sort())!==JSON.stringify(s.map(u=>`${u.file_path}:${u.locked_by}`).sort());return this.saveLocalState(o,s),l}startWatcher(){this.watcher=Hf.default.watch(this.localStatePath,{ignoreInitial:!1,persistent:!0}),this.watcher.on("change",()=>{let e=this.getLocalState();this.processStateChanges(e.sessions,e.locks)})}processStateChanges(e,t){let s=new Set;for(let i of e)if(i.developer_name!==this.username)if(s.add(i.developer_name),!this.knownSessions.has(i.developer_name))this.knownSessions.set(i.developer_name,i.current_task||"none"),console.log(`
318
+ `),this.announcedOffline=!0))}async syncWithCloud(){let e=await this.apiRequest(`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}`,"GET");if(!e.ok)return!1;let t=e.data||[],s=await this.fetchLocks(),r=await this.fetchUnreadMessages();for(let u of r)this.renderMessageBox(u.sender_name,u.message_content);let i=Date.now(),o=t.filter(u=>{if(u.developer_name===this.username)return!0;let d=new Date(u.last_heartbeat).getTime();return i-d<=n.STALE_MS}),a=this.getLocalState(),l=r.length>0||JSON.stringify(a.sessions?.map(u=>u.developer_name).sort())!==JSON.stringify(o.map(u=>u.developer_name).sort())||JSON.stringify(a.locks?.map(u=>`${u.file_path}:${u.locked_by}`).sort())!==JSON.stringify(s.map(u=>`${u.file_path}:${u.locked_by}`).sort());return this.saveLocalState(o,s),l}startWatcher(){this.watcher=Wf.default.watch(this.localStatePath,{ignoreInitial:!1,persistent:!0}),this.watcher.on("change",()=>{let e=this.getLocalState();this.processStateChanges(e.sessions,e.locks)})}processStateChanges(e,t){let s=new Set;for(let i of e)if(i.developer_name!==this.username)if(s.add(i.developer_name),!this.knownSessions.has(i.developer_name))this.knownSessions.set(i.developer_name,i.current_task||"none"),console.log(`
319
319
  ${c.success("\u{1F514}")} ${c.muted("[Live Sync]")} ${c.strong(`@${i.developer_name}`)} has joined the session.
320
320
  `);else{let o=this.knownSessions.get(i.developer_name);i.current_task&&i.current_task!==o&&i.current_task!=="none"&&(this.knownSessions.set(i.developer_name,i.current_task),console.log(` ${c.accent("\u27F3")} ${c.muted("[Activity]")} ${c.strong(`@${i.developer_name}`)} is now: "${c.secondary(i.current_task)}"
321
321
  `))}for(let i of this.knownSessions.keys())s.has(i)||(this.knownSessions.delete(i),console.log(`
322
322
  ${c.warning("\u{1F44B}")} ${c.muted("[Live Sync]")} ${c.strong(`@${i}`)} has left the session.
323
323
  `));let r=new Set;for(let i of t)r.add(i.file_path),this.knownLocks.has(i.file_path)||(this.knownLocks.set(i.file_path,i.locked_by),i.locked_by!==this.username&&console.log(` ${c.error("\u{1F512}")} ${c.muted("[File Locked]")} ${c.strong(`@${i.locked_by}`)} locked ${c.highlight(i.file_path)}`));for(let i of this.knownLocks.keys())if(!r.has(i)){let o=this.knownLocks.get(i);this.knownLocks.delete(i),o!==this.username&&console.log(` ${c.success("\u{1F513}")} ${c.muted("[File Unlocked]")} ${c.strong(`@${o}`)} released lock on ${c.highlight(i)}`)}}renderMessageBox(e,t){let s=Math.min(process.stdout.columns-4,80),r=c.border("\u250C"+"\u2500".repeat(s-2)+"\u2510"),i=c.border("\u2514"+"\u2500".repeat(s-2)+"\u2518"),o=` MESSAGE FROM @${e.toUpperCase()} `,a=Math.max(0,Math.floor((s-2-o.length)/2)),l=c.border("\u2502")+" ".repeat(a)+c.strong(o)+" ".repeat(s-2-o.length-a)+c.border("\u2502"),u=t.replace(/\n/g," "),d=Math.max(0,s-8-u.length),f=c.border("\u2502")+` "${c.secondary(u)}"`+" ".repeat(d)+c.border("\u2502");console.log(`
324
324
  `+r),console.log(l),console.log(f),console.log(i+`
325
- `)}registerCleanups(){this.signalHandler||(this.signalHandler=()=>{this.shutdown()},process.on("SIGTERM",this.signalHandler),process.once("beforeExit",this.signalHandler))}loadSupabaseConfig(){let e=Ye.join(this.workingDir,".env");if(ge.existsSync(e))try{let s=ge.readFileSync(e,"utf-8").split(`
326
- `);for(let r of s){let i=r.split("=");if(i.length>=2){let o=i[0].trim(),a=i.slice(1).join("=").trim().replace(/^['"]|['"]$/g,"");o==="SUPABASE_URL"||o==="VITE_SUPABASE_URL"?this.supabaseUrl=a:(o==="SUPABASE_KEY"||o==="SUPABASE_ANON_KEY"||o==="VITE_SUPABASE_ANON_KEY")&&(this.supabaseKey=a)}}}catch{}if(!this.supabaseUrl||!this.supabaseKey){let t="aHR0cHM6Ly93dXVtYXptcGp6dHZ4a3l3Y3Rvci5zdXBhYmFzZS5jbw==",s="c2JfcHVibGlzaGFibGVfVmxmNEtCUzdsaTRjaGFWNE04d19xQV9fbnJuczh1WQ==";this.supabaseUrl=Buffer.from(t,"base64").toString("utf-8"),this.supabaseKey=Buffer.from(s,"base64").toString("utf-8")}this.isConfigured=!!(this.supabaseUrl&&this.supabaseKey),this.isConfigured&&this.syncLlmConfig()}syncLlmConfig(){let e=Ye.join(fr.homedir(),".hablas","config.json");if(ge.existsSync(e))try{let t=JSON.parse(ge.readFileSync(e,"utf-8"));!this.config.apiUrl&&t.apiUrl&&(this.config.apiUrl=t.apiUrl,this.config.apiKey=t.apiKey,this.config.provider=t.provider)}catch{}}getProjectIdentifier(){let e="";try{let{execSync:t}=require("child_process"),s=t("git config --get remote.origin.url",{cwd:this.workingDir,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(s){let r=s.match(/[:/]([^/]+\/[^/.]+)(\.git)?$/);r&&r[1]&&(e=r[1].toLowerCase())}}catch{}if(!e)try{let t=Ye.join(this.workingDir,"package.json");if(ge.existsSync(t)){let s=JSON.parse(ge.readFileSync(t,"utf-8"));s.name&&(e=s.name.toLowerCase())}}catch{}return e||(e=Ye.basename(this.workingDir).toLowerCase()),e.replace(/\s+/g,"")}}});async function Zt(n){try{if(!oa.existsSync(n))return;oa.existsSync(is)||await vt.mkdir(is,{recursive:!0});let e=await vt.readFile(n,"utf-8"),t=An.basename(n),s=Date.now(),r=`${t}.${s}.bak`,i=An.join(is,r);await vt.writeFile(i,e,"utf-8");let a=(await vt.readdir(is)).filter(l=>l.startsWith(`${t}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>qf)for(let l of a.slice(qf))await vt.unlink(An.join(is,l))}catch{}}var vt,oa,An,Kf,is,qf,Wf=L(()=>{"use strict";vt=O(require("fs/promises")),oa=O(require("fs")),An=O(require("path")),Kf=O(require("os")),is=An.join(Kf.homedir(),".hablas","backup"),qf=10});function Vf(n){let e=m=>Ht.resolve(n,m);return[{name:"read_file",description:"Read the FULL content of a file with line numbers (complete read, no truncation by default per user requirement for 1000/2000+ line files like architecture docs). Use start_line/end_line ONLY if you explicitly need a specific section. Never re-read the same path this turn \u2014 use previous tool observations from history.",safety:"safe",parameters:{path:{type:"string",description:"File path to read",required:!0},start_line:{type:"number",description:"Starting line number (1-based, optional)",required:!1},end_line:{type:"number",description:"Ending line number (inclusive, optional)",required:!1}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[read_file]: path is required"};let p=e(m.path),x=(await ae.readFile(p,"utf-8")).split(`
325
+ `)}registerCleanups(){this.signalHandler||(this.signalHandler=()=>{this.shutdown()},process.on("SIGTERM",this.signalHandler),process.once("beforeExit",this.signalHandler))}loadSupabaseConfig(){let e=Je.join(this.workingDir,".env");if(ye.existsSync(e))try{let s=ye.readFileSync(e,"utf-8").split(`
326
+ `);for(let r of s){let i=r.split("=");if(i.length>=2){let o=i[0].trim(),a=i.slice(1).join("=").trim().replace(/^['"]|['"]$/g,"");o==="SUPABASE_URL"||o==="VITE_SUPABASE_URL"?this.supabaseUrl=a:(o==="SUPABASE_KEY"||o==="SUPABASE_ANON_KEY"||o==="VITE_SUPABASE_ANON_KEY")&&(this.supabaseKey=a)}}}catch{}if(!this.supabaseUrl||!this.supabaseKey){let t="aHR0cHM6Ly93dXVtYXptcGp6dHZ4a3l3Y3Rvci5zdXBhYmFzZS5jbw==",s="c2JfcHVibGlzaGFibGVfVmxmNEtCUzdsaTRjaGFWNE04d19xQV9fbnJuczh1WQ==";this.supabaseUrl=Buffer.from(t,"base64").toString("utf-8"),this.supabaseKey=Buffer.from(s,"base64").toString("utf-8")}this.isConfigured=!!(this.supabaseUrl&&this.supabaseKey),this.isConfigured&&this.syncLlmConfig()}syncLlmConfig(){let e=Je.join(hr.homedir(),".hablas","config.json");if(ye.existsSync(e))try{let t=JSON.parse(ye.readFileSync(e,"utf-8"));!this.config.apiUrl&&t.apiUrl&&(this.config.apiUrl=t.apiUrl,this.config.apiKey=t.apiKey,this.config.provider=t.provider)}catch{}}getProjectIdentifier(){let e="";try{let{execSync:t}=require("child_process"),s=t("git config --get remote.origin.url",{cwd:this.workingDir,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(s){let r=s.match(/[:/]([^/]+\/[^/.]+)(\.git)?$/);r&&r[1]&&(e=r[1].toLowerCase())}}catch{}if(!e)try{let t=Je.join(this.workingDir,"package.json");if(ye.existsSync(t)){let s=JSON.parse(ye.readFileSync(t,"utf-8"));s.name&&(e=s.name.toLowerCase())}}catch{}return e||(e=Je.basename(this.workingDir).toLowerCase()),e.replace(/\s+/g,"")}}});async function en(n){try{if(!ca.existsSync(n))return;ca.existsSync(os)||await bt.mkdir(os,{recursive:!0});let e=await bt.readFile(n,"utf-8"),t=$n.basename(n),s=Date.now(),r=`${t}.${s}.bak`,i=$n.join(os,r);await bt.writeFile(i,e,"utf-8");let a=(await bt.readdir(os)).filter(l=>l.startsWith(`${t}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>zf)for(let l of a.slice(zf))await bt.unlink($n.join(os,l))}catch{}}var bt,ca,$n,Yf,os,zf,Jf=L(()=>{"use strict";bt=O(require("fs/promises")),ca=O(require("fs")),$n=O(require("path")),Yf=O(require("os")),os=$n.join(Yf.homedir(),".hablas","backup"),zf=10});function Qf(n){let e=m=>Ht.resolve(n,m);return[{name:"read_file",description:"Read the FULL content of a file with line numbers (complete read, no truncation by default per user requirement for 1000/2000+ line files like architecture docs). Use start_line/end_line ONLY if you explicitly need a specific section. Never re-read the same path this turn \u2014 use previous tool observations from history.",safety:"safe",parameters:{path:{type:"string",description:"File path to read",required:!0},start_line:{type:"number",description:"Starting line number (1-based, optional)",required:!1},end_line:{type:"number",description:"Ending line number (inclusive, optional)",required:!1}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[read_file]: path is required"};let p=e(m.path),x=(await ae.readFile(p,"utf-8")).split(`
327
327
  `),w=x.length,$=m.start_line?Math.max(1,m.start_line):1,A=m.end_line?Math.min(w,m.end_line):w,y=x.slice($-1,A),v=String(A).length,b=y.map((T,I)=>`${String($+I).padStart(v," ")} | ${T}`),S=`[${m.path} \u2014 lines ${$}-${A} of ${w}]`,_=A<w?`
328
328
  ... [Partial read. Total lines: ${w}.]`:"";return{success:!0,output:`${S}
329
329
  ${b.join(`
330
- `)}${_}`}}catch(p){return{success:!1,output:"",error:`[read_file]: ${p.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(m.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let p=e(m.path);return aa.existsSync(p)&&await Zt(p),await ae.mkdir(Ht.dirname(p),{recursive:!0}),await ae.writeFile(p,m.content,"utf-8"),{success:!0,output:`Written: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[write_file]: ${p.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!m.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let p=e(m.path),g=await ae.readFile(p,"utf-8"),x=m.old_content,w=m.new_content,$=Gf(g,x);if($===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if($>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${$} locations in the file. Provide more surrounding context to be specific.`};await Zt(p);let A=g.replace(x,w);await ae.writeFile(p,A,"utf-8");let y=Gs(m.path,g,A);return{success:!0,output:`Edited: ${m.path}
330
+ `)}${_}`}}catch(p){return{success:!1,output:"",error:`[read_file]: ${p.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(m.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let p=e(m.path);return ua.existsSync(p)&&await en(p),await ae.mkdir(Ht.dirname(p),{recursive:!0}),await ae.writeFile(p,m.content,"utf-8"),{success:!0,output:`Written: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[write_file]: ${p.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!m.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let p=e(m.path),g=await ae.readFile(p,"utf-8"),x=m.old_content,w=m.new_content,$=Xf(g,x);if($===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if($>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${$} locations in the file. Provide more surrounding context to be specific.`};await en(p);let A=g.replace(x,w);await ae.writeFile(p,A,"utf-8");let y=zs(m.path,g,A);return{success:!0,output:`Edited: ${m.path}
331
331
  ${y}`}}catch(p){return{success:!1,output:"",error:`[edit_file]: ${p.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!m.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!m.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(m.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let p=e(m.path),g=await ae.readFile(p,"utf-8"),x=g.split(`
332
- `),w=x.length,$=m.start_line,A=m.end_line;if($<1||$>w)return{success:!1,output:"",error:`[patch_file]: start_line ${$} is out of range (file has ${w} lines)`};if(A<$||A>w)return{success:!1,output:"",error:`[patch_file]: end_line ${A} is out of range (start_line=${$}, total=${w})`};await Zt(p);let y=x.slice(0,$-1),v=x.slice(A),b=m.new_content.split(`
332
+ `),w=x.length,$=m.start_line,A=m.end_line;if($<1||$>w)return{success:!1,output:"",error:`[patch_file]: start_line ${$} is out of range (file has ${w} lines)`};if(A<$||A>w)return{success:!1,output:"",error:`[patch_file]: end_line ${A} is out of range (start_line=${$}, total=${w})`};await en(p);let y=x.slice(0,$-1),v=x.slice(A),b=m.new_content.split(`
333
333
  `),S=[...y,...b,...v].join(`
334
- `);await ae.writeFile(p,S,"utf-8");let _=Gs(m.path,g,S),T=A-$+1,I=b.length;return{success:!0,output:`Patched: ${m.path} (replaced ${T} lines with ${I})
335
- ${_}`}}catch(p){return{success:!1,output:"",error:`[patch_file]: ${p.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!m.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(m.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let p=e(m.path),g=await ae.readFile(p,"utf-8"),x=m.search,w=m.replace,$=m.is_regex;await Zt(p);let A,y;if($){let v=new RegExp(x,"g");y=(g.match(v)||[]).length,A=g.replace(v,w)}else y=Gf(g,x),A=g.split(x).join(w);return y===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await ae.writeFile(p,A,"utf-8"),{success:!0,output:`Replaced ${y} occurrence(s) in ${m.path}`})}catch(p){return{success:!1,output:"",error:`[search_and_replace]: ${p.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(m.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let p=e(m.path);return await ae.mkdir(Ht.dirname(p),{recursive:!0}),aa.existsSync(p)&&await Zt(p),await ae.appendFile(p,m.content,"utf-8"),{success:!0,output:`Appended to: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[append_to_file]: ${p.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let p=e(m.path);return await Zt(p),await ae.unlink(p),{success:!0,output:`Deleted: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[delete_file]: ${p.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async m=>{try{if(!m.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!m.to)return{success:!1,output:"",error:"[move_file]: to is required"};let p=e(m.from),g=e(m.to);return await ae.mkdir(Ht.dirname(g),{recursive:!0}),await ae.rename(p,g),{success:!0,output:`Moved: ${m.from} \u2192 ${m.to}`}}catch(p){return{success:!1,output:"",error:`[move_file]: ${p.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let p=e(m.path);return await ae.mkdir(p,{recursive:!0}),{success:!0,output:`Created directory: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[create_dir]: ${p.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async m=>{try{let p=e(m.path||"."),g=m.depth||3;return{success:!0,output:await zf(p,"",g,0)||"(empty directory)"}}catch(p){return{success:!1,output:"",error:`[list_dir]: ${p.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let p=e(m.path),g=await ae.stat(p);return{success:!0,output:[`Path: ${m.path}`,`Size: ${Cx(g.size)}`,`Type: ${g.isDirectory()?"directory":"file"}`,`Modified: ${g.mtime.toISOString()}`,`Created: ${g.birthtime.toISOString()}`].join(`
336
- `)}}catch(p){return{success:!1,output:"",error:`[get_file_info]: ${p.message}`}}}}]}function Gf(n,e){let t=0,s=0;for(;;){let r=n.indexOf(e,s);if(r===-1)break;t++,s=r+e.length}return t}async function zf(n,e,t,s){if(s>=t)return"";let i=(await ae.readdir(n,{withFileTypes:!0})).filter(a=>!$x.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],u=a===i.length-1,d=u?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${d}${f} ${l.name}
337
- `,l.isDirectory()){let h=e+(u?" ":"\u2502 ");o+=await zf(Ht.join(n,l.name),h,t,s+1)}}return o}function Cx(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var ae,aa,Ht,$x,Yf=L(()=>{"use strict";ae=O(require("fs/promises")),aa=O(require("fs")),Ht=O(require("path"));so();Wf();$x=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"])});var Jf,pr,Xf=L(()=>{"use strict";Jf=require("child_process"),pr=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,t){let s=`bg_${this.nextId++}`,r=t?.timeout||this.config.defaultTimeout,i=(0,Jf.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...t?.env}}),o={id:s,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
334
+ `);await ae.writeFile(p,S,"utf-8");let _=zs(m.path,g,S),T=A-$+1,I=b.length;return{success:!0,output:`Patched: ${m.path} (replaced ${T} lines with ${I})
335
+ ${_}`}}catch(p){return{success:!1,output:"",error:`[patch_file]: ${p.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!m.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(m.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let p=e(m.path),g=await ae.readFile(p,"utf-8"),x=m.search,w=m.replace,$=m.is_regex;await en(p);let A,y;if($){let v=new RegExp(x,"g");y=(g.match(v)||[]).length,A=g.replace(v,w)}else y=Xf(g,x),A=g.split(x).join(w);return y===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await ae.writeFile(p,A,"utf-8"),{success:!0,output:`Replaced ${y} occurrence(s) in ${m.path}`})}catch(p){return{success:!1,output:"",error:`[search_and_replace]: ${p.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(m.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let p=e(m.path);return await ae.mkdir(Ht.dirname(p),{recursive:!0}),ua.existsSync(p)&&await en(p),await ae.appendFile(p,m.content,"utf-8"),{success:!0,output:`Appended to: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[append_to_file]: ${p.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let p=e(m.path);return await en(p),await ae.unlink(p),{success:!0,output:`Deleted: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[delete_file]: ${p.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async m=>{try{if(!m.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!m.to)return{success:!1,output:"",error:"[move_file]: to is required"};let p=e(m.from),g=e(m.to);return await ae.mkdir(Ht.dirname(g),{recursive:!0}),await ae.rename(p,g),{success:!0,output:`Moved: ${m.from} \u2192 ${m.to}`}}catch(p){return{success:!1,output:"",error:`[move_file]: ${p.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let p=e(m.path);return await ae.mkdir(p,{recursive:!0}),{success:!0,output:`Created directory: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[create_dir]: ${p.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async m=>{try{let p=e(m.path||"."),g=m.depth||3;return{success:!0,output:await Zf(p,"",g,0)||"(empty directory)"}}catch(p){return{success:!1,output:"",error:`[list_dir]: ${p.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let p=e(m.path),g=await ae.stat(p);return{success:!0,output:[`Path: ${m.path}`,`Size: ${Px(g.size)}`,`Type: ${g.isDirectory()?"directory":"file"}`,`Modified: ${g.mtime.toISOString()}`,`Created: ${g.birthtime.toISOString()}`].join(`
336
+ `)}}catch(p){return{success:!1,output:"",error:`[get_file_info]: ${p.message}`}}}}]}function Xf(n,e){let t=0,s=0;for(;;){let r=n.indexOf(e,s);if(r===-1)break;t++,s=r+e.length}return t}async function Zf(n,e,t,s){if(s>=t)return"";let i=(await ae.readdir(n,{withFileTypes:!0})).filter(a=>!Ox.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],u=a===i.length-1,d=u?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${d}${f} ${l.name}
337
+ `,l.isDirectory()){let h=e+(u?" ":"\u2502 ");o+=await Zf(Ht.join(n,l.name),h,t,s+1)}}return o}function Px(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var ae,ua,Ht,Ox,ep=L(()=>{"use strict";ae=O(require("fs/promises")),ua=O(require("fs")),Ht=O(require("path"));oo();Jf();Ox=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"])});var tp,mr,np=L(()=>{"use strict";tp=require("child_process"),mr=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,t){let s=`bg_${this.nextId++}`,r=t?.timeout||this.config.defaultTimeout,i=(0,tp.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...t?.env}}),o={id:s,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
338
338
  Error: ${a.message}`}),r>0&&setTimeout(()=>{o.status==="running"&&(this.kill(s),o.status="timeout",o.stderr+=`
339
339
  Process timed out after ${r}ms`)},r),this.processes.set(s,o),s}readOutput(e,t){let s=this.processes.get(e);if(!s)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let r=t?.type||"both",i="";return(r==="stdout"||r==="both")&&(i+=s.stdout),(r==="stderr"||r==="both")&&(i&&(i+=`
340
340
  `),i+=s.stderr),t?.lastLines&&(i=i.split(`
341
341
  `).slice(-t.lastLines).join(`
342
- `)),{success:!0,output:i,status:s.status}}kill(e){let t=this.processes.get(e);if(!t)return!1;if(t.process.pid)try{process.kill(-t.process.pid,"SIGTERM")}catch{try{process.kill(t.process.pid,"SIGTERM")}catch{}}return t.status="killed",!0}killAll(){let e=0;for(let t of this.processes.keys())this.kill(t)&&e++;return e}listProcesses(){let e=[];for(let[t,s]of this.processes){let r=Date.now()-s.startTime,i=this.formatUptime(r);e.push({id:t,command:s.command,status:s.status,pid:s.pid,startTime:s.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[t,s]of this.processes)(s.status==="finished"||s.status==="killed"||s.status==="timeout")&&(this.processes.delete(t),e++);return e}formatUptime(e){let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let s=Math.floor(t/60);return s<60?`${s}m ${t%60}s`:`${Math.floor(s/60)}h ${s%60}m`}}});function Qf(n){return la||(la=new pr({workingDir:n})),la}function ep(n,e){return{name:"run_command",description:"Execute any shell command and return output. Set run_in_background=true for long-running processes (servers, watchers). Use bash_output to read output later.",safety:"confirm",parameters:{command:{type:"string",description:"Shell command to execute",required:!0},run_in_background:{type:"boolean",description:"Run in background for long processes (default: false)",required:!1},timeout:{type:"number",description:"Timeout in ms (default: 120000)",required:!1}},execute:async t=>{let s=t.command,r=t.run_in_background===!0,i=t.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...Ex,...o];if(a.length>0){for(let l of a)if(s.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(r){let l=Qf(n).start(s,{timeout:i});return{success:!0,output:`Background process started: ${l}
343
- PID: ${Qf(n).getProcess(l)?.pid}
344
- Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let u=(0,Zf.exec)(s,{cwd:n,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",h=>{d+=h}),u.stderr?.on("data",h=>{f+=h}),u.on("close",h=>{l(h===0?{success:!0,output:d||"(no output)"}:{success:!1,output:d,error:f||`Exit code: ${h}`})}),u.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var Zf,Ex,la,tp=L(()=>{"use strict";Zf=require("child_process");Xf();Ex=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],la=null});function np(n){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let t=e.query,s=Bt.resolve(n,e.path||"."),r=new RegExp(t,"gi"),i=[];if(await sp(s,r,i,n),i.length===0)return{success:!0,output:`No matches found for: "${t}"`};let o=i.slice(0,50).join(`
342
+ `)),{success:!0,output:i,status:s.status}}kill(e){let t=this.processes.get(e);if(!t)return!1;if(t.process.pid)try{process.kill(-t.process.pid,"SIGTERM")}catch{try{process.kill(t.process.pid,"SIGTERM")}catch{}}return t.status="killed",!0}killAll(){let e=0;for(let t of this.processes.keys())this.kill(t)&&e++;return e}listProcesses(){let e=[];for(let[t,s]of this.processes){let r=Date.now()-s.startTime,i=this.formatUptime(r);e.push({id:t,command:s.command,status:s.status,pid:s.pid,startTime:s.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[t,s]of this.processes)(s.status==="finished"||s.status==="killed"||s.status==="timeout")&&(this.processes.delete(t),e++);return e}formatUptime(e){let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let s=Math.floor(t/60);return s<60?`${s}m ${t%60}s`:`${Math.floor(s/60)}h ${s%60}m`}}});function sp(n){return da||(da=new mr({workingDir:n})),da}function ip(n,e){return{name:"run_command",description:"Execute any shell command and return output. Set run_in_background=true for long-running processes (servers, watchers). Use bash_output to read output later.",safety:"confirm",parameters:{command:{type:"string",description:"Shell command to execute",required:!0},run_in_background:{type:"boolean",description:"Run in background for long processes (default: false)",required:!1},timeout:{type:"number",description:"Timeout in ms (default: 120000)",required:!1}},execute:async t=>{let s=t.command,r=t.run_in_background===!0,i=t.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...Mx,...o];if(a.length>0){for(let l of a)if(s.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(r){let l=sp(n).start(s,{timeout:i});return{success:!0,output:`Background process started: ${l}
343
+ PID: ${sp(n).getProcess(l)?.pid}
344
+ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let u=(0,rp.exec)(s,{cwd:n,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",h=>{d+=h}),u.stderr?.on("data",h=>{f+=h}),u.on("close",h=>{l(h===0?{success:!0,output:d||"(no output)"}:{success:!1,output:d,error:f||`Exit code: ${h}`})}),u.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var rp,Mx,da,op=L(()=>{"use strict";rp=require("child_process");np();Mx=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],da=null});function ap(n){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let t=e.query,s=Bt.resolve(n,e.path||"."),r=new RegExp(t,"gi"),i=[];if(await lp(s,r,i,n),i.length===0)return{success:!0,output:`No matches found for: "${t}"`};let o=i.slice(0,50).join(`
345
345
  `),a=i.length>50?`
346
- ... and ${i.length-50} more matches`:"";return{success:!0,output:o+a}}catch(t){return{success:!1,output:"",error:`Search failed: ${t.message}`}}}}}async function sp(n,e,t,s){let r=await hr.readdir(n,{withFileTypes:!0});for(let i of r){if(Tx.has(i.name)||i.name.startsWith("."))continue;let o=Bt.join(n,i.name);if(i.isDirectory())await sp(o,e,t,s);else if(Rx.has(Bt.extname(i.name)))try{let l=(await hr.readFile(o,"utf-8")).split(`
347
- `),u=Bt.relative(s,o);for(let d=0;d<l.length;d++)e.test(l[d])&&(t.push(`${u}:${d+1}: ${l[d].trim()}`),e.lastIndex=0)}catch{}}}var hr,Bt,Tx,Rx,rp=L(()=>{"use strict";hr=O(require("fs/promises")),Bt=O(require("path")),Tx=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Rx=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"])});function Ox(n){let e=[],t=Ut.join(n,"tsconfig.json");if(!Je.existsSync(t))return e;try{(0,ca.execSync)("npx tsc --noEmit 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(s){let r=s,o=(r.stdout||r.message||"").split(`
348
- `);for(let a of o){let l=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);l&&e.push({file:l[1],line:parseInt(l[2],10),severity:l[3]==="error"?"error":"warning",message:l[4].trim(),source:"typescript"})}}return e}function Px(n){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(s=>Je.existsSync(Ut.join(n,s))))return e;try{(0,ca.execSync)("npx eslint . --format json 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(s){let i=s.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:Ut.relative(n,a.filePath),line:l.line||0,severity:l.severity===2?"error":"warning",message:`${l.message} (${l.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
349
- `);for(let a of o){let l=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);l&&e.push({file:"unknown",line:parseInt(l[1],10),severity:l[3]==="error"?"error":"warning",message:`${l[4]} (${l[5]})`,source:"eslint"})}}}return e}function Mx(n,e,t){let s;try{s=Je.readFileSync(n,"utf-8")}catch{return}let r=Ut.relative(e,n),i=s.split(`
350
- `);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&t.push({file:r,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&t.push({file:r,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&t.push({file:r,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&t.push({file:r,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function Ix(n){let e=[],t=[".ts",".tsx",".js",".jsx"];function s(r,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=Je.readdirSync(r)}catch{return}for(let l of a){if(o.includes(l))continue;let u=Ut.join(r,l),d;try{d=Je.statSync(u)}catch{continue}d.isDirectory()?s(u,i+1):t.some(f=>l.endsWith(f))&&Mx(u,n,e)}}return s(n),e.slice(0,20)}function Dx(n){let e=[];e.push(...Ox(n)),e.push(...Px(n)),e.push(...Ix(n));let t={error:0,warning:1,info:2};return e.sort((s,r)=>t[s.severity]-t[r.severity]),e}function ip(n){if(n.length===0)return" \u2713 No bugs detected";let e=[],t=n.filter(i=>i.severity==="error").length,s=n.filter(i=>i.severity==="warning").length,r=n.filter(i=>i.severity==="info").length;e.push(` Found ${n.length} issue${n.length>1?"s":""}: ${t} errors, ${s} warnings, ${r} info`),e.push("");for(let i of n.slice(0,15)){let o=i.severity==="error"?"\u2717":i.severity==="warning"?"\u26A0":"\u2139",a=i.line>0?`:${i.line}`:"";e.push(` ${o} ${i.file}${a}`),e.push(` ${i.message}`),i.suggestedFix&&e.push(` \u2192 ${i.suggestedFix}`)}return n.length>15&&e.push(` ... and ${n.length-15} more`),e.join(`
351
- `)}function Lx(n,e){let t=[];for(let s of n)if(s.source==="pattern"&&s.message.includes("console.log")){let r=Ut.join(e,s.file);try{let o=Je.readFileSync(r,"utf-8").split(`
352
- `);s.line>0&&s.line<=o.length&&(o[s.line-1]="// "+o[s.line-1],Je.writeFileSync(r,o.join(`
353
- `),"utf-8"),t.push({bug:s,fixed:!0,action:"Commented out console.log"}))}catch{t.push({bug:s,fixed:!1,action:"Failed to read/write file"})}}else t.push({bug:s,fixed:!1,action:"Requires manual fix or LLM assistance"});return t}function op(n){return{name:"detect_bugs",description:"Scan the project for bugs using TypeScript checking, ESLint, and pattern analysis. Returns a report of found issues.",safety:"safe",parameters:{path:{type:"string",description:"Project path to scan (default: current directory)",required:!1},fix:{type:"string",description:'Set to "true" to auto-fix simple issues',required:!1}},execute:async e=>{let t=e.path||n,s=e.fix==="true"||e.fix===!0;try{let r=Dx(t);if(s&&r.length>0){let o=Lx(r,t).filter(l=>l.fixed).length;return{success:!0,output:`${ip(r)}
354
-
355
- Auto-fixed: ${o}/${r.length} issues`}}return{success:!0,output:ip(r)}}catch(r){return{success:!1,output:"",error:`Bug detection failed: ${r instanceof Error?r.message:String(r)}`}}}}}var ca,Je,Ut,ap=L(()=>{"use strict";ca=require("child_process"),Je=O(require("fs")),Ut=O(require("path"))});function Nx(n){let e=n;return e=e.replace(/<(script|style|nav|footer|header|aside|iframe|noscript)[^>]*>[\s\S]*?<\/\1>/gi,""),e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/<\/(p|div|section|article|li|tr|h[1-6])>/gi,`
346
+ ... and ${i.length-50} more matches`:"";return{success:!0,output:o+a}}catch(t){return{success:!1,output:"",error:`Search failed: ${t.message}`}}}}}async function lp(n,e,t,s){let r=await gr.readdir(n,{withFileTypes:!0});for(let i of r){if(Ix.has(i.name)||i.name.startsWith("."))continue;let o=Bt.join(n,i.name);if(i.isDirectory())await lp(o,e,t,s);else if(Dx.has(Bt.extname(i.name)))try{let l=(await gr.readFile(o,"utf-8")).split(`
347
+ `),u=Bt.relative(s,o);for(let d=0;d<l.length;d++)e.test(l[d])&&(t.push(`${u}:${d+1}: ${l[d].trim()}`),e.lastIndex=0)}catch{}}}var gr,Bt,Ix,Dx,cp=L(()=>{"use strict";gr=O(require("fs/promises")),Bt=O(require("path")),Ix=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Dx=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"])});function Lx(n){let e=[],t=Ut.join(n,"tsconfig.json");if(!Xe.existsSync(t))return e;try{(0,fa.execSync)("npx tsc --noEmit 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(s){let r=s,o=(r.stdout||r.message||"").split(`
348
+ `);for(let a of o){let l=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);l&&e.push({file:l[1],line:parseInt(l[2],10),severity:l[3]==="error"?"error":"warning",message:l[4].trim(),source:"typescript"})}}return e}function Nx(n){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(s=>Xe.existsSync(Ut.join(n,s))))return e;try{(0,fa.execSync)("npx eslint . --format json 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(s){let i=s.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:Ut.relative(n,a.filePath),line:l.line||0,severity:l.severity===2?"error":"warning",message:`${l.message} (${l.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
349
+ `);for(let a of o){let l=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);l&&e.push({file:"unknown",line:parseInt(l[1],10),severity:l[3]==="error"?"error":"warning",message:`${l[4]} (${l[5]})`,source:"eslint"})}}}return e}function Fx(n,e,t){let s;try{s=Xe.readFileSync(n,"utf-8")}catch{return}let r=Ut.relative(e,n),i=s.split(`
350
+ `);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&t.push({file:r,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&t.push({file:r,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&t.push({file:r,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&t.push({file:r,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function jx(n){let e=[],t=[".ts",".tsx",".js",".jsx"];function s(r,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=Xe.readdirSync(r)}catch{return}for(let l of a){if(o.includes(l))continue;let u=Ut.join(r,l),d;try{d=Xe.statSync(u)}catch{continue}d.isDirectory()?s(u,i+1):t.some(f=>l.endsWith(f))&&Fx(u,n,e)}}return s(n),e.slice(0,20)}function Hx(n){let e=[];e.push(...Lx(n)),e.push(...Nx(n)),e.push(...jx(n));let t={error:0,warning:1,info:2};return e.sort((s,r)=>t[s.severity]-t[r.severity]),e}function up(n){if(n.length===0)return" \u2713 No bugs detected";let e=[],t=n.filter(i=>i.severity==="error").length,s=n.filter(i=>i.severity==="warning").length,r=n.filter(i=>i.severity==="info").length;e.push(` Found ${n.length} issue${n.length>1?"s":""}: ${t} errors, ${s} warnings, ${r} info`),e.push("");for(let i of n.slice(0,15)){let o=i.severity==="error"?"\u2717":i.severity==="warning"?"\u26A0":"\u2139",a=i.line>0?`:${i.line}`:"";e.push(` ${o} ${i.file}${a}`),e.push(` ${i.message}`),i.suggestedFix&&e.push(` \u2192 ${i.suggestedFix}`)}return n.length>15&&e.push(` ... and ${n.length-15} more`),e.join(`
351
+ `)}function Bx(n,e){let t=[];for(let s of n)if(s.source==="pattern"&&s.message.includes("console.log")){let r=Ut.join(e,s.file);try{let o=Xe.readFileSync(r,"utf-8").split(`
352
+ `);s.line>0&&s.line<=o.length&&(o[s.line-1]="// "+o[s.line-1],Xe.writeFileSync(r,o.join(`
353
+ `),"utf-8"),t.push({bug:s,fixed:!0,action:"Commented out console.log"}))}catch{t.push({bug:s,fixed:!1,action:"Failed to read/write file"})}}else t.push({bug:s,fixed:!1,action:"Requires manual fix or LLM assistance"});return t}function dp(n){return{name:"detect_bugs",description:"Scan the project for bugs using TypeScript checking, ESLint, and pattern analysis. Returns a report of found issues.",safety:"safe",parameters:{path:{type:"string",description:"Project path to scan (default: current directory)",required:!1},fix:{type:"string",description:'Set to "true" to auto-fix simple issues',required:!1}},execute:async e=>{let t=e.path||n,s=e.fix==="true"||e.fix===!0;try{let r=Hx(t);if(s&&r.length>0){let o=Bx(r,t).filter(l=>l.fixed).length;return{success:!0,output:`${up(r)}
354
+
355
+ Auto-fixed: ${o}/${r.length} issues`}}return{success:!0,output:up(r)}}catch(r){return{success:!1,output:"",error:`Bug detection failed: ${r instanceof Error?r.message:String(r)}`}}}}}var fa,Xe,Ut,fp=L(()=>{"use strict";fa=require("child_process"),Xe=O(require("fs")),Ut=O(require("path"))});function qx(n){let e=n;return e=e.replace(/<(script|style|nav|footer|header|aside|iframe|noscript)[^>]*>[\s\S]*?<\/\1>/gi,""),e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/<\/(p|div|section|article|li|tr|h[1-6])>/gi,`
356
356
  `),e=e.replace(/<(br|hr)\s*\/?>/gi,`
357
357
  `),e=e.replace(/<\/?(ul|ol)>/gi,`
358
358
  `),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(t,s,r)=>`
359
359
  ${"#".repeat(parseInt(s))} ${r.replace(/<[^>]+>/g,"").trim()}
360
360
  `),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(t,s,r)=>{let i=r.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${s})`:s}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(t,s)=>"\n```\n"+s.replace(/<[^>]+>/g,"").trim()+"\n```\n"),e=e.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi,"`$1`"),e=e.replace(/<(b|strong)[^>]*>([\s\S]*?)<\/\1>/gi,"**$2**"),e=e.replace(/<(i|em)[^>]*>([\s\S]*?)<\/\1>/gi,"*$2*"),e=e.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,"\u2022 $1"),e=e.replace(/<[^>]+>/g,""),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(t,s)=>String.fromCharCode(parseInt(s))).replace(/&[a-z]+;/gi,""),e=e.replace(/[ \t]+/g," "),e=e.replace(/\n{3,}/g,`
361
361
 
362
- `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function jx(n){let e=n.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let t=n.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return t?t[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function Hx(n,e){let t=[],s=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,r,i=new Set;for(;(r=s.exec(n))!==null;){let o=r[1].trim(),a=r[2].replace(/<[^>]+>/g,"").trim();if(!(o.startsWith("#")||o.startsWith("javascript:")||o.startsWith("mailto:"))){try{o=new URL(o,e).href}catch{continue}i.has(o)||(i.add(o),t.push({text:a||o,url:o}))}}return t}async function dp(n){let e=new AbortController,t=setTimeout(()=>e.abort(),cp);try{let s=await fetch(n,{signal:e.signal,headers:{"User-Agent":Fx,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(t),!s.ok)return{html:"",finalUrl:s.url||n,status:s.status};let r=s.headers.get("content-type")||"";if(!r.includes("text/")&&!r.includes("application/xhtml")&&!r.includes("application/json"))return{html:`[Binary content: ${r}]`,finalUrl:s.url||n,status:s.status};let i=s.body?.getReader();if(!i)return{html:"",finalUrl:s.url||n,status:s.status};let o=[],a=0;for(;a<lp;){let{done:d,value:f}=await i.read();if(d)break;o.push(f),a+=f.length}if(a>=lp)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(d=>l.decode(d,{stream:!0})).join("")+l.decode(),finalUrl:s.url||n,status:s.status}}catch(s){clearTimeout(t);let r=s instanceof Error?s:new Error(String(s));throw r.name==="AbortError"?new Error(`Timeout after ${cp/1e3}s`):r}}function fp(){return[{name:"scrape_url",description:"Fetch a web page and extract its readable text content. Returns clean text/markdown without HTML tags. Use this to read documentation, articles, blog posts, or any web page.",safety:"safe",parameters:{url:{type:"string",description:"The URL to scrape (must start with http:// or https://)",required:!0}},execute:async n=>{let e=n.url;if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:t,finalUrl:s,status:r}=await dp(e);if(!t||r>=400)return{success:!1,output:"",error:`HTTP ${r} \u2014 could not fetch ${e}`};let i=jx(t),o=Nx(t);return o.length>up&&(o=o.slice(0,up)+`
362
+ `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function Kx(n){let e=n.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let t=n.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return t?t[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function Wx(n,e){let t=[],s=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,r,i=new Set;for(;(r=s.exec(n))!==null;){let o=r[1].trim(),a=r[2].replace(/<[^>]+>/g,"").trim();if(!(o.startsWith("#")||o.startsWith("javascript:")||o.startsWith("mailto:"))){try{o=new URL(o,e).href}catch{continue}i.has(o)||(i.add(o),t.push({text:a||o,url:o}))}}return t}async function gp(n){let e=new AbortController,t=setTimeout(()=>e.abort(),hp);try{let s=await fetch(n,{signal:e.signal,headers:{"User-Agent":Ux,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(t),!s.ok)return{html:"",finalUrl:s.url||n,status:s.status};let r=s.headers.get("content-type")||"";if(!r.includes("text/")&&!r.includes("application/xhtml")&&!r.includes("application/json"))return{html:`[Binary content: ${r}]`,finalUrl:s.url||n,status:s.status};let i=s.body?.getReader();if(!i)return{html:"",finalUrl:s.url||n,status:s.status};let o=[],a=0;for(;a<pp;){let{done:d,value:f}=await i.read();if(d)break;o.push(f),a+=f.length}if(a>=pp)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(d=>l.decode(d,{stream:!0})).join("")+l.decode(),finalUrl:s.url||n,status:s.status}}catch(s){clearTimeout(t);let r=s instanceof Error?s:new Error(String(s));throw r.name==="AbortError"?new Error(`Timeout after ${hp/1e3}s`):r}}function yp(){return[{name:"scrape_url",description:"Fetch a web page and extract its readable text content. Returns clean text/markdown without HTML tags. Use this to read documentation, articles, blog posts, or any web page.",safety:"safe",parameters:{url:{type:"string",description:"The URL to scrape (must start with http:// or https://)",required:!0}},execute:async n=>{let e=n.url;if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:t,finalUrl:s,status:r}=await gp(e);if(!t||r>=400)return{success:!1,output:"",error:`HTTP ${r} \u2014 could not fetch ${e}`};let i=Kx(t),o=qx(t);return o.length>mp&&(o=o.slice(0,mp)+`
363
363
 
364
364
  [... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${s}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
365
- `)}}catch(t){let s=t instanceof Error?t.message:String(t);return{success:!1,output:"",error:`Failed to scrape ${e}: ${s}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async n=>{let e=n.url,t=n.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:s,finalUrl:r,status:i}=await dp(e);if(!s||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Hx(s,r);if(t&&(o=o.filter(l=>l.url.toLowerCase().includes(t)||l.text.toLowerCase().includes(t))),o.length===0)return{success:!0,output:"No links found"+(t?` matching "${t}"`:"")};let a=o.slice(0,100).map((l,u)=>`${u+1}. [${l.text}](${l.url})`).join(`
365
+ `)}}catch(t){let s=t instanceof Error?t.message:String(t);return{success:!1,output:"",error:`Failed to scrape ${e}: ${s}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async n=>{let e=n.url,t=n.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:s,finalUrl:r,status:i}=await gp(e);if(!s||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Wx(s,r);if(t&&(o=o.filter(l=>l.url.toLowerCase().includes(t)||l.text.toLowerCase().includes(t))),o.length===0)return{success:!0,output:"No links found"+(t?` matching "${t}"`:"")};let a=o.slice(0,100).map((l,u)=>`${u+1}. [${l.text}](${l.url})`).join(`
366
366
  `);return{success:!0,output:`Found ${o.length} links:
367
367
 
368
- ${a}`}}catch(s){let r=s instanceof Error?s.message:String(s);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${r}`}}}}]}var lp,cp,up,Fx,pp=L(()=>{"use strict";lp=2*1024*1024,cp=15e3,up=32e3,Fx="HablasBot/2.0 (+https://hablas.dev)"});function Ux(n){let e=$n.get(n.toLowerCase().trim());return e?Date.now()-e.timestamp>Bx?($n.delete(n.toLowerCase().trim()),null):e.results:null}function qx(n,e){if($n.size>200){let t=$n.keys().next().value;t!==void 0&&$n.delete(t)}$n.set(n.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Kx(n,e){let t=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!t)return null;try{let s=new URLSearchParams({q:n,count:String(Math.min(e,10))}),r=await fetch(`https://api.search.brave.com/res/v1/web/search?${s}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":t},signal:AbortSignal.timeout(1e4)});return r.ok?((await r.json()).web?.results??[]).slice(0,e).map(a=>({title:a.title||"",url:a.url||"",snippet:a.description||"",source:"brave"})):null}catch{return null}}async function Wx(n,e){try{let t=new URLSearchParams({q:n}),s=await fetch(`https://html.duckduckgo.com/html/?${t}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!s.ok)return null;let r=await s.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(r))!==null&&i.length<e;){let l=a[1],u=a[2].replace(/<[^>]+>/g,"").trim(),d=a[3].replace(/<[^>]+>/g,"").trim(),f=l.match(/uddg=([^&]+)/);if(f)try{l=decodeURIComponent(f[1])}catch{}u&&l&&!l.startsWith("/")&&i.push({title:u,url:l,snippet:d,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,u=new Set;for(;(a=l.exec(r))!==null&&i.length<e;){let d=a[1],f=a[2].replace(/<[^>]+>/g,"").trim();f&&f.length>5&&!u.has(d)&&!d.includes("duckduckgo.com")&&(u.add(d),i.push({title:f,url:d,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function Gx(n,e=5){let t=Ux(n);if(t)return t.slice(0,e);let s=[{name:"brave",fn:()=>Kx(n,e)},{name:"duckduckgo",fn:()=>Wx(n,e)}];for(let r of s)try{let i=await r.fn();if(i&&i.length>0)return qx(n,i),i}catch{}return[]}function hp(){return{name:"web_search",description:"Search the web for current information. Returns titles, URLs, and snippets from search results. Use this to find documentation, answers, latest versions, news, or any information not in your training data.",safety:"safe",parameters:{query:{type:"string",description:"The search query",required:!0},max_results:{type:"number",description:"Max results to return (default: 5, max: 10)",required:!1}},execute:async n=>{let e=n.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let t=Math.min(Math.max(1,n.max_results||5),10);try{let s=await Gx(e.trim(),t);if(s.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let r=[`Search results for: "${e}" (${s.length} results, source: ${s[0].source})`,""];for(let i=0;i<s.length;i++){let o=s[i];r.push(`[${i+1}] ${o.title}`),r.push(` ${o.url}`),o.snippet&&r.push(` ${o.snippet}`),r.push("")}return{success:!0,output:r.join(`
369
- `)}}catch(s){return{success:!1,output:"",error:`Search failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Bx,$n,mp=L(()=>{"use strict";Bx=3600*1e3,$n=new Map});function bp(n){let e=n.toString("latin1"),t={},s=[],r=0,i=e.match(/\/Type\s*\/Page\b/g);r=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(t.title=en(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(t.author=en(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(t.subject=en(l[1]));let u=e.match(/\/Creator\s*\(([^)]*)\)/);u&&(t.creator=en(u[1]));let d=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=d.exec(e))!==null;){let m=f[1],p=vp(m);p.trim()&&s.push(p);try{let g=require("zlib"),x=Buffer.from(m,"latin1"),w=g.inflateSync(x).toString("latin1"),$=vp(w);$.trim()&&!s.includes($)&&s.push($)}catch{}}return{text:s.join(`
368
+ ${a}`}}catch(s){let r=s instanceof Error?s.message:String(s);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${r}`}}}}]}var pp,hp,mp,Ux,bp=L(()=>{"use strict";pp=2*1024*1024,hp=15e3,mp=32e3,Ux="HablasBot/2.0 (+https://hablas.dev)"});function Vx(n){let e=Cn.get(n.toLowerCase().trim());return e?Date.now()-e.timestamp>Gx?(Cn.delete(n.toLowerCase().trim()),null):e.results:null}function zx(n,e){if(Cn.size>200){let t=Cn.keys().next().value;t!==void 0&&Cn.delete(t)}Cn.set(n.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Yx(n,e){let t=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!t)return null;try{let s=new URLSearchParams({q:n,count:String(Math.min(e,10))}),r=await fetch(`https://api.search.brave.com/res/v1/web/search?${s}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":t},signal:AbortSignal.timeout(1e4)});return r.ok?((await r.json()).web?.results??[]).slice(0,e).map(a=>({title:a.title||"",url:a.url||"",snippet:a.description||"",source:"brave"})):null}catch{return null}}async function Jx(n,e){try{let t=new URLSearchParams({q:n}),s=await fetch(`https://html.duckduckgo.com/html/?${t}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!s.ok)return null;let r=await s.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(r))!==null&&i.length<e;){let l=a[1],u=a[2].replace(/<[^>]+>/g,"").trim(),d=a[3].replace(/<[^>]+>/g,"").trim(),f=l.match(/uddg=([^&]+)/);if(f)try{l=decodeURIComponent(f[1])}catch{}u&&l&&!l.startsWith("/")&&i.push({title:u,url:l,snippet:d,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,u=new Set;for(;(a=l.exec(r))!==null&&i.length<e;){let d=a[1],f=a[2].replace(/<[^>]+>/g,"").trim();f&&f.length>5&&!u.has(d)&&!d.includes("duckduckgo.com")&&(u.add(d),i.push({title:f,url:d,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function Xx(n,e=5){let t=Vx(n);if(t)return t.slice(0,e);let s=[{name:"brave",fn:()=>Yx(n,e)},{name:"duckduckgo",fn:()=>Jx(n,e)}];for(let r of s)try{let i=await r.fn();if(i&&i.length>0)return zx(n,i),i}catch{}return[]}function vp(){return{name:"web_search",description:"Search the web for current information. Returns titles, URLs, and snippets from search results. Use this to find documentation, answers, latest versions, news, or any information not in your training data.",safety:"safe",parameters:{query:{type:"string",description:"The search query",required:!0},max_results:{type:"number",description:"Max results to return (default: 5, max: 10)",required:!1}},execute:async n=>{let e=n.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let t=Math.min(Math.max(1,n.max_results||5),10);try{let s=await Xx(e.trim(),t);if(s.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let r=[`Search results for: "${e}" (${s.length} results, source: ${s[0].source})`,""];for(let i=0;i<s.length;i++){let o=s[i];r.push(`[${i+1}] ${o.title}`),r.push(` ${o.url}`),o.snippet&&r.push(` ${o.snippet}`),r.push("")}return{success:!0,output:r.join(`
369
+ `)}}catch(s){return{success:!1,output:"",error:`Search failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Gx,Cn,wp=L(()=>{"use strict";Gx=3600*1e3,Cn=new Map});function _p(n){let e=n.toString("latin1"),t={},s=[],r=0,i=e.match(/\/Type\s*\/Page\b/g);r=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(t.title=tn(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(t.author=tn(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(t.subject=tn(l[1]));let u=e.match(/\/Creator\s*\(([^)]*)\)/);u&&(t.creator=tn(u[1]));let d=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=d.exec(e))!==null;){let m=f[1],p=kp(m);p.trim()&&s.push(p);try{let g=require("zlib"),x=Buffer.from(m,"latin1"),w=g.inflateSync(x).toString("latin1"),$=kp(w);$.trim()&&!s.includes($)&&s.push($)}catch{}}return{text:s.join(`
370
370
  `).replace(/\r\n/g,`
371
371
  `).replace(/\n{3,}/g,`
372
372
 
373
- `).trim(),pages:r,metadata:t}}function vp(n){let e=[],t=/\(([^)]*)\)\s*Tj/g,s;for(;(s=t.exec(n))!==null;)e.push(en(s[1]));let r=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(s=r.exec(n))!==null;){let l=s[1].match(/\(([^)]*)\)/g);if(l){let u=l.map(d=>en(d.slice(1,-1))).join("");e.push(u)}}let i=/\(([^)]*)\)\s*'/g;for(;(s=i.exec(n))!==null;)e.push(en(s[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
374
- `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function en(n){return n.replace(/\\n/g,`
375
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(parseInt(t,8)))}function xp(n){let e=t=>wp.resolve(n,t);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async t=>{let s=e(t.path);if(!It.existsSync(s))return{success:!1,output:"",error:`File not found: ${t.path}`};if(!s.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${t.path}`};let r=It.statSync(s);if(r.size>gp)return{success:!1,output:"",error:`File too large: ${(r.size/1024/1024).toFixed(1)}MB (max: ${gp/1024/1024}MB)`};try{let i=It.readFileSync(s),{text:o,pages:a,metadata:l}=bp(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${t.path} (${a} pages)
373
+ `).trim(),pages:r,metadata:t}}function kp(n){let e=[],t=/\(([^)]*)\)\s*Tj/g,s;for(;(s=t.exec(n))!==null;)e.push(tn(s[1]));let r=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(s=r.exec(n))!==null;){let l=s[1].match(/\(([^)]*)\)/g);if(l){let u=l.map(d=>tn(d.slice(1,-1))).join("");e.push(u)}}let i=/\(([^)]*)\)\s*'/g;for(;(s=i.exec(n))!==null;)e.push(tn(s[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
374
+ `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function tn(n){return n.replace(/\\n/g,`
375
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(parseInt(t,8)))}function $p(n){let e=t=>Ap.resolve(n,t);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async t=>{let s=e(t.path);if(!It.existsSync(s))return{success:!1,output:"",error:`File not found: ${t.path}`};if(!s.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${t.path}`};let r=It.statSync(s);if(r.size>xp)return{success:!1,output:"",error:`File too large: ${(r.size/1024/1024).toFixed(1)}MB (max: ${xp/1024/1024}MB)`};try{let i=It.readFileSync(s),{text:o,pages:a,metadata:l}=_p(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${t.path} (${a} pages)
376
376
 
377
- [No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let u=o;return u.length>yp&&(u=u.slice(0,yp)+`
377
+ [No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let u=o;return u.length>Sp&&(u=u.slice(0,Sp)+`
378
378
 
379
379
  [... content truncated ...]`),{success:!0,output:`${[`PDF: ${t.path}`,`Pages: ${a}`,l.title?`Title: ${l.title}`:"",l.author?`Author: ${l.author}`:"",`Size: ${(r.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
380
380
  `)}
381
- ${u}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async t=>{let s=e(t.path);if(!It.existsSync(s))return{success:!1,output:"",error:`File not found: ${t.path}`};try{let r=It.statSync(s),i=It.readFileSync(s),{pages:o,metadata:a}=bp(i);return{success:!0,output:[`File: ${t.path}`,`Size: ${(r.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${r.mtime.toISOString()}`].filter(Boolean).join(`
382
- `)}}catch(r){return{success:!1,output:"",error:`Failed to read PDF metadata: ${r instanceof Error?r.message:String(r)}`}}}}]}var It,wp,gp,yp,Sp=L(()=>{"use strict";It=O(require("fs")),wp=O(require("path")),gp=50*1024*1024,yp=4e4});function Cn(n){try{let{execSync:e}=require("child_process");return e(`which ${n} 2>/dev/null || where ${n} 2>NUL`,{stdio:"ignore"}),!0}catch{return!1}}async function Vx(n,e,t=Ep){let s=kp[e];if(!s)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(kp).join(", ")}`,exitCode:1,duration:0,language:e};if(!s.available())return{success:!1,stdout:"",stderr:`Language "${e}" is not available on this system. Install the runtime first.`,exitCode:1,duration:0,language:e};let r=$p.tmpdir(),i=Cp.join(r,`hablas_exec_${Date.now()}${s.extension}`);try{mr.writeFileSync(i,n,"utf-8");let o=s.command(i),a=Date.now();return await new Promise(l=>{let u=(0,Ap.exec)(o,{timeout:t,maxBuffer:5242880,cwd:r,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",h=>{d+=h}),u.stderr?.on("data",h=>{f+=h}),u.on("close",h=>{let m=Date.now()-a;l({success:h===0,stdout:d.slice(0,_p),stderr:f.slice(0,_p/2),exitCode:h??1,duration:m,language:e})}),u.on("error",h=>{let m=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:m,language:e})})})}finally{try{mr.unlinkSync(i)}catch{}}}function zx(n){return/\b(interface|type|enum|as\s+\w|:\s*(string|number|boolean|any)\b|<[A-Z]\w*>)/.test(n)?"typescript":/^(import\s+\w|from\s+\w|def\s+\w|class\s+\w|print\s*\(|if\s+__name__)/m.test(n)?"python":/^(#!\/bin\/bash|echo\s|export\s|if\s+\[|for\s+\w+\s+in)/m.test(n)?"bash":"javascript"}function Tp(){return[{name:"execute_code",description:"Execute a code snippet and return the output. Supports JavaScript, TypeScript, Python, and Bash. Code runs in a temporary file with a timeout. Use this to test code, run calculations, verify logic, or prototype solutions.",safety:"confirm",parameters:{code:{type:"string",description:"The code to execute",required:!0},language:{type:"string",description:"Language: javascript, typescript, python, bash (auto-detected if omitted)",required:!1},timeout:{type:"number",description:"Timeout in milliseconds (default: 10000, max: 30000)",required:!1}},execute:async n=>{let e=n.code;if(!e?.trim())return{success:!1,output:"",error:"Code is required"};let t=n.language?.toLowerCase()||zx(e),s=Math.min(Math.max(1e3,n.timeout||Ep),3e4),r=await Vx(e,t,s),i=[];return i.push(`Language: ${r.language} | Exit: ${r.exitCode} | Duration: ${r.duration}ms`),i.push(""),r.stdout&&(i.push("Output:"),i.push(r.stdout)),r.stderr&&(i.push(r.stdout?`
381
+ ${u}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async t=>{let s=e(t.path);if(!It.existsSync(s))return{success:!1,output:"",error:`File not found: ${t.path}`};try{let r=It.statSync(s),i=It.readFileSync(s),{pages:o,metadata:a}=_p(i);return{success:!0,output:[`File: ${t.path}`,`Size: ${(r.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${r.mtime.toISOString()}`].filter(Boolean).join(`
382
+ `)}}catch(r){return{success:!1,output:"",error:`Failed to read PDF metadata: ${r instanceof Error?r.message:String(r)}`}}}}]}var It,Ap,xp,Sp,Cp=L(()=>{"use strict";It=O(require("fs")),Ap=O(require("path")),xp=50*1024*1024,Sp=4e4});function En(n){try{let{execSync:e}=require("child_process");return e(`which ${n} 2>/dev/null || where ${n} 2>NUL`,{stdio:"ignore"}),!0}catch{return!1}}async function Qx(n,e,t=Mp){let s=Tp[e];if(!s)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Tp).join(", ")}`,exitCode:1,duration:0,language:e};if(!s.available())return{success:!1,stdout:"",stderr:`Language "${e}" is not available on this system. Install the runtime first.`,exitCode:1,duration:0,language:e};let r=Op.tmpdir(),i=Pp.join(r,`hablas_exec_${Date.now()}${s.extension}`);try{yr.writeFileSync(i,n,"utf-8");let o=s.command(i),a=Date.now();return await new Promise(l=>{let u=(0,Rp.exec)(o,{timeout:t,maxBuffer:5242880,cwd:r,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",h=>{d+=h}),u.stderr?.on("data",h=>{f+=h}),u.on("close",h=>{let m=Date.now()-a;l({success:h===0,stdout:d.slice(0,Ep),stderr:f.slice(0,Ep/2),exitCode:h??1,duration:m,language:e})}),u.on("error",h=>{let m=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:m,language:e})})})}finally{try{yr.unlinkSync(i)}catch{}}}function Zx(n){return/\b(interface|type|enum|as\s+\w|:\s*(string|number|boolean|any)\b|<[A-Z]\w*>)/.test(n)?"typescript":/^(import\s+\w|from\s+\w|def\s+\w|class\s+\w|print\s*\(|if\s+__name__)/m.test(n)?"python":/^(#!\/bin\/bash|echo\s|export\s|if\s+\[|for\s+\w+\s+in)/m.test(n)?"bash":"javascript"}function Ip(){return[{name:"execute_code",description:"Execute a code snippet and return the output. Supports JavaScript, TypeScript, Python, and Bash. Code runs in a temporary file with a timeout. Use this to test code, run calculations, verify logic, or prototype solutions.",safety:"confirm",parameters:{code:{type:"string",description:"The code to execute",required:!0},language:{type:"string",description:"Language: javascript, typescript, python, bash (auto-detected if omitted)",required:!1},timeout:{type:"number",description:"Timeout in milliseconds (default: 10000, max: 30000)",required:!1}},execute:async n=>{let e=n.code;if(!e?.trim())return{success:!1,output:"",error:"Code is required"};let t=n.language?.toLowerCase()||Zx(e),s=Math.min(Math.max(1e3,n.timeout||Mp),3e4),r=await Qx(e,t,s),i=[];return i.push(`Language: ${r.language} | Exit: ${r.exitCode} | Duration: ${r.duration}ms`),i.push(""),r.stdout&&(i.push("Output:"),i.push(r.stdout)),r.stderr&&(i.push(r.stdout?`
383
383
  Errors/Warnings:`:"Errors:"),i.push(r.stderr)),!r.stdout&&!r.stderr&&i.push("(no output)"),{success:r.success,output:i.join(`
384
- `),error:r.success?void 0:r.stderr||`Exit code: ${r.exitCode}`}}}]}var Ap,mr,$p,Cp,Ep,_p,kp,Rp=L(()=>{"use strict";Ap=require("child_process"),mr=O(require("fs")),$p=O(require("os")),Cp=O(require("path")),Ep=1e4,_p=16e3;kp={javascript:{extension:".js",command:n=>`node --no-warnings "${n}"`,available:()=>!0},typescript:{extension:".ts",command:n=>Cn("tsx")?`tsx "${n}"`:Cn("ts-node")?`ts-node --transpileOnly "${n}"`:`node --no-warnings -e "require('esbuild').buildSync({entryPoints:['${n}'],write:false,format:'cjs'}).outputFiles.forEach(f=>eval(f.text))"`,available:()=>!0},python:{extension:".py",command:n=>Cn("python3")?`python3 "${n}"`:`python "${n}"`,available:()=>Cn("python3")||Cn("python")},bash:{extension:".sh",command:n=>`bash "${n}"`,available:()=>Cn("bash")}}});var En,Op=L(()=>{"use strict";Yf();tp();rp();ap();pp();mp();Sp();Rp();En=class{tools=new Map;constructor(e,t){let s=Vf(e);for(let r of s)this.tools.set(r.name,r);this.tools.set("run_command",ep(e,t)),this.tools.set("search_codebase",np(e)),this.tools.set("detect_bugs",op(e)),this.tools.set("web_search",hp());for(let r of fp())this.tools.set(r.name,r);for(let r of xp(e))this.tools.set(r.name,r);for(let r of Tp())this.tools.set(r.name,r)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let t=this.tools.get(e.name);return t?t.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let t={},s=[];for(let[r,i]of Object.entries(e.parameters))t[r]={type:i.type==="number"?"number":"string",description:i.description},i.required&&s.push(r);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:t,required:s}}}})}getToolDescriptions(){return this.getAll().map(t=>{let s=Object.entries(t.parameters).map(([r,i])=>` ${r}: ${i.type} \u2014 ${i.description}`).join(`
384
+ `),error:r.success?void 0:r.stderr||`Exit code: ${r.exitCode}`}}}]}var Rp,yr,Op,Pp,Mp,Ep,Tp,Dp=L(()=>{"use strict";Rp=require("child_process"),yr=O(require("fs")),Op=O(require("os")),Pp=O(require("path")),Mp=1e4,Ep=16e3;Tp={javascript:{extension:".js",command:n=>`node --no-warnings "${n}"`,available:()=>!0},typescript:{extension:".ts",command:n=>En("tsx")?`tsx "${n}"`:En("ts-node")?`ts-node --transpileOnly "${n}"`:`node --no-warnings -e "require('esbuild').buildSync({entryPoints:['${n}'],write:false,format:'cjs'}).outputFiles.forEach(f=>eval(f.text))"`,available:()=>!0},python:{extension:".py",command:n=>En("python3")?`python3 "${n}"`:`python "${n}"`,available:()=>En("python3")||En("python")},bash:{extension:".sh",command:n=>`bash "${n}"`,available:()=>En("bash")}}});var Tn,Lp=L(()=>{"use strict";ep();op();cp();fp();bp();wp();Cp();Dp();Tn=class{tools=new Map;constructor(e,t){let s=Qf(e);for(let r of s)this.tools.set(r.name,r);this.tools.set("run_command",ip(e,t)),this.tools.set("search_codebase",ap(e)),this.tools.set("detect_bugs",dp(e)),this.tools.set("web_search",vp());for(let r of yp())this.tools.set(r.name,r);for(let r of $p(e))this.tools.set(r.name,r);for(let r of Ip())this.tools.set(r.name,r)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let t=this.tools.get(e.name);return t?t.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let t={},s=[];for(let[r,i]of Object.entries(e.parameters))t[r]={type:i.type==="number"?"number":"string",description:i.description},i.required&&s.push(r);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:t,required:s}}}})}getToolDescriptions(){return this.getAll().map(t=>{let s=Object.entries(t.parameters).map(([r,i])=>` ${r}: ${i.type} \u2014 ${i.description}`).join(`
385
385
  `);return`- ${t.name} [${t.safety}]: ${t.description}
386
386
  ${s}`}).join(`
387
387
 
388
- `)}}});function ua(n){return Math.ceil(n.length/3.5)}function os(n,e){let t=Math.floor(e*3.5);return n.length<=t?n:n.slice(0,t)+`
389
- ... [truncated to fit context budget]`}var da=L(()=>{"use strict"});var Pp,tn,fa=L(()=>{"use strict";Pp=O(require("crypto"));da();tn=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,t,s){let r=this.computeHash(t),i=this.cache.get(e);if(i&&i.hash===r){i.lastUsed=Date.now(),i.accessCount++;return}let o=ua(t),a=s?.importance??this.autoImportance(e,t);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:t,hash:r,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:s?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,t){let s=this.cache.get(e);return s?s.hash!==this.computeHash(t):!0}buildContext(e){let t=e||this.budget,s=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),r=0,i=[];for(let o of s){if(r+o.tokenCount>t){if(o.importance>=7){let a=t-r;if(a>200){let l=os(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
388
+ `)}}});function pa(n){return Math.ceil(n.length/3.5)}function as(n,e){let t=Math.floor(e*3.5);return n.length<=t?n:n.slice(0,t)+`
389
+ ... [truncated to fit context budget]`}var ha=L(()=>{"use strict"});var Np,nn,ma=L(()=>{"use strict";Np=O(require("crypto"));ha();nn=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,t,s){let r=this.computeHash(t),i=this.cache.get(e);if(i&&i.hash===r){i.lastUsed=Date.now(),i.accessCount++;return}let o=pa(t),a=s?.importance??this.autoImportance(e,t);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:t,hash:r,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:s?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,t){let s=this.cache.get(e);return s?s.hash!==this.computeHash(t):!0}buildContext(e){let t=e||this.budget,s=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),r=0,i=[];for(let o of s){if(r+o.tokenCount>t){if(o.importance>=7){let a=t-r;if(a>200){let l=as(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
390
390
  ${l}`),r+=a}}continue}i.push(`--- ${o.path} ---
391
391
  ${o.content}`),r+=o.tokenCount}return i.join(`
392
392
 
393
393
  `)}buildAgentContext(e,t){let s=t||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(u=>i.length===0?!0:i.some(d=>u.path.includes(d))).sort((u,d)=>this.computeScore(d)-this.computeScore(u)),a=0,l=[];for(let u of o){if(a+u.tokenCount>s)break;l.push(`--- ${u.path} ---
394
394
  ${u.content}`),a+=u.tokenCount}return l.join(`
395
395
 
396
- `)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,t)=>t.importance-e.importance)}evictToFit(e){let t=Array.from(this.cache.entries()).map(([r,i])=>({key:r,...i,score:this.computeScore(i)})).sort((r,i)=>r.score-i.score),s=0;for(let r of t){if(s>=e)break;r.importance>=9||(s+=r.tokenCount,this.usedTokens-=r.tokenCount,this.cache.delete(r.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let r=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-r/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,t){let s=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(s=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=3);let r=ua(t);return r>2e3&&(s=Math.max(1,s-1)),r>5e3&&(s=Math.max(1,s-2)),s}autoTag(e){let t=[];return/\.(ts|tsx)$/.test(e)&&t.push("typescript"),/\.(js|jsx)$/.test(e)&&t.push("javascript"),/\.json$/.test(e)&&t.push("config"),/\.md$/.test(e)&&t.push("documentation"),/\.(css|scss|sass)$/.test(e)&&t.push("style"),/\.(test|spec)\./i.test(e)&&t.push("test"),/src\//.test(e)&&t.push("source"),t}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let t=this.accessHistory[this.accessHistory.length-1];if(t&&Date.now()-this.getGroupTime(t)<3e4){if(!t.includes(e)){t.push(e);for(let s of t)if(s!==e){let r=this.cache.get(s);r&&!r.relatedFiles.includes(e)&&r.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return Pp.createHash("md5").update(e).digest("hex")}}});function as(){return`msg_${Date.now()}_${++Yx}`}function Tn(n){return Math.ceil(n.length/4)}var Yx,nn,pa=L(()=>{"use strict";Yx=0;nn=class n{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,t=50,s=32e3){this.maxMessages=t,this.maxTokens=s,this.sessionId=`session_${Date.now()}`;let r=Tn(e);this.messages.push({id:as(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]}),this.totalTokens=r}getSessionId(){return this.sessionId}addUserMessage(e,t){let s=as(),r=Tn(e);return this.messages.push({id:s,role:"user",content:e,timestamp:Date.now(),priority:t?.priority||"high",tokenEstimate:r,compressed:!1,tags:t?.tags||["user-input"]}),this.totalTokens+=r,this.trimIfNeeded(),s}addAssistantMessage(e,t,s){let r=as(),i=Tn(e),o={id:r,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:s||"hablas",tokenEstimate:i,compressed:!1,tags:s?[`agent:${s}`]:["assistant"]};return t&&t.length>0&&(o.tool_calls=t,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,s&&this.agentMessageCounts.set(s,(this.agentMessageCounts.get(s)||0)+1),this.trimIfNeeded(),r}addToolMessage(e,t){let s=as(),r=Tn(e);return this.messages.push({id:s,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:r,compressed:!1,tags:t?[`tool:${t}`]:["tool-result"]}),this.totalTokens+=r,this.trimIfNeeded(),s}getMessages(){return this.messages.map(e=>{let t={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(t.tool_calls=e.tool_calls),t})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(t=>t.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let t=Tn(e),s=this.messages.filter(r=>r.priority==="critical"&&r.role!=="system");this.messages=[{id:as(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:t,compressed:!1,tags:["system"]},...s],this.recalculateTokens()}takeSnapshot(e){let t={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(s=>({...s})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(t),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),t.id}rollback(e){let t=this.snapshots.find(s=>s.id===e);return t?(this.messages=t.messages.map(s=>({...s})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,t){let s=this.messages.length,r=new n(t,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?r.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&r.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:s,session:r}),r}mergeFork(e,t){let s=this.forks.get(e);if(!s)return!1;let r=s.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(t)this.addAssistantMessage(`[Agent @${e} result]: ${t}`,void 0,e);else if(r.length>0){let i=r.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let t=e.toLowerCase();return this.messages.filter(s=>s.content.toLowerCase().includes(t))}getMessagesByTag(e){return this.messages.filter(t=>t.tags.includes(e))}getLastByRole(e,t=1){return this.messages.filter(s=>s.role===e).slice(-t)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(t=>t.role==="tool"&&!t.compressed&&t.tokenEstimate>200);for(let t of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(t)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let t=this.messages.filter(s=>s.role==="assistant"&&!s.compressed&&s.priority!=="critical"&&s.tokenEstimate>300);for(let s of t.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(s)}}if(this.messages.length>this.maxMessages){let t=this.messages[0],s=this.messages.slice(1),r={critical:3,high:2,normal:1,low:0},i=s.sort((o,a)=>{let l=r[a.priority]-r[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[t,...i],this.recalculateTokens()}}compressMessage(e){let t=e.content.length,s=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
396
+ `)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,t)=>t.importance-e.importance)}evictToFit(e){let t=Array.from(this.cache.entries()).map(([r,i])=>({key:r,...i,score:this.computeScore(i)})).sort((r,i)=>r.score-i.score),s=0;for(let r of t){if(s>=e)break;r.importance>=9||(s+=r.tokenCount,this.usedTokens-=r.tokenCount,this.cache.delete(r.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let r=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-r/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,t){let s=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(s=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=3);let r=pa(t);return r>2e3&&(s=Math.max(1,s-1)),r>5e3&&(s=Math.max(1,s-2)),s}autoTag(e){let t=[];return/\.(ts|tsx)$/.test(e)&&t.push("typescript"),/\.(js|jsx)$/.test(e)&&t.push("javascript"),/\.json$/.test(e)&&t.push("config"),/\.md$/.test(e)&&t.push("documentation"),/\.(css|scss|sass)$/.test(e)&&t.push("style"),/\.(test|spec)\./i.test(e)&&t.push("test"),/src\//.test(e)&&t.push("source"),t}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let t=this.accessHistory[this.accessHistory.length-1];if(t&&Date.now()-this.getGroupTime(t)<3e4){if(!t.includes(e)){t.push(e);for(let s of t)if(s!==e){let r=this.cache.get(s);r&&!r.relatedFiles.includes(e)&&r.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return Np.createHash("md5").update(e).digest("hex")}}});function ls(){return`msg_${Date.now()}_${++eS}`}function Rn(n){return Math.ceil(n.length/4)}var eS,sn,ga=L(()=>{"use strict";eS=0;sn=class n{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,t=50,s=32e3){this.maxMessages=t,this.maxTokens=s,this.sessionId=`session_${Date.now()}`;let r=Rn(e);this.messages.push({id:ls(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]}),this.totalTokens=r}getSessionId(){return this.sessionId}addUserMessage(e,t){let s=ls(),r=Rn(e);return this.messages.push({id:s,role:"user",content:e,timestamp:Date.now(),priority:t?.priority||"high",tokenEstimate:r,compressed:!1,tags:t?.tags||["user-input"]}),this.totalTokens+=r,this.trimIfNeeded(),s}addAssistantMessage(e,t,s){let r=ls(),i=Rn(e),o={id:r,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:s||"hablas",tokenEstimate:i,compressed:!1,tags:s?[`agent:${s}`]:["assistant"]};return t&&t.length>0&&(o.tool_calls=t,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,s&&this.agentMessageCounts.set(s,(this.agentMessageCounts.get(s)||0)+1),this.trimIfNeeded(),r}addToolMessage(e,t){let s=ls(),r=Rn(e);return this.messages.push({id:s,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:r,compressed:!1,tags:t?[`tool:${t}`]:["tool-result"]}),this.totalTokens+=r,this.trimIfNeeded(),s}getMessages(){return this.messages.map(e=>{let t={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(t.tool_calls=e.tool_calls),t})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(t=>t.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let t=Rn(e),s=this.messages.filter(r=>r.priority==="critical"&&r.role!=="system");this.messages=[{id:ls(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:t,compressed:!1,tags:["system"]},...s],this.recalculateTokens()}takeSnapshot(e){let t={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(s=>({...s})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(t),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),t.id}rollback(e){let t=this.snapshots.find(s=>s.id===e);return t?(this.messages=t.messages.map(s=>({...s})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,t){let s=this.messages.length,r=new n(t,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?r.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&r.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:s,session:r}),r}mergeFork(e,t){let s=this.forks.get(e);if(!s)return!1;let r=s.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(t)this.addAssistantMessage(`[Agent @${e} result]: ${t}`,void 0,e);else if(r.length>0){let i=r.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let t=e.toLowerCase();return this.messages.filter(s=>s.content.toLowerCase().includes(t))}getMessagesByTag(e){return this.messages.filter(t=>t.tags.includes(e))}getLastByRole(e,t=1){return this.messages.filter(s=>s.role===e).slice(-t)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(t=>t.role==="tool"&&!t.compressed&&t.tokenEstimate>200);for(let t of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(t)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let t=this.messages.filter(s=>s.role==="assistant"&&!s.compressed&&s.priority!=="critical"&&s.tokenEstimate>300);for(let s of t.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(s)}}if(this.messages.length>this.maxMessages){let t=this.messages[0],s=this.messages.slice(1),r={critical:3,high:2,normal:1,low:0},i=s.sort((o,a)=>{let l=r[a.priority]-r[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[t,...i],this.recalculateTokens()}}compressMessage(e){let t=e.content.length,s=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
397
397
  ...(compressed from `+t+" chars)":e.content=e.content.slice(0,400)+`
398
- ...(compressed from `+t+" chars)",e.compressed=!0,e.originalLength=t,e.tokenEstimate=Tn(e.content),this.totalTokens-=s-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,t)=>e+t.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let t=JSON.parse(e);if(!t.messages||!Array.isArray(t.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=t.sessionId||`session_${Date.now()}`,this.messages=t.messages,this.totalTokens=t.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(t.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}}});var Mp,Xe,Ke,Ip,gr,ha,Jx,Xx,Qx,ls,Dp=L(()=>{"use strict";Mp=O(require("readline")),Xe=O(require("fs")),Ke=O(require("path")),Ip=O(require("os"));yn();gr=Ke.join(Ip.homedir(),".hablas","history"),ha=500,Jx=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml",".txt",".env",".sh",".bash",".zsh",".dockerfile",".xml",".svg",".sql"]),Xx=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Qx=["read ","edit ","write ","delete ","open ","patch "],ls=class{rl;history=[];workingDir;fileCache=[];fileCacheTime=0;constructor(e){this.workingDir=e||process.cwd(),this.loadHistory(),this.rl=this.createReadline()}createReadline(){return Mp.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:this.history,historySize:ha,completer:e=>this.autocomplete(e)})}reinitialize(){this.loadHistory(),this.rl=this.createReadline()}async prompt(e){return new Promise(t=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,s=>{s.trim()&&(this.history.push(s.trim()),this.saveHistory()),t(s)})})}async confirm(e){let t=` ${c.warning("?")} ${e} ${c.muted("[Y/n]")} `;return(await this.prompt(t)).toLowerCase()!=="n"}async confirmDangerous(e){console.log(`
398
+ ...(compressed from `+t+" chars)",e.compressed=!0,e.originalLength=t,e.tokenEstimate=Rn(e.content),this.totalTokens-=s-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,t)=>e+t.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let t=JSON.parse(e);if(!t.messages||!Array.isArray(t.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=t.sessionId||`session_${Date.now()}`,this.messages=t.messages,this.totalTokens=t.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(t.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}}});var Fp,Qe,qe,jp,br,ya,tS,nS,sS,cs,Hp=L(()=>{"use strict";Fp=O(require("readline")),Qe=O(require("fs")),qe=O(require("path")),jp=O(require("os"));bn();br=qe.join(jp.homedir(),".hablas","history"),ya=500,tS=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml",".txt",".env",".sh",".bash",".zsh",".dockerfile",".xml",".svg",".sql"]),nS=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),sS=["read ","edit ","write ","delete ","open ","patch "],cs=class{rl;history=[];workingDir;fileCache=[];fileCacheTime=0;constructor(e){this.workingDir=e||process.cwd(),this.loadHistory(),this.rl=this.createReadline()}createReadline(){return Fp.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:this.history,historySize:ya,completer:e=>this.autocomplete(e)})}reinitialize(){this.loadHistory(),this.rl=this.createReadline()}async prompt(e){return new Promise(t=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,s=>{s.trim()&&(this.history.push(s.trim()),this.saveHistory()),t(s)})})}async confirm(e){let t=` ${c.warning("?")} ${e} ${c.muted("[Y/n]")} `;return(await this.prompt(t)).toLowerCase()!=="n"}async confirmDangerous(e){console.log(`
399
399
  ${c.error("\u26A0")} ${c.error(c.strong(e))}`),console.log(` ${c.muted('This action cannot be undone. Type "yes" to confirm.')}
400
- `);let t=` ${c.error("\u2192")} `;return(await this.prompt(t)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){if(e.startsWith("/model ")||e.startsWith("/usemodel "))return[[],e];if(e.startsWith("/mindset ")){let r=["coder","planner","debugger","reviewer"],i=e.slice(9),o=r.filter(a=>a.startsWith(i)).map(a=>"/mindset "+a);return[o.length?o:r.map(a=>"/mindset "+a),e]}if(e.startsWith("/alias ")){let r=["/alias set","/alias del"],i=r.filter(o=>o.startsWith(e));return[i.length?i:r,e]}if(e.startsWith("/plugins ")){let r=["/plugins enable","/plugins disable"],i=r.filter(o=>o.startsWith(e));return[i.length?i:r,e]}let s=Ji.filter(r=>r.startsWith(e));return[s.length?s:Ji,e]}for(let s of Qx)if(e.toLowerCase().includes(s)){let r=e.split(s).pop()??"";if(r&&!r.includes(" "))try{let i=Ke.dirname(r)||".",o=Ke.basename(r),a=Ke.resolve(this.workingDir,i),l=Xe.readdirSync(a).filter(u=>u.startsWith(o)).slice(0,8).map(u=>e.slice(0,e.lastIndexOf(r))+Ke.join(i,u));if(l.length)return[l,e]}catch{}}let t=e.match(/#([\w./-]*)$/);if(t){let s=t[1],r=this.getProjectFiles(),i=r.filter(a=>a.toLowerCase().startsWith(s.toLowerCase())).map(a=>e.slice(0,e.length-t[0].length)+"#"+a);return i.length>0?[i,e]:[r.slice(0,20).map(a=>e.slice(0,e.length-t[0].length)+"#"+a),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let t=[];return this.scanDir(this.workingDir,"",t,3),this.fileCache=t,this.fileCacheTime=e,t}scanDir(e,t,s,r,i=0){if(!(i>=r))try{let o=Xe.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||Xx.has(a.name))continue;let l=t?`${t}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(Ke.join(e,a.name),l,s,r,i+1);else{let u=Ke.extname(a.name).toLowerCase();(Jx.has(u)||a.name==="Dockerfile"||a.name==="Makefile")&&s.push(l)}}}catch{}}loadHistory(){try{if(Xe.existsSync(gr)){let e=Xe.readFileSync(gr,"utf-8");this.history=e.split(`
401
- `).filter(Boolean).slice(-ha)}}catch{}}saveHistory(){try{let e=Ke.dirname(gr);Xe.existsSync(e)||Xe.mkdirSync(e,{recursive:!0});let t=this.history.slice(-ha);Xe.writeFileSync(gr,t.join(`
402
- `),"utf-8")}catch{}}}});function Te(n={}){let e={};if(ot.existsSync(ma))try{let s=ot.readFileSync(ma,"utf-8");e=JSON.parse(s)}catch{}let t={...Fn,...e,tools:{...Fn.tools,...e.tools||{}},ui:{...Fn.ui,...e.ui||{}}};if(process.env.HABLAS_API_URL&&(t.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(t.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_PROVIDER){let s=process.env.HABLAS_PROVIDER;(s==="ollama"||s==="custom")&&(t.provider=s)}if(process.env.HABLAS_MODEL&&(t.model=process.env.HABLAS_MODEL),n.model&&(t.model=n.model),n.host&&(t.ollamaHost=n.host),n.project&&(t.workingDirectory=sn.resolve(n.project)),n.provider){let s=n.provider;(s==="ollama"||s==="custom")&&(t.provider=s)}return n.apiUrl&&(t.apiUrl=n.apiUrl),n.apiKey&&(t.apiKey=n.apiKey),n.team&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.enabled=!0),n.user&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.user=n.user),n.teamKey&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.key=n.teamKey),t.apiUrl&&t.provider==="ollama"&&(t.provider="custom"),t}function wt(n){ot.existsSync(Rn)||ot.mkdirSync(Rn,{recursive:!0}),ot.writeFileSync(ma,JSON.stringify(n,null,2),"utf-8")}function Fp(){let n=[Rn,sn.join(Rn,"logs"),sn.join(Rn,"backup")];for(let e of n)ot.existsSync(e)||ot.mkdirSync(e,{recursive:!0})}var ot,sn,Lp,Rn,ma,yr=L(()=>{"use strict";ot=O(require("fs")),sn=O(require("path")),Lp=O(require("os"));Nn();Rn=sn.join(Lp.homedir(),".hablas"),ma=sn.join(Rn,"config.json")});var cs,ga=L(()=>{"use strict";cs=class{mindsets=new Map;activeMindset="planner";history=[];lastActivatedAt=Date.now();listeners=[];register(e){this.mindsets.set(e.name,e)}get(e){return this.mindsets.get(e)}list(){return Array.from(this.mindsets.values())}listNames(){return Array.from(this.mindsets.keys())}getActive(){return this.mindsets.get(this.activeMindset)}getActiveName(){return this.activeMindset}setActive(e){if(!this.mindsets.has(e))return!1;if(this.activeMindset===e)return!0;let t=this.activeMindset;if(this.history.length>0){let s=this.history[this.history.length-1];s.duration=Date.now()-this.lastActivatedAt}this.activeMindset=e,this.lastActivatedAt=Date.now(),this.history.push({name:e,timestamp:Date.now()}),this.history.length>50&&(this.history=this.history.slice(-50));for(let s of this.listeners)try{s(t,e)}catch{}return!0}has(e){return this.mindsets.has(e)}getHistory(){return[...this.history]}getMostUsed(){let e={};for(let s of this.history)e[s.name]=(e[s.name]||0)+1;let t=Object.entries(e).sort((s,r)=>r[1]-s[1]);return t.length>0?t[0][0]:null}onChange(e){this.listeners.push(e)}createComposite(e,t,s){let r=this.mindsets.get(t),i=this.mindsets.get(s);if(!r||!i)return null;let o={name:e,description:`${r.description} + ${i.description}`,systemPrompt:r.systemPrompt+`
400
+ `);let t=` ${c.error("\u2192")} `;return(await this.prompt(t)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){if(e.startsWith("/model ")||e.startsWith("/usemodel "))return[[],e];if(e.startsWith("/mindset ")){let r=["coder","planner","debugger","reviewer"],i=e.slice(9),o=r.filter(a=>a.startsWith(i)).map(a=>"/mindset "+a);return[o.length?o:r.map(a=>"/mindset "+a),e]}if(e.startsWith("/alias ")){let r=["/alias set","/alias del"],i=r.filter(o=>o.startsWith(e));return[i.length?i:r,e]}if(e.startsWith("/plugins ")){let r=["/plugins enable","/plugins disable"],i=r.filter(o=>o.startsWith(e));return[i.length?i:r,e]}let s=Zi.filter(r=>r.startsWith(e));return[s.length?s:Zi,e]}for(let s of sS)if(e.toLowerCase().includes(s)){let r=e.split(s).pop()??"";if(r&&!r.includes(" "))try{let i=qe.dirname(r)||".",o=qe.basename(r),a=qe.resolve(this.workingDir,i),l=Qe.readdirSync(a).filter(u=>u.startsWith(o)).slice(0,8).map(u=>e.slice(0,e.lastIndexOf(r))+qe.join(i,u));if(l.length)return[l,e]}catch{}}let t=e.match(/#([\w./-]*)$/);if(t){let s=t[1],r=this.getProjectFiles(),i=r.filter(a=>a.toLowerCase().startsWith(s.toLowerCase())).map(a=>e.slice(0,e.length-t[0].length)+"#"+a);return i.length>0?[i,e]:[r.slice(0,20).map(a=>e.slice(0,e.length-t[0].length)+"#"+a),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let t=[];return this.scanDir(this.workingDir,"",t,3),this.fileCache=t,this.fileCacheTime=e,t}scanDir(e,t,s,r,i=0){if(!(i>=r))try{let o=Qe.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||nS.has(a.name))continue;let l=t?`${t}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(qe.join(e,a.name),l,s,r,i+1);else{let u=qe.extname(a.name).toLowerCase();(tS.has(u)||a.name==="Dockerfile"||a.name==="Makefile")&&s.push(l)}}}catch{}}loadHistory(){try{if(Qe.existsSync(br)){let e=Qe.readFileSync(br,"utf-8");this.history=e.split(`
401
+ `).filter(Boolean).slice(-ya)}}catch{}}saveHistory(){try{let e=qe.dirname(br);Qe.existsSync(e)||Qe.mkdirSync(e,{recursive:!0});let t=this.history.slice(-ya);Qe.writeFileSync(br,t.join(`
402
+ `),"utf-8")}catch{}}}});function Re(n={}){let e={};if(at.existsSync(ba))try{let s=at.readFileSync(ba,"utf-8");e=JSON.parse(s)}catch{}let t={...Fn,...e,tools:{...Fn.tools,...e.tools||{}},ui:{...Fn.ui,...e.ui||{}}};if(process.env.HABLAS_API_URL&&(t.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(t.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_PROVIDER){let s=process.env.HABLAS_PROVIDER;(s==="ollama"||s==="custom")&&(t.provider=s)}if(process.env.HABLAS_MODEL&&(t.model=process.env.HABLAS_MODEL),n.model&&(t.model=n.model),n.host&&(t.ollamaHost=n.host),n.project&&(t.workingDirectory=rn.resolve(n.project)),n.provider){let s=n.provider;(s==="ollama"||s==="custom")&&(t.provider=s)}return n.apiUrl&&(t.apiUrl=n.apiUrl),n.apiKey&&(t.apiKey=n.apiKey),n.team&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.enabled=!0),n.user&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.user=n.user),n.teamKey&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.key=n.teamKey),t.apiUrl&&t.provider==="ollama"&&(t.provider="custom"),t}function vt(n){at.existsSync(On)||at.mkdirSync(On,{recursive:!0}),at.writeFileSync(ba,JSON.stringify(n,null,2),"utf-8")}function Up(){let n=[On,rn.join(On,"logs"),rn.join(On,"backup")];for(let e of n)at.existsSync(e)||at.mkdirSync(e,{recursive:!0})}var at,rn,Bp,On,ba,vr=L(()=>{"use strict";at=O(require("fs")),rn=O(require("path")),Bp=O(require("os"));jn();On=rn.join(Bp.homedir(),".hablas"),ba=rn.join(On,"config.json")});var us,va=L(()=>{"use strict";us=class{mindsets=new Map;activeMindset="planner";history=[];lastActivatedAt=Date.now();listeners=[];register(e){this.mindsets.set(e.name,e)}get(e){return this.mindsets.get(e)}list(){return Array.from(this.mindsets.values())}listNames(){return Array.from(this.mindsets.keys())}getActive(){return this.mindsets.get(this.activeMindset)}getActiveName(){return this.activeMindset}setActive(e){if(!this.mindsets.has(e))return!1;if(this.activeMindset===e)return!0;let t=this.activeMindset;if(this.history.length>0){let s=this.history[this.history.length-1];s.duration=Date.now()-this.lastActivatedAt}this.activeMindset=e,this.lastActivatedAt=Date.now(),this.history.push({name:e,timestamp:Date.now()}),this.history.length>50&&(this.history=this.history.slice(-50));for(let s of this.listeners)try{s(t,e)}catch{}return!0}has(e){return this.mindsets.has(e)}getHistory(){return[...this.history]}getMostUsed(){let e={};for(let s of this.history)e[s.name]=(e[s.name]||0)+1;let t=Object.entries(e).sort((s,r)=>r[1]-s[1]);return t.length>0?t[0][0]:null}onChange(e){this.listeners.push(e)}createComposite(e,t,s){let r=this.mindsets.get(t),i=this.mindsets.get(s);if(!r||!i)return null;let o={name:e,description:`${r.description} + ${i.description}`,systemPrompt:r.systemPrompt+`
403
403
 
404
- `+i.systemPrompt,toolPreferences:[...new Set([...i.toolPreferences,...r.toolPreferences])],behaviorModifiers:{...r.behaviorModifiers,...i.behaviorModifiers}};return this.register(o),o}}});var ya,ba=L(()=>{"use strict";ya={name:"coder",description:"Expert coding assistant \u2014 direct file operations, precise edits, production-quality code",systemPrompt:`You are Alex, the Engineer on the Hablas multi-agent team. You are an expert full-stack developer.
404
+ `+i.systemPrompt,toolPreferences:[...new Set([...i.toolPreferences,...r.toolPreferences])],behaviorModifiers:{...r.behaviorModifiers,...i.behaviorModifiers}};return this.register(o),o}}});var wa,xa=L(()=>{"use strict";wa={name:"coder",description:"Expert coding assistant \u2014 direct file operations, precise edits, production-quality code",systemPrompt:`You are Alex, the Engineer on the Hablas multi-agent team. You are an expert full-stack developer.
405
405
 
406
406
  ## Your Strengths
407
407
  - Writing clean, production-ready code with proper error handling
@@ -454,7 +454,7 @@ You: [think internally] \u2192 call read_file on auth.ts (ONE tool)
454
454
  [observe result] \u2192 then call patch_file with precise edit.
455
455
  NEVER: output <read_file path=...> in text, or repeat read on same file, or switch to "I am Bob now".
456
456
 
457
- If previous turn already read "DentalClinic_Blueprint.md", do NOT call read_file on it again this turn.`,toolPreferences:["read_file","patch_file","edit_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"concise",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py","*.go","*.rs","*.css","*.html"]}});var va,wa=L(()=>{"use strict";va={name:"planner",description:"Team Leader \u2014 strategic planning, task breakdown, coordination, decision-making",systemPrompt:`You are Hablas, the inspiring Team Leader of a multi-agent AI development system. You are a highly supportive, communicative, and exceptionally competent Engineering Lead.
457
+ If previous turn already read "DentalClinic_Blueprint.md", do NOT call read_file on it again this turn.`,toolPreferences:["read_file","patch_file","edit_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"concise",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py","*.go","*.rs","*.css","*.html"]}});var Sa,_a=L(()=>{"use strict";Sa={name:"planner",description:"Team Leader \u2014 strategic planning, task breakdown, coordination, decision-making",systemPrompt:`You are Hablas, the inspiring Team Leader of a multi-agent AI development system. You are a highly supportive, communicative, and exceptionally competent Engineering Lead.
458
458
  You coordinate a team of specialized agents to help developers build and modify their codebase, and you love helping the developer succeed with high-quality engineering.
459
459
 
460
460
  ## Your Persona (Supportive, Empathetic & Expert Engineering Lead)
@@ -515,7 +515,7 @@ Never output raw tool XML in text.
515
515
  User: "build the auth system with JWT"
516
516
  You (Hablas): Create plan internally \u2192 handoff to @Bob "design schema" , then to @Alex etc.
517
517
  Use rich theatre via conductor. NEVER output raw XML, repeat tool, or do solo if Build.
518
- For Build: always full team at max power.`,toolPreferences:["read_file","search_codebase","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!0,contextPriority:"all"}}});var xa,Sa=L(()=>{"use strict";xa={name:"reviewer",description:"Code reviewer \u2014 quality audit, anti-patterns, security issues, performance bottlenecks",systemPrompt:`You are an expert code reviewer. You audit code quality and provide actionable feedback.
518
+ For Build: always full team at max power.`,toolPreferences:["read_file","search_codebase","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!0,contextPriority:"all"}}});var ka,Aa=L(()=>{"use strict";ka={name:"reviewer",description:"Code reviewer \u2014 quality audit, anti-patterns, security issues, performance bottlenecks",systemPrompt:`You are an expert code reviewer. You audit code quality and provide actionable feedback.
519
519
 
520
520
  ## Review Checklist
521
521
  - Security vulnerabilities (injection, XSS, CSRF, auth bypass)
@@ -562,7 +562,7 @@ Stay strictly in your role as the Code Reviewer. Focus on audits, issues, sugges
562
562
 
563
563
  After finishing your part, produce a clear handoff summary.
564
564
 
565
- Never output raw tool XML in text.`,toolPreferences:["read_file","search_codebase","list_dir","get_file_info"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py"]}});var _a,ka=L(()=>{"use strict";_a={name:"debugger",description:"Bug hunter \u2014 traces errors, root cause analysis, targeted fixes, regression prevention",systemPrompt:`You are a systematic debugging expert. You find and fix bugs through methodical investigation.
565
+ Never output raw tool XML in text.`,toolPreferences:["read_file","search_codebase","list_dir","get_file_info"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py"]}});var $a,Ca=L(()=>{"use strict";$a={name:"debugger",description:"Bug hunter \u2014 traces errors, root cause analysis, targeted fixes, regression prevention",systemPrompt:`You are a systematic debugging expert. You find and fix bugs through methodical investigation.
566
566
 
567
567
  ## Debugging Process
568
568
  1. **Reproduce**: Understand the symptom and error message
@@ -598,7 +598,7 @@ After finishing your part, produce a clear handoff summary.
598
598
 
599
599
  Never output raw tool XML in text.
600
600
 
601
- Focus on the ROOT CAUSE, not symptoms.`,toolPreferences:["read_file","search_codebase","run_command","patch_file","edit_file"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.py","*.go","*.log","*.json"]}});var Aa,$a=L(()=>{"use strict";Aa={name:"architect",description:"System architecture \u2014 schemas, APIs, project structure, scalability, ADRs",systemPrompt:`You are Bob, the System Architect on the Hablas multi-agent team.
601
+ Focus on the ROOT CAUSE, not symptoms.`,toolPreferences:["read_file","search_codebase","run_command","patch_file","edit_file"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.py","*.go","*.log","*.json"]}});var Ea,Ta=L(()=>{"use strict";Ea={name:"architect",description:"System architecture \u2014 schemas, APIs, project structure, scalability, ADRs",systemPrompt:`You are Bob, the System Architect on the Hablas multi-agent team.
602
602
  Your role is to design robust, scalable, maintainable system architectures.
603
603
 
604
604
  ## Your Strengths
@@ -653,7 +653,7 @@ Never output raw tool XML in text.
653
653
  User: "Design the database schema for users"
654
654
  You: [internal] \u2192 call list_dir or read_file on existing schema files (ONE at a time)
655
655
  [observe] \u2192 then write_file "architecture/users-schema.md" with mermaid + ADR.
656
- NEVER leak <write_file> in chat, repeat reads, or do coding work (that's Alex).`,toolPreferences:["read_file","list_dir","write_file","search_codebase"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"architecture"},filePatterns:["*.md","*.json","*.yaml","*.yml","*.toml","*.xml","schema*","config*"]}});var Ca,Ea=L(()=>{"use strict";Ca={name:"devops",description:"DevOps \u2014 Docker, CI/CD, cloud, monitoring, deployment, infrastructure as code",systemPrompt:`You are a DevOps expert. You handle infrastructure, deployment, and operational concerns.
656
+ NEVER leak <write_file> in chat, repeat reads, or do coding work (that's Alex).`,toolPreferences:["read_file","list_dir","write_file","search_codebase"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"architecture"},filePatterns:["*.md","*.json","*.yaml","*.yml","*.toml","*.xml","schema*","config*"]}});var Ra,Oa=L(()=>{"use strict";Ra={name:"devops",description:"DevOps \u2014 Docker, CI/CD, cloud, monitoring, deployment, infrastructure as code",systemPrompt:`You are a DevOps expert. You handle infrastructure, deployment, and operational concerns.
657
657
 
658
658
  ## Your Expertise
659
659
  - Docker & container orchestration (Kubernetes, Docker Compose)
@@ -697,7 +697,7 @@ Stay strictly in your role as the DevOps Specialist. Focus on infra, CI/CD, depl
697
697
 
698
698
  After finishing your part, produce a clear handoff summary.
699
699
 
700
- Never output raw tool XML in text.`,toolPreferences:["run_command","write_file","read_file","list_dir"],behaviorModifiers:{planFirst:!0,maxIterations:20,verbosity:"normal",autoConfirmSafe:!1,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!1,contextPriority:"all"},filePatterns:["Dockerfile*","docker-compose*","*.yml","*.yaml",".github/*","Makefile","*.sh"]}});var Ta,Ra=L(()=>{"use strict";Ta={name:"researcher",description:"Research & analysis \u2014 documentation, APIs, best practices, data analysis, benchmarks",systemPrompt:`You are David, the Data & Research Specialist on the Hablas multi-agent team.
700
+ Never output raw tool XML in text.`,toolPreferences:["run_command","write_file","read_file","list_dir"],behaviorModifiers:{planFirst:!0,maxIterations:20,verbosity:"normal",autoConfirmSafe:!1,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!1,contextPriority:"all"},filePatterns:["Dockerfile*","docker-compose*","*.yml","*.yaml",".github/*","Makefile","*.sh"]}});var Pa,Ma=L(()=>{"use strict";Pa={name:"researcher",description:"Research & analysis \u2014 documentation, APIs, best practices, data analysis, benchmarks",systemPrompt:`You are David, the Data & Research Specialist on the Hablas multi-agent team.
701
701
  Your role is to find information, analyze data, and provide well-researched context.
702
702
 
703
703
  ## Your Strengths
@@ -752,7 +752,7 @@ Never output raw tool XML in text.
752
752
  ## Few-Shot: Correct Behavior
753
753
  User: "research best OAuth practices for our stack"
754
754
  You: call search_codebase or read_file (one) \u2192 analyze \u2192 write research report.md with citations.
755
- NEVER repeat tool calls, leak XML, or implement the feature (that's Alex).`,toolPreferences:["search_codebase","read_file","run_command","list_dir","web_search"],behaviorModifiers:{planFirst:!1,maxIterations:10,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"exploratory",askWhenUncertain:!0,canDelegate:!1,contextPriority:"data"},filePatterns:["*.md","*.txt","*.csv","*.json","*.sql","*.yml","*.yaml"]}});var Oa,Pa=L(()=>{"use strict";Oa={name:"product-manager",description:"Product Manager \u2014 requirements, PRDs, user stories, market research, competitive analysis",systemPrompt:`You are Emma, the Product Manager on the Hablas multi-agent team.
755
+ NEVER repeat tool calls, leak XML, or implement the feature (that's Alex).`,toolPreferences:["search_codebase","read_file","run_command","list_dir","web_search"],behaviorModifiers:{planFirst:!1,maxIterations:10,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"exploratory",askWhenUncertain:!0,canDelegate:!1,contextPriority:"data"},filePatterns:["*.md","*.txt","*.csv","*.json","*.sql","*.yml","*.yaml"]}});var Ia,Da=L(()=>{"use strict";Ia={name:"product-manager",description:"Product Manager \u2014 requirements, PRDs, user stories, market research, competitive analysis",systemPrompt:`You are Emma, the Product Manager on the Hablas multi-agent team.
756
756
  Your role is to analyze needs, create detailed specs, and ensure the team builds the right thing.
757
757
 
758
758
  ## Your Strengths
@@ -800,7 +800,7 @@ Stay strictly in your role as the Product Manager. Focus on requirements, PRDs,
800
800
 
801
801
  After finishing your part, produce a clear handoff summary.
802
802
 
803
- Never output raw tool XML in text.`,toolPreferences:["read_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"requirements"},filePatterns:["*.md","*.txt","*.json","package.json","README*"]}});var Ma,Ia=L(()=>{"use strict";Ma={name:"sync",description:"Team Coordinator & Diplomatic Consul \u2014 handles lock negotiations, git sync, and team messaging",systemPrompt:`You are @Consul, the Software Diplomat on the Hablas multi-agent team.
803
+ Never output raw tool XML in text.`,toolPreferences:["read_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"requirements"},filePatterns:["*.md","*.txt","*.json","package.json","README*"]}});var La,Na=L(()=>{"use strict";La={name:"sync",description:"Team Coordinator & Diplomatic Consul \u2014 handles lock negotiations, git sync, and team messaging",systemPrompt:`You are @Consul, the Software Diplomat on the Hablas multi-agent team.
804
804
  Your absolute priority is to ensure smooth, conflict-free collaboration between human developers and machine agents.
805
805
 
806
806
  ## Your Personality (INTJ + Diplomatic Coordinator)
@@ -835,72 +835,136 @@ Stay strictly in your role as @Consul the Diplomatic Coordinator. Focus on locks
835
835
 
836
836
  After finishing your part, produce a clear handoff summary.
837
837
 
838
- Never output raw tool XML in text.`,toolPreferences:["read_file","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:10,verbosity:"concise",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!1,contextPriority:"requirements"}}});var Da,La=L(()=>{"use strict";Da={name:"gate",description:"Hidden Executive Decision Layer \u2014 professional input analysis and routing (internal, not visible)",systemPrompt:`You are Gate, the Hidden Executive Decision Layer for the Hablas professional multi-agent system.
838
+ Never output raw tool XML in text.`,toolPreferences:["read_file","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:10,verbosity:"concise",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!1,contextPriority:"requirements"}}});var Fa,ja=L(()=>{"use strict";Fa={name:"gate",description:"Hidden Executive Decision Layer \u2014 professional input analysis and routing (internal, not visible)",systemPrompt:`You are Gate, the Hidden Executive Decision Layer for the Hablas professional senior multi-agent AI coding system.
839
839
 
840
- You are the strong, reliable first layer that every user message passes through before any visible agent work begins. Your role is invisible to the end user \u2014 you never appear in rosters, handoffs, or theatre. You exist to ensure professional, comprehensive, and context-aware routing for high-stakes engineering work.
840
+ You are the STRONG, RELIABLE, INVISIBLE first layer that EVERY user message passes through before ANY visible agent work begins. Your role is 100% hidden \u2014 you NEVER appear in rosters, handoffs, theatre, logs, or user view. You exist solely to ensure perfect professional routing for high-stakes engineering work.
841
841
 
842
- ## Your Professional Context
843
- - This system is used for serious development: white papers, production integrations with NVIDIA NIM, Replit, Cloud providers, and complex multi-file systems.
844
- - Casual chat must be handled lightly and fast.
845
- - Serious engineering requests (architecture, implementation, debugging, planning) must trigger the full powerful team without compromise.
846
- - You must be extremely accurate and conservative on "serious work" \u2014 never misclassify a real task as casual.
842
+ ## Professional Context (White Paper / NVIDIA / Replit / Cloud / Production Level)
843
+ - This system is used for serious senior-level development: production systems, luxury web apps, full frontend stores, complex multi-file React/TS projects, architecture, PRDs.
844
+ - Casual chat must be handled lightly and fast by Hablas solo (no team theatre).
845
+ - Serious engineering (build, create, fix, implement, frontend, web project, store, luxury, senior, architecture, code, files, PRD, "unfinished", "continue", "follow up", "one step", "finished", "no ask", "just give me", "deliver complete", "run it") MUST trigger the FULL powerful team (Hablas + Bob + Alex + David + Emma) at \u0623\u0642\u0635\u0649 \u0648\u0636\u0639 with strict centralization to Leader (Hablas) ONLY.
846
+ - You are extremely accurate and conservative: a real development request must NEVER be routed to "casual". Short length alone is NEVER enough if there is ANY engineering signal.
847
+ - Default for any ambiguity in professional context: BUILD.
847
848
 
848
- ## Your Task
849
- Analyze the user's raw input and output a single structured decision in this exact format (no extra text, no markdown):
849
+ ## Your Task (STRICT OUTPUT FORMAT \u2014 NO EXCEPTIONS)
850
+ Analyze the user's raw input and output EXACTLY three lines. No extra text, no markdown, no thinking, no XML, no "I think", no explanations outside the format:
850
851
 
851
852
  MODE: [casual | build | design | ask]
852
853
  CONFIDENCE: [0.0-1.0]
853
- REASON: [one short professional sentence explaining the routing]
854
-
855
- ## Routing Rules (Very Strict \u2014 Professional Grade)
856
- - MODE = "casual": Pure social, greetings, short confirmations, "\u0627\u0647", "hi", "thanks", "ok", "\u0643\u064A\u0641\u0643", very short non-action messages (< 15 chars with no engineering intent). These should be handled lightly by Hablas alone for speed.
857
- - MODE = "build": The default for any real work. Any mention of creating, fixing, implementing, building, planning, architecture, code changes, features, debugging, deployment, tests, or multi-step engineering tasks. When in doubt for professional work, choose "build".
858
- - MODE = "design": Explicit focus on architecture, blueprints, PRDs, requirements, system design, or high-level planning without immediate implementation.
859
- - MODE = "ask": Quick factual questions, explanations, or single-shot information requests that do not require team execution.
860
-
861
- ## Critical Professional Constraints (Repeated for Reliability)
862
- - ALWAYS prioritize accuracy for engineering work. A real development request must NEVER be routed to "casual".
863
- - Consider the full context of professional software engineering (files, systems, production implications).
864
- - If the input is ambiguous but contains any engineering signal (code words, "system", "architecture", "implement", "fix", "add feature", Arabic equivalents like "\u0627\u0628\u0646\u064A", "\u0635\u0644\u062D", "\u062E\u0637\u0629", "\u062A\u0635\u0645\u064A\u0645"), default to "build".
865
- - Short length alone is NOT enough to choose "casual" if there is clear engineering intent.
866
- - You are the strong layer that protects the team from wasting power on trivia while ensuring nothing important is under-served.
867
- - Output ONLY the three lines in the exact format above. No other text.
868
-
869
- ## STRENGTHENED RULES (Tool & Output Discipline)
870
- NEVER output tool calls as visible text.
871
- Use only the proper tool_calls mechanism if you ever need tools (rare for pure analysis).
872
- Stay strictly in your hidden executive role.
873
- Be terse, precise, and authoritative in your REASON.
874
- This decision directly controls whether the full multi-agent theatre (Hablas + Bob + Alex + David + Emma at maximum power) is activated.
875
-
876
- Analyze the following user input and produce the decision:`,toolPreferences:[],behaviorModifiers:{planFirst:!1,maxIterations:3,verbosity:"concise",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!1,canDelegate:!1,contextPriority:"requirements"}}});function br(){let n=new cs;return n.register(ya),n.register(va),n.register(xa),n.register(_a),n.register(Aa),n.register(Ca),n.register(Ta),n.register(Oa),n.register(Ma),n.register(Da),n}var Fa=L(()=>{"use strict";ga();ba();wa();Sa();ka();$a();Ea();Ra();Pa();Ia();La();ga();ba();wa();Sa();ka();$a();Ea();Ra();Pa();Ia();La()});var vr,Np=L(()=>{"use strict";vr=class{tasks=[];nextId=1;add(e){let t={id:this.nextId++,description:e,status:"pending",createdAt:Date.now()};return this.tasks.push(t),t}addBatch(e){return e.map(t=>this.add(t))}next(){return this.tasks.find(e=>e.status==="pending")}start(e){let t=this.tasks.find(s=>s.id===e);t&&(t.status="running")}complete(e,t){let s=this.tasks.find(r=>r.id===e);s&&(s.status="done",s.result=t,s.completedAt=Date.now())}fail(e,t){let s=this.tasks.find(r=>r.id===e);s&&(s.status="failed",s.error=t,s.completedAt=Date.now())}skip(e){let t=this.tasks.find(s=>s.id===e);t&&(t.status="skipped",t.completedAt=Date.now())}getAll(){return[...this.tasks]}getProgress(){let e=this.tasks.length,t=this.tasks.filter(o=>o.status==="done").length,s=this.tasks.filter(o=>o.status==="failed").length,r=this.tasks.filter(o=>o.status==="pending").length,i=this.tasks.filter(o=>o.status==="running").length;return{total:e,done:t,failed:s,pending:r,running:i}}isComplete(){return this.tasks.every(e=>e.status==="done"||e.status==="failed"||e.status==="skipped")}clear(){this.tasks=[],this.nextId=1}render(){if(this.tasks.length===0)return" No tasks in queue";let e={pending:"\u25CB",running:"\u25C9",done:"\u2713",failed:"\u2717",skipped:"\u2013"},t=this.tasks.map(r=>{let i=e[r.status],o=r.completedAt?` (${Math.round((r.completedAt-r.createdAt)/1e3)}s)`:"";return` ${i} ${r.id}. ${r.description}${o}`}),s=this.getProgress();return t.push(""),t.push(` Progress: ${s.done}/${s.total} done`+(s.failed>0?`, ${s.failed} failed`:"")),t.join(`
877
- `)}}});var Le,wr,jp,Hp,On,us,Bp=L(()=>{"use strict";Le=O(require("fs")),wr=O(require("path")),jp=O(require("os")),Hp=O(require("crypto")),On=wr.join(jp.homedir(),".hablas","memory"),us=class{entries=new Map;agentLanes=new Map;projectHash;filePath;agentLanesPath;constructor(e){this.projectHash=Hp.createHash("md5").update(e).digest("hex").slice(0,12),this.filePath=wr.join(On,`${this.projectHash}.json`),this.agentLanesPath=wr.join(On,`${this.projectHash}_agents.json`),this.load()}set(e,t,s){let r=this.entries.get(e),i=Date.now(),o=s?.category||"note";this.entries.set(e,{key:e,value:t,category:o,importance:s?.importance??this.autoImportance(o,t),createdBy:s?.createdBy||"hablas",accessCount:r?.accessCount??0,useCount:r?.useCount??0,tags:s?.tags||this.autoTag(t,o),relatedFiles:s?.relatedFiles||this.extractFileRefs(t),createdAt:r?.createdAt??i,updatedAt:i,lastAccessedAt:i,consolidatedFrom:r?.consolidatedFrom}),this.save()}get(e){let t=this.entries.get(e);return t&&(t.accessCount++,t.lastAccessedAt=Date.now()),t?.value}getEntry(e){return this.entries.get(e)}markUsed(e){let t=this.entries.get(e);t&&(t.useCount++,t.importance=Math.min(10,t.importance+.5))}delete(e){let t=this.entries.delete(e);return t&&this.save(),t}setAgentMemory(e,t,s,r="agent-learning"){let i=this.agentLanes.get(e);i||(i=new Map,this.agentLanes.set(e,i));let o=Date.now(),a=i.get(t);i.set(t,{key:t,value:s,category:r,importance:this.autoImportance(r,s),createdBy:e,accessCount:a?.accessCount??0,useCount:a?.useCount??0,tags:this.autoTag(s,r),relatedFiles:this.extractFileRefs(s),createdAt:a?.createdAt??o,updatedAt:o,lastAccessedAt:o}),this.saveAgentLanes()}getAgentMemories(e){let t=this.agentLanes.get(e);return t?Array.from(t.values()):[]}getAgentMemorySummary(e,t=10){let s=this.getAgentMemories(e),r=this.getAll().filter(a=>a.importance>=5||a.useCount>=2),i=[...s,...r].sort((a,l)=>{let u=a.importance*(1+a.useCount*.3);return l.importance*(1+l.useCount*.3)-u}).slice(0,t);return i.length===0?"":`## Agent Memory
854
+ REASON: [one short professional sentence explaining the routing, max 120 chars]
855
+
856
+ ## Routing Rules \u2014 STRENGTHENED TO PERFECTION (Repeated for Zero Errors)
857
+ - MODE = "casual": ONLY pure social/greetings/confirmations with ZERO engineering content. Examples: "hi", "hello sir", "thanks", "ok", "\u0627\u0647", "\u0643\u064A\u0641\u0643", "yes", "good", very short <15-20 chars, NO project words, NO "build/create/fix/frontend/web/store/project/flower/luxury/react/typescript/architecture/prd/code/files/unfinished/continue/one step/finished/no ask/deliver/complete".
858
+ - MODE = "build": THE DEFAULT AND SAFE CHOICE for 95%+ of professional use. ANY mention of creating, building, fixing, implementing, frontend, web, store, luxury, senior level, react, typescript, architecture, PRD, code changes, features, debugging, deployment, tests, multi-step engineering, "unfinished project", "this and there", "continue", "follow up", "from the previous PRD", "one step", "finished project", "no ask me any thing", "just give me", "deliver complete", "run it in one step". When in doubt for any engineering signal \u2192 "build".
859
+ - MODE = "design": ONLY when the request is EXPLICITLY high-level design/blueprint/architecture/PRD/requirements WITHOUT immediate implementation request.
860
+ - MODE = "ask": Quick factual questions, explanations, single-shot info requests that do not require team execution or file changes.
861
+
862
+ ## CRITICAL PROFESSIONAL CONSTRAINTS (Zero Black Holes)
863
+ - ALWAYS prioritize accuracy for engineering work. Real dev request \u2192 NEVER "casual".
864
+ - Consider full context of senior software engineering (files, systems, production, continuity from prior PRDs/architecture/src).
865
+ - If input mentions "unfinished", "unfinshed", "this and there", "previous", "continue the ... project", "from the PRD" \u2192 ALWAYS "build" + note continuity.
866
+ - If input has "finished ... one step no ask" / "just give me a finished web project to run it in one step no ask me any thing" / "deliver complete" / "no questions" \u2192 ALWAYS "build" + special "one-step finished" handling.
867
+ - Short length alone is NOT enough for "casual" if ANY engineering word or project reference.
868
+ - You are the strong layer that protects the team from wasting power on trivia while ensuring NOTHING important is under-served.
869
+ - Output ONLY the three lines in exact format. No other text ever.
870
+
871
+ ## FEW-SHOT EXAMPLES (Exact User Cases from Real Logs \u2014 Memorize Perfectly)
872
+ Example 1 (Pure greeting \u2014 casual):
873
+ User input: "hi sir"
874
+ MODE: casual
875
+ CONFIDENCE: 1.0
876
+ REASON: Simple greeting with no engineering intent, suitable for light quick handling.
877
+
878
+ Example 2 (Full flower store unfinished \u2014 build + continuity):
879
+ User input: "full flower store just frontend senior level this and there unfinshed project"
880
+ MODE: build
881
+ CONFIDENCE: 0.98
882
+ REASON: Explicit senior-level frontend flower store request referencing unfinished prior work. Requires full multi-agent team with strict continuity (re-use PRD/architecture/src). Centralized to Hablas only.
883
+
884
+ Example 3 (Finished web project one step no ask \u2014 build + one-step complete delivery):
885
+ User input: "sir just give me a finished wep project to run it in one step no ask me any thing"
886
+ MODE: build
887
+ CONFIDENCE: 0.99
888
+ REASON: Direct command for complete finished web project in ONE STEP with explicit "no ask". Force full team centralized execution. Deliver runnable project immediately, bypass all questions/blockers.
889
+
890
+ Example 4 (Short confirmation \u2014 casual):
891
+ User input: "ok"
892
+ MODE: casual
893
+ CONFIDENCE: 1.0
894
+ REASON: Short confirmation with no action or engineering content.
895
+
896
+ Example 5 (Complex senior frontend build \u2014 build):
897
+ User input: "ok React TypeScript just front no need backend use picture from internet wep + store lexury very nice front needed"
898
+ MODE: build
899
+ CONFIDENCE: 0.97
900
+ REASON: Clear senior frontend luxury store implementation request with specific tech and image requirements. Full team BUILD mode, centralized to leader.
901
+
902
+ Example 6 (Design explicit \u2014 design):
903
+ User input: "design the architecture for the new auth system"
904
+ MODE: design
905
+ CONFIDENCE: 0.92
906
+ REASON: Explicit high-level architecture design request without immediate coding. Design-focused team path.
907
+
908
+ Example 7 (Quick question \u2014 ask):
909
+ User input: "what is the current version of the project"
910
+ MODE: ask
911
+ CONFIDENCE: 0.88
912
+ REASON: Quick factual question suitable for focused solo response.
913
+
914
+ Example 8 (Continue unfinished \u2014 build + continuity):
915
+ User input: "continue the flower store project from the previous PRD and architecture docs"
916
+ MODE: build
917
+ CONFIDENCE: 0.98
918
+ REASON: Follow-up on prior unfinished work. Requires full team with continuity injection (load existing PRD-flower-store.md, architecture/flower-store-frontend-architecture.md, current src/ without restarting analysis from zero).
919
+
920
+ Example 9 (One step finished no questions \u2014 build + deliver complete):
921
+ User input: "just give me the complete finished project no questions"
922
+ MODE: build
923
+ CONFIDENCE: 0.99
924
+ REASON: Explicit "finished" "complete" "no questions" command. One-step delivery path: produce all files ready to run, no blockers.
925
+
926
+ Example 10 (Senior build with files \u2014 build):
927
+ User input: "create a full luxury store frontend with react typescript using pictures from internet"
928
+ MODE: build
929
+ CONFIDENCE: 0.96
930
+ REASON: Senior-level complete frontend store build request. Full multi-agent execution, centralized to Hablas, use full reads of any prior context.
931
+
932
+ ## STRENGTHENED RULES FOR ALL (Tool & Output Discipline \u2014 Zero Leaks)
933
+ - NEVER output tool calls as visible text, JSON, or XML.
934
+ - Use only the proper tool_calls mechanism if you ever need tools (rare for pure analysis \u2014 you almost never need tools).
935
+ - Stay strictly in your hidden executive role. Never mention "Gate" or your name.
936
+ - Be terse, precise, and authoritative in your REASON.
937
+ - This decision directly controls whether the full multi-agent theatre (Hablas + Bob + Alex + David + Emma at maximum power, centralizedToLeader:true) is activated or fast solo Hablas.
938
+ - For "build" with continuity or one-step signals, the downstream system will inject special instructions: continuity re-use of prior files + "Deliver the COMPLETE runnable finished project in this single turn. NO questions, NO blockers, NO clarification. Produce ALL files ready to npm run dev."
939
+
940
+ Analyze the following user input and produce the decision in EXACT format:`,toolPreferences:[],behaviorModifiers:{planFirst:!1,maxIterations:3,verbosity:"concise",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!1,canDelegate:!1,contextPriority:"requirements"}}});function wr(){let n=new us;return n.register(wa),n.register(Sa),n.register(ka),n.register($a),n.register(Ea),n.register(Ra),n.register(Pa),n.register(Ia),n.register(La),n.register(Fa),n}var Ha=L(()=>{"use strict";va();xa();_a();Aa();Ca();Ta();Oa();Ma();Da();Na();ja();va();xa();_a();Aa();Ca();Ta();Oa();Ma();Da();Na();ja()});var xr,qp=L(()=>{"use strict";xr=class{tasks=[];nextId=1;add(e){let t={id:this.nextId++,description:e,status:"pending",createdAt:Date.now()};return this.tasks.push(t),t}addBatch(e){return e.map(t=>this.add(t))}next(){return this.tasks.find(e=>e.status==="pending")}start(e){let t=this.tasks.find(s=>s.id===e);t&&(t.status="running")}complete(e,t){let s=this.tasks.find(r=>r.id===e);s&&(s.status="done",s.result=t,s.completedAt=Date.now())}fail(e,t){let s=this.tasks.find(r=>r.id===e);s&&(s.status="failed",s.error=t,s.completedAt=Date.now())}skip(e){let t=this.tasks.find(s=>s.id===e);t&&(t.status="skipped",t.completedAt=Date.now())}getAll(){return[...this.tasks]}getProgress(){let e=this.tasks.length,t=this.tasks.filter(o=>o.status==="done").length,s=this.tasks.filter(o=>o.status==="failed").length,r=this.tasks.filter(o=>o.status==="pending").length,i=this.tasks.filter(o=>o.status==="running").length;return{total:e,done:t,failed:s,pending:r,running:i}}isComplete(){return this.tasks.every(e=>e.status==="done"||e.status==="failed"||e.status==="skipped")}clear(){this.tasks=[],this.nextId=1}render(){if(this.tasks.length===0)return" No tasks in queue";let e={pending:"\u25CB",running:"\u25C9",done:"\u2713",failed:"\u2717",skipped:"\u2013"},t=this.tasks.map(r=>{let i=e[r.status],o=r.completedAt?` (${Math.round((r.completedAt-r.createdAt)/1e3)}s)`:"";return` ${i} ${r.id}. ${r.description}${o}`}),s=this.getProgress();return t.push(""),t.push(` Progress: ${s.done}/${s.total} done`+(s.failed>0?`, ${s.failed} failed`:"")),t.join(`
941
+ `)}}});var Le,Sr,Kp,Wp,Pn,ds,Gp=L(()=>{"use strict";Le=O(require("fs")),Sr=O(require("path")),Kp=O(require("os")),Wp=O(require("crypto")),Pn=Sr.join(Kp.homedir(),".hablas","memory"),ds=class{entries=new Map;agentLanes=new Map;projectHash;filePath;agentLanesPath;constructor(e){this.projectHash=Wp.createHash("md5").update(e).digest("hex").slice(0,12),this.filePath=Sr.join(Pn,`${this.projectHash}.json`),this.agentLanesPath=Sr.join(Pn,`${this.projectHash}_agents.json`),this.load()}set(e,t,s){let r=this.entries.get(e),i=Date.now(),o=s?.category||"note";this.entries.set(e,{key:e,value:t,category:o,importance:s?.importance??this.autoImportance(o,t),createdBy:s?.createdBy||"hablas",accessCount:r?.accessCount??0,useCount:r?.useCount??0,tags:s?.tags||this.autoTag(t,o),relatedFiles:s?.relatedFiles||this.extractFileRefs(t),createdAt:r?.createdAt??i,updatedAt:i,lastAccessedAt:i,consolidatedFrom:r?.consolidatedFrom}),this.save()}get(e){let t=this.entries.get(e);return t&&(t.accessCount++,t.lastAccessedAt=Date.now()),t?.value}getEntry(e){return this.entries.get(e)}markUsed(e){let t=this.entries.get(e);t&&(t.useCount++,t.importance=Math.min(10,t.importance+.5))}delete(e){let t=this.entries.delete(e);return t&&this.save(),t}setAgentMemory(e,t,s,r="agent-learning"){let i=this.agentLanes.get(e);i||(i=new Map,this.agentLanes.set(e,i));let o=Date.now(),a=i.get(t);i.set(t,{key:t,value:s,category:r,importance:this.autoImportance(r,s),createdBy:e,accessCount:a?.accessCount??0,useCount:a?.useCount??0,tags:this.autoTag(s,r),relatedFiles:this.extractFileRefs(s),createdAt:a?.createdAt??o,updatedAt:o,lastAccessedAt:o}),this.saveAgentLanes()}getAgentMemories(e){let t=this.agentLanes.get(e);return t?Array.from(t.values()):[]}getAgentMemorySummary(e,t=10){let s=this.getAgentMemories(e),r=this.getAll().filter(a=>a.importance>=5||a.useCount>=2),i=[...s,...r].sort((a,l)=>{let u=a.importance*(1+a.useCount*.3);return l.importance*(1+l.useCount*.3)-u}).slice(0,t);return i.length===0?"":`## Agent Memory
878
942
  `+i.map(a=>`- [${a.category}${a.importance>=7?" \u2605":""}] ${a.key}: ${a.value}`).join(`
879
943
  `)}search(e,t){let s=e.toLowerCase(),r=s.split(/\s+/).filter(l=>l.length>2),i=t?.maxResults||20,o=[],a=t?.agent?this.getAgentMemories(t.agent):this.getAll();for(let l of a){if(t?.category&&l.category!==t.category||t?.minImportance&&l.importance<t.minImportance)continue;let u=0,d="partial";l.key.toLowerCase()===s&&(u+=10,d="exact"),l.key.toLowerCase().includes(s)&&(u+=5),l.value.toLowerCase().includes(s)&&(u+=3);for(let h of r)l.key.toLowerCase().includes(h)&&(u+=2),l.value.toLowerCase().includes(h)&&(u+=1),l.tags.some(m=>m.toLowerCase().includes(h))&&(u+=2,d=d==="exact"?"exact":"tag");u*=1+l.importance*.1,u*=1+l.useCount*.2;let f=(Date.now()-l.updatedAt)/(10080*60*1e3);u*=Math.max(.3,1-f*.1),u>.5&&o.push({entry:l,relevanceScore:u,matchType:d})}return o.sort((l,u)=>u.relevanceScore-l.relevanceScore).slice(0,i)}getAll(e){let t=Array.from(this.entries.values());return e?t.filter(s=>s.category===e):t}getByFile(e){return Array.from(this.entries.values()).filter(t=>t.relatedFiles.some(s=>s.includes(e)||e.includes(s)))}getTopMemories(e=15){return Array.from(this.entries.values()).sort((t,s)=>{let r=t.importance*(1+t.useCount*.3)*(1+Math.log1p(t.accessCount)*.1);return s.importance*(1+s.useCount*.3)*(1+Math.log1p(s.accessCount)*.1)-r}).slice(0,e)}getSummary(){let e=this.getTopMemories(15);if(e.length===0)return"";let t={};for(let r of e){let i=r.category;t[i]||(t[i]=[]),t[i].push(`${r.key}: ${r.value}`)}let s=["## Project Memory"];for(let[r,i]of Object.entries(t)){s.push(`### ${r}`);for(let o of i)s.push(`- ${o}`)}return s.join(`
880
944
  `)}getStats(){let e=this.getAll(),t={},s={};for(let r of e)t[r.category]=(t[r.category]||0)+1,s[r.createdBy]=(s[r.createdBy]||0)+1;return{totalEntries:e.length,byCategory:t,byAgent:s,topAccessed:e.sort((r,i)=>i.accessCount-r.accessCount).slice(0,5),recentlyAdded:e.sort((r,i)=>i.createdAt-r.createdAt).slice(0,5),totalAccessCount:e.reduce((r,i)=>r+i.accessCount,0)}}consolidate(e=200){if(this.entries.size<=e)return 0;let t=Array.from(this.entries.values()).filter(o=>o.importance<4&&o.accessCount<3).sort((o,a)=>o.updatedAt-a.updatedAt),s=t.slice(0,Math.max(10,t.length-e)),r={};for(let o of s){let a=o.category;r[a]||(r[a]=[]),r[a].push(o)}let i=0;for(let[o,a]of Object.entries(r)){if(a.length<2)continue;let l=`[consolidated] ${o} (${a.length} items)`,u=a.map(h=>`${h.key}: ${h.value}`).join("; "),d=a.map(h=>h.key);this.set(l,u.slice(0,500),{category:o,importance:3,tags:["consolidated"]});let f=this.entries.get(l);f&&(f.consolidatedFrom=d);for(let h of a)this.entries.delete(h.key),i++}return i>0&&this.save(),i}learnFromToolResult(e,t,s,r,i="hablas"){if(!(s.length<20)){if(!r){let o=`error:${e}:${JSON.stringify(t).slice(0,50)}`,a=this.entries.get(o);a?(a.useCount++,a.importance=Math.min(10,a.importance+1)):this.set(o,`${e} failed with: ${s.slice(0,200)}`,{category:"error",importance:6,createdBy:i,tags:["auto-learned","error",e]})}if(e==="list_dir"&&r){let o=t.path||".";this.set(`structure:${o}`,s.slice(0,300),{category:"pattern",importance:3,createdBy:i,tags:["auto-learned","structure"],relatedFiles:[o]})}}}size(){return this.entries.size}clear(){this.entries.clear(),this.agentLanes.clear(),this.save(),this.saveAgentLanes()}render(){if(this.getAll().length===0)return" No project memories stored";let t={convention:"\u{1F4CF}",decision:"\u{1F3AF}",pattern:"\u{1F504}",note:"\u{1F4DD}",error:"\u26A0\uFE0F","tool-result":"\u{1F527}","user-pref":"\u{1F464}",dependency:"\u{1F4E6}",performance:"\u26A1",security:"\u{1F512}",api:"\u{1F310}","agent-learning":"\u{1F916}"};return this.getTopMemories(20).map(i=>{let o=t[i.category]||"\xB7",a=i.importance>=7?" \u2605":"",l=i.useCount>0?` (used ${i.useCount}\xD7)`:"";return` ${o}${a} ${i.key}: ${i.value}${l}`}).join(`
881
- `)}autoImportance(e,t){let r={convention:6,decision:8,pattern:5,note:3,error:7,"tool-result":2,"user-pref":7,dependency:4,performance:5,security:9,api:6,"agent-learning":4}[e]||3;return/\b(important|critical|must|always|never|danger|warning|breaking)\b/i.test(t)&&(r=Math.min(10,r+2)),r}autoTag(e,t){let s=[t];return/\b(react|vue|angular|svelte|next|nuxt)\b/i.test(e)&&s.push("frontend"),/\b(express|fastify|nest|koa|hapi)\b/i.test(e)&&s.push("backend"),/\b(postgres|mysql|mongo|redis|sqlite)\b/i.test(e)&&s.push("database"),/\b(docker|kubernetes|k8s|ci\/cd|deploy)\b/i.test(e)&&s.push("devops"),/\b(test|jest|vitest|cypress|playwright)\b/i.test(e)&&s.push("testing"),/\b(auth|jwt|oauth|session|token)\b/i.test(e)&&s.push("auth"),/\b(api|endpoint|route|rest|graphql)\b/i.test(e)&&s.push("api"),s}extractFileRefs(e){let t=/[\w\-./]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|scss|html|vue|svelte|go|rs|java|sql|sh|toml|xml|env)/gi,s=e.match(t);return s?[...new Set(s)]:[]}load(){try{if(Le.existsSync(this.filePath)){let e=JSON.parse(Le.readFileSync(this.filePath,"utf-8"));if(Array.isArray(e))for(let t of e)t.importance||(t.importance=3),t.createdBy||(t.createdBy="hablas"),t.accessCount||(t.accessCount=0),t.useCount||(t.useCount=0),t.tags||(t.tags=[t.category||"note"]),t.relatedFiles||(t.relatedFiles=[]),t.lastAccessedAt||(t.lastAccessedAt=t.updatedAt||Date.now()),this.entries.set(t.key,t)}}catch{}this.loadAgentLanes()}save(){try{Le.existsSync(On)||Le.mkdirSync(On,{recursive:!0});let e=Array.from(this.entries.values());Le.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf-8")}catch{}}loadAgentLanes(){try{if(Le.existsSync(this.agentLanesPath)){let e=JSON.parse(Le.readFileSync(this.agentLanesPath,"utf-8"));for(let[t,s]of Object.entries(e)){let r=new Map;for(let i of s)r.set(i.key,i);this.agentLanes.set(t,r)}}}catch{}}saveAgentLanes(){try{Le.existsSync(On)||Le.mkdirSync(On,{recursive:!0});let e={};for(let[t,s]of this.agentLanes)e[t]=Array.from(s.values());Le.writeFileSync(this.agentLanesPath,JSON.stringify(e,null,2),"utf-8")}catch{}}}});var ja=N((LT,Kp)=>{"use strict";var ds=n=>n&&typeof n.message=="string",Na=n=>{if(!n)return;let e=n.cause;if(typeof e=="function"){let t=n.cause();return ds(t)?t:void 0}else return ds(e)?e:void 0},Up=(n,e)=>{if(!ds(n))return"";let t=n.stack||"";if(e.has(n))return t+`
882
- causes have become circular...`;let s=Na(n);return s?(e.add(n),t+`
883
- caused by: `+Up(s,e)):t},Zx=n=>Up(n,new Set),qp=(n,e,t)=>{if(!ds(n))return"";let s=t?"":n.message||"";if(e.has(n))return s+": ...";let r=Na(n);if(r){e.add(n);let i=typeof n.cause=="function";return s+(i?"":": ")+qp(r,e,i)}else return s},eS=n=>qp(n,new Set);Kp.exports={isErrorLike:ds,getErrorCause:Na,stackWithCauses:Zx,messageWithCauses:eS}});var Ha=N((FT,Gp)=>{"use strict";var tS=Symbol("circular-ref-tag"),xr=Symbol("pino-raw-err-ref"),Wp=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[xr]},set:function(n){this[xr]=n}}});Object.defineProperty(Wp,xr,{writable:!0,value:{}});Gp.exports={pinoErrProto:Wp,pinoErrorSymbols:{seen:tS,rawSymbol:xr}}});var Yp=N((NT,zp)=>{"use strict";zp.exports=Ua;var{messageWithCauses:nS,stackWithCauses:sS,isErrorLike:Vp}=ja(),{pinoErrProto:rS,pinoErrorSymbols:iS}=Ha(),{seen:Ba}=iS,{toString:oS}=Object.prototype;function Ua(n){if(!Vp(n))return n;n[Ba]=void 0;let e=Object.create(rS);e.type=oS.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=nS(n),e.stack=sS(n),Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>Ua(t)));for(let t in n)if(e[t]===void 0){let s=n[t];Vp(s)?t!=="cause"&&!Object.prototype.hasOwnProperty.call(s,Ba)&&(e[t]=Ua(s)):e[t]=s}return delete n[Ba],e.raw=n,e}});var Xp=N((jT,Jp)=>{"use strict";Jp.exports=_r;var{isErrorLike:qa}=ja(),{pinoErrProto:aS,pinoErrorSymbols:lS}=Ha(),{seen:Sr}=lS,{toString:cS}=Object.prototype;function _r(n){if(!qa(n))return n;n[Sr]=void 0;let e=Object.create(aS);e.type=cS.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=n.message,e.stack=n.stack,Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>_r(t))),qa(n.cause)&&!Object.prototype.hasOwnProperty.call(n.cause,Sr)&&(e.cause=_r(n.cause));for(let t in n)if(e[t]===void 0){let s=n[t];qa(s)?Object.prototype.hasOwnProperty.call(s,Sr)||(e[t]=_r(s)):e[t]=s}return delete n[Sr],e.raw=n,e}});var th=N((HT,eh)=>{"use strict";eh.exports={mapHttpRequest:uS,reqSerializer:Zp};var Ka=Symbol("pino-raw-req-ref"),Qp=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Ka]},set:function(n){this[Ka]=n}}});Object.defineProperty(Qp,Ka,{writable:!0,value:{}});function Zp(n){let e=n.info||n.socket,t=Object.create(Qp);if(t.id=typeof n.id=="function"?n.id():n.id||(n.info?n.info.id:void 0),t.method=n.method,n.originalUrl)t.url=n.originalUrl;else{let s=n.path;t.url=typeof s=="string"?s:n.url?n.url.path||n.url:void 0}return n.query&&(t.query=n.query),n.params&&(t.params=n.params),t.headers=n.headers,t.remoteAddress=e&&e.remoteAddress,t.remotePort=e&&e.remotePort,t.raw=n.raw||n,t}function uS(n){return{req:Zp(n)}}});var ih=N((BT,rh)=>{"use strict";rh.exports={mapHttpResponse:dS,resSerializer:sh};var Wa=Symbol("pino-raw-res-ref"),nh=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Wa]},set:function(n){this[Wa]=n}}});Object.defineProperty(nh,Wa,{writable:!0,value:{}});function sh(n){let e=Object.create(nh);return e.statusCode=n.headersSent?n.statusCode:null,e.headers=n.getHeaders?n.getHeaders():n._headers,e.raw=n,e}function dS(n){return{res:sh(n)}}});var Va=N((UT,oh)=>{"use strict";var Ga=Yp(),fS=Xp(),kr=th(),Ar=ih();oh.exports={err:Ga,errWithCause:fS,mapHttpRequest:kr.mapHttpRequest,mapHttpResponse:Ar.mapHttpResponse,req:kr.reqSerializer,res:Ar.resSerializer,wrapErrorSerializer:function(e){return e===Ga?e:function(s){return e(Ga(s))}},wrapRequestSerializer:function(e){return e===kr.reqSerializer?e:function(s){return e(kr.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===Ar.resSerializer?e:function(s){return e(Ar.resSerializer(s))}}}});var za=N((qT,ah)=>{"use strict";function pS(n,e){return e}ah.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=pS;let t=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let s=t.slice(2),r=[];for(let i of s)i&&r.push(i.getFileName());return r}});var ph=N((KT,fh)=>{"use strict";function Ya(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof Array){let e=[];for(let t=0;t<n.length;t++)e[t]=Ya(n[t]);return e}if(typeof n=="object"){let e=Object.create(Object.getPrototypeOf(n));for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=Ya(n[t]));return e}return n}function lh(n){let e=[],t="",s=!1,r=!1,i="";for(let o=0;o<n.length;o++){let a=n[o];!s&&a==="."?t&&(e.push(t),t=""):a==="["?(t&&(e.push(t),t=""),s=!0):a==="]"&&s?(e.push(t),t="",s=!1,r=!1):(a==='"'||a==="'")&&s?r?a===i?(r=!1,i=""):t+=a:(r=!0,i=a):t+=a}return t&&e.push(t),e}function ch(n,e,t){let s=n;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof s!="object"||s===null||!(o in s)||typeof s[o]!="object"||s[o]===null)return!1;s=s[o]}let r=e[e.length-1];if(r==="*"){if(Array.isArray(s))for(let i=0;i<s.length;i++)s[i]=t;else if(typeof s=="object"&&s!==null)for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&(s[i]=t)}else typeof s=="object"&&s!==null&&r in s&&Object.prototype.hasOwnProperty.call(s,r)&&(s[r]=t);return!0}function uh(n,e){let t=n;for(let r=0;r<e.length-1;r++){let i=e[r];if(typeof t!="object"||t===null||!(i in t)||typeof t[i]!="object"||t[i]===null)return!1;t=t[i]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(t))for(let r=0;r<t.length;r++)t[r]=void 0;else if(typeof t=="object"&&t!==null)for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&delete t[r]}else typeof t=="object"&&t!==null&&s in t&&Object.prototype.hasOwnProperty.call(t,s)&&delete t[s];return!0}var $r=Symbol("PATH_NOT_FOUND");function hS(n,e){let t=n;for(let s of e){if(t==null||typeof t!="object"||t===null||!(s in t))return $r;t=t[s]}return t}function mS(n,e){let t=n;for(let s of e){if(t==null||typeof t!="object"||t===null)return;t=t[s]}return t}function gS(n,e,t,s=!1){for(let r of e){let i=lh(r);if(i.includes("*"))dh(n,i,t,r,s);else if(s)uh(n,i);else{let o=hS(n,i);if(o===$r)continue;let a=typeof t=="function"?t(o,i):t;ch(n,i,a)}}}function dh(n,e,t,s,r=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=n;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(r)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let u=[...o,l.toString()],d=typeof t=="function"?t(a[l],u):t;a[l]=d}else if(typeof a=="object"&&a!==null)if(r){let l=[];for(let u in a)Object.prototype.hasOwnProperty.call(a,u)&&l.push(u);for(let u of l)delete a[u]}else for(let l in a){let u=[...o,l],d=typeof t=="function"?t(a[l],u):t;a[l]=d}}else yS(n,e,t,i,s,r)}function yS(n,e,t,s,r,i=!1){let o=e.slice(0,s),a=e.slice(s+1),l=[];function u(d,f){if(f===o.length){if(Array.isArray(d))for(let h=0;h<d.length;h++)l[f]=h.toString(),u(d[h],f+1);else if(typeof d=="object"&&d!==null)for(let h in d)l[f]=h,u(d[h],f+1)}else if(f<o.length){let h=o[f];d&&typeof d=="object"&&d!==null&&h in d&&(l[f]=h,u(d[h],f+1))}else if(a.includes("*"))dh(d,a,typeof t=="function"?(m,p)=>{let g=[...l.slice(0,f),...p];return t(m,g)}:t,r,i);else if(i)uh(d,a);else{let h=typeof t=="function"?t(mS(d,a),[...l.slice(0,f),...a]):t;ch(d,a,h)}}if(o.length===0)u(n,0);else{let d=n;for(let f=0;f<o.length;f++){let h=o[f];if(d==null||typeof d!="object"||d===null)return;d=d[h],l[f]=h}d!=null&&u(d,o.length)}}function bS(n){if(n.length===0)return null;let e=new Map;for(let t of n){let s=lh(t),r=e;for(let i=0;i<s.length;i++){let o=s[i];r.has(o)||r.set(o,new Map),r=r.get(o)}}return e}function vS(n,e){if(!e)return n;function t(s,r,i=0){if(!r||r.size===0||s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(Array.isArray(s)){let a=[];for(let l=0;l<s.length;l++){let u=l.toString();r.has(u)||r.has("*")?a[l]=t(s[l],r.get(u)||r.get("*")):a[l]=s[l]}return a}let o=Object.create(Object.getPrototypeOf(s));for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&(r.has(a)||r.has("*")?o[a]=t(s[a],r.get(a)||r.get("*")):o[a]=s[a]);return o}return t(n,e)}function wS(n){if(typeof n!="string")throw new Error("Paths must be (non-empty) strings");if(n==="")throw new Error("Invalid redaction path ()");if(n.includes(".."))throw new Error(`Invalid redaction path (${n})`);if(n.includes(","))throw new Error(`Invalid redaction path (${n})`);let e=0,t=!1,s="";for(let r=0;r<n.length;r++){let i=n[r];if((i==='"'||i==="'")&&e>0)t?i===s&&(t=!1,s=""):(t=!0,s=i);else if(i==="["&&!t)e++;else if(i==="]"&&!t&&(e--,e<0))throw new Error(`Invalid redaction path (${n})`)}if(e!==0)throw new Error(`Invalid redaction path (${n})`)}function xS(n){if(!Array.isArray(n))throw new TypeError("paths must be an array");for(let e of n)wS(e)}function SS(n={}){let{paths:e=[],censor:t="[REDACTED]",serialize:s=JSON.stringify,strict:r=!0,remove:i=!1}=n;xS(e);let o=bS(e);return function(l){if(r&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return s?s(l):l;let u=vS(l,o),d=l,f=t;return typeof t=="function"&&(f=t),gS(u,e,f,i),s===!1?(u.restore=function(){return Ya(d)},u):typeof s=="function"?s(u):JSON.stringify(u)}}fh.exports=SS});var Pn=N((WT,hh)=>{"use strict";var _S=Symbol("pino.setLevel"),kS=Symbol("pino.getLevel"),AS=Symbol("pino.levelVal"),$S=Symbol("pino.levelComp"),CS=Symbol("pino.useLevelLabels"),ES=Symbol("pino.useOnlyCustomLevels"),TS=Symbol("pino.mixin"),RS=Symbol("pino.lsCache"),OS=Symbol("pino.chindings"),PS=Symbol("pino.asJson"),MS=Symbol("pino.write"),IS=Symbol("pino.redactFmt"),DS=Symbol("pino.time"),LS=Symbol("pino.timeSliceIndex"),FS=Symbol("pino.stream"),NS=Symbol("pino.stringify"),jS=Symbol("pino.stringifySafe"),HS=Symbol("pino.stringifiers"),BS=Symbol("pino.end"),US=Symbol("pino.formatOpts"),qS=Symbol("pino.messageKey"),KS=Symbol("pino.errorKey"),WS=Symbol("pino.nestedKey"),GS=Symbol("pino.nestedKeyStr"),VS=Symbol("pino.mixinMergeStrategy"),zS=Symbol("pino.msgPrefix"),YS=Symbol("pino.wildcardFirst"),JS=Symbol.for("pino.serializers"),XS=Symbol.for("pino.formatters"),QS=Symbol.for("pino.hooks"),ZS=Symbol.for("pino.metadata");hh.exports={setLevelSym:_S,getLevelSym:kS,levelValSym:AS,levelCompSym:$S,useLevelLabelsSym:CS,mixinSym:TS,lsCacheSym:RS,chindingsSym:OS,asJsonSym:PS,writeSym:MS,serializersSym:JS,redactFmtSym:IS,timeSym:DS,timeSliceIndexSym:LS,streamSym:FS,stringifySym:NS,stringifySafeSym:jS,stringifiersSym:HS,endSym:BS,formatOptsSym:US,messageKeySym:qS,errorKeySym:KS,nestedKeySym:WS,wildcardFirstSym:YS,needsMetadataGsym:ZS,useOnlyCustomLevelsSym:ES,formattersSym:XS,hooksSym:QS,nestedKeyStrSym:GS,mixinMergeStrategySym:VS,msgPrefixSym:zS}});var Xa=N((GT,bh)=>{"use strict";var mh=ph(),{redactFmtSym:e_,wildcardFirstSym:Cr}=Pn(),Ja=/[^.[\]]+|\[([^[\]]*?)\]/g,gh="[Redacted]",yh=!1;function t_(n,e){let{paths:t,censor:s,remove:r}=n_(n),i=t.reduce((l,u)=>{Ja.lastIndex=0;let d=Ja.exec(u),f=Ja.exec(u),h=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(h==="*"&&(h=Cr),f===null)return l[h]=null,l;if(l[h]===null)return l;let{index:m}=f,p=`${u.substr(m,u.length-1)}`;return l[h]=l[h]||[],h!==Cr&&l[h].length===0&&l[h].push(...l[Cr]||[]),h===Cr&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(p)}),l[h].push(p),l},{}),o={[e_]:mh({paths:t,censor:s,serialize:e,strict:yh,remove:r})},a=(...l)=>e(typeof s=="function"?s(...l):s);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,u)=>{if(i[u]===null)l[u]=d=>a(d,[u]);else{let d=typeof s=="function"?(f,h)=>s(f,[u,...h]):s;l[u]=mh({paths:i[u],censor:d,serialize:e,strict:yh,remove:r})}return l},o)}function n_(n){if(Array.isArray(n))return n={paths:n,censor:gh},n;let{paths:e,censor:t=gh,remove:s}=n;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return s===!0&&(t=void 0),{paths:e,censor:t,remove:s}}bh.exports=t_});var xh=N((VT,wh)=>{"use strict";var s_=()=>"",r_=()=>`,"time":${Date.now()}`,i_=()=>`,"time":${Math.round(Date.now()/1e3)}`,o_=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,a_=1000000n,vh=1000000000n,l_=BigInt(Date.now())*a_,c_=process.hrtime.bigint(),u_=()=>{let n=process.hrtime.bigint()-c_,e=l_+n,t=e/vh,s=e%vh,r=Number(t*1000n+s/1000000n),i=new Date(r),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),u=i.getUTCHours().toString().padStart(2,"0"),d=i.getUTCMinutes().toString().padStart(2,"0"),f=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${u}:${d}:${f}.${s.toString().padStart(9,"0")}Z"`};wh.exports={nullTime:s_,epochTime:r_,unixTime:i_,isoTime:o_,isoTimeNano:u_}});var _h=N((zT,Sh)=>{"use strict";function d_(n){try{return JSON.stringify(n)}catch{return'"[Circular]"'}}Sh.exports=f_;function f_(n,e,t){var s=t&&t.stringify||d_,r=1;if(typeof n=="object"&&n!==null){var i=e.length+r;if(i===1)return n;var o=new Array(i);o[0]=s(n);for(var a=1;a<i;a++)o[a]=s(e[a]);return o.join(" ")}if(typeof n!="string")return n;var l=e.length;if(l===0)return n;for(var u="",d=1-r,f=-1,h=n&&n.length||0,m=0;m<h;){if(n.charCodeAt(m)===37&&m+1<h){switch(f=f>-1?f:0,n.charCodeAt(m+1)){case 100:case 102:if(d>=l||e[d]==null)break;f<m&&(u+=n.slice(f,m)),u+=Number(e[d]),f=m+2,m++;break;case 105:if(d>=l||e[d]==null)break;f<m&&(u+=n.slice(f,m)),u+=Math.floor(Number(e[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||e[d]===void 0)break;f<m&&(u+=n.slice(f,m));var p=typeof e[d];if(p==="string"){u+="'"+e[d]+"'",f=m+2,m++;break}if(p==="function"){u+=e[d].name||"<anonymous>",f=m+2,m++;break}u+=s(e[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=n.slice(f,m)),u+=String(e[d]),f=m+2,m++;break;case 37:f<m&&(u+=n.slice(f,m)),u+="%",f=m+2,m++,d--;break}++d}++m}return f===-1?n:(f<h&&(u+=n.slice(f)),u)}});var Za=N((YT,Qa)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(n,0,0,Number(t))},n=new Int32Array(new SharedArrayBuffer(4));Qa.exports=e}else{let n=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let s=Date.now()+Number(e);for(;s>Date.now(););};Qa.exports=n}});var Oh=N((JT,Rh)=>{"use strict";var le=require("fs"),p_=require("events"),h_=require("util").inherits,kh=require("path"),tl=Za(),m_=require("assert"),Er=100,Tr=Buffer.allocUnsafe(0),g_=16*1024,Ah="buffer",$h="utf8",[y_,b_]=(process.versions.node||"0.0").split(".").map(Number),v_=y_>=22&&b_>=7;function Ch(n,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function t(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=n,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let s=e.append?"a":"w",r=e.mode;if(e.sync)try{e.mkdir&&le.mkdirSync(kh.dirname(n),{recursive:!0});let i=le.openSync(n,s,r);t(null,i)}catch(i){throw t(i),i}else e.mkdir?le.mkdir(kh.dirname(n),{recursive:!0},i=>{if(i)return t(i);le.open(n,s,r,t)}):le.open(n,s,r,t)}function at(n){if(!(this instanceof at))return new at(n);let{fd:e,dest:t,minLength:s,maxLength:r,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:u,retryEAGAIN:d,fsync:f,contentMode:h,mode:m}=n||{};e=e||t,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(s||0,16387),this.file=null,this.destroyed=!1,this.minLength=s||0,this.maxLength=r||0,this.maxWrite=i||g_,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=f||!1,this.append=l||!1,this.mode=m,this.retryEAGAIN=d||(()=>!0),this.mkdir=u||!1;let p,g;if(h===Ah)this._writingBuf=Tr,this.write=S_,this.flush=k_,this.flushSync=$_,this._actualWrite=E_,p=()=>le.writeSync(this.fd,this._writingBuf),g=()=>le.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===$h)this._writingBuf="",this.write=x_,this.flush=__,this.flushSync=A_,this._actualWrite=C_,p=()=>Buffer.isBuffer(this._writingBuf)?le.writeSync(this.fd,this._writingBuf):le.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>Buffer.isBuffer(this._writingBuf)?le.write(this.fd,this._writingBuf,this.release):le.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${$h}" and "${Ah}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Ch(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(x,w)=>{if(x){if((x.code==="EAGAIN"||x.code==="EBUSY")&&this.retryEAGAIN(x,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{tl(Er),this.release(void 0,0)}catch(y){this.release(y)}else setTimeout(g,Er);else this._writing=!1,this.emit("error",x);return}this.emit("write",w);let $=el(this._writingBuf,this._len,w);if(this._len=$.len,this._writingBuf=$.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let y=p(),v=el(this._writingBuf,this._len,y);this._len=v.len,this._writingBuf=v.writingBuf}while(this._writingBuf.length)}catch(y){this.release(y);return}}this._fsync&&le.fsyncSync(this.fd);let A=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):A>this.minLength?this._actualWrite():this._ending?A>0?this._actualWrite():(this._writing=!1,Rr(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(w_,this)):this.emit("drain"))},this.on("newListener",function(x){x==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function el(n,e,t){return typeof n=="string"&&(n=Buffer.from(n)),e=Math.max(e-t,0),n=n.subarray(t),{writingBuf:n,len:e}}function w_(n){n.listenerCount("drain")>0&&(n._asyncDrainScheduled=!1,n.emit("drain"))}h_(at,p_);function Eh(n,e){return n.length===0?Tr:n.length===1?n[0]:Buffer.concat(n,e)}function x_(n){if(this.destroyed)throw new Error("SonicBoom destroyed");n=""+n;let e=Buffer.byteLength(n),t=this._len+e,s=this._bufs;return this.maxLength&&t>this.maxLength?(this.emit("drop",n),this._len<this._hwm):(s.length===0||Buffer.byteLength(s[s.length-1])+e>this.maxWrite?s.push(n):s[s.length-1]+=n,this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function S_(n){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+n.length,t=this._bufs,s=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",n),this._len<this._hwm):(t.length===0||s[s.length-1]+n.length>this.maxWrite?(t.push([n]),s.push(n.length)):(t[t.length-1].push(n),s[s.length-1]+=n.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Th(n){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,n();else try{le.fsync(this.fd,s=>{this._flushPending=!1,n(s)})}catch(s){n(s)}this.off("error",t)},t=s=>{this._flushPending=!1,n(s),this.off("drain",e)};this.once("drain",e),this.once("error",t)}function __(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(n){n(e);return}throw e}if(this.minLength<=0){n?.();return}n&&Th.call(this,n),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function k_(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(n){n(e);return}throw e}if(this.minLength<=0){n?.();return}n&&Th.call(this,n),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}at.prototype.reopen=function(n){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(n)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(n&&(this.file=n),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&le.close(e,t=>{if(t)return this.emit("error",t)})}),Ch(this.file,this)};at.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():Rr(this)))};function A_(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let n="";for(;this._bufs.length||n.length;){n.length<=0&&(n=this._bufs[0]);try{let e=Buffer.isBuffer(n)?le.writeSync(this.fd,n):le.writeSync(this.fd,n,"utf8"),t=el(n,this._len,e);n=t.writingBuf,this._len=t.len,n.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,n.length,this._len-n.length))throw e;tl(Er)}}try{le.fsyncSync(this.fd)}catch{}}function $_(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=Tr);let n=Tr;for(;this._bufs.length||n.length;){n.length<=0&&(n=Eh(this._bufs[0],this._lens[0]));try{let e=le.writeSync(this.fd,n);n=n.subarray(e),this._len=Math.max(this._len-e,0),n.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,n.length,this._len-n.length))throw e;tl(Er)}}}at.prototype.destroy=function(){this.destroyed||Rr(this)};function C_(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?le.writeSync(this.fd,this._writingBuf):le.writeSync(this.fd,this._writingBuf,"utf8");n(null,e)}catch(e){n(e)}else le.write(this.fd,this._writingBuf,n)}function E_(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Eh(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=le.writeSync(this.fd,this._writingBuf);n(null,e)}catch(e){n(e)}else v_&&(this._writingBuf=Buffer.from(this._writingBuf)),le.write(this.fd,this._writingBuf,n)}function Rr(n){if(n.fd===-1){n.once("ready",Rr.bind(null,n));return}n._periodicFlushTimer!==void 0&&clearInterval(n._periodicFlushTimer),n.destroyed=!0,n._bufs=[],n._lens=[],m_(typeof n.fd=="number",`sonic.fd must be a number, got ${typeof n.fd}`);try{le.fsync(n.fd,e)}catch{}function e(){n.fd!==1&&n.fd!==2?le.close(n.fd,t):t()}function t(s){if(s){n.emit("error",s);return}n._ending&&!n._writing&&n.emit("finish"),n.emit("close")}}at.SonicBoom=at;at.default=at;Rh.exports=at});var nl=N((XT,Lh)=>{"use strict";var lt={exit:[],beforeExit:[]},Ph={exit:O_,beforeExit:P_},Mn;function T_(){Mn===void 0&&(Mn=new FinalizationRegistry(M_))}function R_(n){lt[n].length>0||process.on(n,Ph[n])}function Mh(n){lt[n].length>0||(process.removeListener(n,Ph[n]),lt.exit.length===0&&lt.beforeExit.length===0&&(Mn=void 0))}function O_(){Ih("exit")}function P_(){Ih("beforeExit")}function Ih(n){for(let e of lt[n]){let t=e.deref(),s=e.fn;t!==void 0&&s(t,n)}lt[n]=[]}function M_(n){for(let e of["exit","beforeExit"]){let t=lt[e].indexOf(n);lt[e].splice(t,t+1),Mh(e)}}function Dh(n,e,t){if(e===void 0)throw new Error("the object can't be undefined");R_(n);let s=new WeakRef(e);s.fn=t,T_(),Mn.register(e,s),lt[n].push(s)}function I_(n,e){Dh("exit",n,e)}function D_(n,e){Dh("beforeExit",n,e)}function L_(n){if(Mn!==void 0){Mn.unregister(n);for(let e of["exit","beforeExit"])lt[e]=lt[e].filter(t=>{let s=t.deref();return s&&s!==n}),Mh(e)}}Lh.exports={register:I_,registerBeforeExit:D_,unregister:L_}});var Fh=N((QT,F_)=>{F_.exports={name:"thread-stream",version:"4.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",engines:{node:">=20"},dependencies:{"real-require":"^1.0.0"},devDependencies:{"@types/node":"^25.0.2","@yao-pkg/pkg":"^6.0.0",borp:"^1.0.0",desm:"^1.3.0",eslint:"^9.39.1",fastbench:"^1.0.1",neostandard:"^0.13.0","pino-elasticsearch":"^9.0.0","sonic-boom":"^5.0.0","ts-node":"^10.8.0",typescript:"~5.7.3"},scripts:{build:"tsc --noEmit",lint:"eslint",test:'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:ci":'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:yarn":'npm run transpile && borp --pattern "test/*.test.js"',transpile:"sh ./test/ts/transpile.sh"},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina <hello@matteocollina.com>",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var jh=N((ZT,Nh)=>{"use strict";function N_(n,e,t,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{let a=Atomics.load(n,e);if(a===t){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),u=Atomics.waitAsync(n,e,a,l);u.async?u.value.then(o):setImmediate(o)};o()}function j_(n,e,t,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{if(Atomics.load(n,e)!==t){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),u=Atomics.waitAsync(n,e,t,l);u.async?u.value.then(d=>{if(d==="ok"){r(null,"ok");return}o()}):setImmediate(o)};o()}Nh.exports={wait:N_,waitDiff:j_}});var Bh=N((eR,Hh)=>{"use strict";Hh.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Zh=N((tR,Qh)=>{"use strict";var{version:H_}=Fh(),{EventEmitter:B_}=require("events"),{Worker:U_}=require("worker_threads"),{join:q_}=require("path"),{pathToFileURL:K_}=require("url"),{wait:W_}=jh(),{WRITE_INDEX:Dt,READ_INDEX:rn,SEQ_INDEX:sl}=Bh(),G_=require("buffer"),V_=require("assert"),R=Symbol("kImpl"),z_=G_.constants.MAX_STRING_LENGTH;function Uh(){}function al(n,e){Atomics.add(n[R].state,sl,1),e(),Atomics.add(n[R].state,sl,1),Atomics.notify(n[R].state,sl)}function qh(n){al(n,()=>{Atomics.store(n[R].state,rn,0),Atomics.store(n[R].state,Dt,0)})}var fs=class{constructor(e){this._value=e}deref(){return this._value}},Or=class{register(){}unregister(){}},Y_=process.env.NODE_V8_COVERAGE?Or:global.FinalizationRegistry||Or,J_=process.env.NODE_V8_COVERAGE?fs:global.WeakRef||fs,Kh=new Y_(n=>{n.exited||n.terminate()});function X_(n,e){let{filename:t,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||q_(__dirname,"lib","worker.js"),o=new U_(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:t.indexOf("file://")===0?t:K_(t).href,dataBuf:n[R].dataBuf,stateBuf:n[R].stateBuf,workerData:{$context:{threadStreamVersion:H_},...s}}});return o.stream=new fs(n),o.on("message",Q_),o.on("exit",Vh),Kh.register(n,o),o}function Wh(n){V_(!n[R].sync),n[R].needDrain&&(n[R].needDrain=!1,n.emit("drain"))}function Gh(n){for(;;){let e=Atomics.load(n[R].state,Dt),t=n[R].data.length-e;if(t>0){if(n[R].bufLen===0){n[R].flushing=!1,n[R].ending?ll(n):n[R].needDrain&&process.nextTick(Wh,n);return}Jh(n,t,Uh);continue}if(t===0){if(e===0&&n[R].bufLen===0)return;Pr(n,()=>{n.destroyed||(qh(n),Gh(n))});return}Qe(n,new Error("overwritten"));return}}function Q_(n){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(n?.code!=null)switch(n.code){case"READY":this.stream=new J_(e),Pr(e,()=>{e[R].ready=!0,e.emit("ready")});break;case"ERROR":Qe(e,n.err);break;case"EVENT":Array.isArray(n.args)?e.emit(n.name,...n.args):e.emit(n.name,n.args);break;case"FLUSHED":{if(n.context!=="thread-stream"){Qe(e,new Error("this should not happen: "+n.code));break}let t=e[R].flushCallbacks.get(n.id);t&&(e[R].flushCallbacks.delete(n.id),process.nextTick(t));break}case"WARNING":process.emitWarning(n.err);break;default:Qe(e,new Error("this should not happen: "+n.code))}}function Vh(n){let e=this.stream.deref();e!==void 0&&(Kh.unregister(e),e.worker.exited=!0,e.worker.off("exit",Vh),Qe(e,n!==0?new Error("the worker thread exited"):null))}var il=class extends B_{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[R]={},this[R].stateBuf=new SharedArrayBuffer(128),this[R].state=new Int32Array(this[R].stateBuf),this[R].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[R].data=Buffer.from(this[R].dataBuf),this[R].sync=e.sync||!1,this[R].ending=!1,this[R].ended=!1,this[R].needDrain=!1,this[R].destroyed=!1,this[R].flushing=!1,this[R].ready=!1,this[R].finished=!1,this[R].errored=null,this[R].closed=!1,this[R].buf=[],this[R].bufHead=0,this[R].bufLen=0,this[R].flushCallbacks=new Map,this[R].nextFlushId=0,this.worker=X_(this,e),this.on("message",(t,s)=>{this.worker.postMessage(t,s)})}write(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[R].destroyed)return ol(this,new Error("the worker has exited")),!1;if(this[R].ending)return ol(this,new Error("the worker is ending")),!1;if(this[R].flushing&&this[R].bufLen+t.length>=z_)try{rl(this),this[R].flushing=!0}catch(s){return Qe(this,s),!1}if(this[R].buf.push(t),this[R].bufLen+=t.length,this[R].sync)try{return rl(this),!0}catch(s){return Qe(this,s),!1}return this[R].flushing||(this[R].flushing=!0,setImmediate(Gh,this)),this[R].needDrain=this[R].data.length-this[R].bufLen-Atomics.load(this[R].state,Dt)<=0,!this[R].needDrain}end(){this[R].destroyed||(this[R].ending=!0,ll(this))}flush(e){e=typeof e=="function"?e:Uh,zh(this,t=>{if(t){process.nextTick(e,t);return}Yh(this,e)})}flushSync(){this[R].destroyed||(rl(this),Xh(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[R].ready}get destroyed(){return this[R].destroyed}get closed(){return this[R].closed}get writable(){return!this[R].destroyed&&!this[R].ending}get writableEnded(){return this[R].ending}get writableFinished(){return this[R].finished}get writableNeedDrain(){return this[R].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[R].errored}};function zh(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].sync&&(n[R].flushing||n[R].bufLen>0)){setImmediate(zh,n,e);return}Pr(n,e)}function Pr(n,e){let t=Atomics.load(n[R].state,Dt);W_(n[R].state,rn,t,1/0,(s,r)=>{if(s){Qe(n,s),e(s);return}if(r!=="ok"){Pr(n,e);return}e()})}function Yh(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].ready){let s=()=>{i(),Yh(n,e)},r=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{n.off("ready",s),n.off("close",r)};n.once("ready",s),n.once("close",r);return}let t=++n[R].nextFlushId;n[R].flushCallbacks.set(t,e);try{n.worker.postMessage({code:"FLUSH",context:"thread-stream",id:t})}catch(s){n[R].flushCallbacks.delete(t),Qe(n,s),process.nextTick(e,s)}}function Z_(n,e){let t=n[R].flushCallbacks;if(t.size===0)return;let s=e||new Error("the worker has exited");for(let r of t.values())process.nextTick(r,s);t.clear()}function ol(n,e){setImmediate(()=>{n.emit("error",e)})}function Qe(n,e){n[R].destroyed||(n[R].destroyed=!0,Z_(n,e),e&&(n[R].errored=e,ol(n,e)),n.worker.exited?setImmediate(()=>{n[R].closed=!0,n.emit("close")}):n.worker.terminate().catch(()=>{}).then(()=>{n[R].closed=!0,n.emit("close")}))}function Jh(n,e,t){let r=Atomics.load(n[R].state,Dt),i=e;for(;i>0&&n[R].bufLen!==0;){let o=n[R].bufHead,a=n[R].buf[o];if(a.length<=i){a.copy(n[R].data,r),r+=a.length,i-=a.length,n[R].bufLen-=a.length,n[R].bufHead=o+1,n[R].bufHead===n[R].buf.length?(n[R].buf.length=0,n[R].bufHead=0):n[R].bufHead>=1024&&n[R].bufHead*2>=n[R].buf.length&&(n[R].buf.splice(0,n[R].bufHead),n[R].bufHead=0);continue}a.copy(n[R].data,r,0,i),n[R].buf[o]=a.subarray(i),n[R].bufLen-=i,r+=i,i=0}return al(n,()=>{Atomics.store(n[R].state,Dt,r)}),t(),!0}function ll(n){if(!(n[R].ended||!n[R].ending||n[R].flushing)){n[R].ended=!0;try{n.flushSync();let e=Atomics.load(n[R].state,rn);al(n,()=>{Atomics.store(n[R].state,Dt,-1)});let t=0;for(;e!==-1;){if(Atomics.wait(n[R].state,rn,e,1e3),e=Atomics.load(n[R].state,rn),e===-2){Qe(n,new Error("end() failed"));return}if(++t===10){Qe(n,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{n[R].finished=!0,n.emit("finish")})}catch(e){Qe(n,e)}}}function rl(n){let e=()=>{n[R].ending?ll(n):n[R].needDrain&&process.nextTick(Wh,n)};for(n[R].flushing=!1;n[R].bufLen!==0;){let t=Atomics.load(n[R].state,Dt),s=n[R].data.length-t;if(s===0){Xh(n),qh(n);continue}else if(s<0)throw new Error("overwritten");Jh(n,s,e)}}function Xh(n){if(n[R].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(n[R].state,Dt),t=0;for(;;){let s=Atomics.load(n[R].state,rn);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(n[R].state,rn,s,1e3);else break;if(++t===10)throw new Error("_flushSync took too long (10s)")}}Qh.exports=il});var dl=N((nR,nm)=>{"use strict";var{createRequire:ek}=require("module"),{existsSync:tk}=require("node:fs"),nk=za(),{join:cl,isAbsolute:tm,sep:sk}=require("node:path"),{fileURLToPath:rk}=require("node:url"),ik=Za(),ul=nl(),ok=Zh();function ak(n){ul.register(n,fk),ul.registerBeforeExit(n,pk),n.on("close",function(){ul.unregister(n)})}function lk(){let n=process.execArgv;for(let e=0;e<n.length;e++){let t=n[e];if(t==="--import"||t==="--require"||t==="-r"||t.startsWith("--import=")||t.startsWith("--require=")||t.startsWith("-r="))return!0}return!1}function ck(n){let e=n.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return n;let t=[],s=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i==="--require"||i==="-r"||i==="--import"){let o=e[r+1];if(o&&em(o)){s=!0,r++;continue}t.push(i),o&&(t.push(o),r++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(em(o)){s=!0;continue}}t.push(i)}return s?t.join(" "):n}function em(n){let e=uk(n);if(!e)return!1;let t=e;if(t.startsWith("file://"))try{t=rk(t)}catch{return!1}return tm(t)&&!tk(t)}function uk(n){let e=n[0],t=n[n.length-1];return e==='"'&&t==='"'||e==="'"&&t==="'"?n.slice(1,-1):n}function dk(n,e,t,s,r){if(!t.execArgv&&lk()&&require.main===void 0&&(t={...t,execArgv:[]}),!t.env&&process.env.NODE_OPTIONS){let l=ck(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(t={...t,env:{...process.env,NODE_OPTIONS:l}})}t={...t,name:r};let i=new ok({filename:n,workerData:e,workerOpts:t,sync:s});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),t.autoEnd!==!1&&ak(i)}function a(){i.closed||(i.flushSync(),ik(100),i.end())}return i}function fk(n){n.ref(),n.flushSync(),n.end(),n.once("close",function(){n.unref()})}function pk(n){n.flushSync()}function hk(n){let{pipeline:e,targets:t,levels:s,dedupe:r,worker:i={},caller:o=nk(),sync:a=!1}=n,l={...n.options},u=typeof o=="string"?[o]:o,d=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),f=n.target;if(f&&t)throw new Error("only one of target or targets can be specified");t?(f=d["pino-worker"]||cl(__dirname,"worker.js"),l.targets=t.filter(p=>p.target).map(p=>({...p,target:m(p.target)})),l.pipelines=t.filter(p=>p.pipeline).map(p=>p.pipeline.map(g=>({...g,level:p.level,target:m(g.target)})))):e&&(f=d["pino-worker"]||cl(__dirname,"worker.js"),l.pipelines=[e.map(p=>({...p,target:m(p.target)}))]),s&&(l.levels=s),r&&(l.dedupe=r),l.pinoWillSendConfig=!0;let h=t||e?"pino.transport":f;return dk(m(f),l,i,a,h);function m(p){if(p=d[p]||p,tm(p)||p.indexOf("file://")===0)return p;if(p==="pino/file")return cl(__dirname,"..","file.js");let g;for(let x of u)try{let w=x==="node:repl"?process.cwd()+sk:x;g=ek(w).resolve(p);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${p}"`);return g}}nm.exports=hk});var Dr=N((sR,mm)=>{"use strict";var mk=require("node:diagnostics_channel"),sm=_h(),{mapHttpRequest:gk,mapHttpResponse:yk}=Va(),pl=Oh(),rm=nl(),{lsCacheSym:bk,chindingsSym:cm,writeSym:im,serializersSym:um,formatOptsSym:om,endSym:vk,stringifiersSym:dm,stringifySym:fm,stringifySafeSym:hl,wildcardFirstSym:pm,nestedKeySym:wk,formattersSym:hm,messageKeySym:xk,errorKeySym:Sk,nestedKeyStrSym:_k,msgPrefixSym:Mr}=Pn(),{isMainThread:kk}=require("worker_threads"),Ak=dl(),[$k]=process.versions.node.split(".").map(n=>Number(n)),am=mk.tracingChannel("pino_asJson"),fl=$k>=25?n=>JSON.stringify(n):Ek;function In(){}function Ck(n,e){if(!e)return t;return function(...r){e.call(this,r,t,n)};function t(s,...r){if(typeof s=="object"){let i=s;s!==null&&(s.method&&s.headers&&s.socket?s=gk(s):typeof s.setHeader=="function"&&(s=yk(s)));let o;i===null&&r.length===0?o=[null]:(i=r.shift(),o=r),typeof this[Mr]=="string"&&i!==void 0&&i!==null&&(i=this[Mr]+i),this[im](s,sm(i,o,this[om]),n)}else{let i=s===void 0?r.shift():s;typeof this[Mr]=="string"&&i!==void 0&&i!==null&&(i=this[Mr]+i),this[im](null,sm(i,r,this[om]),n)}}}function Ek(n){let e="",t=0,s=!1,r=255,i=n.length;if(i>100)return JSON.stringify(n);for(var o=0;o<i&&r>=32;o++)r=n.charCodeAt(o),(r===34||r===92)&&(e+=n.slice(t,o)+"\\",t=o,s=!0);return s?e+=n.slice(t):e=n,r<32?JSON.stringify(n):'"'+e+'"'}function Tk(n,e,t,s){if(am.hasSubscribers===!1)return lm.call(this,n,e,t,s);let r={instance:this,arguments};return am.traceSync(lm,r,this,n,e,t,s)}function lm(n,e,t,s){let r=this[fm],i=this[hl],o=this[dm],a=this[vk],l=this[cm],u=this[um],d=this[hm],f=this[xk],h=this[Sk],m=this[bk][t]+s;m=m+l;let p;d.log&&(n=d.log(n));let g=o[pm],x="";for(let $ in n)if(p=n[$],Object.prototype.hasOwnProperty.call(n,$)&&p!==void 0){u[$]?p=u[$](p):$===h&&u.err&&(p=u.err(p));let A=o[$]||g;switch(typeof p){case"undefined":case"function":continue;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":A&&(p=A(p));break;case"string":p=(A||fl)(p);break;default:p=(A||r)(p,i)}if(p===void 0)continue;let y=fl($);x+=","+y+":"+p}let w="";if(e!==void 0){p=u[f]?u[f](e):e;let $=o[f]||g;switch(typeof p){case"function":break;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":$&&(p=$(p)),w=',"'+f+'":'+p;break;case"string":p=($||fl)(p),w=',"'+f+'":'+p;break;default:p=($||r)(p,i),w=',"'+f+'":'+p}}return this[wk]&&x?m+this[_k]+x.slice(1)+"}"+w+a:m+x+w+a}function Rk(n,e){let t,s=n[cm],r=n[fm],i=n[hl],o=n[dm],a=o[pm],l=n[um],u=n[hm].bindings;e=u(e);for(let d in e)if(t=e[d],((d.length<5||d!=="level"&&d!=="serializers"&&d!=="formatters"&&d!=="customLevels")&&e.hasOwnProperty(d)&&t!==void 0)===!0){if(t=l[d]?l[d](t):t,t=(o[d]||a||r)(t,i),t===void 0)continue;s+=',"'+d+'":'+t}return s}function Ok(n){return n.write!==n.constructor.prototype.write}function Ir(n){let e=new pl(n);return e.on("error",t),!n.sync&&kk&&(rm.register(e,Pk),e.on("close",function(){rm.unregister(e)})),e;function t(s){if(s.code==="EPIPE"){e.write=In,e.end=In,e.flushSync=In,e.destroy=In;return}e.removeListener("error",t),e.emit("error",s)}}function Pk(n,e){n.destroyed||(e==="beforeExit"?(n.flush(),n.on("drain",function(){n.end()})):n.flushSync())}function Mk(n){return function(t,s,r={},i){if(typeof r=="string")i=Ir({dest:r}),r={};else if(typeof i=="string"){if(r&&r.transport)throw Error("only one of option.transport or stream can be specified");i=Ir({dest:i})}else if(r instanceof pl||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof pl||r.transport.writable||r.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;r.customLevels&&(l=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=Ak({caller:s,...r.transport,levels:l})}if(r=Object.assign({},n,r),r.serializers=Object.assign({},n.serializers,r.serializers),r.formatters=Object.assign({},n.formatters,r.formatters),r.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=r;return o===!1&&(r.level="silent"),a||(r.onChild=In),i||(Ok(process.stdout)?i=process.stdout:i=Ir({fd:process.stdout.fd||1})),{opts:r,stream:i}}}function Ik(n,e){try{return JSON.stringify(n)}catch{try{return(e||this[hl])(n)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Dk(n,e,t){return{level:n,bindings:e,log:t}}function Lk(n){let e=Number(n);return typeof n=="string"&&Number.isFinite(e)?e:n===void 0?1:n}mm.exports={noop:In,buildSafeSonicBoom:Ir,asChindings:Rk,asJson:Tk,genLog:Ck,createArgsNormalizer:Mk,stringify:Ik,buildFormatters:Dk,normalizeDestFileDescriptor:Lk}});var Lr=N((rR,gm)=>{var Fk={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Nk={ASC:"ASC",DESC:"DESC"};gm.exports={DEFAULT_LEVELS:Fk,SORTING_ORDER:Nk}});var yl=N((iR,wm)=>{"use strict";var{lsCacheSym:jk,levelValSym:ml,useOnlyCustomLevelsSym:Hk,streamSym:Bk,formattersSym:Uk,hooksSym:qk,levelCompSym:ym}=Pn(),{noop:Kk,genLog:on}=Dr(),{DEFAULT_LEVELS:xt,SORTING_ORDER:bm}=Lr(),vm={fatal:n=>{let e=on(xt.fatal,n);return function(...t){let s=this[Bk];if(e.call(this,...t),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:n=>on(xt.error,n),warn:n=>on(xt.warn,n),info:n=>on(xt.info,n),debug:n=>on(xt.debug,n),trace:n=>on(xt.trace,n)},gl=Object.keys(xt).reduce((n,e)=>(n[xt[e]]=e,n),{}),Wk=Object.keys(gl).reduce((n,e)=>(n[e]='{"level":'+Number(e),n),{});function Gk(n){let e=n[Uk].level,{labels:t}=n.levels,s={};for(let r in t){let i=e(t[r],Number(r));s[r]=JSON.stringify(i).slice(0,-1)}return n[jk]=s,n}function Vk(n,e){if(e)return!1;switch(n){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function zk(n){let{labels:e,values:t}=this.levels;if(typeof n=="number"){if(e[n]===void 0)throw Error("unknown level value"+n);n=e[n]}if(t[n]===void 0)throw Error("unknown level "+n);let s=this[ml],r=this[ml]=t[n],i=this[Hk],o=this[ym],a=this[qk].logMethod;for(let l in t){if(o(t[l],r)===!1){this[l]=Kk;continue}this[l]=Vk(l,i)?vm[l](a):on(t[l],a)}this.emit("level-change",n,r,e[s],s,this)}function Yk(n){let{levels:e,levelVal:t}=this;return e&&e.labels?e.labels[t]:""}function Jk(n){let{values:e}=this.levels,t=e[n];return t!==void 0&&this[ym](t,this[ml])}function Xk(n,e,t){return n===bm.DESC?e<=t:e>=t}function Qk(n){return typeof n=="string"?Xk.bind(null,n):n}function Zk(n=null,e=!1){let t=n?Object.keys(n).reduce((i,o)=>(i[n[o]]=o,i),{}):null,s=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:gl,t),r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:xt,n);return{labels:s,values:r}}function eA(n,e,t){if(typeof n=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),t?[]:Object.keys(gl).map(i=>+i),1/0).includes(n))throw Error(`default level:${n} must be included in custom levels`);return}let s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:xt,e);if(!(n in s))throw Error(`default level:${n} must be included in custom levels`)}function tA(n,e){let{labels:t,values:s}=n;for(let r in e){if(r in s)throw Error("levels cannot be overridden");if(e[r]in t)throw Error("pre-existing level values cannot be used for new levels")}}function nA(n){if(typeof n!="function"&&!(typeof n=="string"&&Object.values(bm).includes(n)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}wm.exports={initialLsCache:Wk,genLsCache:Gk,levelMethods:vm,getLevel:Yk,setLevel:zk,isLevelEnabled:Jk,mappings:Zk,assertNoLevelCollisions:tA,assertDefaultLevelFound:eA,genLevelComparison:Qk,assertLevelComparison:nA}});var bl=N((oR,xm)=>{"use strict";xm.exports={version:"10.3.1"}});var Tm=N((lR,Em)=>{"use strict";var{EventEmitter:sA}=require("node:events"),{lsCacheSym:rA,levelValSym:iA,setLevelSym:wl,getLevelSym:Sm,chindingsSym:Nr,mixinSym:oA,asJsonSym:km,writeSym:aA,mixinMergeStrategySym:lA,timeSym:cA,timeSliceIndexSym:uA,streamSym:Am,serializersSym:an,formattersSym:ps,errorKeySym:dA,messageKeySym:fA,useOnlyCustomLevelsSym:pA,needsMetadataGsym:hA,redactFmtSym:mA,stringifySym:gA,formatOptsSym:yA,stringifiersSym:bA,msgPrefixSym:xl,hooksSym:vA}=Pn(),{getLevel:wA,setLevel:xA,isLevelEnabled:SA,mappings:_A,initialLsCache:kA,genLsCache:AA,assertNoLevelCollisions:$A}=yl(),{asChindings:Sl,asJson:CA,buildFormatters:vl,stringify:_m,noop:$m}=Dr(),{version:EA}=bl(),TA=Xa(),RA=class{},Cm={constructor:RA,child:OA,bindings:PA,setBindings:MA,flush:LA,isLevelEnabled:SA,version:EA,get level(){return this[Sm]()},set level(n){this[wl](n)},get levelVal(){return this[iA]},set levelVal(n){throw Error("levelVal is read-only")},get msgPrefix(){return this[xl]},get[Symbol.toStringTag](){return"Pino"},[rA]:kA,[aA]:DA,[km]:CA,[Sm]:wA,[wl]:xA};Object.setPrototypeOf(Cm,sA.prototype);Em.exports=function(){return Object.create(Cm)};var Fr=n=>n;function OA(n,e){if(!n)throw Error("missing bindings for child Pino");let t=this[an],s=this[ps],r=Object.create(this);if(e==null)return r[ps].bindings!==Fr&&(r[ps]=vl(s.level,Fr,s.log)),r[Nr]=Sl(r,n),this.onChild!==$m&&this.onChild(r),r;if(e.hasOwnProperty("serializers")===!0){r[an]=Object.create(null);for(let u in t)r[an][u]=t[u];let a=Object.getOwnPropertySymbols(t);for(var i=0;i<a.length;i++){let u=a[i];r[an][u]=t[u]}for(let u in e.serializers)r[an][u]=e.serializers[u];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let u=l[o];r[an][u]=e.serializers[u]}}else r[an]=t;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:u}=e.formatters;r[ps]=vl(a||s.level,l||Fr,u||s.log)}else r[ps]=vl(s.level,Fr,s.log);if(e.hasOwnProperty("customLevels")===!0&&($A(this.levels,e.customLevels),r.levels=_A(e.customLevels,r[pA]),AA(r)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){r.redact=e.redact;let a=TA(r.redact,_m),l={stringify:a[mA]};r[gA]=_m,r[bA]=a,r[yA]=l}if(typeof e.msgPrefix=="string"&&(r[xl]=(this[xl]||"")+e.msgPrefix),r[Nr]=Sl(r,n),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;r[wl](a)}return this.onChild(r),r}function PA(){let e=`{${this[Nr].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function MA(n){let e=Sl(this,n);this[Nr]=e}function IA(n,e){return Object.assign(e,n)}function DA(n,e,t){let s=this[cA](),r=this[oA],i=this[dA],o=this[fA],a=this[lA]||IA,l,u=this[vA].streamWrite;n==null?l={}:n instanceof Error?(l={[i]:n},e===void 0&&(e=n.message)):(l=n,e===void 0&&n[o]===void 0&&n[i]&&(e=n[i].message)),r&&(l=a(l,r(l,t,this)));let d=this[km](l,e,t,s),f=this[Am];f[hA]===!0&&(f.lastLevel=t,f.lastObj=l,f.lastMsg=e,f.lastTime=s.slice(this[uA]),f.lastLogger=this),f.write(u?u(d):d)}function LA(n){if(n!=null&&typeof n!="function")throw Error("callback must be a function");let e=this[Am];typeof e.flush=="function"?e.flush(n||$m):n&&n()}});var Mm=N(($l,Pm)=>{"use strict";var{hasOwnProperty:hs}=Object.prototype,cn=Al();cn.configure=Al;cn.stringify=cn;cn.default=cn;$l.stringify=cn;$l.configure=Al;Pm.exports=cn;var FA=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function qt(n){return n.length<5e3&&!FA.test(n)?`"${n}"`:JSON.stringify(n)}function _l(n,e){if(n.length>200||e)return n.sort(e);for(let t=1;t<n.length;t++){let s=n[t],r=t;for(;r!==0&&n[r-1]>s;)n[r]=n[r-1],r--;n[r]=s}return n}var NA=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function kl(n){return NA.call(n)!==void 0&&n.length!==0}function Rm(n,e,t){n.length<t&&(t=n.length);let s=e===","?"":" ",r=`"0":${s}${n[0]}`;for(let i=1;i<t;i++)r+=`${e}"${i}":${s}${n[i]}`;return r}function jA(n){if(hs.call(n,"circularValue")){let e=n.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function HA(n){let e;if(hs.call(n,"deterministic")&&(e=n.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function BA(n,e){let t;if(hs.call(n,e)&&(t=n[e],typeof t!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return t===void 0?!0:t}function Om(n,e){let t;if(hs.call(n,e)){if(t=n[e],typeof t!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(t))throw new TypeError(`The "${e}" argument must be an integer`);if(t<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return t===void 0?1/0:t}function ln(n){return n===1?"1 item":`${n} items`}function UA(n){let e=new Set;for(let t of n)(typeof t=="string"||typeof t=="number")&&e.add(String(t));return e}function qA(n){if(hs.call(n,"strict")){let e=n.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return t=>{let s=`Object can not safely be stringified. Received type ${typeof t}`;throw typeof t!="function"&&(s+=` (${t.toString()})`),new Error(s)}}}function Al(n){n={...n};let e=qA(n);e&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let t=jA(n),s=BA(n,"bigint"),r=HA(n),i=typeof r=="function"?r:void 0,o=Om(n,"maximumDepth"),a=Om(n,"maximumBreadth");function l(m,p,g,x,w,$){let A=p[m];switch(typeof A=="object"&&A!==null&&typeof A.toJSON=="function"&&(A=A.toJSON(m)),A=x.call(p,m,A),typeof A){case"string":return qt(A);case"object":{if(A===null)return"null";if(g.indexOf(A)!==-1)return t;let y="",v=",",b=$;if(Array.isArray(A)){if(A.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(A),w!==""&&($+=w,y+=`
945
+ `)}autoImportance(e,t){let r={convention:6,decision:8,pattern:5,note:3,error:7,"tool-result":2,"user-pref":7,dependency:4,performance:5,security:9,api:6,"agent-learning":4}[e]||3;return/\b(important|critical|must|always|never|danger|warning|breaking)\b/i.test(t)&&(r=Math.min(10,r+2)),r}autoTag(e,t){let s=[t];return/\b(react|vue|angular|svelte|next|nuxt)\b/i.test(e)&&s.push("frontend"),/\b(express|fastify|nest|koa|hapi)\b/i.test(e)&&s.push("backend"),/\b(postgres|mysql|mongo|redis|sqlite)\b/i.test(e)&&s.push("database"),/\b(docker|kubernetes|k8s|ci\/cd|deploy)\b/i.test(e)&&s.push("devops"),/\b(test|jest|vitest|cypress|playwright)\b/i.test(e)&&s.push("testing"),/\b(auth|jwt|oauth|session|token)\b/i.test(e)&&s.push("auth"),/\b(api|endpoint|route|rest|graphql)\b/i.test(e)&&s.push("api"),s}extractFileRefs(e){let t=/[\w\-./]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|scss|html|vue|svelte|go|rs|java|sql|sh|toml|xml|env)/gi,s=e.match(t);return s?[...new Set(s)]:[]}load(){try{if(Le.existsSync(this.filePath)){let e=JSON.parse(Le.readFileSync(this.filePath,"utf-8"));if(Array.isArray(e))for(let t of e)t.importance||(t.importance=3),t.createdBy||(t.createdBy="hablas"),t.accessCount||(t.accessCount=0),t.useCount||(t.useCount=0),t.tags||(t.tags=[t.category||"note"]),t.relatedFiles||(t.relatedFiles=[]),t.lastAccessedAt||(t.lastAccessedAt=t.updatedAt||Date.now()),this.entries.set(t.key,t)}}catch{}this.loadAgentLanes()}save(){try{Le.existsSync(Pn)||Le.mkdirSync(Pn,{recursive:!0});let e=Array.from(this.entries.values());Le.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf-8")}catch{}}loadAgentLanes(){try{if(Le.existsSync(this.agentLanesPath)){let e=JSON.parse(Le.readFileSync(this.agentLanesPath,"utf-8"));for(let[t,s]of Object.entries(e)){let r=new Map;for(let i of s)r.set(i.key,i);this.agentLanes.set(t,r)}}}catch{}}saveAgentLanes(){try{Le.existsSync(Pn)||Le.mkdirSync(Pn,{recursive:!0});let e={};for(let[t,s]of this.agentLanes)e[t]=Array.from(s.values());Le.writeFileSync(this.agentLanesPath,JSON.stringify(e,null,2),"utf-8")}catch{}}}});var Ua=F((BT,Yp)=>{"use strict";var fs=n=>n&&typeof n.message=="string",Ba=n=>{if(!n)return;let e=n.cause;if(typeof e=="function"){let t=n.cause();return fs(t)?t:void 0}else return fs(e)?e:void 0},Vp=(n,e)=>{if(!fs(n))return"";let t=n.stack||"";if(e.has(n))return t+`
946
+ causes have become circular...`;let s=Ba(n);return s?(e.add(n),t+`
947
+ caused by: `+Vp(s,e)):t},rS=n=>Vp(n,new Set),zp=(n,e,t)=>{if(!fs(n))return"";let s=t?"":n.message||"";if(e.has(n))return s+": ...";let r=Ba(n);if(r){e.add(n);let i=typeof n.cause=="function";return s+(i?"":": ")+zp(r,e,i)}else return s},iS=n=>zp(n,new Set);Yp.exports={isErrorLike:fs,getErrorCause:Ba,stackWithCauses:rS,messageWithCauses:iS}});var qa=F((UT,Xp)=>{"use strict";var oS=Symbol("circular-ref-tag"),_r=Symbol("pino-raw-err-ref"),Jp=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[_r]},set:function(n){this[_r]=n}}});Object.defineProperty(Jp,_r,{writable:!0,value:{}});Xp.exports={pinoErrProto:Jp,pinoErrorSymbols:{seen:oS,rawSymbol:_r}}});var eh=F((qT,Zp)=>{"use strict";Zp.exports=Wa;var{messageWithCauses:aS,stackWithCauses:lS,isErrorLike:Qp}=Ua(),{pinoErrProto:cS,pinoErrorSymbols:uS}=qa(),{seen:Ka}=uS,{toString:dS}=Object.prototype;function Wa(n){if(!Qp(n))return n;n[Ka]=void 0;let e=Object.create(cS);e.type=dS.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=aS(n),e.stack=lS(n),Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>Wa(t)));for(let t in n)if(e[t]===void 0){let s=n[t];Qp(s)?t!=="cause"&&!Object.prototype.hasOwnProperty.call(s,Ka)&&(e[t]=Wa(s)):e[t]=s}return delete n[Ka],e.raw=n,e}});var nh=F((KT,th)=>{"use strict";th.exports=Ar;var{isErrorLike:Ga}=Ua(),{pinoErrProto:fS,pinoErrorSymbols:pS}=qa(),{seen:kr}=pS,{toString:hS}=Object.prototype;function Ar(n){if(!Ga(n))return n;n[kr]=void 0;let e=Object.create(fS);e.type=hS.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=n.message,e.stack=n.stack,Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>Ar(t))),Ga(n.cause)&&!Object.prototype.hasOwnProperty.call(n.cause,kr)&&(e.cause=Ar(n.cause));for(let t in n)if(e[t]===void 0){let s=n[t];Ga(s)?Object.prototype.hasOwnProperty.call(s,kr)||(e[t]=Ar(s)):e[t]=s}return delete n[kr],e.raw=n,e}});var oh=F((WT,ih)=>{"use strict";ih.exports={mapHttpRequest:mS,reqSerializer:rh};var Va=Symbol("pino-raw-req-ref"),sh=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Va]},set:function(n){this[Va]=n}}});Object.defineProperty(sh,Va,{writable:!0,value:{}});function rh(n){let e=n.info||n.socket,t=Object.create(sh);if(t.id=typeof n.id=="function"?n.id():n.id||(n.info?n.info.id:void 0),t.method=n.method,n.originalUrl)t.url=n.originalUrl;else{let s=n.path;t.url=typeof s=="string"?s:n.url?n.url.path||n.url:void 0}return n.query&&(t.query=n.query),n.params&&(t.params=n.params),t.headers=n.headers,t.remoteAddress=e&&e.remoteAddress,t.remotePort=e&&e.remotePort,t.raw=n.raw||n,t}function mS(n){return{req:rh(n)}}});var uh=F((GT,ch)=>{"use strict";ch.exports={mapHttpResponse:gS,resSerializer:lh};var za=Symbol("pino-raw-res-ref"),ah=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[za]},set:function(n){this[za]=n}}});Object.defineProperty(ah,za,{writable:!0,value:{}});function lh(n){let e=Object.create(ah);return e.statusCode=n.headersSent?n.statusCode:null,e.headers=n.getHeaders?n.getHeaders():n._headers,e.raw=n,e}function gS(n){return{res:lh(n)}}});var Ja=F((VT,dh)=>{"use strict";var Ya=eh(),yS=nh(),$r=oh(),Cr=uh();dh.exports={err:Ya,errWithCause:yS,mapHttpRequest:$r.mapHttpRequest,mapHttpResponse:Cr.mapHttpResponse,req:$r.reqSerializer,res:Cr.resSerializer,wrapErrorSerializer:function(e){return e===Ya?e:function(s){return e(Ya(s))}},wrapRequestSerializer:function(e){return e===$r.reqSerializer?e:function(s){return e($r.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===Cr.resSerializer?e:function(s){return e(Cr.resSerializer(s))}}}});var Xa=F((zT,fh)=>{"use strict";function bS(n,e){return e}fh.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=bS;let t=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let s=t.slice(2),r=[];for(let i of s)i&&r.push(i.getFileName());return r}});var bh=F((YT,yh)=>{"use strict";function Qa(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof Array){let e=[];for(let t=0;t<n.length;t++)e[t]=Qa(n[t]);return e}if(typeof n=="object"){let e=Object.create(Object.getPrototypeOf(n));for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=Qa(n[t]));return e}return n}function ph(n){let e=[],t="",s=!1,r=!1,i="";for(let o=0;o<n.length;o++){let a=n[o];!s&&a==="."?t&&(e.push(t),t=""):a==="["?(t&&(e.push(t),t=""),s=!0):a==="]"&&s?(e.push(t),t="",s=!1,r=!1):(a==='"'||a==="'")&&s?r?a===i?(r=!1,i=""):t+=a:(r=!0,i=a):t+=a}return t&&e.push(t),e}function hh(n,e,t){let s=n;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof s!="object"||s===null||!(o in s)||typeof s[o]!="object"||s[o]===null)return!1;s=s[o]}let r=e[e.length-1];if(r==="*"){if(Array.isArray(s))for(let i=0;i<s.length;i++)s[i]=t;else if(typeof s=="object"&&s!==null)for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&(s[i]=t)}else typeof s=="object"&&s!==null&&r in s&&Object.prototype.hasOwnProperty.call(s,r)&&(s[r]=t);return!0}function mh(n,e){let t=n;for(let r=0;r<e.length-1;r++){let i=e[r];if(typeof t!="object"||t===null||!(i in t)||typeof t[i]!="object"||t[i]===null)return!1;t=t[i]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(t))for(let r=0;r<t.length;r++)t[r]=void 0;else if(typeof t=="object"&&t!==null)for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&delete t[r]}else typeof t=="object"&&t!==null&&s in t&&Object.prototype.hasOwnProperty.call(t,s)&&delete t[s];return!0}var Er=Symbol("PATH_NOT_FOUND");function vS(n,e){let t=n;for(let s of e){if(t==null||typeof t!="object"||t===null||!(s in t))return Er;t=t[s]}return t}function wS(n,e){let t=n;for(let s of e){if(t==null||typeof t!="object"||t===null)return;t=t[s]}return t}function xS(n,e,t,s=!1){for(let r of e){let i=ph(r);if(i.includes("*"))gh(n,i,t,r,s);else if(s)mh(n,i);else{let o=vS(n,i);if(o===Er)continue;let a=typeof t=="function"?t(o,i):t;hh(n,i,a)}}}function gh(n,e,t,s,r=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=n;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(r)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let u=[...o,l.toString()],d=typeof t=="function"?t(a[l],u):t;a[l]=d}else if(typeof a=="object"&&a!==null)if(r){let l=[];for(let u in a)Object.prototype.hasOwnProperty.call(a,u)&&l.push(u);for(let u of l)delete a[u]}else for(let l in a){let u=[...o,l],d=typeof t=="function"?t(a[l],u):t;a[l]=d}}else SS(n,e,t,i,s,r)}function SS(n,e,t,s,r,i=!1){let o=e.slice(0,s),a=e.slice(s+1),l=[];function u(d,f){if(f===o.length){if(Array.isArray(d))for(let h=0;h<d.length;h++)l[f]=h.toString(),u(d[h],f+1);else if(typeof d=="object"&&d!==null)for(let h in d)l[f]=h,u(d[h],f+1)}else if(f<o.length){let h=o[f];d&&typeof d=="object"&&d!==null&&h in d&&(l[f]=h,u(d[h],f+1))}else if(a.includes("*"))gh(d,a,typeof t=="function"?(m,p)=>{let g=[...l.slice(0,f),...p];return t(m,g)}:t,r,i);else if(i)mh(d,a);else{let h=typeof t=="function"?t(wS(d,a),[...l.slice(0,f),...a]):t;hh(d,a,h)}}if(o.length===0)u(n,0);else{let d=n;for(let f=0;f<o.length;f++){let h=o[f];if(d==null||typeof d!="object"||d===null)return;d=d[h],l[f]=h}d!=null&&u(d,o.length)}}function _S(n){if(n.length===0)return null;let e=new Map;for(let t of n){let s=ph(t),r=e;for(let i=0;i<s.length;i++){let o=s[i];r.has(o)||r.set(o,new Map),r=r.get(o)}}return e}function kS(n,e){if(!e)return n;function t(s,r,i=0){if(!r||r.size===0||s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(Array.isArray(s)){let a=[];for(let l=0;l<s.length;l++){let u=l.toString();r.has(u)||r.has("*")?a[l]=t(s[l],r.get(u)||r.get("*")):a[l]=s[l]}return a}let o=Object.create(Object.getPrototypeOf(s));for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&(r.has(a)||r.has("*")?o[a]=t(s[a],r.get(a)||r.get("*")):o[a]=s[a]);return o}return t(n,e)}function AS(n){if(typeof n!="string")throw new Error("Paths must be (non-empty) strings");if(n==="")throw new Error("Invalid redaction path ()");if(n.includes(".."))throw new Error(`Invalid redaction path (${n})`);if(n.includes(","))throw new Error(`Invalid redaction path (${n})`);let e=0,t=!1,s="";for(let r=0;r<n.length;r++){let i=n[r];if((i==='"'||i==="'")&&e>0)t?i===s&&(t=!1,s=""):(t=!0,s=i);else if(i==="["&&!t)e++;else if(i==="]"&&!t&&(e--,e<0))throw new Error(`Invalid redaction path (${n})`)}if(e!==0)throw new Error(`Invalid redaction path (${n})`)}function $S(n){if(!Array.isArray(n))throw new TypeError("paths must be an array");for(let e of n)AS(e)}function CS(n={}){let{paths:e=[],censor:t="[REDACTED]",serialize:s=JSON.stringify,strict:r=!0,remove:i=!1}=n;$S(e);let o=_S(e);return function(l){if(r&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return s?s(l):l;let u=kS(l,o),d=l,f=t;return typeof t=="function"&&(f=t),xS(u,e,f,i),s===!1?(u.restore=function(){return Qa(d)},u):typeof s=="function"?s(u):JSON.stringify(u)}}yh.exports=CS});var Mn=F((JT,vh)=>{"use strict";var ES=Symbol("pino.setLevel"),TS=Symbol("pino.getLevel"),RS=Symbol("pino.levelVal"),OS=Symbol("pino.levelComp"),PS=Symbol("pino.useLevelLabels"),MS=Symbol("pino.useOnlyCustomLevels"),IS=Symbol("pino.mixin"),DS=Symbol("pino.lsCache"),LS=Symbol("pino.chindings"),NS=Symbol("pino.asJson"),FS=Symbol("pino.write"),jS=Symbol("pino.redactFmt"),HS=Symbol("pino.time"),BS=Symbol("pino.timeSliceIndex"),US=Symbol("pino.stream"),qS=Symbol("pino.stringify"),KS=Symbol("pino.stringifySafe"),WS=Symbol("pino.stringifiers"),GS=Symbol("pino.end"),VS=Symbol("pino.formatOpts"),zS=Symbol("pino.messageKey"),YS=Symbol("pino.errorKey"),JS=Symbol("pino.nestedKey"),XS=Symbol("pino.nestedKeyStr"),QS=Symbol("pino.mixinMergeStrategy"),ZS=Symbol("pino.msgPrefix"),e_=Symbol("pino.wildcardFirst"),t_=Symbol.for("pino.serializers"),n_=Symbol.for("pino.formatters"),s_=Symbol.for("pino.hooks"),r_=Symbol.for("pino.metadata");vh.exports={setLevelSym:ES,getLevelSym:TS,levelValSym:RS,levelCompSym:OS,useLevelLabelsSym:PS,mixinSym:IS,lsCacheSym:DS,chindingsSym:LS,asJsonSym:NS,writeSym:FS,serializersSym:t_,redactFmtSym:jS,timeSym:HS,timeSliceIndexSym:BS,streamSym:US,stringifySym:qS,stringifySafeSym:KS,stringifiersSym:WS,endSym:GS,formatOptsSym:VS,messageKeySym:zS,errorKeySym:YS,nestedKeySym:JS,wildcardFirstSym:e_,needsMetadataGsym:r_,useOnlyCustomLevelsSym:MS,formattersSym:n_,hooksSym:s_,nestedKeyStrSym:XS,mixinMergeStrategySym:QS,msgPrefixSym:ZS}});var el=F((XT,_h)=>{"use strict";var wh=bh(),{redactFmtSym:i_,wildcardFirstSym:Tr}=Mn(),Za=/[^.[\]]+|\[([^[\]]*?)\]/g,xh="[Redacted]",Sh=!1;function o_(n,e){let{paths:t,censor:s,remove:r}=a_(n),i=t.reduce((l,u)=>{Za.lastIndex=0;let d=Za.exec(u),f=Za.exec(u),h=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(h==="*"&&(h=Tr),f===null)return l[h]=null,l;if(l[h]===null)return l;let{index:m}=f,p=`${u.substr(m,u.length-1)}`;return l[h]=l[h]||[],h!==Tr&&l[h].length===0&&l[h].push(...l[Tr]||[]),h===Tr&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(p)}),l[h].push(p),l},{}),o={[i_]:wh({paths:t,censor:s,serialize:e,strict:Sh,remove:r})},a=(...l)=>e(typeof s=="function"?s(...l):s);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,u)=>{if(i[u]===null)l[u]=d=>a(d,[u]);else{let d=typeof s=="function"?(f,h)=>s(f,[u,...h]):s;l[u]=wh({paths:i[u],censor:d,serialize:e,strict:Sh,remove:r})}return l},o)}function a_(n){if(Array.isArray(n))return n={paths:n,censor:xh},n;let{paths:e,censor:t=xh,remove:s}=n;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return s===!0&&(t=void 0),{paths:e,censor:t,remove:s}}_h.exports=o_});var $h=F((QT,Ah)=>{"use strict";var l_=()=>"",c_=()=>`,"time":${Date.now()}`,u_=()=>`,"time":${Math.round(Date.now()/1e3)}`,d_=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,f_=1000000n,kh=1000000000n,p_=BigInt(Date.now())*f_,h_=process.hrtime.bigint(),m_=()=>{let n=process.hrtime.bigint()-h_,e=p_+n,t=e/kh,s=e%kh,r=Number(t*1000n+s/1000000n),i=new Date(r),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),u=i.getUTCHours().toString().padStart(2,"0"),d=i.getUTCMinutes().toString().padStart(2,"0"),f=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${u}:${d}:${f}.${s.toString().padStart(9,"0")}Z"`};Ah.exports={nullTime:l_,epochTime:c_,unixTime:u_,isoTime:d_,isoTimeNano:m_}});var Eh=F((ZT,Ch)=>{"use strict";function g_(n){try{return JSON.stringify(n)}catch{return'"[Circular]"'}}Ch.exports=y_;function y_(n,e,t){var s=t&&t.stringify||g_,r=1;if(typeof n=="object"&&n!==null){var i=e.length+r;if(i===1)return n;var o=new Array(i);o[0]=s(n);for(var a=1;a<i;a++)o[a]=s(e[a]);return o.join(" ")}if(typeof n!="string")return n;var l=e.length;if(l===0)return n;for(var u="",d=1-r,f=-1,h=n&&n.length||0,m=0;m<h;){if(n.charCodeAt(m)===37&&m+1<h){switch(f=f>-1?f:0,n.charCodeAt(m+1)){case 100:case 102:if(d>=l||e[d]==null)break;f<m&&(u+=n.slice(f,m)),u+=Number(e[d]),f=m+2,m++;break;case 105:if(d>=l||e[d]==null)break;f<m&&(u+=n.slice(f,m)),u+=Math.floor(Number(e[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||e[d]===void 0)break;f<m&&(u+=n.slice(f,m));var p=typeof e[d];if(p==="string"){u+="'"+e[d]+"'",f=m+2,m++;break}if(p==="function"){u+=e[d].name||"<anonymous>",f=m+2,m++;break}u+=s(e[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=n.slice(f,m)),u+=String(e[d]),f=m+2,m++;break;case 37:f<m&&(u+=n.slice(f,m)),u+="%",f=m+2,m++,d--;break}++d}++m}return f===-1?n:(f<h&&(u+=n.slice(f)),u)}});var nl=F((eR,tl)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(n,0,0,Number(t))},n=new Int32Array(new SharedArrayBuffer(4));tl.exports=e}else{let n=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let s=Date.now()+Number(e);for(;s>Date.now(););};tl.exports=n}});var Lh=F((tR,Dh)=>{"use strict";var le=require("fs"),b_=require("events"),v_=require("util").inherits,Th=require("path"),rl=nl(),w_=require("assert"),Rr=100,Or=Buffer.allocUnsafe(0),x_=16*1024,Rh="buffer",Oh="utf8",[S_,__]=(process.versions.node||"0.0").split(".").map(Number),k_=S_>=22&&__>=7;function Ph(n,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function t(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=n,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let s=e.append?"a":"w",r=e.mode;if(e.sync)try{e.mkdir&&le.mkdirSync(Th.dirname(n),{recursive:!0});let i=le.openSync(n,s,r);t(null,i)}catch(i){throw t(i),i}else e.mkdir?le.mkdir(Th.dirname(n),{recursive:!0},i=>{if(i)return t(i);le.open(n,s,r,t)}):le.open(n,s,r,t)}function lt(n){if(!(this instanceof lt))return new lt(n);let{fd:e,dest:t,minLength:s,maxLength:r,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:u,retryEAGAIN:d,fsync:f,contentMode:h,mode:m}=n||{};e=e||t,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(s||0,16387),this.file=null,this.destroyed=!1,this.minLength=s||0,this.maxLength=r||0,this.maxWrite=i||x_,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=f||!1,this.append=l||!1,this.mode=m,this.retryEAGAIN=d||(()=>!0),this.mkdir=u||!1;let p,g;if(h===Rh)this._writingBuf=Or,this.write=C_,this.flush=T_,this.flushSync=O_,this._actualWrite=M_,p=()=>le.writeSync(this.fd,this._writingBuf),g=()=>le.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===Oh)this._writingBuf="",this.write=$_,this.flush=E_,this.flushSync=R_,this._actualWrite=P_,p=()=>Buffer.isBuffer(this._writingBuf)?le.writeSync(this.fd,this._writingBuf):le.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>Buffer.isBuffer(this._writingBuf)?le.write(this.fd,this._writingBuf,this.release):le.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Oh}" and "${Rh}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Ph(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(x,w)=>{if(x){if((x.code==="EAGAIN"||x.code==="EBUSY")&&this.retryEAGAIN(x,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{rl(Rr),this.release(void 0,0)}catch(y){this.release(y)}else setTimeout(g,Rr);else this._writing=!1,this.emit("error",x);return}this.emit("write",w);let $=sl(this._writingBuf,this._len,w);if(this._len=$.len,this._writingBuf=$.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let y=p(),v=sl(this._writingBuf,this._len,y);this._len=v.len,this._writingBuf=v.writingBuf}while(this._writingBuf.length)}catch(y){this.release(y);return}}this._fsync&&le.fsyncSync(this.fd);let A=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):A>this.minLength?this._actualWrite():this._ending?A>0?this._actualWrite():(this._writing=!1,Pr(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(A_,this)):this.emit("drain"))},this.on("newListener",function(x){x==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function sl(n,e,t){return typeof n=="string"&&(n=Buffer.from(n)),e=Math.max(e-t,0),n=n.subarray(t),{writingBuf:n,len:e}}function A_(n){n.listenerCount("drain")>0&&(n._asyncDrainScheduled=!1,n.emit("drain"))}v_(lt,b_);function Mh(n,e){return n.length===0?Or:n.length===1?n[0]:Buffer.concat(n,e)}function $_(n){if(this.destroyed)throw new Error("SonicBoom destroyed");n=""+n;let e=Buffer.byteLength(n),t=this._len+e,s=this._bufs;return this.maxLength&&t>this.maxLength?(this.emit("drop",n),this._len<this._hwm):(s.length===0||Buffer.byteLength(s[s.length-1])+e>this.maxWrite?s.push(n):s[s.length-1]+=n,this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function C_(n){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+n.length,t=this._bufs,s=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",n),this._len<this._hwm):(t.length===0||s[s.length-1]+n.length>this.maxWrite?(t.push([n]),s.push(n.length)):(t[t.length-1].push(n),s[s.length-1]+=n.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Ih(n){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,n();else try{le.fsync(this.fd,s=>{this._flushPending=!1,n(s)})}catch(s){n(s)}this.off("error",t)},t=s=>{this._flushPending=!1,n(s),this.off("drain",e)};this.once("drain",e),this.once("error",t)}function E_(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(n){n(e);return}throw e}if(this.minLength<=0){n?.();return}n&&Ih.call(this,n),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function T_(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(n){n(e);return}throw e}if(this.minLength<=0){n?.();return}n&&Ih.call(this,n),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}lt.prototype.reopen=function(n){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(n)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(n&&(this.file=n),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&le.close(e,t=>{if(t)return this.emit("error",t)})}),Ph(this.file,this)};lt.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():Pr(this)))};function R_(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let n="";for(;this._bufs.length||n.length;){n.length<=0&&(n=this._bufs[0]);try{let e=Buffer.isBuffer(n)?le.writeSync(this.fd,n):le.writeSync(this.fd,n,"utf8"),t=sl(n,this._len,e);n=t.writingBuf,this._len=t.len,n.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,n.length,this._len-n.length))throw e;rl(Rr)}}try{le.fsyncSync(this.fd)}catch{}}function O_(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=Or);let n=Or;for(;this._bufs.length||n.length;){n.length<=0&&(n=Mh(this._bufs[0],this._lens[0]));try{let e=le.writeSync(this.fd,n);n=n.subarray(e),this._len=Math.max(this._len-e,0),n.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,n.length,this._len-n.length))throw e;rl(Rr)}}}lt.prototype.destroy=function(){this.destroyed||Pr(this)};function P_(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?le.writeSync(this.fd,this._writingBuf):le.writeSync(this.fd,this._writingBuf,"utf8");n(null,e)}catch(e){n(e)}else le.write(this.fd,this._writingBuf,n)}function M_(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Mh(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=le.writeSync(this.fd,this._writingBuf);n(null,e)}catch(e){n(e)}else k_&&(this._writingBuf=Buffer.from(this._writingBuf)),le.write(this.fd,this._writingBuf,n)}function Pr(n){if(n.fd===-1){n.once("ready",Pr.bind(null,n));return}n._periodicFlushTimer!==void 0&&clearInterval(n._periodicFlushTimer),n.destroyed=!0,n._bufs=[],n._lens=[],w_(typeof n.fd=="number",`sonic.fd must be a number, got ${typeof n.fd}`);try{le.fsync(n.fd,e)}catch{}function e(){n.fd!==1&&n.fd!==2?le.close(n.fd,t):t()}function t(s){if(s){n.emit("error",s);return}n._ending&&!n._writing&&n.emit("finish"),n.emit("close")}}lt.SonicBoom=lt;lt.default=lt;Dh.exports=lt});var il=F((nR,Bh)=>{"use strict";var ct={exit:[],beforeExit:[]},Nh={exit:L_,beforeExit:N_},In;function I_(){In===void 0&&(In=new FinalizationRegistry(F_))}function D_(n){ct[n].length>0||process.on(n,Nh[n])}function Fh(n){ct[n].length>0||(process.removeListener(n,Nh[n]),ct.exit.length===0&&ct.beforeExit.length===0&&(In=void 0))}function L_(){jh("exit")}function N_(){jh("beforeExit")}function jh(n){for(let e of ct[n]){let t=e.deref(),s=e.fn;t!==void 0&&s(t,n)}ct[n]=[]}function F_(n){for(let e of["exit","beforeExit"]){let t=ct[e].indexOf(n);ct[e].splice(t,t+1),Fh(e)}}function Hh(n,e,t){if(e===void 0)throw new Error("the object can't be undefined");D_(n);let s=new WeakRef(e);s.fn=t,I_(),In.register(e,s),ct[n].push(s)}function j_(n,e){Hh("exit",n,e)}function H_(n,e){Hh("beforeExit",n,e)}function B_(n){if(In!==void 0){In.unregister(n);for(let e of["exit","beforeExit"])ct[e]=ct[e].filter(t=>{let s=t.deref();return s&&s!==n}),Fh(e)}}Bh.exports={register:j_,registerBeforeExit:H_,unregister:B_}});var Uh=F((sR,U_)=>{U_.exports={name:"thread-stream",version:"4.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",engines:{node:">=20"},dependencies:{"real-require":"^1.0.0"},devDependencies:{"@types/node":"^25.0.2","@yao-pkg/pkg":"^6.0.0",borp:"^1.0.0",desm:"^1.3.0",eslint:"^9.39.1",fastbench:"^1.0.1",neostandard:"^0.13.0","pino-elasticsearch":"^9.0.0","sonic-boom":"^5.0.0","ts-node":"^10.8.0",typescript:"~5.7.3"},scripts:{build:"tsc --noEmit",lint:"eslint",test:'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:ci":'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:yarn":'npm run transpile && borp --pattern "test/*.test.js"',transpile:"sh ./test/ts/transpile.sh"},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina <hello@matteocollina.com>",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var Kh=F((rR,qh)=>{"use strict";function q_(n,e,t,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{let a=Atomics.load(n,e);if(a===t){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),u=Atomics.waitAsync(n,e,a,l);u.async?u.value.then(o):setImmediate(o)};o()}function K_(n,e,t,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{if(Atomics.load(n,e)!==t){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),u=Atomics.waitAsync(n,e,t,l);u.async?u.value.then(d=>{if(d==="ok"){r(null,"ok");return}o()}):setImmediate(o)};o()}qh.exports={wait:q_,waitDiff:K_}});var Gh=F((iR,Wh)=>{"use strict";Wh.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var rm=F((oR,sm)=>{"use strict";var{version:W_}=Uh(),{EventEmitter:G_}=require("events"),{Worker:V_}=require("worker_threads"),{join:z_}=require("path"),{pathToFileURL:Y_}=require("url"),{wait:J_}=Kh(),{WRITE_INDEX:Dt,READ_INDEX:on,SEQ_INDEX:ol}=Gh(),X_=require("buffer"),Q_=require("assert"),R=Symbol("kImpl"),Z_=X_.constants.MAX_STRING_LENGTH;function Vh(){}function ul(n,e){Atomics.add(n[R].state,ol,1),e(),Atomics.add(n[R].state,ol,1),Atomics.notify(n[R].state,ol)}function zh(n){ul(n,()=>{Atomics.store(n[R].state,on,0),Atomics.store(n[R].state,Dt,0)})}var ps=class{constructor(e){this._value=e}deref(){return this._value}},Mr=class{register(){}unregister(){}},ek=process.env.NODE_V8_COVERAGE?Mr:global.FinalizationRegistry||Mr,tk=process.env.NODE_V8_COVERAGE?ps:global.WeakRef||ps,Yh=new ek(n=>{n.exited||n.terminate()});function nk(n,e){let{filename:t,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||z_(__dirname,"lib","worker.js"),o=new V_(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:t.indexOf("file://")===0?t:Y_(t).href,dataBuf:n[R].dataBuf,stateBuf:n[R].stateBuf,workerData:{$context:{threadStreamVersion:W_},...s}}});return o.stream=new ps(n),o.on("message",sk),o.on("exit",Qh),Yh.register(n,o),o}function Jh(n){Q_(!n[R].sync),n[R].needDrain&&(n[R].needDrain=!1,n.emit("drain"))}function Xh(n){for(;;){let e=Atomics.load(n[R].state,Dt),t=n[R].data.length-e;if(t>0){if(n[R].bufLen===0){n[R].flushing=!1,n[R].ending?dl(n):n[R].needDrain&&process.nextTick(Jh,n);return}tm(n,t,Vh);continue}if(t===0){if(e===0&&n[R].bufLen===0)return;Ir(n,()=>{n.destroyed||(zh(n),Xh(n))});return}Ze(n,new Error("overwritten"));return}}function sk(n){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(n?.code!=null)switch(n.code){case"READY":this.stream=new tk(e),Ir(e,()=>{e[R].ready=!0,e.emit("ready")});break;case"ERROR":Ze(e,n.err);break;case"EVENT":Array.isArray(n.args)?e.emit(n.name,...n.args):e.emit(n.name,n.args);break;case"FLUSHED":{if(n.context!=="thread-stream"){Ze(e,new Error("this should not happen: "+n.code));break}let t=e[R].flushCallbacks.get(n.id);t&&(e[R].flushCallbacks.delete(n.id),process.nextTick(t));break}case"WARNING":process.emitWarning(n.err);break;default:Ze(e,new Error("this should not happen: "+n.code))}}function Qh(n){let e=this.stream.deref();e!==void 0&&(Yh.unregister(e),e.worker.exited=!0,e.worker.off("exit",Qh),Ze(e,n!==0?new Error("the worker thread exited"):null))}var ll=class extends G_{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[R]={},this[R].stateBuf=new SharedArrayBuffer(128),this[R].state=new Int32Array(this[R].stateBuf),this[R].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[R].data=Buffer.from(this[R].dataBuf),this[R].sync=e.sync||!1,this[R].ending=!1,this[R].ended=!1,this[R].needDrain=!1,this[R].destroyed=!1,this[R].flushing=!1,this[R].ready=!1,this[R].finished=!1,this[R].errored=null,this[R].closed=!1,this[R].buf=[],this[R].bufHead=0,this[R].bufLen=0,this[R].flushCallbacks=new Map,this[R].nextFlushId=0,this.worker=nk(this,e),this.on("message",(t,s)=>{this.worker.postMessage(t,s)})}write(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[R].destroyed)return cl(this,new Error("the worker has exited")),!1;if(this[R].ending)return cl(this,new Error("the worker is ending")),!1;if(this[R].flushing&&this[R].bufLen+t.length>=Z_)try{al(this),this[R].flushing=!0}catch(s){return Ze(this,s),!1}if(this[R].buf.push(t),this[R].bufLen+=t.length,this[R].sync)try{return al(this),!0}catch(s){return Ze(this,s),!1}return this[R].flushing||(this[R].flushing=!0,setImmediate(Xh,this)),this[R].needDrain=this[R].data.length-this[R].bufLen-Atomics.load(this[R].state,Dt)<=0,!this[R].needDrain}end(){this[R].destroyed||(this[R].ending=!0,dl(this))}flush(e){e=typeof e=="function"?e:Vh,Zh(this,t=>{if(t){process.nextTick(e,t);return}em(this,e)})}flushSync(){this[R].destroyed||(al(this),nm(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[R].ready}get destroyed(){return this[R].destroyed}get closed(){return this[R].closed}get writable(){return!this[R].destroyed&&!this[R].ending}get writableEnded(){return this[R].ending}get writableFinished(){return this[R].finished}get writableNeedDrain(){return this[R].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[R].errored}};function Zh(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].sync&&(n[R].flushing||n[R].bufLen>0)){setImmediate(Zh,n,e);return}Ir(n,e)}function Ir(n,e){let t=Atomics.load(n[R].state,Dt);J_(n[R].state,on,t,1/0,(s,r)=>{if(s){Ze(n,s),e(s);return}if(r!=="ok"){Ir(n,e);return}e()})}function em(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].ready){let s=()=>{i(),em(n,e)},r=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{n.off("ready",s),n.off("close",r)};n.once("ready",s),n.once("close",r);return}let t=++n[R].nextFlushId;n[R].flushCallbacks.set(t,e);try{n.worker.postMessage({code:"FLUSH",context:"thread-stream",id:t})}catch(s){n[R].flushCallbacks.delete(t),Ze(n,s),process.nextTick(e,s)}}function rk(n,e){let t=n[R].flushCallbacks;if(t.size===0)return;let s=e||new Error("the worker has exited");for(let r of t.values())process.nextTick(r,s);t.clear()}function cl(n,e){setImmediate(()=>{n.emit("error",e)})}function Ze(n,e){n[R].destroyed||(n[R].destroyed=!0,rk(n,e),e&&(n[R].errored=e,cl(n,e)),n.worker.exited?setImmediate(()=>{n[R].closed=!0,n.emit("close")}):n.worker.terminate().catch(()=>{}).then(()=>{n[R].closed=!0,n.emit("close")}))}function tm(n,e,t){let r=Atomics.load(n[R].state,Dt),i=e;for(;i>0&&n[R].bufLen!==0;){let o=n[R].bufHead,a=n[R].buf[o];if(a.length<=i){a.copy(n[R].data,r),r+=a.length,i-=a.length,n[R].bufLen-=a.length,n[R].bufHead=o+1,n[R].bufHead===n[R].buf.length?(n[R].buf.length=0,n[R].bufHead=0):n[R].bufHead>=1024&&n[R].bufHead*2>=n[R].buf.length&&(n[R].buf.splice(0,n[R].bufHead),n[R].bufHead=0);continue}a.copy(n[R].data,r,0,i),n[R].buf[o]=a.subarray(i),n[R].bufLen-=i,r+=i,i=0}return ul(n,()=>{Atomics.store(n[R].state,Dt,r)}),t(),!0}function dl(n){if(!(n[R].ended||!n[R].ending||n[R].flushing)){n[R].ended=!0;try{n.flushSync();let e=Atomics.load(n[R].state,on);ul(n,()=>{Atomics.store(n[R].state,Dt,-1)});let t=0;for(;e!==-1;){if(Atomics.wait(n[R].state,on,e,1e3),e=Atomics.load(n[R].state,on),e===-2){Ze(n,new Error("end() failed"));return}if(++t===10){Ze(n,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{n[R].finished=!0,n.emit("finish")})}catch(e){Ze(n,e)}}}function al(n){let e=()=>{n[R].ending?dl(n):n[R].needDrain&&process.nextTick(Jh,n)};for(n[R].flushing=!1;n[R].bufLen!==0;){let t=Atomics.load(n[R].state,Dt),s=n[R].data.length-t;if(s===0){nm(n),zh(n);continue}else if(s<0)throw new Error("overwritten");tm(n,s,e)}}function nm(n){if(n[R].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(n[R].state,Dt),t=0;for(;;){let s=Atomics.load(n[R].state,on);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(n[R].state,on,s,1e3);else break;if(++t===10)throw new Error("_flushSync took too long (10s)")}}sm.exports=ll});var hl=F((aR,am)=>{"use strict";var{createRequire:ik}=require("module"),{existsSync:ok}=require("node:fs"),ak=Xa(),{join:fl,isAbsolute:om,sep:lk}=require("node:path"),{fileURLToPath:ck}=require("node:url"),uk=nl(),pl=il(),dk=rm();function fk(n){pl.register(n,yk),pl.registerBeforeExit(n,bk),n.on("close",function(){pl.unregister(n)})}function pk(){let n=process.execArgv;for(let e=0;e<n.length;e++){let t=n[e];if(t==="--import"||t==="--require"||t==="-r"||t.startsWith("--import=")||t.startsWith("--require=")||t.startsWith("-r="))return!0}return!1}function hk(n){let e=n.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return n;let t=[],s=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i==="--require"||i==="-r"||i==="--import"){let o=e[r+1];if(o&&im(o)){s=!0,r++;continue}t.push(i),o&&(t.push(o),r++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(im(o)){s=!0;continue}}t.push(i)}return s?t.join(" "):n}function im(n){let e=mk(n);if(!e)return!1;let t=e;if(t.startsWith("file://"))try{t=ck(t)}catch{return!1}return om(t)&&!ok(t)}function mk(n){let e=n[0],t=n[n.length-1];return e==='"'&&t==='"'||e==="'"&&t==="'"?n.slice(1,-1):n}function gk(n,e,t,s,r){if(!t.execArgv&&pk()&&require.main===void 0&&(t={...t,execArgv:[]}),!t.env&&process.env.NODE_OPTIONS){let l=hk(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(t={...t,env:{...process.env,NODE_OPTIONS:l}})}t={...t,name:r};let i=new dk({filename:n,workerData:e,workerOpts:t,sync:s});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),t.autoEnd!==!1&&fk(i)}function a(){i.closed||(i.flushSync(),uk(100),i.end())}return i}function yk(n){n.ref(),n.flushSync(),n.end(),n.once("close",function(){n.unref()})}function bk(n){n.flushSync()}function vk(n){let{pipeline:e,targets:t,levels:s,dedupe:r,worker:i={},caller:o=ak(),sync:a=!1}=n,l={...n.options},u=typeof o=="string"?[o]:o,d=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),f=n.target;if(f&&t)throw new Error("only one of target or targets can be specified");t?(f=d["pino-worker"]||fl(__dirname,"worker.js"),l.targets=t.filter(p=>p.target).map(p=>({...p,target:m(p.target)})),l.pipelines=t.filter(p=>p.pipeline).map(p=>p.pipeline.map(g=>({...g,level:p.level,target:m(g.target)})))):e&&(f=d["pino-worker"]||fl(__dirname,"worker.js"),l.pipelines=[e.map(p=>({...p,target:m(p.target)}))]),s&&(l.levels=s),r&&(l.dedupe=r),l.pinoWillSendConfig=!0;let h=t||e?"pino.transport":f;return gk(m(f),l,i,a,h);function m(p){if(p=d[p]||p,om(p)||p.indexOf("file://")===0)return p;if(p==="pino/file")return fl(__dirname,"..","file.js");let g;for(let x of u)try{let w=x==="node:repl"?process.cwd()+lk:x;g=ik(w).resolve(p);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${p}"`);return g}}am.exports=vk});var Nr=F((lR,wm)=>{"use strict";var wk=require("node:diagnostics_channel"),lm=Eh(),{mapHttpRequest:xk,mapHttpResponse:Sk}=Ja(),gl=Lh(),cm=il(),{lsCacheSym:_k,chindingsSym:hm,writeSym:um,serializersSym:mm,formatOptsSym:dm,endSym:kk,stringifiersSym:gm,stringifySym:ym,stringifySafeSym:yl,wildcardFirstSym:bm,nestedKeySym:Ak,formattersSym:vm,messageKeySym:$k,errorKeySym:Ck,nestedKeyStrSym:Ek,msgPrefixSym:Dr}=Mn(),{isMainThread:Tk}=require("worker_threads"),Rk=hl(),[Ok]=process.versions.node.split(".").map(n=>Number(n)),fm=wk.tracingChannel("pino_asJson"),ml=Ok>=25?n=>JSON.stringify(n):Mk;function Dn(){}function Pk(n,e){if(!e)return t;return function(...r){e.call(this,r,t,n)};function t(s,...r){if(typeof s=="object"){let i=s;s!==null&&(s.method&&s.headers&&s.socket?s=xk(s):typeof s.setHeader=="function"&&(s=Sk(s)));let o;i===null&&r.length===0?o=[null]:(i=r.shift(),o=r),typeof this[Dr]=="string"&&i!==void 0&&i!==null&&(i=this[Dr]+i),this[um](s,lm(i,o,this[dm]),n)}else{let i=s===void 0?r.shift():s;typeof this[Dr]=="string"&&i!==void 0&&i!==null&&(i=this[Dr]+i),this[um](null,lm(i,r,this[dm]),n)}}}function Mk(n){let e="",t=0,s=!1,r=255,i=n.length;if(i>100)return JSON.stringify(n);for(var o=0;o<i&&r>=32;o++)r=n.charCodeAt(o),(r===34||r===92)&&(e+=n.slice(t,o)+"\\",t=o,s=!0);return s?e+=n.slice(t):e=n,r<32?JSON.stringify(n):'"'+e+'"'}function Ik(n,e,t,s){if(fm.hasSubscribers===!1)return pm.call(this,n,e,t,s);let r={instance:this,arguments};return fm.traceSync(pm,r,this,n,e,t,s)}function pm(n,e,t,s){let r=this[ym],i=this[yl],o=this[gm],a=this[kk],l=this[hm],u=this[mm],d=this[vm],f=this[$k],h=this[Ck],m=this[_k][t]+s;m=m+l;let p;d.log&&(n=d.log(n));let g=o[bm],x="";for(let $ in n)if(p=n[$],Object.prototype.hasOwnProperty.call(n,$)&&p!==void 0){u[$]?p=u[$](p):$===h&&u.err&&(p=u.err(p));let A=o[$]||g;switch(typeof p){case"undefined":case"function":continue;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":A&&(p=A(p));break;case"string":p=(A||ml)(p);break;default:p=(A||r)(p,i)}if(p===void 0)continue;let y=ml($);x+=","+y+":"+p}let w="";if(e!==void 0){p=u[f]?u[f](e):e;let $=o[f]||g;switch(typeof p){case"function":break;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":$&&(p=$(p)),w=',"'+f+'":'+p;break;case"string":p=($||ml)(p),w=',"'+f+'":'+p;break;default:p=($||r)(p,i),w=',"'+f+'":'+p}}return this[Ak]&&x?m+this[Ek]+x.slice(1)+"}"+w+a:m+x+w+a}function Dk(n,e){let t,s=n[hm],r=n[ym],i=n[yl],o=n[gm],a=o[bm],l=n[mm],u=n[vm].bindings;e=u(e);for(let d in e)if(t=e[d],((d.length<5||d!=="level"&&d!=="serializers"&&d!=="formatters"&&d!=="customLevels")&&e.hasOwnProperty(d)&&t!==void 0)===!0){if(t=l[d]?l[d](t):t,t=(o[d]||a||r)(t,i),t===void 0)continue;s+=',"'+d+'":'+t}return s}function Lk(n){return n.write!==n.constructor.prototype.write}function Lr(n){let e=new gl(n);return e.on("error",t),!n.sync&&Tk&&(cm.register(e,Nk),e.on("close",function(){cm.unregister(e)})),e;function t(s){if(s.code==="EPIPE"){e.write=Dn,e.end=Dn,e.flushSync=Dn,e.destroy=Dn;return}e.removeListener("error",t),e.emit("error",s)}}function Nk(n,e){n.destroyed||(e==="beforeExit"?(n.flush(),n.on("drain",function(){n.end()})):n.flushSync())}function Fk(n){return function(t,s,r={},i){if(typeof r=="string")i=Lr({dest:r}),r={};else if(typeof i=="string"){if(r&&r.transport)throw Error("only one of option.transport or stream can be specified");i=Lr({dest:i})}else if(r instanceof gl||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof gl||r.transport.writable||r.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;r.customLevels&&(l=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=Rk({caller:s,...r.transport,levels:l})}if(r=Object.assign({},n,r),r.serializers=Object.assign({},n.serializers,r.serializers),r.formatters=Object.assign({},n.formatters,r.formatters),r.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=r;return o===!1&&(r.level="silent"),a||(r.onChild=Dn),i||(Lk(process.stdout)?i=process.stdout:i=Lr({fd:process.stdout.fd||1})),{opts:r,stream:i}}}function jk(n,e){try{return JSON.stringify(n)}catch{try{return(e||this[yl])(n)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Hk(n,e,t){return{level:n,bindings:e,log:t}}function Bk(n){let e=Number(n);return typeof n=="string"&&Number.isFinite(e)?e:n===void 0?1:n}wm.exports={noop:Dn,buildSafeSonicBoom:Lr,asChindings:Dk,asJson:Ik,genLog:Pk,createArgsNormalizer:Fk,stringify:jk,buildFormatters:Hk,normalizeDestFileDescriptor:Bk}});var Fr=F((cR,xm)=>{var Uk={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},qk={ASC:"ASC",DESC:"DESC"};xm.exports={DEFAULT_LEVELS:Uk,SORTING_ORDER:qk}});var wl=F((uR,Am)=>{"use strict";var{lsCacheSym:Kk,levelValSym:bl,useOnlyCustomLevelsSym:Wk,streamSym:Gk,formattersSym:Vk,hooksSym:zk,levelCompSym:Sm}=Mn(),{noop:Yk,genLog:an}=Nr(),{DEFAULT_LEVELS:wt,SORTING_ORDER:_m}=Fr(),km={fatal:n=>{let e=an(wt.fatal,n);return function(...t){let s=this[Gk];if(e.call(this,...t),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:n=>an(wt.error,n),warn:n=>an(wt.warn,n),info:n=>an(wt.info,n),debug:n=>an(wt.debug,n),trace:n=>an(wt.trace,n)},vl=Object.keys(wt).reduce((n,e)=>(n[wt[e]]=e,n),{}),Jk=Object.keys(vl).reduce((n,e)=>(n[e]='{"level":'+Number(e),n),{});function Xk(n){let e=n[Vk].level,{labels:t}=n.levels,s={};for(let r in t){let i=e(t[r],Number(r));s[r]=JSON.stringify(i).slice(0,-1)}return n[Kk]=s,n}function Qk(n,e){if(e)return!1;switch(n){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function Zk(n){let{labels:e,values:t}=this.levels;if(typeof n=="number"){if(e[n]===void 0)throw Error("unknown level value"+n);n=e[n]}if(t[n]===void 0)throw Error("unknown level "+n);let s=this[bl],r=this[bl]=t[n],i=this[Wk],o=this[Sm],a=this[zk].logMethod;for(let l in t){if(o(t[l],r)===!1){this[l]=Yk;continue}this[l]=Qk(l,i)?km[l](a):an(t[l],a)}this.emit("level-change",n,r,e[s],s,this)}function eA(n){let{levels:e,levelVal:t}=this;return e&&e.labels?e.labels[t]:""}function tA(n){let{values:e}=this.levels,t=e[n];return t!==void 0&&this[Sm](t,this[bl])}function nA(n,e,t){return n===_m.DESC?e<=t:e>=t}function sA(n){return typeof n=="string"?nA.bind(null,n):n}function rA(n=null,e=!1){let t=n?Object.keys(n).reduce((i,o)=>(i[n[o]]=o,i),{}):null,s=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:vl,t),r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:wt,n);return{labels:s,values:r}}function iA(n,e,t){if(typeof n=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),t?[]:Object.keys(vl).map(i=>+i),1/0).includes(n))throw Error(`default level:${n} must be included in custom levels`);return}let s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:wt,e);if(!(n in s))throw Error(`default level:${n} must be included in custom levels`)}function oA(n,e){let{labels:t,values:s}=n;for(let r in e){if(r in s)throw Error("levels cannot be overridden");if(e[r]in t)throw Error("pre-existing level values cannot be used for new levels")}}function aA(n){if(typeof n!="function"&&!(typeof n=="string"&&Object.values(_m).includes(n)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Am.exports={initialLsCache:Jk,genLsCache:Xk,levelMethods:km,getLevel:eA,setLevel:Zk,isLevelEnabled:tA,mappings:rA,assertNoLevelCollisions:oA,assertDefaultLevelFound:iA,genLevelComparison:sA,assertLevelComparison:aA}});var xl=F((dR,$m)=>{"use strict";$m.exports={version:"10.3.1"}});var Im=F((pR,Mm)=>{"use strict";var{EventEmitter:lA}=require("node:events"),{lsCacheSym:cA,levelValSym:uA,setLevelSym:_l,getLevelSym:Cm,chindingsSym:Hr,mixinSym:dA,asJsonSym:Tm,writeSym:fA,mixinMergeStrategySym:pA,timeSym:hA,timeSliceIndexSym:mA,streamSym:Rm,serializersSym:ln,formattersSym:hs,errorKeySym:gA,messageKeySym:yA,useOnlyCustomLevelsSym:bA,needsMetadataGsym:vA,redactFmtSym:wA,stringifySym:xA,formatOptsSym:SA,stringifiersSym:_A,msgPrefixSym:kl,hooksSym:kA}=Mn(),{getLevel:AA,setLevel:$A,isLevelEnabled:CA,mappings:EA,initialLsCache:TA,genLsCache:RA,assertNoLevelCollisions:OA}=wl(),{asChindings:Al,asJson:PA,buildFormatters:Sl,stringify:Em,noop:Om}=Nr(),{version:MA}=xl(),IA=el(),DA=class{},Pm={constructor:DA,child:LA,bindings:NA,setBindings:FA,flush:BA,isLevelEnabled:CA,version:MA,get level(){return this[Cm]()},set level(n){this[_l](n)},get levelVal(){return this[uA]},set levelVal(n){throw Error("levelVal is read-only")},get msgPrefix(){return this[kl]},get[Symbol.toStringTag](){return"Pino"},[cA]:TA,[fA]:HA,[Tm]:PA,[Cm]:AA,[_l]:$A};Object.setPrototypeOf(Pm,lA.prototype);Mm.exports=function(){return Object.create(Pm)};var jr=n=>n;function LA(n,e){if(!n)throw Error("missing bindings for child Pino");let t=this[ln],s=this[hs],r=Object.create(this);if(e==null)return r[hs].bindings!==jr&&(r[hs]=Sl(s.level,jr,s.log)),r[Hr]=Al(r,n),this.onChild!==Om&&this.onChild(r),r;if(e.hasOwnProperty("serializers")===!0){r[ln]=Object.create(null);for(let u in t)r[ln][u]=t[u];let a=Object.getOwnPropertySymbols(t);for(var i=0;i<a.length;i++){let u=a[i];r[ln][u]=t[u]}for(let u in e.serializers)r[ln][u]=e.serializers[u];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let u=l[o];r[ln][u]=e.serializers[u]}}else r[ln]=t;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:u}=e.formatters;r[hs]=Sl(a||s.level,l||jr,u||s.log)}else r[hs]=Sl(s.level,jr,s.log);if(e.hasOwnProperty("customLevels")===!0&&(OA(this.levels,e.customLevels),r.levels=EA(e.customLevels,r[bA]),RA(r)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){r.redact=e.redact;let a=IA(r.redact,Em),l={stringify:a[wA]};r[xA]=Em,r[_A]=a,r[SA]=l}if(typeof e.msgPrefix=="string"&&(r[kl]=(this[kl]||"")+e.msgPrefix),r[Hr]=Al(r,n),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;r[_l](a)}return this.onChild(r),r}function NA(){let e=`{${this[Hr].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function FA(n){let e=Al(this,n);this[Hr]=e}function jA(n,e){return Object.assign(e,n)}function HA(n,e,t){let s=this[hA](),r=this[dA],i=this[gA],o=this[yA],a=this[pA]||jA,l,u=this[kA].streamWrite;n==null?l={}:n instanceof Error?(l={[i]:n},e===void 0&&(e=n.message)):(l=n,e===void 0&&n[o]===void 0&&n[i]&&(e=n[i].message)),r&&(l=a(l,r(l,t,this)));let d=this[Tm](l,e,t,s),f=this[Rm];f[vA]===!0&&(f.lastLevel=t,f.lastObj=l,f.lastMsg=e,f.lastTime=s.slice(this[mA]),f.lastLogger=this),f.write(u?u(d):d)}function BA(n){if(n!=null&&typeof n!="function")throw Error("callback must be a function");let e=this[Rm];typeof e.flush=="function"?e.flush(n||Om):n&&n()}});var Fm=F((Tl,Nm)=>{"use strict";var{hasOwnProperty:ms}=Object.prototype,un=El();un.configure=El;un.stringify=un;un.default=un;Tl.stringify=un;Tl.configure=El;Nm.exports=un;var UA=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function qt(n){return n.length<5e3&&!UA.test(n)?`"${n}"`:JSON.stringify(n)}function $l(n,e){if(n.length>200||e)return n.sort(e);for(let t=1;t<n.length;t++){let s=n[t],r=t;for(;r!==0&&n[r-1]>s;)n[r]=n[r-1],r--;n[r]=s}return n}var qA=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Cl(n){return qA.call(n)!==void 0&&n.length!==0}function Dm(n,e,t){n.length<t&&(t=n.length);let s=e===","?"":" ",r=`"0":${s}${n[0]}`;for(let i=1;i<t;i++)r+=`${e}"${i}":${s}${n[i]}`;return r}function KA(n){if(ms.call(n,"circularValue")){let e=n.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function WA(n){let e;if(ms.call(n,"deterministic")&&(e=n.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function GA(n,e){let t;if(ms.call(n,e)&&(t=n[e],typeof t!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return t===void 0?!0:t}function Lm(n,e){let t;if(ms.call(n,e)){if(t=n[e],typeof t!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(t))throw new TypeError(`The "${e}" argument must be an integer`);if(t<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return t===void 0?1/0:t}function cn(n){return n===1?"1 item":`${n} items`}function VA(n){let e=new Set;for(let t of n)(typeof t=="string"||typeof t=="number")&&e.add(String(t));return e}function zA(n){if(ms.call(n,"strict")){let e=n.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return t=>{let s=`Object can not safely be stringified. Received type ${typeof t}`;throw typeof t!="function"&&(s+=` (${t.toString()})`),new Error(s)}}}function El(n){n={...n};let e=zA(n);e&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let t=KA(n),s=GA(n,"bigint"),r=WA(n),i=typeof r=="function"?r:void 0,o=Lm(n,"maximumDepth"),a=Lm(n,"maximumBreadth");function l(m,p,g,x,w,$){let A=p[m];switch(typeof A=="object"&&A!==null&&typeof A.toJSON=="function"&&(A=A.toJSON(m)),A=x.call(p,m,A),typeof A){case"string":return qt(A);case"object":{if(A===null)return"null";if(g.indexOf(A)!==-1)return t;let y="",v=",",b=$;if(Array.isArray(A)){if(A.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(A),w!==""&&($+=w,y+=`
884
948
  ${$}`,v=`,
885
- ${$}`);let F=Math.min(A.length,a),H=0;for(;H<F-1;H++){let E=l(String(H),A,g,x,w,$);y+=E!==void 0?E:"null",y+=v}let G=l(String(H),A,g,x,w,$);if(y+=G!==void 0?G:"null",A.length-1>a){let E=A.length-a-1;y+=`${v}"... ${ln(E)} not stringified"`}return w!==""&&(y+=`
949
+ ${$}`);let N=Math.min(A.length,a),H=0;for(;H<N-1;H++){let E=l(String(H),A,g,x,w,$);y+=E!==void 0?E:"null",y+=v}let G=l(String(H),A,g,x,w,$);if(y+=G!==void 0?G:"null",A.length-1>a){let E=A.length-a-1;y+=`${v}"... ${cn(E)} not stringified"`}return w!==""&&(y+=`
886
950
  ${b}`),g.pop(),`[${y}]`}let S=Object.keys(A),_=S.length;if(_===0)return"{}";if(o<g.length+1)return'"[Object]"';let T="",I="";w!==""&&($+=w,v=`,
887
- ${$}`,T=" ");let C=Math.min(_,a);r&&!kl(A)&&(S=_l(S,i)),g.push(A);for(let F=0;F<C;F++){let H=S[F],G=l(H,A,g,x,w,$);G!==void 0&&(y+=`${I}${qt(H)}:${T}${G}`,I=v)}if(_>a){let F=_-a;y+=`${I}"...":${T}"${ln(F)} not stringified"`,I=v}return w!==""&&I.length>1&&(y=`
951
+ ${$}`,T=" ");let C=Math.min(_,a);r&&!Cl(A)&&(S=$l(S,i)),g.push(A);for(let N=0;N<C;N++){let H=S[N],G=l(H,A,g,x,w,$);G!==void 0&&(y+=`${I}${qt(H)}:${T}${G}`,I=v)}if(_>a){let N=_-a;y+=`${I}"...":${T}"${cn(N)} not stringified"`,I=v}return w!==""&&I.length>1&&(y=`
888
952
  ${$}${y}
889
953
  ${b}`),g.pop(),`{${y}}`}case"number":return isFinite(A)?String(A):e?e(A):"null";case"boolean":return A===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(A);default:return e?e(A):void 0}}function u(m,p,g,x,w,$){switch(typeof p=="object"&&p!==null&&typeof p.toJSON=="function"&&(p=p.toJSON(m)),typeof p){case"string":return qt(p);case"object":{if(p===null)return"null";if(g.indexOf(p)!==-1)return t;let A=$,y="",v=",";if(Array.isArray(p)){if(p.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(p),w!==""&&($+=w,y+=`
890
954
  ${$}`,v=`,
891
- ${$}`);let _=Math.min(p.length,a),T=0;for(;T<_-1;T++){let C=u(String(T),p[T],g,x,w,$);y+=C!==void 0?C:"null",y+=v}let I=u(String(T),p[T],g,x,w,$);if(y+=I!==void 0?I:"null",p.length-1>a){let C=p.length-a-1;y+=`${v}"... ${ln(C)} not stringified"`}return w!==""&&(y+=`
955
+ ${$}`);let _=Math.min(p.length,a),T=0;for(;T<_-1;T++){let C=u(String(T),p[T],g,x,w,$);y+=C!==void 0?C:"null",y+=v}let I=u(String(T),p[T],g,x,w,$);if(y+=I!==void 0?I:"null",p.length-1>a){let C=p.length-a-1;y+=`${v}"... ${cn(C)} not stringified"`}return w!==""&&(y+=`
892
956
  ${A}`),g.pop(),`[${y}]`}g.push(p);let b="";w!==""&&($+=w,v=`,
893
957
  ${$}`,b=" ");let S="";for(let _ of x){let T=u(_,p[_],g,x,w,$);T!==void 0&&(y+=`${S}${qt(_)}:${b}${T}`,S=v)}return w!==""&&S.length>1&&(y=`
894
958
  ${$}${y}
895
959
  ${A}`),g.pop(),`{${y}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function d(m,p,g,x,w){switch(typeof p){case"string":return qt(p);case"object":{if(p===null)return"null";if(typeof p.toJSON=="function"){if(p=p.toJSON(m),typeof p!="object")return d(m,p,g,x,w);if(p===null)return"null"}if(g.indexOf(p)!==-1)return t;let $=w;if(Array.isArray(p)){if(p.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(p),w+=x;let T=`
896
960
  ${w}`,I=`,
897
- ${w}`,C=Math.min(p.length,a),F=0;for(;F<C-1;F++){let G=d(String(F),p[F],g,x,w);T+=G!==void 0?G:"null",T+=I}let H=d(String(F),p[F],g,x,w);if(T+=H!==void 0?H:"null",p.length-1>a){let G=p.length-a-1;T+=`${I}"... ${ln(G)} not stringified"`}return T+=`
961
+ ${w}`,C=Math.min(p.length,a),N=0;for(;N<C-1;N++){let G=d(String(N),p[N],g,x,w);T+=G!==void 0?G:"null",T+=I}let H=d(String(N),p[N],g,x,w);if(T+=H!==void 0?H:"null",p.length-1>a){let G=p.length-a-1;T+=`${I}"... ${cn(G)} not stringified"`}return T+=`
898
962
  ${$}`,g.pop(),`[${T}]`}let A=Object.keys(p),y=A.length;if(y===0)return"{}";if(o<g.length+1)return'"[Object]"';w+=x;let v=`,
899
- ${w}`,b="",S="",_=Math.min(y,a);kl(p)&&(b+=Rm(p,v,a),A=A.slice(p.length),_-=p.length,S=v),r&&(A=_l(A,i)),g.push(p);for(let T=0;T<_;T++){let I=A[T],C=d(I,p[I],g,x,w);C!==void 0&&(b+=`${S}${qt(I)}: ${C}`,S=v)}if(y>a){let T=y-a;b+=`${S}"...": "${ln(T)} not stringified"`,S=v}return S!==""&&(b=`
963
+ ${w}`,b="",S="",_=Math.min(y,a);Cl(p)&&(b+=Dm(p,v,a),A=A.slice(p.length),_-=p.length,S=v),r&&(A=$l(A,i)),g.push(p);for(let T=0;T<_;T++){let I=A[T],C=d(I,p[I],g,x,w);C!==void 0&&(b+=`${S}${qt(I)}: ${C}`,S=v)}if(y>a){let T=y-a;b+=`${S}"...": "${cn(T)} not stringified"`,S=v}return S!==""&&(b=`
900
964
  ${w}${b}
901
- ${$}`),g.pop(),`{${b}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function f(m,p,g){switch(typeof p){case"string":return qt(p);case"object":{if(p===null)return"null";if(typeof p.toJSON=="function"){if(p=p.toJSON(m),typeof p!="object")return f(m,p,g);if(p===null)return"null"}if(g.indexOf(p)!==-1)return t;let x="",w=p.length!==void 0;if(w&&Array.isArray(p)){if(p.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(p);let b=Math.min(p.length,a),S=0;for(;S<b-1;S++){let T=f(String(S),p[S],g);x+=T!==void 0?T:"null",x+=","}let _=f(String(S),p[S],g);if(x+=_!==void 0?_:"null",p.length-1>a){let T=p.length-a-1;x+=`,"... ${ln(T)} not stringified"`}return g.pop(),`[${x}]`}let $=Object.keys(p),A=$.length;if(A===0)return"{}";if(o<g.length+1)return'"[Object]"';let y="",v=Math.min(A,a);w&&kl(p)&&(x+=Rm(p,",",a),$=$.slice(p.length),v-=p.length,y=","),r&&($=_l($,i)),g.push(p);for(let b=0;b<v;b++){let S=$[b],_=f(S,p[S],g);_!==void 0&&(x+=`${y}${qt(S)}:${_}`,y=",")}if(A>a){let b=A-a;x+=`${y}"...":"${ln(b)} not stringified"`}return g.pop(),`{${x}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function h(m,p,g){if(arguments.length>1){let x="";if(typeof g=="number"?x=" ".repeat(Math.min(g,10)):typeof g=="string"&&(x=g.slice(0,10)),p!=null){if(typeof p=="function")return l("",{"":m},[],p,x,"");if(Array.isArray(p))return u("",m,[],UA(p),x,"")}if(x.length!==0)return d("",m,[],x,"")}return f("",m,[])}return h}});var Fm=N((cR,Lm)=>{"use strict";var Cl=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Dm}=Lr(),KA=Dm.info;function WA(n,e){n=n||[],e=e||{dedupe:!1};let t=Object.create(Dm);t.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(f=>{t[f]=e.levels[f]});let s={write:r,add:a,remove:l,emit:i,flushSync:o,end:u,minLevel:0,lastId:0,streams:[],clone:d,[Cl]:!0,streamLevels:t};return Array.isArray(n)?n.forEach(a,s):a.call(s,n),n=null,s;function r(f){let h,m=this.lastLevel,{streams:p}=this,g=0,x;for(let w=GA(p.length,e.dedupe);zA(w,p.length,e.dedupe);w=VA(w,e.dedupe))if(h=p[w],h.level<=m){if(g!==0&&g!==h.level)break;if(x=h.stream,x[Cl]){let{lastTime:$,lastMsg:A,lastObj:y,lastLogger:v}=this;x.lastLevel=m,x.lastTime=$,x.lastMsg=A,x.lastObj=y,x.lastLogger=v}x.write(f),e.dedupe&&(g=h.level)}else if(!e.dedupe)break}function i(...f){for(let{stream:h}of this.streams)typeof h.emit=="function"&&h.emit(...f)}function o(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync()}function a(f){if(!f)return s;let h=typeof f.write=="function"||f.stream,m=f.write?f:f.stream;if(!h)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:p,streamLevels:g}=this,x;typeof f.levelVal=="number"?x=f.levelVal:typeof f.level=="string"?x=g[f.level]:typeof f.level=="number"?x=f.level:x=KA;let w={stream:m,level:x,levelVal:void 0,id:++s.lastId};return p.unshift(w),p.sort(Im),this.minLevel=p[0].level,s}function l(f){let{streams:h}=this,m=h.findIndex(p=>p.id===f);return m>=0&&(h.splice(m,1),h.sort(Im),this.minLevel=h.length>0?h[0].level:-1),s}function u(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync(),f.end()}function d(f){let h=new Array(this.streams.length);for(let m=0;m<h.length;m++)h[m]={level:f,stream:this.streams[m].stream};return{write:r,add:a,remove:l,minLevel:f,streams:h,clone:d,emit:i,flushSync:o,[Cl]:!0}}}function Im(n,e){return n.level-e.level}function GA(n,e){return e?n-1:0}function VA(n,e){return e?n-1:n+1}function zA(n,e,t){return t?n>=0:n<e}Lm.exports=WA});var Ol=N((uR,Ze)=>{"use strict";var YA=require("node:os"),Wm=Va(),JA=za(),XA=Xa(),Gm=xh(),QA=Tm(),Vm=Pn(),{configure:ZA}=Mm(),{assertDefaultLevelFound:e$,mappings:zm,genLsCache:t$,genLevelComparison:n$,assertLevelComparison:s$}=yl(),{DEFAULT_LEVELS:Ym,SORTING_ORDER:r$}=Lr(),{createArgsNormalizer:i$,asChindings:o$,buildSafeSonicBoom:Nm,buildFormatters:a$,stringify:El,normalizeDestFileDescriptor:jm,noop:l$}=Dr(),{version:c$}=bl(),{chindingsSym:Hm,redactFmtSym:u$,serializersSym:Bm,timeSym:d$,timeSliceIndexSym:f$,streamSym:p$,stringifySym:Um,stringifySafeSym:Tl,stringifiersSym:qm,setLevelSym:h$,endSym:m$,formatOptsSym:g$,messageKeySym:y$,errorKeySym:b$,nestedKeySym:v$,mixinSym:w$,levelCompSym:x$,useOnlyCustomLevelsSym:S$,formattersSym:Km,hooksSym:_$,nestedKeyStrSym:k$,mixinMergeStrategySym:A$,msgPrefixSym:$$}=Vm,{epochTime:Jm,nullTime:C$}=Gm,{pid:E$}=process,T$=YA.hostname(),R$=Wm.err,O$={level:"info",levelComparison:r$.ASC,levels:Ym,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:E$,hostname:T$},serializers:Object.assign(Object.create(null),{err:R$}),formatters:Object.assign(Object.create(null),{bindings(n){return n},level(n,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Jm,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},P$=i$(O$),M$=Object.assign(Object.create(null),Wm);function Rl(...n){let e={},{opts:t,stream:s}=P$(e,JA(),...n);t.level&&typeof t.level=="string"&&Ym[t.level.toLowerCase()]!==void 0&&(t.level=t.level.toLowerCase());let{redact:r,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:u,nestedKey:d,base:f,name:h,level:m,customLevels:p,levelComparison:g,mixin:x,mixinMergeStrategy:w,useOnlyCustomLevels:$,formatters:A,hooks:y,depthLimit:v,edgeLimit:b,onChild:S,msgPrefix:_}=t,T=ZA({maximumDepth:v,maximumBreadth:b}),I=a$(A.level,A.bindings,A.log),C=El.bind({[Tl]:T}),F=r?XA(r,C):{},H=r?{stringify:F[u$]}:{stringify:C},G="}"+(i?`\r
965
+ ${$}`),g.pop(),`{${b}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function f(m,p,g){switch(typeof p){case"string":return qt(p);case"object":{if(p===null)return"null";if(typeof p.toJSON=="function"){if(p=p.toJSON(m),typeof p!="object")return f(m,p,g);if(p===null)return"null"}if(g.indexOf(p)!==-1)return t;let x="",w=p.length!==void 0;if(w&&Array.isArray(p)){if(p.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(p);let b=Math.min(p.length,a),S=0;for(;S<b-1;S++){let T=f(String(S),p[S],g);x+=T!==void 0?T:"null",x+=","}let _=f(String(S),p[S],g);if(x+=_!==void 0?_:"null",p.length-1>a){let T=p.length-a-1;x+=`,"... ${cn(T)} not stringified"`}return g.pop(),`[${x}]`}let $=Object.keys(p),A=$.length;if(A===0)return"{}";if(o<g.length+1)return'"[Object]"';let y="",v=Math.min(A,a);w&&Cl(p)&&(x+=Dm(p,",",a),$=$.slice(p.length),v-=p.length,y=","),r&&($=$l($,i)),g.push(p);for(let b=0;b<v;b++){let S=$[b],_=f(S,p[S],g);_!==void 0&&(x+=`${y}${qt(S)}:${_}`,y=",")}if(A>a){let b=A-a;x+=`${y}"...":"${cn(b)} not stringified"`}return g.pop(),`{${x}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function h(m,p,g){if(arguments.length>1){let x="";if(typeof g=="number"?x=" ".repeat(Math.min(g,10)):typeof g=="string"&&(x=g.slice(0,10)),p!=null){if(typeof p=="function")return l("",{"":m},[],p,x,"");if(Array.isArray(p))return u("",m,[],VA(p),x,"")}if(x.length!==0)return d("",m,[],x,"")}return f("",m,[])}return h}});var Um=F((hR,Bm)=>{"use strict";var Rl=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Hm}=Fr(),YA=Hm.info;function JA(n,e){n=n||[],e=e||{dedupe:!1};let t=Object.create(Hm);t.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(f=>{t[f]=e.levels[f]});let s={write:r,add:a,remove:l,emit:i,flushSync:o,end:u,minLevel:0,lastId:0,streams:[],clone:d,[Rl]:!0,streamLevels:t};return Array.isArray(n)?n.forEach(a,s):a.call(s,n),n=null,s;function r(f){let h,m=this.lastLevel,{streams:p}=this,g=0,x;for(let w=XA(p.length,e.dedupe);ZA(w,p.length,e.dedupe);w=QA(w,e.dedupe))if(h=p[w],h.level<=m){if(g!==0&&g!==h.level)break;if(x=h.stream,x[Rl]){let{lastTime:$,lastMsg:A,lastObj:y,lastLogger:v}=this;x.lastLevel=m,x.lastTime=$,x.lastMsg=A,x.lastObj=y,x.lastLogger=v}x.write(f),e.dedupe&&(g=h.level)}else if(!e.dedupe)break}function i(...f){for(let{stream:h}of this.streams)typeof h.emit=="function"&&h.emit(...f)}function o(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync()}function a(f){if(!f)return s;let h=typeof f.write=="function"||f.stream,m=f.write?f:f.stream;if(!h)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:p,streamLevels:g}=this,x;typeof f.levelVal=="number"?x=f.levelVal:typeof f.level=="string"?x=g[f.level]:typeof f.level=="number"?x=f.level:x=YA;let w={stream:m,level:x,levelVal:void 0,id:++s.lastId};return p.unshift(w),p.sort(jm),this.minLevel=p[0].level,s}function l(f){let{streams:h}=this,m=h.findIndex(p=>p.id===f);return m>=0&&(h.splice(m,1),h.sort(jm),this.minLevel=h.length>0?h[0].level:-1),s}function u(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync(),f.end()}function d(f){let h=new Array(this.streams.length);for(let m=0;m<h.length;m++)h[m]={level:f,stream:this.streams[m].stream};return{write:r,add:a,remove:l,minLevel:f,streams:h,clone:d,emit:i,flushSync:o,[Rl]:!0}}}function jm(n,e){return n.level-e.level}function XA(n,e){return e?n-1:0}function QA(n,e){return e?n-1:n+1}function ZA(n,e,t){return t?n>=0:n<e}Bm.exports=JA});var Il=F((mR,et)=>{"use strict";var e$=require("node:os"),Jm=Ja(),t$=Xa(),n$=el(),Xm=$h(),s$=Im(),Qm=Mn(),{configure:r$}=Fm(),{assertDefaultLevelFound:i$,mappings:Zm,genLsCache:o$,genLevelComparison:a$,assertLevelComparison:l$}=wl(),{DEFAULT_LEVELS:eg,SORTING_ORDER:c$}=Fr(),{createArgsNormalizer:u$,asChindings:d$,buildSafeSonicBoom:qm,buildFormatters:f$,stringify:Ol,normalizeDestFileDescriptor:Km,noop:p$}=Nr(),{version:h$}=xl(),{chindingsSym:Wm,redactFmtSym:m$,serializersSym:Gm,timeSym:g$,timeSliceIndexSym:y$,streamSym:b$,stringifySym:Vm,stringifySafeSym:Pl,stringifiersSym:zm,setLevelSym:v$,endSym:w$,formatOptsSym:x$,messageKeySym:S$,errorKeySym:_$,nestedKeySym:k$,mixinSym:A$,levelCompSym:$$,useOnlyCustomLevelsSym:C$,formattersSym:Ym,hooksSym:E$,nestedKeyStrSym:T$,mixinMergeStrategySym:R$,msgPrefixSym:O$}=Qm,{epochTime:tg,nullTime:P$}=Xm,{pid:M$}=process,I$=e$.hostname(),D$=Jm.err,L$={level:"info",levelComparison:c$.ASC,levels:eg,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:M$,hostname:I$},serializers:Object.assign(Object.create(null),{err:D$}),formatters:Object.assign(Object.create(null),{bindings(n){return n},level(n,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:tg,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},N$=u$(L$),F$=Object.assign(Object.create(null),Jm);function Ml(...n){let e={},{opts:t,stream:s}=N$(e,t$(),...n);t.level&&typeof t.level=="string"&&eg[t.level.toLowerCase()]!==void 0&&(t.level=t.level.toLowerCase());let{redact:r,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:u,nestedKey:d,base:f,name:h,level:m,customLevels:p,levelComparison:g,mixin:x,mixinMergeStrategy:w,useOnlyCustomLevels:$,formatters:A,hooks:y,depthLimit:v,edgeLimit:b,onChild:S,msgPrefix:_}=t,T=r$({maximumDepth:v,maximumBreadth:b}),I=f$(A.level,A.bindings,A.log),C=Ol.bind({[Pl]:T}),N=r?n$(r,C):{},H=r?{stringify:N[m$]}:{stringify:C},G="}"+(i?`\r
902
966
  `:`
903
- `),E=o$.bind(null,{[Hm]:"",[Bm]:o,[qm]:F,[Um]:El,[Tl]:T,[Km]:I}),k="";f!==null&&(h===void 0?k=E(f):k=E(Object.assign({},f,{name:h})));let Y=a instanceof Function?a:a?Jm:C$,q=Y().indexOf(":")+1;if($&&!p)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(x&&typeof x!="function")throw Error(`Unknown mixin type "${typeof x}" - expected "function"`);if(_&&typeof _!="string")throw Error(`Unknown msgPrefix type "${typeof _}" - expected "string"`);e$(m,p,$);let Z=zm(p,$);typeof s.emit=="function"&&s.emit("message",{code:"PINO_CONFIG",config:{levels:Z,messageKey:l,errorKey:u}}),s$(g);let ee=n$(g);return Object.assign(e,{levels:Z,[x$]:ee,[S$]:$,[p$]:s,[d$]:Y,[f$]:q,[Um]:El,[Tl]:T,[qm]:F,[m$]:G,[g$]:H,[y$]:l,[b$]:u,[v$]:d,[k$]:d?`,${JSON.stringify(d)}:{`:"",[Bm]:o,[w$]:x,[A$]:w,[Hm]:k,[Km]:I,[_$]:y,silent:l$,onChild:S,[$$]:_}),Object.setPrototypeOf(e,QA()),t$(e),e[h$](m),e}Ze.exports=Rl;Ze.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=jm(n.dest||process.stdout.fd),Nm(n)):Nm({dest:jm(n),minLength:0});Ze.exports.transport=dl();Ze.exports.multistream=Fm();Ze.exports.levels=zm();Ze.exports.stdSerializers=M$;Ze.exports.stdTimeFunctions=Object.assign({},Gm);Ze.exports.symbols=Vm;Ze.exports.version=c$;Ze.exports.default=Rl;Ze.exports.pino=Rl});function ms(n){return new Pl(n)}var I$,D$,L$,Pl,Ml=L(()=>{"use strict";I$={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},D$=`
967
+ `),E=d$.bind(null,{[Wm]:"",[Gm]:o,[zm]:N,[Vm]:Ol,[Pl]:T,[Ym]:I}),k="";f!==null&&(h===void 0?k=E(f):k=E(Object.assign({},f,{name:h})));let Y=a instanceof Function?a:a?tg:P$,U=Y().indexOf(":")+1;if($&&!p)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(x&&typeof x!="function")throw Error(`Unknown mixin type "${typeof x}" - expected "function"`);if(_&&typeof _!="string")throw Error(`Unknown msgPrefix type "${typeof _}" - expected "string"`);i$(m,p,$);let ee=Zm(p,$);typeof s.emit=="function"&&s.emit("message",{code:"PINO_CONFIG",config:{levels:ee,messageKey:l,errorKey:u}}),l$(g);let ne=a$(g);return Object.assign(e,{levels:ee,[$$]:ne,[C$]:$,[b$]:s,[g$]:Y,[y$]:U,[Vm]:Ol,[Pl]:T,[zm]:N,[w$]:G,[x$]:H,[S$]:l,[_$]:u,[k$]:d,[T$]:d?`,${JSON.stringify(d)}:{`:"",[Gm]:o,[A$]:x,[R$]:w,[Wm]:k,[Ym]:I,[E$]:y,silent:p$,onChild:S,[O$]:_}),Object.setPrototypeOf(e,s$()),o$(e),e[v$](m),e}et.exports=Ml;et.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=Km(n.dest||process.stdout.fd),qm(n)):qm({dest:Km(n),minLength:0});et.exports.transport=hl();et.exports.multistream=Um();et.exports.levels=Zm();et.exports.stdSerializers=F$;et.exports.stdTimeFunctions=Object.assign({},Xm);et.exports.symbols=Qm;et.exports.version=h$;et.exports.default=Ml;et.exports.pino=Ml});function gs(n){return new Dl(n)}var j$,H$,B$,Dl,Ll=L(()=>{"use strict";j$={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},H$=`
904
968
  ## Reasoning Protocol
905
969
 
906
970
  Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
@@ -929,15 +993,15 @@ After receiving a tool result, think again:
929
993
  - One tool call per turn. Wait for the result before the next call.
930
994
  - If a tool fails, analyze the error in <thinking> before retrying.
931
995
  - When done, give a concise final answer WITHOUT <thinking> tags.
932
- `.trim(),L$=`
996
+ `.trim(),B$=`
933
997
  ## Reasoning
934
998
  For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
935
999
  The user will NOT see thinking blocks. One tool call per turn.
936
- `.trim(),Pl=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...I$,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,t="M"){return!this.config.thinkingEnabled||t==="XS"?e:t==="S"?`${e}
1000
+ `.trim(),Dl=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...j$,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,t="M"){return!this.config.thinkingEnabled||t==="XS"?e:t==="S"?`${e}
937
1001
 
938
- ${L$}`:`${e}
1002
+ ${B$}`:`${e}
939
1003
 
940
- ${D$}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let t=[],s=e,r=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=r.exec(e))!==null;)t.push(i[1].trim());s=s.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)t.push(i[1].trim());s=s.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(s);a&&(t.push(a[1].trim()),s=s.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(s);return l&&(t.push(l[1].trim()),s=s.replace(/<think>[\s\S]*$/i,"")),{thinking:t.join(`
1004
+ ${H$}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let t=[],s=e,r=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=r.exec(e))!==null;)t.push(i[1].trim());s=s.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)t.push(i[1].trim());s=s.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(s);a&&(t.push(a[1].trim()),s=s.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(s);return l&&(t.push(l[1].trim()),s=s.replace(/<think>[\s\S]*$/i,"")),{thinking:t.join(`
941
1005
 
942
1006
  `).trim(),visibleContent:s.trim(),hasThinking:t.length>0}}startTurn(){this.turnSteps=[],this.stepCounter=0}recordStep(e){let t={...e,stepIndex:this.stepCounter++,timestamp:new Date().toISOString()};return this.turnSteps.push(t),t}recordObservation(e,t){let s=this.turnSteps[this.turnSteps.length-1];s&&(s.observation=e,t&&(s.reflection=t))}getSteps(){return this.turnSteps}isOverBudget(){return this.stepCounter>=this.config.maxSteps}remainingBudget(){return Math.max(0,this.config.maxSteps-this.stepCounter)}buildSelfEvalPrompt(e,t,s){return`
943
1007
  <self_eval>
@@ -960,24 +1024,24 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
960
1024
  }
961
1025
  </self_eval>
962
1026
  `.trim()}parseSelfEval(e){let t=[/^\s*(\{[\s\S]*\})\s*$/,/```(?:json)?\s*\n([\s\S]*?)\n```/,/<self_eval_result>([\s\S]*?)<\/self_eval_result>/,/(\{[\s\S]*?"score"[\s\S]*?"completed"[\s\S]*?\})/];for(let s of t){let r=e.match(s);if(r)try{let i=JSON.parse(r[1]);return this.normalizeSelfEval(i)}catch{}}return null}normalizeSelfEval(e){let t=typeof e.score=="number"?Math.max(0,Math.min(10,Math.round(e.score))):5,s=typeof e.completed=="boolean"?e.completed:t>=7,r=typeof e.rationale=="string"?e.rationale.slice(0,500):"No rationale provided",i=Array.isArray(e.issues)?e.issues.filter(a=>typeof a=="string").slice(0,5):[],o="medium";return e.confidence==="high"||e.confidence==="medium"||e.confidence==="low"?o=e.confidence:t>=8?o="high":t<=4&&(o="low"),{score:t,completed:s,rationale:r,issues:i,confidence:o}}buildBudgetWarningPrompt(){let e=this.remainingBudget();return e<=0?"[SYSTEM] You have exceeded the maximum reasoning steps. You MUST provide your final answer NOW. Do not call any more tools.":e<=3?`[SYSTEM] You have only ${e} step(s) remaining. Wrap up your work and provide a final answer soon.`:null}buildReflectionHint(e,t,s){return t?"":["<thinking>",`Tool "${e}" FAILED. Before retrying:`,"1. What went wrong? Analyze the error message carefully.","2. Can I fix the arguments and retry?","3. Is there an alternative approach?",`Error preview: ${s.slice(0,300)}`,"</thinking>"].join(`
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 F$,Il,Dl=L(()=>{"use strict";F$=[{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 F$)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
- `)}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 N$(){try{if(Lt.existsSync(jr))return JSON.parse(Lt.readFileSync(jr,"utf-8"))}catch{}return{}}function j$(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 Qm(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 H$(n){return n.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function B$(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 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());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=Zm(r);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function Zm(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]=H$(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 K$(n){return Zm(n)}function W$(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 G$(n){let e=[],t=/\{\s*"function"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Qm(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 V$(n){let e=[],t=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Qm(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 z$(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 eg(){return Fl||(Fl=new Nl),Fl}var Lt,Hr,Xm,jr,Ll,Nl,Fl,tg=L(()=>{"use strict";Lt=O(require("fs")),Hr=O(require("path")),Xm=O(require("os")),jr=Hr.join(Xm.homedir(),".hablas","model-formats.json");Ll=[{format:"xml_tool_call_wrapper",parse:q$},{format:"xml_prompt",parse:K$},{format:"xml_tags",parse:B$},{format:"xml_parameters",parse:z$},{format:"hermes",parse:U$},{format:"markdown_json",parse:W$},{format:"function_call",parse:G$},{format:"json_object",parse:V$}],Nl=class{registry;constructor(){this.registry=N$()}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()},j$(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,`
1027
+ `)}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 ys(n=3){return new Nl(n)}var U$,Nl,Fl=L(()=>{"use strict";U$=[{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}],Nl=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 U$)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(`
1028
+ `)}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 q$(){try{if(Lt.existsSync(Br))return JSON.parse(Lt.readFileSync(Br,"utf-8"))}catch{}return{}}function K$(n){try{let e=Ur.dirname(Br);Lt.existsSync(e)||Lt.mkdirSync(e,{recursive:!0}),Lt.writeFileSync(Br,JSON.stringify(n,null,2),"utf-8")}catch{}}function sg(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 bs(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 W$(n){return n.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function G$(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=bs(r);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function V$(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=bs(r);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function z$(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=rg(r);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function rg(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]=W$(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 Y$(n){return rg(n)}function J$(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=bs(r);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function X$(n){let e=[],t=/\{\s*"function"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=sg(n,s.index);if(r)try{let i=JSON.parse(r),o=bs(i);o&&e.push({...o,format:"function_call",rawMatch:r})}catch{}}return e}function Q$(n){let e=[],t=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=sg(n,s.index);if(r)try{let i=JSON.parse(r),o=bs(i);o&&e.push({...o,format:"json_object",rawMatch:r})}catch{}}return e}function Z$(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 ig(){return Hl||(Hl=new Bl),Hl}var Lt,Ur,ng,Br,jl,Bl,Hl,og=L(()=>{"use strict";Lt=O(require("fs")),Ur=O(require("path")),ng=O(require("os")),Br=Ur.join(ng.homedir(),".hablas","model-formats.json");jl=[{format:"xml_tool_call_wrapper",parse:z$},{format:"xml_prompt",parse:Y$},{format:"xml_tags",parse:G$},{format:"xml_parameters",parse:Z$},{format:"hermes",parse:V$},{format:"markdown_json",parse:J$},{format:"function_call",parse:X$},{format:"json_object",parse:Q$}],Bl=class{registry;constructor(){this.registry=q$()}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=jl.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 jl){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 jl)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()},K$(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
1029
 
966
- `),{toolCalls:s,displayContent:r.trim(),format:e[0]?.format??"unknown"}}},Fl=null});function J$(n,e,t){let r=eg().parse(e,n,t);return{toolCalls:r.toolCalls,displayContent:r.displayContent}}function X$(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 Q$(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 rg(n,e,t,s){let r=0,i=Date.now();for(;r<=sg;){let o=await n.execute({name:e,arguments:t});if(o.success||r>=sg)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??Y$,x=[],w=[],$=[],A="",y=0,v=!1;for(;y<g;){if(y++,u?.aborted)return{output:A,toolsUsed:Kt(x),toolResults:w,touchedFiles:Kt($),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:Kt(x),toolResults:w,touchedFiles:Kt($),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:Kt(x),toolResults:w,touchedFiles:Kt($),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}=J$(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||{},q=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,q,Y)==="skip"){r.addToolMessage(`Tool ${k} was skipped by policy/user.`);break}x.push(k),typeof Y.path=="string"&&$.push(Y.path);let ee=X$(k,Y);a.onToolStart?.(k,ee,Y),a.onToolCall?.(),f.recordStep({thought:I.hasThinking?`Executing: ${k}`:"",action:k,actionInput:Y});let X=await rg(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,ng),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",_e=h.analyze(k,Oe,Y);if(ue=h.buildRecoveryMessage(_e,Oe),f.recordObservation(`FAILED: ${Oe}`,`Recovery: ${_e.strategy} \u2014 ${_e.suggestion}`),o.info({tool:k,errorClass:_e.errorClass,strategy:_e.strategy},"Error recovery analysis"),w.push({tool:k,success:!1,summary:Oe.slice(0,150)}),_e.autoRetry&&!f.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let ne=await rg(s,k,Y,o);a.onToolEnd?.(k,ne.success,ne.output,ne.duration,Y),ne.success&&(ue=os(ne.output,ng),f.recordObservation(ue.slice(0,300),"Auto-retry succeeded"),w[w.length-1]={tool:k,success:!0,summary:ne.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&&Q$(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:Kt(x),toolResults:w,touchedFiles:Kt($),iterations:y,success:!0,completedNaturally:v}}function Kt(n){return[...new Set(n)]}function ig(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 og(){return(n,e)=>e==="dangerous"?"skip":"allow"}var Y$,ng,sg,jl=L(()=>{"use strict";da();Ml();Dl();tg();Y$=600,ng=2e3,sg=2});var lg,Z$,e0,t0,ag,bs,cg=L(()=>{"use strict";lg=O(Ol());jn();pa();fa();Ns();Ri();Fa();jl();Z$={hablas:"planner",bob:"architect",alex:"coder",david:"researcher",emma:"product-manager",gate:"gate"},e0=(0,lg.default)({level:"silent"}),t0=200,ag={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??ag[e]?.temperature??.5};let s=ag[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)||{name:String(e),title:"Specialist",role:e,description:"",expertise:[]};let l=this.getAgentModel(e),u=i?.maxIterations||t0,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:e0,io:g,safetyPolicy:og(),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(`
1030
+ `),{toolCalls:s,displayContent:r.trim(),format:e[0]?.format??"unknown"}}},Hl=null});function t0(n,e,t){let r=ig().parse(e,n,t);return{toolCalls:r.toolCalls,displayContent:r.displayContent}}function n0(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 s0(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 cg(n,e,t,s){let r=0,i=Date.now();for(;r<=lg;){let o=await n.execute({name:e,arguments:t});if(o.success||r>=lg)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 qr(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??gs(),h=n.errorRecovery??ys(),m=d?[]:s.getOllamaTools(),p=t.getModel(),g=n.maxIterations??e0,x=[],w=[],$=[],A="",y=0,v=!1;for(;y<g;){if(y++,u?.aborted)return{output:A,toolsUsed:Kt(x),toolResults:w,touchedFiles:Kt($),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:Kt(x),toolResults:w,touchedFiles:Kt($),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:Kt(x),toolResults:w,touchedFiles:Kt($),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:N}=t0(T,_,p);if(N&&N.trim()&&(A=N,await a.onAssistantText?.(N,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||{},U=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(Pe=>Pe.name).join(", ")}`);continue}if(await l(k,U,Y)==="skip"){r.addToolMessage(`Tool ${k} was skipped by policy/user.`);break}x.push(k),typeof Y.path=="string"&&$.push(Y.path);let ne=n0(k,Y);a.onToolStart?.(k,ne,Y),a.onToolCall?.(),f.recordStep({thought:I.hasThinking?`Executing: ${k}`:"",action:k,actionInput:Y});let X=await cg(s,k,Y,o);a.onToolEnd?.(k,X.success,X.error||X.output,X.duration,Y);let ue;if(X.success)ue=as(X.output,ag),f.recordObservation(ue.slice(0,300)),w.push({tool:k,success:!0,summary:X.output.slice(0,150)});else{let Pe=X.error||"Unknown error",xe=h.analyze(k,Pe,Y);if(ue=h.buildRecoveryMessage(xe,Pe),f.recordObservation(`FAILED: ${Pe}`,`Recovery: ${xe.strategy} \u2014 ${xe.suggestion}`),o.info({tool:k,errorClass:xe.errorClass,strategy:xe.strategy},"Error recovery analysis"),w.push({tool:k,success:!1,summary:Pe.slice(0,150)}),xe.autoRetry&&!f.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let we=await cg(s,k,Y,o);a.onToolEnd?.(k,we.success,we.output,we.duration,Y),we.success&&(ue=as(we.output,ag),f.recordObservation(ue.slice(0,300),"Auto-retry succeeded"),w[w.length-1]={tool:k,success:!0,summary:we.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&&s0(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:Kt(x),toolResults:w,touchedFiles:Kt($),iterations:y,success:!0,completedNaturally:v}}function Kt(n){return[...new Set(n)]}function ug(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 dg(){return(n,e)=>e==="dangerous"?"skip":"allow"}var e0,ag,lg,Ul=L(()=>{"use strict";ha();Ll();Fl();og();e0=600,ag=2e3,lg=2});var pg,r0,i0,o0,fg,vs,hg=L(()=>{"use strict";pg=O(Il());Hn();ga();ma();Hs();Mi();Ha();Ul();r0={hablas:"planner",bob:"architect",alex:"coder",david:"researcher",emma:"product-manager",gate:"gate"},i0=(0,pg.default)({level:"silent"}),o0=200,fg={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}},vs=class{baseConfig;agentModels;toolRegistry=null;onOutput=null;channel=null;mindsetRegistry=wr();sharedContext=null;contextManager;constructor(e){this.baseConfig=e,this.agentModels=Yt(),this.contextManager=new nn(e)}setSharedContext(e){this.sharedContext=e}setChannel(e){this.channel=e}setToolRegistry(e){this.toolRegistry=e}setOutputCallback(e){this.onOutput=e}reloadModels(){this.agentModels=Yt()}getAgentModel(e){let t=this.agentModels[e];if(t)return{model:t.model,temperature:t.temperature??fg[e]?.temperature??.5};let s=fg[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=Se.find($=>$.role===e)||{name:String(e),title:"Specialist",role:e,description:"",expertise:[]};let l=this.getAgentModel(e),u=i?.maxIterations||o0,d={...this.baseConfig,model:l.model},f=Me(d),h=this.buildAgentPrompt(a,s),m=new sn(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 qr({identity:p,client:f,registry:this.toolRegistry,session:m,contextManager:this.contextManager,logger:i0,io:g,safetyPolicy:dg(),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
1031
  ## Handoff Chain`);for(let p of o)d.push(`- @${p.from} \u2192 @${p.to}: ${p.context.slice(0,100)}`)}let f=d.join(`
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+=`
1032
+ `),h=Se.find(p=>p.role===l);if(h&&a>0){let p=e[a-1].role,g=Se.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
1033
 
970
- ### @${m.agentName} (${we.find(g=>g.role===l)?.title||l})
971
- ${p}`,a<e.length-1&&o.push({from:l,to:e[a+1].role,context:m.output.slice(0,200),artifacts:m.touchedFiles})}}return r}async runParallel(e,t,s){let r=s?.maxConcurrent||3,i=[];for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r),l=await Promise.all(a.map(({role:u,task:d})=>this.runAgent(u,d,void 0,t,s)));i.push(...l)}return i}async runWithEscalation(e,t,s,r){let i=await this.runAgent(e,t,s,r);if(i.success)return i;this.emit(we.find(a=>a.role===e)?.name||e,"error",`First attempt failed: ${i.error}. Retrying...`);let o=(s||"")+`
1034
+ ### @${m.agentName} (${Se.find(g=>g.role===l)?.title||l})
1035
+ ${p}`,a<e.length-1&&o.push({from:l,to:e[a+1].role,context:m.output.slice(0,200),artifacts:m.touchedFiles})}}return r}async runParallel(e,t,s){let r=s?.maxConcurrent||3,i=[];for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r),l=await Promise.all(a.map(({role:u,task:d})=>this.runAgent(u,d,void 0,t,s)));i.push(...l)}return i}async runWithEscalation(e,t,s,r){let i=await this.runAgent(e,t,s,r);if(i.success)return i;this.emit(Se.find(a=>a.role===e)?.name||e,"error",`First attempt failed: ${i.error}. Retrying...`);let o=(s||"")+`
972
1036
 
973
1037
  ## Previous Attempt Failed
974
1038
  Error: ${i.error}
975
- Please try a different approach.`;if(i=await this.runAgent(e,t,o,r),i.success)return i;if(e!=="hablas"){this.emit("Hablas","thinking",`@${we.find(l=>l.role===e)?.name} failed. Hablas taking over...`);let a=`Agent @${e} failed twice on this task.
1039
+ Please try a different approach.`;if(i=await this.runAgent(e,t,o,r),i.success)return i;if(e!=="hablas"){this.emit("Hablas","thinking",`@${Se.find(l=>l.role===e)?.name} failed. Hablas taking over...`);let a=`Agent @${e} failed twice on this task.
976
1040
  Original error: ${i.error}
977
1041
  Please complete this task.`;return this.runAgent("hablas",t,a,r)}return i}buildAgentPrompt(e,t){if(e.role==="gate"){let a=this.mindsetRegistry.get("gate");return a?a.systemPrompt+(t?`
978
1042
 
979
1043
  ## Additional Context
980
- ${t}`:""):"You are the hidden professional decision layer. Analyze the input and decide routing."}let s=Z$[e.role]??"coder",r=this.mindsetRegistry.get(s),o=(r?`${r.systemPrompt}
1044
+ ${t}`:""):"You are the hidden professional decision layer. Analyze the input and decide routing."}let s=r0[e.role]??"coder",r=this.mindsetRegistry.get(s),o=(r?`${r.systemPrompt}
981
1045
 
982
1046
  ---
983
1047
 
@@ -1040,15 +1104,15 @@ Never output raw tool XML in text.
1040
1104
  ${t}`),this.sharedContext){let a=this.sharedContext.getSummary();a&&(o+=`
1041
1105
 
1042
1106
  ## 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 ug,vs,dg=L(()=>{"use strict";ug=require("events"),vs=class extends ug.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 n0,St,Ur,ws,fg=L(()=>{"use strict";jn();n0={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
- ${n0[e]}
1107
+ ${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 mg,ws,gg=L(()=>{"use strict";mg=require("events"),ws=class extends mg.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 a0,xt,Kr,xs,yg=L(()=>{"use strict";Hn();a0={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."},xt={hablas:"Hablas",emma:"Emma",bob:"Bob",alex:"Alex",david:"David"},Kr={handoff:(n,e,t)=>{let s=xt[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, @${xt[e]}. Proceeding.`,review:(n,e)=>`@${xt[e]}, structurally sound. Watch the boundaries on the next pass.`,reviewAck:(n,e)=>`Noted, @${xt[e]}. Integrating.`},xs=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),()=>Kr.handoff(e,t,s))}async generateAckLine(e,t){return this.generate(`ack:${e}:${t}`,this.buildPrompt(e,t,"ack"),()=>Kr.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)),()=>Kr.review(e,t))}async generateReviewAck(e,t){return this.generate(`reviewAck:${e}:${t}`,this.buildPrompt(e,t,"reviewAck"),()=>Kr.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 ${xt[e]}, speaking in your own voice.
1108
+ ${a0[e]}
1045
1109
 
1046
1110
  Hard constraints:
1047
1111
  - Output exactly ONE sentence.
1048
1112
  - No prefix, no quotes, no markdown, no emojis, no role labels.
1049
1113
  - Maximum ${this.opts.maxChars} characters.
1050
- - Address @${St[t]} directly.
1051
- - Stay in character. Be useful, not chatty.`,o;switch(s){case"handoff":o=`You are about to hand the following task to @${St[t]}. Write a single in-character line that briefly frames what you need from them. Task: "${(r||"").slice(0,300)}"`;break;case"ack":o=`@${St[t]} just handed you a task. Write a single in-character line acknowledging it and stating your immediate next move.`;break;case"review":o=`You just reviewed @${St[t]}'s output below. Write a single in-character line of feedback \u2014 substantive but extremely brief. Output excerpt: """${(r||"").slice(0,400)}"""`;break;case"reviewAck":o=`@${St[t]} just reviewed your work and gave you feedback. Write a single in-character line acknowledging it and noting the integration.`;break}return[{role:"system",content:i},{role:"user",content:o}]}cleanLine(e){let t=e.trim();return t=t.replace(/^```[a-z]*\n?|```$/gi,"").trim(),t=t.split(/\r?\n/)[0].trim(),t=t.replace(/^@?[A-Z][a-zA-Z]+\s*:\s*/,"").trim(),t=t.replace(/^["'`«»“”]+|["'`«»“”]+$/g,"").trim(),t.length>this.opts.maxChars&&(t=t.slice(0,this.opts.maxChars-1).trim()+"\u2026"),t}hash(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e.charCodeAt(s),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t.toString(36)}}});var re,ct,s0,hg,r0,mg,pg,Dn,Hl=L(()=>{"use strict";re=O(require("fs")),ct=O(require("path")),s0=".hablas",hg=`# Project Context
1114
+ - Address @${xt[t]} directly.
1115
+ - Stay in character. Be useful, not chatty.`,o;switch(s){case"handoff":o=`You are about to hand the following task to @${xt[t]}. Write a single in-character line that briefly frames what you need from them. Task: "${(r||"").slice(0,300)}"`;break;case"ack":o=`@${xt[t]} just handed you a task. Write a single in-character line acknowledging it and stating your immediate next move.`;break;case"review":o=`You just reviewed @${xt[t]}'s output below. Write a single in-character line of feedback \u2014 substantive but extremely brief. Output excerpt: """${(r||"").slice(0,400)}"""`;break;case"reviewAck":o=`@${xt[t]} just reviewed your work and gave you feedback. Write a single in-character line acknowledging it and noting the integration.`;break}return[{role:"system",content:i},{role:"user",content:o}]}cleanLine(e){let t=e.trim();return t=t.replace(/^```[a-z]*\n?|```$/gi,"").trim(),t=t.split(/\r?\n/)[0].trim(),t=t.replace(/^@?[A-Z][a-zA-Z]+\s*:\s*/,"").trim(),t=t.replace(/^["'`«»“”]+|["'`«»“”]+$/g,"").trim(),t.length>this.opts.maxChars&&(t=t.slice(0,this.opts.maxChars-1).trim()+"\u2026"),t}hash(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e.charCodeAt(s),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t.toString(36)}}});var oe,ut,l0,vg,c0,wg,bg,Ln,ql=L(()=>{"use strict";oe=O(require("fs")),ut=O(require("path")),l0=".hablas",vg=`# Project Context
1052
1116
 
1053
1117
  ## Overview
1054
1118
  <!-- Auto-generated by hablas. Describe your project here. -->
@@ -1061,33 +1125,33 @@ Hard constraints:
1061
1125
 
1062
1126
  ## Notes
1063
1127
  <!-- Miscellaneous context for agents -->
1064
- `,r0=`# Decisions Log
1128
+ `,c0=`# Decisions Log
1065
1129
 
1066
1130
  | Date | Decision | By | Rationale |
1067
1131
  |------|----------|-----|-----------|
1068
- `,mg=`# Task Assignments
1132
+ `,wg=`# Task Assignments
1069
1133
 
1070
1134
  ## Active Tasks
1071
1135
  <!-- Format: - [ ] Task description (@agent) -->
1072
1136
 
1073
1137
  ## Completed
1074
1138
  <!-- Format: - [x] Task description (@agent) \u2014 result -->
1075
- `,pg={"CONTEXT.md":hg,"DECISIONS.md":r0,"TASKS.md":mg},Dn=class{contextDir;constructor(e){this.contextDir=ct.join(e,s0)}init(){let e=ct.join(ct.dirname(this.contextDir),".flowagent");if(re.existsSync(e)&&!re.existsSync(this.contextDir))try{re.renameSync(e,this.contextDir)}catch{}re.existsSync(this.contextDir)||re.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(pg)){let r=ct.join(this.contextDir,t);re.existsSync(r)||re.writeFileSync(r,s,"utf-8")}}exists(){return re.existsSync(this.contextDir)}read(e){let t=ct.join(this.contextDir,e);return re.existsSync(t)?re.readFileSync(t,"utf-8"):null}write(e,t){this.ensureDir();let s=ct.join(this.contextDir,e);re.writeFileSync(s,t,"utf-8")}append(e,t){this.ensureDir();let s=ct.join(this.contextDir,e),r=re.existsSync(s)?re.readFileSync(s,"utf-8"):"";re.writeFileSync(s,r+`
1076
- `+t,"utf-8")}logDecision(e,t,s){let i=`| ${new Date().toISOString().split("T")[0]} | ${e} | ${t} | ${s} |`;this.append("DECISIONS.md",i)}addTask(e,t){let s=`- [ ] ${e} (@${t})`,i=(this.read("TASKS.md")||mg).replace(`## Active Tasks
1139
+ `,bg={"CONTEXT.md":vg,"DECISIONS.md":c0,"TASKS.md":wg},Ln=class{contextDir;constructor(e){this.contextDir=ut.join(e,l0)}init(){let e=ut.join(ut.dirname(this.contextDir),".flowagent");if(oe.existsSync(e)&&!oe.existsSync(this.contextDir))try{oe.renameSync(e,this.contextDir)}catch{}oe.existsSync(this.contextDir)||oe.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(bg)){let r=ut.join(this.contextDir,t);oe.existsSync(r)||oe.writeFileSync(r,s,"utf-8")}}exists(){return oe.existsSync(this.contextDir)}read(e){let t=ut.join(this.contextDir,e);return oe.existsSync(t)?oe.readFileSync(t,"utf-8"):null}write(e,t){this.ensureDir();let s=ut.join(this.contextDir,e);oe.writeFileSync(s,t,"utf-8")}append(e,t){this.ensureDir();let s=ut.join(this.contextDir,e),r=oe.existsSync(s)?oe.readFileSync(s,"utf-8"):"";oe.writeFileSync(s,r+`
1140
+ `+t,"utf-8")}logDecision(e,t,s){let i=`| ${new Date().toISOString().split("T")[0]} | ${e} | ${t} | ${s} |`;this.append("DECISIONS.md",i)}addTask(e,t){let s=`- [ ] ${e} (@${t})`,i=(this.read("TASKS.md")||wg).replace(`## Active Tasks
1077
1141
  `,`## Active Tasks
1078
1142
  ${s}
1079
- `);this.write("TASKS.md",i)}completeTask(e,t){let s=this.read("TASKS.md");if(!s)return;let r=`- [ ] ${e}`,i=`- [x] ${e}${t?" \u2014 "+t:""}`,o=s.replace(r,i);this.write("TASKS.md",o)}getAll(){return re.existsSync(this.contextDir)?re.readdirSync(this.contextDir).filter(t=>t.endsWith(".md")).map(t=>{let s=ct.join(this.contextDir,t),r=re.statSync(s);return{file:t,content:re.readFileSync(s,"utf-8"),lastModified:r.mtime}}):[]}getSummary(){let e=this.getAll();return e.length===0?"":e.map(t=>`### ${t.file}
1143
+ `);this.write("TASKS.md",i)}completeTask(e,t){let s=this.read("TASKS.md");if(!s)return;let r=`- [ ] ${e}`,i=`- [x] ${e}${t?" \u2014 "+t:""}`,o=s.replace(r,i);this.write("TASKS.md",o)}getAll(){return oe.existsSync(this.contextDir)?oe.readdirSync(this.contextDir).filter(t=>t.endsWith(".md")).map(t=>{let s=ut.join(this.contextDir,t),r=oe.statSync(s);return{file:t,content:oe.readFileSync(s,"utf-8"),lastModified:r.mtime}}):[]}getSummary(){let e=this.getAll();return e.length===0?"":e.map(t=>`### ${t.file}
1080
1144
  ${t.content}`).join(`
1081
1145
 
1082
- `)}kvStore=new Map;set(e,t){this.kvStore.set(e,t),this.persistKV()}get(e){return this.kvStore.get(e)}delete(e){let t=this.kvStore.delete(e);return t&&this.persistKV(),t}clear(){this.kvStore.clear();for(let[e,t]of Object.entries(pg)){let s=ct.join(this.contextDir,e);re.existsSync(s)&&re.writeFileSync(s,t,"utf-8")}}getDecisions(){let e=this.read("DECISIONS.md");if(!e)return[];let t=e.split(`
1146
+ `)}kvStore=new Map;set(e,t){this.kvStore.set(e,t),this.persistKV()}get(e){return this.kvStore.get(e)}delete(e){let t=this.kvStore.delete(e);return t&&this.persistKV(),t}clear(){this.kvStore.clear();for(let[e,t]of Object.entries(bg)){let s=ut.join(this.contextDir,e);oe.existsSync(s)&&oe.writeFileSync(s,t,"utf-8")}}getDecisions(){let e=this.read("DECISIONS.md");if(!e)return[];let t=e.split(`
1083
1147
  `),s=[];for(let r of t){let i=r.match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|$/);i&&s.push({timestamp:i[1],decision:i[2].trim(),by:i[3].trim(),rationale:i[4].trim()})}return s}render(){let e=[];if(this.kvStore.size>0){e.push(" Key-Value Store:");for(let[r,i]of this.kvStore)e.push(` ${r}: ${i}`)}else e.push(" No key-value entries");let t=this.getAll();if(t.length>0){e.push(""),e.push(" Context Files:");for(let r of t){let i=r.content.split(`
1084
1148
  `).length;e.push(` ${r.file} (${i} lines)`)}}let s=this.getDecisions();return s.length>0&&(e.push(""),e.push(` Decisions: ${s.length} logged`)),e.join(`
1085
- `)}persistKV(){if(this.kvStore.size===0)return;let e=this.read("CONTEXT.md")||hg,t=Array.from(this.kvStore.entries()).map(([i,o])=>`- **${i}**: ${o}`).join(`
1149
+ `)}persistKV(){if(this.kvStore.size===0)return;let e=this.read("CONTEXT.md")||vg,t=Array.from(this.kvStore.entries()).map(([i,o])=>`- **${i}**: ${o}`).join(`
1086
1150
  `),s=/## Notes\n[\s\S]*$/,r=e.replace(s,`## Notes
1087
1151
  ${t}
1088
- `);this.write("CONTEXT.md",r)}ensureDir(){re.existsSync(this.contextDir)||re.mkdirSync(this.contextDir,{recursive:!0})}}});function Bl(n){return we.find(e=>e.role===n)?.name||n}var xs,gg=L(()=>{"use strict";Ns();Hl();xs=class{channel;runner;chat;constructor(e,t,s,r){this.channel=e,this.runner=t,this.chat=s,this.runner.setChannel(e),this.chat.resetBudget()}async run(e,t,s,r={}){this.chat.setAbortSignal(r.abortSignal);let i=r.peerReview!==!1,o=r.centralizedToLeader===!0,a=new Dn(process.cwd());this.runner.setSharedContext(a),this.channel.emitEvent({type:"phase",agent:"System",content:"Delegating to the team"});let l=t.tasks.filter(m=>m.role!=="hablas").map(m=>({role:m.role,task:`${m.description}
1152
+ `);this.write("CONTEXT.md",r)}ensureDir(){oe.existsSync(this.contextDir)||oe.mkdirSync(this.contextDir,{recursive:!0})}}});function Kl(n){return Se.find(e=>e.role===n)?.name||n}var Ss,xg=L(()=>{"use strict";Hs();ql();Ss=class{channel;runner;chat;constructor(e,t,s,r){this.channel=e,this.runner=t,this.chat=s,this.runner.setChannel(e),this.chat.resetBudget()}async run(e,t,s,r={}){this.chat.setAbortSignal(r.abortSignal);let i=r.peerReview!==!1,o=r.centralizedToLeader===!0,a=new Ln(process.cwd());this.runner.setSharedContext(a),this.channel.emitEvent({type:"phase",agent:"System",content:"Delegating to the team"});let l=t.tasks.filter(m=>m.role!=="hablas").map(m=>({role:m.role,task:`${m.description}
1089
1153
 
1090
- Original request: ${e}`})),u=[],d="hablas",f=null;for(let m of l){if(r.abortSignal?.aborted)break;let p=we.find(w=>w.role===m.role);if(!p)continue;if(!o){this.channel.emitEvent({type:"handoff",agent:Bl(d),to:p.name});let w=await this.chat.generateHandoffLine(d,m.role,m.task);this.channel.emitEvent({type:"speak",agent:Bl(d),to:p.name,content:w});let $=await this.chat.generateAckLine(m.role,d);this.channel.emitEvent({type:"speak",agent:p.name,to:Bl(d),content:$})}let g=Date.now(),x=await this.runner.runAgent(m.role,m.task,void 0,s,{abortSignal:r.abortSignal});u.push(x),x.success&&x.output?(this.channel.emitEvent({type:"summary",agent:p.name,durationMs:Date.now()-g}),m.role==="alex"&&(f=x.output),i&&m.role==="alex"&&t.tasks.some(w=>w.role==="bob")&&f&&await this.runPeerReview("bob","alex",f,r.abortSignal,o)):x.error&&this.channel.emitEvent({type:"error",agent:p.name,content:x.error}),d=m.role}this.channel.emitEvent({type:"phase",agent:"System",content:"Hablas compiling final report"});let h=await this.synthesize(e,u,s,r.abortSignal);return this.channel.emitEvent({type:"done",agent:"Hablas"}),h}async runPeerReview(e,t,s,r,i=!1){let o=we.find(l=>l.role===e),a=we.find(l=>l.role===t);if(!(!o||!a)){if(!i){let l=await this.chat.generateReviewLine(e,t,s);this.channel.emitEvent({type:"review",agent:o.name,to:a.name,content:l});let u=await this.chat.generateReviewAck(t,e);this.channel.emitEvent({type:"speak",agent:a.name,to:o.name,content:u})}r?.aborted}}async synthesize(e,t,s,r){let i=t.filter(d=>d.success&&d.output);if(i.length===0)return{results:t,finalSynthesis:"The team encountered errors and could not complete the task. Please review the logs and try again.",synthesisOk:!1};let o=i.map(d=>{let f=we.find(h=>h.role===d.agent);return`### Report from @${d.agentName} (${f?.title??d.agent}):
1154
+ Original request: ${e}`})),u=[],d="hablas",f=null;for(let m of l){if(r.abortSignal?.aborted)break;let p=Se.find(w=>w.role===m.role);if(!p)continue;if(!o){this.channel.emitEvent({type:"handoff",agent:Kl(d),to:p.name});let w=await this.chat.generateHandoffLine(d,m.role,m.task);this.channel.emitEvent({type:"speak",agent:Kl(d),to:p.name,content:w});let $=await this.chat.generateAckLine(m.role,d);this.channel.emitEvent({type:"speak",agent:p.name,to:Kl(d),content:$})}let g=Date.now(),x=await this.runner.runAgent(m.role,m.task,void 0,s,{abortSignal:r.abortSignal});u.push(x),x.success&&x.output?(this.channel.emitEvent({type:"summary",agent:p.name,durationMs:Date.now()-g}),m.role==="alex"&&(f=x.output),i&&m.role==="alex"&&t.tasks.some(w=>w.role==="bob")&&f&&await this.runPeerReview("bob","alex",f,r.abortSignal,o)):x.error&&this.channel.emitEvent({type:"error",agent:p.name,content:x.error}),d=m.role}this.channel.emitEvent({type:"phase",agent:"System",content:"Hablas compiling final report"});let h=await this.synthesize(e,u,s,r.abortSignal);return this.channel.emitEvent({type:"done",agent:"Hablas"}),h}async runPeerReview(e,t,s,r,i=!1){let o=Se.find(l=>l.role===e),a=Se.find(l=>l.role===t);if(!(!o||!a)){if(!i){let l=await this.chat.generateReviewLine(e,t,s);this.channel.emitEvent({type:"review",agent:o.name,to:a.name,content:l});let u=await this.chat.generateReviewAck(t,e);this.channel.emitEvent({type:"speak",agent:a.name,to:o.name,content:u})}r?.aborted}}async synthesize(e,t,s,r){let i=t.filter(d=>d.success&&d.output);if(i.length===0)return{results:t,finalSynthesis:"The team encountered errors and could not complete the task. Please review the logs and try again.",synthesisOk:!1};let o=i.map(d=>{let f=Se.find(h=>h.role===d.agent);return`### Report from @${d.agentName} (${f?.title??d.agent}):
1091
1155
  ${d.output}`}).join(`
1092
1156
 
1093
1157
  `),a=`You are Hablas, the Team Leader. Your team has completed a multi-agent workflow for the user's request: "${e}".
@@ -1097,13 +1161,13 @@ Here are the individual execution reports from your team members:
1097
1161
  ${o}
1098
1162
  """
1099
1163
 
1100
- Please compile, synthesize, and present the final unified response to the user. Describe what was achieved, the files modified/created (if any), and any next steps. Speak in your characteristic Hablas voice \u2014 INTJ, authoritative, terse, engineering-precise. Speak directly to the user.`,l=await this.runner.runAgent("hablas",a,void 0,s,{abortSignal:r});if(l.success&&l.output)return{results:t,finalSynthesis:l.output,synthesisOk:!0};let u=i.map(d=>{let f=we.find(h=>h.role===d.agent);return`### @${d.agentName} (${f?.title??d.agent}):
1164
+ Please compile, synthesize, and present the final unified response to the user. Describe what was achieved, the files modified/created (if any), and any next steps. Speak in your characteristic Hablas voice \u2014 INTJ, authoritative, terse, engineering-precise. Speak directly to the user.`,l=await this.runner.runAgent("hablas",a,void 0,s,{abortSignal:r});if(l.success&&l.output)return{results:t,finalSynthesis:l.output,synthesisOk:!0};let u=i.map(d=>{let f=Se.find(h=>h.role===d.agent);return`### @${d.agentName} (${f?.title??d.agent}):
1101
1165
  ${d.output}`}).join(`
1102
1166
 
1103
- `);return{results:t,finalSynthesis:u,synthesisOk:!1}}}});function ut(n){switch(n){case"Hablas":return c.leader;case"Bob":return c.architect;case"Alex":return c.engineer;case"David":return c.analyst;case"Emma":return c.product;default:return c.primary}}function qr(n){return n==="Hablas"?"\u2605":"\u25C6"}function Ss(n,e=140){let t=(n||"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e-1)+"\u2026":t}var _s,yg=L(()=>{"use strict";yn();_s=class{channel;opts;attached=!1;listener;lastThinking=null;lastLine="";constructor(e,t={}){this.channel=e,this.opts={hideThinking:t.hideThinking??!1,hideActs:t.hideActs??!1,maxChars:t.maxChars??140},this.listener=s=>this.handle(s)}attach(){return this.attached?this:(this.channel.onEvent(this.listener),this.attached=!0,this)}detach(){return this.attached?(this.channel.offEvent(this.listener),this.attached=!1,this):this}handle(e){switch(e.type){case"phase":return this.renderPhase(e);case"handoff":return this.renderHandoff(e);case"thinking":return this.renderThinking(e);case"speak":return this.renderSpeak(e);case"act":return this.renderAct(e);case"observe":return this.renderObserve(e);case"review":return this.renderReview(e);case"summary":return this.renderSummary(e);case"decision":return this.renderDecision(e);case"done":return this.renderDone(e);case"error":return this.renderError(e)}}renderPhase(e){let t=(e.content||"").toString();t&&(this.print(`
1104
- ${c.muted("\u25B8")} ${c.secondary(t)}`),this.lastThinking=null)}renderHandoff(e){let t=e.agent,s=e.to||"";if(!s)return;let r=ut(t),i=ut(s);this.print(` ${r(qr(t))} ${r(t)} ${c.muted("\u2501\u2501\u25B6")} ${i(qr(s))} ${i(s)}`),this.lastThinking=null}renderThinking(e){if(this.opts.hideThinking||this.lastThinking===e.agent)return;this.lastThinking=e.agent;let t=ut(e.agent),s=e.content&&e.content.length>5?e.content:"analyzing and formulating response\u2026";this.print(` ${t("\u25C9")} ${t(e.agent)} ${c.muted("\u2014")} ${s}`)}renderSpeak(e){let t=Ss(e.content||"",this.opts.maxChars);if(!t)return;let s=ut(e.agent),r=e.to?` ${c.muted("\u2192")} ${ut(e.to)("@"+e.to)}`:"",i=`speak:${e.agent}:${e.to||""}:${t}`;i!==this.lastLine&&(this.lastLine=i,this.print(` ${s(qr(e.agent))} ${s(e.agent)}${r}${c.muted(":")} ${c.secondary(t)}`),this.lastThinking=null)}renderAct(e){if(this.opts.hideActs)return;let t=ut(e.agent),s=e.toolName||"tool",r=e.toolArgs||{},i="";typeof r.path=="string"?i=` ${c.primary(r.path)}`:typeof r.command=="string"?i=` ${c.primary(r.command)}`:typeof r.query=="string"&&(i=` "${c.primary(r.query)}"`);let o=s==="write_file"||s==="edit_file"||s==="patch_file"?"\u270E":s==="run_command"?"\u2318":s==="read_file"?"\u{1F4D6}":s==="search_codebase"?"\u{1F50E}":"\u{1F527}";this.print(` ${t(o)} [Running Tool]: ${t(e.agent)} is executing ${c.strong(s)}${i}...`),this.lastThinking=null}renderObserve(e){if(this.opts.hideActs)return;let t=e.success!==!1,s=t?c.success("\u2713 COMPLETED"):c.error("\u2717 FAILED"),r=Ss(e.content||(t?"Execution succeeded":"Execution failed"),this.opts.maxChars);this.print(` ${c.muted("\u21B3")} ${s}: ${c.muted(r)}`)}renderReview(e){let t=e.agent,s=e.to||"",r=Ss(e.content||"",this.opts.maxChars);if(!r)return;let i=ut(t),o=ut(s);this.print(`
1105
- ${i("\u270E")} ${c.strong("@"+t)} ${c.muted("reviewing")} ${o("@"+s)}${c.muted(":")} ${c.secondary(r)}`),this.lastThinking=null}renderSummary(e){let t=ut(e.agent),s=e.durationMs?` ${c.muted(`(${(e.durationMs/1e3).toFixed(1)}s)`)}`:"";this.print(` ${t(qr(e.agent))} ${t(e.agent)} ${c.muted("\u2500\u2500\u25BA")} ${c.leader("\u2605 Hablas")} ${c.muted("\xB7 report submitted")}${s}`),this.lastThinking=null}renderDecision(e){let t=Ss(e.content||"",this.opts.maxChars);if(!t)return;let s=ut(e.agent);this.print(` ${s("\u25C6")} ${s(e.agent)} ${c.muted("decision:")} ${c.secondary(t)}`)}renderDone(e){this.print(`
1106
- ${c.chrome("\u2500".repeat(56))}`),this.lastThinking=null}renderError(e){let t=ut(e.agent),s=Ss(e.content||"unknown error",this.opts.maxChars);this.print(` ${t("\u25C6")} ${t(e.agent)} ${c.error("\u2717")} ${c.error(s)}`),this.lastThinking=null}print(e){console.log(e)}}});var Kr,bg=L(()=>{"use strict";Kr=class{plans=new Map;activePlanId=null;nextPlanNum=1;createPlan(e,t,s){let r=`plan_${this.nextPlanNum++}`,i={hablas:"Hablas",bob:"Bob",alex:"Alex",david:"David"},o={id:r,title:e,strategy:t,tasks:s.map((a,l)=>({task_id:`${r}_t${l+1}`,dependent_task_ids:a.dependent_task_ids||[],description:a.description,assignee:a.assignee,assigneeName:a.assigneeName||i[a.assignee]||a.assignee,status:"pending",createdAt:Date.now()})),createdAt:Date.now(),updatedAt:Date.now()};return this.plans.set(r,o),this.activePlanId=r,o}getActivePlan(){return this.activePlanId&&this.plans.get(this.activePlanId)||null}getTask(e){let t=this.getActivePlan();return t&&t.tasks.find(s=>s.task_id===e)||null}startTask(e){let t=this.getTask(e);return!t||!this.areDependenciesMet(e)?!1:(t.status="running",t.startedAt=Date.now(),this.touch(),!0)}finishTask(e,t){let s=this.getTask(e);return s?(s.status="done",s.result=t,s.completedAt=Date.now(),this.touch(),!0):!1}failTask(e,t){let s=this.getTask(e);return s?(s.status="failed",s.error=t,s.completedAt=Date.now(),this.touch(),!0):!1}skipTask(e){let t=this.getTask(e);return t?(t.status="skipped",t.completedAt=Date.now(),this.touch(),!0):!1}resetTask(e){let t=this.getTask(e);return t?(t.status="pending",t.result=void 0,t.error=void 0,t.startedAt=void 0,t.completedAt=void 0,this.touch(),!0):!1}replaceTask(e,t,s){let r=this.getTask(e);return r?(r.description=t,s&&(r.assignee=s),r.status="pending",r.result=void 0,r.error=void 0,this.touch(),!0):!1}areDependenciesMet(e){let t=this.getTask(e);if(!t)return!1;if(t.dependent_task_ids.length===0)return!0;let s=this.getActivePlan();return s?t.dependent_task_ids.every(r=>{let i=s.tasks.find(o=>o.task_id===r);return i&&(i.status==="done"||i.status==="skipped")}):!1}getNextTask(){let e=this.getActivePlan();if(!e)return null;for(let t of e.tasks)if(t.status==="pending"&&this.areDependenciesMet(t.task_id))return t;return null}getDependencyOrder(){let e=this.getActivePlan();if(!e)return[];let t=new Set,s=[],r=new Map(e.tasks.map(o=>[o.task_id,o])),i=o=>{if(t.has(o))return;t.add(o);let a=r.get(o);if(a){for(let l of a.dependent_task_ids)i(l);s.push(a)}};for(let o of e.tasks)i(o.task_id);return s}getProgress(){let e=this.getActivePlan();if(!e)return{total:0,done:0,failed:0,pending:0,running:0,skipped:0,percentage:0};let t=e.tasks.length,s=e.tasks.filter(u=>u.status==="done").length,r=e.tasks.filter(u=>u.status==="failed").length,i=e.tasks.filter(u=>u.status==="pending").length,o=e.tasks.filter(u=>u.status==="running").length,a=e.tasks.filter(u=>u.status==="skipped").length,l=t>0?Math.round((s+a)/t*100):0;return{total:t,done:s,failed:r,pending:i,running:o,skipped:a,percentage:l}}isComplete(){let e=this.getActivePlan();return e?e.tasks.every(t=>t.status==="done"||t.status==="failed"||t.status==="skipped"):!0}serialize(){let e=this.getActivePlan();return e?JSON.stringify(e,null,2):"{}"}deserialize(e){try{let t=JSON.parse(e);return t.id&&t.tasks?(this.plans.set(t.id,t),this.activePlanId=t.id,t):null}catch{return null}}reset(){this.plans.clear(),this.activePlanId=null,this.nextPlanNum=1}clear(){this.plans.clear(),this.activePlanId=null}touch(){let e=this.getActivePlan();e&&(e.updatedAt=Date.now())}}});var ce,dt,i0,o0,a0,l0,c0,u0,d0,Wr,vg=L(()=>{"use strict";ce=O(require("fs")),dt=O(require("path")),i0=".hablas",o0=`# Project Context \u2014 Hablas AI
1167
+ `);return{results:t,finalSynthesis:u,synthesisOk:!1}}}});function dt(n){switch(n){case"Hablas":return c.leader;case"Bob":return c.architect;case"Alex":return c.engineer;case"David":return c.analyst;case"Emma":return c.product;default:return c.primary}}function Wr(n){return n==="Hablas"?"\u2605":"\u25C6"}function _s(n,e=140){let t=(n||"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e-1)+"\u2026":t}var ks,Sg=L(()=>{"use strict";bn();ks=class{channel;opts;attached=!1;listener;lastThinking=null;lastLine="";constructor(e,t={}){this.channel=e,this.opts={hideThinking:t.hideThinking??!1,hideActs:t.hideActs??!1,maxChars:t.maxChars??140},this.listener=s=>this.handle(s)}attach(){return this.attached?this:(this.channel.onEvent(this.listener),this.attached=!0,this)}detach(){return this.attached?(this.channel.offEvent(this.listener),this.attached=!1,this):this}handle(e){switch(e.type){case"phase":return this.renderPhase(e);case"handoff":return this.renderHandoff(e);case"thinking":return this.renderThinking(e);case"speak":return this.renderSpeak(e);case"act":return this.renderAct(e);case"observe":return this.renderObserve(e);case"review":return this.renderReview(e);case"summary":return this.renderSummary(e);case"decision":return this.renderDecision(e);case"done":return this.renderDone(e);case"error":return this.renderError(e)}}renderPhase(e){let t=(e.content||"").toString();t&&(this.print(`
1168
+ ${c.muted("\u25B8")} ${c.secondary(t)}`),this.lastThinking=null)}renderHandoff(e){let t=e.agent,s=e.to||"";if(!s)return;let r=dt(t),i=dt(s);this.print(` ${r(Wr(t))} ${r(t)} ${c.muted("\u2501\u2501\u25B6")} ${i(Wr(s))} ${i(s)}`),this.lastThinking=null}renderThinking(e){if(this.opts.hideThinking||this.lastThinking===e.agent)return;this.lastThinking=e.agent;let t=dt(e.agent),s=e.content&&e.content.length>5?e.content:"analyzing and formulating response\u2026";this.print(` ${t("\u25C9")} ${t(e.agent)} ${c.muted("\u2014")} ${s}`)}renderSpeak(e){let t=_s(e.content||"",this.opts.maxChars);if(!t)return;let s=dt(e.agent),r=e.to?` ${c.muted("\u2192")} ${dt(e.to)("@"+e.to)}`:"",i=`speak:${e.agent}:${e.to||""}:${t}`;i!==this.lastLine&&(this.lastLine=i,this.print(` ${s(Wr(e.agent))} ${s(e.agent)}${r}${c.muted(":")} ${c.secondary(t)}`),this.lastThinking=null)}renderAct(e){if(this.opts.hideActs)return;let t=dt(e.agent),s=e.toolName||"tool",r=e.toolArgs||{},i="";typeof r.path=="string"?i=` ${c.primary(r.path)}`:typeof r.command=="string"?i=` ${c.primary(r.command)}`:typeof r.query=="string"&&(i=` "${c.primary(r.query)}"`);let o=s==="write_file"||s==="edit_file"||s==="patch_file"?"\u270E":s==="run_command"?"\u2318":s==="read_file"?"\u{1F4D6}":s==="search_codebase"?"\u{1F50E}":"\u{1F527}";this.print(` ${t(o)} [Running Tool]: ${t(e.agent)} is executing ${c.strong(s)}${i}...`),this.lastThinking=null}renderObserve(e){if(this.opts.hideActs)return;let t=e.success!==!1,s=t?c.success("\u2713 COMPLETED"):c.error("\u2717 FAILED"),r=_s(e.content||(t?"Execution succeeded":"Execution failed"),this.opts.maxChars);this.print(` ${c.muted("\u21B3")} ${s}: ${c.muted(r)}`)}renderReview(e){let t=e.agent,s=e.to||"",r=_s(e.content||"",this.opts.maxChars);if(!r)return;let i=dt(t),o=dt(s);this.print(`
1169
+ ${i("\u270E")} ${c.strong("@"+t)} ${c.muted("reviewing")} ${o("@"+s)}${c.muted(":")} ${c.secondary(r)}`),this.lastThinking=null}renderSummary(e){let t=dt(e.agent),s=e.durationMs?` ${c.muted(`(${(e.durationMs/1e3).toFixed(1)}s)`)}`:"";this.print(` ${t(Wr(e.agent))} ${t(e.agent)} ${c.muted("\u2500\u2500\u25BA")} ${c.leader("\u2605 Hablas")} ${c.muted("\xB7 report submitted")}${s}`),this.lastThinking=null}renderDecision(e){let t=_s(e.content||"",this.opts.maxChars);if(!t)return;let s=dt(e.agent);this.print(` ${s("\u25C6")} ${s(e.agent)} ${c.muted("decision:")} ${c.secondary(t)}`)}renderDone(e){this.print(`
1170
+ ${c.chrome("\u2500".repeat(56))}`),this.lastThinking=null}renderError(e){let t=dt(e.agent),s=_s(e.content||"unknown error",this.opts.maxChars);this.print(` ${t("\u25C6")} ${t(e.agent)} ${c.error("\u2717")} ${c.error(s)}`),this.lastThinking=null}print(e){console.log(e)}}});var Gr,_g=L(()=>{"use strict";Gr=class{plans=new Map;activePlanId=null;nextPlanNum=1;createPlan(e,t,s){let r=`plan_${this.nextPlanNum++}`,i={hablas:"Hablas",bob:"Bob",alex:"Alex",david:"David"},o={id:r,title:e,strategy:t,tasks:s.map((a,l)=>({task_id:`${r}_t${l+1}`,dependent_task_ids:a.dependent_task_ids||[],description:a.description,assignee:a.assignee,assigneeName:a.assigneeName||i[a.assignee]||a.assignee,status:"pending",createdAt:Date.now()})),createdAt:Date.now(),updatedAt:Date.now()};return this.plans.set(r,o),this.activePlanId=r,o}getActivePlan(){return this.activePlanId&&this.plans.get(this.activePlanId)||null}getTask(e){let t=this.getActivePlan();return t&&t.tasks.find(s=>s.task_id===e)||null}startTask(e){let t=this.getTask(e);return!t||!this.areDependenciesMet(e)?!1:(t.status="running",t.startedAt=Date.now(),this.touch(),!0)}finishTask(e,t){let s=this.getTask(e);return s?(s.status="done",s.result=t,s.completedAt=Date.now(),this.touch(),!0):!1}failTask(e,t){let s=this.getTask(e);return s?(s.status="failed",s.error=t,s.completedAt=Date.now(),this.touch(),!0):!1}skipTask(e){let t=this.getTask(e);return t?(t.status="skipped",t.completedAt=Date.now(),this.touch(),!0):!1}resetTask(e){let t=this.getTask(e);return t?(t.status="pending",t.result=void 0,t.error=void 0,t.startedAt=void 0,t.completedAt=void 0,this.touch(),!0):!1}replaceTask(e,t,s){let r=this.getTask(e);return r?(r.description=t,s&&(r.assignee=s),r.status="pending",r.result=void 0,r.error=void 0,this.touch(),!0):!1}areDependenciesMet(e){let t=this.getTask(e);if(!t)return!1;if(t.dependent_task_ids.length===0)return!0;let s=this.getActivePlan();return s?t.dependent_task_ids.every(r=>{let i=s.tasks.find(o=>o.task_id===r);return i&&(i.status==="done"||i.status==="skipped")}):!1}getNextTask(){let e=this.getActivePlan();if(!e)return null;for(let t of e.tasks)if(t.status==="pending"&&this.areDependenciesMet(t.task_id))return t;return null}getDependencyOrder(){let e=this.getActivePlan();if(!e)return[];let t=new Set,s=[],r=new Map(e.tasks.map(o=>[o.task_id,o])),i=o=>{if(t.has(o))return;t.add(o);let a=r.get(o);if(a){for(let l of a.dependent_task_ids)i(l);s.push(a)}};for(let o of e.tasks)i(o.task_id);return s}getProgress(){let e=this.getActivePlan();if(!e)return{total:0,done:0,failed:0,pending:0,running:0,skipped:0,percentage:0};let t=e.tasks.length,s=e.tasks.filter(u=>u.status==="done").length,r=e.tasks.filter(u=>u.status==="failed").length,i=e.tasks.filter(u=>u.status==="pending").length,o=e.tasks.filter(u=>u.status==="running").length,a=e.tasks.filter(u=>u.status==="skipped").length,l=t>0?Math.round((s+a)/t*100):0;return{total:t,done:s,failed:r,pending:i,running:o,skipped:a,percentage:l}}isComplete(){let e=this.getActivePlan();return e?e.tasks.every(t=>t.status==="done"||t.status==="failed"||t.status==="skipped"):!0}serialize(){let e=this.getActivePlan();return e?JSON.stringify(e,null,2):"{}"}deserialize(e){try{let t=JSON.parse(e);return t.id&&t.tasks?(this.plans.set(t.id,t),this.activePlanId=t.id,t):null}catch{return null}}reset(){this.plans.clear(),this.activePlanId=null,this.nextPlanNum=1}clear(){this.plans.clear(),this.activePlanId=null}touch(){let e=this.getActivePlan();e&&(e.updatedAt=Date.now())}}});var ce,ft,u0,d0,f0,p0,h0,m0,g0,Vr,kg=L(()=>{"use strict";ce=O(require("fs")),ft=O(require("path")),u0=".hablas",d0=`# Project Context \u2014 Hablas AI
1107
1171
 
1108
1172
  ## Project Overview
1109
1173
  <!-- Auto-populated by Hablas on first scan -->
@@ -1120,7 +1184,7 @@ ${d.output}`}).join(`
1120
1184
 
1121
1185
  ## Team Notes
1122
1186
  <!-- Freeform notes from agents and user -->
1123
- `,a0=`# Requirements & Progress
1187
+ `,f0=`# Requirements & Progress
1124
1188
 
1125
1189
  ## Current Sprint
1126
1190
  <!-- Active work items -->
@@ -1137,7 +1201,7 @@ ${d.output}`}).join(`
1137
1201
 
1138
1202
  ## Progress Log
1139
1203
  <!-- Chronological log of all actions taken -->
1140
- `,l0=`# Architecture Design
1204
+ `,p0=`# Architecture Design
1141
1205
 
1142
1206
  ## System Overview
1143
1207
  <!-- High-level architecture description -->
@@ -1165,7 +1229,7 @@ ${d.output}`}).join(`
1165
1229
 
1166
1230
  ## Implementation Guide
1167
1231
  <!-- Step-by-step implementation order -->
1168
- `,c0=`# Agent Activity Log
1232
+ `,h0=`# Agent Activity Log
1169
1233
 
1170
1234
  ## Session History
1171
1235
  | Session | Date | Duration | Agents Used | Tasks Completed |
@@ -1181,7 +1245,7 @@ ${d.output}`}).join(`
1181
1245
 
1182
1246
  ## Inter-Agent Communication
1183
1247
  <!-- Messages exchanged between agents during complex tasks -->
1184
- `,u0=`# Learned Knowledge
1248
+ `,m0=`# Learned Knowledge
1185
1249
 
1186
1250
  ## Project Conventions
1187
1251
  <!-- Coding style, naming conventions, file organization patterns -->
@@ -1197,7 +1261,7 @@ ${d.output}`}).join(`
1197
1261
 
1198
1262
  ## Dependency Notes
1199
1263
  <!-- Important notes about dependencies and versions -->
1200
- `,d0={"HABLAS.md":o0,"PROGRESS.md":a0,"ARCHITECTURE.md":l0,"AGENTS.md":c0,"MEMORY.md":u0},Wr=class{contextDir;sessionDelegations=[];sessionDiscoveries=[];constructor(e){this.contextDir=dt.join(e,i0)}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(d0)){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)+`
1264
+ `,g0={"HABLAS.md":d0,"PROGRESS.md":f0,"ARCHITECTURE.md":p0,"AGENTS.md":h0,"MEMORY.md":m0},Vr=class{contextDir;sessionDelegations=[];sessionDiscoveries=[];constructor(e){this.contextDir=ft.join(e,u0)}init(){let e=ft.join(ft.dirname(this.contextDir),".hablas-legacy");if(ce.existsSync(e)&&!ce.existsSync(this.contextDir))try{ce.renameSync(e,this.contextDir);let t=ft.join(this.contextDir,"LEGACY.md"),s=ft.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(g0)){let r=ft.join(this.contextDir,t);ce.existsSync(r)||ce.writeFileSync(r,s,"utf-8")}}exists(){return ce.existsSync(this.contextDir)}readContext(e){let t=ft.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
1265
  ...(truncated)`:o;s.push(`### ${i}
1202
1266
  ${l}`),r+=l.length}}return s.length>0?s.join(`
1203
1267
 
@@ -1209,44 +1273,44 @@ ${a}`),r=s.join(`
1209
1273
  `)}getSessionDelegations(){return[...this.sessionDelegations]}getSessionDiscoveries(){return[...this.sessionDiscoveries]}addContextFromFile(e,t,s,r){let i=this.readContext(t);if(!i)return;let o=0;for(let a of s){if(o>=r)break;let l=this.extractSection(i,a);if(l&&l.trim().length>10){let u=r-o,d=l.length>u?l.slice(0,u)+"...":l;e.push(`${a}
1210
1274
  ${d}`),o+=d.length}}}extractSection(e,t){let s=e.split(`
1211
1275
  `),r=s.findIndex(o=>o.trim()===t);if(r===-1)return null;let i=s.length;for(let o=r+1;o<s.length;o++)if(/^#{1,2}\s/.test(s[o])){i=o;break}return s.slice(r+1,i).join(`
1212
- `).trim()}updateSection(e,t,s){let r=dt.join(this.contextDir,e);if(!ce.existsSync(r))return;let o=ce.readFileSync(r,"utf-8").split(`
1276
+ `).trim()}updateSection(e,t,s){let r=ft.join(this.contextDir,e);if(!ce.existsSync(r))return;let o=ce.readFileSync(r,"utf-8").split(`
1213
1277
  `),a=o.findIndex(h=>h.trim()===t);if(a===-1)return;let l=o.length;for(let h=a+1;h<o.length;h++)if(/^#{1,2}\s/.test(o[h])){l=h;break}let u=o.slice(0,a+1),d=o.slice(l),f=[...u,s,"",...d].join(`
1214
- `);ce.writeFileSync(r,f,"utf-8")}appendToSection(e,t,s){let r=dt.join(this.contextDir,e);ce.existsSync(r)||this.init();let i=ce.readFileSync(r,"utf-8"),o=i.split(`
1278
+ `);ce.writeFileSync(r,f,"utf-8")}appendToSection(e,t,s){let r=ft.join(this.contextDir,e);ce.existsSync(r)||this.init();let i=ce.readFileSync(r,"utf-8"),o=i.split(`
1215
1279
  `),a=o.findIndex(u=>u.trim()===t);if(a===-1){ce.writeFileSync(r,i+`
1216
1280
  `+s+`
1217
1281
  `,"utf-8");return}let l=a+1;for(;l<o.length;){let u=o[l].trim();if(/^#{1,2}\s/.test(u))break;l++}o.splice(l,0,s),ce.writeFileSync(r,o.join(`
1218
- `),"utf-8")}}});function xg(n){let e=n.trim();if(e.length<20||e.length<15||wg.test(e)||e.includes("```")||p0.test(e)||/\/[\w-]+\.[\w]+/.test(e)||e.length<60&&wg.test(e))return null;for(let{pattern:t,question:s,choices:r}of f0)if(t.test(e))return e.length>40&&/\b(called|named|using|with|for)\b/i.test(e)?null:{question:s,choices:r,context:e};return null}function Sg(n,e){let t=n.trim().toLowerCase(),s=t.split(/[,\s]+/).filter(i=>/^[a-z]$/.test(i));if(s.length>0)return s.map(i=>{let o=i.charCodeAt(0)-97;return e.choices[o]?.value}).filter(i=>i!==void 0);let r=t.split(/[,\s]+/).filter(i=>/^\d+$/.test(i));return r.length>0?r.map(i=>{let o=parseInt(i,10)-1;return e.choices[o]?.value}).filter(i=>i!==void 0):[t]}var f0,wg,p0,_g=L(()=>{"use strict";f0=[{pattern:/\b(create|make|build)\s+(a|an|the)?\s*(app|application|project)\b/i,question:"What type of application would you like to create?",choices:[{label:"Web application (React/Next.js)",value:"web"},{label:"CLI tool (Node.js)",value:"cli"},{label:"API server (Express/Fastify)",value:"api"},{label:"Something else (please describe)",value:"other"}]},{pattern:/\b(refactor|rewrite|restructure)\s+(the\s+)?(entire|whole|all)\b/i,question:"Large-scale refactoring detected. How would you like to proceed?",choices:[{label:"Incremental \u2014 one module at a time",value:"incremental"},{label:"Full rewrite \u2014 replace everything",value:"full"},{label:"Just the architecture \u2014 keep implementations",value:"architecture"},{label:"Let me specify which parts",value:"specify"}]},{pattern:/\b(delete|remove|drop)\s+(all|every|the\s+entire)\b/i,question:"This is a destructive operation. Please confirm scope:",choices:[{label:"Yes, remove everything matching",value:"all"},{label:"Only unused/dead code",value:"unused"},{label:"Let me be more specific",value:"specify"},{label:"Cancel \u2014 don't delete anything",value:"cancel"}]},{pattern:/\b(setup|configure|install)\s+(the\s+)?(project|environment|dev)\b/i,question:"What environment are you setting up?",choices:[{label:"Development (local)",value:"dev"},{label:"Production deployment",value:"prod"},{label:"CI/CD pipeline",value:"ci"},{label:"Docker/containerized",value:"docker"}]},{pattern:/\b(fix|debug|solve)\s+(the\s+)?(issue|bug|problem|error)\b/i,question:"Can you provide more details about the issue?",choices:[{label:"Runtime error (crashes/exceptions)",value:"runtime"},{label:"Build/compile error",value:"build"},{label:"Logic bug (wrong behavior)",value:"logic"},{label:"Performance issue (slow)",value:"performance"}]}],wg=/[\w-]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|scss|html|vue|svelte|go|rs|java|c|cpp|h|rb|php|sql|sh|bash|toml|xml|env)/i,p0=/\b(fix|update|change|add|remove|rename|move|edit|read|show|cat|open)\s+(the\s+)?(typo|bug|error|import|line|function|variable|class|method|comment|style)/i});var Gr,_t,zr,Vr,kg=L(()=>{"use strict";Gr=O(require("fs")),_t=O(require("fs/promises")),zr=O(require("path")),Vr=class{stack=[];workingDir;maxEntries;nextGroupId=1;constructor(e,t=200){this.workingDir=e,this.maxEntries=t}async record(e,t,s,r="hablas",i){let o=zr.resolve(this.workingDir,e),a=null;try{Gr.existsSync(o)&&(a=await _t.readFile(o,"utf-8"))}catch{}let l={id:`undo_${Date.now()}_${this.stack.length}`,filePath:e,absolutePath:o,originalContent:a,newContent:t,toolName:s,agent:r,timestamp:Date.now(),undone:!1,groupId:i};return this.stack.push(l),this.stack.length>this.maxEntries&&(this.stack=this.stack.slice(-this.maxEntries)),l.id}beginGroup(){return`group_${this.nextGroupId++}`}async undo(e=1){let t=[],r=this.stack.filter(i=>!i.undone).reverse().slice(0,e);for(let i of r)try{i.originalContent===null?(Gr.existsSync(i.absolutePath)&&await _t.unlink(i.absolutePath),t.push({file:i.filePath,success:!0})):(await _t.mkdir(zr.dirname(i.absolutePath),{recursive:!0}),await _t.writeFile(i.absolutePath,i.originalContent,"utf-8"),t.push({file:i.filePath,success:!0})),i.undone=!0}catch(o){t.push({file:i.filePath,success:!1,error:o.message})}return t}async undoGroup(e){let t=this.stack.filter(r=>r.groupId===e&&!r.undone).reverse(),s=[];for(let r of t)try{r.originalContent===null?Gr.existsSync(r.absolutePath)&&await _t.unlink(r.absolutePath):await _t.writeFile(r.absolutePath,r.originalContent,"utf-8"),r.undone=!0,s.push({file:r.filePath,success:!0})}catch(i){s.push({file:r.filePath,success:!1,error:i.message})}return s}async undoAll(){return this.undo(this.getUndoableCount())}getUndoableCount(){return this.stack.filter(e=>!e.undone).length}getRecent(e=15){return this.stack.filter(t=>!t.undone).slice(-e).reverse()}getModifiedFiles(){let e=new Set;for(let t of this.stack.filter(s=>!s.undone))e.add(t.filePath);return Array.from(e)}formatList(e=15){let t=this.getRecent(e);if(t.length===0)return" No changes to undo";let s=[];for(let i=0;i<t.length;i++){let o=t[i],a=this.formatAge(o.timestamp),l=o.originalContent===null?"created":"modified",u=o.agent!=="hablas"?` [@${o.agent}]`:"";s.push(` ${i+1}. ${o.filePath} \u2014 ${l} by ${o.toolName}${u} (${a})`)}let r=this.getUndoableCount();return r>e&&s.push(` ... and ${r-e} more`),s.join(`
1219
- `)}formatAge(e){let t=Date.now()-e,s=Math.floor(t/1e3);if(s<60)return`${s}s ago`;let r=Math.floor(s/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}size(){return this.stack.length}clear(){this.stack=[]}}});function h0(n,e){let t=[],s;for(Ag.lastIndex=0;(s=Ag.exec(n))!==null;){let r=s[1],i=Ee.resolve(e,r);ft.existsSync(i)&&t.push(r)}return[...new Set(t)]}function m0(n,e,t){let s=[],r=Ee.extname(e),i=Ee.dirname(Ee.resolve(t,e));if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(r)){let o;for($g.lastIndex=0;(o=$g.exec(n))!==null;){let a=o[1]||o[2];if(!a||!a.startsWith(".")&&!a.startsWith("/"))continue;let l=g0(a,i);l&&s.push(Ee.relative(t,l))}}else if(r===".py"){let o;for(Cg.lastIndex=0;(o=Cg.exec(n))!==null;){let a=o[1]||o[2];if(!a)continue;let l=a.replace(/\./g,"/")+".py",u=Ee.resolve(i,l);ft.existsSync(u)&&s.push(Ee.relative(t,u))}}return[...new Set(s)]}function g0(n,e){let t=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],s=Ee.resolve(e,n);if(ft.existsSync(s)&&ft.statSync(s).isFile())return s;for(let r of t){let i=s+r;if(ft.existsSync(i))return i}for(let r of t){let i=Ee.join(s,`index${r}`);if(ft.existsSync(i))return i}return null}function Eg(n,e,t){let s=t?.maxFiles||10,r=t?.maxTokens||8e3,i=t?.followImports!==!1,o=h0(n,e),a=[],l=new Set,u=0;for(let d of o){if(a.length>=s||u>=r)break;if(!l.has(d)){l.add(d);try{let f=Ee.resolve(e,d),h=ft.readFileSync(f,"utf-8"),m=h.split(`
1282
+ `),"utf-8")}}});function $g(n){let e=n.trim();if(e.length<20||e.length<15||Ag.test(e)||e.includes("```")||b0.test(e)||/\/[\w-]+\.[\w]+/.test(e)||e.length<60&&Ag.test(e))return null;for(let{pattern:t,question:s,choices:r}of y0)if(t.test(e))return e.length>40&&/\b(called|named|using|with|for)\b/i.test(e)?null:{question:s,choices:r,context:e};return null}function Cg(n,e){let t=n.trim().toLowerCase(),s=t.split(/[,\s]+/).filter(i=>/^[a-z]$/.test(i));if(s.length>0)return s.map(i=>{let o=i.charCodeAt(0)-97;return e.choices[o]?.value}).filter(i=>i!==void 0);let r=t.split(/[,\s]+/).filter(i=>/^\d+$/.test(i));return r.length>0?r.map(i=>{let o=parseInt(i,10)-1;return e.choices[o]?.value}).filter(i=>i!==void 0):[t]}var y0,Ag,b0,Eg=L(()=>{"use strict";y0=[{pattern:/\b(create|make|build)\s+(a|an|the)?\s*(app|application|project)\b/i,question:"What type of application would you like to create?",choices:[{label:"Web application (React/Next.js)",value:"web"},{label:"CLI tool (Node.js)",value:"cli"},{label:"API server (Express/Fastify)",value:"api"},{label:"Something else (please describe)",value:"other"}]},{pattern:/\b(refactor|rewrite|restructure)\s+(the\s+)?(entire|whole|all)\b/i,question:"Large-scale refactoring detected. How would you like to proceed?",choices:[{label:"Incremental \u2014 one module at a time",value:"incremental"},{label:"Full rewrite \u2014 replace everything",value:"full"},{label:"Just the architecture \u2014 keep implementations",value:"architecture"},{label:"Let me specify which parts",value:"specify"}]},{pattern:/\b(delete|remove|drop)\s+(all|every|the\s+entire)\b/i,question:"This is a destructive operation. Please confirm scope:",choices:[{label:"Yes, remove everything matching",value:"all"},{label:"Only unused/dead code",value:"unused"},{label:"Let me be more specific",value:"specify"},{label:"Cancel \u2014 don't delete anything",value:"cancel"}]},{pattern:/\b(setup|configure|install)\s+(the\s+)?(project|environment|dev)\b/i,question:"What environment are you setting up?",choices:[{label:"Development (local)",value:"dev"},{label:"Production deployment",value:"prod"},{label:"CI/CD pipeline",value:"ci"},{label:"Docker/containerized",value:"docker"}]},{pattern:/\b(fix|debug|solve)\s+(the\s+)?(issue|bug|problem|error)\b/i,question:"Can you provide more details about the issue?",choices:[{label:"Runtime error (crashes/exceptions)",value:"runtime"},{label:"Build/compile error",value:"build"},{label:"Logic bug (wrong behavior)",value:"logic"},{label:"Performance issue (slow)",value:"performance"}]}],Ag=/[\w-]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|scss|html|vue|svelte|go|rs|java|c|cpp|h|rb|php|sql|sh|bash|toml|xml|env)/i,b0=/\b(fix|update|change|add|remove|rename|move|edit|read|show|cat|open)\s+(the\s+)?(typo|bug|error|import|line|function|variable|class|method|comment|style)/i});var zr,St,Jr,Yr,Tg=L(()=>{"use strict";zr=O(require("fs")),St=O(require("fs/promises")),Jr=O(require("path")),Yr=class{stack=[];workingDir;maxEntries;nextGroupId=1;constructor(e,t=200){this.workingDir=e,this.maxEntries=t}async record(e,t,s,r="hablas",i){let o=Jr.resolve(this.workingDir,e),a=null;try{zr.existsSync(o)&&(a=await St.readFile(o,"utf-8"))}catch{}let l={id:`undo_${Date.now()}_${this.stack.length}`,filePath:e,absolutePath:o,originalContent:a,newContent:t,toolName:s,agent:r,timestamp:Date.now(),undone:!1,groupId:i};return this.stack.push(l),this.stack.length>this.maxEntries&&(this.stack=this.stack.slice(-this.maxEntries)),l.id}beginGroup(){return`group_${this.nextGroupId++}`}async undo(e=1){let t=[],r=this.stack.filter(i=>!i.undone).reverse().slice(0,e);for(let i of r)try{i.originalContent===null?(zr.existsSync(i.absolutePath)&&await St.unlink(i.absolutePath),t.push({file:i.filePath,success:!0})):(await St.mkdir(Jr.dirname(i.absolutePath),{recursive:!0}),await St.writeFile(i.absolutePath,i.originalContent,"utf-8"),t.push({file:i.filePath,success:!0})),i.undone=!0}catch(o){t.push({file:i.filePath,success:!1,error:o.message})}return t}async undoGroup(e){let t=this.stack.filter(r=>r.groupId===e&&!r.undone).reverse(),s=[];for(let r of t)try{r.originalContent===null?zr.existsSync(r.absolutePath)&&await St.unlink(r.absolutePath):await St.writeFile(r.absolutePath,r.originalContent,"utf-8"),r.undone=!0,s.push({file:r.filePath,success:!0})}catch(i){s.push({file:r.filePath,success:!1,error:i.message})}return s}async undoAll(){return this.undo(this.getUndoableCount())}getUndoableCount(){return this.stack.filter(e=>!e.undone).length}getRecent(e=15){return this.stack.filter(t=>!t.undone).slice(-e).reverse()}getModifiedFiles(){let e=new Set;for(let t of this.stack.filter(s=>!s.undone))e.add(t.filePath);return Array.from(e)}formatList(e=15){let t=this.getRecent(e);if(t.length===0)return" No changes to undo";let s=[];for(let i=0;i<t.length;i++){let o=t[i],a=this.formatAge(o.timestamp),l=o.originalContent===null?"created":"modified",u=o.agent!=="hablas"?` [@${o.agent}]`:"";s.push(` ${i+1}. ${o.filePath} \u2014 ${l} by ${o.toolName}${u} (${a})`)}let r=this.getUndoableCount();return r>e&&s.push(` ... and ${r-e} more`),s.join(`
1283
+ `)}formatAge(e){let t=Date.now()-e,s=Math.floor(t/1e3);if(s<60)return`${s}s ago`;let r=Math.floor(s/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}size(){return this.stack.length}clear(){this.stack=[]}}});function v0(n,e){let t=[],s;for(Rg.lastIndex=0;(s=Rg.exec(n))!==null;){let r=s[1],i=Te.resolve(e,r);pt.existsSync(i)&&t.push(r)}return[...new Set(t)]}function w0(n,e,t){let s=[],r=Te.extname(e),i=Te.dirname(Te.resolve(t,e));if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(r)){let o;for(Og.lastIndex=0;(o=Og.exec(n))!==null;){let a=o[1]||o[2];if(!a||!a.startsWith(".")&&!a.startsWith("/"))continue;let l=x0(a,i);l&&s.push(Te.relative(t,l))}}else if(r===".py"){let o;for(Pg.lastIndex=0;(o=Pg.exec(n))!==null;){let a=o[1]||o[2];if(!a)continue;let l=a.replace(/\./g,"/")+".py",u=Te.resolve(i,l);pt.existsSync(u)&&s.push(Te.relative(t,u))}}return[...new Set(s)]}function x0(n,e){let t=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],s=Te.resolve(e,n);if(pt.existsSync(s)&&pt.statSync(s).isFile())return s;for(let r of t){let i=s+r;if(pt.existsSync(i))return i}for(let r of t){let i=Te.join(s,`index${r}`);if(pt.existsSync(i))return i}return null}function Mg(n,e,t){let s=t?.maxFiles||10,r=t?.maxTokens||8e3,i=t?.followImports!==!1,o=v0(n,e),a=[],l=new Set,u=0;for(let d of o){if(a.length>=s||u>=r)break;if(!l.has(d)){l.add(d);try{let f=Te.resolve(e,d),h=pt.readFileSync(f,"utf-8"),m=h.split(`
1220
1284
  `).length,p=Math.ceil(h.length/4);if(p>4e3){let g=h.split(`
1221
1285
  `).slice(0,200).join(`
1222
1286
  `)+`
1223
- ...(truncated)`,x=Math.ceil(g.length/4);u+x<=r&&(a.push({path:d,content:g,source:"mentioned",lineCount:200}),u+=x)}else if(u+p<=r&&(a.push({path:d,content:h,source:"mentioned",lineCount:m}),u+=p,i)){let g=m0(h,d,e);for(let x of g.slice(0,5)){if(a.length>=s||u>=r)break;if(!l.has(x)){l.add(x);try{let w=Ee.resolve(e,x),$=ft.readFileSync(w,"utf-8"),A=Math.ceil($.length/4),y=$.split(`
1287
+ ...(truncated)`,x=Math.ceil(g.length/4);u+x<=r&&(a.push({path:d,content:g,source:"mentioned",lineCount:200}),u+=x)}else if(u+p<=r&&(a.push({path:d,content:h,source:"mentioned",lineCount:m}),u+=p,i)){let g=w0(h,d,e);for(let x of g.slice(0,5)){if(a.length>=s||u>=r)break;if(!l.has(x)){l.add(x);try{let w=Te.resolve(e,x),$=pt.readFileSync(w,"utf-8"),A=Math.ceil($.length/4),y=$.split(`
1224
1288
  `).length;if(A>2e3){let v=$.split(`
1225
1289
  `).slice(0,100).join(`
1226
1290
  `)+`
1227
- ...(truncated)`,b=Math.ceil(v.length/4);u+b<=r&&(a.push({path:x,content:v,source:"imported",lineCount:100}),u+=b)}else u+A<=r&&(a.push({path:x,content:$,source:"imported",lineCount:y}),u+=A)}catch{}}}}}catch{}}}return{files:a,totalTokensEstimate:u,mentionedPaths:o}}function Tg(n){if(n.files.length===0)return"";let e=["## Referenced Files"];for(let t of n.files){let s=t.source==="imported"?" (imported)":"";e.push(`### ${t.path}${s} (${t.lineCount} lines)`),e.push("```"),e.push(t.content),e.push("```")}return e.join(`
1228
- `)}var ft,Ee,Ag,$g,Cg,Rg=L(()=>{"use strict";ft=O(require("fs")),Ee=O(require("path")),Ag=/(?:^|\s|['"`])([.\w\-/\\]+\.(?:ts|js|tsx|jsx|py|go|rs|java|c|cpp|h|css|scss|html|vue|svelte|json|yaml|yml|toml|md|sql|sh|env|xml))\b/gi,$g=/(?:import\s+.*?\s+from\s+['"]([^'"]+)['"]|require\s*\(\s*['"]([^'"]+)['"]\s*\))/g,Cg=/(?:from\s+(\S+)\s+import|import\s+(\S+))/g});var Pg={};Ne(Pg,{runSetupWizard:()=>Ul});function be(n,e){return new Promise(t=>{n.question(e,s=>t(s))})}function b0(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}async function Ul(n){let e=Og.createInterface({input:process.stdin,output:process.stdout});switch(console.log(),console.log(`${ht}${ye} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${M}`),console.log(`${ht}${ye} hablas \u2014 Setup Wizard${M}`),console.log(`${W} Configure your AI provider and model${M}`),console.log(`${ht}${ye} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${M}`),console.log(),console.log(`${ht} Choose your setup:${M}`),console.log(),console.log(` ${y0}${ht}1${M}. ${ht}Hablas Integrated Engine${M} ${pt}(instant \u2014 no setup needed)${M}`),console.log(` ${W}Pre-configured cloud AI, ready to use immediately${M}`),console.log(),console.log(` ${ye}${ht}2${M}. ${ht}Custom Provider${M} ${W}(bring your own API key)${M}`),console.log(` ${W}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${M}`),console.log(),(await be(e,` ${W}Your choice (1-2):${M} `)).trim()){case"1":{n.provider=Wt.provider,n.apiUrl=Wt.apiUrl,n.apiKey=b0(),n.model=Wt.model,wt(n),tt({name:Wt.name,apiUrl:Wt.apiUrl,apiKey:n.apiKey,models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.3-70b-instruct","deepseek-ai/deepseek-r1"],defaultModel:Wt.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${pt} \u2713 Hablas Integrated Engine activated!${M}`),console.log(`${W} Model: ${Wt.model}${M}`),console.log(`${W} API: ${Wt.apiUrl}${M}`),console.log(`${W} No API key needed \u2014 everything is pre-configured.${M}`);break}case"2":{switch(console.log(),console.log(`${W} Select your provider:${M}`),console.log(` ${ye}a${M}. Ollama (local, free, private)`),console.log(` ${ye}b${M}. OpenAI API`),console.log(` ${ye}c${M}. Groq (fast, free tier)`),console.log(` ${ye}d${M}. OpenRouter (many models)`),console.log(` ${ye}e${M}. Together AI`),console.log(` ${ye}f${M}. DeepSeek`),console.log(` ${ye}g${M}. Custom OpenAI-compatible API`),console.log(` ${ye}h${M}. NVIDIA NIM (powerful cloud models)`),console.log(),(await be(e,` ${W}Your choice (a-h):${M} `)).trim().toLowerCase()){case"a":{n.provider="ollama";let r=await be(e,` ${W}Ollama host [http://localhost:11434]:${M} `);r.trim()&&(n.ollamaHost=r.trim());let i=await be(e,` ${W}Model [qwen2.5-coder:7b]:${M} `);i.trim()&&(n.model=i.trim()),wt(n),console.log(),console.log(`${pt} \u2713 Configured for Ollama${M}`),console.log(`${W} Model: ${n.model}${M}`),console.log(`${W} Host: ${n.ollamaHost}${M}`),console.log(`${W} Make sure Ollama is running: ollama serve${M}`);break}case"b":{let r=await be(e,` ${W}OpenAI API Key (sk-...):${M} `);if(!r.trim()){console.log(`${kt} \u26A0 No key provided \u2014 cancelled${M}`);break}let i=await be(e,` ${W}Model [gpt-4o]:${M} `);n.provider="custom",n.apiUrl="https://api.openai.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"gpt-4o",wt(n),tt({name:"OpenAI",apiUrl:"https://api.openai.com/v1",apiKey:r.trim(),models:["gpt-4o","gpt-4o-mini","gpt-4-turbo","o1","o3-mini"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${pt} \u2713 Configured for OpenAI${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"c":{let r=await be(e,` ${W}Groq API Key (gsk_...):${M} `);if(!r.trim()){console.log(`${kt} \u26A0 No key provided \u2014 cancelled${M}`);break}let i=await be(e,` ${W}Model [llama-3.3-70b-versatile]:${M} `);n.provider="custom",n.apiUrl="https://api.groq.com/openai/v1",n.apiKey=r.trim(),n.model=i.trim()||"llama-3.3-70b-versatile",wt(n),tt({name:"Groq",apiUrl:"https://api.groq.com/openai/v1",apiKey:r.trim(),models:["llama-3.3-70b-versatile","llama-3.1-70b-versatile","mixtral-8x7b-32768","gemma2-9b-it"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${pt} \u2713 Configured for Groq${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"d":{let r=await be(e,` ${W}OpenRouter API Key (sk-or-...):${M} `);if(!r.trim()){console.log(`${kt} \u26A0 No key provided \u2014 cancelled${M}`);break}let i=await be(e,` ${W}Model [anthropic/claude-3.5-sonnet]:${M} `);n.provider="custom",n.apiUrl="https://openrouter.ai/api/v1",n.apiKey=r.trim(),n.model=i.trim()||"anthropic/claude-3.5-sonnet",wt(n),tt({name:"OpenRouter",apiUrl:"https://openrouter.ai/api/v1",apiKey:r.trim(),models:["openai/gpt-4o","anthropic/claude-3.5-sonnet","google/gemini-2.0-flash-001","deepseek/deepseek-r1"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${pt} \u2713 Configured for OpenRouter${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"e":{let r=await be(e,` ${W}Together API Key:${M} `);if(!r.trim()){console.log(`${kt} \u26A0 No key provided \u2014 cancelled${M}`);break}let i=await be(e,` ${W}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${M} `);n.provider="custom",n.apiUrl="https://api.together.xyz/v1",n.apiKey=r.trim(),n.model=i.trim()||"meta-llama/Llama-3.3-70B-Instruct-Turbo",wt(n),tt({name:"Together",apiUrl:"https://api.together.xyz/v1",apiKey:r.trim(),models:["meta-llama/Llama-3.3-70B-Instruct-Turbo","Qwen/Qwen2.5-72B-Instruct-Turbo","deepseek-ai/DeepSeek-R1"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${pt} \u2713 Configured for Together AI${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"f":{let r=await be(e,` ${W}DeepSeek API Key:${M} `);if(!r.trim()){console.log(`${kt} \u26A0 No key provided \u2014 cancelled${M}`);break}let i=await be(e,` ${W}Model [deepseek-chat]:${M} `);n.provider="custom",n.apiUrl="https://api.deepseek.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"deepseek-chat",wt(n),tt({name:"DeepSeek",apiUrl:"https://api.deepseek.com/v1",apiKey:r.trim(),models:["deepseek-chat","deepseek-coder","deepseek-reasoner"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${pt} \u2713 Configured for DeepSeek${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"g":{let r=await be(e,` ${W}Provider name:${M} `);if(!r.trim()){console.log(`${kt} \u26A0 Cancelled${M}`);break}let i=await be(e,` ${W}API base URL:${M} `);if(!i.trim()){console.log(`${kt} \u26A0 URL is required \u2014 cancelled${M}`);break}let o=await be(e,` ${W}API Key (leave empty if none):${M} `),a=await be(e,` ${W}Default model ID:${M} `);n.provider="custom",n.apiUrl=i.trim(),n.apiKey=o.trim(),n.model=a.trim()||"default",wt(n),tt({name:r.trim(),apiUrl:i.trim(),apiKey:o.trim(),models:[n.model],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${pt} \u2713 Configured for ${r.trim()}${M}`),console.log(`${W} URL: ${i.trim()}${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"h":{let r=await be(e,` ${W}NVIDIA API Key (nvapi-...):${M} `);if(!r.trim()){console.log(`${kt} \u26A0 No key provided \u2014 cancelled${M}`),console.log(`${W} Get your key at: https://build.nvidia.com/${M}`);break}let{NVIDIA_PROVIDER:i}=await Promise.resolve().then(()=>(Nn(),dc));console.log(),console.log(`${W} Available NVIDIA models:${M}`),i.models.forEach((u,d)=>{console.log(` ${ye}${d+1}${M}. ${u}`)}),console.log();let o=await be(e,` ${W}Model number [1]:${M} `),a=parseInt(o.trim())-1,l=i.models[a]||i.defaultModel;n.provider="nvidia",n.apiUrl=i.apiUrl,n.apiKey=r.trim(),n.model=l,wt(n),tt({name:"NVIDIA",apiUrl:i.apiUrl,apiKey:r.trim(),models:i.models,defaultModel:l,addedAt:new Date().toISOString()}),console.log(),console.log(`${pt} \u2713 Configured for NVIDIA NIM${M}`),console.log(`${W} Model: ${l}${M}`),console.log(`${W} API: ${i.apiUrl}${M}`);break}default:console.log(`${kt} \u26A0 Invalid choice${M}`)}break}default:console.log(`${kt} \u26A0 Invalid choice \u2014 please select 1 or 2${M}`)}console.log(),console.log(`${ht}${pt} \u2713 Setup complete!${M}`),console.log(),console.log(`${ht} Launch the base command, then choose mode *inside*:${M}`),console.log(),console.log(` ${ye}hablas${M} \u2192 Interactive REPL (starts in BUILD mode)`),console.log(` ${ye}hablas --auto${M} \u2192 Same, with auto-confirm for tools`),console.log(),console.log(" Inside the REPL you will see:"),console.log(` ${ht}CURRENT MODE: BUILD${M} \u2014 Full Multi-Agent Team at Maximum Power`),console.log(" (Hablas + Bob + Alex + David + Emma + rich theatre)"),console.log(),console.log(` Switch modes inside with: ${ye}/mode design${M} or ${ye}/mode ask${M}`),console.log(" Or use one-shot from terminal:"),console.log(` ${ye}hablas build "your serious task"${M} (full team, recommended)`),console.log(` ${ye}hablas design "blueprint / PRD"${M}`),console.log(` ${ye}hablas ask "quick question"${M}`),console.log(),console.log(`${W} You are always in a mode. Default = BUILD (full team). No work without mode.${M}`),console.log(),e.close()}var Og,ye,pt,kt,W,ht,M,y0,Wt,ql=L(()=>{"use strict";Og=O(require("readline"));yr();gi();ye="\x1B[36m",pt="\x1B[32m",kt="\x1B[33m",W="\x1B[2m",ht="\x1B[1m",M="\x1B[0m",y0="\x1B[35m";Wt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"}});var rt={};Ne(rt,{activeCollabManager:()=>Re,runFullTeamCommand:()=>A0,runSingleCommand:()=>$0,startRepl:()=>Gl});function S0(){return!mt.existsSync(Kl)}function Mg(){return mt.existsSync(v0)}function _0(){let n=Ft.dirname(Kl);mt.existsSync(n)||mt.mkdirSync(n,{recursive:!0}),mt.writeFileSync(Kl,new Date().toISOString(),"utf-8")}async function k0(n,e=10){let t=n.split(/(\s+)/);for(let s of t)process.stdout.write(s),await new Promise(r=>setTimeout(r,e))}async function Lg(n,e,t,s,r){let{interactive:i,autoMode:o,input:a,logger:l,abortSignal:u,onToolCall:d,skipTools:f}=r,h=r.reactEngine??ms(),m=r.errorRecovery??gs(),p=new Ge("Hablas is thinking");p.start();let g=$=>{p&&(p.stop($),p=null)},x=ig({autoMode:o,interactive:i,confirm:a?$=>a.confirm($):void 0,confirmDangerous:a?$=>a.confirmDangerous($):void 0});await Br({identity:{name:"Hablas",title:"Team Leader",role:"hablas"},client:e,registry:t,session:n,contextManager:s,reactEngine:h,errorRecovery:m,logger:l,io:{onAssistantText:async $=>{g(),console.log(mn("Hablas","Team Leader")),await k0(gn($))},onToolStart:($,A)=>{g(),console.log(uu($,A)),p=new Ge("Continuing"),p.start()},onToolEnd:($,A,y,v)=>{g(),console.log(du(A,y,v))},onNotice:($,A)=>{g(),console.log(A==="retry"?c.muted(` \u21BB ${$}`):j($))},onError:$=>{g(),$.includes("ECONNREFUSED")?console.log(Be("Connection lost","Check your provider connection or run /provider test")):/timeout/i.test($)?console.log(Be("Request timed out (120s)","The API is slow. Try again or use a faster model.")):$.includes("429")?console.log(Be("Rate limited by API","Wait a moment and try again, or switch providers.")):$.includes("model")?console.log(Be("Model error","Check model availability: /models")):console.log(Be(`Error: ${$}`,"Try again or check /status"))},onToolCall:()=>{d&&d()}},safetyPolicy:x,abortSignal:u,skipTools:f,maxIterations:w0}),g()}async function Gl(n,e){Fp();let t=n.workingDirectory==="."?process.cwd():n.workingDirectory,s=Z=>mt.existsSync(Ft.join(Z,".git"));if(!s(t)&&!n.team?.enabled)console.log(` ${c.warning("\u26A0")} ${c.secondary("Not in a Git repository. Versioning and auto-sync features are limited.")}
1291
+ ...(truncated)`,b=Math.ceil(v.length/4);u+b<=r&&(a.push({path:x,content:v,source:"imported",lineCount:100}),u+=b)}else u+A<=r&&(a.push({path:x,content:$,source:"imported",lineCount:y}),u+=A)}catch{}}}}}catch{}}}return{files:a,totalTokensEstimate:u,mentionedPaths:o}}function Ig(n){if(n.files.length===0)return"";let e=["## Referenced Files"];for(let t of n.files){let s=t.source==="imported"?" (imported)":"";e.push(`### ${t.path}${s} (${t.lineCount} lines)`),e.push("```"),e.push(t.content),e.push("```")}return e.join(`
1292
+ `)}var pt,Te,Rg,Og,Pg,Dg=L(()=>{"use strict";pt=O(require("fs")),Te=O(require("path")),Rg=/(?:^|\s|['"`])([.\w\-/\\]+\.(?:ts|js|tsx|jsx|py|go|rs|java|c|cpp|h|css|scss|html|vue|svelte|json|yaml|yml|toml|md|sql|sh|env|xml))\b/gi,Og=/(?:import\s+.*?\s+from\s+['"]([^'"]+)['"]|require\s*\(\s*['"]([^'"]+)['"]\s*\))/g,Pg=/(?:from\s+(\S+)\s+import|import\s+(\S+))/g});var Ng={};Ne(Ng,{runSetupWizard:()=>Wl});function ve(n,e){return new Promise(t=>{n.question(e,s=>t(s))})}function _0(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}async function Wl(n){let e=Lg.createInterface({input:process.stdin,output:process.stdout});switch(console.log(),console.log(`${mt}${be} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${M}`),console.log(`${mt}${be} hablas \u2014 Setup Wizard${M}`),console.log(`${W} Configure your AI provider and model${M}`),console.log(`${mt}${be} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${M}`),console.log(),console.log(`${mt} Choose your setup:${M}`),console.log(),console.log(` ${S0}${mt}1${M}. ${mt}Hablas Integrated Engine${M} ${ht}(instant \u2014 no setup needed)${M}`),console.log(` ${W}Pre-configured cloud AI, ready to use immediately${M}`),console.log(),console.log(` ${be}${mt}2${M}. ${mt}Custom Provider${M} ${W}(bring your own API key)${M}`),console.log(` ${W}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${M}`),console.log(),(await ve(e,` ${W}Your choice (1-2):${M} `)).trim()){case"1":{n.provider=Wt.provider,n.apiUrl=Wt.apiUrl,n.apiKey=_0(),n.model=Wt.model,vt(n),nt({name:Wt.name,apiUrl:Wt.apiUrl,apiKey:n.apiKey,models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.3-70b-instruct","deepseek-ai/deepseek-r1"],defaultModel:Wt.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ht} \u2713 Hablas Integrated Engine activated!${M}`),console.log(`${W} Model: ${Wt.model}${M}`),console.log(`${W} API: ${Wt.apiUrl}${M}`),console.log(`${W} No API key needed \u2014 everything is pre-configured.${M}`);break}case"2":{switch(console.log(),console.log(`${W} Select your provider:${M}`),console.log(` ${be}a${M}. Ollama (local, free, private)`),console.log(` ${be}b${M}. OpenAI API`),console.log(` ${be}c${M}. Groq (fast, free tier)`),console.log(` ${be}d${M}. OpenRouter (many models)`),console.log(` ${be}e${M}. Together AI`),console.log(` ${be}f${M}. DeepSeek`),console.log(` ${be}g${M}. Custom OpenAI-compatible API`),console.log(` ${be}h${M}. NVIDIA NIM (powerful cloud models)`),console.log(),(await ve(e,` ${W}Your choice (a-h):${M} `)).trim().toLowerCase()){case"a":{n.provider="ollama";let r=await ve(e,` ${W}Ollama host [http://localhost:11434]:${M} `);r.trim()&&(n.ollamaHost=r.trim());let i=await ve(e,` ${W}Model [qwen2.5-coder:7b]:${M} `);i.trim()&&(n.model=i.trim()),vt(n),console.log(),console.log(`${ht} \u2713 Configured for Ollama${M}`),console.log(`${W} Model: ${n.model}${M}`),console.log(`${W} Host: ${n.ollamaHost}${M}`),console.log(`${W} Make sure Ollama is running: ollama serve${M}`);break}case"b":{let r=await ve(e,` ${W}OpenAI API Key (sk-...):${M} `);if(!r.trim()){console.log(`${_t} \u26A0 No key provided \u2014 cancelled${M}`);break}let i=await ve(e,` ${W}Model [gpt-4o]:${M} `);n.provider="custom",n.apiUrl="https://api.openai.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"gpt-4o",vt(n),nt({name:"OpenAI",apiUrl:"https://api.openai.com/v1",apiKey:r.trim(),models:["gpt-4o","gpt-4o-mini","gpt-4-turbo","o1","o3-mini"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ht} \u2713 Configured for OpenAI${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"c":{let r=await ve(e,` ${W}Groq API Key (gsk_...):${M} `);if(!r.trim()){console.log(`${_t} \u26A0 No key provided \u2014 cancelled${M}`);break}let i=await ve(e,` ${W}Model [llama-3.3-70b-versatile]:${M} `);n.provider="custom",n.apiUrl="https://api.groq.com/openai/v1",n.apiKey=r.trim(),n.model=i.trim()||"llama-3.3-70b-versatile",vt(n),nt({name:"Groq",apiUrl:"https://api.groq.com/openai/v1",apiKey:r.trim(),models:["llama-3.3-70b-versatile","llama-3.1-70b-versatile","mixtral-8x7b-32768","gemma2-9b-it"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ht} \u2713 Configured for Groq${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"d":{let r=await ve(e,` ${W}OpenRouter API Key (sk-or-...):${M} `);if(!r.trim()){console.log(`${_t} \u26A0 No key provided \u2014 cancelled${M}`);break}let i=await ve(e,` ${W}Model [anthropic/claude-3.5-sonnet]:${M} `);n.provider="custom",n.apiUrl="https://openrouter.ai/api/v1",n.apiKey=r.trim(),n.model=i.trim()||"anthropic/claude-3.5-sonnet",vt(n),nt({name:"OpenRouter",apiUrl:"https://openrouter.ai/api/v1",apiKey:r.trim(),models:["openai/gpt-4o","anthropic/claude-3.5-sonnet","google/gemini-2.0-flash-001","deepseek/deepseek-r1"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ht} \u2713 Configured for OpenRouter${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"e":{let r=await ve(e,` ${W}Together API Key:${M} `);if(!r.trim()){console.log(`${_t} \u26A0 No key provided \u2014 cancelled${M}`);break}let i=await ve(e,` ${W}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${M} `);n.provider="custom",n.apiUrl="https://api.together.xyz/v1",n.apiKey=r.trim(),n.model=i.trim()||"meta-llama/Llama-3.3-70B-Instruct-Turbo",vt(n),nt({name:"Together",apiUrl:"https://api.together.xyz/v1",apiKey:r.trim(),models:["meta-llama/Llama-3.3-70B-Instruct-Turbo","Qwen/Qwen2.5-72B-Instruct-Turbo","deepseek-ai/DeepSeek-R1"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ht} \u2713 Configured for Together AI${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"f":{let r=await ve(e,` ${W}DeepSeek API Key:${M} `);if(!r.trim()){console.log(`${_t} \u26A0 No key provided \u2014 cancelled${M}`);break}let i=await ve(e,` ${W}Model [deepseek-chat]:${M} `);n.provider="custom",n.apiUrl="https://api.deepseek.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"deepseek-chat",vt(n),nt({name:"DeepSeek",apiUrl:"https://api.deepseek.com/v1",apiKey:r.trim(),models:["deepseek-chat","deepseek-coder","deepseek-reasoner"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ht} \u2713 Configured for DeepSeek${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"g":{let r=await ve(e,` ${W}Provider name:${M} `);if(!r.trim()){console.log(`${_t} \u26A0 Cancelled${M}`);break}let i=await ve(e,` ${W}API base URL:${M} `);if(!i.trim()){console.log(`${_t} \u26A0 URL is required \u2014 cancelled${M}`);break}let o=await ve(e,` ${W}API Key (leave empty if none):${M} `),a=await ve(e,` ${W}Default model ID:${M} `);n.provider="custom",n.apiUrl=i.trim(),n.apiKey=o.trim(),n.model=a.trim()||"default",vt(n),nt({name:r.trim(),apiUrl:i.trim(),apiKey:o.trim(),models:[n.model],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ht} \u2713 Configured for ${r.trim()}${M}`),console.log(`${W} URL: ${i.trim()}${M}`),console.log(`${W} Model: ${n.model}${M}`);break}case"h":{let r=await ve(e,` ${W}NVIDIA API Key (nvapi-...):${M} `);if(!r.trim()){console.log(`${_t} \u26A0 No key provided \u2014 cancelled${M}`),console.log(`${W} Get your key at: https://build.nvidia.com/${M}`);break}let{NVIDIA_PROVIDER:i}=await Promise.resolve().then(()=>(jn(),gc));console.log(),console.log(`${W} Available NVIDIA models:${M}`),i.models.forEach((u,d)=>{console.log(` ${be}${d+1}${M}. ${u}`)}),console.log();let o=await ve(e,` ${W}Model number [1]:${M} `),a=parseInt(o.trim())-1,l=i.models[a]||i.defaultModel;n.provider="nvidia",n.apiUrl=i.apiUrl,n.apiKey=r.trim(),n.model=l,vt(n),nt({name:"NVIDIA",apiUrl:i.apiUrl,apiKey:r.trim(),models:i.models,defaultModel:l,addedAt:new Date().toISOString()}),console.log(),console.log(`${ht} \u2713 Configured for NVIDIA NIM${M}`),console.log(`${W} Model: ${l}${M}`),console.log(`${W} API: ${i.apiUrl}${M}`);break}default:console.log(`${_t} \u26A0 Invalid choice${M}`)}break}default:console.log(`${_t} \u26A0 Invalid choice \u2014 please select 1 or 2${M}`)}console.log(),console.log(`${mt}${ht} \u2713 Setup complete!${M}`),console.log(),console.log(`${mt} Launch the base command, then choose mode *inside*:${M}`),console.log(),console.log(` ${be}hablas${M} \u2192 Interactive REPL (starts in BUILD mode)`),console.log(` ${be}hablas --auto${M} \u2192 Same, with auto-confirm for tools`),console.log(),console.log(" Inside the REPL you will see:"),console.log(` ${mt}CURRENT MODE: BUILD${M} \u2014 Full Multi-Agent Team at Maximum Power`),console.log(" (Hablas + Bob + Alex + David + Emma + rich theatre)"),console.log(),console.log(` Switch modes inside with: ${be}/mode design${M} or ${be}/mode ask${M}`),console.log(" Or use one-shot from terminal:"),console.log(` ${be}hablas build "your serious task"${M} (full team, recommended)`),console.log(` ${be}hablas design "blueprint / PRD"${M}`),console.log(` ${be}hablas ask "quick question"${M}`),console.log(),console.log(`${W} You are always in a mode. Default = BUILD (full team). No work without mode.${M}`),console.log(),e.close()}var Lg,be,ht,_t,W,mt,M,S0,Wt,Gl=L(()=>{"use strict";Lg=O(require("readline"));vr();vi();be="\x1B[36m",ht="\x1B[32m",_t="\x1B[33m",W="\x1B[2m",mt="\x1B[1m",M="\x1B[0m",S0="\x1B[35m";Wt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"}});var it={};Ne(it,{activeCollabManager:()=>Oe,runFullTeamCommand:()=>R0,runSingleCommand:()=>O0,startRepl:()=>Yl});function C0(){return!gt.existsSync(Vl)}function Fg(){return gt.existsSync(k0)}function E0(){let n=Nt.dirname(Vl);gt.existsSync(n)||gt.mkdirSync(n,{recursive:!0}),gt.writeFileSync(Vl,new Date().toISOString(),"utf-8")}async function T0(n,e=10){let t=n.split(/(\s+)/);for(let s of t)process.stdout.write(s),await new Promise(r=>setTimeout(r,e))}async function Bg(n,e,t,s,r){let{interactive:i,autoMode:o,input:a,logger:l,abortSignal:u,onToolCall:d,skipTools:f}=r,h=r.reactEngine??gs(),m=r.errorRecovery??ys(),p=new Ve("Hablas is thinking");p.start();let g=$=>{p&&(p.stop($),p=null)},x=ug({autoMode:o,interactive:i,confirm:a?$=>a.confirm($):void 0,confirmDangerous:a?$=>a.confirmDangerous($):void 0});await qr({identity:{name:"Hablas",title:"Team Leader",role:"hablas"},client:e,registry:t,session:n,contextManager:s,reactEngine:h,errorRecovery:m,logger:l,io:{onAssistantText:async $=>{g(),console.log(gn("Hablas","Team Leader")),await T0(yn($))},onToolStart:($,A)=>{g(),console.log(mu($,A)),p=new Ve("Continuing"),p.start()},onToolEnd:($,A,y,v)=>{g(),console.log(gu(A,y,v))},onNotice:($,A)=>{g(),console.log(A==="retry"?c.muted(` \u21BB ${$}`):j($))},onError:$=>{g(),$.includes("ECONNREFUSED")?console.log(He("Connection lost","Check your provider connection or run /provider test")):/timeout/i.test($)?console.log(He("Request timed out (120s)","The API is slow. Try again or use a faster model.")):$.includes("429")?console.log(He("Rate limited by API","Wait a moment and try again, or switch providers.")):$.includes("model")?console.log(He("Model error","Check model availability: /models")):console.log(He(`Error: ${$}`,"Try again or check /status"))},onToolCall:()=>{d&&d()}},safetyPolicy:x,abortSignal:u,skipTools:f,maxIterations:A0}),g()}async function Yl(n,e){Up();let t=n.workingDirectory==="."?process.cwd():n.workingDirectory,s=ee=>gt.existsSync(Nt.join(ee,".git"));if(!s(t)&&!n.team?.enabled)console.log(` ${c.warning("\u26A0")} ${c.secondary("Not in a Git repository. Versioning and auto-sync features are limited.")}
1229
1293
  `);else if(n.team?.enabled&&!s(t)){console.log(`
1230
1294
  ${c.accent("\u2726")} ${c.strong("Team Mode Strategy Required")}`),console.log(` ${c.muted("Collaboration requires a stable Git repository root.")}
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,Dg.execSync)("git init",{cwd:t,stdio:"ignore"}),console.log(` ${c.success("\u2713")} Git repository initialized in ${c.highlight(t)}
1232
- `)}catch{console.log(ke("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(ke(`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 Kr,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
- `)}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<x0){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
- `),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)")),(S0()||!Mg())&&(console.log(au()),console.log(""),console.log(pe("First run detected \u2014 launching setup wizard...")),console.log(""),a.close(),await Ul(n),_0(),r=Me(n),a.reinitialize()),Mg()){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(Be(`Cannot connect to ${n.apiUrl}`,"Check your --api-url and --api-key, or run /provider test")):n.provider==="nvidia"?console.log(Be("Cannot connect to NVIDIA NIM","Check your API key or run: hablas --setup")):console.log(Be("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 q=!0;for(;q;)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"){q=!1;break}continue}e.info({input:ee},"Processing user input");let X=Ec(ee),ue=Fg(X,t);if(C++,console.log(fu(C)),I=Di(I),dn(I),!G){let ne=xg(ue);if(ne){console.log(gu(ne));let U=await a.prompt(` ${c.muted("\u203A")} `),Pe=Sg(U,ne);ue=`${ue}
1236
- [Clarification: ${Pe.join(", ")}]`}}let Oe=Eg(ue,t,{maxFiles:8,maxTokens:6e3});if(Oe.files.length>0){let ne=Tg(Oe);T.addUserMessage(`[Auto-loaded ${Oe.files.length} file(s): ${Oe.mentionedPaths.join(", ")}]
1237
- ${ne}`,{priority:"low",tags:["auto-inject"]})}if(n.team?.enabled&&Re){let ne=n.team?.user||Re.getLocalState().my_username,U=Oe.mentionedPaths||[];if(U.length>0){let Pe=await Re.fetchLocks(),Fe=U.map(P=>Pe.find(Q=>Q.file_path===P&&Q.locked_by!==ne)).filter(P=>!!P);if(Fe.length>0){let P=Fe[0];console.log(`
1295
+ `);let ne=await new cs(t).prompt(` ${c.primary("\u203A")} Specify repo path OR type 'init' to start here: `);if(ne.trim().toLowerCase()==="init")try{(0,Hg.execSync)("git init",{cwd:t,stdio:"ignore"}),console.log(` ${c.success("\u2713")} Git repository initialized in ${c.highlight(t)}
1296
+ `)}catch{console.log(Ae("Failed to initialize Git. Please run git init manually.")),process.exit(1)}else{let X=Nt.resolve(t,ne.trim());gt.existsSync(X)&&s(X)?(t=X,n.workingDirectory=t,console.log(` ${c.success("\u2713")} Context switched to repository: ${c.highlight(t)}
1297
+ `)):(console.log(Ae(`Path "${X}" is not a valid Git repository.`)),process.exit(1))}}let r=Me(n),i=new Tn(t,n),o=new nn(n),a=new cs(t),l=wr(),u=new xr,d=new ds(t),f=new Ln(t),h=new Gr,m=new vs(n);m.setToolRegistry(i);let p=new ws,g=new ks(p,{hideActs:!0}).attach(),x=new xs(n,{tokenBudget:3e3,maxChars:400});if(m.setChannel(p),n.team?.enabled){let ee=n.team.user||"developer",ne=n.team.key||"default-key";Oe=new is(t,n,ee,ne),await Oe.init()&&console.log(` ${c.success("\u2713")} ${c.muted("[Team]")} Scoped cooperative sync initialized successfully.
1298
+ `)}let w=new Yr(t);f.init();let $=null;n.context?.hablasCoreEnabled&&($=new Vr(t),$.init());let A=await vn(t,n),y=l.getActive(),v=y?y.systemPrompt:Gn,b=wn(v,A,d,f),S=gs({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:150,minConfidence:.6}),_=ys(3),T=new sn(b,n.historySize),I=Un();I=Ni(I),fn(I);let C=0,N=0,H=Date.now(),G=n.autoMode||!1,E=0,k=new AbortController;process.on("SIGINT",()=>{let ee=Date.now();if(ee-E<$0){console.log(Qi({turns:C,duration:Date.now()-H,toolCalls:N}));let ne=Oe?Oe.shutdown():Promise.resolve();Promise.resolve(ne).finally(()=>process.exit(0)),setTimeout(()=>process.exit(0),2e3);return}E=ee,k.abort(),k=new AbortController,process.stdout.write(`
1299
+ `),console.log(j("Operation cancelled \u2014 press Ctrl+C again to exit"))});let Y=Ps(n);if(console.log(cu(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)")),(C0()||!Fg())&&(console.log(fu()),console.log(""),console.log(pe("First run detected \u2014 launching setup wizard...")),console.log(""),a.close(),await Wl(n),E0(),r=Me(n),a.reinitialize()),Fg()){let ee=new Ve("Connecting");ee.start();let ne=await r.checkConnection();if(ee.stop(ne?"ready":void 0),ne){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(uu()),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 U=!0;for(;U;)try{let ne=(await a.prompt(` ${c.primary("\u203A")} `)).trim();if(!ne)continue;if(ne.startsWith("/")){if(await Uu(ne,n,r,i,o,T,t,a,C,l,u,d,P=>{r=P},f,h,w,m)==="quit"){U=!1;break}continue}e.info({input:ne},"Processing user input");let X=Mc(ne),ue=Ug(X,t);if(C++,console.log(yu(C)),I=Fi(I),fn(I),!G){let Z=$g(ue);if(Z){console.log(xu(Z));let P=await a.prompt(` ${c.muted("\u203A")} `),K=Cg(P,Z);ue=`${ue}
1300
+ [Clarification: ${K.join(", ")}]`}}let Pe=Mg(ue,t,{maxFiles:8,maxTokens:6e3});if(Pe.files.length>0){let Z=Ig(Pe);T.addUserMessage(`[Auto-loaded ${Pe.files.length} file(s): ${Pe.mentionedPaths.join(", ")}]
1301
+ ${Z}`,{priority:"low",tags:["auto-inject"]})}if(n.team?.enabled&&Oe){let Z=n.team?.user||Oe.getLocalState().my_username,P=Pe.mentionedPaths||[];if(P.length>0){let K=await Oe.fetchLocks(),se=P.map(te=>K.find(Q=>Q.file_path===te&&Q.locked_by!==Z)).filter(te=>!!te);if(se.length>0){let te=se[0];console.log(`
1238
1302
  ${c.architect("\u25C6")} ${c.strong("@Consul")} [Coordinator] detected an active lock held by a teammate.`),console.log(`
1239
- ${c.error("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")}`),console.log(` ${c.error("\u2551")} ${c.strong("\u{1F512} FILE LOCKED BY TEAMMATE")} ${c.error("\u2551")}`),console.log(` ${c.error("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563")}`),console.log(` ${c.error("\u2551")} File ${c.highlight(P.file_path.padEnd(44))} held by ${c.strong(`@${(P.locked_by||"").padEnd(12)}`)} ${c.error("\u2551")}`),console.log(` ${c.error("\u2551")} Context: ${c.muted((P.lock_context||"\u2014").slice(0,61).padEnd(61))} ${c.error("\u2551")}`),console.log(` ${c.error("\u2551")} @Consul halted this turn to prevent a Git conflict on the shared repo. ${c.error("\u2551")}`),console.log(` ${c.error("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")}`);for(let Q of Fe)await Re.sendMessage(Q.locked_by,`@${ne} needs to edit ${Q.file_path}. Please release the lock when you can.`);console.log(` ${c.muted("@Consul notified the teammate(s). Try again once the lock is released, or coordinate directly.")}
1240
- `);continue}for(let P of U)if(!await Re.acquireLock(P,ue.slice(0,100))){console.log(`
1241
- ${c.warning("\u26A0")} ${c.strong("@Consul")}: a teammate locked ${c.highlight(P)} first. Halting to avoid a conflict.
1242
- `);continue}}Re.setActivity(ue.slice(0,80))}let _e=!0;if(m&&n.agents.enabled)try{let ne=m.channel;m.setChannel(null),console.log(` ${c.muted("\u25C9 Thinking and determining execution mode...")}`);let U=`User input: "${ue}"
1303
+ ${c.error("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")}`),console.log(` ${c.error("\u2551")} ${c.strong("\u{1F512} FILE LOCKED BY TEAMMATE")} ${c.error("\u2551")}`),console.log(` ${c.error("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563")}`),console.log(` ${c.error("\u2551")} File ${c.highlight(te.file_path.padEnd(44))} held by ${c.strong(`@${(te.locked_by||"").padEnd(12)}`)} ${c.error("\u2551")}`),console.log(` ${c.error("\u2551")} Context: ${c.muted((te.lock_context||"\u2014").slice(0,61).padEnd(61))} ${c.error("\u2551")}`),console.log(` ${c.error("\u2551")} @Consul halted this turn to prevent a Git conflict on the shared repo. ${c.error("\u2551")}`),console.log(` ${c.error("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")}`);for(let Q of se)await Oe.sendMessage(Q.locked_by,`@${Z} needs to edit ${Q.file_path}. Please release the lock when you can.`);console.log(` ${c.muted("@Consul notified the teammate(s). Try again once the lock is released, or coordinate directly.")}
1304
+ `);continue}for(let te of P)if(!await Oe.acquireLock(te,ue.slice(0,100))){console.log(`
1305
+ ${c.warning("\u26A0")} ${c.strong("@Consul")}: a teammate locked ${c.highlight(te)} first. Halting to avoid a conflict.
1306
+ `);continue}}Oe.setActivity(ue.slice(0,80))}let xe=!0,we=!1,q="",he=ue.toLowerCase(),$s=he.includes("finished")&&(he.includes("one step")||he.includes("one-step"))&&(he.includes("no ask")||he.includes("no ask me")||he.includes("just give me")||he.includes("no questions")||he.includes("deliver complete")),D=he.includes("unfinished")||he.includes("unfinshed")||he.includes("this and there")||he.includes("previous")||he.includes("continue")||he.includes("follow up")||he.includes("from the prd")||he.includes("from the previous");if($s&&(we=!0,q='[ONE-STEP FINISHED DELIVERY: Deliver the COMPLETE runnable finished web project in this SINGLE turn. NO questions, NO blockers, NO clarification requests, NO "provide answers to 7 questions". Produce ALL necessary files (PRD if missing, architecture, full src/ with React/TS/Vite, package.json, vite.config, main.tsx, components, stores, utils, etc.) ready to `npm run dev`. Use pictures from internet as specified. Make it luxury senior level. End synthesis with "Project is finished and runnable \u2014 cd into the folder and run `npm run dev`."]'),D&&(q+='[CONTINUITY MODE: This is an "unfinished project" follow-up. Re-use existing PRDs (e.g. PRD-flower-store.md, PRD-clarification.md), architecture docs (e.g. architecture/flower-store-frontend-architecture.md), and current src/ files WITHOUT restarting analysis from zero. Load and reference exact prior files via full read_file. Build incrementally on top of existing code/state. Do not create new PRD from scratch if prior exists.]'),m&&n.agents.enabled)try{let Z=m.channel;m.setChannel(null),console.log(` ${c.muted("\u25C9 Thinking and determining execution mode...")}`);let P=`User input: "${ue}"
1243
1307
 
1244
- Decide the professional routing for this engineering interaction.`,Pe=await m.runAgent("gate",U,void 0,i.getOllamaTools(),{abortSignal:k?.signal});if(ne&&m.setChannel(ne),Pe.success&&Pe.output){let Fe=Pe.output.toLowerCase();Fe.includes("mode: casual")||Fe.includes("casual")?_e=!1:(Fe.includes("mode: build")||Fe.includes("build")||Fe.includes("mode: design"))&&(_e=!0)}}catch{_e=!0}if(_e){let ne=["hablas","bob","alex","david","emma"];for(let K of ne)I=Fi(I,K);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},Pe=i.getOllamaTools(),Fe=new xs(p,m,x,n),P=[],Q="The team operation completed.",D=!1;try{let K=await Fe.run(ue,U,Pe,{abortSignal:k?.signal,peerReview:!0,centralizedToLeader:!0});P=K.results||[],Q=K.finalSynthesis||Q,D=!!K.synthesisOk}catch(K){let ie=K?.message||String(K);ie.includes("Aborted")||K?.name==="AbortError"?(console.log(` ${c.warning("Operation aborted.")}`),Q="Team operation was aborted. Provide more details or try a focused request."):(console.log(ke(`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 Ig(n,t);continue}else T.addUserMessage(ue);k=new AbortController,S.startTurn(),_.resetTurn(),await Lg(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 Ig(n,t)}catch(Z){if(Z.code==="ERR_USE_AFTER_CLOSE")break;if(Z.name==="AbortError")continue;console.log(ke(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 A0(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(`
1308
+ Decide the professional routing for this engineering interaction.`,K=await m.runAgent("gate",P,void 0,i.getOllamaTools(),{abortSignal:k?.signal});if(Z&&m.setChannel(Z),K.success&&K.output){let te=K.output.toLowerCase().match(/mode:\s*(casual|build|design|ask)/i),Q=te?te[1].toLowerCase():null;Q==="casual"?xe=!1:Q==="build"||Q==="design"?xe=!0:Q==="ask"&&(xe=!1)}}catch{xe=!0}if(($s||D)&&(xe=!0),xe){let Z=["hablas","bob","alex","david","emma"];for(let kt of Z)I=Hi(I,kt);fn(I),p.reset(),x.resetBudget();let P=`Analyze the request from product/requirements perspective. ${q||""} ${we?"Deliver complete spec without any open questions or blockers.":""}`,K=`Provide architecture, design or structural guidance. ${q||""}`,se=`Execute the core implementation, coding or action based on the input. ${q||""} ${we?"Produce ALL files for a complete runnable project in this turn. No partials.":""}`,te=`Research, data analysis or supporting information. ${q||""}`,Q={id:"build-"+Date.now(),description:ue.substring(0,100),tasks:[{role:"emma",description:P},{role:"bob",description:K},{role:"alex",description:se},{role:"david",description:te}],strategy:"mixed",createdAt:new Date,approved:!0},Ke=i.getOllamaTools(),We=new Ss(p,m,x,n),Zl=[],Gt="The team operation completed.",Qr=!1;try{let kt=await We.run(ue,Q,Ke,{abortSignal:k?.signal,peerReview:!0,centralizedToLeader:!0});Zl=kt.results||[],Gt=kt.finalSynthesis||Gt,Qr=!!kt.synthesisOk}catch(kt){let ec=kt?.message||String(kt);ec.includes("Aborted")||kt?.name==="AbortError"?(console.log(` ${c.warning("Operation aborted.")}`),Gt="Team operation was aborted. Provide more details or try a focused request."):(console.log(Ae(`Team error: ${ec}`)),Gt="The team encountered an error during execution. Please review logs and retry."),Qr=!1}console.log(gn("Hablas","Team Leader")),console.log(yn(Gt)),T.addAssistantMessage(Qr?Gt:`[Team Summary]
1309
+ `+Gt),await jg(n,t);continue}else T.addUserMessage(ue);k=new AbortController,S.startTurn(),_.resetTurn(),await Bg(T,r,i,o,{interactive:!0,autoMode:G,input:a,logger:e,config:n,abortSignal:k.signal,reactEngine:S,errorRecovery:_,skipTools:!1,onToolCall:()=>{N++,I=ji(I,"tool_call"),fn(I)}}),await jg(n,t)}catch(ee){if(ee.code==="ERR_USE_AFTER_CLOSE")break;if(ee.name==="AbortError")continue;console.log(Ae(ee.message)),e.error(ee,"REPL error")}a.close(),Oe&&await Oe.shutdown(),console.log(Qi({turns:C,duration:Date.now()-H,toolCalls:N}))}async function R0(n,e,t,s="build"){let r=e.workingDirectory==="."?process.cwd():e.workingDirectory;e.agents.enabled=!0;let i=Me(e),o=new Tn(r,e),a=new vs(e);a.setToolRegistry(o);let l=new ws,u=new ks(l,{hideActs:!0}).attach(),d=new xs(e,{tokenBudget:3e3,maxChars:400});a.setChannel(l),l.onEvent(w=>{w.type==="phase"?console.log(`
1246
1310
  ${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
- ${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
- ${mn("Hablas","Team Leader")}`),console.log(gn(g||"Team completed the task.")),console.log(`
1249
- ${c.muted("Full team execution complete. "+(x?"Synthesis OK.":"Used fallback summary."))}`)}async function $0(n,e,t){let s=e.workingDirectory==="."?process.cwd():e.workingDirectory,r=Me(e),i=new En(s,e),o=new tn(e),a=new us(s),l=await bn(s,e),u=vn(Wn,l,a),d=new nn(u,e.historySize),f=Fg(n,s);d.addUserMessage(f),await Lg(d,r,i,o,{interactive:!1,autoMode:e.autoMode||!1,logger:t,config:e})}function Fg(n,e){let t=/#([\w./-]+)/g,s=n,r;for(;(r=t.exec(n))!==null;){let i=r[1],o=Ft.resolve(e,i);mt.existsSync(o)&&(s=s.replace(`#${i}`,i))}return s}async function Ig(n,e){if(!(n.team?.enabled&&Re))return;if(await Re.releaseAllMyLocks(),!n.workspace?.autoPush){console.log(`
1311
+ ${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 Ss(l,a,d,e),{results:p,finalSynthesis:g,synthesisOk:x}=await m.run(n,f,h,{peerReview:!0,centralizedToLeader:!0});console.log(`
1312
+ ${gn("Hablas","Team Leader")}`),console.log(yn(g||"Team completed the task.")),console.log(`
1313
+ ${c.muted("Full team execution complete. "+(x?"Synthesis OK.":"Used fallback summary."))}`)}async function O0(n,e,t){let s=e.workingDirectory==="."?process.cwd():e.workingDirectory,r=Me(e),i=new Tn(s,e),o=new nn(e),a=new ds(s),l=await vn(s,e),u=wn(Gn,l,a),d=new sn(u,e.historySize),f=Ug(n,s);d.addUserMessage(f),await Bg(d,r,i,o,{interactive:!1,autoMode:e.autoMode||!1,logger:t,config:e})}function Ug(n,e){let t=/#([\w./-]+)/g,s=n,r;for(;(r=t.exec(n))!==null;){let i=r[1],o=Nt.resolve(e,i);gt.existsSync(o)&&(s=s.replace(`#${i}`,i))}return s}async function jg(n,e){if(!(n.team?.enabled&&Oe))return;if(await Oe.releaseAllMyLocks(),!n.workspace?.autoPush){console.log(`
1250
1314
  ${c.info("\u2139")} ${c.strong("@Consul")}: "Changes tracked. Auto-push is off \u2014 commit & push manually when ready."
1251
1315
  `);return}let{execSync:t}=await import("child_process"),s=r=>t(r,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim();try{if(!s("git status --porcelain")){console.log(`
1252
1316
  ${c.muted("@Consul: workspace clean \u2014 nothing to push.")}
@@ -1257,16 +1321,16 @@ ${mn("Hablas","Team Leader")}`),console.log(gn(g||"Team completed the task.")),c
1257
1321
  `),s("git add -A"),s('git commit -m "sync(team): automatic updates via @Consul" --no-verify');return}console.log(`
1258
1322
  ${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
1323
  `)}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,Dg,Ft,Wl,Re,Kl,v0,w0,x0,Ve=L(()=>{"use strict";Nu();ia();mt=O(require("fs")),Dg=require("child_process"),Ft=O(require("path")),Wl=O(require("os"));jn();Op();fa();pa();Dp();yr();Fa();Np();Bp();yi();cg();dg();fg();gg();yg();Un();Hl();bg();vg();_g();yn();kg();Rg();ql();Ml();Dl();jl();Re=null,Kl=Ft.join(Wl.homedir(),".hablas",".first_run_done"),v0=Ft.join(Wl.homedir(),".hablas","config.json"),w0=600,x0=1500});function et(n){let e=zl.join(Ng.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,Ng,Yr,Yl=L(()=>{"use strict";Vl=O(Ol()),zl=O(require("path")),Ng=O(require("os")),Yr=O(require("fs"))});var qg={};Ne(qg,{createApiServer:()=>Ug,startApiServer:()=>R0});function C0(){try{return JSON.parse(Hg.readFileSync(Bg.resolve(__dirname,"..","..","package.json"),"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function Ug(n){let e=et(n),t=T0(n);return jg.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 T0(n){return[{method:"GET",path:"/api/v1/health",handler:async()=>({status:200,body:{status:"ok",version:E0,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 R0(n){return new Promise((e,t)=>{let s=Ug(n);s.on("error",t),s.listen(n.api.port,n.api.host,()=>{e(s)})})}var jg,Hg,Bg,E0,Kg=L(()=>{"use strict";jg=O(require("http")),Hg=O(require("fs")),Bg=O(require("path"));Yl();E0=C0()});var P0={};Ne(P0,{CLI_VERSION:()=>ks});module.exports=Qg(P0);var cc=O(lc(),1),{program:B0,createCommand:U0,createArgument:q0,createOption:K0,CommanderError:W0,InvalidArgumentError:G0,InvalidOptionArgumentError:V0,Command:uc,Argument:z0,Option:Y0,Help:J0}=cc.default;Ve();yr();Yl();var Wg=O(require("fs")),Gg=O(require("path"));function O0(){try{let n=Gg.resolve(__dirname,"..","package.json");return JSON.parse(Wg.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}var ks=O0(),te=new uc;te.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");te.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=te.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")});te.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=te.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")});te.command("ask <question>").description("Quick solo ask (minimal team, fast response, no full theatre).").action(async n=>{let e=te.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)});te.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=te.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")});te.command("commit").description("Generate a smart commit message from staged changes").action(async()=>{let n=te.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(),qn)),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)});te.command("pr").description("Generate a PR description from branch commits").option("--base <branch>","Base branch","main").action(async n=>{let e=te.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(),qn)),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)});te.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=te.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(),qn)),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)});te.command("security").description("Run security scan on the project").option("--fix","Auto-fix issues where possible").action(async n=>{let e=te.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(`
1324
+ `)}}var gt,Hg,Nt,zl,Oe,Vl,k0,A0,$0,ze=L(()=>{"use strict";qu();la();gt=O(require("fs")),Hg=require("child_process"),Nt=O(require("path")),zl=O(require("os"));Hn();Lp();ma();ga();Hp();vr();Ha();qp();Gp();wi();hg();gg();yg();xg();Sg();qn();ql();_g();kg();Eg();bn();Tg();Dg();Gl();Ll();Fl();Ul();Oe=null,Vl=Nt.join(zl.homedir(),".hablas",".first_run_done"),k0=Nt.join(zl.homedir(),".hablas","config.json"),A0=600,$0=1500});function tt(n){let e=Xl.join(qg.homedir(),".hablas","logs");Xr.existsSync(e)||Xr.mkdirSync(e,{recursive:!0});let t=Xl.join(e,`session-${Date.now()}.log`);return(0,Jl.default)({level:"info"},Jl.default.destination({dest:t,sync:!1}))}var Jl,Xl,qg,Xr,Ql=L(()=>{"use strict";Jl=O(Il()),Xl=O(require("path")),qg=O(require("os")),Xr=O(require("fs"))});var zg={};Ne(zg,{createApiServer:()=>Vg,startApiServer:()=>D0});function P0(){try{return JSON.parse(Wg.readFileSync(Gg.resolve(__dirname,"..","..","package.json"),"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function Vg(n){let e=tt(n),t=I0(n);return Kg.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 I0(n){return[{method:"GET",path:"/api/v1/health",handler:async()=>({status:200,body:{status:"ok",version:M0,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 D0(n){return new Promise((e,t)=>{let s=Vg(n);s.on("error",t),s.listen(n.api.port,n.api.host,()=>{e(s)})})}var Kg,Wg,Gg,M0,Yg=L(()=>{"use strict";Kg=O(require("http")),Wg=O(require("fs")),Gg=O(require("path"));Ql();M0=P0()});var N0={};Ne(N0,{CLI_VERSION:()=>As});module.exports=sy(N0);var hc=O(pc(),1),{program:G0,createCommand:V0,createArgument:z0,createOption:Y0,CommanderError:J0,InvalidArgumentError:X0,InvalidOptionArgumentError:Q0,Command:mc,Argument:Z0,Option:eC,Help:tC}=hc.default;ze();vr();Ql();var Jg=O(require("fs")),Xg=O(require("path"));function L0(){try{let n=Xg.resolve(__dirname,"..","package.json");return JSON.parse(Jg.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}var As=L0(),re=new mc;re.name("hablas").description(`hablas CLI v${As} by Abdulmoin Hablas \u2014 Multi-agent AI development system. Local-first via Ollama, NVIDIA NIM, or any OpenAI-compatible API.`).version(As).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");re.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=re.opts(),t=Re({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=tt(t),{runFullTeamCommand:r}=await Promise.resolve().then(()=>(ze(),it));await r(n,t,s,"build")});re.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=re.opts(),t=Re({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=tt(t),{runFullTeamCommand:r}=await Promise.resolve().then(()=>(ze(),it));await r(n,t,s,"design")});re.command("ask <question>").description("Quick solo ask (minimal team, fast response, no full theatre).").action(async n=>{let e=re.opts(),t=Re({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=tt(t),{runSingleCommand:r}=await Promise.resolve().then(()=>(ze(),it));await r(n,t,s)});re.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=re.opts(),s=Re({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=tt(s),{runFullTeamCommand:i}=await Promise.resolve().then(()=>(ze(),it)),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")});re.command("commit").description("Generate a smart commit message from staged changes").action(async()=>{let n=re.opts(),e=Re({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),t=tt(e),{getGitStatus:s,getDetailedDiff:r,generateCommitPrompt:i}=await Promise.resolve().then(()=>(hn(),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(()=>(ze(),it));await d(u,e,t)});re.command("pr").description("Generate a PR description from branch commits").option("--base <branch>","Base branch","main").action(async n=>{let e=re.opts(),t=Re({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=tt(t),{getGitStatus:r,getRecentCommits:i,generatePRPrompt:o}=await Promise.resolve().then(()=>(hn(),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(()=>(ze(),it));await f(d,t,s)});re.command("changelog").description("Generate changelog from recent commits").option("--version <ver>","Version number",As).option("-n, --count <n>","Number of commits to include","30").action(async n=>{let e=re.opts(),t=Re({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=tt(t),{getRecentCommits:r,generateChangelogPrompt:i}=await Promise.resolve().then(()=>(hn(),Kn)),o=t.workingDirectory||process.cwd(),a=await r(o,parseInt(n.count)),l=i(a,n.version),{runSingleCommand:u}=await Promise.resolve().then(()=>(ze(),it));await u(l,t,s)});re.command("security").description("Run security scan on the project").option("--fix","Auto-fix issues where possible").action(async n=>{let e=re.opts(),t=Re({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(()=>(Ki(),Vc)),i=t.workingDirectory||process.cwd();console.log(`
1261
1325
  \u{1F512} Running security scan...
1262
- `);let o=s(i);console.log(r(o))});te.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))});te.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=te.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(`
1326
+ `);let o=s(i);console.log(r(o))});re.command("stats").description("Show developer analytics and usage statistics").action(async()=>{let{loadStats:n,formatStats:e}=await Promise.resolve().then(()=>(qn(),Bi)),t=n();console.log(e(t))});re.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=re.opts(),t=Re({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(()=>(la(),Vf)),l=t.workingDirectory||process.cwd();if(n.init)r(l,n.init),console.log(`
1263
1327
  \u2713 Team "${n.init}" initialized.`),console.log(` Config saved to: .hablas/team.json
1264
- `);else if(n.add){let u=s(l);if(!u){console.log(" \u26A0 No team config found. Run `hablas team --init <name>` first.");return}let d=i(u,n.add.split("@")[0],n.add);o(l,d),console.log(` \u2713 Added ${n.add} to team.`)}else{let u=s(l);if(!u){console.log(" No team config found. Run `hablas team --init <name>` to create one.");return}console.log(a(u))}});te.command("info").description("Show workspace information and detected configuration").action(async()=>{let n=te.opts(),e=Te({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),{scanWorkspace:t,formatWorkspaceInfo:s}=await Promise.resolve().then(()=>(Ki(),Yc)),r=e.workingDirectory||process.cwd();console.log(`
1328
+ `);else if(n.add){let u=s(l);if(!u){console.log(" \u26A0 No team config found. Run `hablas team --init <name>` first.");return}let d=i(u,n.add.split("@")[0],n.add);o(l,d),console.log(` \u2713 Added ${n.add} to team.`)}else{let u=s(l);if(!u){console.log(" No team config found. Run `hablas team --init <name>` to create one.");return}console.log(a(u))}});re.command("info").description("Show workspace information and detected configuration").action(async()=>{let n=re.opts(),e=Re({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),{scanWorkspace:t,formatWorkspaceInfo:s}=await Promise.resolve().then(()=>(Vi(),eu)),r=e.workingDirectory||process.cwd();console.log(`
1265
1329
  \u25C6 Workspace Information
1266
- `);let i=t(r);console.log(s(i)),console.log("")});te.command("api").description("Start the REST API server").option("--port <port>","Port number","8080").option("--key <key>","API key for authentication").action(async n=>{let e=te.opts(),t=Te({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});t.api.enabled=!0,t.api.port=parseInt(n.port),n.key&&(t.api.apiKey=n.key);let{startApiServer:s}=await Promise.resolve().then(()=>(Kg(),qg));console.log(`
1267
- \u25C6 Hablas API Server v${ks}`),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Starting on port ${t.api.port}...`);try{await s(t),console.log(` \u2713 API server running at http://${t.api.host}:${t.api.port}`),console.log(" Endpoints:"),console.log(" GET /api/v1/health \u2014 Health check"),console.log(" GET /api/v1/agents \u2014 List agents"),console.log(" GET /api/v1/models \u2014 List models"),console.log(" POST /api/v1/chat \u2014 Send message"),console.log(" POST /api/v1/plan \u2014 Generate plan"),console.log(" POST /api/v1/execute \u2014 Execute command"),console.log(" GET /api/v1/stats \u2014 Usage stats"),console.log(`
1330
+ `);let i=t(r);console.log(s(i)),console.log("")});re.command("api").description("Start the REST API server").option("--port <port>","Port number","8080").option("--key <key>","API key for authentication").action(async n=>{let e=re.opts(),t=Re({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});t.api.enabled=!0,t.api.port=parseInt(n.port),n.key&&(t.api.apiKey=n.key);let{startApiServer:s}=await Promise.resolve().then(()=>(Yg(),zg));console.log(`
1331
+ \u25C6 Hablas API Server v${As}`),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Starting on port ${t.api.port}...`);try{await s(t),console.log(` \u2713 API server running at http://${t.api.host}:${t.api.port}`),console.log(" Endpoints:"),console.log(" GET /api/v1/health \u2014 Health check"),console.log(" GET /api/v1/agents \u2014 List agents"),console.log(" GET /api/v1/models \u2014 List models"),console.log(" POST /api/v1/chat \u2014 Send message"),console.log(" POST /api/v1/plan \u2014 Generate plan"),console.log(" POST /api/v1/execute \u2014 Execute command"),console.log(" GET /api/v1/stats \u2014 Usage stats"),console.log(`
1268
1332
  Press Ctrl+C to stop.
1269
- `)}catch(r){console.error(` \u2717 Failed to start API server: ${r}`)}});te.command("run <prompt>").description("Run a single command non-interactively (solo Hablas path)").action(async n=>{let e=te.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),{runSingleCommand:r}=await Promise.resolve().then(()=>(Ve(),rt));await r(n,t,s)});te.command("doctor").description("Run system diagnostics").action(async()=>{let n=te.opts(),e=Te({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),{runDiagnostics:t,renderDiagnostics:s}=await Promise.resolve().then(()=>(Ci(),Dc)),r=await t({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(s(r))});te.command("plugins").description("Manage plugins").option("--enable <name>","Enable a plugin").option("--disable <name>","Disable a plugin").option("--search <query>","Search plugin marketplace").option("--install <name>","Install a plugin from marketplace").action(async n=>{let{enablePlugin:e,disablePlugin:t,renderPlugins:s,ensurePluginsDir:r}=await Promise.resolve().then(()=>(_i(),Pc));r(),n.enable?(e(n.enable),console.log(` \u2713 Plugin "${n.enable}" enabled`)):n.disable?(t(n.disable),console.log(` \u26A0 Plugin "${n.disable}" disabled`)):n.search?(console.log(`
1333
+ `)}catch(r){console.error(` \u2717 Failed to start API server: ${r}`)}});re.command("run <prompt>").description("Run a single command non-interactively (solo Hablas path)").action(async n=>{let e=re.opts(),t=Re({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=tt(t),{runSingleCommand:r}=await Promise.resolve().then(()=>(ze(),it));await r(n,t,s)});re.command("doctor").description("Run system diagnostics").action(async()=>{let n=re.opts(),e=Re({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),{runDiagnostics:t,renderDiagnostics:s}=await Promise.resolve().then(()=>(Ri(),Hc)),r=await t({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(s(r))});re.command("plugins").description("Manage plugins").option("--enable <name>","Enable a plugin").option("--disable <name>","Disable a plugin").option("--search <query>","Search plugin marketplace").option("--install <name>","Install a plugin from marketplace").action(async n=>{let{enablePlugin:e,disablePlugin:t,renderPlugins:s,ensurePluginsDir:r}=await Promise.resolve().then(()=>($i(),Nc));r(),n.enable?(e(n.enable),console.log(` \u2713 Plugin "${n.enable}" enabled`)):n.disable?(t(n.disable),console.log(` \u26A0 Plugin "${n.disable}" disabled`)):n.search?(console.log(`
1270
1334
  \u{1F50D} Searching marketplace for "${n.search}"...`),console.log(" (Marketplace: https://registry.hablas.dev/plugins)"),console.log(`
1271
1335
  Available plugins:`),console.log(" hablas-docker \u2014 Docker integration"),console.log(" hablas-aws \u2014 AWS toolkit"),console.log(" hablas-firebase \u2014 Firebase integration"),console.log(" hablas-supabase \u2014 Supabase toolkit"),console.log(" hablas-stripe \u2014 Stripe payment integration"),console.log(`
1272
1336
  Install: hablas plugins --install <name>
@@ -1276,7 +1340,7 @@ ${mn("Hablas","Team Leader")}`),console.log(gn(g||"Team completed the task.")),c
1276
1340
  \u25C6 Installed Plugins
1277
1341
  `),console.log(s()),console.log(`
1278
1342
  Plugins directory: ~/.hablas/plugins/`),console.log(" Search: hablas plugins --search <query>"),console.log(" Install: hablas plugins --install <name>"),console.log(" Enable: hablas plugins --enable <name>"),console.log(` Disable: hablas plugins --disable <name>
1279
- `))});te.action(async()=>{let n=te.opts(),e=Te({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey,team:n.team,user:n.user,teamKey:n.teamKey});if(n.auto&&(e.autoMode=!0),n.timeout&&(e.timeout=parseInt(n.timeout,10)),n.theme&&(e.ui.theme=n.theme),n.dashboard&&(e.ui.dashboard=!0),n.setup){let{runSetupWizard:s}=await Promise.resolve().then(()=>(ql(),Pg));await s(e);return}let t=et(e);await Gl(e,t)});te.parse();0&&(module.exports={CLI_VERSION});
1343
+ `))});re.action(async()=>{let n=re.opts(),e=Re({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey,team:n.team,user:n.user,teamKey:n.teamKey});if(n.auto&&(e.autoMode=!0),n.timeout&&(e.timeout=parseInt(n.timeout,10)),n.theme&&(e.ui.theme=n.theme),n.dashboard&&(e.ui.dashboard=!0),n.setup){let{runSetupWizard:s}=await Promise.resolve().then(()=>(Gl(),Ng));await s(e);return}let t=tt(e);await Yl(e,t)});re.parse();0&&(module.exports={CLI_VERSION});
1280
1344
  /*! Bundled license information:
1281
1345
 
1282
1346
  normalize-path/index.js: