hablas-ai 1.0.6 → 1.0.7

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 +171 -169
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,47 +1,47 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var ny=Object.create;var ks=Object.defineProperty;var sy=Object.getOwnPropertyDescriptor;var ry=Object.getOwnPropertyNames;var iy=Object.getPrototypeOf,oy=Object.prototype.hasOwnProperty;var N=(n,e)=>()=>(n&&(e=n(n=0)),e);var j=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Fe=(n,e)=>{for(var t in e)ks(n,t,{get:e[t],enumerable:!0})},sc=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ry(e))!oy.call(n,r)&&r!==t&&ks(n,r,{get:()=>e[r],enumerable:!(s=sy(e,r))||s.enumerable});return n};var O=(n,e,t)=>(t=n!=null?ny(iy(n)):{},sc(e||!n||!n.__esModule?ks(t,"default",{value:n,enumerable:!0}):t,n)),ay=n=>sc(ks({},"__esModule",{value:!0}),n);var Fn=j(ri=>{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}},si=class extends $s{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ri.CommanderError=$s;ri.InvalidArgumentError=si});var Cs=j(oi=>{var{InvalidArgumentError:ly}=Fn(),ii=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 ly(`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 cy(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}oi.Argument=ii;oi.humanReadableArgName=cy});var li=j(rc=>{var{humanReadableArgName:uy}=Cs(),ai=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=>uy(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(h,g){if(g){let S=`${h.padEnd(s+o)}${g}`;return t.wrap(S,r-i,s+o)}return h}function l(h){return h.join(`
2
+ "use strict";var ry=Object.create;var ks=Object.defineProperty;var iy=Object.getOwnPropertyDescriptor;var oy=Object.getOwnPropertyNames;var ay=Object.getPrototypeOf,ly=Object.prototype.hasOwnProperty;var N=(n,e)=>()=>(n&&(e=n(n=0)),e);var j=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),je=(n,e)=>{for(var t in e)ks(n,t,{get:e[t],enumerable:!0})},rc=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of oy(e))!ly.call(n,r)&&r!==t&&ks(n,r,{get:()=>e[r],enumerable:!(s=iy(e,r))||s.enumerable});return n};var O=(n,e,t)=>(t=n!=null?ry(ay(n)):{},rc(e||!n||!n.__esModule?ks(t,"default",{value:n,enumerable:!0}):t,n)),cy=n=>rc(ks({},"__esModule",{value:!0}),n);var Fn=j(si=>{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}},ni=class extends $s{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};si.CommanderError=$s;si.InvalidArgumentError=ni});var Cs=j(ii=>{var{InvalidArgumentError:uy}=Fn(),ri=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 uy(`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 dy(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}ii.Argument=ri;ii.humanReadableArgName=dy});var ai=j(ic=>{var{humanReadableArgName:fy}=Cs(),oi=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=>fy(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(h,g){if(g){let S=`${h.padEnd(s+o)}${g}`;return t.wrap(S,r-i,s+o)}return h}function l(h){return h.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(h=>a(t.argumentTerm(h),t.argumentDescription(h)));f.length>0&&(u=u.concat(["Arguments:",l(f),""]));let p=t.visibleOptions(e).map(h=>a(t.optionTerm(h),t.optionDescription(h)));if(p.length>0&&(u=u.concat(["Options:",l(p),""])),this.showGlobalOptions){let h=t.visibleGlobalOptions(e).map(g=>a(t.optionTerm(g),t.optionDescription(g)));h.length>0&&(u=u.concat(["Global Options:",l(h),""]))}let m=t.visibleCommands(e).map(h=>a(t.subcommandTerm(h),t.subcommandDescription(h)));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),p="\\s\u200B",m=new RegExp(`
7
7
  |.{1,${a-1}}([${p}]|$)|[^${p}]+?([${p}]|$)`,"g"),h=u.match(m)||[];return l+h.map((g,S)=>g===`
8
8
  `?"":(S>0?d:"")+g.trimEnd()).join(`
9
- `)}};rc.Help=ai});var fi=j(di=>{var{InvalidArgumentError:dy}=Fn(),ci=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=py(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 dy(`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 fy(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ui=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 fy(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function py(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}}di.Option=ci;di.DualOptions=ui});var oc=j(ic=>{function hy(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 my(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=hy(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
+ `)}};ic.Help=oi});var di=j(ui=>{var{InvalidArgumentError:py}=Fn(),li=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=my(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 py(`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 hy(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ci=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 hy(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function my(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}}ui.Option=li;ui.DualOptions=ci});var ac=j(oc=>{function gy(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 yy(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=gy(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]}?)`:""}ic.suggestSimilar=my});var dc=j(uc=>{var gy=require("node:events").EventEmitter,pi=require("node:child_process"),St=require("node:path"),hi=require("node:fs"),he=require("node:process"),{Argument:yy,humanReadableArgName:by}=Cs(),{CommanderError:mi}=Fn(),{Help:vy}=li(),{Option:ac,DualOptions:wy}=fi(),{suggestSimilar:lc}=oc(),gi=class n extends gy{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=>he.stdout.write(t),writeErr:t=>he.stderr.write(t),getOutHelpWidth:()=>he.stdout.isTTY?he.stdout.columns:void 0,getErrHelpWidth:()=>he.stderr.isTTY?he.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 vy,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 yy(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 mi(e,t,s)),he.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 ac(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 ac)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){he.versions?.electron&&(t.from="electron");let r=he.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=he.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":he.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 p=St.resolve(d,f);if(hi.existsSync(p))return p;if(r.includes(St.extname(f)))return;let m=r.find(h=>hi.existsSync(`${p}${h}`));if(m)return`${p}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=hi.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=St.resolve(St.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=St.basename(this._scriptPath,St.extname(this._scriptPath));f!==this._name&&(d=i(a,`${f}-${e._name}`))}o=d||o}s=r.includes(St.extname(o));let l;he.platform!=="win32"?s?(t.unshift(o),t=cc(he.execArgv).concat(t),l=pi.spawn(he.argv[0],t,{stdio:"inherit"})):l=pi.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=cc(he.execArgv).concat(t),l=pi.spawn(he.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{he.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 mi(d,"commander.executeSubCommandAsync","(close)")):he.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",p=`'${o}' does not exist
11
+ (Did you mean ${s[0]}?)`:""}oc.suggestSimilar=yy});var fc=j(dc=>{var by=require("node:events").EventEmitter,fi=require("node:child_process"),xt=require("node:path"),pi=require("node:fs"),he=require("node:process"),{Argument:vy,humanReadableArgName:wy}=Cs(),{CommanderError:hi}=Fn(),{Help:xy}=ai(),{Option:lc,DualOptions:Sy}=di(),{suggestSimilar:cc}=ac(),mi=class n extends by{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=>he.stdout.write(t),writeErr:t=>he.stderr.write(t),getOutHelpWidth:()=>he.stdout.isTTY?he.stdout.columns:void 0,getErrHelpWidth:()=>he.stderr.isTTY?he.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 xy,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 vy(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 hi(e,t,s)),he.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 lc(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 lc)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){he.versions?.electron&&(t.from="electron");let r=he.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=he.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":he.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 p=xt.resolve(d,f);if(pi.existsSync(p))return p;if(r.includes(xt.extname(f)))return;let m=r.find(h=>pi.existsSync(`${p}${h}`));if(m)return`${p}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=pi.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=xt.resolve(xt.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=xt.basename(this._scriptPath,xt.extname(this._scriptPath));f!==this._name&&(d=i(a,`${f}-${e._name}`))}o=d||o}s=r.includes(xt.extname(o));let l;he.platform!=="win32"?s?(t.unshift(o),t=uc(he.execArgv).concat(t),l=fi.spawn(he.argv[0],t,{stdio:"inherit"})):l=fi.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=uc(he.execArgv).concat(t),l=fi.spawn(he.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{he.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 hi(d,"commander.executeSubCommandAsync","(close)")):he.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",p=`'${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(p)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)he.exit(1);else{let f=new mi(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(p)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)he.exit(1);else{let f=new hi(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 he.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()}`,he.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new wy(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=lc(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=lc(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=>by(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=St.basename(e,St.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=he.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 he.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()}`,he.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Sy(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=cc(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=cc(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=>wy(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=xt.basename(e,xt.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=he.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 cc(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})}uc.Command=gi});var mc=j(Ve=>{var{Argument:fc}=Cs(),{Command:yi}=dc(),{CommanderError:xy,InvalidArgumentError:pc}=Fn(),{Help:Sy}=li(),{Option:hc}=fi();Ve.program=new yi;Ve.createCommand=n=>new yi(n);Ve.createOption=(n,e)=>new hc(n,e);Ve.createArgument=(n,e)=>new fc(n,e);Ve.Command=yi;Ve.Option=hc;Ve.Argument=fc;Ve.Help=Sy;Ve.CommanderError=xy;Ve.InvalidArgumentError=pc;Ve.InvalidOptionArgumentError=pc});var bc={};Fe(bc,{DEFAULT_CONFIG:()=>jn,NVIDIA_PROVIDER:()=>Nt});var jn,Nt,Hn=N(()=>{"use strict";jn={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",contextBudget:32e3,streamingEnabled:!0,autoConfirmSafe:!0,autoMode:!1,workingDirectory:".",historySize:800,timeout:12e4,maxRetries:3,tools:{runCommand:{allowedCommands:[],blocklist:[],timeout:12e4}},ui:{theme:"dark",showTokenCount:!0,diffPreview:!0,compactMode:!1,dashboard:!1},cache:{enabled:!0,maxEntries:100,ttlMs:3e5},logging:{level:"info",file:!0},plugins:{enabled:!0,directory:"~/.hablas/plugins",marketplace:"https://registry.hablas.dev/plugins"},agents:{enabled:!0,orchestration:"auto",maxConcurrent:3},context:{astParsing:!0,projectGraph:!0,longTermMemory:!0,fileWatcher:!0},workspace:{frameworkDetection:!0,gitAwareness:!0,envParsing:!0,autoPush:!1},security:{scanOnCommit:!1,secretDetection:!0,dependencyAudit:!0},analytics:{enabled:!0,trackUsage:!0,weeklyReports:!1},collaboration:{enabled:!1,teamConfigPath:".hablas/team.json",sharedMemory:!1},team:{enabled:!1,user:"",key:""},api:{enabled:!1,port:8080,host:"0.0.0.0",apiKey:""},license:{tier:"free",key:""}},Nt={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.1-nemotron-70b-instruct","nvidia/nemotron-4-340b-instruct","meta/llama-3.1-405b-instruct","meta/llama-3.1-70b-instruct","meta/llama-3.1-8b-instruct","mistralai/mixtral-8x22b-instruct-v0.1","mistralai/mistral-large-latest","google/gemma-2-27b-it","microsoft/phi-3-medium-128k-instruct","deepseek-ai/deepseek-coder-33b-instruct","nvidia/llama-3.1-nemotron-51b-instruct","qwen/qwen2.5-coder-32b-instruct"]}});var Es,vc=N(()=>{"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 Sc(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 ky(n){return n.map(e=>({type:"function",function:e.function}))}function $y(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 _c(n){return new Promise(e=>setTimeout(e,n))}function Ac(n,e){return!(n.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var wc,_y,Ts,xc,Ay,Vt,bi=N(()=>{"use strict";wc=12e4,_y=6e4,Ts=3,xc=1e3,Ay=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<Ay;){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(_y)});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:Sc(e)};t.length>0&&(i.tools=ky(t),i.tool_choice="auto");let o=null;for(let a=0;a<=Ts;a++)try{let l=new AbortController,u=setTimeout(()=>l.abort(),wc),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(!Ac(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 S=xc*Math.pow(2,a);await _c(S);continue}throw o}let m=(await f.json()).choices?.[0];if(!m)throw new Error("API returned empty response");let h=m.message.tool_calls?$y(m.message.tool_calls):void 0;return{message:{role:m.message.role||"assistant",content:m.message.content||"",tool_calls:h},done:!0,done_reason:m.finish_reason}}catch(f){if(clearTimeout(u),f.name==="AbortError"&&s?.aborted)throw f;if(Ac(f)&&(o=f,a<Ts)){let p=xc*Math.pow(2,a);await _c(p);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:Sc(e),stream:!0}),signal:t||AbortSignal.timeout(wc)});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 p=f.trim();if(!(!p||p==="data: [DONE]")&&p.startsWith("data: "))try{let h=JSON.parse(p.slice(6)).choices?.[0]?.delta?.content;h&&(yield h)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}}});function je(n){if(n.provider==="nvidia"){let e={...n,provider:"custom",apiUrl:Nt.apiUrl};return new Vt(e)}return n.provider==="custom"&&n.apiUrl?new Vt(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 Bn=N(()=>{"use strict";Hn();vc();bi()});var kc=N(()=>{"use strict"});function zt(){let n={providers:[],activeProvider:null,activeModel:null};try{if(_t.existsSync(wi)){let e=_t.readFileSync(wi,"utf-8"),t=JSON.parse(e);return{...n,...t}}}catch{}return n}function Si(n){_t.existsSync(vi)||_t.mkdirSync(vi,{recursive:!0}),_t.writeFileSync(wi,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),Si(e)}function Cc(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),Si(e),!0):!1}function Ec(n){return zt().providers.find(t=>t.name.toLowerCase()===n.toLowerCase())}function Ps(){return zt().providers}function Tc(n,e){let t=zt(),s=t.providers.find(r=>r.name===n);s&&(t.activeProvider=n,t.activeModel=e||s.defaultModel,Si(t))}function Rc(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,xi,$c,vi,wi,_i=N(()=>{"use strict";_t=O(require("fs")),xi=O(require("path")),$c=O(require("os"));kc();vi=xi.join($c.homedir(),".hablas"),wi=xi.join(vi,"models.json")});function Ms(){try{if(At.existsSync(Os))return JSON.parse(At.readFileSync(Os,"utf-8"))}catch{}return{}}function Oc(n){let e=Is.dirname(Os);At.existsSync(e)||At.mkdirSync(e,{recursive:!0}),At.writeFileSync(Os,JSON.stringify(n,null,2),"utf-8")}function Ic(n,e){let t=Ms();t[n]=e,Oc(t)}function Mc(n){let e=Ms();return e[n]?(delete e[n],Oc(e),!0):!1}function Lc(n){let e=Ms(),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 Dc(){let n=Ms(),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 uc(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})}dc.Command=mi});var gc=j(Ve=>{var{Argument:pc}=Cs(),{Command:gi}=fc(),{CommanderError:_y,InvalidArgumentError:hc}=Fn(),{Help:Ay}=ai(),{Option:mc}=di();Ve.program=new gi;Ve.createCommand=n=>new gi(n);Ve.createOption=(n,e)=>new mc(n,e);Ve.createArgument=(n,e)=>new pc(n,e);Ve.Command=gi;Ve.Option=mc;Ve.Argument=pc;Ve.Help=Ay;Ve.CommanderError=_y;Ve.InvalidArgumentError=hc;Ve.InvalidOptionArgumentError=hc});var vc={};je(vc,{DEFAULT_CONFIG:()=>jn,NVIDIA_PROVIDER:()=>Nt});var jn,Nt,Hn=N(()=>{"use strict";jn={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",contextBudget:32e3,streamingEnabled:!0,autoConfirmSafe:!0,autoMode:!1,workingDirectory:".",historySize:800,timeout:12e4,maxRetries:3,tools:{runCommand:{allowedCommands:[],blocklist:[],timeout:12e4}},ui:{theme:"dark",showTokenCount:!0,diffPreview:!0,compactMode:!1,dashboard:!1},cache:{enabled:!0,maxEntries:100,ttlMs:3e5},logging:{level:"info",file:!0},plugins:{enabled:!0,directory:"~/.hablas/plugins",marketplace:"https://registry.hablas.dev/plugins"},agents:{enabled:!0,orchestration:"auto",maxConcurrent:3},context:{astParsing:!0,projectGraph:!0,longTermMemory:!0,fileWatcher:!0},workspace:{frameworkDetection:!0,gitAwareness:!0,envParsing:!0,autoPush:!1},security:{scanOnCommit:!1,secretDetection:!0,dependencyAudit:!0},analytics:{enabled:!0,trackUsage:!0,weeklyReports:!1},collaboration:{enabled:!1,teamConfigPath:".hablas/team.json",sharedMemory:!1},team:{enabled:!1,user:"",key:""},api:{enabled:!1,port:8080,host:"0.0.0.0",apiKey:""},license:{tier:"free",key:""}},Nt={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.1-nemotron-70b-instruct","nvidia/nemotron-4-340b-instruct","meta/llama-3.1-405b-instruct","meta/llama-3.1-70b-instruct","meta/llama-3.1-8b-instruct","mistralai/mixtral-8x22b-instruct-v0.1","mistralai/mistral-large-latest","google/gemma-2-27b-it","microsoft/phi-3-medium-128k-instruct","deepseek-ai/deepseek-coder-33b-instruct","nvidia/llama-3.1-nemotron-51b-instruct","qwen/qwen2.5-coder-32b-instruct"]}});var Es,wc=N(()=>{"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 _c(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 Cy(n){return n.map(e=>({type:"function",function:e.function}))}function Ey(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 Ac(n){return new Promise(e=>setTimeout(e,n))}function kc(n,e){return!(n.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var xc,ky,Ts,Sc,$y,Vt,yi=N(()=>{"use strict";xc=12e4,ky=6e4,Ts=3,Sc=1e3,$y=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<$y;){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(ky)});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:_c(e)};t.length>0&&(i.tools=Cy(t),i.tool_choice="auto");let o=null;for(let a=0;a<=Ts;a++)try{let l=new AbortController,u=setTimeout(()=>l.abort(),xc),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(!kc(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 S=Sc*Math.pow(2,a);await Ac(S);continue}throw o}let m=(await f.json()).choices?.[0];if(!m)throw new Error("API returned empty response");let h=m.message.tool_calls?Ey(m.message.tool_calls):void 0;return{message:{role:m.message.role||"assistant",content:m.message.content||"",tool_calls:h},done:!0,done_reason:m.finish_reason}}catch(f){if(clearTimeout(u),f.name==="AbortError"&&s?.aborted)throw f;if(kc(f)&&(o=f,a<Ts)){let p=Sc*Math.pow(2,a);await Ac(p);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:_c(e),stream:!0}),signal:t||AbortSignal.timeout(xc)});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 p=f.trim();if(!(!p||p==="data: [DONE]")&&p.startsWith("data: "))try{let h=JSON.parse(p.slice(6)).choices?.[0]?.delta?.content;h&&(yield h)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}}});function He(n){if(n.provider==="nvidia"){let e={...n,provider:"custom",apiUrl:Nt.apiUrl};return new Vt(e)}return n.provider==="custom"&&n.apiUrl?new Vt(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 Bn=N(()=>{"use strict";Hn();wc();yi()});var $c=N(()=>{"use strict"});function zt(){let n={providers:[],activeProvider:null,activeModel:null};try{if(St.existsSync(vi)){let e=St.readFileSync(vi,"utf-8"),t=JSON.parse(e);return{...n,...t}}}catch{}return n}function xi(n){St.existsSync(bi)||St.mkdirSync(bi,{recursive:!0}),St.writeFileSync(vi,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),xi(e)}function Ec(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),xi(e),!0):!1}function Tc(n){return zt().providers.find(t=>t.name.toLowerCase()===n.toLowerCase())}function Ps(){return zt().providers}function Rc(n,e){let t=zt(),s=t.providers.find(r=>r.name===n);s&&(t.activeProvider=n,t.activeModel=e||s.defaultModel,xi(t))}function Pc(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 St,wi,Cc,bi,vi,Si=N(()=>{"use strict";St=O(require("fs")),wi=O(require("path")),Cc=O(require("os"));$c();bi=wi.join(Cc.homedir(),".hablas"),vi=wi.join(bi,"models.json")});function Ms(){try{if(_t.existsSync(Os))return JSON.parse(_t.readFileSync(Os,"utf-8"))}catch{}return{}}function Ic(n){let e=Is.dirname(Os);_t.existsSync(e)||_t.mkdirSync(e,{recursive:!0}),_t.writeFileSync(Os,JSON.stringify(n,null,2),"utf-8")}function Mc(n,e){let t=Ms();t[n]=e,Ic(t)}function Lc(n){let e=Ms();return e[n]?(delete e[n],Ic(e),!0):!1}function Dc(n){let e=Ms(),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 Nc(){let n=Ms(),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 At,Is,Pc,Os,Ai=N(()=>{"use strict";At=O(require("fs")),Is=O(require("path")),Pc=O(require("os")),Os=Is.join(Pc.homedir(),".hablas","aliases.json")});var jc={};Fe(jc,{disablePlugin:()=>Ei,enablePlugin:()=>Ci,ensurePluginsDir:()=>Ns,listPlugins:()=>Fc,renderPlugins:()=>Ti});function $i(){try{if(He.existsSync(Ds))return JSON.parse(He.readFileSync(Ds,"utf-8"))}catch{}return{disabled:[]}}function Nc(n){let e=hn.dirname(Ds);He.existsSync(e)||He.mkdirSync(e,{recursive:!0}),He.writeFileSync(Ds,JSON.stringify(n,null,2),"utf-8")}function Ns(){He.existsSync(Ls)||He.mkdirSync(Ls,{recursive:!0})}function Fc(){Ns();let n=$i(),e=[];try{let t=He.readdirSync(Ls).filter(s=>s.endsWith(".js"));for(let s of t){let r=hn.join(Ls,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 Ci(n){let e=$i(),t=e.disabled.indexOf(n);return t!==-1?(e.disabled.splice(t,1),Nc(e),!0):!1}function Ei(n){let e=$i();return e.disabled.includes(n)?!1:(e.disabled.push(n),Nc(e),!0)}function Ti(){let n=Fc();return n.length===0?` No plugins installed.
28
+ `)}var _t,Is,Oc,Os,_i=N(()=>{"use strict";_t=O(require("fs")),Is=O(require("path")),Oc=O(require("os")),Os=Is.join(Oc.homedir(),".hablas","aliases.json")});var Hc={};je(Hc,{disablePlugin:()=>Ci,enablePlugin:()=>$i,ensurePluginsDir:()=>Ns,listPlugins:()=>jc,renderPlugins:()=>Ei});function ki(){try{if(Be.existsSync(Ds))return JSON.parse(Be.readFileSync(Ds,"utf-8"))}catch{}return{disabled:[]}}function Fc(n){let e=hn.dirname(Ds);Be.existsSync(e)||Be.mkdirSync(e,{recursive:!0}),Be.writeFileSync(Ds,JSON.stringify(n,null,2),"utf-8")}function Ns(){Be.existsSync(Ls)||Be.mkdirSync(Ls,{recursive:!0})}function jc(){Ns();let n=ki(),e=[];try{let t=Be.readdirSync(Ls).filter(s=>s.endsWith(".js"));for(let s of t){let r=hn.join(Ls,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=ki(),t=e.disabled.indexOf(n);return t!==-1?(e.disabled.splice(t,1),Fc(e),!0):!1}function Ci(n){let e=ki();return e.disabled.includes(n)?!1:(e.disabled.push(n),Fc(e),!0)}function Ei(){let n=jc();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 He,hn,ki,Ls,Ds,Ri=N(()=>{"use strict";He=O(require("fs")),hn=O(require("path")),ki=O(require("os")),Ls=hn.join(ki.homedir(),".hablas","plugins"),Ds=hn.join(ki.homedir(),".hablas","plugins.json")});var Uc={};Fe(Uc,{renderDiagnostics:()=>Ii,runDiagnostics:()=>Oi});async function Oi(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=Hc.join(st.homedir(),".hablas");if(e.push({name:"Config directory",status:Pi.existsSync(r)?"ok":"warn",message:Pi.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,Bc.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 Ii(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 Pi,Hc,st,Bc,Mi=N(()=>{"use strict";Pi=O(require("fs")),Hc=O(require("path")),st=O(require("os")),Bc=require("child_process")});function Un(n){let e=n.trim();return!!(e.length<15&&!qc.test(e)||Cy.test(e)||Ey.test(e)||Ty.test(e)||Ry.test(e))}function Fs(n){let e=n.toLowerCase(),t=["hablas"];return Un(n)||(/\b(design|architect|schema|structure|api\s*design|database\s*design|system\s*design|blueprint|uml|erd|class\s*diagram)\b/i.test(e)&&t.push("bob"),/\b(create|build|implement|write|generate|code|function|component|class|fix|bug|debug|deploy|docker|ci\/cd|test|refactor|edit|modify|update|change)\b/i.test(e)&&t.push("alex"),/\b(research|find\s+info|search\s+for|documentation|how\s+to|best\s+practice|compare|analyze|data\s+analysis|optimize|benchmark|explain\s+concept)\b/i.test(e)&&t.push("david"),/\b(prd|product\s*requirements|user\s*stories|market\s*research|competitive\s*analysis|requirements\s*document|feature\s*spec|product\s*spec|stakeholder|user\s*needs|roadmap)\b/i.test(e)&&t.push("emma"),t.length===1&&qc.test(n)&&t.push("alex")),t}function js(n,e){let t=[],s=1,r=e.includes("emma"),i=e.includes("bob"),o=e.includes("alex"),a=e.includes("david");if(r&&t.push({id:`task-${s++}`,role:"emma",agentName:"Emma",description:"Analyze requirements, create PRD, and define user stories",input:n,dependencies:[],status:"pending"}),a&&t.push({id:`task-${s++}`,role:"david",agentName:"David",description:"Research requirements, best practices, and relevant documentation",input:n,dependencies:r?[t.find(u=>u.role==="emma").id]:[],status:"pending"}),i){let u=[];a?u.push(t.find(d=>d.role==="david").id):r&&u.push(t.find(d=>d.role==="emma").id),t.push({id:`task-${s++}`,role:"bob",agentName:"Bob",description:"Design system architecture and structure",input:n,dependencies:u,status:"pending"})}if(o){let u=[];i?u.push(t.find(d=>d.role==="bob").id):a?u.push(t.find(d=>d.role==="david").id):r&&u.push(t.find(d=>d.role==="emma").id),t.push({id:`task-${s++}`,role:"alex",agentName:"Alex",description:"Implement the code based on architecture/requirements",input:n,dependencies:u,status:"pending"})}let l="sequential";return t.length>2&&t.some(u=>u.dependencies.length===0)&&(l="mixed"),{id:`plan-${Date.now()}`,description:`Orchestration plan for: ${n.substring(0,100)}`,tasks:t,strategy:l,createdAt:new Date,approved:!1}}function Li(){let n=[];for(let e of _e){let s=e.role==="hablas"?" \u2605":"";n.push(` @${e.name}${s} \u2014 ${e.title}`),n.push(` ${e.description}`)}return n.join(`
34
- `)}var _e,Cy,Ey,Ty,Ry,qc,mn=N(()=>{"use strict";_e=[{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"]}],Cy=/^(hi|hello|hey|howdy|yo|sup|hiya|good\s*(morning|afternoon|evening|night)|what'?s\s*up|greetings)\b/i,Ey=/^(مرحبا|أهلا|أهلاً|هلا|السلام\s*عليكم|وعليكم\s*السلام|كيف\s*حالك|كيفك|شلونك|صباح\s*الخير|مساء\s*الخير|شكرا|شكراً|يعطيك\s*العافية|تمام|اهلين|هلو|مرحبتين|الله\s*يسلمك|حياك|حياك\s*الله|يا\s*هلا|كيف\s*الحال|اخبارك|شخبارك)/i,Ty=/^(thanks?|thank\s*you|bye|goodbye|see\s*ya|ok(ay)?|yes|no|yep|nope|cool|nice|great|got\s*it|sure|alright|fine|good|perfect|awesome|amazing|wow|lol|haha|hmm|well|right|exactly|indeed|absolutely|of\s*course|no\s*problem|you'?re\s*welcome|np)\s*[.!?]*$/i,Ry=/^(how\s*are\s*you|what'?s\s*your\s*name|who\s*are\s*you|what\s*can\s*you\s*do|help|can\s*you\s*help|what\s*is\s*this|tell\s*me\s*about\s*yourself)\s*[?!.]*$/i,qc=/\b(create|build|implement|write|generate|code|make|develop|design|architect|setup|configure|install|deploy|fix|debug|refactor|rewrite|restructure|migrate|convert|add|remove|delete|update|change|modify|edit|move|rename|test|run|execute|analyze|research|find|search|compare|optimize|benchmark)\b/i});function qn(){try{if(gn.existsSync(Di)){let n=gn.readFileSync(Di,"utf-8"),e=JSON.parse(n);return{...Kc,...e}}}catch{}return{...Kc}}function Gc(){return Di}var gn,Ni,Wc,Di,Kc,Fi=N(()=>{"use strict";gn=O(require("fs")),Ni=O(require("path")),Wc=O(require("os")),Di=Ni.join(Wc.homedir(),".hablas","agents.json"),Kc={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}}});var Wi={};Fe(Wi,{formatStats:()=>My,loadStats:()=>Kn,saveStats:()=>$t,trackAgentUsage:()=>yn,trackFileModified:()=>Oy,trackMessage:()=>qi,trackSession:()=>Ui,trackToolCall:()=>Ki});function Kn(){try{if(kt.existsSync(Hi))return JSON.parse(kt.readFileSync(Hi,"utf-8"))}catch{}return Py()}function $t(n){try{kt.existsSync(ji)||kt.mkdirSync(ji,{recursive:!0}),kt.writeFileSync(Hi,JSON.stringify(n,null,2))}catch{}}function Py(){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 Ui(n){return n.totalSessions++,n.lastUsed=new Date().toISOString(),Iy(n),n}function qi(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 Ki(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 yn(n,e){return n.agentUsage[e]=(n.agentUsage[e]||0)+1,n}function Oy(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 Iy(n){let e=Hs(),t=zc(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 zc(new Date)}function zc(n){return n.toISOString().split("T")[0]}function My(n){let e=[];e.push(`
32
+ `)}var Be,hn,Ai,Ls,Ds,Ti=N(()=>{"use strict";Be=O(require("fs")),hn=O(require("path")),Ai=O(require("os")),Ls=hn.join(Ai.homedir(),".hablas","plugins"),Ds=hn.join(Ai.homedir(),".hablas","plugins.json")});var qc={};je(qc,{renderDiagnostics:()=>Oi,runDiagnostics:()=>Pi});async function Pi(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=Bc.join(st.homedir(),".hablas");if(e.push({name:"Config directory",status:Ri.existsSync(r)?"ok":"warn",message:Ri.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,Uc.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 Oi(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 Ri,Bc,st,Uc,Ii=N(()=>{"use strict";Ri=O(require("fs")),Bc=O(require("path")),st=O(require("os")),Uc=require("child_process")});function Un(n){let e=n.trim();return!!(e.length<15&&!Kc.test(e)||Ty.test(e)||Ry.test(e)||Py.test(e)||Oy.test(e))}function Fs(n){let e=n.toLowerCase(),t=["hablas"];return Un(n)||(/\b(design|architect|schema|structure|api\s*design|database\s*design|system\s*design|blueprint|uml|erd|class\s*diagram)\b/i.test(e)&&t.push("bob"),/\b(create|build|implement|write|generate|code|function|component|class|fix|bug|debug|deploy|docker|ci\/cd|test|refactor|edit|modify|update|change)\b/i.test(e)&&t.push("alex"),/\b(research|find\s+info|search\s+for|documentation|how\s+to|best\s+practice|compare|analyze|data\s+analysis|optimize|benchmark|explain\s+concept)\b/i.test(e)&&t.push("david"),/\b(prd|product\s*requirements|user\s*stories|market\s*research|competitive\s*analysis|requirements\s*document|feature\s*spec|product\s*spec|stakeholder|user\s*needs|roadmap)\b/i.test(e)&&t.push("emma"),t.length===1&&Kc.test(n)&&t.push("alex")),t}function js(n,e){let t=[],s=1,r=e.includes("emma"),i=e.includes("bob"),o=e.includes("alex"),a=e.includes("david");if(r&&t.push({id:`task-${s++}`,role:"emma",agentName:"Emma",description:"Analyze requirements, create PRD, and define user stories",input:n,dependencies:[],status:"pending"}),a&&t.push({id:`task-${s++}`,role:"david",agentName:"David",description:"Research requirements, best practices, and relevant documentation",input:n,dependencies:r?[t.find(u=>u.role==="emma").id]:[],status:"pending"}),i){let u=[];a?u.push(t.find(d=>d.role==="david").id):r&&u.push(t.find(d=>d.role==="emma").id),t.push({id:`task-${s++}`,role:"bob",agentName:"Bob",description:"Design system architecture and structure",input:n,dependencies:u,status:"pending"})}if(o){let u=[];i?u.push(t.find(d=>d.role==="bob").id):a?u.push(t.find(d=>d.role==="david").id):r&&u.push(t.find(d=>d.role==="emma").id),t.push({id:`task-${s++}`,role:"alex",agentName:"Alex",description:"Implement the code based on architecture/requirements",input:n,dependencies:u,status:"pending"})}let l="sequential";return t.length>2&&t.some(u=>u.dependencies.length===0)&&(l="mixed"),{id:`plan-${Date.now()}`,description:`Orchestration plan for: ${n.substring(0,100)}`,tasks:t,strategy:l,createdAt:new Date,approved:!1}}function Mi(){let n=[];for(let e of _e){let s=e.role==="hablas"?" \u2605":"";n.push(` @${e.name}${s} \u2014 ${e.title}`),n.push(` ${e.description}`)}return n.join(`
34
+ `)}var _e,Ty,Ry,Py,Oy,Kc,mn=N(()=>{"use strict";_e=[{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"]}],Ty=/^(hi|hello|hey|howdy|yo|sup|hiya|good\s*(morning|afternoon|evening|night)|what'?s\s*up|greetings)\b/i,Ry=/^(مرحبا|أهلا|أهلاً|هلا|السلام\s*عليكم|وعليكم\s*السلام|كيف\s*حالك|كيفك|شلونك|صباح\s*الخير|مساء\s*الخير|شكرا|شكراً|يعطيك\s*العافية|تمام|اهلين|هلو|مرحبتين|الله\s*يسلمك|حياك|حياك\s*الله|يا\s*هلا|كيف\s*الحال|اخبارك|شخبارك)/i,Py=/^(thanks?|thank\s*you|bye|goodbye|see\s*ya|ok(ay)?|yes|no|yep|nope|cool|nice|great|got\s*it|sure|alright|fine|good|perfect|awesome|amazing|wow|lol|haha|hmm|well|right|exactly|indeed|absolutely|of\s*course|no\s*problem|you'?re\s*welcome|np)\s*[.!?]*$/i,Oy=/^(how\s*are\s*you|what'?s\s*your\s*name|who\s*are\s*you|what\s*can\s*you\s*do|help|can\s*you\s*help|what\s*is\s*this|tell\s*me\s*about\s*yourself)\s*[?!.]*$/i,Kc=/\b(create|build|implement|write|generate|code|make|develop|design|architect|setup|configure|install|deploy|fix|debug|refactor|rewrite|restructure|migrate|convert|add|remove|delete|update|change|modify|edit|move|rename|test|run|execute|analyze|research|find|search|compare|optimize|benchmark)\b/i});function qn(){try{if(gn.existsSync(Li)){let n=gn.readFileSync(Li,"utf-8"),e=JSON.parse(n);return{...Wc,...e}}}catch{}return{...Wc}}function Vc(){return Li}var gn,Di,Gc,Li,Wc,Ni=N(()=>{"use strict";gn=O(require("fs")),Di=O(require("path")),Gc=O(require("os")),Li=Di.join(Gc.homedir(),".hablas","agents.json"),Wc={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}}});var Ki={};je(Ki,{formatStats:()=>Dy,loadStats:()=>Kn,saveStats:()=>kt,trackAgentUsage:()=>yn,trackFileModified:()=>My,trackMessage:()=>Ui,trackSession:()=>Bi,trackToolCall:()=>qi});function Kn(){try{if(At.existsSync(ji))return JSON.parse(At.readFileSync(ji,"utf-8"))}catch{}return Iy()}function kt(n){try{At.existsSync(Fi)||At.mkdirSync(Fi,{recursive:!0}),At.writeFileSync(ji,JSON.stringify(n,null,2))}catch{}}function Iy(){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 Bi(n){return n.totalSessions++,n.lastUsed=new Date().toISOString(),Ly(n),n}function Ui(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 qi(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 yn(n,e){return n.agentUsage[e]=(n.agentUsage[e]||0)+1,n}function My(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 Ly(n){let e=Hs(),t=Yc(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 Yc(new Date)}function Yc(n){return n.toISOString().split("T")[0]}function Dy(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 kt,Bi,Vc,ji,Hi,Wn=N(()=>{"use strict";kt=O(require("fs")),Bi=O(require("path")),Vc=O(require("os")),ji=Bi.join(Vc.homedir(),".hablas"),Hi=Bi.join(ji,"analytics.json")});var Jc={};Fe(Jc,{formatScanResults:()=>Vi,runSecurityScan:()=>Gi});function Fy(n,e){let t=[],s=e.split(`
37
- `);for(let{pattern:r,name:i,severity:o}of Ly){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 jy(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 Yc(n,e=[]){try{let t=Bs.readdirSync(n,{withFileTypes:!0});for(let s of t){if(Dy.has(s.name))continue;let r=Yt.join(n,s.name);if(s.isDirectory())Yc(r,e);else if(s.isFile()){let i=Yt.extname(s.name);Ny.has(i)||e.push(r)}}}catch{}return e}function Gi(n){let e=Date.now(),t=Yc(n),s=[];for(let o of t)try{let a=Bs.readFileSync(o,"utf-8"),l=Yt.relative(n,o),u=Fy(l,a);s.push(...u);let d=jy(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 Vi(n){let e=[];if(e.push(`
36
+ `)}var At,Hi,zc,Fi,ji,Wn=N(()=>{"use strict";At=O(require("fs")),Hi=O(require("path")),zc=O(require("os")),Fi=Hi.join(zc.homedir(),".hablas"),ji=Hi.join(Fi,"analytics.json")});var Xc={};je(Xc,{formatScanResults:()=>Gi,runSecurityScan:()=>Wi});function Hy(n,e){let t=[],s=e.split(`
37
+ `);for(let{pattern:r,name:i,severity:o}of Ny){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 By(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 Jc(n,e=[]){try{let t=Bs.readdirSync(n,{withFileTypes:!0});for(let s of t){if(Fy.has(s.name))continue;let r=Yt.join(n,s.name);if(s.isDirectory())Jc(r,e);else if(s.isFile()){let i=Yt.extname(s.name);jy.has(i)||e.push(r)}}}catch{}return e}function Wi(n){let e=Date.now(),t=Jc(n),s=[];for(let o of t)try{let a=Bs.readFileSync(o,"utf-8"),l=Yt.relative(n,o),u=Hy(l,a);s.push(...u);let d=By(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 Gi(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,Ly,Dy,Ny,zi=N(()=>{"use strict";Bs=O(require("fs")),Yt=O(require("path")),Ly=[{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"}],Dy=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Ny=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"])});var Gn={};Fe(Gn,{formatGitStatus:()=>Gy,generateChangelogPrompt:()=>Wy,generateCommitPrompt:()=>qy,generatePRPrompt:()=>Ky,getDetailedDiff:()=>By,getGitStatus:()=>Yi,getRecentCommits:()=>Uy,getStagedDiff:()=>Hy});async function Yi(n){try{let{stdout:e}=await bn("git branch --show-current",{cwd:n}),{stdout:t}=await bn("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 bn("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 Hy(n){try{let{stdout:e}=await bn("git diff --cached --stat",{cwd:n});return e.trim()}catch{return""}}async function By(n){try{let{stdout:e}=await bn("git diff --cached",{cwd:n,maxBuffer:1048576});return e.length>1e4?e.substring(0,1e4)+`
43
- ... (truncated)`:e.trim()}catch{return""}}async function Uy(n,e=20){try{let{stdout:t}=await bn(`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 qy(n,e){return`Based on the following git diff, generate a concise, conventional commit message.
41
+ `)}var Bs,Yt,Ny,Fy,jy,Vi=N(()=>{"use strict";Bs=O(require("fs")),Yt=O(require("path")),Ny=[{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"}],Fy=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),jy=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"])});var Gn={};je(Gn,{formatGitStatus:()=>zy,generateChangelogPrompt:()=>Vy,generateCommitPrompt:()=>Wy,generatePRPrompt:()=>Gy,getDetailedDiff:()=>qy,getGitStatus:()=>zi,getRecentCommits:()=>Ky,getStagedDiff:()=>Uy});async function zi(n){try{let{stdout:e}=await bn("git branch --show-current",{cwd:n}),{stdout:t}=await bn("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 bn("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 Uy(n){try{let{stdout:e}=await bn("git diff --cached --stat",{cwd:n});return e.trim()}catch{return""}}async function qy(n){try{let{stdout:e}=await bn("git diff --cached",{cwd:n,maxBuffer:1048576});return e.length>1e4?e.substring(0,1e4)+`
43
+ ... (truncated)`:e.trim()}catch{return""}}async function Ky(n,e=20){try{let{stdout:t}=await bn(`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 Wy(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 Ky(n,e,t){let s=n.map(r=>`- ${r.message}`).join(`
58
+ Generate ONLY the commit message, nothing else.`}function Gy(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 Wy(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 Vy(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 Gy(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 Xc,Qc,bn,vn=N(()=>{"use strict";Xc=require("child_process"),Qc=require("util"),bn=(0,Qc.promisify)(Xc.exec)});var su={};Fe(su,{detectFramework:()=>Zc,detectLanguage:()=>tu,detectPackageManager:()=>eu,formatWorkspaceInfo:()=>Ji,getGitBranch:()=>nu,scanWorkspace:()=>Us});function Zc(n){let e=Q.join(n,"package.json");if(Y.existsSync(e))try{let t=JSON.parse(Y.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(Y.existsSync(Q.join(n,"requirements.txt"))||Y.existsSync(Q.join(n,"pyproject.toml")))try{let t=Y.existsSync(Q.join(n,"requirements.txt"))?Y.readFileSync(Q.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(Y.existsSync(Q.join(n,"Cargo.toml")))try{if(Y.readFileSync(Q.join(n,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(Y.existsSync(Q.join(n,"go.mod")))try{if(Y.readFileSync(Q.join(n,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function eu(n){return Y.existsSync(Q.join(n,"pnpm-lock.yaml"))?"pnpm":Y.existsSync(Q.join(n,"yarn.lock"))?"yarn":Y.existsSync(Q.join(n,"bun.lockb"))?"bun":Y.existsSync(Q.join(n,"package-lock.json"))?"npm":Y.existsSync(Q.join(n,"Cargo.toml"))?"cargo":Y.existsSync(Q.join(n,"go.mod"))?"go":Y.existsSync(Q.join(n,"requirements.txt"))||Y.existsSync(Q.join(n,"pyproject.toml"))?"pip":"unknown"}function tu(n){return Y.existsSync(Q.join(n,"tsconfig.json"))?"TypeScript":Y.existsSync(Q.join(n,"package.json"))?"JavaScript":Y.existsSync(Q.join(n,"Cargo.toml"))?"Rust":Y.existsSync(Q.join(n,"go.mod"))?"Go":Y.existsSync(Q.join(n,"pyproject.toml"))||Y.existsSync(Q.join(n,"requirements.txt"))?"Python":"Unknown"}function nu(n){let e=Q.join(n,".git","HEAD");if(!Y.existsSync(e))return null;try{let t=Y.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=Zc(n),t=eu(n),s=tu(n),r=nu(n),i=Y.existsSync(Q.join(n,"Dockerfile"))||Y.existsSync(Q.join(n,"docker-compose.yml"))||Y.existsSync(Q.join(n,"docker-compose.yaml")),o=Y.existsSync(Q.join(n,".github","workflows"))||Y.existsSync(Q.join(n,".gitlab-ci.yml"))||Y.existsSync(Q.join(n,"Jenkinsfile")),a=Y.existsSync(Q.join(n,"__tests__"))||Y.existsSync(Q.join(n,"tests"))||Y.existsSync(Q.join(n,"test"))||Y.existsSync(Q.join(n,"spec")),l=Y.existsSync(Q.join(n,".git")),u=[],d=[".env",".env.local",".env.development",".env.production",".env.example"];for(let g of d)Y.existsSync(Q.join(n,g))&&u.push(g);let f=[],p=["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 p)Y.existsSync(Q.join(n,g))&&f.push(g);let m=[],h=["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 h)Y.existsSync(Q.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 Ji(n){let e=[` Project: ${Q.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 Y,Q,Xi=N(()=>{"use strict";Y=O(require("fs")),Q=O(require("path"))});function ru(){return`
101
+ Only include sections that have entries. Generate ONLY the changelog markdown.`}function zy(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,Zc,bn,vn=N(()=>{"use strict";Qc=require("child_process"),Zc=require("util"),bn=(0,Zc.promisify)(Qc.exec)});var ru={};je(ru,{detectFramework:()=>eu,detectLanguage:()=>nu,detectPackageManager:()=>tu,formatWorkspaceInfo:()=>Yi,getGitBranch:()=>su,scanWorkspace:()=>Us});function eu(n){let e=Q.join(n,"package.json");if(Y.existsSync(e))try{let t=JSON.parse(Y.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(Y.existsSync(Q.join(n,"requirements.txt"))||Y.existsSync(Q.join(n,"pyproject.toml")))try{let t=Y.existsSync(Q.join(n,"requirements.txt"))?Y.readFileSync(Q.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(Y.existsSync(Q.join(n,"Cargo.toml")))try{if(Y.readFileSync(Q.join(n,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(Y.existsSync(Q.join(n,"go.mod")))try{if(Y.readFileSync(Q.join(n,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function tu(n){return Y.existsSync(Q.join(n,"pnpm-lock.yaml"))?"pnpm":Y.existsSync(Q.join(n,"yarn.lock"))?"yarn":Y.existsSync(Q.join(n,"bun.lockb"))?"bun":Y.existsSync(Q.join(n,"package-lock.json"))?"npm":Y.existsSync(Q.join(n,"Cargo.toml"))?"cargo":Y.existsSync(Q.join(n,"go.mod"))?"go":Y.existsSync(Q.join(n,"requirements.txt"))||Y.existsSync(Q.join(n,"pyproject.toml"))?"pip":"unknown"}function nu(n){return Y.existsSync(Q.join(n,"tsconfig.json"))?"TypeScript":Y.existsSync(Q.join(n,"package.json"))?"JavaScript":Y.existsSync(Q.join(n,"Cargo.toml"))?"Rust":Y.existsSync(Q.join(n,"go.mod"))?"Go":Y.existsSync(Q.join(n,"pyproject.toml"))||Y.existsSync(Q.join(n,"requirements.txt"))?"Python":"Unknown"}function su(n){let e=Q.join(n,".git","HEAD");if(!Y.existsSync(e))return null;try{let t=Y.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=eu(n),t=tu(n),s=nu(n),r=su(n),i=Y.existsSync(Q.join(n,"Dockerfile"))||Y.existsSync(Q.join(n,"docker-compose.yml"))||Y.existsSync(Q.join(n,"docker-compose.yaml")),o=Y.existsSync(Q.join(n,".github","workflows"))||Y.existsSync(Q.join(n,".gitlab-ci.yml"))||Y.existsSync(Q.join(n,"Jenkinsfile")),a=Y.existsSync(Q.join(n,"__tests__"))||Y.existsSync(Q.join(n,"tests"))||Y.existsSync(Q.join(n,"test"))||Y.existsSync(Q.join(n,"spec")),l=Y.existsSync(Q.join(n,".git")),u=[],d=[".env",".env.local",".env.development",".env.production",".env.example"];for(let g of d)Y.existsSync(Q.join(n,g))&&u.push(g);let f=[],p=["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 p)Y.existsSync(Q.join(n,g))&&f.push(g);let m=[],h=["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 h)Y.existsSync(Q.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 Yi(n){let e=[` Project: ${Q.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 Y,Q,Ji=N(()=>{"use strict";Y=O(require("fs")),Q=O(require("path"))});function iu(){return`
104
104
  ## Available Tools (HEP-1 Protocol)
105
105
 
106
106
  You can execute tools by outputting a strict JSON block wrapped inside <action>...</action> tags.
@@ -181,39 +181,39 @@ You MUST NOT write any conversational text or explanation outside of these tags
181
181
  1. ONLY ONE tool execution per turn. Wait for result before calling another.
182
182
  2. The JSON block inside <action>...</action> MUST be valid JSON (use double quotes, escape newlines properly).
183
183
  3. If you have no tools to run, output your response inside <response>...</response> tags. Do NOT use <action> tags if you are answering.
184
- `.trim()}var iu=N(()=>{"use strict"});function Vy(){try{let n=lu.resolve(__dirname,"..","..","package.json");return JSON.parse(au.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function me(n,e){return uu||!wn?n:`${e}${n}\x1B[0m`}function zy(n){let e=Be();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 Yy(n,e=2){let t=Be()-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(`
185
- `)}function Jy(n){let e=Math.max(...n.map(([t])=>t.length));return n.map(([t,s])=>` ${c.muted(t.padEnd(e))} ${s}`).join(`
186
- `)}function Xy(n){if(uu||!wn)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 fu(n,e){let t=Be(),s=e?e.replace(eo.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"),p=Math.max(0,Math.floor((t-2-l.length)/2)),m=c.border("\u2551")+" ".repeat(p)+c.secondary(l)+" ".repeat(t-2-l.length-p)+c.border("\u2551"),h=Math.max(0,Math.floor((t-2-u.length)/2)),g=c.border("\u2551")+" ".repeat(h)+c.muted(u)+" ".repeat(t-2-u.length-h)+c.border("\u2551"),S=c.muted(`SYSTEM VERSION: v${cu}`),k=c.warning(`CORE MODEL: ${n}`);return["",r,f,m,u?g:"",i,` ${c.muted("\u25B8")} ${S}`,` ${c.muted("\u25B8")} ${k}`,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(`
187
- `)}function pu(){let n=Be();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(`
184
+ `.trim()}var ou=N(()=>{"use strict"});function Yy(){try{let n=cu.resolve(__dirname,"..","..","package.json");return JSON.parse(lu.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function me(n,e){return du||!wn?n:`${e}${n}\x1B[0m`}function Jy(n){let e=Ie();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 Xy(n,e=2){let t=Ie()-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(`
185
+ `)}function Qy(n){let e=Math.max(...n.map(([t])=>t.length));return n.map(([t,s])=>` ${c.muted(t.padEnd(e))} ${s}`).join(`
186
+ `)}function Zy(n){if(du||!wn)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 pu(n,e){let t=Ie(),s=e?e.replace(Zi.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"),p=Math.max(0,Math.floor((t-2-l.length)/2)),m=c.border("\u2551")+" ".repeat(p)+c.secondary(l)+" ".repeat(t-2-l.length-p)+c.border("\u2551"),h=Math.max(0,Math.floor((t-2-u.length)/2)),g=c.border("\u2551")+" ".repeat(h)+c.muted(u)+" ".repeat(t-2-u.length-h)+c.border("\u2551"),S=c.muted(`SYSTEM VERSION: v${uu}`),k=c.warning(`CORE MODEL: ${n}`);return["",r,f,m,u?g:"",i,` ${c.muted("\u25B8")} ${S}`,` ${c.muted("\u25B8")} ${k}`,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(`
187
+ `)}function hu(){let n=Ie();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(`
188
188
  `)}function Jt(n,e){return`
189
- ${(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 hu(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(`
190
- `)}function mu(){let n=Be(),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(`
191
- `)}function gu(){let n=Be();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(`
192
- `)}function yu(){return["",` ${Xy("\u25C6 hablas")} ${c.success(`v${cu}`)}`,"",` ${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(`
193
- `)}function ou(n,e){let t=Math.min(Be()-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 "),p=c.codeBlock(u);return` ${c.chrome("\u2502")} ${f}${p}`}),l=` ${c.chrome("\u2514"+"\u2500".repeat(t))}`;return[i,...a,l]}function Xt(n){let e=n.split(`
194
- `),t=[],s=!1,r="",i=[];for(let o of e){if(o.trimStart().startsWith("```")){s?(t.push(...ou(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=Qi(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]+".")} ${Qi(l[2])}`);continue}}if(!o.trim()){t.push("");continue}let a=Yy(Qi(o),2);t.push(...a.split(`
195
- `))}return s&&i.length>0&&t.push(...ou(i,r)),`
189
+ ${(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 mu(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(`
190
+ `)}function gu(){let n=Ie(),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(`
191
+ `)}function yu(){let n=Ie();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(`
192
+ `)}function bu(){return["",` ${Zy("\u25C6 hablas")} ${c.success(`v${uu}`)}`,"",` ${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(`
193
+ `)}function au(n,e){let t=Math.min(Ie()-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 "),p=c.codeBlock(u);return` ${c.chrome("\u2502")} ${f}${p}`}),l=` ${c.chrome("\u2514"+"\u2500".repeat(t))}`;return[i,...a,l]}function Xt(n){let e=n.split(`
194
+ `),t=[],s=!1,r="",i=[];for(let o of e){if(o.trimStart().startsWith("```")){s?(t.push(...au(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=Xi(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]+".")} ${Xi(l[2])}`);continue}}if(!o.trim()){t.push("");continue}let a=Xy(Xi(o),2);t.push(...a.split(`
195
+ `))}return s&&i.length>0&&t.push(...au(i,r)),`
196
196
  `+t.join(`
197
197
  `)+`
198
- `}function Qi(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 bu(n,e){let t=Be(),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`
198
+ `}function Xi(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 vu(n,e){let t=Ie(),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`
199
199
  ${r}
200
- ${i}${" ".repeat(a)} ${c.border("\u2502")}`}function vu(n,e,t){let s=Be(),r=c.muted(`${t}ms`),i="";if(n){let u=e.split(`
200
+ ${i}${" ".repeat(a)} ${c.border("\u2502")}`}function wu(n,e,t){let s=Ie(),r=c.muted(`${t}ms`),i="";if(n){let u=e.split(`
201
201
  `).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(`
202
202
  `)[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")}
203
203
  ${l}
204
- `}function to(n){let e=n.split(`
204
+ `}function eo(n){let e=n.split(`
205
205
  `),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(`
206
- `)}function wu(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`
207
- `+zy(t)+`
206
+ `)}function xu(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`
207
+ `+Jy(t)+`
208
208
  `}function Ce(n){return` ${c.error("\u2717")} ${n}`}function Ue(n,e){return` ${c.error("\u2717")} ${n}
209
- ${c.warning("\u2192")} ${c.muted(e)}`}function J(n){return` ${c.success("\u2713")} ${n}`}function le(n){return` ${c.muted(n)}`}function B(n){return` ${c.warning("\u26A0")} ${n}`}function Qy(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 xu(n){let e=Be(),t=n.connected?c.success("\u25CF connected"):c.error("\u25CB offline"),s=Qy(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(eo.homedir(),"~"))],["context",`${s} ${c.muted(`${n.cacheFiles} files \xB7 ${n.cacheTokens}/${n.budgetTokens} tokens`)}`],["turns",c.muted(String(n.turnCount))],["status",t]];return`
209
+ ${c.warning("\u2192")} ${c.muted(e)}`}function J(n){return` ${c.success("\u2713")} ${n}`}function le(n){return` ${c.muted(n)}`}function B(n){return` ${c.warning("\u26A0")} ${n}`}function eb(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 Su(n){let e=Ie(),t=n.connected?c.success("\u25CF connected"):c.error("\u25CB offline"),s=eb(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(Zi.homedir(),"~"))],["context",`${s} ${c.muted(`${n.cacheFiles} files \xB7 ${n.cacheTokens}/${n.budgetTokens} tokens`)}`],["turns",c.muted(String(n.turnCount))],["status",t]];return`
210
210
  `+c.chrome("\u256D"+"\u2500".repeat(e-2)+"\u256E")+`
211
211
  ${c.accent("\u2726")} ${c.strong("Status")}
212
212
 
213
- `+Jy(r)+`
213
+ `+Qy(r)+`
214
214
 
215
215
  `+c.chrome("\u2570"+"\u2500".repeat(e-2)+"\u256F")+`
216
- `}function Su(){let n=Be(),e=Math.max(...Zi.map(r=>r.cmd.length+(r.arg?r.arg.length+1:0))),t=Zi.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`
216
+ `}function _u(){let n=Ie(),e=Math.max(...Qi.map(r=>r.cmd.length+(r.arg?r.arg.length+1:0))),t=Qi.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`
217
217
  `+c.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E")+`
218
218
  ${c.accent("\u2726")} ${c.strong("Commands")}
219
219
 
@@ -223,14 +223,15 @@ ${l}
223
223
  `)+`
224
224
 
225
225
  `+c.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F")+`
226
- `}function no(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(`
227
- `)}function Vn(n,e){let t=Be(),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=eb[u.status](Zy[u.status]),p=(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 h=c.secondary(u.description);s.push(` ${c.chrome("\u2502")} ${d} ${c.muted(`${u.task_id}.`)} ${p} ${c.muted("\u2192")} ${h}${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(`
228
- `)}function _u(n){let e=Be(),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(`
229
- `)}var eo,au,lu,cu,wn,uu,du,Be,c,ze,Zi,Zy,eb,so,xn=N(()=>{"use strict";eo=O(require("os")),au=O(require("fs")),lu=O(require("path"));cu=Vy(),wn=process.stdout.isTTY===!0,uu=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",du=process.stdout.columns||80;wn&&process.stdout.on("resize",()=>{du=process.stdout.columns||80});Be=()=>Math.min(du-4,100);c={primary:n=>me(n,"\x1B[38;5;253m"),secondary:n=>me(n,"\x1B[38;5;247m"),muted:n=>me(n,"\x1B[38;5;242m"),strong:n=>me(n,"\x1B[1;38;5;255m"),accent:n=>me(n,"\x1B[38;5;145m"),highlight:n=>me(n,"\x1B[38;5;231m"),success:n=>me(n,"\x1B[38;5;108m"),error:n=>me(n,"\x1B[38;5;167m"),warning:n=>me(n,"\x1B[38;5;179m"),info:n=>me(n,"\x1B[38;5;110m"),codeBlock:n=>me(n,"\x1B[38;5;188m"),lineNum:n=>me(n,"\x1B[38;5;239m"),border:n=>me(n,"\x1B[38;5;237m"),chrome:n=>me(n,"\x1B[38;5;235m"),added:n=>me(n,"\x1B[38;5;108m"),removed:n=>me(n,"\x1B[38;5;167m"),hunk:n=>me(n,"\x1B[38;5;145m"),leader:n=>me(n,"\x1B[38;5;179m"),architect:n=>me(n,"\x1B[38;5;250m"),engineer:n=>me(n,"\x1B[38;5;145m"),analyst:n=>me(n,"\x1B[38;5;108m"),product:n=>me(n,"\x1B[38;5;180m")};ze=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(),!wn){process.stderr.write(` ${this.message}...
230
- `);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(wn&&process.stdout.write("\r"+" ".repeat(80)+"\r"),e&&wn){let s=c.muted(`${t}ms`);console.log(` ${c.muted("\xB7")} ${c.secondary(e)} ${s}`)}}};Zi=[{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"}];Zy={pending:"\u25CB",running:"\u25C9",done:"\u2713",failed:"\u2717",skipped:"\u2013"},eb={pending:c.muted,running:c.accent,done:c.success,failed:c.error,skipped:c.muted};so=Zi.map(n=>n.cmd).concat(["/exit","/addmodel","/listmodels","/removemodel","/usemodel","/provider","/task","/memory","/mindset","/mindsets","/alias","/doctor","/plugins","/team","/agents","/delegate"])});function ro(n){let e=rt.join(n,"package.json");if(qe.existsSync(e))try{let t=JSON.parse(qe.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(qe.existsSync(rt.join(n,"pytest.ini"))||qe.existsSync(rt.join(n,"pyproject.toml"))||qe.existsSync(rt.join(n,"setup.py")))try{let t=qe.existsSync(rt.join(n,"requirements.txt"))?qe.readFileSync(rt.join(n,"requirements.txt"),"utf-8"):"",s=qe.existsSync(rt.join(n,"pyproject.toml"))?qe.readFileSync(rt.join(n,"pyproject.toml"),"utf-8"):"";if(t.includes("pytest")||s.includes("pytest"))return"pytest"}catch{}return qe.existsSync(rt.join(n,"go.mod"))?"go":qe.existsSync(rt.join(n,"Cargo.toml"))?"cargo":"unknown"}function tb(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 ku(n,e){let t=ro(n),s=tb(t,e),r=Date.now(),i="",o="",a=!1;try{i=(0,Au.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:p}=nb(i+`
231
- `+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:p}}function nb(n,e){let t=0,s=0,r=0,i=[],o=n.split(`
232
- `);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 $u(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(`
233
- `)}function Cu(n){return`The following tests are failing. Analyze the error output and fix the code.
226
+ `}function to(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(`
227
+ `)}function Vn(n,e){let t=Ie(),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=nb[u.status](tb[u.status]),p=(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 h=c.secondary(u.description);s.push(` ${c.chrome("\u2502")} ${d} ${c.muted(`${u.task_id}.`)} ${p} ${c.muted("\u2192")} ${h}${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(`
228
+ `)}function Au(n){let e=Ie(),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(`
229
+ `)}function no(n){let e=Math.min(Ie(),80),t=[],s=`\u250C${"\u2500".repeat(e-2)}\u2510`,r=`\u251C${"\u2500".repeat(e-2)}\u2524`,i=`\u2514${"\u2500".repeat(e-2)}\u2518`;t.push(` ${c.border(s)}`);let a=`\u2605 MISSION STATUS: ${n.taskTitle}`.slice(0,e-4).padEnd(e-4);t.push(` ${c.border("\u2502")} ${c.strong(a)} ${c.border("\u2502")}`),t.push(` ${c.border(r)}`);let u=`Phase: ${n.currentPhase}`.slice(0,e-4).padEnd(e-4);t.push(` ${c.border("\u2502")} ${c.primary(u)} ${c.border("\u2502")}`);let d=[];for(let[y,v]of Object.entries(n.roster)){let b=y==="Hablas"?c.leader:y==="Bob"?c.architect:y==="Alex"?c.engineer:y==="David"?c.analyst:c.product,w="";v==="done"?w=c.success("\u2713"):v==="active"?w=c.highlight("\u25CF"):w=c.muted("\u25CB"),d.push(`@${b(y)} ${w}`)}let f=`Roster: ${d.join(" ")}`,p=f.replace(/\x1b\[[0-9;]*m/g,""),m=Math.max(0,e-4-p.length);t.push(` ${c.border("\u2502")} ${f}${" ".repeat(m)} ${c.border("\u2502")}`);let h=`Active: @${n.activeAgent} (${n.activeAgentTitle})`,g=h.replace(/\x1b\[[0-9;]*m/g,""),S=Math.max(0,e-4-g.length);t.push(` ${c.border("\u2502")} ${h}${" ".repeat(S)} ${c.border("\u2502")}`);let k=`Action: ${n.currentActivity}`,x=k.replace(/\x1b\[[0-9;]*m/g,""),A=Math.max(0,e-4-x.length);return t.push(` ${c.border("\u2502")} ${c.secondary(k)}${" ".repeat(A)} ${c.border("\u2502")}`),t.push(` ${c.border(i)}`),t.join(`
230
+ `)}var Zi,lu,cu,uu,wn,du,fu,Ie,c,ze,Qi,tb,nb,so,xn=N(()=>{"use strict";Zi=O(require("os")),lu=O(require("fs")),cu=O(require("path"));uu=Yy(),wn=process.stdout.isTTY===!0,du=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",fu=process.stdout.columns||80;wn&&process.stdout.on("resize",()=>{fu=process.stdout.columns||80});Ie=()=>Math.min(fu-4,100);c={primary:n=>me(n,"\x1B[38;5;253m"),secondary:n=>me(n,"\x1B[38;5;247m"),muted:n=>me(n,"\x1B[38;5;242m"),strong:n=>me(n,"\x1B[1;38;5;255m"),accent:n=>me(n,"\x1B[38;5;145m"),highlight:n=>me(n,"\x1B[38;5;231m"),success:n=>me(n,"\x1B[38;5;108m"),error:n=>me(n,"\x1B[38;5;167m"),warning:n=>me(n,"\x1B[38;5;179m"),info:n=>me(n,"\x1B[38;5;110m"),codeBlock:n=>me(n,"\x1B[38;5;188m"),lineNum:n=>me(n,"\x1B[38;5;239m"),border:n=>me(n,"\x1B[38;5;237m"),chrome:n=>me(n,"\x1B[38;5;235m"),added:n=>me(n,"\x1B[38;5;108m"),removed:n=>me(n,"\x1B[38;5;167m"),hunk:n=>me(n,"\x1B[38;5;145m"),leader:n=>me(n,"\x1B[38;5;179m"),architect:n=>me(n,"\x1B[38;5;250m"),engineer:n=>me(n,"\x1B[38;5;145m"),analyst:n=>me(n,"\x1B[38;5;108m"),product:n=>me(n,"\x1B[38;5;180m")};ze=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(),!wn){process.stderr.write(` ${this.message}...
231
+ `);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(wn&&process.stdout.write("\r"+" ".repeat(80)+"\r"),e&&wn){let s=c.muted(`${t}ms`);console.log(` ${c.muted("\xB7")} ${c.secondary(e)} ${s}`)}}};Qi=[{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"}];tb={pending:"\u25CB",running:"\u25C9",done:"\u2713",failed:"\u2717",skipped:"\u2013"},nb={pending:c.muted,running:c.accent,done:c.success,failed:c.error,skipped:c.muted};so=Qi.map(n=>n.cmd).concat(["/exit","/addmodel","/listmodels","/removemodel","/usemodel","/provider","/task","/memory","/mindset","/mindsets","/alias","/doctor","/plugins","/team","/agents","/delegate"])});function ro(n){let e=rt.join(n,"package.json");if(qe.existsSync(e))try{let t=JSON.parse(qe.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(qe.existsSync(rt.join(n,"pytest.ini"))||qe.existsSync(rt.join(n,"pyproject.toml"))||qe.existsSync(rt.join(n,"setup.py")))try{let t=qe.existsSync(rt.join(n,"requirements.txt"))?qe.readFileSync(rt.join(n,"requirements.txt"),"utf-8"):"",s=qe.existsSync(rt.join(n,"pyproject.toml"))?qe.readFileSync(rt.join(n,"pyproject.toml"),"utf-8"):"";if(t.includes("pytest")||s.includes("pytest"))return"pytest"}catch{}return qe.existsSync(rt.join(n,"go.mod"))?"go":qe.existsSync(rt.join(n,"Cargo.toml"))?"cargo":"unknown"}function sb(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=ro(n),s=sb(t,e),r=Date.now(),i="",o="",a=!1;try{i=(0,ku.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:p}=rb(i+`
232
+ `+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:p}}function rb(n,e){let t=0,s=0,r=0,i=[],o=n.split(`
233
+ `);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 Cu(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(`
234
+ `)}function Eu(n){return`The following tests are failing. Analyze the error output and fix the code.
234
235
 
235
236
  Test framework: ${n.framework}
236
237
  Command: ${n.command}
@@ -250,20 +251,20 @@ Instructions:
250
251
  1. Read the failing test files to understand what's expected
251
252
  2. Read the source files being tested
252
253
  3. Fix the source code (not the tests) to make them pass
253
- 4. After fixing, explain what was wrong and what you changed`}var Au,qe,rt,Eu=N(()=>{"use strict";Au=require("child_process"),qe=O(require("fs")),rt=O(require("path"))});function Ks(n){let e=Buffer.from(n).toString("base64url").slice(0,16);return Ie.join(sb,e)}async function Ru(n,e,t){let s=Ks(n);Ee.existsSync(s)||Ee.mkdirSync(s,{recursive:!0});let r=`cp_${Date.now()}`,i=[];for(let f of t){let p=Ie.resolve(n,f);if(Ee.existsSync(p))try{let m=await Ct.readFile(p,"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(`
254
- `).filter(Boolean);for(let p of f)if(!i.find(m=>m.path===p))try{let m=await Ct.readFile(Ie.resolve(n,p),"utf-8");i.push({path:p,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 Ct.writeFile(u,JSON.stringify(l,null,2),"utf-8");let d=Ee.readdirSync(s).filter(f=>f.endsWith(".json")).sort();if(d.length>20)for(let f of d.slice(0,d.length-20))try{Ee.unlinkSync(Ie.join(s,f))}catch{}return{id:r,label:e,timestamp:l.timestamp,fileCount:i.length,projectPath:n}}function Pu(n){let e=Ks(n);if(!Ee.existsSync(e))return[];let t=Ee.readdirSync(e).filter(r=>r.endsWith(".json")).sort().reverse(),s=[];for(let r of t)try{let i=JSON.parse(Ee.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 Ou(n,e){let t=Ks(n),s=Ie.join(t,`${e}.json`);if(!Ee.existsSync(s))return{success:!1,filesRestored:0,error:`Checkpoint ${e} not found`};try{let r=JSON.parse(await Ct.readFile(s,"utf-8")),i=0;for(let o of r.files)try{let a=Ie.resolve(n,o.path);await Ct.mkdir(Ie.dirname(a),{recursive:!0}),await Ct.writeFile(a,o.content,"utf-8"),i++}catch{}return{success:!0,filesRestored:i}}catch(r){return{success:!1,filesRestored:0,error:r.message}}}function Iu(n,e){let t=Ks(n),s=Ie.join(t,`${e}.json`);try{if(Ee.existsSync(s))return Ee.unlinkSync(s),!0}catch{}return!1}function Mu(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(`
255
- `)}var Ee,Ct,Ie,Tu,qs,sb,Lu=N(()=>{"use strict";Ee=O(require("fs")),Ct=O(require("fs/promises")),Ie=O(require("path")),Tu=O(require("os")),qs=require("child_process"),sb=Ie.join(Tu.homedir(),".hablas","checkpoints")});function Et(){}function rb(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 p=t.slice(u,u+f.count);p=p.map(function(g,S){var k=s[d+S];return k.length>g.length?k:g}),f.value=n.join(p)}else f.value=n.join(t.slice(u,u+f.count));u+=f.count,f.added||(d+=f.count)}}var h=i[l-1];return l>1&&typeof h.value=="string"&&(h.added||h.removed)&&n.equals("",h.value)&&(i[l-2].value+=h.value,i.pop()),i}function ib(n,e,t){return co.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 io(n){return lb(n)||cb(n)||ub(n)||db()}function lb(n){if(Array.isArray(n))return oo(n)}function cb(n){if(typeof Symbol<"u"&&Symbol.iterator in Object(n))return Array.from(n)}function ub(n,e){if(n){if(typeof n=="string")return oo(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 oo(n,e)}}function oo(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 db(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
256
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ao(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(fb.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]=ao(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]=ao(n[l],e,t,s,l);e.pop(),t.pop()}else o=n;return o}function pb(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 p=t[i];if(/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(p))break;if(/^@@/.test(p))u.hunks.push(l());else{if(p&&e.strict)throw new Error("Unknown line "+(i+1)+" "+JSON.stringify(p));i++}}}function a(u){var d=/^(---|\+\+\+)\s+/.exec(t[i]);if(d){var f=d[1]==="---"?"old":"new",p=t[i].substring(3).trim().split(" ",2),m=p[0].replace(/\\\\/g,"\\");m.startsWith('"')&&m.endsWith('"')&&(m=m.substr(1,m.length-2)),u[f+"FileName"]=m,u[f+"Header"]=(p[1]||"").trim(),i++}}function l(){var u=i,d=t[i++],f=d.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/),p={oldStart:+f[1],oldLines:typeof f[2]>"u"?1:+f[2],newStart:+f[3],newLines:typeof f[4]>"u"?1:+f[4],lines:[],linedelimiters:[]};p.oldLines===0&&(p.oldStart+=1),p.newLines===0&&(p.newStart+=1);for(var m=0,h=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==="\\")p.lines.push(t[i]),p.linedelimiters.push(s[i]||`
257
- `),g==="+"?m++:g==="-"?h++:g===" "&&(m++,h++);else break}if(!m&&p.newLines===1&&(p.newLines=0),!h&&p.oldLines===1&&(p.oldLines=0),e.strict){if(m!==p.newLines)throw new Error("Added line count did not match for hunk at line "+(u+1));if(h!==p.oldLines)throw new Error("Removed line count did not match for hunk at line "+(u+1))}return p}for(;i<t.length;)o();return r}function hb(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 ju(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(typeof e=="string"&&(e=pb(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(T,C,ne,D){return C===D},a=0,l=t.fuzzFactor||0,u=0,d=0,f,p;function m(T,C){for(var ne=0;ne<T.lines.length;ne++){var D=T.lines[ne],W=D.length>0?D[0]:" ",ie=D.length>0?D.substr(1):D;if(W===" "||W==="-"){if(!o(C+1,s[C],W,ie)&&(a++,a>l))return!1;C++}}return!0}for(var h=0;h<i.length;h++){for(var g=i[h],S=s.length-g.oldLines,k=0,x=d+g.oldStart-1,A=hb(x,u,S);k!==void 0;k=A())if(m(g,x+k)){g.offset=d+=k;break}if(k===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],w=b.oldStart+b.offset+y-1;y+=b.newLines-b.oldLines;for(var _=0;_<b.lines.length;_++){var E=b.lines[_],I=E.length>0?E[0]:" ",$=E.length>0?E.substr(1):E,F=b.linedelimiters&&b.linedelimiters[_]||`
254
+ 4. After fixing, explain what was wrong and what you changed`}var ku,qe,rt,Tu=N(()=>{"use strict";ku=require("child_process"),qe=O(require("fs")),rt=O(require("path"))});function Ks(n){let e=Buffer.from(n).toString("base64url").slice(0,16);return Me.join(ib,e)}async function Pu(n,e,t){let s=Ks(n);Ee.existsSync(s)||Ee.mkdirSync(s,{recursive:!0});let r=`cp_${Date.now()}`,i=[];for(let f of t){let p=Me.resolve(n,f);if(Ee.existsSync(p))try{let m=await $t.readFile(p,"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(`
255
+ `).filter(Boolean);for(let p of f)if(!i.find(m=>m.path===p))try{let m=await $t.readFile(Me.resolve(n,p),"utf-8");i.push({path:p,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=Me.join(s,`${r}.json`);await $t.writeFile(u,JSON.stringify(l,null,2),"utf-8");let d=Ee.readdirSync(s).filter(f=>f.endsWith(".json")).sort();if(d.length>20)for(let f of d.slice(0,d.length-20))try{Ee.unlinkSync(Me.join(s,f))}catch{}return{id:r,label:e,timestamp:l.timestamp,fileCount:i.length,projectPath:n}}function Ou(n){let e=Ks(n);if(!Ee.existsSync(e))return[];let t=Ee.readdirSync(e).filter(r=>r.endsWith(".json")).sort().reverse(),s=[];for(let r of t)try{let i=JSON.parse(Ee.readFileSync(Me.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 Iu(n,e){let t=Ks(n),s=Me.join(t,`${e}.json`);if(!Ee.existsSync(s))return{success:!1,filesRestored:0,error:`Checkpoint ${e} not found`};try{let r=JSON.parse(await $t.readFile(s,"utf-8")),i=0;for(let o of r.files)try{let a=Me.resolve(n,o.path);await $t.mkdir(Me.dirname(a),{recursive:!0}),await $t.writeFile(a,o.content,"utf-8"),i++}catch{}return{success:!0,filesRestored:i}}catch(r){return{success:!1,filesRestored:0,error:r.message}}}function Mu(n,e){let t=Ks(n),s=Me.join(t,`${e}.json`);try{if(Ee.existsSync(s))return Ee.unlinkSync(s),!0}catch{}return!1}function Lu(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(`
256
+ `)}var Ee,$t,Me,Ru,qs,ib,Du=N(()=>{"use strict";Ee=O(require("fs")),$t=O(require("fs/promises")),Me=O(require("path")),Ru=O(require("os")),qs=require("child_process"),ib=Me.join(Ru.homedir(),".hablas","checkpoints")});function Ct(){}function ob(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 p=t.slice(u,u+f.count);p=p.map(function(g,S){var k=s[d+S];return k.length>g.length?k:g}),f.value=n.join(p)}else f.value=n.join(t.slice(u,u+f.count));u+=f.count,f.added||(d+=f.count)}}var h=i[l-1];return l>1&&typeof h.value=="string"&&(h.added||h.removed)&&n.equals("",h.value)&&(i[l-2].value+=h.value,i.pop()),i}function ab(n,e,t){return co.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 io(n){return ub(n)||db(n)||fb(n)||pb()}function ub(n){if(Array.isArray(n))return oo(n)}function db(n){if(typeof Symbol<"u"&&Symbol.iterator in Object(n))return Array.from(n)}function fb(n,e){if(n){if(typeof n=="string")return oo(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 oo(n,e)}}function oo(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 pb(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
257
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ao(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(hb.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]=ao(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]=ao(n[l],e,t,s,l);e.pop(),t.pop()}else o=n;return o}function mb(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 p=t[i];if(/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(p))break;if(/^@@/.test(p))u.hunks.push(l());else{if(p&&e.strict)throw new Error("Unknown line "+(i+1)+" "+JSON.stringify(p));i++}}}function a(u){var d=/^(---|\+\+\+)\s+/.exec(t[i]);if(d){var f=d[1]==="---"?"old":"new",p=t[i].substring(3).trim().split(" ",2),m=p[0].replace(/\\\\/g,"\\");m.startsWith('"')&&m.endsWith('"')&&(m=m.substr(1,m.length-2)),u[f+"FileName"]=m,u[f+"Header"]=(p[1]||"").trim(),i++}}function l(){var u=i,d=t[i++],f=d.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/),p={oldStart:+f[1],oldLines:typeof f[2]>"u"?1:+f[2],newStart:+f[3],newLines:typeof f[4]>"u"?1:+f[4],lines:[],linedelimiters:[]};p.oldLines===0&&(p.oldStart+=1),p.newLines===0&&(p.newStart+=1);for(var m=0,h=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==="\\")p.lines.push(t[i]),p.linedelimiters.push(s[i]||`
258
+ `),g==="+"?m++:g==="-"?h++:g===" "&&(m++,h++);else break}if(!m&&p.newLines===1&&(p.newLines=0),!h&&p.oldLines===1&&(p.oldLines=0),e.strict){if(m!==p.newLines)throw new Error("Added line count did not match for hunk at line "+(u+1));if(h!==p.oldLines)throw new Error("Removed line count did not match for hunk at line "+(u+1))}return p}for(;i<t.length;)o();return r}function gb(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 Hu(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(typeof e=="string"&&(e=mb(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(T,C,ne,D){return C===D},a=0,l=t.fuzzFactor||0,u=0,d=0,f,p;function m(T,C){for(var ne=0;ne<T.lines.length;ne++){var D=T.lines[ne],W=D.length>0?D[0]:" ",ie=D.length>0?D.substr(1):D;if(W===" "||W==="-"){if(!o(C+1,s[C],W,ie)&&(a++,a>l))return!1;C++}}return!0}for(var h=0;h<i.length;h++){for(var g=i[h],S=s.length-g.oldLines,k=0,x=d+g.oldStart-1,A=gb(x,u,S);k!==void 0;k=A())if(m(g,x+k)){g.offset=d+=k;break}if(k===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],w=b.oldStart+b.offset+y-1;y+=b.newLines-b.oldLines;for(var _=0;_<b.lines.length;_++){var E=b.lines[_],I=E.length>0?E[0]:" ",$=E.length>0?E.substr(1):E,F=b.linedelimiters&&b.linedelimiters[_]||`
258
259
  `;if(I===" ")w++;else if(I==="-")s.splice(w,1),r.splice(w,1);else if(I==="+")s.splice(w,0,$),r.splice(w,0,F),w++;else if(I==="\\"){var H=b.lines[_-1]?b.lines[_-1][0]:null;H==="+"?f=!0:H==="-"&&(p=!0)}}}if(f)for(;!s[s.length-1];)s.pop(),r.pop();else p&&(s.push(""),r.push(`
259
- `));for(var X=0;X<s.length-1;X++)s[X]=s[X]+r[X];return s.join("")}function mb(n,e,t,s,r,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=ib(t,s,o);if(!a)return;a.push({value:"",lines:[]});function l(k){return k.map(function(x){return" "+x})}for(var u=[],d=0,f=0,p=[],m=1,h=1,g=function(x){var A=a[x],y=A.lines||A.value.replace(/\n$/,"").split(`
260
- `);if(A.lines=y,A.added||A.removed){var v;if(!d){var b=a[x-1];d=m,f=h,b&&(p=o.context>0?l(b.lines.slice(-o.context)):[],d-=p.length,f-=p.length)}(v=p).push.apply(v,io(y.map(function(X){return(A.added?"+":"-")+X}))),A.added?h+=y.length:m+=y.length}else{if(d)if(y.length<=o.context*2&&x<a.length-2){var w;(w=p).push.apply(w,io(l(y)))}else{var _,E=Math.min(y.length,o.context);(_=p).push.apply(_,io(l(y.slice(0,E))));var I={oldStart:d,oldLines:m-d+E,newStart:f,newLines:h-f+E,lines:p};if(x>=a.length-2&&y.length<=o.context){var $=/\n$/.test(t),F=/\n$/.test(s),H=y.length==0&&p.length>I.oldLines;!$&&H&&t.length>0&&p.splice(I.oldLines,0,"\"),(!$&&!H||!F)&&p.push("\")}u.push(I),d=0,f=0,p=[]}m+=y.length,h+=y.length}},S=0;S<a.length;S++)g(S);return{oldFileName:n,newFileName:e,oldHeader:r,newHeader:i,hunks:u}}function Hu(n){if(Array.isArray(n))return n.map(Hu).join(`
260
+ `));for(var X=0;X<s.length-1;X++)s[X]=s[X]+r[X];return s.join("")}function yb(n,e,t,s,r,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=ab(t,s,o);if(!a)return;a.push({value:"",lines:[]});function l(k){return k.map(function(x){return" "+x})}for(var u=[],d=0,f=0,p=[],m=1,h=1,g=function(x){var A=a[x],y=A.lines||A.value.replace(/\n$/,"").split(`
261
+ `);if(A.lines=y,A.added||A.removed){var v;if(!d){var b=a[x-1];d=m,f=h,b&&(p=o.context>0?l(b.lines.slice(-o.context)):[],d-=p.length,f-=p.length)}(v=p).push.apply(v,io(y.map(function(X){return(A.added?"+":"-")+X}))),A.added?h+=y.length:m+=y.length}else{if(d)if(y.length<=o.context*2&&x<a.length-2){var w;(w=p).push.apply(w,io(l(y)))}else{var _,E=Math.min(y.length,o.context);(_=p).push.apply(_,io(l(y.slice(0,E))));var I={oldStart:d,oldLines:m-d+E,newStart:f,newLines:h-f+E,lines:p};if(x>=a.length-2&&y.length<=o.context){var $=/\n$/.test(t),F=/\n$/.test(s),H=y.length==0&&p.length>I.oldLines;!$&&H&&t.length>0&&p.splice(I.oldLines,0,"\"),(!$&&!H||!F)&&p.push("\")}u.push(I),d=0,f=0,p=[]}m+=y.length,h+=y.length}},S=0;S<a.length;S++)g(S);return{oldFileName:n,newFileName:e,oldHeader:r,newHeader:i,hunks:u}}function Bu(n){if(Array.isArray(n))return n.map(Bu).join(`
261
262
  `);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(`
262
263
  `)+`
263
- `}function gb(n,e,t,s,r,i,o){return Hu(mb(n,e,t,s,r,i,o))}function Bu(n,e,t,s,r,i){return gb(n,n,e,t,s,r,i)}var BC,Du,Nu,Fu,co,ob,ab,fb,zn,lo,Uu=N(()=>{Et.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 p=(s=r.timeout)!==null&&s!==void 0?s:1/0,m=Date.now()+p,h=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(h[0],t,e,0);if(h[0].oldPos+1>=u&&g+1>=l)return a([{value:this.join(t),count:t.length}]);var S=-1/0,k=1/0;function x(){for(var y=Math.max(S,-d);y<=Math.min(k,d);y+=2){var v=void 0,b=h[y-1],w=h[y+1];b&&(h[y-1]=void 0);var _=!1;if(w){var E=w.oldPos-y;_=w&&0<=E&&E<l}var I=b&&b.oldPos+1<u;if(!_&&!I){h[y]=void 0;continue}if(!I||_&&b.oldPos+1<w.oldPos?v=o.addToPath(w,!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(rb(o,v.lastComponent,t,e,o.useLongestToken));h[y]=v,v.oldPos+1>=u&&(k=Math.min(k,y-1)),g+1>=l&&(S=Math.max(S,y+1))}d++}if(i)(function y(){setTimeout(function(){if(d>f||Date.now()>m)return i();x()||y()},0)})();else for(;d<=f&&Date.now()<=m;){var A=x();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("")}};BC=new Et,Du=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Nu=/\S/,Fu=new Et;Fu.equals=function(n,e){return this.options.ignoreCase&&(n=n.toLowerCase(),e=e.toLowerCase()),n===e||this.options.ignoreWhitespace&&!Nu.test(n)&&!Nu.test(e)};Fu.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]&&Du.test(e[t])&&Du.test(e[t+2])&&(e[t]+=e[t+2],e.splice(t+1,2),t--);return e};co=new Et;co.tokenize=function(n){this.options.stripTrailingCr&&(n=n.replace(/\r\n/g,`
264
- `));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};ob=new Et;ob.tokenize=function(n){return n.split(/(\S.+?[.!?])(?=\s+|$)/)};ab=new Et;ab.tokenize=function(n){return n.split(/([{}:;,]|\s+)/)};fb=Object.prototype.toString,zn=new Et;zn.useLongestToken=!0;zn.tokenize=co.tokenize;zn.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(ao(n,null,null,r),r," ")};zn.equals=function(n,e){return Et.prototype.equals.call(zn,n.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};lo=new Et;lo.tokenize=function(n){return n.slice()};lo.join=lo.removeEmpty=function(n){return n}});var qu={};Fe(qu,{applyDiff:()=>yb,formatDiffForDisplay:()=>bb,generateDiff:()=>Gs});function Gs(n,e,t){return Bu(n,e,t,"original","modified")}function yb(n,e){return ju(n,e)}function bb(n){return n.split(`
264
+ `}function bb(n,e,t,s,r,i,o){return Bu(yb(n,e,t,s,r,i,o))}function Uu(n,e,t,s,r,i){return bb(n,n,e,t,s,r,i)}var qC,Nu,Fu,ju,co,lb,cb,hb,zn,lo,qu=N(()=>{Ct.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 p=(s=r.timeout)!==null&&s!==void 0?s:1/0,m=Date.now()+p,h=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(h[0],t,e,0);if(h[0].oldPos+1>=u&&g+1>=l)return a([{value:this.join(t),count:t.length}]);var S=-1/0,k=1/0;function x(){for(var y=Math.max(S,-d);y<=Math.min(k,d);y+=2){var v=void 0,b=h[y-1],w=h[y+1];b&&(h[y-1]=void 0);var _=!1;if(w){var E=w.oldPos-y;_=w&&0<=E&&E<l}var I=b&&b.oldPos+1<u;if(!_&&!I){h[y]=void 0;continue}if(!I||_&&b.oldPos+1<w.oldPos?v=o.addToPath(w,!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(ob(o,v.lastComponent,t,e,o.useLongestToken));h[y]=v,v.oldPos+1>=u&&(k=Math.min(k,y-1)),g+1>=l&&(S=Math.max(S,y+1))}d++}if(i)(function y(){setTimeout(function(){if(d>f||Date.now()>m)return i();x()||y()},0)})();else for(;d<=f&&Date.now()<=m;){var A=x();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("")}};qC=new Ct,Nu=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Fu=/\S/,ju=new Ct;ju.equals=function(n,e){return this.options.ignoreCase&&(n=n.toLowerCase(),e=e.toLowerCase()),n===e||this.options.ignoreWhitespace&&!Fu.test(n)&&!Fu.test(e)};ju.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]&&Nu.test(e[t])&&Nu.test(e[t+2])&&(e[t]+=e[t+2],e.splice(t+1,2),t--);return e};co=new Ct;co.tokenize=function(n){this.options.stripTrailingCr&&(n=n.replace(/\r\n/g,`
265
+ `));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};lb=new Ct;lb.tokenize=function(n){return n.split(/(\S.+?[.!?])(?=\s+|$)/)};cb=new Ct;cb.tokenize=function(n){return n.split(/([{}:;,]|\s+)/)};hb=Object.prototype.toString,zn=new Ct;zn.useLongestToken=!0;zn.tokenize=co.tokenize;zn.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(ao(n,null,null,r),r," ")};zn.equals=function(n,e){return Ct.prototype.equals.call(zn,n.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};lo=new Ct;lo.tokenize=function(n){return n.slice()};lo.join=lo.removeEmpty=function(n){return n}});var Ku={};je(Ku,{applyDiff:()=>vb,formatDiffForDisplay:()=>wb,generateDiff:()=>Gs});function Gs(n,e,t){return Uu(n,e,t,"original","modified")}function vb(n,e){return Hu(n,e)}function wb(n){return n.split(`
265
266
  `).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(`
266
- `)}var uo=N(()=>{"use strict";Uu()});async function Qt(n,e){let t=[],s=$e.join(n,"package.json");if(be.existsSync(s))try{let o=JSON.parse(be.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 Yi(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=>be.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=>be.existsSync($e.join(n,o)));if(i.length>0&&t.push(`Config: ${i.join(", ")}`),e?.context?.projectGraph)try{let o=be.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=be.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(`
267
+ `)}var uo=N(()=>{"use strict";qu()});async function Qt(n,e){let t=[],s=$e.join(n,"package.json");if(be.existsSync(s))try{let o=JSON.parse(be.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 zi(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=>be.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=>be.existsSync($e.join(n,o)));if(i.length>0&&t.push(`Config: ${i.join(", ")}`),e?.context?.projectGraph)try{let o=be.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=be.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(`
267
268
  `)}function Zt(n,e,t,s){let r=n+`
268
269
 
269
270
  ## Current Project
@@ -274,14 +275,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
274
275
  ## Shared Context
275
276
  `+i)}return r+=`
276
277
 
277
- `+ru(),r}async function vb(n){try{if(!be.existsSync(fo))return null;let t=(await Ft.readdir(fo)).filter(f=>f.endsWith(".bak"));if(n){let f=$e.basename(n);t=t.filter(p=>p.startsWith(`${f}.`))}if(t.length===0)return null;t.sort().reverse();let s=t[0],r=$e.join(fo,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 Ku(n,e,t,s,r,i,o,a,l,u,d,f,p,m,h,g,S){let k=n.split(/\s+/),x=k[0],A=k.slice(1).join(" ");switch(x){case"/quit":case"/exit":return"quit";case"/help":console.log(Su()),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(gu());break;case"/version":console.log(yu());break;case"/team":{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Team Roster")}`),console.log(),console.log(Li()),console.log();break}case"/model":if(A){let y=await t.listModels();t.setModel(A),y.includes(A)?console.log(J(`Model: ${A}`)):console.log(B(`Model set to "${A}" (not found locally)`))}else console.log(le(`Current model: ${t.getModel()}`)),console.log(c.muted(" Usage: /model <name>"));break;case"/models":{let y=A.trim(),v=1,b="";if(y){let C=parseInt(y);!isNaN(C)&&C>0?v=C:b=y.toLowerCase()}let w=new ze("Fetching models");w.start();let _=await t.listModels();if(w.stop(_.length>0?`${_.length} found`:void 0),_.length===0){console.log(B("No models found \u2014 check your connection")),console.log(c.muted(" Use /provider test to verify"));break}let E=_;if(b&&(E=_.filter(C=>C.toLowerCase().includes(b)),E.length===0)){console.log(B(`No models matching: "${b}"`)),console.log(c.muted(` ${_.length} models available. Try a different search.`));break}let I=20,$=Math.ceil(E.length/I),F=Math.max(1,Math.min(v,$)),H=(F-1)*I,X=H+I,T=E.slice(H,X);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Available Models")} ${c.muted(`(${E.length} total \xB7 page ${F}/${$})`)}`),console.log();for(let C=0;C<T.length;C++){let ne=H+C+1,W=T[C]===t.getModel()?` ${c.success("\u25CF active")}`:"";console.log(` ${c.muted(String(ne).padStart(3," "))}. ${c.secondary(T[C])}${W}`)}console.log(),$>1&&console.log(c.muted(` /models ${F<$?F+1:1} \u2014 next page`)),b&&console.log(c.muted(` Filtered: ${E.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(`
278
+ `+iu(),r}async function xb(n){try{if(!be.existsSync(fo))return null;let t=(await Ft.readdir(fo)).filter(f=>f.endsWith(".bak"));if(n){let f=$e.basename(n);t=t.filter(p=>p.startsWith(`${f}.`))}if(t.length===0)return null;t.sort().reverse();let s=t[0],r=$e.join(fo,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 Wu(n,e,t,s,r,i,o,a,l,u,d,f,p,m,h,g,S){let k=n.split(/\s+/),x=k[0],A=k.slice(1).join(" ");switch(x){case"/quit":case"/exit":return"quit";case"/help":console.log(_u()),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(yu());break;case"/version":console.log(bu());break;case"/team":{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Team Roster")}`),console.log(),console.log(Mi()),console.log();break}case"/model":if(A){let y=await t.listModels();t.setModel(A),y.includes(A)?console.log(J(`Model: ${A}`)):console.log(B(`Model set to "${A}" (not found locally)`))}else console.log(le(`Current model: ${t.getModel()}`)),console.log(c.muted(" Usage: /model <name>"));break;case"/models":{let y=A.trim(),v=1,b="";if(y){let C=parseInt(y);!isNaN(C)&&C>0?v=C:b=y.toLowerCase()}let w=new ze("Fetching models");w.start();let _=await t.listModels();if(w.stop(_.length>0?`${_.length} found`:void 0),_.length===0){console.log(B("No models found \u2014 check your connection")),console.log(c.muted(" Use /provider test to verify"));break}let E=_;if(b&&(E=_.filter(C=>C.toLowerCase().includes(b)),E.length===0)){console.log(B(`No models matching: "${b}"`)),console.log(c.muted(` ${_.length} models available. Try a different search.`));break}let I=20,$=Math.ceil(E.length/I),F=Math.max(1,Math.min(v,$)),H=(F-1)*I,X=H+I,T=E.slice(H,X);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Available Models")} ${c.muted(`(${E.length} total \xB7 page ${F}/${$})`)}`),console.log();for(let C=0;C<T.length;C++){let ne=H+C+1,W=T[C]===t.getModel()?` ${c.success("\u25CF active")}`:"";console.log(` ${c.muted(String(ne).padStart(3," "))}. ${c.secondary(T[C])}${W}`)}console.log(),$>1&&console.log(c.muted(` /models ${F<$?F+1:1} \u2014 next page`)),b&&console.log(c.muted(` Filtered: ${E.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(`
278
279
  ${v.output}
279
- `)}break}case"/status":{let y=await t.checkConnection(),v=u?u.getActiveName():"planner",b=f?f.size():0,w=d?d.getProgress():void 0;console.log(xu({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}`)),w&&w.total>0&&console.log(c.muted(` Tasks: ${w.done}/${w.total} done`)),console.log();break}case"/clear":r.clear(),i.clear(),console.log(J("History cleared"));break;case"/history":{let y=parseInt(A)||10,v=i.getHistory().slice(-y);if(v.length===0){console.log(le("No history yet"));break}console.log(),v.forEach(b=>{let w=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(` ${w}: ${c.muted(_)}`)}),console.log();break}case"/undo":{if(!g){let y=await vb(A||void 0);if(!y){console.log(B("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 w=await Ft.readFile(y.backupPath,"utf-8");await Ft.writeFile(v,w,"utf-8"),console.log(J(`Restored ${y.originalName} from backup (${y.age})`))}catch(w){console.log(Ce(`Failed: ${w.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(le("Nothing to undo"));break}if(await a.confirm(`Undo ALL ${y} changes?`)){let b=await g.undoAll(),w=b.filter(_=>_.success).length;console.log(J(`Reverted ${w}/${b.length} changes`))}}else{let y=A&&parseInt(A)||1;if(g.getUndoableCount()===0){console.log(le("Nothing to undo"));break}let v=await g.undo(y);for(let b of v)b.success?console.log(J(`Reverted: ${b.file}`)):console.log(Ce(`Failed to revert ${b.file}: ${b.error}`))}break}case"/config":console.log(`
280
+ `)}break}case"/status":{let y=await t.checkConnection(),v=u?u.getActiveName():"planner",b=f?f.size():0,w=d?d.getProgress():void 0;console.log(Su({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}`)),w&&w.total>0&&console.log(c.muted(` Tasks: ${w.done}/${w.total} done`)),console.log();break}case"/clear":r.clear(),i.clear(),console.log(J("History cleared"));break;case"/history":{let y=parseInt(A)||10,v=i.getHistory().slice(-y);if(v.length===0){console.log(le("No history yet"));break}console.log(),v.forEach(b=>{let w=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(` ${w}: ${c.muted(_)}`)}),console.log();break}case"/undo":{if(!g){let y=await xb(A||void 0);if(!y){console.log(B("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 w=await Ft.readFile(y.backupPath,"utf-8");await Ft.writeFile(v,w,"utf-8"),console.log(J(`Restored ${y.originalName} from backup (${y.age})`))}catch(w){console.log(Ce(`Failed: ${w.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(le("Nothing to undo"));break}if(await a.confirm(`Undo ALL ${y} changes?`)){let b=await g.undoAll(),w=b.filter(_=>_.success).length;console.log(J(`Reverted ${w}/${b.length} changes`))}}else{let y=A&&parseInt(A)||1;if(g.getUndoableCount()===0){console.log(le("Nothing to undo"));break}let v=await g.undo(y);for(let b of v)b.success?console.log(J(`Reverted: ${b.file}`)):console.log(Ce(`Failed to revert ${b.file}: ${b.error}`))}break}case"/config":console.log(`
280
281
  ${c.muted(JSON.stringify(e,null,2))}
281
- `),console.log(c.muted(" ~/.hablas/config.json")),console.log();break;case"/mindset":{if(!u){console.log(B("Mindset system not available"));break}if(A)if(u.setActive(A)){let v=u.getActive(),b=await Qt(o,e),w=Zt(v.systemPrompt,b,f,m);i.updateSystemPrompt(w),console.log(J(`Mindset: ${v.name} \u2014 ${v.description}`))}else{let v=u.listNames().join(", ");console.log(Ue(`Unknown mindset: "${A}"`,`Available: ${v}`))}else{let y=u.getActive();y&&console.log(le(`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(B("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(B("Task queue not available"));break}let y=k[1],v=k.slice(2).join(" ");switch(y){case"add":if(v){let b=d.add(v);console.log(J(`Task #${b.id} added: ${v}`))}else console.log(B("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(J(`Task #${b} marked as done`))):console.log(B("Usage: /task done <id>"));break}case"fail":{let b=parseInt(v);b?(d.fail(b,"Manually marked as failed"),console.log(B(`Task #${b} marked as failed`))):console.log(B("Usage: /task fail <id>"));break}case"clear":d.clear(),console.log(J("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(B("Cancelled \u2014 name is required"));break}let w=(await a.prompt(` ${c.muted("API URL (e.g. https://api.openai.com/v1):")} `)).trim();if(!w){console.log(B("Cancelled \u2014 URL is required"));break}let E=(await a.prompt(` ${c.muted("API Key (leave empty if none):")} `)).trim(),$=(await a.prompt(` ${c.muted("Default model ID (e.g. gpt-4o):")} `)).trim()||"default",F={name:v,apiUrl:w,apiKey:E,models:[$],defaultModel:$,addedAt:new Date().toISOString()};nt(F),console.log(),console.log(J(`Provider "${v}" saved!`)),console.log(c.muted(` Use: /usemodel ${v}`)),console.log();break}case"/listmodels":{let y=zt();console.log(),console.log(Rc(y.providers,y.activeProvider));break}case"/removemodel":{let y=A.trim();if(!y){console.log(B("Usage: /removemodel <provider-name>"));break}if(Cc(y))console.log(J(`Provider "${y}" removed`));else{console.log(B(`Provider "${y}" not found`));let b=Ps();b.length>0&&console.log(c.muted(` Available: ${b.map(w=>w.name).join(", ")}`))}break}case"/usemodel":{let y=A.trim();if(!y){console.log(B("Usage: /usemodel <provider-name> [model-id]"));let F=Ps();F.length>0&&console.log(c.muted(` Available: ${F.map(H=>H.name).join(", ")}`));break}let v=y.split(/\s+/),b=v[0],w=v[1],_=Ec(b);if(!_){console.log(B(`Provider "${b}" not found`));let F=Ps();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=w||_.defaultModel;let E=je(e);p&&p(E),Tc(_.name,e.model),console.log(J(`Switched to ${_.name} \xB7 Model: ${e.model}`));let I=new ze("Testing");I.start();let $=await E.checkConnection();I.stop($?"connected":void 0),$||console.log(B("Connection test failed \u2014 check URL and key"));break}case"/provider":{let y=k[1],v=k.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=je(e);p&&p(b),console.log(J("Switched to Ollama (local)"));break}case"nvidia":{let b=k[2];if(!b&&!e.apiKey){console.log(B("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 w=je(e);p&&p(w),console.log(J(`Switched to NVIDIA NIM \xB7 Model: ${e.model}`)),console.log(c.muted(` Available models: ${Nt.models.length}`));let _=new ze("Testing NVIDIA connection");_.start();let E=await w.checkConnection();_.stop(E?"connected":void 0),E||(console.log(B("Connection test failed \u2014 check your API key")),console.log(c.muted(" Get key: https://build.nvidia.com/")));break}case"custom":{let b=k[2],w=k[3];if(!b){console.log(B("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,w&&(e.apiKey=w);let _=je(e);p&&p(_),console.log(J(`Switched to Custom API: ${b}`)),!w&&!e.apiKey&&console.log(B("No API key set. Use: /provider custom <url> <key>"));break}case"test":{let b=new ze("Testing connection");b.start();let w=await t.checkConnection();if(b.stop(w?"connected":void 0),w){let _=await t.listModels();console.log(J(`Connected! ${_.length} models available.`)),_.length>0&&console.log(c.muted(` Models: ${_.slice(0,5).join(", ")}${_.length>5?"...":""}`))}else console.log(Ce("Connection failed"));break}case"key":{v?(e.apiKey=k[2],t instanceof Vt&&t.setApiKey(e.apiKey),console.log(J("API key updated"))):console.log(B("Usage: /provider key <api-key>"));break}default:console.log(Ue(`Unknown: /provider ${y}`,"Type /provider for help"))}break}case"/memory":{if(!f){console.log(B("Project memory not available"));break}let y=k[1],v=k.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");f.set(b,w),console.log(J(`Memory stored: ${b}`));let _=u?.getActive(),E=_?_.systemPrompt:Yn,I=await Qt(o,e);i.updateSystemPrompt(Zt(E,I,f,m))}else console.log(B("Usage: /memory set <key> <value>"));break}case"del":case"delete":{if(v[0]){let b=f.delete(v[0]);console.log(b?J(`Memory deleted: ${v[0]}`):B(`Memory key not found: ${v[0]}`))}else console.log(B("Usage: /memory del <key>"));break}case"search":{if(v[0]){let b=f.search(v.join(" "));b.length>0?(console.log(),b.forEach(w=>console.log(` \xB7 ${w.entry.key}: ${w.entry.value}`)),console.log()):console.log(le("No matching memories found"))}else console.log(B("Usage: /memory search <query>"));break}case"clear":f.clear(),console.log(J("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=k[1],v=k.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");Ic(b,w),console.log(J(`Alias set: ${b} \u2192 ${w}`))}else console.log(B("Usage: /alias set <name> <expansion>"));break}case"del":case"remove":{if(v[0]){let b=Mc(v[0]);console.log(b?J(`Alias removed: ${v[0]}`):B(`Alias not found: ${v[0]}`))}else console.log(B("Usage: /alias del <name>"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Aliases")}`),console.log(),console.log(Dc()),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 ze("Running diagnostics");y.start();let v=await Oi({ollamaHost:e.ollamaHost,model:t.getModel(),provider:e.provider,apiUrl:e.apiUrl});y.stop(),console.log(Ii(v));break}case"/plugins":{let y=k[1],v=k.slice(2).join(" ");switch(y){case"enable":v?(Ci(v),console.log(J(`Plugin "${v}" enabled`))):console.log(B("Usage: /plugins enable <name>"));break;case"disable":v?(Ei(v),console.log(B(`Plugin "${v}" disabled`))):console.log(B("Usage: /plugins disable <name>"));break;default:Ns(),console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plugins")}`),console.log(),console.log(Ti()),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"/agents":{let y=k[1];if(y==="on")e.agents.enabled=!0,console.log(J("Multi-agent orchestration enabled"));else if(y==="off")e.agents.enabled=!1,console.log(J("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(Li()),console.log();else if(y==="models"){let v=qn();console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Agent Models")}`),console.log();for(let b of _e){let w=v[b.role];console.log(w?` ${c.primary(b.name.padEnd(8))} \u2192 ${c.highlight(w.model)}${w.temperature!==void 0?c.muted(` (temp: ${w.temperature})`):""}`:` ${c.primary(b.name.padEnd(8))} \u2192 ${c.muted("(default)")}`)}console.log(),console.log(c.muted(` Config: ${Gc()}`)),console.log(c.muted(" Edit the file to change models per agent.")),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=Gi(o);console.log(Vi(y));break}case"/git":{if(k[1]==="status")try{let{getGitStatus:v,formatGitStatus:b}=await Promise.resolve().then(()=>(vn(),Gn)),w=await v(o);w?(console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Git Status")}`),console.log(b(w)),console.log()):console.log(B("Not a git repository"))}catch{console.log(B("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(Ji(y)),console.log();break}case"/stats":{let{loadStats:y,formatStats:v}=await Promise.resolve().then(()=>(Wn(),Wi)),b=y();console.log(v(b));break}case"/context":{if(!m){console.log(B("Shared context not available"));break}let y=k[1],v=k.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");m.set(b,w),console.log(J(`Context stored: ${b}`))}else console.log(B("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(B(`Context key not found: ${v[0]}`))}else console.log(B("Usage: /context get <key>"));break}case"del":case"delete":{if(v[0]){let b=m.delete(v[0]);console.log(b?J(`Context deleted: ${v[0]}`):B(`Context key not found: ${v[0]}`))}else console.log(B("Usage: /context del <key>"));break}case"decisions":{let b=m.getDecisions();if(b.length===0)console.log(le("No decisions logged yet"));else{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Decisions")}`),console.log();for(let w of b)console.log(` ${c.muted(w.timestamp)} ${c.primary(w.by)}: ${w.decision}`),w.rationale&&console.log(` ${c.muted(w.rationale)}`);console.log()}break}case"clear":m.clear(),console.log(J("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(!h){console.log(B("Plan manager not available"));break}let y=k[1],v=k.slice(2).join(" ");switch(y){case"status":{let w=h.getActivePlan();if(!w){console.log(le("No active plan"));break}let _=h.getProgress();console.log(Vn(w,{percent:_.percentage,done:_.done,total:_.total}));break}case"finish":{if(v){h.finishTask(v),console.log(J(`Task finished: ${v}`));let w=h.getProgress();console.log(c.muted(` Progress: ${w.done}/${w.total} (${w.percentage}%)`))}else console.log(B("Usage: /plan finish <task_id>"));break}case"reset":{h.reset(),console.log(J("Plan manager reset"));break}case"next":{let w=h.getNextTask();console.log(w?le(`Next task: [${w.task_id}] ${w.description} \u2192 @${w.assignee}`):le("No pending tasks"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plan Manager")}`),console.log();let b=h.getActivePlan();if(b){let w=h.getProgress();console.log(` Active plan: ${b.title} (${w.percentage}% done)`),console.log(` Tasks: ${w.done}/${w.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(B('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 Qt(o,e),b=u?.getActive(),w=b?b.systemPrompt:Yn,_=Zt(w,v,f,m);i.updateSystemPrompt(_)}console.log(J(`Learned: "${A}"`)),console.log(c.muted(" This will be remembered across sessions and injected into every prompt."));break}case"/test":{let y=ro(o);if(y==="unknown"&&!A){console.log(B("No test framework detected. Install jest, vitest, pytest, etc."));break}console.log(le(`Running tests (${y})...`));let v=ku(o,A==="--fix"?void 0:A||void 0);if(console.log(),console.log($u(v)),console.log(),!v.passed&&A==="--fix"){console.log(le("Tests failed \u2014 adding fix request to conversation..."));let b=Cu(v);i.addUserMessage(b),console.log(le("Type your next message or let the agent work on the fix."))}break}case"/checkpoint":{let y=k[1],v=k.slice(2).join(" ");if(y==="save"){let b=v||`Checkpoint at turn ${l}`,w=g?.getModifiedFiles?.()||[],_=await Ru(o,b,w);console.log(J(`Checkpoint saved: ${_.id} "${b}" (${_.fileCount} files)`))}else if(y==="list"){let b=Pu(o);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Checkpoints")}`),console.log(),console.log(Mu(b)),console.log()}else if(y==="restore"){if(!v){console.log(B("Usage: /checkpoint restore <id>"));break}let b=await Ou(o,v);b.success?console.log(J(`Restored checkpoint: ${v} (${b.filesRestored} files)`)):console.log(Ce(b.error||"Restore failed"))}else y==="delete"?v&&Iu(o,v)?console.log(J(`Deleted checkpoint: ${v}`)):console.log(B("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=k.slice(1);if(y.length===2)try{let v=await Ft.readFile($e.resolve(o,y[0]),"utf-8"),b=await Ft.readFile($e.resolve(o,y[1]),"utf-8"),{generateDiff:w}=await Promise.resolve().then(()=>(uo(),qu)),_=w(y[0]+" vs "+y[1],v,b);console.log(to(_))}catch(v){console.log(Ce(`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(to(b||"(no changes)"))}catch(v){console.log(Ce(`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=Kn(),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[w,_]of b.sort((E,I)=>I[1]-E[1]))console.log(` @${w}: ${_} invocations`)}console.log();break}case"/delegate":{if(!e.agents.enabled){console.log(B("Multi-agent system is disabled. Enable with /agents on"));break}let y=k[1]?.toLowerCase(),v=k.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(B(`Unknown agent: "${y}". Valid: ${b.join(", ")}`));break}let w=_e.find(_=>_.role===y);if(w){if(!S){console.log(B("Agent runner not initialized. Cannot delegate."));break}console.log(hu("Hablas",w.name,w.title,v)),console.log(Jt(w.name,w.title));let _=s.getOllamaTools(),E=await S.runAgent(y,v,void 0,_);E.success&&E.output?(console.log(Xt(E.output)),i.addAssistantMessage(`[@${w.name}]: ${E.output}`)):E.error?console.log(B(`${w.name} failed: ${E.error}`)):console.log(le(`${w.name} completed without output.`))}break}case"/session":{let y=k[1],v=k.slice(2).join(" "),b=$e.join(po.homedir(),".hablas","sessions");if(y==="save"){let w=v||`session_${Date.now()}`;try{be.existsSync(b)||be.mkdirSync(b,{recursive:!0});let _=i.toJSON(),E=$e.join(b,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);be.writeFileSync(E,_,"utf-8"),console.log(J(`Session saved: "${w}"`))}catch(_){console.log(Ce(`Save failed: ${_.message}`))}}else if(y==="list")try{if(!be.existsSync(b)){console.log(le("No saved sessions"));break}let w=be.readdirSync(b).filter(_=>_.endsWith(".json"));console.log();for(let _ of w){let E=be.statSync($e.join(b,_));console.log(` ${_.replace(".json","")} (${new Date(E.mtime).toLocaleString()})`)}console.log()}catch{console.log(le("No saved sessions"))}else if(y==="load"){let w=v;if(!w){console.log(Ce("Please specify the session label to load: /session load <label>"));break}try{let _=$e.join(b,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);if(!be.existsSync(_)){console.log(Ce(`Session file not found: ${w}`));break}let E=be.readFileSync(_,"utf-8");i.fromJSON(E),console.log(J(`Session successfully loaded: "${w}"`))}catch(_){console.log(Ce(`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(()=>(Tt(),jt));if(!y){console.log(B("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(`
282
+ `),console.log(c.muted(" ~/.hablas/config.json")),console.log();break;case"/mindset":{if(!u){console.log(B("Mindset system not available"));break}if(A)if(u.setActive(A)){let v=u.getActive(),b=await Qt(o,e),w=Zt(v.systemPrompt,b,f,m);i.updateSystemPrompt(w),console.log(J(`Mindset: ${v.name} \u2014 ${v.description}`))}else{let v=u.listNames().join(", ");console.log(Ue(`Unknown mindset: "${A}"`,`Available: ${v}`))}else{let y=u.getActive();y&&console.log(le(`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(B("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(B("Task queue not available"));break}let y=k[1],v=k.slice(2).join(" ");switch(y){case"add":if(v){let b=d.add(v);console.log(J(`Task #${b.id} added: ${v}`))}else console.log(B("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(J(`Task #${b} marked as done`))):console.log(B("Usage: /task done <id>"));break}case"fail":{let b=parseInt(v);b?(d.fail(b,"Manually marked as failed"),console.log(B(`Task #${b} marked as failed`))):console.log(B("Usage: /task fail <id>"));break}case"clear":d.clear(),console.log(J("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(B("Cancelled \u2014 name is required"));break}let w=(await a.prompt(` ${c.muted("API URL (e.g. https://api.openai.com/v1):")} `)).trim();if(!w){console.log(B("Cancelled \u2014 URL is required"));break}let E=(await a.prompt(` ${c.muted("API Key (leave empty if none):")} `)).trim(),$=(await a.prompt(` ${c.muted("Default model ID (e.g. gpt-4o):")} `)).trim()||"default",F={name:v,apiUrl:w,apiKey:E,models:[$],defaultModel:$,addedAt:new Date().toISOString()};nt(F),console.log(),console.log(J(`Provider "${v}" saved!`)),console.log(c.muted(` Use: /usemodel ${v}`)),console.log();break}case"/listmodels":{let y=zt();console.log(),console.log(Pc(y.providers,y.activeProvider));break}case"/removemodel":{let y=A.trim();if(!y){console.log(B("Usage: /removemodel <provider-name>"));break}if(Ec(y))console.log(J(`Provider "${y}" removed`));else{console.log(B(`Provider "${y}" not found`));let b=Ps();b.length>0&&console.log(c.muted(` Available: ${b.map(w=>w.name).join(", ")}`))}break}case"/usemodel":{let y=A.trim();if(!y){console.log(B("Usage: /usemodel <provider-name> [model-id]"));let F=Ps();F.length>0&&console.log(c.muted(` Available: ${F.map(H=>H.name).join(", ")}`));break}let v=y.split(/\s+/),b=v[0],w=v[1],_=Tc(b);if(!_){console.log(B(`Provider "${b}" not found`));let F=Ps();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=w||_.defaultModel;let E=He(e);p&&p(E),Rc(_.name,e.model),console.log(J(`Switched to ${_.name} \xB7 Model: ${e.model}`));let I=new ze("Testing");I.start();let $=await E.checkConnection();I.stop($?"connected":void 0),$||console.log(B("Connection test failed \u2014 check URL and key"));break}case"/provider":{let y=k[1],v=k.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=He(e);p&&p(b),console.log(J("Switched to Ollama (local)"));break}case"nvidia":{let b=k[2];if(!b&&!e.apiKey){console.log(B("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 w=He(e);p&&p(w),console.log(J(`Switched to NVIDIA NIM \xB7 Model: ${e.model}`)),console.log(c.muted(` Available models: ${Nt.models.length}`));let _=new ze("Testing NVIDIA connection");_.start();let E=await w.checkConnection();_.stop(E?"connected":void 0),E||(console.log(B("Connection test failed \u2014 check your API key")),console.log(c.muted(" Get key: https://build.nvidia.com/")));break}case"custom":{let b=k[2],w=k[3];if(!b){console.log(B("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,w&&(e.apiKey=w);let _=He(e);p&&p(_),console.log(J(`Switched to Custom API: ${b}`)),!w&&!e.apiKey&&console.log(B("No API key set. Use: /provider custom <url> <key>"));break}case"test":{let b=new ze("Testing connection");b.start();let w=await t.checkConnection();if(b.stop(w?"connected":void 0),w){let _=await t.listModels();console.log(J(`Connected! ${_.length} models available.`)),_.length>0&&console.log(c.muted(` Models: ${_.slice(0,5).join(", ")}${_.length>5?"...":""}`))}else console.log(Ce("Connection failed"));break}case"key":{v?(e.apiKey=k[2],t instanceof Vt&&t.setApiKey(e.apiKey),console.log(J("API key updated"))):console.log(B("Usage: /provider key <api-key>"));break}default:console.log(Ue(`Unknown: /provider ${y}`,"Type /provider for help"))}break}case"/memory":{if(!f){console.log(B("Project memory not available"));break}let y=k[1],v=k.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");f.set(b,w),console.log(J(`Memory stored: ${b}`));let _=u?.getActive(),E=_?_.systemPrompt:Yn,I=await Qt(o,e);i.updateSystemPrompt(Zt(E,I,f,m))}else console.log(B("Usage: /memory set <key> <value>"));break}case"del":case"delete":{if(v[0]){let b=f.delete(v[0]);console.log(b?J(`Memory deleted: ${v[0]}`):B(`Memory key not found: ${v[0]}`))}else console.log(B("Usage: /memory del <key>"));break}case"search":{if(v[0]){let b=f.search(v.join(" "));b.length>0?(console.log(),b.forEach(w=>console.log(` \xB7 ${w.entry.key}: ${w.entry.value}`)),console.log()):console.log(le("No matching memories found"))}else console.log(B("Usage: /memory search <query>"));break}case"clear":f.clear(),console.log(J("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=k[1],v=k.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");Mc(b,w),console.log(J(`Alias set: ${b} \u2192 ${w}`))}else console.log(B("Usage: /alias set <name> <expansion>"));break}case"del":case"remove":{if(v[0]){let b=Lc(v[0]);console.log(b?J(`Alias removed: ${v[0]}`):B(`Alias not found: ${v[0]}`))}else console.log(B("Usage: /alias del <name>"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Aliases")}`),console.log(),console.log(Nc()),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 ze("Running diagnostics");y.start();let v=await Pi({ollamaHost:e.ollamaHost,model:t.getModel(),provider:e.provider,apiUrl:e.apiUrl});y.stop(),console.log(Oi(v));break}case"/plugins":{let y=k[1],v=k.slice(2).join(" ");switch(y){case"enable":v?($i(v),console.log(J(`Plugin "${v}" enabled`))):console.log(B("Usage: /plugins enable <name>"));break;case"disable":v?(Ci(v),console.log(B(`Plugin "${v}" disabled`))):console.log(B("Usage: /plugins disable <name>"));break;default:Ns(),console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plugins")}`),console.log(),console.log(Ei()),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"/agents":{let y=k[1];if(y==="on")e.agents.enabled=!0,console.log(J("Multi-agent orchestration enabled"));else if(y==="off")e.agents.enabled=!1,console.log(J("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(Mi()),console.log();else if(y==="models"){let v=qn();console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Agent Models")}`),console.log();for(let b of _e){let w=v[b.role];console.log(w?` ${c.primary(b.name.padEnd(8))} \u2192 ${c.highlight(w.model)}${w.temperature!==void 0?c.muted(` (temp: ${w.temperature})`):""}`:` ${c.primary(b.name.padEnd(8))} \u2192 ${c.muted("(default)")}`)}console.log(),console.log(c.muted(` Config: ${Vc()}`)),console.log(c.muted(" Edit the file to change models per agent.")),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=Wi(o);console.log(Gi(y));break}case"/git":{if(k[1]==="status")try{let{getGitStatus:v,formatGitStatus:b}=await Promise.resolve().then(()=>(vn(),Gn)),w=await v(o);w?(console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Git Status")}`),console.log(b(w)),console.log()):console.log(B("Not a git repository"))}catch{console.log(B("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(Yi(y)),console.log();break}case"/stats":{let{loadStats:y,formatStats:v}=await Promise.resolve().then(()=>(Wn(),Ki)),b=y();console.log(v(b));break}case"/context":{if(!m){console.log(B("Shared context not available"));break}let y=k[1],v=k.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");m.set(b,w),console.log(J(`Context stored: ${b}`))}else console.log(B("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(B(`Context key not found: ${v[0]}`))}else console.log(B("Usage: /context get <key>"));break}case"del":case"delete":{if(v[0]){let b=m.delete(v[0]);console.log(b?J(`Context deleted: ${v[0]}`):B(`Context key not found: ${v[0]}`))}else console.log(B("Usage: /context del <key>"));break}case"decisions":{let b=m.getDecisions();if(b.length===0)console.log(le("No decisions logged yet"));else{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Decisions")}`),console.log();for(let w of b)console.log(` ${c.muted(w.timestamp)} ${c.primary(w.by)}: ${w.decision}`),w.rationale&&console.log(` ${c.muted(w.rationale)}`);console.log()}break}case"clear":m.clear(),console.log(J("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(!h){console.log(B("Plan manager not available"));break}let y=k[1],v=k.slice(2).join(" ");switch(y){case"status":{let w=h.getActivePlan();if(!w){console.log(le("No active plan"));break}let _=h.getProgress();console.log(Vn(w,{percent:_.percentage,done:_.done,total:_.total}));break}case"finish":{if(v){h.finishTask(v),console.log(J(`Task finished: ${v}`));let w=h.getProgress();console.log(c.muted(` Progress: ${w.done}/${w.total} (${w.percentage}%)`))}else console.log(B("Usage: /plan finish <task_id>"));break}case"reset":{h.reset(),console.log(J("Plan manager reset"));break}case"next":{let w=h.getNextTask();console.log(w?le(`Next task: [${w.task_id}] ${w.description} \u2192 @${w.assignee}`):le("No pending tasks"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plan Manager")}`),console.log();let b=h.getActivePlan();if(b){let w=h.getProgress();console.log(` Active plan: ${b.title} (${w.percentage}% done)`),console.log(` Tasks: ${w.done}/${w.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(B('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 Qt(o,e),b=u?.getActive(),w=b?b.systemPrompt:Yn,_=Zt(w,v,f,m);i.updateSystemPrompt(_)}console.log(J(`Learned: "${A}"`)),console.log(c.muted(" This will be remembered across sessions and injected into every prompt."));break}case"/test":{let y=ro(o);if(y==="unknown"&&!A){console.log(B("No test framework detected. Install jest, vitest, pytest, etc."));break}console.log(le(`Running tests (${y})...`));let v=$u(o,A==="--fix"?void 0:A||void 0);if(console.log(),console.log(Cu(v)),console.log(),!v.passed&&A==="--fix"){console.log(le("Tests failed \u2014 adding fix request to conversation..."));let b=Eu(v);i.addUserMessage(b),console.log(le("Type your next message or let the agent work on the fix."))}break}case"/checkpoint":{let y=k[1],v=k.slice(2).join(" ");if(y==="save"){let b=v||`Checkpoint at turn ${l}`,w=g?.getModifiedFiles?.()||[],_=await Pu(o,b,w);console.log(J(`Checkpoint saved: ${_.id} "${b}" (${_.fileCount} files)`))}else if(y==="list"){let b=Ou(o);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Checkpoints")}`),console.log(),console.log(Lu(b)),console.log()}else if(y==="restore"){if(!v){console.log(B("Usage: /checkpoint restore <id>"));break}let b=await Iu(o,v);b.success?console.log(J(`Restored checkpoint: ${v} (${b.filesRestored} files)`)):console.log(Ce(b.error||"Restore failed"))}else y==="delete"?v&&Mu(o,v)?console.log(J(`Deleted checkpoint: ${v}`)):console.log(B("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=k.slice(1);if(y.length===2)try{let v=await Ft.readFile($e.resolve(o,y[0]),"utf-8"),b=await Ft.readFile($e.resolve(o,y[1]),"utf-8"),{generateDiff:w}=await Promise.resolve().then(()=>(uo(),Ku)),_=w(y[0]+" vs "+y[1],v,b);console.log(eo(_))}catch(v){console.log(Ce(`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(eo(b||"(no changes)"))}catch(v){console.log(Ce(`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=Kn(),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[w,_]of b.sort((E,I)=>I[1]-E[1]))console.log(` @${w}: ${_} invocations`)}console.log();break}case"/delegate":{if(!e.agents.enabled){console.log(B("Multi-agent system is disabled. Enable with /agents on"));break}let y=k[1]?.toLowerCase(),v=k.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(B(`Unknown agent: "${y}". Valid: ${b.join(", ")}`));break}let w=_e.find(_=>_.role===y);if(w){if(!S){console.log(B("Agent runner not initialized. Cannot delegate."));break}console.log(mu("Hablas",w.name,w.title,v)),console.log(Jt(w.name,w.title));let _=s.getOllamaTools(),E=await S.runAgent(y,v,void 0,_);E.success&&E.output?(console.log(Xt(E.output)),i.addAssistantMessage(`[@${w.name}]: ${E.output}`)):E.error?console.log(B(`${w.name} failed: ${E.error}`)):console.log(le(`${w.name} completed without output.`))}break}case"/session":{let y=k[1],v=k.slice(2).join(" "),b=$e.join(po.homedir(),".hablas","sessions");if(y==="save"){let w=v||`session_${Date.now()}`;try{be.existsSync(b)||be.mkdirSync(b,{recursive:!0});let _=i.toJSON(),E=$e.join(b,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);be.writeFileSync(E,_,"utf-8"),console.log(J(`Session saved: "${w}"`))}catch(_){console.log(Ce(`Save failed: ${_.message}`))}}else if(y==="list")try{if(!be.existsSync(b)){console.log(le("No saved sessions"));break}let w=be.readdirSync(b).filter(_=>_.endsWith(".json"));console.log();for(let _ of w){let E=be.statSync($e.join(b,_));console.log(` ${_.replace(".json","")} (${new Date(E.mtime).toLocaleString()})`)}console.log()}catch{console.log(le("No saved sessions"))}else if(y==="load"){let w=v;if(!w){console.log(Ce("Please specify the session label to load: /session load <label>"));break}try{let _=$e.join(b,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);if(!be.existsSync(_)){console.log(Ce(`Session file not found: ${w}`));break}let E=be.readFileSync(_,"utf-8");i.fromJSON(E),console.log(J(`Session successfully loaded: "${w}"`))}catch(_){console.log(Ce(`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(()=>(Et(),jt));if(!y){console.log(B("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(`
282
283
  `+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(E=>E.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 E of _){let I=` @${E.developer_name} [${E.active_section||"idle"}] - ${E.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")+`
283
284
  `),console.log(c.muted(` Verify that "Room Fingerprint" matches on all devices to ensure connectivity.
284
- `));break}case"/msg":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(Tt(),jt));if(!y){console.log(B("Team mode is not active. Use hablas --team to start."));break}let v=A.split(/\s+/),b=v[0],w=v.slice(1).join(" ");if(!b||!w){console.log(B("Usage: /msg <username> <content>"));break}let _=await y.sendMessage(b,w);console.log(_?J(`Message sent to @${b}`):Ce(`Failed to send message to @${b}`));break}default:console.log(Ue(`Unknown: ${x}`,"Type /help for commands"))}}var be,Ft,$e,po,Yn,fo,Wu=N(()=>{"use strict";be=O(require("fs")),Ft=O(require("fs/promises")),$e=O(require("path")),po=O(require("os"));Hn();Bn();bi();_i();Ai();Ri();Mi();mn();Fi();Wn();zi();vn();Xi();iu();xn();Eu();Lu();Yn=`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.
285
+ `));break}case"/msg":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(Et(),jt));if(!y){console.log(B("Team mode is not active. Use hablas --team to start."));break}let v=A.split(/\s+/),b=v[0],w=v.slice(1).join(" ");if(!b||!w){console.log(B("Usage: /msg <username> <content>"));break}let _=await y.sendMessage(b,w);console.log(_?J(`Message sent to @${b}`):Ce(`Failed to send message to @${b}`));break}default:console.log(Ue(`Unknown: ${x}`,"Type /help for commands"))}}var be,Ft,$e,po,Yn,fo,Gu=N(()=>{"use strict";be=O(require("fs")),Ft=O(require("fs/promises")),$e=O(require("path")),po=O(require("os"));Hn();Bn();yi();Si();_i();Ti();Ii();mn();Ni();Wn();Vi();vn();Ji();ou();xn();Tu();Du();Yn=`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.
285
286
 
286
287
  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.
287
288
 
@@ -319,15 +320,15 @@ Your role is to orchestrate, coordinate, and synthesize the work of your special
319
320
  ## Important
320
321
  Never output tool calls as text or JSON in your response.
321
322
  Always use the tool_calls field provided by the API.
322
- If you cannot complete a task, explain why with absolute technical objectivity.`;fo=$e.join(po.homedir(),".hablas","backup")});var Jn=j((fE,Ju)=>{"use strict";var wb=require("path"),ht="\\\\/",Gu=`[^${ht}]`,xb=0,Rt="\\.",Sb="\\+",_b="\\?",Vs="\\/",Ab="(?=.)",Vu="[^/]",ho=`(?:${Vs}|$)`,zu=`(?:^|${Vs})`,mo=`${Rt}{1,2}${ho}`,kb=`(?!${Rt})`,$b=`(?!${zu}${mo})`,Cb=`(?!${Rt}{0,1}${ho})`,Eb=`(?!${mo})`,Tb=`[^.${Vs}]`,Rb=`${Vu}*?`,Yu={DOT_LITERAL:Rt,PLUS_LITERAL:Sb,QMARK_LITERAL:_b,SLASH_LITERAL:Vs,ONE_CHAR:Ab,QMARK:Vu,END_ANCHOR:ho,DOTS_SLASH:mo,NO_DOT:kb,NO_DOTS:$b,NO_DOT_SLASH:Cb,NO_DOTS_SLASH:Eb,QMARK_NO_DOT:Tb,STAR:Rb,START_ANCHOR:zu},Pb={...Yu,SLASH_LITERAL:`[${ht}]`,QMARK:Gu,STAR:`${Gu}*?`,DOTS_SLASH:`${Rt}{1,2}(?:[${ht}]|$)`,NO_DOT:`(?!${Rt})`,NO_DOTS:`(?!(?:^|[${ht}])${Rt}{1,2}(?:[${ht}]|$))`,NO_DOT_SLASH:`(?!${Rt}{0,1}(?:[${ht}]|$))`,NO_DOTS_SLASH:`(?!${Rt}{1,2}(?:[${ht}]|$))`,QMARK_NO_DOT:`[^.${ht}]`,START_ANCHOR:`(?:^|[${ht}])`,END_ANCHOR:`(?:[${ht}]|$)`},Ob={__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"};Ju.exports={DEFAULT_MAX_EXTGLOB_RECURSION:xb,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Ob,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:wb.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?Pb:Yu}}});var zs=j(Me=>{"use strict";var Ib=require("path"),Mb=process.platform==="win32",{REGEX_BACKSLASH:Lb,REGEX_REMOVE_BACKSLASH:Db,REGEX_SPECIAL_CHARS:Nb,REGEX_SPECIAL_CHARS_GLOBAL:Fb}=Jn();Me.isObject=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);Me.hasRegexChars=n=>Nb.test(n);Me.isRegexChar=n=>n.length===1&&Me.hasRegexChars(n);Me.escapeRegex=n=>n.replace(Fb,"\\$1");Me.toPosixSlashes=n=>n.replace(Lb,"/");Me.removeBackslashes=n=>n.replace(Db,e=>e==="\\"?"":e);Me.supportsLookbehinds=()=>{let n=process.version.slice(1).split(".").map(Number);return n.length===3&&n[0]>=9||n[0]===8&&n[1]>=10};Me.isWindows=n=>n&&typeof n.windows=="boolean"?n.windows:Mb===!0||Ib.sep==="\\";Me.escapeLast=(n,e,t)=>{let s=n.lastIndexOf(e,t);return s===-1?n:n[s-1]==="\\"?Me.escapeLast(n,e,s-1):`${n.slice(0,s)}\\${n.slice(s)}`};Me.removePrefix=(n,e={})=>{let t=n;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Me.wrapOutput=(n,e={},t={})=>{let s=t.contains?"":"^",r=t.contains?"":"$",i=`${s}(?:${n})${r}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var rd=j((hE,sd)=>{"use strict";var Xu=zs(),{CHAR_ASTERISK:go,CHAR_AT:jb,CHAR_BACKWARD_SLASH:Xn,CHAR_COMMA:Hb,CHAR_DOT:yo,CHAR_EXCLAMATION_MARK:bo,CHAR_FORWARD_SLASH:nd,CHAR_LEFT_CURLY_BRACE:vo,CHAR_LEFT_PARENTHESES:wo,CHAR_LEFT_SQUARE_BRACKET:Bb,CHAR_PLUS:Ub,CHAR_QUESTION_MARK:Qu,CHAR_RIGHT_CURLY_BRACE:qb,CHAR_RIGHT_PARENTHESES:Zu,CHAR_RIGHT_SQUARE_BRACKET:Kb}=Jn(),ed=n=>n===nd||n===Xn,td=n=>{n.isPrefix!==!0&&(n.depth=n.isGlobstar?1/0:1)},Wb=(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,p=!1,m=!1,h=!1,g=!1,S=!1,k=!1,x=!1,A=!1,y=!1,v=!1,b=0,w,_,E={value:"",depth:0,isGlob:!1},I=()=>u>=s,$=()=>l.charCodeAt(u+1),F=()=>(w=_,l.charCodeAt(++u));for(;u<s;){_=F();let ne;if(_===Xn){x=E.backslashes=!0,_=F(),_===vo&&(k=!0);continue}if(k===!0||_===vo){for(b++;I()!==!0&&(_=F());){if(_===Xn){x=E.backslashes=!0,F();continue}if(_===vo){b++;continue}if(k!==!0&&_===yo&&(_=F())===yo){if(p=E.isBrace=!0,h=E.isGlob=!0,v=!0,r===!0)continue;break}if(k!==!0&&_===Hb){if(p=E.isBrace=!0,h=E.isGlob=!0,v=!0,r===!0)continue;break}if(_===qb&&(b--,b===0)){k=!1,p=E.isBrace=!0,v=!0;break}}if(r===!0)continue;break}if(_===nd){if(i.push(u),o.push(E),E={value:"",depth:0,isGlob:!1},v===!0)continue;if(w===yo&&u===d+1){d+=2;continue}f=u+1;continue}if(t.noext!==!0&&(_===Ub||_===jb||_===go||_===Qu||_===bo)===!0&&$()===wo){if(h=E.isGlob=!0,g=E.isExtglob=!0,v=!0,_===bo&&u===d&&(y=!0),r===!0){for(;I()!==!0&&(_=F());){if(_===Xn){x=E.backslashes=!0,_=F();continue}if(_===Zu){h=E.isGlob=!0,v=!0;break}}continue}break}if(_===go){if(w===go&&(S=E.isGlobstar=!0),h=E.isGlob=!0,v=!0,r===!0)continue;break}if(_===Qu){if(h=E.isGlob=!0,v=!0,r===!0)continue;break}if(_===Bb){for(;I()!==!0&&(ne=F());){if(ne===Xn){x=E.backslashes=!0,F();continue}if(ne===Kb){m=E.isBracket=!0,h=E.isGlob=!0,v=!0;break}}if(r===!0)continue;break}if(t.nonegate!==!0&&_===bo&&u===d){A=E.negated=!0,d++;continue}if(t.noparen!==!0&&_===wo){if(h=E.isGlob=!0,r===!0){for(;I()!==!0&&(_=F());){if(_===wo){x=E.backslashes=!0,_=F();continue}if(_===Zu){v=!0;break}}continue}break}if(h===!0){if(v=!0,r===!0)continue;break}}t.noext===!0&&(g=!1,h=!1);let H=l,X="",T="";d>0&&(X=l.slice(0,d),l=l.slice(d),f-=d),H&&h===!0&&f>0?(H=l.slice(0,f),T=l.slice(f)):h===!0?(H="",T=l):H=l,H&&H!==""&&H!=="/"&&H!==l&&ed(H.charCodeAt(H.length-1))&&(H=H.slice(0,-1)),t.unescape===!0&&(T&&(T=Xu.removeBackslashes(T)),H&&x===!0&&(H=Xu.removeBackslashes(H)));let C={prefix:X,input:n,start:d,base:H,glob:T,isBrace:p,isBracket:m,isGlob:h,isExtglob:g,isGlobstar:S,negated:A,negatedExtglob:y};if(t.tokens===!0&&(C.maxDepth=0,ed(_)||o.push(E),C.tokens=o),t.parts===!0||t.tokens===!0){let ne;for(let D=0;D<i.length;D++){let W=ne?ne+1:d,ie=i[D],ue=n.slice(W,ie);t.tokens&&(D===0&&d!==0?(o[D].isPrefix=!0,o[D].value=X):o[D].value=ue,td(o[D]),C.maxDepth+=o[D].depth),(D!==0||ue!=="")&&a.push(ue),ne=ie}if(ne&&ne+1<n.length){let D=n.slice(ne+1);a.push(D),t.tokens&&(o[o.length-1].value=D,td(o[o.length-1]),C.maxDepth+=o[o.length-1].depth)}C.slashes=i,C.parts=a}return C};sd.exports=Wb});var cd=j((mE,ld)=>{"use strict";var Qn=Jn(),Te=zs(),{MAX_LENGTH:Ys,POSIX_REGEX_SOURCE:Gb,REGEX_NON_SPECIAL_CHARS:Vb,REGEX_SPECIAL_CHARS_BACKREF:zb,REPLACEMENTS:id}=Qn,Yb=(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=>Te.escapeRegex(r)).join("..")}return t},Sn=(n,e)=>`Missing ${n}: "${e}" - use "\\\\${e}" to match literal characters`,od=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},Jb=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},ad=n=>{let e=n.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(Jb(e))return e.replace(/\\(.)/g,"$1")},Xb=n=>{let e=n.map(ad).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},xo=(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}}}}},Qb=n=>{let e=0,t=[];for(;e<n.length;){let r=xo(n.slice(e),!1);if(!r||r.type!=="*")return;let i=od(r.body).map(a=>a.trim());if(i.length!==1)return;let o=ad(i[0]);if(!o||o.length!==1)return;t.push(o),e+=r.end+1}return t.length<1?void 0:`${t.length===1?Te.escapeRegex(t[0]):`[${t.map(r=>Te.escapeRegex(r)).join("")}]`}*`},Zb=n=>{let e=0,t=n.trim(),s=xo(t);for(;s;)e++,t=s.body.trim(),s=xo(t);return e},ev=(n,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Qn.DEFAULT_MAX_EXTGLOB_RECURSION,s=od(n).map(r=>r.trim());if(s.length>1&&(s.some(r=>r==="")||s.some(r=>/^[*?]+$/.test(r))||Xb(s)))return{risky:!0};for(let r of s){let i=Qb(r);if(i)return{risky:!0,safeOutput:i};if(Zb(r)>t)return{risky:!0}}return{risky:!1}},So=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a string");n=id[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=Te.isWindows(e),u=Qn.globChars(l),d=Qn.extglobChars(u),{DOT_LITERAL:f,PLUS_LITERAL:p,SLASH_LITERAL:m,ONE_CHAR:h,DOTS_SLASH:g,NO_DOT:S,NO_DOT_SLASH:k,NO_DOTS_SLASH:x,QMARK:A,QMARK_NO_DOT:y,STAR:v,START_ANCHOR:b}=u,w=P=>`(${a}(?:(?!${b}${P.dot?g:f}).)*?)`,_=t.dot?"":S,E=t.dot?A:y,I=t.bash===!0?w(t):v;t.capture&&(I=`(${I})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let $={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=Te.removePrefix(n,$),r=n.length;let F=[],H=[],X=[],T=i,C,ne=()=>$.index===r-1,D=$.peek=(P=1)=>n[$.index+P],W=$.advance=()=>n[++$.index]||"",ie=()=>n.slice($.index+1),ue=(P="",q=0)=>{$.consumed+=P,$.index+=q},ee=P=>{$.output+=P.output!=null?P.output:P.value,ue(P.value)},ge=()=>{let P=1;for(;D()==="!"&&(D(2)!=="("||D(3)==="?");)W(),$.start++,P++;return P%2===0?!1:($.negated=!0,$.start++,!0)},Ne=P=>{$[P]++,X.push(P)},re=P=>{$[P]--,X.pop()},K=P=>{if(T.type==="globstar"){let q=$.braces>0&&(P.type==="comma"||P.type==="brace"),M=P.extglob===!0||F.length&&(P.type==="pipe"||P.type==="paren");P.type!=="slash"&&P.type!=="paren"&&!q&&!M&&($.output=$.output.slice(0,-T.output.length),T.type="star",T.value="*",T.output=I,$.output+=T.output)}if(F.length&&P.type!=="paren"&&(F[F.length-1].inner+=P.value),(P.value||P.output)&&ee(P),T&&T.type==="text"&&P.type==="text"){T.value+=P.value,T.output=(T.output||"")+P.value;return}P.prev=T,o.push(P),T=P},se=(P,q)=>{let M={...d[q],conditions:1,inner:""};M.prev=T,M.parens=$.parens,M.output=$.output,M.startIndex=$.index,M.tokensIndex=o.length;let G=(t.capture?"(":"")+M.open;Ne("parens"),K({type:P,value:q,output:$.output?"":h}),K({type:"paren",extglob:!0,value:W(),output:G}),F.push(M)},ye=P=>{let q=n.slice(P.startIndex,$.index+1),M=n.slice(P.startIndex+2,$.index),G=ev(M,t);if((P.type==="plus"||P.type==="star")&&G.risky){let Z=G.safeOutput?(P.output?"":h)+(t.capture?`(${G.safeOutput})`:G.safeOutput):void 0,Oe=o[P.tokensIndex];Oe.type="text",Oe.value=q,Oe.output=Z||Te.escapeRegex(q);for(let Se=P.tokensIndex+1;Se<o.length;Se++)o[Se].value="",o[Se].output="",delete o[Se].suffix;$.output=P.output+Oe.output,$.backtrack=!0,K({type:"paren",extglob:!0,value:C,output:""}),re("parens");return}let te=P.close+(t.capture?")":""),V;if(P.type==="negate"){let Z=I;if(P.inner&&P.inner.length>1&&P.inner.includes("/")&&(Z=w(t)),(Z!==I||ne()||/^\)+$/.test(ie()))&&(te=P.close=`)$))${Z}`),P.inner.includes("*")&&(V=ie())&&/^\.[^\\/.]+$/.test(V)){let Oe=So(V,{...e,fastpaths:!1}).output;te=P.close=`)${Oe})${Z})`}P.prev.type==="bos"&&($.negatedExtglob=!0)}K({type:"paren",extglob:!0,value:C,output:te}),re("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(n)){let P=!1,q=n.replace(zb,(M,G,te,V,Z,Oe)=>V==="\\"?(P=!0,M):V==="?"?G?G+V+(Z?A.repeat(Z.length):""):Oe===0?E+(Z?A.repeat(Z.length):""):A.repeat(te.length):V==="."?f.repeat(te.length):V==="*"?G?G+V+(Z?I:""):I:G?M:`\\${M}`);return P===!0&&(t.unescape===!0?q=q.replace(/\\/g,""):q=q.replace(/\\+/g,M=>M.length%2===0?"\\\\":M?"\\":"")),q===n&&t.contains===!0?($.output=n,$):($.output=Te.wrapOutput(q,$,e),$)}for(;!ne();){if(C=W(),C==="\0")continue;if(C==="\\"){let M=D();if(M==="/"&&t.bash!==!0||M==="."||M===";")continue;if(!M){C+="\\",K({type:"text",value:C});continue}let G=/^\\+/.exec(ie()),te=0;if(G&&G[0].length>2&&(te=G[0].length,$.index+=te,te%2!==0&&(C+="\\")),t.unescape===!0?C=W():C+=W(),$.brackets===0){K({type:"text",value:C});continue}}if($.brackets>0&&(C!=="]"||T.value==="["||T.value==="[^")){if(t.posix!==!1&&C===":"){let M=T.value.slice(1);if(M.includes("[")&&(T.posix=!0,M.includes(":"))){let G=T.value.lastIndexOf("["),te=T.value.slice(0,G),V=T.value.slice(G+2),Z=Gb[V];if(Z){T.value=te+Z,$.backtrack=!0,W(),!i.output&&o.indexOf(T)===1&&(i.output=h);continue}}}(C==="["&&D()!==":"||C==="-"&&D()==="]")&&(C=`\\${C}`),C==="]"&&(T.value==="["||T.value==="[^")&&(C=`\\${C}`),t.posix===!0&&C==="!"&&T.value==="["&&(C="^"),T.value+=C,ee({value:C});continue}if($.quotes===1&&C!=='"'){C=Te.escapeRegex(C),T.value+=C,ee({value:C});continue}if(C==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&K({type:"text",value:C});continue}if(C==="("){Ne("parens"),K({type:"paren",value:C});continue}if(C===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Sn("opening","("));let M=F[F.length-1];if(M&&$.parens===M.parens+1){ye(F.pop());continue}K({type:"paren",value:C,output:$.parens?")":"\\)"}),re("parens");continue}if(C==="["){if(t.nobracket===!0||!ie().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Sn("closing","]"));C=`\\${C}`}else Ne("brackets");K({type:"bracket",value:C});continue}if(C==="]"){if(t.nobracket===!0||T&&T.type==="bracket"&&T.value.length===1){K({type:"text",value:C,output:`\\${C}`});continue}if($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Sn("opening","["));K({type:"text",value:C,output:`\\${C}`});continue}re("brackets");let M=T.value.slice(1);if(T.posix!==!0&&M[0]==="^"&&!M.includes("/")&&(C=`/${C}`),T.value+=C,ee({value:C}),t.literalBrackets===!1||Te.hasRegexChars(M))continue;let G=Te.escapeRegex(T.value);if($.output=$.output.slice(0,-T.value.length),t.literalBrackets===!0){$.output+=G,T.value=G;continue}T.value=`(${a}${G}|${T.value})`,$.output+=T.value;continue}if(C==="{"&&t.nobrace!==!0){Ne("braces");let M={type:"brace",value:C,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};H.push(M),K(M);continue}if(C==="}"){let M=H[H.length-1];if(t.nobrace===!0||!M){K({type:"text",value:C,output:C});continue}let G=")";if(M.dots===!0){let te=o.slice(),V=[];for(let Z=te.length-1;Z>=0&&(o.pop(),te[Z].type!=="brace");Z--)te[Z].type!=="dots"&&V.unshift(te[Z].value);G=Yb(V,t),$.backtrack=!0}if(M.comma!==!0&&M.dots!==!0){let te=$.output.slice(0,M.outputIndex),V=$.tokens.slice(M.tokensIndex);M.value=M.output="\\{",C=G="\\}",$.output=te;for(let Z of V)$.output+=Z.output||Z.value}K({type:"brace",value:C,output:G}),re("braces"),H.pop();continue}if(C==="|"){F.length>0&&F[F.length-1].conditions++,K({type:"text",value:C});continue}if(C===","){let M=C,G=H[H.length-1];G&&X[X.length-1]==="braces"&&(G.comma=!0,M="|"),K({type:"comma",value:C,output:M});continue}if(C==="/"){if(T.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),T=i;continue}K({type:"slash",value:C,output:m});continue}if(C==="."){if($.braces>0&&T.type==="dot"){T.value==="."&&(T.output=f);let M=H[H.length-1];T.type="dots",T.output+=C,T.value+=C,M.dots=!0;continue}if($.braces+$.parens===0&&T.type!=="bos"&&T.type!=="slash"){K({type:"text",value:C,output:f});continue}K({type:"dot",value:C,output:f});continue}if(C==="?"){if(!(T&&T.value==="(")&&t.noextglob!==!0&&D()==="("&&D(2)!=="?"){se("qmark",C);continue}if(T&&T.type==="paren"){let G=D(),te=C;if(G==="<"&&!Te.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(T.value==="("&&!/[!=<:]/.test(G)||G==="<"&&!/<([!=]|\w+>)/.test(ie()))&&(te=`\\${C}`),K({type:"text",value:C,output:te});continue}if(t.dot!==!0&&(T.type==="slash"||T.type==="bos")){K({type:"qmark",value:C,output:y});continue}K({type:"qmark",value:C,output:A});continue}if(C==="!"){if(t.noextglob!==!0&&D()==="("&&(D(2)!=="?"||!/[!=<:]/.test(D(3)))){se("negate",C);continue}if(t.nonegate!==!0&&$.index===0){ge();continue}}if(C==="+"){if(t.noextglob!==!0&&D()==="("&&D(2)!=="?"){se("plus",C);continue}if(T&&T.value==="("||t.regex===!1){K({type:"plus",value:C,output:p});continue}if(T&&(T.type==="bracket"||T.type==="paren"||T.type==="brace")||$.parens>0){K({type:"plus",value:C});continue}K({type:"plus",value:p});continue}if(C==="@"){if(t.noextglob!==!0&&D()==="("&&D(2)!=="?"){K({type:"at",extglob:!0,value:C,output:""});continue}K({type:"text",value:C});continue}if(C!=="*"){(C==="$"||C==="^")&&(C=`\\${C}`);let M=Vb.exec(ie());M&&(C+=M[0],$.index+=M[0].length),K({type:"text",value:C});continue}if(T&&(T.type==="globstar"||T.star===!0)){T.type="star",T.star=!0,T.value+=C,T.output=I,$.backtrack=!0,$.globstar=!0,ue(C);continue}let P=ie();if(t.noextglob!==!0&&/^\([^?]/.test(P)){se("star",C);continue}if(T.type==="star"){if(t.noglobstar===!0){ue(C);continue}let M=T.prev,G=M.prev,te=M.type==="slash"||M.type==="bos",V=G&&(G.type==="star"||G.type==="globstar");if(t.bash===!0&&(!te||P[0]&&P[0]!=="/")){K({type:"star",value:C,output:""});continue}let Z=$.braces>0&&(M.type==="comma"||M.type==="brace"),Oe=F.length&&(M.type==="pipe"||M.type==="paren");if(!te&&M.type!=="paren"&&!Z&&!Oe){K({type:"star",value:C,output:""});continue}for(;P.slice(0,3)==="/**";){let Se=n[$.index+4];if(Se&&Se!=="/")break;P=P.slice(3),ue("/**",3)}if(M.type==="bos"&&ne()){T.type="globstar",T.value+=C,T.output=w(t),$.output=T.output,$.globstar=!0,ue(C);continue}if(M.type==="slash"&&M.prev.type!=="bos"&&!V&&ne()){$.output=$.output.slice(0,-(M.output+T.output).length),M.output=`(?:${M.output}`,T.type="globstar",T.output=w(t)+(t.strictSlashes?")":"|$)"),T.value+=C,$.globstar=!0,$.output+=M.output+T.output,ue(C);continue}if(M.type==="slash"&&M.prev.type!=="bos"&&P[0]==="/"){let Se=P[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(M.output+T.output).length),M.output=`(?:${M.output}`,T.type="globstar",T.output=`${w(t)}${m}|${m}${Se})`,T.value+=C,$.output+=M.output+T.output,$.globstar=!0,ue(C+W()),K({type:"slash",value:"/",output:""});continue}if(M.type==="bos"&&P[0]==="/"){T.type="globstar",T.value+=C,T.output=`(?:^|${m}|${w(t)}${m})`,$.output=T.output,$.globstar=!0,ue(C+W()),K({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-T.output.length),T.type="globstar",T.output=w(t),T.value+=C,$.output+=T.output,$.globstar=!0,ue(C);continue}let q={type:"star",value:C,output:I};if(t.bash===!0){q.output=".*?",(T.type==="bos"||T.type==="slash")&&(q.output=_+q.output),K(q);continue}if(T&&(T.type==="bracket"||T.type==="paren")&&t.regex===!0){q.output=C,K(q);continue}($.index===$.start||T.type==="slash"||T.type==="dot")&&(T.type==="dot"?($.output+=k,T.output+=k):t.dot===!0?($.output+=x,T.output+=x):($.output+=_,T.output+=_),D()!=="*"&&($.output+=h,T.output+=h)),K(q)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Sn("closing","]"));$.output=Te.escapeLast($.output,"["),re("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Sn("closing",")"));$.output=Te.escapeLast($.output,"("),re("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Sn("closing","}"));$.output=Te.escapeLast($.output,"{"),re("braces")}if(t.strictSlashes!==!0&&(T.type==="star"||T.type==="bracket")&&K({type:"maybe_slash",value:"",output:`${m}?`}),$.backtrack===!0){$.output="";for(let P of $.tokens)$.output+=P.output!=null?P.output:P.value,P.suffix&&($.output+=P.suffix)}return $};So.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=id[n]||n;let i=Te.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:l,DOTS_SLASH:u,NO_DOT:d,NO_DOTS:f,NO_DOTS_SLASH:p,STAR:m,START_ANCHOR:h}=Qn.globChars(i),g=t.dot?f:d,S=t.dot?p:d,k=t.capture?"":"?:",x={negated:!1,prefix:""},A=t.bash===!0?".*?":m;t.capture&&(A=`(${A})`);let y=_=>_.noglobstar===!0?A:`(${k}(?:(?!${h}${_.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}${S}${A}`;case"**":return g+y(t);case"**/*":return`(?:${g}${y(t)}${a})?${S}${l}${A}`;case"**/*.*":return`(?:${g}${y(t)}${a})?${S}${A}${o}${l}${A}`;case"**/.*":return`(?:${g}${y(t)}${a})?${o}${l}${A}`;default:{let E=/^(.*?)\.(\w+)$/.exec(_);if(!E)return;let I=v(E[1]);return I?I+o+E[2]:void 0}}},b=Te.removePrefix(n,x),w=v(b);return w&&t.strictSlashes!==!0&&(w+=`${a}?`),w};ld.exports=So});var dd=j((gE,ud)=>{"use strict";var tv=require("path"),nv=rd(),_o=cd(),Ao=zs(),sv=Jn(),rv=n=>n&&typeof n=="object"&&!Array.isArray(n),ve=(n,e,t=!1)=>{if(Array.isArray(n)){let d=n.map(p=>ve(p,e,t));return p=>{for(let m of d){let h=m(p);if(h)return h}return!1}}let s=rv(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=Ao.isWindows(e),o=s?ve.compileRe(n,e):ve.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=ve(r.ignore,d,t)}let u=(d,f=!1)=>{let{isMatch:p,match:m,output:h}=ve.test(d,o,e,{glob:n,posix:i}),g={glob:n,state:a,regex:o,posix:i,input:d,output:h,match:m,isMatch:p};return typeof r.onResult=="function"&&r.onResult(g),p===!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};ve.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?Ao.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=ve.matchBase(n,e,t,r):a=e.exec(l)),{isMatch:!!a,match:a,output:l}};ve.matchBase=(n,e,t,s=Ao.isWindows(t))=>(e instanceof RegExp?e:ve.makeRe(e,t)).test(tv.basename(n));ve.isMatch=(n,e,t)=>ve(e,t)(n);ve.parse=(n,e)=>Array.isArray(n)?n.map(t=>ve.parse(t,e)):_o(n,{...e,fastpaths:!1});ve.scan=(n,e)=>nv(n,e);ve.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=ve.toRegex(a,e);return s===!0&&(l.state=n),l};ve.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=_o.fastpaths(n,e)),r.output||(r=_o(n,e)),ve.compileRe(r,e,t,s)};ve.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/$^/}};ve.constants=sv;ud.exports=ve});var ko=j((yE,fd)=>{"use strict";fd.exports=dd()});var wd=j((bE,vd)=>{"use strict";var es=require("fs"),{Readable:iv}=require("stream"),Zn=require("path"),{promisify:Zs}=require("util"),$o=ko(),ov=Zs(es.readdir),av=Zs(es.stat),pd=Zs(es.lstat),lv=Zs(es.realpath),cv="!",yd="READDIRP_RECURSIVE_ERROR",uv=new Set(["ENOENT","EPERM","EACCES","ELOOP",yd]),Co="files",bd="directories",Xs="files_directories",Js="all",hd=[Co,bd,Xs,Js],dv=n=>uv.has(n.code),[md,fv]=process.versions.node.split(".").slice(0,2).map(n=>Number.parseInt(n,10)),pv=process.platform==="win32"&&(md>10||md===10&&fv>=5),gd=n=>{if(n!==void 0){if(typeof n=="function")return n;if(typeof n=="string"){let e=$o(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)===cv?t.push($o(r.slice(1))):e.push($o(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 iv{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:Co,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=gd(t.fileFilter),this._directoryFilter=gd(t.directoryFilter);let i=t.lstat?pd:av;pv?this._stat=o=>i(o,{bigint:!0}):this._stat=i,this._maxDepth=t.depth,this._wantsDir=[bd,Xs,Js].includes(r),this._wantsFile=[Co,Xs,Js].includes(r),this._wantsEverything=r===Js,this._root=Zn.resolve(s),this._isDirent="Dirent"in es&&!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 ov(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=Zn.resolve(Zn.join(t,r));s={path:Zn.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){dv(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 lv(s),i=await pd(r);if(i.isFile())return"file";if(i.isDirectory()){let o=r.length;if(s.startsWith(r)&&s.substr(o,1)===Zn.sep){let a=new Error(`Circular symlink detected: "${s}" points to "${r}"`);return a.code=yd,this._onError(a)}return"directory"}}catch(r){this._onError(r)}}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}},_n=(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&&!hd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${hd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=n,new Qs(e)},hv=(n,e={})=>new Promise((t,s)=>{let r=[];_n(n,e).on("data",i=>r.push(i)).on("end",()=>t(r)).on("error",i=>s(i))});_n.promise=hv;_n.ReaddirpStream=Qs;_n.default=_n;vd.exports=_n});var Eo=j((vE,xd)=>{xd.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 Cd=j((kd,$d)=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var Ad=ko(),mv=Eo(),Sd="!",gv={returnIndex:!1},yv=n=>Array.isArray(n)?n:[n],bv=(n,e)=>{if(typeof n=="function")return n;if(typeof n=="string"){let t=Ad(n,e);return s=>n===s||t(s)}return n instanceof RegExp?t=>n.test(t):t=>!1},_d=(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=mv(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},To=(n,e,t=gv)=>{if(n==null)throw new TypeError("anymatch: specify first argument");let s=typeof t=="boolean"?{returnIndex:t}:t,r=s.returnIndex||!1,i=yv(n),o=i.filter(l=>typeof l=="string"&&l.charAt(0)===Sd).map(l=>l.slice(1)).map(l=>Ad(l,s)),a=i.filter(l=>typeof l!="string"||typeof l=="string"&&l.charAt(0)!==Sd).map(l=>bv(l,s));return e==null?(l,u=!1)=>_d(a,o,l,typeof u=="boolean"?u:!1):_d(a,o,e,r)};To.default=To;$d.exports=To});var Td=j((wE,Ed)=>{Ed.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 Ro=j((xE,Pd)=>{var vv=Td(),Rd={"{":"}","(":")","[":"]"},wv=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=Rd[a];if(l){var u=n.indexOf(l,e);u!==-1&&(e=u+1)}if(n[e]==="!")return!0}else e++}return!1},xv=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=Rd[t];if(s){var r=n.indexOf(s,e);r!==-1&&(e=r+1)}if(n[e]==="!")return!0}else e++}return!1};Pd.exports=function(e,t){if(typeof e!="string"||e==="")return!1;if(vv(e))return!0;var s=wv;return t&&t.strict===!1&&(s=xv),s(e)}});var Id=j((SE,Od)=>{"use strict";var Sv=Ro(),_v=require("path").posix.dirname,Av=require("os").platform()==="win32",Po="/",kv=/\\/g,$v=/[\{\[].*[\}\]]$/,Cv=/(^|[^\\])([\{\[]|\([^\)]+$)/,Ev=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Od.exports=function(e,t){var s=Object.assign({flipBackslashes:!0},t);s.flipBackslashes&&Av&&e.indexOf(Po)<0&&(e=e.replace(kv,Po)),$v.test(e)&&(e+=Po),e+="a";do e=_v(e);while(Sv(e)||Cv.test(e));return e.replace(Ev,"$1")}});var er=j(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 tr=j((AE,Ld)=>{"use strict";var Md=er();Ld.exports=(n,e={})=>{let t=(s,r={})=>{let i=e.escapeInvalid&&Md.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(i||o)&&Md.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 Nd=j((kE,Dd)=>{"use strict";Dd.exports=function(n){return typeof n=="number"?n-n===0:typeof n=="string"&&n.trim()!==""?Number.isFinite?Number.isFinite(+n):isFinite(+n):!1}});var Gd=j(($E,Wd)=>{"use strict";var Fd=Nd(),en=(n,e,t)=>{if(Fd(n)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||n===e)return String(n);if(Fd(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(en.cache.hasOwnProperty(l))return en.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=Kd(n)||Kd(e),p={min:n,max:e,a:u,b:d},m=[],h=[];if(f&&(p.isPadded=f,p.maxLen=String(p.max).length),u<0){let g=d<0?Math.abs(d):1;h=jd(g,Math.abs(u),p,s),u=p.a=0}return d>=0&&(m=jd(u,d,p,s)),p.negatives=h,p.positives=m,p.result=Tv(h,m,s),s.capture===!0?p.result=`(${p.result})`:s.wrap!==!1&&m.length+h.length>1&&(p.result=`(?:${p.result})`),en.cache[l]=p,p.result};function Tv(n,e,t){let s=Oo(n,e,"-",!1,t)||[],r=Oo(e,n,"",!1,t)||[],i=Oo(n,e,"-?",!0,t)||[];return s.concat(i).concat(r).join("|")}function Rv(n,e){let t=1,s=1,r=Bd(n,t),i=new Set([e]);for(;n<=r&&r<=e;)i.add(r),t+=1,r=Bd(n,t);for(r=Ud(e+1,s)-1;n<r&&r<=e;)i.add(r),s+=1,r=Ud(e+1,s)-1;return i=[...i],i.sort(Iv),i}function Pv(n,e,t){if(n===e)return{pattern:n,count:[],digits:0};let s=Ov(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+=Mv(l,u,t):o++}return o&&(i+=t.shorthand===!0?"\\d":"[0-9]"),{pattern:i,count:[o],digits:r}}function jd(n,e,t,s){let r=Rv(n,e),i=[],o=n,a;for(let l=0;l<r.length;l++){let u=r[l],d=Pv(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+qd(a.count),o=u+1;continue}t.isPadded&&(f=Lv(u,t,s)),d.string=f+d.pattern+qd(d.count),i.push(d),o=u+1,a=d}return i}function Oo(n,e,t,s,r){let i=[];for(let o of n){let{string:a}=o;!s&&!Hd(e,"string",a)&&i.push(t+a),s&&Hd(e,"string",a)&&i.push(t+a)}return i}function Ov(n,e){let t=[];for(let s=0;s<n.length;s++)t.push([n[s],e[s]]);return t}function Iv(n,e){return n>e?1:e>n?-1:0}function Hd(n,e,t){return n.some(s=>s[e]===t)}function Bd(n,e){return Number(String(n).slice(0,-e)+"9".repeat(e))}function Ud(n,e){return n-n%Math.pow(10,e)}function qd(n){let[e=0,t=""]=n;return t||e>1?`{${e+(t?","+t:"")}}`:""}function Mv(n,e,t){return`[${n}${e-n===1?"":"-"}${e}]`}function Kd(n){return/^-?(0+)\d/.test(n)}function Lv(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}}`}}en.cache={};en.clearCache=()=>en.cache={};Wd.exports=en});var Lo=j((CE,Zd)=>{"use strict";var Dv=require("util"),zd=Gd(),Vd=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),Nv=n=>e=>n===!0?Number(e):String(e),Io=n=>typeof n=="number"||typeof n=="string"&&n!=="",ts=n=>Number.isInteger(+n),Mo=n=>{let e=`${n}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},Fv=(n,e,t)=>typeof n=="string"||typeof e=="string"?!0:t.stringify===!0,jv=(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},Hv=(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},Yd=(n,e,t,s)=>{if(t)return zd(n,e,{wrap:!1,...s});let r=String.fromCharCode(n);if(n===e)return r;let i=String.fromCharCode(e);return`[${r}-${i}]`},Jd=(n,e,t)=>{if(Array.isArray(n)){let s=t.wrap===!0,r=t.capture?"":"?:";return s?`(${r}${n.join("|")})`:n.join("|")}return zd(n,e,t)},Xd=(...n)=>new RangeError("Invalid range arguments: "+Dv.inspect(...n)),Qd=(n,e,t)=>{if(t.strictRanges===!0)throw Xd([n,e]);return[]},Bv=(n,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${n}" to be a number`);return[]},Uv=(n,e,t=1,s={})=>{let r=Number(n),i=Number(e);if(!Number.isInteger(r)||!Number.isInteger(i)){if(s.strictRanges===!0)throw Xd([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=Mo(a)||Mo(l)||Mo(u),f=d?Math.max(a.length,l.length,u.length):0,p=d===!1&&Fv(n,e,s)===!1,m=s.transform||Nv(p);if(s.toRegex&&t===1)return Yd(sr(n,f),sr(e,f),!0,s);let h={negatives:[],positives:[]},g=x=>h[x<0?"negatives":"positives"].push(Math.abs(x)),S=[],k=0;for(;o?r>=i:r<=i;)s.toRegex===!0&&t>1?g(r):S.push(jv(m(r,k),f,p)),r=o?r-t:r+t,k++;return s.toRegex===!0?t>1?Hv(h,s,f):Jd(S,null,{wrap:!1,...s}):S},qv=(n,e,t=1,s={})=>{if(!ts(n)&&n.length>1||!ts(e)&&e.length>1)return Qd(n,e,s);let r=s.transform||(p=>String.fromCharCode(p)),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 Yd(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?Jd(d,null,{wrap:!1,options:s}):d},nr=(n,e,t,s={})=>{if(e==null&&Io(n))return[n];if(!Io(n)||!Io(e))return Qd(n,e,s);if(typeof t=="function")return nr(n,e,1,{transform:t});if(Vd(t))return nr(n,e,0,t);let r={...s};return r.capture===!0&&(r.wrap=!0),t=t||r.step||1,ts(t)?ts(n)&&ts(e)?Uv(n,e,t,r):qv(n,e,Math.max(Math.abs(t),1),r):t!=null&&!Vd(t)?Bv(t,r):nr(n,e,1,t)};Zd.exports=nr});var nf=j((EE,tf)=>{"use strict";var Kv=Lo(),ef=er(),Wv=(n,e={})=>{let t=(s,r={})=>{let i=ef.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=ef.reduce(s.nodes),f=Kv(...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)};tf.exports=Wv});var of=j((TE,rf)=>{"use strict";var Gv=Lo(),sf=tr(),An=er(),tn=(n="",e="",t=!1)=>{let s=[];if(n=[].concat(n),e=[].concat(e),!e.length)return n;if(!n.length)return t?An.flatten(e).map(r=>`{${r}}`):e;for(let r of n)if(Array.isArray(r))for(let i of r)s.push(tn(i,e,t));else for(let i of e)t===!0&&typeof i=="string"&&(i=`{${i}}`),s.push(Array.isArray(i)?tn(r,i,t):r+i);return An.flatten(s)},Vv=(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(tn(a.pop(),sf(r,e)));return}if(r.type==="brace"&&r.invalid!==!0&&r.nodes.length===2){a.push(tn(a.pop(),["{}"]));return}if(r.nodes&&r.ranges>0){let f=An.reduce(r.nodes);if(An.exceedsLimit(...f,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let p=Gv(...f,e);p.length===0&&(p=sf(r,e)),a.push(tn(a.pop(),p)),r.nodes=[];return}let l=An.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 p=r.nodes[f];if(p.type==="comma"&&r.type==="brace"){f===1&&u.push(""),u.push("");continue}if(p.type==="close"){a.push(tn(a.pop(),u,l));continue}if(p.value&&p.type!=="open"){u.push(tn(u.pop(),p.value));continue}p.nodes&&s(p,r)}return u};return An.flatten(s(n))};rf.exports=Vv});var lf=j((RE,af)=>{"use strict";af.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:`
323
- `,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 pf=j((PE,ff)=>{"use strict";var zv=tr(),{MAX_LENGTH:cf,CHAR_BACKSLASH:Do,CHAR_BACKTICK:Yv,CHAR_COMMA:Jv,CHAR_DOT:Xv,CHAR_LEFT_PARENTHESES:Qv,CHAR_RIGHT_PARENTHESES:Zv,CHAR_LEFT_CURLY_BRACE:ew,CHAR_RIGHT_CURLY_BRACE:tw,CHAR_LEFT_SQUARE_BRACKET:uf,CHAR_RIGHT_SQUARE_BRACKET:df,CHAR_DOUBLE_QUOTE:nw,CHAR_SINGLE_QUOTE:sw,CHAR_NO_BREAK_SPACE:rw,CHAR_ZERO_WIDTH_NOBREAK_SPACE:iw}=lf(),ow=(n,e={})=>{if(typeof n!="string")throw new TypeError("Expected a string");let t=e||{},s=typeof t.maxLength=="number"?Math.min(cf,t.maxLength):cf;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,p,m=()=>n[d++],h=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(h({type:"bos"});d<u;)if(o=i[i.length-1],p=m(),!(p===iw||p===rw)){if(p===Do){h({type:"text",value:(e.keepEscaping?p:"")+m()});continue}if(p===df){h({type:"text",value:"\\"+p});continue}if(p===uf){l++;let g;for(;d<u&&(g=m());){if(p+=g,g===uf){l++;continue}if(g===Do){p+=m();continue}if(g===df&&(l--,l===0))break}h({type:"text",value:p});continue}if(p===Qv){o=h({type:"paren",nodes:[]}),i.push(o),h({type:"text",value:p});continue}if(p===Zv){if(o.type!=="paren"){h({type:"text",value:p});continue}o=i.pop(),h({type:"text",value:p}),o=i[i.length-1];continue}if(p===nw||p===sw||p===Yv){let g=p,S;for(e.keepQuotes!==!0&&(p="");d<u&&(S=m());){if(S===Do){p+=S+m();continue}if(S===g){e.keepQuotes===!0&&(p+=S);break}p+=S}h({type:"text",value:p});continue}if(p===ew){f++;let S={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:f,commas:0,ranges:0,nodes:[]};o=h(S),i.push(o),h({type:"open",value:p});continue}if(p===tw){if(o.type!=="brace"){h({type:"text",value:p});continue}let g="close";o=i.pop(),o.close=!0,h({type:g,value:p}),f--,o=i[i.length-1];continue}if(p===Jv&&f>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:zv(o)}]}h({type:"comma",value:p}),o.commas++;continue}if(p===Xv&&f>0&&o.commas===0){let g=o.nodes;if(f===0||g.length===0){h({type:"text",value:p});continue}if(a.type==="dot"){if(o.range=[],a.value+=p,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 S=g[g.length-1];S.value+=a.value+p,a=S,o.ranges--;continue}h({type:"dot",value:p});continue}h({type:"text",value:p})}do if(o=i.pop(),o.type!=="root"){o.nodes.forEach(k=>{k.nodes||(k.type==="open"&&(k.isOpen=!0),k.type==="close"&&(k.isClose=!0),k.nodes||(k.type="text"),k.invalid=!0)});let g=i[i.length-1],S=g.nodes.indexOf(o);g.nodes.splice(S,1,...o.nodes)}while(i.length>0);return h({type:"eos"}),r};ff.exports=ow});var gf=j((OE,mf)=>{"use strict";var hf=tr(),aw=nf(),lw=of(),cw=pf(),Ke=(n,e={})=>{let t=[];if(Array.isArray(n))for(let s of n){let r=Ke.create(s,e);Array.isArray(r)?t.push(...r):t.push(r)}else t=[].concat(Ke.create(n,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};Ke.parse=(n,e={})=>cw(n,e);Ke.stringify=(n,e={})=>hf(typeof n=="string"?Ke.parse(n,e):n,e);Ke.compile=(n,e={})=>(typeof n=="string"&&(n=Ke.parse(n,e)),aw(n,e));Ke.expand=(n,e={})=>{typeof n=="string"&&(n=Ke.parse(n,e));let t=lw(n,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};Ke.create=(n,e={})=>n===""||n.length<3?[n]:e.expand!==!0?Ke.compile(n,e):Ke.expand(n,e);mf.exports=Ke});var yf=j((IE,uw)=>{uw.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 vf=j((ME,bf)=>{bf.exports=yf()});var xf=j((LE,wf)=>{"use strict";var dw=require("path"),fw=vf(),pw=new Set(fw);wf.exports=n=>pw.has(dw.extname(n).slice(1).toLowerCase())});var rr=j(U=>{"use strict";var{sep:hw}=require("path"),{platform:No}=process,mw=require("os");U.EV_ALL="all";U.EV_READY="ready";U.EV_ADD="add";U.EV_CHANGE="change";U.EV_ADD_DIR="addDir";U.EV_UNLINK="unlink";U.EV_UNLINK_DIR="unlinkDir";U.EV_RAW="raw";U.EV_ERROR="error";U.STR_DATA="data";U.STR_END="end";U.STR_CLOSE="close";U.FSEVENT_CREATED="created";U.FSEVENT_MODIFIED="modified";U.FSEVENT_DELETED="deleted";U.FSEVENT_MOVED="moved";U.FSEVENT_CLONED="cloned";U.FSEVENT_UNKNOWN="unknown";U.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;U.FSEVENT_TYPE_FILE="file";U.FSEVENT_TYPE_DIRECTORY="directory";U.FSEVENT_TYPE_SYMLINK="symlink";U.KEY_LISTENERS="listeners";U.KEY_ERR="errHandlers";U.KEY_RAW="rawEmitters";U.HANDLER_KEYS=[U.KEY_LISTENERS,U.KEY_ERR,U.KEY_RAW];U.DOT_SLASH=`.${hw}`;U.BACK_SLASH_RE=/\\/g;U.DOUBLE_SLASH_RE=/\/\//;U.SLASH_OR_BACK_SLASH_RE=/[/\\]/;U.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;U.REPLACER_RE=/^\.[/\\]/;U.SLASH="/";U.SLASH_SLASH="//";U.BRACE_START="{";U.BANG="!";U.ONE_DOT=".";U.TWO_DOTS="..";U.STAR="*";U.GLOBSTAR="**";U.ROOT_GLOBSTAR="/**/*";U.SLASH_GLOBSTAR="/**";U.DIR_SUFFIX="Dir";U.ANYMATCH_OPTS={dot:!0};U.STRING_TYPE="string";U.FUNCTION_TYPE="function";U.EMPTY_STR="";U.EMPTY_FN=()=>{};U.IDENTITY_FN=n=>n;U.isWindows=No==="win32";U.isMacos=No==="darwin";U.isLinux=No==="linux";U.isIBMi=mw.type()==="OS400"});var Cf=j((NE,$f)=>{"use strict";var Pt=require("fs"),Ae=require("path"),{promisify:is}=require("util"),gw=xf(),{isWindows:yw,isLinux:bw,EMPTY_FN:vw,EMPTY_STR:ww,KEY_LISTENERS:kn,KEY_ERR:Fo,KEY_RAW:ns,HANDLER_KEYS:xw,EV_CHANGE:or,EV_ADD:ir,EV_ADD_DIR:Sw,EV_ERROR:_f,STR_DATA:_w,STR_END:Aw,BRACE_START:kw,STAR:$w}=rr(),Cw="watch",Ew=is(Pt.open),Af=is(Pt.stat),Tw=is(Pt.lstat),Rw=is(Pt.close),jo=is(Pt.realpath),Pw={lstat:Tw,stat:Af},Bo=(n,e)=>{n instanceof Set?n.forEach(e):e(n)},ss=(n,e,t)=>{let s=n[e];s instanceof Set||(n[e]=s=new Set([s])),s.add(t)},Ow=n=>e=>{let t=n[e];t instanceof Set?t.clear():delete n[e]},rs=(n,e,t)=>{let s=n[e];s instanceof Set?s.delete(t):s===t&&delete n[e]},kf=n=>n instanceof Set?n.size===0:!n,ar=new Map;function Sf(n,e,t,s,r){let i=(o,a)=>{t(n),r(o,a,{watchedPath:n}),a&&n!==a&&lr(Ae.resolve(n,a),kn,Ae.join(n,a))};try{return Pt.watch(n,e,i)}catch(o){s(o)}}var lr=(n,e,t,s,r)=>{let i=ar.get(n);i&&Bo(i[e],o=>{o(t,s,r)})},Iw=(n,e,t,s)=>{let{listener:r,errHandler:i,rawEmitter:o}=s,a=ar.get(e),l;if(!t.persistent)return l=Sf(n,t,r,i,o),l.close.bind(l);if(a)ss(a,kn,r),ss(a,Fo,i),ss(a,ns,o);else{if(l=Sf(n,t,lr.bind(null,e,kn),i,lr.bind(null,e,ns)),!l)return;l.on(_f,async u=>{let d=lr.bind(null,e,Fo);if(a.watcherUnusable=!0,yw&&u.code==="EPERM")try{let f=await Ew(n,"r");await Rw(f),d(u)}catch{}else d(u)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:l},ar.set(e,a)}return()=>{rs(a,kn,r),rs(a,Fo,i),rs(a,ns,o),kf(a.listeners)&&(a.watcher.close(),ar.delete(e),xw.forEach(Ow(a)),a.watcher=void 0,Object.freeze(a))}},Ho=new Map,Mw=(n,e,t,s)=>{let{listener:r,rawEmitter:i}=s,o=Ho.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,Pt.unwatchFile(e),o=void 0),o?(ss(o,kn,r),ss(o,ns,i)):(o={listeners:r,rawEmitters:i,options:t,watcher:Pt.watchFile(e,t,(d,f)=>{Bo(o.rawEmitters,m=>{m(or,e,{curr:d,prev:f})});let p=d.mtimeMs;(d.size!==f.size||p>f.mtimeMs||p===0)&&Bo(o.listeners,m=>m(n,d))})},Ho.set(e,o)),()=>{rs(o,kn,r),rs(o,ns,i),kf(o.listeners)&&(Ho.delete(e),Pt.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},Uo=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let s=this.fsw.options,r=Ae.dirname(e),i=Ae.basename(e);this.fsw._getWatchedDir(r).add(i);let a=Ae.resolve(e),l={persistent:s.persistent};t||(t=vw);let u;return s.usePolling?(l.interval=s.enableBinaryInterval&&gw(i)?s.binaryInterval:s.interval,u=Mw(e,a,l,{listener:t,rawEmitter:this.fsw._emitRaw})):u=Iw(e,a,l,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),u}_handleFile(e,t,s){if(this.fsw.closed)return;let r=Ae.dirname(e),i=Ae.basename(e),o=this.fsw._getWatchedDir(r),a=t;if(o.has(i))return;let l=async(d,f)=>{if(this.fsw._throttle(Cw,e,5)){if(!f||f.mtimeMs===0)try{let p=await Af(e);if(this.fsw.closed)return;let m=p.atimeMs,h=p.mtimeMs;(!m||m<=h||h!==a.mtimeMs)&&this.fsw._emit(or,e,p),bw&&a.ino!==p.ino?(this.fsw._closeFile(d),a=p,this.fsw._addPathCloser(d,this._watchWithNodeFs(e,l))):a=p}catch{this.fsw._remove(r,i)}else if(o.has(i)){let p=f.atimeMs,m=f.mtimeMs;(!p||p<=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 jo(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=Ae.join(e,ww),!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(_w,async f=>{if(this.fsw.closed){d=void 0;return}let p=f.path,m=Ae.join(e,p);if(u.add(p),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,m,p))){if(this.fsw.closed){d=void 0;return}(p===r||!r&&!l.has(p))&&(this.fsw._incrReadyCount(),m=Ae.join(i,Ae.relative(i,m)),this._addToNodeFs(m,t,s,o+1))}}).on(_f,this._boundHandleError);return new Promise(f=>d.once(Aw,()=>{if(this.fsw.closed){d=void 0;return}let p=a?a.clear():!1;f(),l.getChildren().filter(m=>m!==e&&!u.has(m)&&(!s.hasGlob||s.filterPath({fullPath:Ae.resolve(e,m)}))).forEach(m=>{this.fsw._remove(e,m)}),d=void 0,p&&this._handleRead(e,!1,s,r,i,o,a)}))}async _handleDir(e,t,s,r,i,o,a){let l=this.fsw._getWatchedDir(Ae.dirname(e)),u=l.has(Ae.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!i&&!u&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(Sw,e,t),l.add(Ae.basename(e)),this.fsw._getWatchedDir(e);let d,f,p=this.fsw.options.depth;if((p==null||r<=p)&&!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,h)=>{h&&h.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 Pw[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($w)&&!e.includes(kw),d;if(l.isDirectory()){let f=Ae.resolve(e),p=u?await jo(e):e;if(this.fsw.closed||(d=await this._handleDir(a.watchPath,l,t,r,i,a,p),this.fsw.closed))return;f!==p&&p!==void 0&&this.fsw._symlinkPaths.set(f,p)}else if(l.isSymbolicLink()){let f=u?await jo(e):e;if(this.fsw.closed)return;let p=Ae.dirname(a.watchPath);if(this.fsw._getWatchedDir(p).add(a.watchPath),this.fsw._emit(ir,a.watchPath,l),d=await this._handleDir(p,l,t,r,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(Ae.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}}};$f.exports=Uo});var Mf=j((FE,Jo)=>{"use strict";var zo=require("fs"),ke=require("path"),{promisify:Yo}=require("util"),$n;try{$n=require("fsevents")}catch(n){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(n)}if($n){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&&($n=void 0)}}var{EV_ADD:qo,EV_CHANGE:Lw,EV_ADD_DIR:Ef,EV_UNLINK:cr,EV_ERROR:Dw,STR_DATA:Nw,STR_END:Fw,FSEVENT_CREATED:jw,FSEVENT_MODIFIED:Hw,FSEVENT_DELETED:Bw,FSEVENT_MOVED:Uw,FSEVENT_UNKNOWN:qw,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:Kw,FSEVENT_TYPE_FILE:Ww,FSEVENT_TYPE_DIRECTORY:os,FSEVENT_TYPE_SYMLINK:If,ROOT_GLOBSTAR:Tf,DIR_SUFFIX:Gw,DOT_SLASH:Rf,FUNCTION_TYPE:Ko,EMPTY_FN:Vw,IDENTITY_FN:zw}=rr(),Yw=n=>isNaN(n)?{}:{depth:n},Go=Yo(zo.stat),Jw=Yo(zo.lstat),Pf=Yo(zo.realpath),Xw={stat:Go,lstat:Jw},nn=new Map,Qw=10,Zw=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),ex=(n,e)=>({stop:$n.watch(n,e)});function tx(n,e,t,s){let r=ke.extname(e)?ke.dirname(e):e,i=ke.dirname(r),o=nn.get(r);nx(i)&&(r=i);let a=ke.resolve(n),l=a!==e,u=(f,p,m)=>{l&&(f=f.replace(e,a)),(f===a||!f.indexOf(a+ke.sep))&&t(f,p,m)},d=!1;for(let f of nn.keys())if(e.indexOf(ke.resolve(f)+ke.sep)===0){r=f,o=nn.get(r),d=!0;break}return o||d?o.listeners.add(u):(o={listeners:new Set([u]),rawEmitter:s,watcher:ex(r,(f,p)=>{if(!o.listeners.size||p&Kw)return;let m=$n.getInfo(f,p);o.listeners.forEach(h=>{h(f,p,m)}),o.rawEmitter(m.event,f,m)})},nn.set(r,o)),()=>{let f=o.listeners;if(f.delete(u),!f.size&&(nn.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var nx=n=>{let e=0;for(let t of nn.keys())if(t.indexOf(n)===0&&(e++,e>=Qw))return!0;return!1},sx=()=>$n&&nn.size<128,Wo=(n,e)=>{let t=0;for(;!n.indexOf(e)&&(n=ke.dirname(n))!==e;)t++;return t},Of=(n,e)=>n.type===os&&e.isDirectory()||n.type===If&&e.isSymbolicLink()||n.type===Ww&&e.isFile(),Vo=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+Tf),!0;s.delete(e),s.delete(e+Tf)}addOrChange(e,t,s,r,i,o,a,l){let u=i.has(o)?Lw:qo;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 Go(e);if(this.fsw.closed)return;Of(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===os;(d||o.has(a))&&this.fsw._remove(i,a,d)}else{if(e===qo){if(l.type===os&&this.fsw._getWatchedDir(t),l.type===If&&u.followSymlinks){let f=u.depth===void 0?void 0:Wo(s,r)+1;return this._addToFsEvents(t,!1,!0,f)}this.fsw._getWatchedDir(i).add(a)}let d=l.type===os?e+Gw:e;this.fsw._emit(d,t),d===Ef&&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=tx(e,t,async(l,u,d)=>{if(this.fsw.closed||i.depth!==void 0&&Wo(l,t)>i.depth)return;let f=s(ke.join(e,ke.relative(e,l)));if(r&&!r(f))return;let p=ke.dirname(f),m=ke.basename(f),h=this.fsw._getWatchedDir(d.type===os?f:p);if(Zw.has(u)||d.event===qw)if(typeof i.ignored===Ko){let g;try{g=await Go(f)}catch{}if(this.fsw.closed||this.checkIgnored(f,g))return;Of(d,g)?this.addOrChange(f,l,t,p,h,m,d,i):this.handleEvent(cr,f,l,t,p,h,m,d,i)}else this.checkExists(f,l,t,p,h,m,d,i);else switch(d.event){case jw:case Hw:return this.addOrChange(f,l,t,p,h,m,d,i);case Bw:case Uw:return this.checkExists(f,l,t,p,h,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 Pf(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!==Rf?a=o.replace(i,e):o!==Rf&&(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?Ef:qo,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===Ko?t:zw,a=this.fsw._getWatchHelpers(e);try{let l=await Xw[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),...Yw(i.depth-(r||0))}).on(Nw,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 p=i.depth===void 0?void 0:Wo(d,ke.resolve(a.watchPath))+1;this._handleFsEventsSymlink(d,f,o,p)}else this.emitAdd(d,u.stats,o,i,s)}).on(Dw,Vw).on(Fw,()=>{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===Ko)this.initWatch(void 0,e,a,o);else{let l;try{l=await Pf(a.watchPath)}catch{}this.initWatch(l,e,a,o)}}};Jo.exports=Vo;Jo.exports.canUse=sx});var Wf=j(da=>{"use strict";var{EventEmitter:rx}=require("events"),ca=require("fs"),oe=require("path"),{promisify:Bf}=require("util"),ix=wd(),na=Cd().default,ox=Id(),Xo=Ro(),ax=gf(),lx=Eo(),cx=Cf(),Lf=Mf(),{EV_ALL:Qo,EV_READY:ux,EV_ADD:ur,EV_CHANGE:as,EV_UNLINK:Df,EV_ADD_DIR:dx,EV_UNLINK_DIR:fx,EV_RAW:px,EV_ERROR:Zo,STR_CLOSE:hx,STR_END:mx,BACK_SLASH_RE:gx,DOUBLE_SLASH_RE:Nf,SLASH_OR_BACK_SLASH_RE:yx,DOT_RE:bx,REPLACER_RE:vx,SLASH:ea,SLASH_SLASH:wx,BRACE_START:xx,BANG:sa,ONE_DOT:Uf,TWO_DOTS:Sx,GLOBSTAR:_x,SLASH_GLOBSTAR:ta,ANYMATCH_OPTS:ra,STRING_TYPE:ua,FUNCTION_TYPE:Ax,EMPTY_STR:ia,EMPTY_FN:kx,isWindows:$x,isMacos:Cx,isIBMi:Ex}=rr(),Tx=Bf(ca.stat),Rx=Bf(ca.readdir),oa=(n=[])=>Array.isArray(n)?n:[n],qf=(n,e=[])=>(n.forEach(t=>{Array.isArray(t)?qf(t,e):e.push(t)}),e),Ff=n=>{let e=qf(oa(n));if(!e.every(t=>typeof t===ua))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Kf)},jf=n=>{let e=n.replace(gx,ea),t=!1;for(e.startsWith(wx)&&(t=!0);e.match(Nf);)e=e.replace(Nf,ea);return t&&(e=ea+e),e},Kf=n=>jf(oe.normalize(jf(n))),Hf=(n=ia)=>e=>typeof e!==ua?e:Kf(oe.isAbsolute(e)?e:oe.join(n,e)),Px=(n,e)=>oe.isAbsolute(n)?n:n.startsWith(sa)?sa+oe.join(e,n.slice(1)):oe.join(e,n),it=(n,e)=>n[e]===void 0,aa=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Uf&&e!==Sx&&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 Rx(s)}catch{this._removeWatcher&&this._removeWatcher(oe.dirname(s),oe.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)}},Ox="stat",Ix="lstat",la=class{constructor(e,t,s,r){this.fsw=r,this.path=e=e.replace(vx,ia),this.watchPath=t,this.fullWatchPath=oe.resolve(t),this.hasGlob=t!==e,e===ia&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&s?void 0:!1,this.globFilter=this.hasGlob?na(e,void 0,ra):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=s,this.statMethod=s?Ox:Ix}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 oe.join(this.watchPath,oe.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===Ax?this.globFilter(s):!0)&&this.fsw._isntIgnored(s,t)&&this.fsw._hasReadPermissions(t)}getDirParts(e){if(!this.hasGlob)return[];let t=[];return(e.includes(xx)?ax.expand(e):[e]).forEach(r=>{t.push(oe.relative(this.watchPath,r).split(yx))}),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===_x&&(s=!0),s||!t[0][o]||na(i,t[0][o],ra))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},dr=class extends rx{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),Lf.canUse()||(t.useFsEvents=!1),it(t,"usePolling")&&!t.useFsEvents&&(t.usePolling=Cx),Ex&&(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=oa(t.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=kx,this._readyEmitted=!0,process.nextTick(()=>this.emit(ux)))},this._emitRaw=(...l)=>this.emit(px,...l),this._readyEmitted=!1,this.options=t,t.useFsEvents?this._fsEventsHandler=new Lf(this):this._nodeFsHandler=new cx(this),Object.freeze(t)}add(e,t,s){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=Ff(e);return r&&(o=o.map(a=>{let l=Px(a,r);return i||!Xo(a)?l:lx(l)})),o=o.filter(a=>a.startsWith(sa)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+ta),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(oe.dirname(l),oe.basename(t||l))})})),this}unwatch(e){if(this.closed)return this;let t=Ff(e),{cwd:s}=this.options;return t.forEach(r=>{!oe.isAbsolute(r)&&!this._closers.has(r)&&(s&&(r=oe.join(s,r)),r=oe.resolve(r)),this._closePath(r),this._ignoredPaths.add(r),this._watched.has(r)&&this._ignoredPaths.add(r+ta),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?oe.relative(this.options.cwd,s):s;e[r||Uf]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(...t),e!==Zo&&this.emit(Qo,...t)}async _emit(e,t,s,r,i){if(this.closed)return;let o=this.options;$x&&(t=oe.normalize(t)),o.cwd&&(t=oe.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===Df)return this._pendingUnlinks.set(t,a),setTimeout(()=>{this._pendingUnlinks.forEach((d,f)=>{this.emit(...d),this.emit(Qo,...d),this._pendingUnlinks.delete(f)})},typeof o.atomic=="number"?o.atomic:100),this;e===ur&&this._pendingUnlinks.has(t)&&(e=a[0]=as,this._pendingUnlinks.delete(t))}if(l&&(e===ur||e===as)&&this._readyEmitted){let d=(f,p)=>{f?(e=a[0]=Zo,a[1]=f,this.emitWithAll(e,a)):p&&(a.length>2?a[2]=p:a.push(p),this.emitWithAll(e,a))};return this._awaitWriteFinish(t,l.stabilityThreshold,e,d),this}if(e===as&&!this._throttle(as,t,50))return this;if(o.alwaysStat&&s===void 0&&(e===ur||e===dx||e===as)){let d=o.cwd?oe.join(o.cwd,t):t,f;try{f=await Tx(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(Zo,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&&!oe.isAbsolute(e)&&(o=oe.join(this.options.cwd,e));let a=new Date,l=u=>{ca.stat(o,(d,f)=>{if(d||!this._pendingWrites.has(e)){d&&d.code!=="ENOENT"&&r(d);return}let p=Number(new Date);u&&f.size!==u.size&&(this._pendingWrites.get(e).lastChange=p);let m=this._pendingWrites.get(e);p-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&&bx.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,r=this.options.ignored,i=r&&r.map(Hf(s)),o=oa(i).filter(l=>typeof l===ua&&!Xo(l)).map(l=>l+ta),a=this._getGlobIgnored().map(Hf(s)).concat(i,o);this._userIgnored=na(a,void 0,ra)}return this._userIgnored([e,t])}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e,t){let s=t||this.options.disableGlobbing||!Xo(e)?e:ox(e),r=this.options.followSymlinks;return new la(e,s,r,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let t=oe.resolve(e);return this._watched.has(t)||this._watched.set(t,new aa(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=oe.join(e,t),i=oe.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(p=>this._remove(r,p));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=oe.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?fx:Df;u&&!this._isIgnored(r)&&this._emit(f,r),this.options.useFsEvents||this._closePath(r)}_closePath(e){this._closeFile(e);let t=oe.dirname(e);this._getWatchedDir(t).remove(oe.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:Qo,alwaysStat:!0,lstat:!0,...t},r=ix(e,s);return this._streams.add(r),r.once(hx,()=>{r=void 0}),r.once(mx,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};da.FSWatcher=dr;var Mx=(n,e)=>{let t=new dr(e);return t.add(n),t};da.watch=Mx});var Yf={};Fe(Yf,{CollaborationManager:()=>ls,addTeamMember:()=>Nx,formatTeamConfig:()=>Fx,initTeamConfig:()=>Dx,loadTeamConfig:()=>Lx,saveTeamConfig:()=>zf});function Lx(n){let e=Je.join(n,".hablas","team.json");if(we.existsSync(e))try{return JSON.parse(we.readFileSync(e,"utf-8"))}catch{return null}return null}function Dx(n,e){let t={name:e,members:[]};return zf(n,t),t}function zf(n,e){let t=Je.join(n,".hablas","team.json"),s=Je.dirname(t);we.existsSync(s)||we.mkdirSync(s,{recursive:!0}),we.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}function Nx(n,e,t){return n.members.push({name:e,email:t}),n}function Fx(n){return[`Team: ${n.name}`,"Members:",...n.members.map(t=>` - ${t.name} (${t.email})`)].join(`
324
- `)}var we,Je,fr,Gf,Vf,ls,fa=N(()=>{"use strict";we=O(require("fs")),Je=O(require("path")),fr=O(require("os")),Gf=O(require("crypto")),Vf=O(Wf());xn();ls=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=Je.join(this.workingDir,".hablas","collaboration.json");let i=this.getProjectIdentifier();console.log(`
325
- ${c.muted("[Debug] Project Context:")} ${c.highlight(i)}`),this.projectTeamToken=Gf.createHash("sha256").update(`${i}:${this.teamKey}`).digest("hex"),console.log(` ${c.muted("[Debug] Session Fingerprint:")} ${c.muted(this.projectTeamToken.slice(0,16))}...
323
+ If you cannot complete a task, explain why with absolute technical objectivity.`;fo=$e.join(po.homedir(),".hablas","backup")});var Jn=j((hE,Xu)=>{"use strict";var Sb=require("path"),pt="\\\\/",Vu=`[^${pt}]`,_b=0,Tt="\\.",Ab="\\+",kb="\\?",Vs="\\/",$b="(?=.)",zu="[^/]",ho=`(?:${Vs}|$)`,Yu=`(?:^|${Vs})`,mo=`${Tt}{1,2}${ho}`,Cb=`(?!${Tt})`,Eb=`(?!${Yu}${mo})`,Tb=`(?!${Tt}{0,1}${ho})`,Rb=`(?!${mo})`,Pb=`[^.${Vs}]`,Ob=`${zu}*?`,Ju={DOT_LITERAL:Tt,PLUS_LITERAL:Ab,QMARK_LITERAL:kb,SLASH_LITERAL:Vs,ONE_CHAR:$b,QMARK:zu,END_ANCHOR:ho,DOTS_SLASH:mo,NO_DOT:Cb,NO_DOTS:Eb,NO_DOT_SLASH:Tb,NO_DOTS_SLASH:Rb,QMARK_NO_DOT:Pb,STAR:Ob,START_ANCHOR:Yu},Ib={...Ju,SLASH_LITERAL:`[${pt}]`,QMARK:Vu,STAR:`${Vu}*?`,DOTS_SLASH:`${Tt}{1,2}(?:[${pt}]|$)`,NO_DOT:`(?!${Tt})`,NO_DOTS:`(?!(?:^|[${pt}])${Tt}{1,2}(?:[${pt}]|$))`,NO_DOT_SLASH:`(?!${Tt}{0,1}(?:[${pt}]|$))`,NO_DOTS_SLASH:`(?!${Tt}{1,2}(?:[${pt}]|$))`,QMARK_NO_DOT:`[^.${pt}]`,START_ANCHOR:`(?:^|[${pt}])`,END_ANCHOR:`(?:[${pt}]|$)`},Mb={__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"};Xu.exports={DEFAULT_MAX_EXTGLOB_RECURSION:_b,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Mb,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:Sb.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?Ib:Ju}}});var zs=j(Le=>{"use strict";var Lb=require("path"),Db=process.platform==="win32",{REGEX_BACKSLASH:Nb,REGEX_REMOVE_BACKSLASH:Fb,REGEX_SPECIAL_CHARS:jb,REGEX_SPECIAL_CHARS_GLOBAL:Hb}=Jn();Le.isObject=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);Le.hasRegexChars=n=>jb.test(n);Le.isRegexChar=n=>n.length===1&&Le.hasRegexChars(n);Le.escapeRegex=n=>n.replace(Hb,"\\$1");Le.toPosixSlashes=n=>n.replace(Nb,"/");Le.removeBackslashes=n=>n.replace(Fb,e=>e==="\\"?"":e);Le.supportsLookbehinds=()=>{let n=process.version.slice(1).split(".").map(Number);return n.length===3&&n[0]>=9||n[0]===8&&n[1]>=10};Le.isWindows=n=>n&&typeof n.windows=="boolean"?n.windows:Db===!0||Lb.sep==="\\";Le.escapeLast=(n,e,t)=>{let s=n.lastIndexOf(e,t);return s===-1?n:n[s-1]==="\\"?Le.escapeLast(n,e,s-1):`${n.slice(0,s)}\\${n.slice(s)}`};Le.removePrefix=(n,e={})=>{let t=n;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Le.wrapOutput=(n,e={},t={})=>{let s=t.contains?"":"^",r=t.contains?"":"$",i=`${s}(?:${n})${r}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var id=j((gE,rd)=>{"use strict";var Qu=zs(),{CHAR_ASTERISK:go,CHAR_AT:Bb,CHAR_BACKWARD_SLASH:Xn,CHAR_COMMA:Ub,CHAR_DOT:yo,CHAR_EXCLAMATION_MARK:bo,CHAR_FORWARD_SLASH:sd,CHAR_LEFT_CURLY_BRACE:vo,CHAR_LEFT_PARENTHESES:wo,CHAR_LEFT_SQUARE_BRACKET:qb,CHAR_PLUS:Kb,CHAR_QUESTION_MARK:Zu,CHAR_RIGHT_CURLY_BRACE:Wb,CHAR_RIGHT_PARENTHESES:ed,CHAR_RIGHT_SQUARE_BRACKET:Gb}=Jn(),td=n=>n===sd||n===Xn,nd=n=>{n.isPrefix!==!0&&(n.depth=n.isGlobstar?1/0:1)},Vb=(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,p=!1,m=!1,h=!1,g=!1,S=!1,k=!1,x=!1,A=!1,y=!1,v=!1,b=0,w,_,E={value:"",depth:0,isGlob:!1},I=()=>u>=s,$=()=>l.charCodeAt(u+1),F=()=>(w=_,l.charCodeAt(++u));for(;u<s;){_=F();let ne;if(_===Xn){x=E.backslashes=!0,_=F(),_===vo&&(k=!0);continue}if(k===!0||_===vo){for(b++;I()!==!0&&(_=F());){if(_===Xn){x=E.backslashes=!0,F();continue}if(_===vo){b++;continue}if(k!==!0&&_===yo&&(_=F())===yo){if(p=E.isBrace=!0,h=E.isGlob=!0,v=!0,r===!0)continue;break}if(k!==!0&&_===Ub){if(p=E.isBrace=!0,h=E.isGlob=!0,v=!0,r===!0)continue;break}if(_===Wb&&(b--,b===0)){k=!1,p=E.isBrace=!0,v=!0;break}}if(r===!0)continue;break}if(_===sd){if(i.push(u),o.push(E),E={value:"",depth:0,isGlob:!1},v===!0)continue;if(w===yo&&u===d+1){d+=2;continue}f=u+1;continue}if(t.noext!==!0&&(_===Kb||_===Bb||_===go||_===Zu||_===bo)===!0&&$()===wo){if(h=E.isGlob=!0,g=E.isExtglob=!0,v=!0,_===bo&&u===d&&(y=!0),r===!0){for(;I()!==!0&&(_=F());){if(_===Xn){x=E.backslashes=!0,_=F();continue}if(_===ed){h=E.isGlob=!0,v=!0;break}}continue}break}if(_===go){if(w===go&&(S=E.isGlobstar=!0),h=E.isGlob=!0,v=!0,r===!0)continue;break}if(_===Zu){if(h=E.isGlob=!0,v=!0,r===!0)continue;break}if(_===qb){for(;I()!==!0&&(ne=F());){if(ne===Xn){x=E.backslashes=!0,F();continue}if(ne===Gb){m=E.isBracket=!0,h=E.isGlob=!0,v=!0;break}}if(r===!0)continue;break}if(t.nonegate!==!0&&_===bo&&u===d){A=E.negated=!0,d++;continue}if(t.noparen!==!0&&_===wo){if(h=E.isGlob=!0,r===!0){for(;I()!==!0&&(_=F());){if(_===wo){x=E.backslashes=!0,_=F();continue}if(_===ed){v=!0;break}}continue}break}if(h===!0){if(v=!0,r===!0)continue;break}}t.noext===!0&&(g=!1,h=!1);let H=l,X="",T="";d>0&&(X=l.slice(0,d),l=l.slice(d),f-=d),H&&h===!0&&f>0?(H=l.slice(0,f),T=l.slice(f)):h===!0?(H="",T=l):H=l,H&&H!==""&&H!=="/"&&H!==l&&td(H.charCodeAt(H.length-1))&&(H=H.slice(0,-1)),t.unescape===!0&&(T&&(T=Qu.removeBackslashes(T)),H&&x===!0&&(H=Qu.removeBackslashes(H)));let C={prefix:X,input:n,start:d,base:H,glob:T,isBrace:p,isBracket:m,isGlob:h,isExtglob:g,isGlobstar:S,negated:A,negatedExtglob:y};if(t.tokens===!0&&(C.maxDepth=0,td(_)||o.push(E),C.tokens=o),t.parts===!0||t.tokens===!0){let ne;for(let D=0;D<i.length;D++){let W=ne?ne+1:d,ie=i[D],ue=n.slice(W,ie);t.tokens&&(D===0&&d!==0?(o[D].isPrefix=!0,o[D].value=X):o[D].value=ue,nd(o[D]),C.maxDepth+=o[D].depth),(D!==0||ue!=="")&&a.push(ue),ne=ie}if(ne&&ne+1<n.length){let D=n.slice(ne+1);a.push(D),t.tokens&&(o[o.length-1].value=D,nd(o[o.length-1]),C.maxDepth+=o[o.length-1].depth)}C.slashes=i,C.parts=a}return C};rd.exports=Vb});var ud=j((yE,cd)=>{"use strict";var Qn=Jn(),Te=zs(),{MAX_LENGTH:Ys,POSIX_REGEX_SOURCE:zb,REGEX_NON_SPECIAL_CHARS:Yb,REGEX_SPECIAL_CHARS_BACKREF:Jb,REPLACEMENTS:od}=Qn,Xb=(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=>Te.escapeRegex(r)).join("..")}return t},Sn=(n,e)=>`Missing ${n}: "${e}" - use "\\\\${e}" to match literal characters`,ad=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},Qb=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},ld=n=>{let e=n.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(Qb(e))return e.replace(/\\(.)/g,"$1")},Zb=n=>{let e=n.map(ld).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},xo=(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}}}}},ev=n=>{let e=0,t=[];for(;e<n.length;){let r=xo(n.slice(e),!1);if(!r||r.type!=="*")return;let i=ad(r.body).map(a=>a.trim());if(i.length!==1)return;let o=ld(i[0]);if(!o||o.length!==1)return;t.push(o),e+=r.end+1}return t.length<1?void 0:`${t.length===1?Te.escapeRegex(t[0]):`[${t.map(r=>Te.escapeRegex(r)).join("")}]`}*`},tv=n=>{let e=0,t=n.trim(),s=xo(t);for(;s;)e++,t=s.body.trim(),s=xo(t);return e},nv=(n,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Qn.DEFAULT_MAX_EXTGLOB_RECURSION,s=ad(n).map(r=>r.trim());if(s.length>1&&(s.some(r=>r==="")||s.some(r=>/^[*?]+$/.test(r))||Zb(s)))return{risky:!0};for(let r of s){let i=ev(r);if(i)return{risky:!0,safeOutput:i};if(tv(r)>t)return{risky:!0}}return{risky:!1}},So=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a string");n=od[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=Te.isWindows(e),u=Qn.globChars(l),d=Qn.extglobChars(u),{DOT_LITERAL:f,PLUS_LITERAL:p,SLASH_LITERAL:m,ONE_CHAR:h,DOTS_SLASH:g,NO_DOT:S,NO_DOT_SLASH:k,NO_DOTS_SLASH:x,QMARK:A,QMARK_NO_DOT:y,STAR:v,START_ANCHOR:b}=u,w=P=>`(${a}(?:(?!${b}${P.dot?g:f}).)*?)`,_=t.dot?"":S,E=t.dot?A:y,I=t.bash===!0?w(t):v;t.capture&&(I=`(${I})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let $={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=Te.removePrefix(n,$),r=n.length;let F=[],H=[],X=[],T=i,C,ne=()=>$.index===r-1,D=$.peek=(P=1)=>n[$.index+P],W=$.advance=()=>n[++$.index]||"",ie=()=>n.slice($.index+1),ue=(P="",q=0)=>{$.consumed+=P,$.index+=q},ee=P=>{$.output+=P.output!=null?P.output:P.value,ue(P.value)},ge=()=>{let P=1;for(;D()==="!"&&(D(2)!=="("||D(3)==="?");)W(),$.start++,P++;return P%2===0?!1:($.negated=!0,$.start++,!0)},Fe=P=>{$[P]++,X.push(P)},re=P=>{$[P]--,X.pop()},K=P=>{if(T.type==="globstar"){let q=$.braces>0&&(P.type==="comma"||P.type==="brace"),M=P.extglob===!0||F.length&&(P.type==="pipe"||P.type==="paren");P.type!=="slash"&&P.type!=="paren"&&!q&&!M&&($.output=$.output.slice(0,-T.output.length),T.type="star",T.value="*",T.output=I,$.output+=T.output)}if(F.length&&P.type!=="paren"&&(F[F.length-1].inner+=P.value),(P.value||P.output)&&ee(P),T&&T.type==="text"&&P.type==="text"){T.value+=P.value,T.output=(T.output||"")+P.value;return}P.prev=T,o.push(P),T=P},se=(P,q)=>{let M={...d[q],conditions:1,inner:""};M.prev=T,M.parens=$.parens,M.output=$.output,M.startIndex=$.index,M.tokensIndex=o.length;let G=(t.capture?"(":"")+M.open;Fe("parens"),K({type:P,value:q,output:$.output?"":h}),K({type:"paren",extglob:!0,value:W(),output:G}),F.push(M)},ye=P=>{let q=n.slice(P.startIndex,$.index+1),M=n.slice(P.startIndex+2,$.index),G=nv(M,t);if((P.type==="plus"||P.type==="star")&&G.risky){let Z=G.safeOutput?(P.output?"":h)+(t.capture?`(${G.safeOutput})`:G.safeOutput):void 0,Oe=o[P.tokensIndex];Oe.type="text",Oe.value=q,Oe.output=Z||Te.escapeRegex(q);for(let Se=P.tokensIndex+1;Se<o.length;Se++)o[Se].value="",o[Se].output="",delete o[Se].suffix;$.output=P.output+Oe.output,$.backtrack=!0,K({type:"paren",extglob:!0,value:C,output:""}),re("parens");return}let te=P.close+(t.capture?")":""),V;if(P.type==="negate"){let Z=I;if(P.inner&&P.inner.length>1&&P.inner.includes("/")&&(Z=w(t)),(Z!==I||ne()||/^\)+$/.test(ie()))&&(te=P.close=`)$))${Z}`),P.inner.includes("*")&&(V=ie())&&/^\.[^\\/.]+$/.test(V)){let Oe=So(V,{...e,fastpaths:!1}).output;te=P.close=`)${Oe})${Z})`}P.prev.type==="bos"&&($.negatedExtglob=!0)}K({type:"paren",extglob:!0,value:C,output:te}),re("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(n)){let P=!1,q=n.replace(Jb,(M,G,te,V,Z,Oe)=>V==="\\"?(P=!0,M):V==="?"?G?G+V+(Z?A.repeat(Z.length):""):Oe===0?E+(Z?A.repeat(Z.length):""):A.repeat(te.length):V==="."?f.repeat(te.length):V==="*"?G?G+V+(Z?I:""):I:G?M:`\\${M}`);return P===!0&&(t.unescape===!0?q=q.replace(/\\/g,""):q=q.replace(/\\+/g,M=>M.length%2===0?"\\\\":M?"\\":"")),q===n&&t.contains===!0?($.output=n,$):($.output=Te.wrapOutput(q,$,e),$)}for(;!ne();){if(C=W(),C==="\0")continue;if(C==="\\"){let M=D();if(M==="/"&&t.bash!==!0||M==="."||M===";")continue;if(!M){C+="\\",K({type:"text",value:C});continue}let G=/^\\+/.exec(ie()),te=0;if(G&&G[0].length>2&&(te=G[0].length,$.index+=te,te%2!==0&&(C+="\\")),t.unescape===!0?C=W():C+=W(),$.brackets===0){K({type:"text",value:C});continue}}if($.brackets>0&&(C!=="]"||T.value==="["||T.value==="[^")){if(t.posix!==!1&&C===":"){let M=T.value.slice(1);if(M.includes("[")&&(T.posix=!0,M.includes(":"))){let G=T.value.lastIndexOf("["),te=T.value.slice(0,G),V=T.value.slice(G+2),Z=zb[V];if(Z){T.value=te+Z,$.backtrack=!0,W(),!i.output&&o.indexOf(T)===1&&(i.output=h);continue}}}(C==="["&&D()!==":"||C==="-"&&D()==="]")&&(C=`\\${C}`),C==="]"&&(T.value==="["||T.value==="[^")&&(C=`\\${C}`),t.posix===!0&&C==="!"&&T.value==="["&&(C="^"),T.value+=C,ee({value:C});continue}if($.quotes===1&&C!=='"'){C=Te.escapeRegex(C),T.value+=C,ee({value:C});continue}if(C==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&K({type:"text",value:C});continue}if(C==="("){Fe("parens"),K({type:"paren",value:C});continue}if(C===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Sn("opening","("));let M=F[F.length-1];if(M&&$.parens===M.parens+1){ye(F.pop());continue}K({type:"paren",value:C,output:$.parens?")":"\\)"}),re("parens");continue}if(C==="["){if(t.nobracket===!0||!ie().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Sn("closing","]"));C=`\\${C}`}else Fe("brackets");K({type:"bracket",value:C});continue}if(C==="]"){if(t.nobracket===!0||T&&T.type==="bracket"&&T.value.length===1){K({type:"text",value:C,output:`\\${C}`});continue}if($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Sn("opening","["));K({type:"text",value:C,output:`\\${C}`});continue}re("brackets");let M=T.value.slice(1);if(T.posix!==!0&&M[0]==="^"&&!M.includes("/")&&(C=`/${C}`),T.value+=C,ee({value:C}),t.literalBrackets===!1||Te.hasRegexChars(M))continue;let G=Te.escapeRegex(T.value);if($.output=$.output.slice(0,-T.value.length),t.literalBrackets===!0){$.output+=G,T.value=G;continue}T.value=`(${a}${G}|${T.value})`,$.output+=T.value;continue}if(C==="{"&&t.nobrace!==!0){Fe("braces");let M={type:"brace",value:C,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};H.push(M),K(M);continue}if(C==="}"){let M=H[H.length-1];if(t.nobrace===!0||!M){K({type:"text",value:C,output:C});continue}let G=")";if(M.dots===!0){let te=o.slice(),V=[];for(let Z=te.length-1;Z>=0&&(o.pop(),te[Z].type!=="brace");Z--)te[Z].type!=="dots"&&V.unshift(te[Z].value);G=Xb(V,t),$.backtrack=!0}if(M.comma!==!0&&M.dots!==!0){let te=$.output.slice(0,M.outputIndex),V=$.tokens.slice(M.tokensIndex);M.value=M.output="\\{",C=G="\\}",$.output=te;for(let Z of V)$.output+=Z.output||Z.value}K({type:"brace",value:C,output:G}),re("braces"),H.pop();continue}if(C==="|"){F.length>0&&F[F.length-1].conditions++,K({type:"text",value:C});continue}if(C===","){let M=C,G=H[H.length-1];G&&X[X.length-1]==="braces"&&(G.comma=!0,M="|"),K({type:"comma",value:C,output:M});continue}if(C==="/"){if(T.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),T=i;continue}K({type:"slash",value:C,output:m});continue}if(C==="."){if($.braces>0&&T.type==="dot"){T.value==="."&&(T.output=f);let M=H[H.length-1];T.type="dots",T.output+=C,T.value+=C,M.dots=!0;continue}if($.braces+$.parens===0&&T.type!=="bos"&&T.type!=="slash"){K({type:"text",value:C,output:f});continue}K({type:"dot",value:C,output:f});continue}if(C==="?"){if(!(T&&T.value==="(")&&t.noextglob!==!0&&D()==="("&&D(2)!=="?"){se("qmark",C);continue}if(T&&T.type==="paren"){let G=D(),te=C;if(G==="<"&&!Te.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(T.value==="("&&!/[!=<:]/.test(G)||G==="<"&&!/<([!=]|\w+>)/.test(ie()))&&(te=`\\${C}`),K({type:"text",value:C,output:te});continue}if(t.dot!==!0&&(T.type==="slash"||T.type==="bos")){K({type:"qmark",value:C,output:y});continue}K({type:"qmark",value:C,output:A});continue}if(C==="!"){if(t.noextglob!==!0&&D()==="("&&(D(2)!=="?"||!/[!=<:]/.test(D(3)))){se("negate",C);continue}if(t.nonegate!==!0&&$.index===0){ge();continue}}if(C==="+"){if(t.noextglob!==!0&&D()==="("&&D(2)!=="?"){se("plus",C);continue}if(T&&T.value==="("||t.regex===!1){K({type:"plus",value:C,output:p});continue}if(T&&(T.type==="bracket"||T.type==="paren"||T.type==="brace")||$.parens>0){K({type:"plus",value:C});continue}K({type:"plus",value:p});continue}if(C==="@"){if(t.noextglob!==!0&&D()==="("&&D(2)!=="?"){K({type:"at",extglob:!0,value:C,output:""});continue}K({type:"text",value:C});continue}if(C!=="*"){(C==="$"||C==="^")&&(C=`\\${C}`);let M=Yb.exec(ie());M&&(C+=M[0],$.index+=M[0].length),K({type:"text",value:C});continue}if(T&&(T.type==="globstar"||T.star===!0)){T.type="star",T.star=!0,T.value+=C,T.output=I,$.backtrack=!0,$.globstar=!0,ue(C);continue}let P=ie();if(t.noextglob!==!0&&/^\([^?]/.test(P)){se("star",C);continue}if(T.type==="star"){if(t.noglobstar===!0){ue(C);continue}let M=T.prev,G=M.prev,te=M.type==="slash"||M.type==="bos",V=G&&(G.type==="star"||G.type==="globstar");if(t.bash===!0&&(!te||P[0]&&P[0]!=="/")){K({type:"star",value:C,output:""});continue}let Z=$.braces>0&&(M.type==="comma"||M.type==="brace"),Oe=F.length&&(M.type==="pipe"||M.type==="paren");if(!te&&M.type!=="paren"&&!Z&&!Oe){K({type:"star",value:C,output:""});continue}for(;P.slice(0,3)==="/**";){let Se=n[$.index+4];if(Se&&Se!=="/")break;P=P.slice(3),ue("/**",3)}if(M.type==="bos"&&ne()){T.type="globstar",T.value+=C,T.output=w(t),$.output=T.output,$.globstar=!0,ue(C);continue}if(M.type==="slash"&&M.prev.type!=="bos"&&!V&&ne()){$.output=$.output.slice(0,-(M.output+T.output).length),M.output=`(?:${M.output}`,T.type="globstar",T.output=w(t)+(t.strictSlashes?")":"|$)"),T.value+=C,$.globstar=!0,$.output+=M.output+T.output,ue(C);continue}if(M.type==="slash"&&M.prev.type!=="bos"&&P[0]==="/"){let Se=P[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(M.output+T.output).length),M.output=`(?:${M.output}`,T.type="globstar",T.output=`${w(t)}${m}|${m}${Se})`,T.value+=C,$.output+=M.output+T.output,$.globstar=!0,ue(C+W()),K({type:"slash",value:"/",output:""});continue}if(M.type==="bos"&&P[0]==="/"){T.type="globstar",T.value+=C,T.output=`(?:^|${m}|${w(t)}${m})`,$.output=T.output,$.globstar=!0,ue(C+W()),K({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-T.output.length),T.type="globstar",T.output=w(t),T.value+=C,$.output+=T.output,$.globstar=!0,ue(C);continue}let q={type:"star",value:C,output:I};if(t.bash===!0){q.output=".*?",(T.type==="bos"||T.type==="slash")&&(q.output=_+q.output),K(q);continue}if(T&&(T.type==="bracket"||T.type==="paren")&&t.regex===!0){q.output=C,K(q);continue}($.index===$.start||T.type==="slash"||T.type==="dot")&&(T.type==="dot"?($.output+=k,T.output+=k):t.dot===!0?($.output+=x,T.output+=x):($.output+=_,T.output+=_),D()!=="*"&&($.output+=h,T.output+=h)),K(q)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Sn("closing","]"));$.output=Te.escapeLast($.output,"["),re("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Sn("closing",")"));$.output=Te.escapeLast($.output,"("),re("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Sn("closing","}"));$.output=Te.escapeLast($.output,"{"),re("braces")}if(t.strictSlashes!==!0&&(T.type==="star"||T.type==="bracket")&&K({type:"maybe_slash",value:"",output:`${m}?`}),$.backtrack===!0){$.output="";for(let P of $.tokens)$.output+=P.output!=null?P.output:P.value,P.suffix&&($.output+=P.suffix)}return $};So.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=od[n]||n;let i=Te.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:l,DOTS_SLASH:u,NO_DOT:d,NO_DOTS:f,NO_DOTS_SLASH:p,STAR:m,START_ANCHOR:h}=Qn.globChars(i),g=t.dot?f:d,S=t.dot?p:d,k=t.capture?"":"?:",x={negated:!1,prefix:""},A=t.bash===!0?".*?":m;t.capture&&(A=`(${A})`);let y=_=>_.noglobstar===!0?A:`(${k}(?:(?!${h}${_.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}${S}${A}`;case"**":return g+y(t);case"**/*":return`(?:${g}${y(t)}${a})?${S}${l}${A}`;case"**/*.*":return`(?:${g}${y(t)}${a})?${S}${A}${o}${l}${A}`;case"**/.*":return`(?:${g}${y(t)}${a})?${o}${l}${A}`;default:{let E=/^(.*?)\.(\w+)$/.exec(_);if(!E)return;let I=v(E[1]);return I?I+o+E[2]:void 0}}},b=Te.removePrefix(n,x),w=v(b);return w&&t.strictSlashes!==!0&&(w+=`${a}?`),w};cd.exports=So});var fd=j((bE,dd)=>{"use strict";var sv=require("path"),rv=id(),_o=ud(),Ao=zs(),iv=Jn(),ov=n=>n&&typeof n=="object"&&!Array.isArray(n),ve=(n,e,t=!1)=>{if(Array.isArray(n)){let d=n.map(p=>ve(p,e,t));return p=>{for(let m of d){let h=m(p);if(h)return h}return!1}}let s=ov(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=Ao.isWindows(e),o=s?ve.compileRe(n,e):ve.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=ve(r.ignore,d,t)}let u=(d,f=!1)=>{let{isMatch:p,match:m,output:h}=ve.test(d,o,e,{glob:n,posix:i}),g={glob:n,state:a,regex:o,posix:i,input:d,output:h,match:m,isMatch:p};return typeof r.onResult=="function"&&r.onResult(g),p===!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};ve.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?Ao.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=ve.matchBase(n,e,t,r):a=e.exec(l)),{isMatch:!!a,match:a,output:l}};ve.matchBase=(n,e,t,s=Ao.isWindows(t))=>(e instanceof RegExp?e:ve.makeRe(e,t)).test(sv.basename(n));ve.isMatch=(n,e,t)=>ve(e,t)(n);ve.parse=(n,e)=>Array.isArray(n)?n.map(t=>ve.parse(t,e)):_o(n,{...e,fastpaths:!1});ve.scan=(n,e)=>rv(n,e);ve.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=ve.toRegex(a,e);return s===!0&&(l.state=n),l};ve.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=_o.fastpaths(n,e)),r.output||(r=_o(n,e)),ve.compileRe(r,e,t,s)};ve.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/$^/}};ve.constants=iv;dd.exports=ve});var ko=j((vE,pd)=>{"use strict";pd.exports=fd()});var xd=j((wE,wd)=>{"use strict";var es=require("fs"),{Readable:av}=require("stream"),Zn=require("path"),{promisify:Zs}=require("util"),$o=ko(),lv=Zs(es.readdir),cv=Zs(es.stat),hd=Zs(es.lstat),uv=Zs(es.realpath),dv="!",bd="READDIRP_RECURSIVE_ERROR",fv=new Set(["ENOENT","EPERM","EACCES","ELOOP",bd]),Co="files",vd="directories",Xs="files_directories",Js="all",md=[Co,vd,Xs,Js],pv=n=>fv.has(n.code),[gd,hv]=process.versions.node.split(".").slice(0,2).map(n=>Number.parseInt(n,10)),mv=process.platform==="win32"&&(gd>10||gd===10&&hv>=5),yd=n=>{if(n!==void 0){if(typeof n=="function")return n;if(typeof n=="string"){let e=$o(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)===dv?t.push($o(r.slice(1))):e.push($o(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 av{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:Co,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=yd(t.fileFilter),this._directoryFilter=yd(t.directoryFilter);let i=t.lstat?hd:cv;mv?this._stat=o=>i(o,{bigint:!0}):this._stat=i,this._maxDepth=t.depth,this._wantsDir=[vd,Xs,Js].includes(r),this._wantsFile=[Co,Xs,Js].includes(r),this._wantsEverything=r===Js,this._root=Zn.resolve(s),this._isDirent="Dirent"in es&&!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 lv(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=Zn.resolve(Zn.join(t,r));s={path:Zn.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){pv(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 uv(s),i=await hd(r);if(i.isFile())return"file";if(i.isDirectory()){let o=r.length;if(s.startsWith(r)&&s.substr(o,1)===Zn.sep){let a=new Error(`Circular symlink detected: "${s}" points to "${r}"`);return a.code=bd,this._onError(a)}return"directory"}}catch(r){this._onError(r)}}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}},_n=(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&&!md.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${md.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=n,new Qs(e)},gv=(n,e={})=>new Promise((t,s)=>{let r=[];_n(n,e).on("data",i=>r.push(i)).on("end",()=>t(r)).on("error",i=>s(i))});_n.promise=gv;_n.ReaddirpStream=Qs;_n.default=_n;wd.exports=_n});var Eo=j((xE,Sd)=>{Sd.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 Ed=j(($d,Cd)=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var kd=ko(),yv=Eo(),_d="!",bv={returnIndex:!1},vv=n=>Array.isArray(n)?n:[n],wv=(n,e)=>{if(typeof n=="function")return n;if(typeof n=="string"){let t=kd(n,e);return s=>n===s||t(s)}return n instanceof RegExp?t=>n.test(t):t=>!1},Ad=(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=yv(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},To=(n,e,t=bv)=>{if(n==null)throw new TypeError("anymatch: specify first argument");let s=typeof t=="boolean"?{returnIndex:t}:t,r=s.returnIndex||!1,i=vv(n),o=i.filter(l=>typeof l=="string"&&l.charAt(0)===_d).map(l=>l.slice(1)).map(l=>kd(l,s)),a=i.filter(l=>typeof l!="string"||typeof l=="string"&&l.charAt(0)!==_d).map(l=>wv(l,s));return e==null?(l,u=!1)=>Ad(a,o,l,typeof u=="boolean"?u:!1):Ad(a,o,e,r)};To.default=To;Cd.exports=To});var Rd=j((SE,Td)=>{Td.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 Ro=j((_E,Od)=>{var xv=Rd(),Pd={"{":"}","(":")","[":"]"},Sv=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=Pd[a];if(l){var u=n.indexOf(l,e);u!==-1&&(e=u+1)}if(n[e]==="!")return!0}else e++}return!1},_v=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=Pd[t];if(s){var r=n.indexOf(s,e);r!==-1&&(e=r+1)}if(n[e]==="!")return!0}else e++}return!1};Od.exports=function(e,t){if(typeof e!="string"||e==="")return!1;if(xv(e))return!0;var s=Sv;return t&&t.strict===!1&&(s=_v),s(e)}});var Md=j((AE,Id)=>{"use strict";var Av=Ro(),kv=require("path").posix.dirname,$v=require("os").platform()==="win32",Po="/",Cv=/\\/g,Ev=/[\{\[].*[\}\]]$/,Tv=/(^|[^\\])([\{\[]|\([^\)]+$)/,Rv=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Id.exports=function(e,t){var s=Object.assign({flipBackslashes:!0},t);s.flipBackslashes&&$v&&e.indexOf(Po)<0&&(e=e.replace(Cv,Po)),Ev.test(e)&&(e+=Po),e+="a";do e=kv(e);while(Av(e)||Tv.test(e));return e.replace(Rv,"$1")}});var er=j(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 tr=j(($E,Dd)=>{"use strict";var Ld=er();Dd.exports=(n,e={})=>{let t=(s,r={})=>{let i=e.escapeInvalid&&Ld.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(i||o)&&Ld.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 Fd=j((CE,Nd)=>{"use strict";Nd.exports=function(n){return typeof n=="number"?n-n===0:typeof n=="string"&&n.trim()!==""?Number.isFinite?Number.isFinite(+n):isFinite(+n):!1}});var Vd=j((EE,Gd)=>{"use strict";var jd=Fd(),en=(n,e,t)=>{if(jd(n)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||n===e)return String(n);if(jd(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(en.cache.hasOwnProperty(l))return en.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=Wd(n)||Wd(e),p={min:n,max:e,a:u,b:d},m=[],h=[];if(f&&(p.isPadded=f,p.maxLen=String(p.max).length),u<0){let g=d<0?Math.abs(d):1;h=Hd(g,Math.abs(u),p,s),u=p.a=0}return d>=0&&(m=Hd(u,d,p,s)),p.negatives=h,p.positives=m,p.result=Pv(h,m,s),s.capture===!0?p.result=`(${p.result})`:s.wrap!==!1&&m.length+h.length>1&&(p.result=`(?:${p.result})`),en.cache[l]=p,p.result};function Pv(n,e,t){let s=Oo(n,e,"-",!1,t)||[],r=Oo(e,n,"",!1,t)||[],i=Oo(n,e,"-?",!0,t)||[];return s.concat(i).concat(r).join("|")}function Ov(n,e){let t=1,s=1,r=Ud(n,t),i=new Set([e]);for(;n<=r&&r<=e;)i.add(r),t+=1,r=Ud(n,t);for(r=qd(e+1,s)-1;n<r&&r<=e;)i.add(r),s+=1,r=qd(e+1,s)-1;return i=[...i],i.sort(Lv),i}function Iv(n,e,t){if(n===e)return{pattern:n,count:[],digits:0};let s=Mv(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+=Dv(l,u,t):o++}return o&&(i+=t.shorthand===!0?"\\d":"[0-9]"),{pattern:i,count:[o],digits:r}}function Hd(n,e,t,s){let r=Ov(n,e),i=[],o=n,a;for(let l=0;l<r.length;l++){let u=r[l],d=Iv(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+Kd(a.count),o=u+1;continue}t.isPadded&&(f=Nv(u,t,s)),d.string=f+d.pattern+Kd(d.count),i.push(d),o=u+1,a=d}return i}function Oo(n,e,t,s,r){let i=[];for(let o of n){let{string:a}=o;!s&&!Bd(e,"string",a)&&i.push(t+a),s&&Bd(e,"string",a)&&i.push(t+a)}return i}function Mv(n,e){let t=[];for(let s=0;s<n.length;s++)t.push([n[s],e[s]]);return t}function Lv(n,e){return n>e?1:e>n?-1:0}function Bd(n,e,t){return n.some(s=>s[e]===t)}function Ud(n,e){return Number(String(n).slice(0,-e)+"9".repeat(e))}function qd(n,e){return n-n%Math.pow(10,e)}function Kd(n){let[e=0,t=""]=n;return t||e>1?`{${e+(t?","+t:"")}}`:""}function Dv(n,e,t){return`[${n}${e-n===1?"":"-"}${e}]`}function Wd(n){return/^-?(0+)\d/.test(n)}function Nv(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}}`}}en.cache={};en.clearCache=()=>en.cache={};Gd.exports=en});var Lo=j((TE,ef)=>{"use strict";var Fv=require("util"),Yd=Vd(),zd=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),jv=n=>e=>n===!0?Number(e):String(e),Io=n=>typeof n=="number"||typeof n=="string"&&n!=="",ts=n=>Number.isInteger(+n),Mo=n=>{let e=`${n}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},Hv=(n,e,t)=>typeof n=="string"||typeof e=="string"?!0:t.stringify===!0,Bv=(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},Uv=(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},Jd=(n,e,t,s)=>{if(t)return Yd(n,e,{wrap:!1,...s});let r=String.fromCharCode(n);if(n===e)return r;let i=String.fromCharCode(e);return`[${r}-${i}]`},Xd=(n,e,t)=>{if(Array.isArray(n)){let s=t.wrap===!0,r=t.capture?"":"?:";return s?`(${r}${n.join("|")})`:n.join("|")}return Yd(n,e,t)},Qd=(...n)=>new RangeError("Invalid range arguments: "+Fv.inspect(...n)),Zd=(n,e,t)=>{if(t.strictRanges===!0)throw Qd([n,e]);return[]},qv=(n,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${n}" to be a number`);return[]},Kv=(n,e,t=1,s={})=>{let r=Number(n),i=Number(e);if(!Number.isInteger(r)||!Number.isInteger(i)){if(s.strictRanges===!0)throw Qd([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=Mo(a)||Mo(l)||Mo(u),f=d?Math.max(a.length,l.length,u.length):0,p=d===!1&&Hv(n,e,s)===!1,m=s.transform||jv(p);if(s.toRegex&&t===1)return Jd(sr(n,f),sr(e,f),!0,s);let h={negatives:[],positives:[]},g=x=>h[x<0?"negatives":"positives"].push(Math.abs(x)),S=[],k=0;for(;o?r>=i:r<=i;)s.toRegex===!0&&t>1?g(r):S.push(Bv(m(r,k),f,p)),r=o?r-t:r+t,k++;return s.toRegex===!0?t>1?Uv(h,s,f):Xd(S,null,{wrap:!1,...s}):S},Wv=(n,e,t=1,s={})=>{if(!ts(n)&&n.length>1||!ts(e)&&e.length>1)return Zd(n,e,s);let r=s.transform||(p=>String.fromCharCode(p)),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 Jd(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?Xd(d,null,{wrap:!1,options:s}):d},nr=(n,e,t,s={})=>{if(e==null&&Io(n))return[n];if(!Io(n)||!Io(e))return Zd(n,e,s);if(typeof t=="function")return nr(n,e,1,{transform:t});if(zd(t))return nr(n,e,0,t);let r={...s};return r.capture===!0&&(r.wrap=!0),t=t||r.step||1,ts(t)?ts(n)&&ts(e)?Kv(n,e,t,r):Wv(n,e,Math.max(Math.abs(t),1),r):t!=null&&!zd(t)?qv(t,r):nr(n,e,1,t)};ef.exports=nr});var sf=j((RE,nf)=>{"use strict";var Gv=Lo(),tf=er(),Vv=(n,e={})=>{let t=(s,r={})=>{let i=tf.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=tf.reduce(s.nodes),f=Gv(...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)};nf.exports=Vv});var af=j((PE,of)=>{"use strict";var zv=Lo(),rf=tr(),An=er(),tn=(n="",e="",t=!1)=>{let s=[];if(n=[].concat(n),e=[].concat(e),!e.length)return n;if(!n.length)return t?An.flatten(e).map(r=>`{${r}}`):e;for(let r of n)if(Array.isArray(r))for(let i of r)s.push(tn(i,e,t));else for(let i of e)t===!0&&typeof i=="string"&&(i=`{${i}}`),s.push(Array.isArray(i)?tn(r,i,t):r+i);return An.flatten(s)},Yv=(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(tn(a.pop(),rf(r,e)));return}if(r.type==="brace"&&r.invalid!==!0&&r.nodes.length===2){a.push(tn(a.pop(),["{}"]));return}if(r.nodes&&r.ranges>0){let f=An.reduce(r.nodes);if(An.exceedsLimit(...f,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let p=zv(...f,e);p.length===0&&(p=rf(r,e)),a.push(tn(a.pop(),p)),r.nodes=[];return}let l=An.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 p=r.nodes[f];if(p.type==="comma"&&r.type==="brace"){f===1&&u.push(""),u.push("");continue}if(p.type==="close"){a.push(tn(a.pop(),u,l));continue}if(p.value&&p.type!=="open"){u.push(tn(u.pop(),p.value));continue}p.nodes&&s(p,r)}return u};return An.flatten(s(n))};of.exports=Yv});var cf=j((OE,lf)=>{"use strict";lf.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:`
324
+ `,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 hf=j((IE,pf)=>{"use strict";var Jv=tr(),{MAX_LENGTH:uf,CHAR_BACKSLASH:Do,CHAR_BACKTICK:Xv,CHAR_COMMA:Qv,CHAR_DOT:Zv,CHAR_LEFT_PARENTHESES:ew,CHAR_RIGHT_PARENTHESES:tw,CHAR_LEFT_CURLY_BRACE:nw,CHAR_RIGHT_CURLY_BRACE:sw,CHAR_LEFT_SQUARE_BRACKET:df,CHAR_RIGHT_SQUARE_BRACKET:ff,CHAR_DOUBLE_QUOTE:rw,CHAR_SINGLE_QUOTE:iw,CHAR_NO_BREAK_SPACE:ow,CHAR_ZERO_WIDTH_NOBREAK_SPACE:aw}=cf(),lw=(n,e={})=>{if(typeof n!="string")throw new TypeError("Expected a string");let t=e||{},s=typeof t.maxLength=="number"?Math.min(uf,t.maxLength):uf;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,p,m=()=>n[d++],h=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(h({type:"bos"});d<u;)if(o=i[i.length-1],p=m(),!(p===aw||p===ow)){if(p===Do){h({type:"text",value:(e.keepEscaping?p:"")+m()});continue}if(p===ff){h({type:"text",value:"\\"+p});continue}if(p===df){l++;let g;for(;d<u&&(g=m());){if(p+=g,g===df){l++;continue}if(g===Do){p+=m();continue}if(g===ff&&(l--,l===0))break}h({type:"text",value:p});continue}if(p===ew){o=h({type:"paren",nodes:[]}),i.push(o),h({type:"text",value:p});continue}if(p===tw){if(o.type!=="paren"){h({type:"text",value:p});continue}o=i.pop(),h({type:"text",value:p}),o=i[i.length-1];continue}if(p===rw||p===iw||p===Xv){let g=p,S;for(e.keepQuotes!==!0&&(p="");d<u&&(S=m());){if(S===Do){p+=S+m();continue}if(S===g){e.keepQuotes===!0&&(p+=S);break}p+=S}h({type:"text",value:p});continue}if(p===nw){f++;let S={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:f,commas:0,ranges:0,nodes:[]};o=h(S),i.push(o),h({type:"open",value:p});continue}if(p===sw){if(o.type!=="brace"){h({type:"text",value:p});continue}let g="close";o=i.pop(),o.close=!0,h({type:g,value:p}),f--,o=i[i.length-1];continue}if(p===Qv&&f>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:Jv(o)}]}h({type:"comma",value:p}),o.commas++;continue}if(p===Zv&&f>0&&o.commas===0){let g=o.nodes;if(f===0||g.length===0){h({type:"text",value:p});continue}if(a.type==="dot"){if(o.range=[],a.value+=p,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 S=g[g.length-1];S.value+=a.value+p,a=S,o.ranges--;continue}h({type:"dot",value:p});continue}h({type:"text",value:p})}do if(o=i.pop(),o.type!=="root"){o.nodes.forEach(k=>{k.nodes||(k.type==="open"&&(k.isOpen=!0),k.type==="close"&&(k.isClose=!0),k.nodes||(k.type="text"),k.invalid=!0)});let g=i[i.length-1],S=g.nodes.indexOf(o);g.nodes.splice(S,1,...o.nodes)}while(i.length>0);return h({type:"eos"}),r};pf.exports=lw});var yf=j((ME,gf)=>{"use strict";var mf=tr(),cw=sf(),uw=af(),dw=hf(),Ke=(n,e={})=>{let t=[];if(Array.isArray(n))for(let s of n){let r=Ke.create(s,e);Array.isArray(r)?t.push(...r):t.push(r)}else t=[].concat(Ke.create(n,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};Ke.parse=(n,e={})=>dw(n,e);Ke.stringify=(n,e={})=>mf(typeof n=="string"?Ke.parse(n,e):n,e);Ke.compile=(n,e={})=>(typeof n=="string"&&(n=Ke.parse(n,e)),cw(n,e));Ke.expand=(n,e={})=>{typeof n=="string"&&(n=Ke.parse(n,e));let t=uw(n,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};Ke.create=(n,e={})=>n===""||n.length<3?[n]:e.expand!==!0?Ke.compile(n,e):Ke.expand(n,e);gf.exports=Ke});var bf=j((LE,fw)=>{fw.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 wf=j((DE,vf)=>{vf.exports=bf()});var Sf=j((NE,xf)=>{"use strict";var pw=require("path"),hw=wf(),mw=new Set(hw);xf.exports=n=>mw.has(pw.extname(n).slice(1).toLowerCase())});var rr=j(U=>{"use strict";var{sep:gw}=require("path"),{platform:No}=process,yw=require("os");U.EV_ALL="all";U.EV_READY="ready";U.EV_ADD="add";U.EV_CHANGE="change";U.EV_ADD_DIR="addDir";U.EV_UNLINK="unlink";U.EV_UNLINK_DIR="unlinkDir";U.EV_RAW="raw";U.EV_ERROR="error";U.STR_DATA="data";U.STR_END="end";U.STR_CLOSE="close";U.FSEVENT_CREATED="created";U.FSEVENT_MODIFIED="modified";U.FSEVENT_DELETED="deleted";U.FSEVENT_MOVED="moved";U.FSEVENT_CLONED="cloned";U.FSEVENT_UNKNOWN="unknown";U.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;U.FSEVENT_TYPE_FILE="file";U.FSEVENT_TYPE_DIRECTORY="directory";U.FSEVENT_TYPE_SYMLINK="symlink";U.KEY_LISTENERS="listeners";U.KEY_ERR="errHandlers";U.KEY_RAW="rawEmitters";U.HANDLER_KEYS=[U.KEY_LISTENERS,U.KEY_ERR,U.KEY_RAW];U.DOT_SLASH=`.${gw}`;U.BACK_SLASH_RE=/\\/g;U.DOUBLE_SLASH_RE=/\/\//;U.SLASH_OR_BACK_SLASH_RE=/[/\\]/;U.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;U.REPLACER_RE=/^\.[/\\]/;U.SLASH="/";U.SLASH_SLASH="//";U.BRACE_START="{";U.BANG="!";U.ONE_DOT=".";U.TWO_DOTS="..";U.STAR="*";U.GLOBSTAR="**";U.ROOT_GLOBSTAR="/**/*";U.SLASH_GLOBSTAR="/**";U.DIR_SUFFIX="Dir";U.ANYMATCH_OPTS={dot:!0};U.STRING_TYPE="string";U.FUNCTION_TYPE="function";U.EMPTY_STR="";U.EMPTY_FN=()=>{};U.IDENTITY_FN=n=>n;U.isWindows=No==="win32";U.isMacos=No==="darwin";U.isLinux=No==="linux";U.isIBMi=yw.type()==="OS400"});var Ef=j((jE,Cf)=>{"use strict";var Rt=require("fs"),Ae=require("path"),{promisify:is}=require("util"),bw=Sf(),{isWindows:vw,isLinux:ww,EMPTY_FN:xw,EMPTY_STR:Sw,KEY_LISTENERS:kn,KEY_ERR:Fo,KEY_RAW:ns,HANDLER_KEYS:_w,EV_CHANGE:or,EV_ADD:ir,EV_ADD_DIR:Aw,EV_ERROR:Af,STR_DATA:kw,STR_END:$w,BRACE_START:Cw,STAR:Ew}=rr(),Tw="watch",Rw=is(Rt.open),kf=is(Rt.stat),Pw=is(Rt.lstat),Ow=is(Rt.close),jo=is(Rt.realpath),Iw={lstat:Pw,stat:kf},Bo=(n,e)=>{n instanceof Set?n.forEach(e):e(n)},ss=(n,e,t)=>{let s=n[e];s instanceof Set||(n[e]=s=new Set([s])),s.add(t)},Mw=n=>e=>{let t=n[e];t instanceof Set?t.clear():delete n[e]},rs=(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,ar=new Map;function _f(n,e,t,s,r){let i=(o,a)=>{t(n),r(o,a,{watchedPath:n}),a&&n!==a&&lr(Ae.resolve(n,a),kn,Ae.join(n,a))};try{return Rt.watch(n,e,i)}catch(o){s(o)}}var lr=(n,e,t,s,r)=>{let i=ar.get(n);i&&Bo(i[e],o=>{o(t,s,r)})},Lw=(n,e,t,s)=>{let{listener:r,errHandler:i,rawEmitter:o}=s,a=ar.get(e),l;if(!t.persistent)return l=_f(n,t,r,i,o),l.close.bind(l);if(a)ss(a,kn,r),ss(a,Fo,i),ss(a,ns,o);else{if(l=_f(n,t,lr.bind(null,e,kn),i,lr.bind(null,e,ns)),!l)return;l.on(Af,async u=>{let d=lr.bind(null,e,Fo);if(a.watcherUnusable=!0,vw&&u.code==="EPERM")try{let f=await Rw(n,"r");await Ow(f),d(u)}catch{}else d(u)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:l},ar.set(e,a)}return()=>{rs(a,kn,r),rs(a,Fo,i),rs(a,ns,o),$f(a.listeners)&&(a.watcher.close(),ar.delete(e),_w.forEach(Mw(a)),a.watcher=void 0,Object.freeze(a))}},Ho=new Map,Dw=(n,e,t,s)=>{let{listener:r,rawEmitter:i}=s,o=Ho.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,Rt.unwatchFile(e),o=void 0),o?(ss(o,kn,r),ss(o,ns,i)):(o={listeners:r,rawEmitters:i,options:t,watcher:Rt.watchFile(e,t,(d,f)=>{Bo(o.rawEmitters,m=>{m(or,e,{curr:d,prev:f})});let p=d.mtimeMs;(d.size!==f.size||p>f.mtimeMs||p===0)&&Bo(o.listeners,m=>m(n,d))})},Ho.set(e,o)),()=>{rs(o,kn,r),rs(o,ns,i),$f(o.listeners)&&(Ho.delete(e),Rt.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},Uo=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let s=this.fsw.options,r=Ae.dirname(e),i=Ae.basename(e);this.fsw._getWatchedDir(r).add(i);let a=Ae.resolve(e),l={persistent:s.persistent};t||(t=xw);let u;return s.usePolling?(l.interval=s.enableBinaryInterval&&bw(i)?s.binaryInterval:s.interval,u=Dw(e,a,l,{listener:t,rawEmitter:this.fsw._emitRaw})):u=Lw(e,a,l,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),u}_handleFile(e,t,s){if(this.fsw.closed)return;let r=Ae.dirname(e),i=Ae.basename(e),o=this.fsw._getWatchedDir(r),a=t;if(o.has(i))return;let l=async(d,f)=>{if(this.fsw._throttle(Tw,e,5)){if(!f||f.mtimeMs===0)try{let p=await kf(e);if(this.fsw.closed)return;let m=p.atimeMs,h=p.mtimeMs;(!m||m<=h||h!==a.mtimeMs)&&this.fsw._emit(or,e,p),ww&&a.ino!==p.ino?(this.fsw._closeFile(d),a=p,this.fsw._addPathCloser(d,this._watchWithNodeFs(e,l))):a=p}catch{this.fsw._remove(r,i)}else if(o.has(i)){let p=f.atimeMs,m=f.mtimeMs;(!p||p<=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 jo(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=Ae.join(e,Sw),!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(kw,async f=>{if(this.fsw.closed){d=void 0;return}let p=f.path,m=Ae.join(e,p);if(u.add(p),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,m,p))){if(this.fsw.closed){d=void 0;return}(p===r||!r&&!l.has(p))&&(this.fsw._incrReadyCount(),m=Ae.join(i,Ae.relative(i,m)),this._addToNodeFs(m,t,s,o+1))}}).on(Af,this._boundHandleError);return new Promise(f=>d.once($w,()=>{if(this.fsw.closed){d=void 0;return}let p=a?a.clear():!1;f(),l.getChildren().filter(m=>m!==e&&!u.has(m)&&(!s.hasGlob||s.filterPath({fullPath:Ae.resolve(e,m)}))).forEach(m=>{this.fsw._remove(e,m)}),d=void 0,p&&this._handleRead(e,!1,s,r,i,o,a)}))}async _handleDir(e,t,s,r,i,o,a){let l=this.fsw._getWatchedDir(Ae.dirname(e)),u=l.has(Ae.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!i&&!u&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(Aw,e,t),l.add(Ae.basename(e)),this.fsw._getWatchedDir(e);let d,f,p=this.fsw.options.depth;if((p==null||r<=p)&&!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,h)=>{h&&h.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 Iw[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(Ew)&&!e.includes(Cw),d;if(l.isDirectory()){let f=Ae.resolve(e),p=u?await jo(e):e;if(this.fsw.closed||(d=await this._handleDir(a.watchPath,l,t,r,i,a,p),this.fsw.closed))return;f!==p&&p!==void 0&&this.fsw._symlinkPaths.set(f,p)}else if(l.isSymbolicLink()){let f=u?await jo(e):e;if(this.fsw.closed)return;let p=Ae.dirname(a.watchPath);if(this.fsw._getWatchedDir(p).add(a.watchPath),this.fsw._emit(ir,a.watchPath,l),d=await this._handleDir(p,l,t,r,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(Ae.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}}};Cf.exports=Uo});var Lf=j((HE,Jo)=>{"use strict";var zo=require("fs"),ke=require("path"),{promisify:Yo}=require("util"),$n;try{$n=require("fsevents")}catch(n){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(n)}if($n){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&&($n=void 0)}}var{EV_ADD:qo,EV_CHANGE:Nw,EV_ADD_DIR:Tf,EV_UNLINK:cr,EV_ERROR:Fw,STR_DATA:jw,STR_END:Hw,FSEVENT_CREATED:Bw,FSEVENT_MODIFIED:Uw,FSEVENT_DELETED:qw,FSEVENT_MOVED:Kw,FSEVENT_UNKNOWN:Ww,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:Gw,FSEVENT_TYPE_FILE:Vw,FSEVENT_TYPE_DIRECTORY:os,FSEVENT_TYPE_SYMLINK:Mf,ROOT_GLOBSTAR:Rf,DIR_SUFFIX:zw,DOT_SLASH:Pf,FUNCTION_TYPE:Ko,EMPTY_FN:Yw,IDENTITY_FN:Jw}=rr(),Xw=n=>isNaN(n)?{}:{depth:n},Go=Yo(zo.stat),Qw=Yo(zo.lstat),Of=Yo(zo.realpath),Zw={stat:Go,lstat:Qw},nn=new Map,ex=10,tx=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),nx=(n,e)=>({stop:$n.watch(n,e)});function sx(n,e,t,s){let r=ke.extname(e)?ke.dirname(e):e,i=ke.dirname(r),o=nn.get(r);rx(i)&&(r=i);let a=ke.resolve(n),l=a!==e,u=(f,p,m)=>{l&&(f=f.replace(e,a)),(f===a||!f.indexOf(a+ke.sep))&&t(f,p,m)},d=!1;for(let f of nn.keys())if(e.indexOf(ke.resolve(f)+ke.sep)===0){r=f,o=nn.get(r),d=!0;break}return o||d?o.listeners.add(u):(o={listeners:new Set([u]),rawEmitter:s,watcher:nx(r,(f,p)=>{if(!o.listeners.size||p&Gw)return;let m=$n.getInfo(f,p);o.listeners.forEach(h=>{h(f,p,m)}),o.rawEmitter(m.event,f,m)})},nn.set(r,o)),()=>{let f=o.listeners;if(f.delete(u),!f.size&&(nn.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var rx=n=>{let e=0;for(let t of nn.keys())if(t.indexOf(n)===0&&(e++,e>=ex))return!0;return!1},ix=()=>$n&&nn.size<128,Wo=(n,e)=>{let t=0;for(;!n.indexOf(e)&&(n=ke.dirname(n))!==e;)t++;return t},If=(n,e)=>n.type===os&&e.isDirectory()||n.type===Mf&&e.isSymbolicLink()||n.type===Vw&&e.isFile(),Vo=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+Rf),!0;s.delete(e),s.delete(e+Rf)}addOrChange(e,t,s,r,i,o,a,l){let u=i.has(o)?Nw:qo;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 Go(e);if(this.fsw.closed)return;If(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===os;(d||o.has(a))&&this.fsw._remove(i,a,d)}else{if(e===qo){if(l.type===os&&this.fsw._getWatchedDir(t),l.type===Mf&&u.followSymlinks){let f=u.depth===void 0?void 0:Wo(s,r)+1;return this._addToFsEvents(t,!1,!0,f)}this.fsw._getWatchedDir(i).add(a)}let d=l.type===os?e+zw:e;this.fsw._emit(d,t),d===Tf&&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=sx(e,t,async(l,u,d)=>{if(this.fsw.closed||i.depth!==void 0&&Wo(l,t)>i.depth)return;let f=s(ke.join(e,ke.relative(e,l)));if(r&&!r(f))return;let p=ke.dirname(f),m=ke.basename(f),h=this.fsw._getWatchedDir(d.type===os?f:p);if(tx.has(u)||d.event===Ww)if(typeof i.ignored===Ko){let g;try{g=await Go(f)}catch{}if(this.fsw.closed||this.checkIgnored(f,g))return;If(d,g)?this.addOrChange(f,l,t,p,h,m,d,i):this.handleEvent(cr,f,l,t,p,h,m,d,i)}else this.checkExists(f,l,t,p,h,m,d,i);else switch(d.event){case Bw:case Uw:return this.addOrChange(f,l,t,p,h,m,d,i);case qw:case Kw:return this.checkExists(f,l,t,p,h,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 Of(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!==Pf?a=o.replace(i,e):o!==Pf&&(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?Tf:qo,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===Ko?t:Jw,a=this.fsw._getWatchHelpers(e);try{let l=await Zw[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),...Xw(i.depth-(r||0))}).on(jw,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 p=i.depth===void 0?void 0:Wo(d,ke.resolve(a.watchPath))+1;this._handleFsEventsSymlink(d,f,o,p)}else this.emitAdd(d,u.stats,o,i,s)}).on(Fw,Yw).on(Hw,()=>{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===Ko)this.initWatch(void 0,e,a,o);else{let l;try{l=await Of(a.watchPath)}catch{}this.initWatch(l,e,a,o)}}};Jo.exports=Vo;Jo.exports.canUse=ix});var Gf=j(da=>{"use strict";var{EventEmitter:ox}=require("events"),ca=require("fs"),oe=require("path"),{promisify:Uf}=require("util"),ax=xd(),na=Ed().default,lx=Md(),Xo=Ro(),cx=yf(),ux=Eo(),dx=Ef(),Df=Lf(),{EV_ALL:Qo,EV_READY:fx,EV_ADD:ur,EV_CHANGE:as,EV_UNLINK:Nf,EV_ADD_DIR:px,EV_UNLINK_DIR:hx,EV_RAW:mx,EV_ERROR:Zo,STR_CLOSE:gx,STR_END:yx,BACK_SLASH_RE:bx,DOUBLE_SLASH_RE:Ff,SLASH_OR_BACK_SLASH_RE:vx,DOT_RE:wx,REPLACER_RE:xx,SLASH:ea,SLASH_SLASH:Sx,BRACE_START:_x,BANG:sa,ONE_DOT:qf,TWO_DOTS:Ax,GLOBSTAR:kx,SLASH_GLOBSTAR:ta,ANYMATCH_OPTS:ra,STRING_TYPE:ua,FUNCTION_TYPE:$x,EMPTY_STR:ia,EMPTY_FN:Cx,isWindows:Ex,isMacos:Tx,isIBMi:Rx}=rr(),Px=Uf(ca.stat),Ox=Uf(ca.readdir),oa=(n=[])=>Array.isArray(n)?n:[n],Kf=(n,e=[])=>(n.forEach(t=>{Array.isArray(t)?Kf(t,e):e.push(t)}),e),jf=n=>{let e=Kf(oa(n));if(!e.every(t=>typeof t===ua))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Wf)},Hf=n=>{let e=n.replace(bx,ea),t=!1;for(e.startsWith(Sx)&&(t=!0);e.match(Ff);)e=e.replace(Ff,ea);return t&&(e=ea+e),e},Wf=n=>Hf(oe.normalize(Hf(n))),Bf=(n=ia)=>e=>typeof e!==ua?e:Wf(oe.isAbsolute(e)?e:oe.join(n,e)),Ix=(n,e)=>oe.isAbsolute(n)?n:n.startsWith(sa)?sa+oe.join(e,n.slice(1)):oe.join(e,n),it=(n,e)=>n[e]===void 0,aa=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==qf&&e!==Ax&&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 Ox(s)}catch{this._removeWatcher&&this._removeWatcher(oe.dirname(s),oe.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)}},Mx="stat",Lx="lstat",la=class{constructor(e,t,s,r){this.fsw=r,this.path=e=e.replace(xx,ia),this.watchPath=t,this.fullWatchPath=oe.resolve(t),this.hasGlob=t!==e,e===ia&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&s?void 0:!1,this.globFilter=this.hasGlob?na(e,void 0,ra):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=s,this.statMethod=s?Mx:Lx}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 oe.join(this.watchPath,oe.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===$x?this.globFilter(s):!0)&&this.fsw._isntIgnored(s,t)&&this.fsw._hasReadPermissions(t)}getDirParts(e){if(!this.hasGlob)return[];let t=[];return(e.includes(_x)?cx.expand(e):[e]).forEach(r=>{t.push(oe.relative(this.watchPath,r).split(vx))}),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===kx&&(s=!0),s||!t[0][o]||na(i,t[0][o],ra))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},dr=class extends ox{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),Df.canUse()||(t.useFsEvents=!1),it(t,"usePolling")&&!t.useFsEvents&&(t.usePolling=Tx),Rx&&(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=oa(t.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Cx,this._readyEmitted=!0,process.nextTick(()=>this.emit(fx)))},this._emitRaw=(...l)=>this.emit(mx,...l),this._readyEmitted=!1,this.options=t,t.useFsEvents?this._fsEventsHandler=new Df(this):this._nodeFsHandler=new dx(this),Object.freeze(t)}add(e,t,s){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=jf(e);return r&&(o=o.map(a=>{let l=Ix(a,r);return i||!Xo(a)?l:ux(l)})),o=o.filter(a=>a.startsWith(sa)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+ta),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(oe.dirname(l),oe.basename(t||l))})})),this}unwatch(e){if(this.closed)return this;let t=jf(e),{cwd:s}=this.options;return t.forEach(r=>{!oe.isAbsolute(r)&&!this._closers.has(r)&&(s&&(r=oe.join(s,r)),r=oe.resolve(r)),this._closePath(r),this._ignoredPaths.add(r),this._watched.has(r)&&this._ignoredPaths.add(r+ta),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?oe.relative(this.options.cwd,s):s;e[r||qf]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(...t),e!==Zo&&this.emit(Qo,...t)}async _emit(e,t,s,r,i){if(this.closed)return;let o=this.options;Ex&&(t=oe.normalize(t)),o.cwd&&(t=oe.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===Nf)return this._pendingUnlinks.set(t,a),setTimeout(()=>{this._pendingUnlinks.forEach((d,f)=>{this.emit(...d),this.emit(Qo,...d),this._pendingUnlinks.delete(f)})},typeof o.atomic=="number"?o.atomic:100),this;e===ur&&this._pendingUnlinks.has(t)&&(e=a[0]=as,this._pendingUnlinks.delete(t))}if(l&&(e===ur||e===as)&&this._readyEmitted){let d=(f,p)=>{f?(e=a[0]=Zo,a[1]=f,this.emitWithAll(e,a)):p&&(a.length>2?a[2]=p:a.push(p),this.emitWithAll(e,a))};return this._awaitWriteFinish(t,l.stabilityThreshold,e,d),this}if(e===as&&!this._throttle(as,t,50))return this;if(o.alwaysStat&&s===void 0&&(e===ur||e===px||e===as)){let d=o.cwd?oe.join(o.cwd,t):t,f;try{f=await Px(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(Zo,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&&!oe.isAbsolute(e)&&(o=oe.join(this.options.cwd,e));let a=new Date,l=u=>{ca.stat(o,(d,f)=>{if(d||!this._pendingWrites.has(e)){d&&d.code!=="ENOENT"&&r(d);return}let p=Number(new Date);u&&f.size!==u.size&&(this._pendingWrites.get(e).lastChange=p);let m=this._pendingWrites.get(e);p-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&&wx.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,r=this.options.ignored,i=r&&r.map(Bf(s)),o=oa(i).filter(l=>typeof l===ua&&!Xo(l)).map(l=>l+ta),a=this._getGlobIgnored().map(Bf(s)).concat(i,o);this._userIgnored=na(a,void 0,ra)}return this._userIgnored([e,t])}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e,t){let s=t||this.options.disableGlobbing||!Xo(e)?e:lx(e),r=this.options.followSymlinks;return new la(e,s,r,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let t=oe.resolve(e);return this._watched.has(t)||this._watched.set(t,new aa(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=oe.join(e,t),i=oe.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(p=>this._remove(r,p));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=oe.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?hx:Nf;u&&!this._isIgnored(r)&&this._emit(f,r),this.options.useFsEvents||this._closePath(r)}_closePath(e){this._closeFile(e);let t=oe.dirname(e);this._getWatchedDir(t).remove(oe.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:Qo,alwaysStat:!0,lstat:!0,...t},r=ax(e,s);return this._streams.add(r),r.once(gx,()=>{r=void 0}),r.once(yx,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};da.FSWatcher=dr;var Dx=(n,e)=>{let t=new dr(e);return t.add(n),t};da.watch=Dx});var Jf={};je(Jf,{CollaborationManager:()=>ls,addTeamMember:()=>jx,formatTeamConfig:()=>Hx,initTeamConfig:()=>Fx,loadTeamConfig:()=>Nx,saveTeamConfig:()=>Yf});function Nx(n){let e=Je.join(n,".hablas","team.json");if(we.existsSync(e))try{return JSON.parse(we.readFileSync(e,"utf-8"))}catch{return null}return null}function Fx(n,e){let t={name:e,members:[]};return Yf(n,t),t}function Yf(n,e){let t=Je.join(n,".hablas","team.json"),s=Je.dirname(t);we.existsSync(s)||we.mkdirSync(s,{recursive:!0}),we.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}function jx(n,e,t){return n.members.push({name:e,email:t}),n}function Hx(n){return[`Team: ${n.name}`,"Members:",...n.members.map(t=>` - ${t.name} (${t.email})`)].join(`
325
+ `)}var we,Je,fr,Vf,zf,ls,fa=N(()=>{"use strict";we=O(require("fs")),Je=O(require("path")),fr=O(require("os")),Vf=O(require("crypto")),zf=O(Gf());xn();ls=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=Je.join(this.workingDir,".hablas","collaboration.json");let i=this.getProjectIdentifier();console.log(`
326
+ ${c.muted("[Debug] Project Context:")} ${c.highlight(i)}`),this.projectTeamToken=Vf.createHash("sha256").update(`${i}:${this.teamKey}`).digest("hex"),console.log(` ${c.muted("[Debug] Session Fingerprint:")} ${c.muted(this.projectTeamToken.slice(0,16))}...
326
327
  `),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 we.existsSync(e)||we.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 p=await d.text().catch(()=>"");if(l=new Error(`[Supabase ${d.status}] ${p}`),(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};we.writeFileSync(this.localStatePath,JSON.stringify(s,null,2),"utf-8")}getLocalState(){if(we.existsSync(this.localStatePath))try{return JSON.parse(we.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(`
327
328
  ${c.success("\u2713")} ${c.muted("[Team]")} Cloud sync reconnected \u2014 session restored.
328
329
  `),this.announcedOffline=!1),this.consecutiveHeartbeatFailures=0):(this.consecutiveHeartbeatFailures++,this.consecutiveHeartbeatFailures>=4&&!this.announcedOffline&&(console.log(`
329
330
  ${c.warning("\u26A0")} ${c.muted("[Team]")} Cloud sync is unreachable \u2014 retrying in the background. Your session is preserved.
330
- `),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=Vf.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(`
331
+ `),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=zf.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(`
331
332
  ${c.success("\u{1F514}")} ${c.muted("[Live Sync]")} ${c.strong(`@${i.developer_name}`)} has joined the session.
332
333
  `);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)}"
333
334
  `))}for(let i of this.knownSessions.keys())s.has(i)||(this.knownSessions.delete(i),console.log(`
@@ -335,83 +336,83 @@ If you cannot complete a task, explain why with absolute technical objectivity.`
335
336
  `));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(`
336
337
  `+r),console.log(l),console.log(f),console.log(i+`
337
338
  `)}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(we.existsSync(e))try{let s=we.readFileSync(e,"utf-8").split(`
338
- `);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(fr.homedir(),".hablas","config.json");if(we.existsSync(e))try{let t=JSON.parse(we.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(we.existsSync(t)){let s=JSON.parse(we.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 sn(n){try{if(!pa.existsSync(n))return;pa.existsSync(cs)||await mt.mkdir(cs,{recursive:!0});let e=await mt.readFile(n,"utf-8"),t=Cn.basename(n),s=Date.now(),r=`${t}.${s}.bak`,i=Cn.join(cs,r);await mt.writeFile(i,e,"utf-8");let a=(await mt.readdir(cs)).filter(l=>l.startsWith(`${t}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Jf)for(let l of a.slice(Jf))await mt.unlink(Cn.join(cs,l))}catch{}}var mt,pa,Cn,Xf,cs,Jf,Qf=N(()=>{"use strict";mt=O(require("fs/promises")),pa=O(require("fs")),Cn=O(require("path")),Xf=O(require("os")),cs=Cn.join(Xf.homedir(),".hablas","backup"),Jf=10});function tp(n){let e=m=>Ht.resolve(n,m);return[{name:"read_file",description:"Read the content of a file with line numbers. Returns up to 300 lines. Use start_line/end_line for large files.",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 h=e(m.path),S=(await de.readFile(h,"utf-8")).split(`
339
- `),k=S.length,x=m.start_line?Math.max(1,m.start_line):1,A=m.end_line?Math.min(k,m.end_line):Math.min(k,x+Zf-1),y=Math.min(A,x+Zf-1),v=S.slice(x-1,y),b=String(y).length,w=v.map((I,$)=>`${String(x+$).padStart(b," ")} | ${I}`),_=`[${m.path} \u2014 lines ${x}-${y} of ${k}]`,E=y<k?`
339
+ `);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(fr.homedir(),".hablas","config.json");if(we.existsSync(e))try{let t=JSON.parse(we.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(we.existsSync(t)){let s=JSON.parse(we.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 sn(n){try{if(!pa.existsSync(n))return;pa.existsSync(cs)||await ht.mkdir(cs,{recursive:!0});let e=await ht.readFile(n,"utf-8"),t=Cn.basename(n),s=Date.now(),r=`${t}.${s}.bak`,i=Cn.join(cs,r);await ht.writeFile(i,e,"utf-8");let a=(await ht.readdir(cs)).filter(l=>l.startsWith(`${t}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Xf)for(let l of a.slice(Xf))await ht.unlink(Cn.join(cs,l))}catch{}}var ht,pa,Cn,Qf,cs,Xf,Zf=N(()=>{"use strict";ht=O(require("fs/promises")),pa=O(require("fs")),Cn=O(require("path")),Qf=O(require("os")),cs=Cn.join(Qf.homedir(),".hablas","backup"),Xf=10});function np(n){let e=m=>Ht.resolve(n,m);return[{name:"read_file",description:"Read the content of a file with line numbers. Returns up to 300 lines. Use start_line/end_line for large files.",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 h=e(m.path),S=(await de.readFile(h,"utf-8")).split(`
340
+ `),k=S.length,x=m.start_line?Math.max(1,m.start_line):1,A=m.end_line?Math.min(k,m.end_line):Math.min(k,x+ep-1),y=Math.min(A,x+ep-1),v=S.slice(x-1,y),b=String(y).length,w=v.map((I,$)=>`${String(x+$).padStart(b," ")} | ${I}`),_=`[${m.path} \u2014 lines ${x}-${y} of ${k}]`,E=y<k?`
340
341
  ... [File has ${k} total lines. Use start_line/end_line to read more.]`:"";return{success:!0,output:`${_}
341
342
  ${w.join(`
342
- `)}${E}`}}catch(h){return{success:!1,output:"",error:`[read_file]: ${h.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 h=e(m.path);return ha.existsSync(h)&&await sn(h),await de.mkdir(Ht.dirname(h),{recursive:!0}),await de.writeFile(h,m.content,"utf-8"),{success:!0,output:`Written: ${m.path}`}}catch(h){return{success:!1,output:"",error:`[write_file]: ${h.message}`}}}},{name:"edit_file",description:"Apply a surgical edit by replacing old content with new content. Must match exactly one location.",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 h=e(m.path),g=await de.readFile(h,"utf-8"),S=m.old_content,k=m.new_content,x=ep(g,S);if(x===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(x>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${x} locations in the file. Provide more surrounding context to be specific.`};await sn(h);let A=g.replace(S,k);await de.writeFile(h,A,"utf-8");let y=Gs(m.path,g,A);return{success:!0,output:`Edited: ${m.path}
343
+ `)}${E}`}}catch(h){return{success:!1,output:"",error:`[read_file]: ${h.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 h=e(m.path);return ha.existsSync(h)&&await sn(h),await de.mkdir(Ht.dirname(h),{recursive:!0}),await de.writeFile(h,m.content,"utf-8"),{success:!0,output:`Written: ${m.path}`}}catch(h){return{success:!1,output:"",error:`[write_file]: ${h.message}`}}}},{name:"edit_file",description:"Apply a surgical edit by replacing old content with new content. Must match exactly one location.",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 h=e(m.path),g=await de.readFile(h,"utf-8"),S=m.old_content,k=m.new_content,x=tp(g,S);if(x===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(x>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${x} locations in the file. Provide more surrounding context to be specific.`};await sn(h);let A=g.replace(S,k);await de.writeFile(h,A,"utf-8");let y=Gs(m.path,g,A);return{success:!0,output:`Edited: ${m.path}
343
344
  ${y}`}}catch(h){return{success:!1,output:"",error:`[edit_file]: ${h.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 h=e(m.path),g=await de.readFile(h,"utf-8"),S=g.split(`
344
345
  `),k=S.length,x=m.start_line,A=m.end_line;if(x<1||x>k)return{success:!1,output:"",error:`[patch_file]: start_line ${x} is out of range (file has ${k} lines)`};if(A<x||A>k)return{success:!1,output:"",error:`[patch_file]: end_line ${A} is out of range (start_line=${x}, total=${k})`};await sn(h);let y=S.slice(0,x-1),v=S.slice(A),b=m.new_content.split(`
345
346
  `),w=[...y,...b,...v].join(`
346
347
  `);await de.writeFile(h,w,"utf-8");let _=Gs(m.path,g,w),E=A-x+1,I=b.length;return{success:!0,output:`Patched: ${m.path} (replaced ${E} lines with ${I})
347
- ${_}`}}catch(h){return{success:!1,output:"",error:`[patch_file]: ${h.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 h=e(m.path),g=await de.readFile(h,"utf-8"),S=m.search,k=m.replace,x=m.is_regex;await sn(h);let A,y;if(x){let v=new RegExp(S,"g");y=(g.match(v)||[]).length,A=g.replace(v,k)}else y=ep(g,S),A=g.split(S).join(k);return y===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await de.writeFile(h,A,"utf-8"),{success:!0,output:`Replaced ${y} occurrence(s) in ${m.path}`})}catch(h){return{success:!1,output:"",error:`[search_and_replace]: ${h.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 h=e(m.path);return await de.mkdir(Ht.dirname(h),{recursive:!0}),ha.existsSync(h)&&await sn(h),await de.appendFile(h,m.content,"utf-8"),{success:!0,output:`Appended to: ${m.path}`}}catch(h){return{success:!1,output:"",error:`[append_to_file]: ${h.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 h=e(m.path);return await sn(h),await de.unlink(h),{success:!0,output:`Deleted: ${m.path}`}}catch(h){return{success:!1,output:"",error:`[delete_file]: ${h.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 h=e(m.from),g=e(m.to);return await de.mkdir(Ht.dirname(g),{recursive:!0}),await de.rename(h,g),{success:!0,output:`Moved: ${m.from} \u2192 ${m.to}`}}catch(h){return{success:!1,output:"",error:`[move_file]: ${h.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 h=e(m.path);return await de.mkdir(h,{recursive:!0}),{success:!0,output:`Created directory: ${m.path}`}}catch(h){return{success:!1,output:"",error:`[create_dir]: ${h.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 h=e(m.path||"."),g=m.depth||3;return{success:!0,output:await np(h,"",g,0)||"(empty directory)"}}catch(h){return{success:!1,output:"",error:`[list_dir]: ${h.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 h=e(m.path),g=await de.stat(h);return{success:!0,output:[`Path: ${m.path}`,`Size: ${Hx(g.size)}`,`Type: ${g.isDirectory()?"directory":"file"}`,`Modified: ${g.mtime.toISOString()}`,`Created: ${g.birthtime.toISOString()}`].join(`
348
- `)}}catch(h){return{success:!1,output:"",error:`[get_file_info]: ${h.message}`}}}}]}function ep(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 np(n,e,t,s){if(s>=t)return"";let i=(await de.readdir(n,{withFileTypes:!0})).filter(a=>!jx.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}
349
- `,l.isDirectory()){let p=e+(u?" ":"\u2502 ");o+=await np(Ht.join(n,l.name),p,t,s+1)}}return o}function Hx(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var de,ha,Ht,Zf,jx,sp=N(()=>{"use strict";de=O(require("fs/promises")),ha=O(require("fs")),Ht=O(require("path"));uo();Qf();Zf=300;jx=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"])});var rp,pr,ip=N(()=>{"use strict";rp=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,rp.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+=`
348
+ ${_}`}}catch(h){return{success:!1,output:"",error:`[patch_file]: ${h.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 h=e(m.path),g=await de.readFile(h,"utf-8"),S=m.search,k=m.replace,x=m.is_regex;await sn(h);let A,y;if(x){let v=new RegExp(S,"g");y=(g.match(v)||[]).length,A=g.replace(v,k)}else y=tp(g,S),A=g.split(S).join(k);return y===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await de.writeFile(h,A,"utf-8"),{success:!0,output:`Replaced ${y} occurrence(s) in ${m.path}`})}catch(h){return{success:!1,output:"",error:`[search_and_replace]: ${h.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 h=e(m.path);return await de.mkdir(Ht.dirname(h),{recursive:!0}),ha.existsSync(h)&&await sn(h),await de.appendFile(h,m.content,"utf-8"),{success:!0,output:`Appended to: ${m.path}`}}catch(h){return{success:!1,output:"",error:`[append_to_file]: ${h.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 h=e(m.path);return await sn(h),await de.unlink(h),{success:!0,output:`Deleted: ${m.path}`}}catch(h){return{success:!1,output:"",error:`[delete_file]: ${h.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 h=e(m.from),g=e(m.to);return await de.mkdir(Ht.dirname(g),{recursive:!0}),await de.rename(h,g),{success:!0,output:`Moved: ${m.from} \u2192 ${m.to}`}}catch(h){return{success:!1,output:"",error:`[move_file]: ${h.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 h=e(m.path);return await de.mkdir(h,{recursive:!0}),{success:!0,output:`Created directory: ${m.path}`}}catch(h){return{success:!1,output:"",error:`[create_dir]: ${h.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 h=e(m.path||"."),g=m.depth||3;return{success:!0,output:await sp(h,"",g,0)||"(empty directory)"}}catch(h){return{success:!1,output:"",error:`[list_dir]: ${h.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 h=e(m.path),g=await de.stat(h);return{success:!0,output:[`Path: ${m.path}`,`Size: ${Ux(g.size)}`,`Type: ${g.isDirectory()?"directory":"file"}`,`Modified: ${g.mtime.toISOString()}`,`Created: ${g.birthtime.toISOString()}`].join(`
349
+ `)}}catch(h){return{success:!1,output:"",error:`[get_file_info]: ${h.message}`}}}}]}function tp(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 sp(n,e,t,s){if(s>=t)return"";let i=(await de.readdir(n,{withFileTypes:!0})).filter(a=>!Bx.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}
350
+ `,l.isDirectory()){let p=e+(u?" ":"\u2502 ");o+=await sp(Ht.join(n,l.name),p,t,s+1)}}return o}function Ux(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var de,ha,Ht,ep,Bx,rp=N(()=>{"use strict";de=O(require("fs/promises")),ha=O(require("fs")),Ht=O(require("path"));uo();Zf();ep=300;Bx=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"])});var ip,pr,op=N(()=>{"use strict";ip=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,ip.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+=`
350
351
  Error: ${a.message}`}),r>0&&setTimeout(()=>{o.status==="running"&&(this.kill(s),o.status="timeout",o.stderr+=`
351
352
  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+=`
352
353
  `),i+=s.stderr),t?.lastLines&&(i=i.split(`
353
354
  `).slice(-t.lastLines).join(`
354
- `)),{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 op(n){return ma||(ma=new pr({workingDir:n})),ma}function lp(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=[...Bx,...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=op(n).start(s,{timeout:i});return{success:!0,output:`Background process started: ${l}
355
- PID: ${op(n).getProcess(l)?.pid}
356
- Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let u=(0,ap.exec)(s,{cwd:n,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",p=>{d+=p}),u.stderr?.on("data",p=>{f+=p}),u.on("close",p=>{l(p===0?{success:!0,output:d||"(no output)"}:{success:!1,output:d,error:f||`Exit code: ${p}`})}),u.on("error",p=>{l({success:!1,output:"",error:p.message})})})}}}var ap,Bx,ma,cp=N(()=>{"use strict";ap=require("child_process");ip();Bx=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],ma=null});function up(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 dp(s,r,i,n),i.length===0)return{success:!0,output:`No matches found for: "${t}"`};let o=i.slice(0,50).join(`
355
+ `)),{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 ap(n){return ma||(ma=new pr({workingDir:n})),ma}function cp(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=[...qx,...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=ap(n).start(s,{timeout:i});return{success:!0,output:`Background process started: ${l}
356
+ PID: ${ap(n).getProcess(l)?.pid}
357
+ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let u=(0,lp.exec)(s,{cwd:n,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",p=>{d+=p}),u.stderr?.on("data",p=>{f+=p}),u.on("close",p=>{l(p===0?{success:!0,output:d||"(no output)"}:{success:!1,output:d,error:f||`Exit code: ${p}`})}),u.on("error",p=>{l({success:!1,output:"",error:p.message})})})}}}var lp,qx,ma,up=N(()=>{"use strict";lp=require("child_process");op();qx=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],ma=null});function dp(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 fp(s,r,i,n),i.length===0)return{success:!0,output:`No matches found for: "${t}"`};let o=i.slice(0,50).join(`
357
358
  `),a=i.length>50?`
358
- ... 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 dp(n,e,t,s){let r=await hr.readdir(n,{withFileTypes:!0});for(let i of r){if(Ux.has(i.name)||i.name.startsWith("."))continue;let o=Bt.join(n,i.name);if(i.isDirectory())await dp(o,e,t,s);else if(qx.has(Bt.extname(i.name)))try{let l=(await hr.readFile(o,"utf-8")).split(`
359
- `),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,Ux,qx,fp=N(()=>{"use strict";hr=O(require("fs/promises")),Bt=O(require("path")),Ux=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),qx=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"])});function Kx(n){let e=[],t=Ut.join(n,"tsconfig.json");if(!Xe.existsSync(t))return e;try{(0,ga.execSync)("npx tsc --noEmit 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(s){let r=s,o=(r.stdout||r.message||"").split(`
360
- `);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 Wx(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,ga.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(`
361
- `);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 Gx(n,e,t){let s;try{s=Xe.readFileSync(n,"utf-8")}catch{return}let r=Ut.relative(e,n),i=s.split(`
362
- `);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 Vx(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))&&Gx(u,n,e)}}return s(n),e.slice(0,20)}function zx(n){let e=[];e.push(...Kx(n)),e.push(...Wx(n)),e.push(...Vx(n));let t={error:0,warning:1,info:2};return e.sort((s,r)=>t[s.severity]-t[r.severity]),e}function pp(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(`
363
- `)}function Yx(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(`
359
+ ... 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 fp(n,e,t,s){let r=await hr.readdir(n,{withFileTypes:!0});for(let i of r){if(Kx.has(i.name)||i.name.startsWith("."))continue;let o=Bt.join(n,i.name);if(i.isDirectory())await fp(o,e,t,s);else if(Wx.has(Bt.extname(i.name)))try{let l=(await hr.readFile(o,"utf-8")).split(`
360
+ `),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,Kx,Wx,pp=N(()=>{"use strict";hr=O(require("fs/promises")),Bt=O(require("path")),Kx=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Wx=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"])});function Gx(n){let e=[],t=Ut.join(n,"tsconfig.json");if(!Xe.existsSync(t))return e;try{(0,ga.execSync)("npx tsc --noEmit 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(s){let r=s,o=(r.stdout||r.message||"").split(`
361
+ `);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 Vx(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,ga.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(`
362
+ `);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 zx(n,e,t){let s;try{s=Xe.readFileSync(n,"utf-8")}catch{return}let r=Ut.relative(e,n),i=s.split(`
363
+ `);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 Yx(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))&&zx(u,n,e)}}return s(n),e.slice(0,20)}function Jx(n){let e=[];e.push(...Gx(n)),e.push(...Vx(n)),e.push(...Yx(n));let t={error:0,warning:1,info:2};return e.sort((s,r)=>t[s.severity]-t[r.severity]),e}function hp(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(`
364
+ `)}function Xx(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(`
364
365
  `);s.line>0&&s.line<=o.length&&(o[s.line-1]="// "+o[s.line-1],Xe.writeFileSync(r,o.join(`
365
- `),"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 hp(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=zx(t);if(s&&r.length>0){let o=Yx(r,t).filter(l=>l.fixed).length;return{success:!0,output:`${pp(r)}
366
+ `),"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 mp(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=Jx(t);if(s&&r.length>0){let o=Xx(r,t).filter(l=>l.fixed).length;return{success:!0,output:`${hp(r)}
366
367
 
367
- Auto-fixed: ${o}/${r.length} issues`}}return{success:!0,output:pp(r)}}catch(r){return{success:!1,output:"",error:`Bug detection failed: ${r instanceof Error?r.message:String(r)}`}}}}}var ga,Xe,Ut,mp=N(()=>{"use strict";ga=require("child_process"),Xe=O(require("fs")),Ut=O(require("path"))});function Xx(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,`
368
+ Auto-fixed: ${o}/${r.length} issues`}}return{success:!0,output:hp(r)}}catch(r){return{success:!1,output:"",error:`Bug detection failed: ${r instanceof Error?r.message:String(r)}`}}}}}var ga,Xe,Ut,gp=N(()=>{"use strict";ga=require("child_process"),Xe=O(require("fs")),Ut=O(require("path"))});function Zx(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,`
368
369
  `),e=e.replace(/<(br|hr)\s*\/?>/gi,`
369
370
  `),e=e.replace(/<\/?(ul|ol)>/gi,`
370
371
  `),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(t,s,r)=>`
371
372
  ${"#".repeat(parseInt(s))} ${r.replace(/<[^>]+>/g,"").trim()}
372
373
  `),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,`
373
374
 
374
- `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function Qx(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 Zx(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 vp(n){let e=new AbortController,t=setTimeout(()=>e.abort(),yp);try{let s=await fetch(n,{signal:e.signal,headers:{"User-Agent":Jx,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<gp;){let{done:d,value:f}=await i.read();if(d)break;o.push(f),a+=f.length}if(a>=gp)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 ${yp/1e3}s`):r}}function wp(){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 vp(e);if(!t||r>=400)return{success:!1,output:"",error:`HTTP ${r} \u2014 could not fetch ${e}`};let i=Qx(t),o=Xx(t);return o.length>bp&&(o=o.slice(0,bp)+`
375
+ `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function eS(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 tS(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 wp(n){let e=new AbortController,t=setTimeout(()=>e.abort(),bp);try{let s=await fetch(n,{signal:e.signal,headers:{"User-Agent":Qx,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<yp;){let{done:d,value:f}=await i.read();if(d)break;o.push(f),a+=f.length}if(a>=yp)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 ${bp/1e3}s`):r}}function xp(){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 wp(e);if(!t||r>=400)return{success:!1,output:"",error:`HTTP ${r} \u2014 could not fetch ${e}`};let i=eS(t),o=Zx(t);return o.length>vp&&(o=o.slice(0,vp)+`
375
376
 
376
377
  [... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${s}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
377
- `)}}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 vp(e);if(!s||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Zx(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(`
378
+ `)}}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 wp(e);if(!s||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=tS(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(`
378
379
  `);return{success:!0,output:`Found ${o.length} links:
379
380
 
380
- ${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 gp,yp,bp,Jx,xp=N(()=>{"use strict";gp=2*1024*1024,yp=15e3,bp=32e3,Jx="HablasBot/2.0 (+https://hablas.dev)"});function tS(n){let e=En.get(n.toLowerCase().trim());return e?Date.now()-e.timestamp>eS?(En.delete(n.toLowerCase().trim()),null):e.results:null}function nS(n,e){if(En.size>200){let t=En.keys().next().value;t!==void 0&&En.delete(t)}En.set(n.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function sS(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 rS(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 iS(n,e=5){let t=tS(n);if(t)return t.slice(0,e);let s=[{name:"brave",fn:()=>sS(n,e)},{name:"duckduckgo",fn:()=>rS(n,e)}];for(let r of s)try{let i=await r.fn();if(i&&i.length>0)return nS(n,i),i}catch{}return[]}function Sp(){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 iS(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(`
381
- `)}}catch(s){return{success:!1,output:"",error:`Search failed: ${s instanceof Error?s.message:String(s)}`}}}}}var eS,En,_p=N(()=>{"use strict";eS=3600*1e3,En=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=rn(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(t.author=rn(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(t.subject=rn(l[1]));let u=e.match(/\/Creator\s*\(([^)]*)\)/);u&&(t.creator=rn(u[1]));let d=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=d.exec(e))!==null;){let m=f[1],h=Cp(m);h.trim()&&s.push(h);try{let g=require("zlib"),S=Buffer.from(m,"latin1"),k=g.inflateSync(S).toString("latin1"),x=Cp(k);x.trim()&&!s.includes(x)&&s.push(x)}catch{}}return{text:s.join(`
381
+ ${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 yp,bp,vp,Qx,Sp=N(()=>{"use strict";yp=2*1024*1024,bp=15e3,vp=32e3,Qx="HablasBot/2.0 (+https://hablas.dev)"});function sS(n){let e=En.get(n.toLowerCase().trim());return e?Date.now()-e.timestamp>nS?(En.delete(n.toLowerCase().trim()),null):e.results:null}function rS(n,e){if(En.size>200){let t=En.keys().next().value;t!==void 0&&En.delete(t)}En.set(n.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function iS(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 oS(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 aS(n,e=5){let t=sS(n);if(t)return t.slice(0,e);let s=[{name:"brave",fn:()=>iS(n,e)},{name:"duckduckgo",fn:()=>oS(n,e)}];for(let r of s)try{let i=await r.fn();if(i&&i.length>0)return rS(n,i),i}catch{}return[]}function _p(){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 aS(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(`
382
+ `)}}catch(s){return{success:!1,output:"",error:`Search failed: ${s instanceof Error?s.message:String(s)}`}}}}}var nS,En,Ap=N(()=>{"use strict";nS=3600*1e3,En=new Map});function Cp(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=rn(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(t.author=rn(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(t.subject=rn(l[1]));let u=e.match(/\/Creator\s*\(([^)]*)\)/);u&&(t.creator=rn(u[1]));let d=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=d.exec(e))!==null;){let m=f[1],h=Ep(m);h.trim()&&s.push(h);try{let g=require("zlib"),S=Buffer.from(m,"latin1"),k=g.inflateSync(S).toString("latin1"),x=Ep(k);x.trim()&&!s.includes(x)&&s.push(x)}catch{}}return{text:s.join(`
382
383
  `).replace(/\r\n/g,`
383
384
  `).replace(/\n{3,}/g,`
384
385
 
385
- `).trim(),pages:r,metadata:t}}function Cp(n){let e=[],t=/\(([^)]*)\)\s*Tj/g,s;for(;(s=t.exec(n))!==null;)e.push(rn(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=>rn(d.slice(1,-1))).join("");e.push(u)}}let i=/\(([^)]*)\)\s*'/g;for(;(s=i.exec(n))!==null;)e.push(rn(s[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
386
+ `).trim(),pages:r,metadata:t}}function Ep(n){let e=[],t=/\(([^)]*)\)\s*Tj/g,s;for(;(s=t.exec(n))!==null;)e.push(rn(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=>rn(d.slice(1,-1))).join("");e.push(u)}}let i=/\(([^)]*)\)\s*'/g;for(;(s=i.exec(n))!==null;)e.push(rn(s[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
386
387
  `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function rn(n){return n.replace(/\\n/g,`
387
- `).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 Tp(n){let e=t=>Ep.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(!Ot.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=Ot.statSync(s);if(r.size>Ap)return{success:!1,output:"",error:`File too large: ${(r.size/1024/1024).toFixed(1)}MB (max: ${Ap/1024/1024}MB)`};try{let i=Ot.readFileSync(s),{text:o,pages:a,metadata:l}=$p(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${t.path} (${a} pages)
388
+ `).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 Rp(n){let e=t=>Tp.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(!Pt.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=Pt.statSync(s);if(r.size>kp)return{success:!1,output:"",error:`File too large: ${(r.size/1024/1024).toFixed(1)}MB (max: ${kp/1024/1024}MB)`};try{let i=Pt.readFileSync(s),{text:o,pages:a,metadata:l}=Cp(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${t.path} (${a} pages)
388
389
 
389
- [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>kp&&(u=u.slice(0,kp)+`
390
+ [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>$p&&(u=u.slice(0,$p)+`
390
391
 
391
392
  [... 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(`
392
393
  `)}
393
- ${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(!Ot.existsSync(s))return{success:!1,output:"",error:`File not found: ${t.path}`};try{let r=Ot.statSync(s),i=Ot.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(`
394
- `)}}catch(r){return{success:!1,output:"",error:`Failed to read PDF metadata: ${r instanceof Error?r.message:String(r)}`}}}}]}var Ot,Ep,Ap,kp,Rp=N(()=>{"use strict";Ot=O(require("fs")),Ep=O(require("path")),Ap=50*1024*1024,kp=4e4});function Tn(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 oS(n,e,t=Dp){let s=Op[e];if(!s)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Op).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=Mp.tmpdir(),i=Lp.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,Ip.exec)(o,{timeout:t,maxBuffer:5242880,cwd:r,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",p=>{d+=p}),u.stderr?.on("data",p=>{f+=p}),u.on("close",p=>{let m=Date.now()-a;l({success:p===0,stdout:d.slice(0,Pp),stderr:f.slice(0,Pp/2),exitCode:p??1,duration:m,language:e})}),u.on("error",p=>{let m=Date.now()-a;l({success:!1,stdout:"",stderr:p.message,exitCode:1,duration:m,language:e})})})}finally{try{mr.unlinkSync(i)}catch{}}}function aS(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 Np(){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()||aS(e),s=Math.min(Math.max(1e3,n.timeout||Dp),3e4),r=await oS(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?`
394
+ ${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(!Pt.existsSync(s))return{success:!1,output:"",error:`File not found: ${t.path}`};try{let r=Pt.statSync(s),i=Pt.readFileSync(s),{pages:o,metadata:a}=Cp(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(`
395
+ `)}}catch(r){return{success:!1,output:"",error:`Failed to read PDF metadata: ${r instanceof Error?r.message:String(r)}`}}}}]}var Pt,Tp,kp,$p,Pp=N(()=>{"use strict";Pt=O(require("fs")),Tp=O(require("path")),kp=50*1024*1024,$p=4e4});function Tn(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 lS(n,e,t=Np){let s=Ip[e];if(!s)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Ip).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=Lp.tmpdir(),i=Dp.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,Mp.exec)(o,{timeout:t,maxBuffer:5242880,cwd:r,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",p=>{d+=p}),u.stderr?.on("data",p=>{f+=p}),u.on("close",p=>{let m=Date.now()-a;l({success:p===0,stdout:d.slice(0,Op),stderr:f.slice(0,Op/2),exitCode:p??1,duration:m,language:e})}),u.on("error",p=>{let m=Date.now()-a;l({success:!1,stdout:"",stderr:p.message,exitCode:1,duration:m,language:e})})})}finally{try{mr.unlinkSync(i)}catch{}}}function cS(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 Fp(){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()||cS(e),s=Math.min(Math.max(1e3,n.timeout||Np),3e4),r=await lS(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?`
395
396
  Errors/Warnings:`:"Errors:"),i.push(r.stderr)),!r.stdout&&!r.stderr&&i.push("(no output)"),{success:r.success,output:i.join(`
396
- `),error:r.success?void 0:r.stderr||`Exit code: ${r.exitCode}`}}}]}var Ip,mr,Mp,Lp,Dp,Pp,Op,Fp=N(()=>{"use strict";Ip=require("child_process"),mr=O(require("fs")),Mp=O(require("os")),Lp=O(require("path")),Dp=1e4,Pp=16e3;Op={javascript:{extension:".js",command:n=>`node --no-warnings "${n}"`,available:()=>!0},typescript:{extension:".ts",command:n=>Tn("tsx")?`tsx "${n}"`:Tn("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=>Tn("python3")?`python3 "${n}"`:`python "${n}"`,available:()=>Tn("python3")||Tn("python")},bash:{extension:".sh",command:n=>`bash "${n}"`,available:()=>Tn("bash")}}});var us,jp=N(()=>{"use strict";sp();cp();fp();mp();xp();_p();Rp();Fp();us=class{tools=new Map;constructor(e,t){let s=tp(e);for(let r of s)this.tools.set(r.name,r);this.tools.set("run_command",lp(e,t)),this.tools.set("search_codebase",up(e)),this.tools.set("detect_bugs",hp(e)),this.tools.set("web_search",Sp());for(let r of wp())this.tools.set(r.name,r);for(let r of Tp(e))this.tools.set(r.name,r);for(let r of Np())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(`
397
+ `),error:r.success?void 0:r.stderr||`Exit code: ${r.exitCode}`}}}]}var Mp,mr,Lp,Dp,Np,Op,Ip,jp=N(()=>{"use strict";Mp=require("child_process"),mr=O(require("fs")),Lp=O(require("os")),Dp=O(require("path")),Np=1e4,Op=16e3;Ip={javascript:{extension:".js",command:n=>`node --no-warnings "${n}"`,available:()=>!0},typescript:{extension:".ts",command:n=>Tn("tsx")?`tsx "${n}"`:Tn("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=>Tn("python3")?`python3 "${n}"`:`python "${n}"`,available:()=>Tn("python3")||Tn("python")},bash:{extension:".sh",command:n=>`bash "${n}"`,available:()=>Tn("bash")}}});var us,Hp=N(()=>{"use strict";rp();up();pp();gp();Sp();Ap();Pp();jp();us=class{tools=new Map;constructor(e,t){let s=np(e);for(let r of s)this.tools.set(r.name,r);this.tools.set("run_command",cp(e,t)),this.tools.set("search_codebase",dp(e)),this.tools.set("detect_bugs",mp(e)),this.tools.set("web_search",_p());for(let r of xp())this.tools.set(r.name,r);for(let r of Rp(e))this.tools.set(r.name,r);for(let r of Fp())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(`
397
398
  `);return`- ${t.name} [${t.safety}]: ${t.description}
398
399
  ${s}`}).join(`
399
400
 
400
401
  `)}}});function ya(n){return Math.ceil(n.length/3.5)}function ds(n,e){let t=Math.floor(e*3.5);return n.length<=t?n:n.slice(0,t)+`
401
- ... [truncated to fit context budget]`}var ba=N(()=>{"use strict"});var Hp,on,va=N(()=>{"use strict";Hp=O(require("crypto"));ba();on=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=ya(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=ds(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
402
+ ... [truncated to fit context budget]`}var ba=N(()=>{"use strict"});var Bp,on,va=N(()=>{"use strict";Bp=O(require("crypto"));ba();on=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=ya(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=ds(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
402
403
  ${l}`),r+=a}}continue}i.push(`--- ${o.path} ---
403
404
  ${o.content}`),r+=o.tokenCount}return i.join(`
404
405
 
405
406
  `)}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} ---
406
407
  ${u.content}`),a+=u.tokenCount}return l.join(`
407
408
 
408
- `)}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=ya(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 Hp.createHash("md5").update(e).digest("hex")}}});function fs(){return`msg_${Date.now()}_${++lS}`}function Rn(n){return Math.ceil(n.length/4)}var lS,an,wa=N(()=>{"use strict";lS=0;an=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:fs(),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=fs(),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=fs(),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=fs(),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:fs(),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)+`
409
+ `)}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=ya(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 Bp.createHash("md5").update(e).digest("hex")}}});function fs(){return`msg_${Date.now()}_${++uS}`}function Rn(n){return Math.ceil(n.length/4)}var uS,an,wa=N(()=>{"use strict";uS=0;an=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:fs(),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=fs(),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=fs(),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=fs(),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:fs(),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)+`
409
410
  ...(compressed from `+t+" chars)":e.content=e.content.slice(0,400)+`
410
- ...(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 Bp,Qe,We,Up,gr,xa,cS,uS,dS,ps,qp=N(()=>{"use strict";Bp=O(require("readline")),Qe=O(require("fs")),We=O(require("path")),Up=O(require("os"));xn();gr=We.join(Up.homedir(),".hablas","history"),xa=500,cS=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"]),uS=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),dS=["read ","edit ","write ","delete ","open ","patch "],ps=class{rl;history=[];workingDir;fileCache=[];fileCacheTime=0;constructor(e){this.workingDir=e||process.cwd(),this.loadHistory(),this.rl=this.createReadline()}createReadline(){return Bp.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:this.history,historySize:xa,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(`
411
+ ...(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 Up,Qe,We,qp,gr,xa,dS,fS,pS,ps,Kp=N(()=>{"use strict";Up=O(require("readline")),Qe=O(require("fs")),We=O(require("path")),qp=O(require("os"));xn();gr=We.join(qp.homedir(),".hablas","history"),xa=500,dS=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"]),fS=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),pS=["read ","edit ","write ","delete ","open ","patch "],ps=class{rl;history=[];workingDir;fileCache=[];fileCacheTime=0;constructor(e){this.workingDir=e||process.cwd(),this.loadHistory(),this.rl=this.createReadline()}createReadline(){return Up.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:this.history,historySize:xa,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(`
411
412
  ${c.error("\u26A0")} ${c.error(c.strong(e))}`),console.log(` ${c.muted('This action cannot be undone. Type "yes" to confirm.')}
412
- `);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=so.filter(r=>r.startsWith(e));return[s.length?s:so,e]}for(let s of dS)if(e.toLowerCase().includes(s)){let r=e.split(s).pop()??"";if(r&&!r.includes(" "))try{let i=We.dirname(r)||".",o=We.basename(r),a=We.resolve(this.workingDir,i),l=Qe.readdirSync(a).filter(u=>u.startsWith(o)).slice(0,8).map(u=>e.slice(0,e.lastIndexOf(r))+We.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(".")||uS.has(a.name))continue;let l=t?`${t}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(We.join(e,a.name),l,s,r,i+1);else{let u=We.extname(a.name).toLowerCase();(cS.has(u)||a.name==="Dockerfile"||a.name==="Makefile")&&s.push(l)}}}catch{}}loadHistory(){try{if(Qe.existsSync(gr)){let e=Qe.readFileSync(gr,"utf-8");this.history=e.split(`
413
+ `);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=so.filter(r=>r.startsWith(e));return[s.length?s:so,e]}for(let s of pS)if(e.toLowerCase().includes(s)){let r=e.split(s).pop()??"";if(r&&!r.includes(" "))try{let i=We.dirname(r)||".",o=We.basename(r),a=We.resolve(this.workingDir,i),l=Qe.readdirSync(a).filter(u=>u.startsWith(o)).slice(0,8).map(u=>e.slice(0,e.lastIndexOf(r))+We.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(".")||fS.has(a.name))continue;let l=t?`${t}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(We.join(e,a.name),l,s,r,i+1);else{let u=We.extname(a.name).toLowerCase();(dS.has(u)||a.name==="Dockerfile"||a.name==="Makefile")&&s.push(l)}}}catch{}}loadHistory(){try{if(Qe.existsSync(gr)){let e=Qe.readFileSync(gr,"utf-8");this.history=e.split(`
413
414
  `).filter(Boolean).slice(-xa)}}catch{}}saveHistory(){try{let e=We.dirname(gr);Qe.existsSync(e)||Qe.mkdirSync(e,{recursive:!0});let t=this.history.slice(-xa);Qe.writeFileSync(gr,t.join(`
414
- `),"utf-8")}catch{}}}});function Ze(n={}){let e={};if(ot.existsSync(Sa))try{let s=ot.readFileSync(Sa,"utf-8");e=JSON.parse(s)}catch{}let t={...jn,...e,tools:{...jn.tools,...e.tools||{}},ui:{...jn.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=ln.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 gt(n){ot.existsSync(Pn)||ot.mkdirSync(Pn,{recursive:!0}),ot.writeFileSync(Sa,JSON.stringify(n,null,2),"utf-8")}function Wp(){let n=[Pn,ln.join(Pn,"logs"),ln.join(Pn,"backup")];for(let e of n)ot.existsSync(e)||ot.mkdirSync(e,{recursive:!0})}var ot,ln,Kp,Pn,Sa,yr=N(()=>{"use strict";ot=O(require("fs")),ln=O(require("path")),Kp=O(require("os"));Hn();Pn=ln.join(Kp.homedir(),".hablas"),Sa=ln.join(Pn,"config.json")});var hs,_a=N(()=>{"use strict";hs=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+`
415
+ `),"utf-8")}catch{}}}});function Ze(n={}){let e={};if(ot.existsSync(Sa))try{let s=ot.readFileSync(Sa,"utf-8");e=JSON.parse(s)}catch{}let t={...jn,...e,tools:{...jn.tools,...e.tools||{}},ui:{...jn.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=ln.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 mt(n){ot.existsSync(Pn)||ot.mkdirSync(Pn,{recursive:!0}),ot.writeFileSync(Sa,JSON.stringify(n,null,2),"utf-8")}function Gp(){let n=[Pn,ln.join(Pn,"logs"),ln.join(Pn,"backup")];for(let e of n)ot.existsSync(e)||ot.mkdirSync(e,{recursive:!0})}var ot,ln,Wp,Pn,Sa,yr=N(()=>{"use strict";ot=O(require("fs")),ln=O(require("path")),Wp=O(require("os"));Hn();Pn=ln.join(Wp.homedir(),".hablas"),Sa=ln.join(Pn,"config.json")});var hs,_a=N(()=>{"use strict";hs=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+`
415
416
 
416
417
  `+i.systemPrompt,toolPreferences:[...new Set([...i.toolPreferences,...r.toolPreferences])],behaviorModifiers:{...r.behaviorModifiers,...i.behaviorModifiers}};return this.register(o),o}}});var Aa,ka=N(()=>{"use strict";Aa={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.
417
418
 
@@ -704,14 +705,14 @@ Your absolute priority is to ensure smooth, conflict-free collaboration between
704
705
 
705
706
  ## Important
706
707
  Never output tool calls as text or JSON in your response.
707
- Always use the tool_calls field provided by the API.`,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"}}});function br(){let n=new hs;return n.register(Aa),n.register($a),n.register(Ea),n.register(Ra),n.register(Oa),n.register(Ma),n.register(Da),n.register(Fa),n.register(Ha),n}var Ua=N(()=>{"use strict";_a();ka();Ca();Ta();Pa();Ia();La();Na();ja();Ba();_a();ka();Ca();Ta();Pa();Ia();La();Na();ja();Ba()});var vr,Gp=N(()=>{"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(`
708
- `)}}});var Le,wr,Vp,zp,On,ms,Yp=N(()=>{"use strict";Le=O(require("fs")),wr=O(require("path")),Vp=O(require("os")),zp=O(require("crypto")),On=wr.join(Vp.homedir(),".hablas","memory"),ms=class{entries=new Map;agentLanes=new Map;projectHash;filePath;agentLanesPath;constructor(e){this.projectHash=zp.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
708
+ Always use the tool_calls field provided by the API.`,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"}}});function br(){let n=new hs;return n.register(Aa),n.register($a),n.register(Ea),n.register(Ra),n.register(Oa),n.register(Ma),n.register(Da),n.register(Fa),n.register(Ha),n}var Ua=N(()=>{"use strict";_a();ka();Ca();Ta();Pa();Ia();La();Na();ja();Ba();_a();ka();Ca();Ta();Pa();Ia();La();Na();ja();Ba()});var vr,Vp=N(()=>{"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(`
709
+ `)}}});var De,wr,zp,Yp,On,ms,Jp=N(()=>{"use strict";De=O(require("fs")),wr=O(require("path")),zp=O(require("os")),Yp=O(require("crypto")),On=wr.join(zp.homedir(),".hablas","memory"),ms=class{entries=new Map;agentLanes=new Map;projectHash;filePath;agentLanesPath;constructor(e){this.projectHash=Yp.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
709
710
  `+i.map(a=>`- [${a.category}${a.importance>=7?" \u2605":""}] ${a.key}: ${a.value}`).join(`
710
711
  `)}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 p of r)l.key.toLowerCase().includes(p)&&(u+=2),l.value.toLowerCase().includes(p)&&(u+=1),l.tags.some(m=>m.toLowerCase().includes(p))&&(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(`
711
712
  `)}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(p=>`${p.key}: ${p.value}`).join("; "),d=a.map(p=>p.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 p of a)this.entries.delete(p.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(`
712
- `)}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 Ka=j((ZT,Qp)=>{"use strict";var gs=n=>n&&typeof n.message=="string",qa=n=>{if(!n)return;let e=n.cause;if(typeof e=="function"){let t=n.cause();return gs(t)?t:void 0}else return gs(e)?e:void 0},Jp=(n,e)=>{if(!gs(n))return"";let t=n.stack||"";if(e.has(n))return t+`
713
+ `)}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(De.existsSync(this.filePath)){let e=JSON.parse(De.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{De.existsSync(On)||De.mkdirSync(On,{recursive:!0});let e=Array.from(this.entries.values());De.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf-8")}catch{}}loadAgentLanes(){try{if(De.existsSync(this.agentLanesPath)){let e=JSON.parse(De.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{De.existsSync(On)||De.mkdirSync(On,{recursive:!0});let e={};for(let[t,s]of this.agentLanes)e[t]=Array.from(s.values());De.writeFileSync(this.agentLanesPath,JSON.stringify(e,null,2),"utf-8")}catch{}}}});var Ka=j((tR,Zp)=>{"use strict";var gs=n=>n&&typeof n.message=="string",qa=n=>{if(!n)return;let e=n.cause;if(typeof e=="function"){let t=n.cause();return gs(t)?t:void 0}else return gs(e)?e:void 0},Xp=(n,e)=>{if(!gs(n))return"";let t=n.stack||"";if(e.has(n))return t+`
713
714
  causes have become circular...`;let s=qa(n);return s?(e.add(n),t+`
714
- caused by: `+Jp(s,e)):t},fS=n=>Jp(n,new Set),Xp=(n,e,t)=>{if(!gs(n))return"";let s=t?"":n.message||"";if(e.has(n))return s+": ...";let r=qa(n);if(r){e.add(n);let i=typeof n.cause=="function";return s+(i?"":": ")+Xp(r,e,i)}else return s},pS=n=>Xp(n,new Set);Qp.exports={isErrorLike:gs,getErrorCause:qa,stackWithCauses:fS,messageWithCauses:pS}});var Wa=j((eR,eh)=>{"use strict";var hS=Symbol("circular-ref-tag"),xr=Symbol("pino-raw-err-ref"),Zp=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(Zp,xr,{writable:!0,value:{}});eh.exports={pinoErrProto:Zp,pinoErrorSymbols:{seen:hS,rawSymbol:xr}}});var sh=j((tR,nh)=>{"use strict";nh.exports=Va;var{messageWithCauses:mS,stackWithCauses:gS,isErrorLike:th}=Ka(),{pinoErrProto:yS,pinoErrorSymbols:bS}=Wa(),{seen:Ga}=bS,{toString:vS}=Object.prototype;function Va(n){if(!th(n))return n;n[Ga]=void 0;let e=Object.create(yS);e.type=vS.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=mS(n),e.stack=gS(n),Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>Va(t)));for(let t in n)if(e[t]===void 0){let s=n[t];th(s)?t!=="cause"&&!Object.prototype.hasOwnProperty.call(s,Ga)&&(e[t]=Va(s)):e[t]=s}return delete n[Ga],e.raw=n,e}});var ih=j((nR,rh)=>{"use strict";rh.exports=_r;var{isErrorLike:za}=Ka(),{pinoErrProto:wS,pinoErrorSymbols:xS}=Wa(),{seen:Sr}=xS,{toString:SS}=Object.prototype;function _r(n){if(!za(n))return n;n[Sr]=void 0;let e=Object.create(wS);e.type=SS.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))),za(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];za(s)?Object.prototype.hasOwnProperty.call(s,Sr)||(e[t]=_r(s)):e[t]=s}return delete n[Sr],e.raw=n,e}});var ch=j((sR,lh)=>{"use strict";lh.exports={mapHttpRequest:_S,reqSerializer:ah};var Ya=Symbol("pino-raw-req-ref"),oh=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[Ya]},set:function(n){this[Ya]=n}}});Object.defineProperty(oh,Ya,{writable:!0,value:{}});function ah(n){let e=n.info||n.socket,t=Object.create(oh);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 _S(n){return{req:ah(n)}}});var ph=j((rR,fh)=>{"use strict";fh.exports={mapHttpResponse:AS,resSerializer:dh};var Ja=Symbol("pino-raw-res-ref"),uh=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Ja]},set:function(n){this[Ja]=n}}});Object.defineProperty(uh,Ja,{writable:!0,value:{}});function dh(n){let e=Object.create(uh);return e.statusCode=n.headersSent?n.statusCode:null,e.headers=n.getHeaders?n.getHeaders():n._headers,e.raw=n,e}function AS(n){return{res:dh(n)}}});var Qa=j((iR,hh)=>{"use strict";var Xa=sh(),kS=ih(),Ar=ch(),kr=ph();hh.exports={err:Xa,errWithCause:kS,mapHttpRequest:Ar.mapHttpRequest,mapHttpResponse:kr.mapHttpResponse,req:Ar.reqSerializer,res:kr.resSerializer,wrapErrorSerializer:function(e){return e===Xa?e:function(s){return e(Xa(s))}},wrapRequestSerializer:function(e){return e===Ar.reqSerializer?e:function(s){return e(Ar.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===kr.resSerializer?e:function(s){return e(kr.resSerializer(s))}}}});var Za=j((oR,mh)=>{"use strict";function $S(n,e){return e}mh.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=$S;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 xh=j((aR,wh)=>{"use strict";function el(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]=el(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]=el(n[t]));return e}return n}function gh(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 yh(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 bh(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 CS(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 ES(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 TS(n,e,t,s=!1){for(let r of e){let i=gh(r);if(i.includes("*"))vh(n,i,t,r,s);else if(s)bh(n,i);else{let o=CS(n,i);if(o===$r)continue;let a=typeof t=="function"?t(o,i):t;yh(n,i,a)}}}function vh(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 RS(n,e,t,i,s,r)}function RS(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 p=0;p<d.length;p++)l[f]=p.toString(),u(d[p],f+1);else if(typeof d=="object"&&d!==null)for(let p in d)l[f]=p,u(d[p],f+1)}else if(f<o.length){let p=o[f];d&&typeof d=="object"&&d!==null&&p in d&&(l[f]=p,u(d[p],f+1))}else if(a.includes("*"))vh(d,a,typeof t=="function"?(m,h)=>{let g=[...l.slice(0,f),...h];return t(m,g)}:t,r,i);else if(i)bh(d,a);else{let p=typeof t=="function"?t(ES(d,a),[...l.slice(0,f),...a]):t;yh(d,a,p)}}if(o.length===0)u(n,0);else{let d=n;for(let f=0;f<o.length;f++){let p=o[f];if(d==null||typeof d!="object"||d===null)return;d=d[p],l[f]=p}d!=null&&u(d,o.length)}}function PS(n){if(n.length===0)return null;let e=new Map;for(let t of n){let s=gh(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 OS(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 IS(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 MS(n){if(!Array.isArray(n))throw new TypeError("paths must be an array");for(let e of n)IS(e)}function LS(n={}){let{paths:e=[],censor:t="[REDACTED]",serialize:s=JSON.stringify,strict:r=!0,remove:i=!1}=n;MS(e);let o=PS(e);return function(l){if(r&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return s?s(l):l;let u=OS(l,o),d=l,f=t;return typeof t=="function"&&(f=t),TS(u,e,f,i),s===!1?(u.restore=function(){return el(d)},u):typeof s=="function"?s(u):JSON.stringify(u)}}wh.exports=LS});var In=j((lR,Sh)=>{"use strict";var DS=Symbol("pino.setLevel"),NS=Symbol("pino.getLevel"),FS=Symbol("pino.levelVal"),jS=Symbol("pino.levelComp"),HS=Symbol("pino.useLevelLabels"),BS=Symbol("pino.useOnlyCustomLevels"),US=Symbol("pino.mixin"),qS=Symbol("pino.lsCache"),KS=Symbol("pino.chindings"),WS=Symbol("pino.asJson"),GS=Symbol("pino.write"),VS=Symbol("pino.redactFmt"),zS=Symbol("pino.time"),YS=Symbol("pino.timeSliceIndex"),JS=Symbol("pino.stream"),XS=Symbol("pino.stringify"),QS=Symbol("pino.stringifySafe"),ZS=Symbol("pino.stringifiers"),e_=Symbol("pino.end"),t_=Symbol("pino.formatOpts"),n_=Symbol("pino.messageKey"),s_=Symbol("pino.errorKey"),r_=Symbol("pino.nestedKey"),i_=Symbol("pino.nestedKeyStr"),o_=Symbol("pino.mixinMergeStrategy"),a_=Symbol("pino.msgPrefix"),l_=Symbol("pino.wildcardFirst"),c_=Symbol.for("pino.serializers"),u_=Symbol.for("pino.formatters"),d_=Symbol.for("pino.hooks"),f_=Symbol.for("pino.metadata");Sh.exports={setLevelSym:DS,getLevelSym:NS,levelValSym:FS,levelCompSym:jS,useLevelLabelsSym:HS,mixinSym:US,lsCacheSym:qS,chindingsSym:KS,asJsonSym:WS,writeSym:GS,serializersSym:c_,redactFmtSym:VS,timeSym:zS,timeSliceIndexSym:YS,streamSym:JS,stringifySym:XS,stringifySafeSym:QS,stringifiersSym:ZS,endSym:e_,formatOptsSym:t_,messageKeySym:n_,errorKeySym:s_,nestedKeySym:r_,wildcardFirstSym:l_,needsMetadataGsym:f_,useOnlyCustomLevelsSym:BS,formattersSym:u_,hooksSym:d_,nestedKeyStrSym:i_,mixinMergeStrategySym:o_,msgPrefixSym:a_}});var nl=j((cR,$h)=>{"use strict";var _h=xh(),{redactFmtSym:p_,wildcardFirstSym:Cr}=In(),tl=/[^.[\]]+|\[([^[\]]*?)\]/g,Ah="[Redacted]",kh=!1;function h_(n,e){let{paths:t,censor:s,remove:r}=m_(n),i=t.reduce((l,u)=>{tl.lastIndex=0;let d=tl.exec(u),f=tl.exec(u),p=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(p==="*"&&(p=Cr),f===null)return l[p]=null,l;if(l[p]===null)return l;let{index:m}=f,h=`${u.substr(m,u.length-1)}`;return l[p]=l[p]||[],p!==Cr&&l[p].length===0&&l[p].push(...l[Cr]||[]),p===Cr&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(h)}),l[p].push(h),l},{}),o={[p_]:_h({paths:t,censor:s,serialize:e,strict:kh,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,p)=>s(f,[u,...p]):s;l[u]=_h({paths:i[u],censor:d,serialize:e,strict:kh,remove:r})}return l},o)}function m_(n){if(Array.isArray(n))return n={paths:n,censor:Ah},n;let{paths:e,censor:t=Ah,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=h_});var Th=j((uR,Eh)=>{"use strict";var g_=()=>"",y_=()=>`,"time":${Date.now()}`,b_=()=>`,"time":${Math.round(Date.now()/1e3)}`,v_=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,w_=1000000n,Ch=1000000000n,x_=BigInt(Date.now())*w_,S_=process.hrtime.bigint(),__=()=>{let n=process.hrtime.bigint()-S_,e=x_+n,t=e/Ch,s=e%Ch,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"`};Eh.exports={nullTime:g_,epochTime:y_,unixTime:b_,isoTime:v_,isoTimeNano:__}});var Ph=j((dR,Rh)=>{"use strict";function A_(n){try{return JSON.stringify(n)}catch{return'"[Circular]"'}}Rh.exports=k_;function k_(n,e,t){var s=t&&t.stringify||A_,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,p=n&&n.length||0,m=0;m<p;){if(n.charCodeAt(m)===37&&m+1<p){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 h=typeof e[d];if(h==="string"){u+="'"+e[d]+"'",f=m+2,m++;break}if(h==="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<p&&(u+=n.slice(f)),u)}});var rl=j((fR,sl)=>{"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));sl.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(););};sl.exports=n}});var jh=j((pR,Fh)=>{"use strict";var fe=require("fs"),$_=require("events"),C_=require("util").inherits,Oh=require("path"),ol=rl(),E_=require("assert"),Er=100,Tr=Buffer.allocUnsafe(0),T_=16*1024,Ih="buffer",Mh="utf8",[R_,P_]=(process.versions.node||"0.0").split(".").map(Number),O_=R_>=22&&P_>=7;function Lh(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&&fe.mkdirSync(Oh.dirname(n),{recursive:!0});let i=fe.openSync(n,s,r);t(null,i)}catch(i){throw t(i),i}else e.mkdir?fe.mkdir(Oh.dirname(n),{recursive:!0},i=>{if(i)return t(i);fe.open(n,s,r,t)}):fe.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:p,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||T_,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 h,g;if(p===Ih)this._writingBuf=Tr,this.write=L_,this.flush=N_,this.flushSync=j_,this._actualWrite=B_,h=()=>fe.writeSync(this.fd,this._writingBuf),g=()=>fe.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===Mh)this._writingBuf="",this.write=M_,this.flush=D_,this.flushSync=F_,this._actualWrite=H_,h=()=>Buffer.isBuffer(this._writingBuf)?fe.writeSync(this.fd,this._writingBuf):fe.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>Buffer.isBuffer(this._writingBuf)?fe.write(this.fd,this._writingBuf,this.release):fe.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Mh}" and "${Ih}", but passed ${p}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Lh(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=(S,k)=>{if(S){if((S.code==="EAGAIN"||S.code==="EBUSY")&&this.retryEAGAIN(S,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{ol(Er),this.release(void 0,0)}catch(y){this.release(y)}else setTimeout(g,Er);else this._writing=!1,this.emit("error",S);return}this.emit("write",k);let x=il(this._writingBuf,this._len,k);if(this._len=x.len,this._writingBuf=x.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let y=h(),v=il(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&&fe.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(I_,this)):this.emit("drain"))},this.on("newListener",function(S){S==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function il(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 I_(n){n.listenerCount("drain")>0&&(n._asyncDrainScheduled=!1,n.emit("drain"))}C_(at,$_);function Dh(n,e){return n.length===0?Tr:n.length===1?n[0]:Buffer.concat(n,e)}function M_(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 L_(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 Nh(n){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,n();else try{fe.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 D_(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&&Nh.call(this,n),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function N_(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&&Nh.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&&fe.close(e,t=>{if(t)return this.emit("error",t)})}),Lh(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 F_(){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)?fe.writeSync(this.fd,n):fe.writeSync(this.fd,n,"utf8"),t=il(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;ol(Er)}}try{fe.fsyncSync(this.fd)}catch{}}function j_(){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=Dh(this._bufs[0],this._lens[0]));try{let e=fe.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;ol(Er)}}}at.prototype.destroy=function(){this.destroyed||Rr(this)};function H_(){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)?fe.writeSync(this.fd,this._writingBuf):fe.writeSync(this.fd,this._writingBuf,"utf8");n(null,e)}catch(e){n(e)}else fe.write(this.fd,this._writingBuf,n)}function B_(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Dh(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=fe.writeSync(this.fd,this._writingBuf);n(null,e)}catch(e){n(e)}else O_&&(this._writingBuf=Buffer.from(this._writingBuf)),fe.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=[],E_(typeof n.fd=="number",`sonic.fd must be a number, got ${typeof n.fd}`);try{fe.fsync(n.fd,e)}catch{}function e(){n.fd!==1&&n.fd!==2?fe.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;Fh.exports=at});var al=j((hR,Kh)=>{"use strict";var lt={exit:[],beforeExit:[]},Hh={exit:K_,beforeExit:W_},Mn;function U_(){Mn===void 0&&(Mn=new FinalizationRegistry(G_))}function q_(n){lt[n].length>0||process.on(n,Hh[n])}function Bh(n){lt[n].length>0||(process.removeListener(n,Hh[n]),lt.exit.length===0&&lt.beforeExit.length===0&&(Mn=void 0))}function K_(){Uh("exit")}function W_(){Uh("beforeExit")}function Uh(n){for(let e of lt[n]){let t=e.deref(),s=e.fn;t!==void 0&&s(t,n)}lt[n]=[]}function G_(n){for(let e of["exit","beforeExit"]){let t=lt[e].indexOf(n);lt[e].splice(t,t+1),Bh(e)}}function qh(n,e,t){if(e===void 0)throw new Error("the object can't be undefined");q_(n);let s=new WeakRef(e);s.fn=t,U_(),Mn.register(e,s),lt[n].push(s)}function V_(n,e){qh("exit",n,e)}function z_(n,e){qh("beforeExit",n,e)}function Y_(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}),Bh(e)}}Kh.exports={register:V_,registerBeforeExit:z_,unregister:Y_}});var Wh=j((mR,J_)=>{J_.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 Vh=j((gR,Gh)=>{"use strict";function X_(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 Q_(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()}Gh.exports={wait:X_,waitDiff:Q_}});var Yh=j((yR,zh)=>{"use strict";zh.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var am=j((bR,om)=>{"use strict";var{version:Z_}=Wh(),{EventEmitter:eA}=require("events"),{Worker:tA}=require("worker_threads"),{join:nA}=require("path"),{pathToFileURL:sA}=require("url"),{wait:rA}=Vh(),{WRITE_INDEX:It,READ_INDEX:cn,SEQ_INDEX:ll}=Yh(),iA=require("buffer"),oA=require("assert"),R=Symbol("kImpl"),aA=iA.constants.MAX_STRING_LENGTH;function Jh(){}function fl(n,e){Atomics.add(n[R].state,ll,1),e(),Atomics.add(n[R].state,ll,1),Atomics.notify(n[R].state,ll)}function Xh(n){fl(n,()=>{Atomics.store(n[R].state,cn,0),Atomics.store(n[R].state,It,0)})}var ys=class{constructor(e){this._value=e}deref(){return this._value}},Pr=class{register(){}unregister(){}},lA=process.env.NODE_V8_COVERAGE?Pr:global.FinalizationRegistry||Pr,cA=process.env.NODE_V8_COVERAGE?ys:global.WeakRef||ys,Qh=new lA(n=>{n.exited||n.terminate()});function uA(n,e){let{filename:t,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||nA(__dirname,"lib","worker.js"),o=new tA(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:t.indexOf("file://")===0?t:sA(t).href,dataBuf:n[R].dataBuf,stateBuf:n[R].stateBuf,workerData:{$context:{threadStreamVersion:Z_},...s}}});return o.stream=new ys(n),o.on("message",dA),o.on("exit",tm),Qh.register(n,o),o}function Zh(n){oA(!n[R].sync),n[R].needDrain&&(n[R].needDrain=!1,n.emit("drain"))}function em(n){for(;;){let e=Atomics.load(n[R].state,It),t=n[R].data.length-e;if(t>0){if(n[R].bufLen===0){n[R].flushing=!1,n[R].ending?pl(n):n[R].needDrain&&process.nextTick(Zh,n);return}rm(n,t,Jh);continue}if(t===0){if(e===0&&n[R].bufLen===0)return;Or(n,()=>{n.destroyed||(Xh(n),em(n))});return}et(n,new Error("overwritten"));return}}function dA(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 cA(e),Or(e,()=>{e[R].ready=!0,e.emit("ready")});break;case"ERROR":et(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"){et(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:et(e,new Error("this should not happen: "+n.code))}}function tm(n){let e=this.stream.deref();e!==void 0&&(Qh.unregister(e),e.worker.exited=!0,e.worker.off("exit",tm),et(e,n!==0?new Error("the worker thread exited"):null))}var ul=class extends eA{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=uA(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 dl(this,new Error("the worker has exited")),!1;if(this[R].ending)return dl(this,new Error("the worker is ending")),!1;if(this[R].flushing&&this[R].bufLen+t.length>=aA)try{cl(this),this[R].flushing=!0}catch(s){return et(this,s),!1}if(this[R].buf.push(t),this[R].bufLen+=t.length,this[R].sync)try{return cl(this),!0}catch(s){return et(this,s),!1}return this[R].flushing||(this[R].flushing=!0,setImmediate(em,this)),this[R].needDrain=this[R].data.length-this[R].bufLen-Atomics.load(this[R].state,It)<=0,!this[R].needDrain}end(){this[R].destroyed||(this[R].ending=!0,pl(this))}flush(e){e=typeof e=="function"?e:Jh,nm(this,t=>{if(t){process.nextTick(e,t);return}sm(this,e)})}flushSync(){this[R].destroyed||(cl(this),im(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 nm(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(nm,n,e);return}Or(n,e)}function Or(n,e){let t=Atomics.load(n[R].state,It);rA(n[R].state,cn,t,1/0,(s,r)=>{if(s){et(n,s),e(s);return}if(r!=="ok"){Or(n,e);return}e()})}function sm(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].ready){let s=()=>{i(),sm(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),et(n,s),process.nextTick(e,s)}}function fA(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 dl(n,e){setImmediate(()=>{n.emit("error",e)})}function et(n,e){n[R].destroyed||(n[R].destroyed=!0,fA(n,e),e&&(n[R].errored=e,dl(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 rm(n,e,t){let r=Atomics.load(n[R].state,It),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 fl(n,()=>{Atomics.store(n[R].state,It,r)}),t(),!0}function pl(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,cn);fl(n,()=>{Atomics.store(n[R].state,It,-1)});let t=0;for(;e!==-1;){if(Atomics.wait(n[R].state,cn,e,1e3),e=Atomics.load(n[R].state,cn),e===-2){et(n,new Error("end() failed"));return}if(++t===10){et(n,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{n[R].finished=!0,n.emit("finish")})}catch(e){et(n,e)}}}function cl(n){let e=()=>{n[R].ending?pl(n):n[R].needDrain&&process.nextTick(Zh,n)};for(n[R].flushing=!1;n[R].bufLen!==0;){let t=Atomics.load(n[R].state,It),s=n[R].data.length-t;if(s===0){im(n),Xh(n);continue}else if(s<0)throw new Error("overwritten");rm(n,s,e)}}function im(n){if(n[R].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(n[R].state,It),t=0;for(;;){let s=Atomics.load(n[R].state,cn);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(n[R].state,cn,s,1e3);else break;if(++t===10)throw new Error("_flushSync took too long (10s)")}}om.exports=ul});var gl=j((vR,um)=>{"use strict";var{createRequire:pA}=require("module"),{existsSync:hA}=require("node:fs"),mA=Za(),{join:hl,isAbsolute:cm,sep:gA}=require("node:path"),{fileURLToPath:yA}=require("node:url"),bA=rl(),ml=al(),vA=am();function wA(n){ml.register(n,kA),ml.registerBeforeExit(n,$A),n.on("close",function(){ml.unregister(n)})}function xA(){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 SA(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&&lm(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(lm(o)){s=!0;continue}}t.push(i)}return s?t.join(" "):n}function lm(n){let e=_A(n);if(!e)return!1;let t=e;if(t.startsWith("file://"))try{t=yA(t)}catch{return!1}return cm(t)&&!hA(t)}function _A(n){let e=n[0],t=n[n.length-1];return e==='"'&&t==='"'||e==="'"&&t==="'"?n.slice(1,-1):n}function AA(n,e,t,s,r){if(!t.execArgv&&xA()&&require.main===void 0&&(t={...t,execArgv:[]}),!t.env&&process.env.NODE_OPTIONS){let l=SA(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(t={...t,env:{...process.env,NODE_OPTIONS:l}})}t={...t,name:r};let i=new vA({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&&wA(i)}function a(){i.closed||(i.flushSync(),bA(100),i.end())}return i}function kA(n){n.ref(),n.flushSync(),n.end(),n.once("close",function(){n.unref()})}function $A(n){n.flushSync()}function CA(n){let{pipeline:e,targets:t,levels:s,dedupe:r,worker:i={},caller:o=mA(),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"]||hl(__dirname,"worker.js"),l.targets=t.filter(h=>h.target).map(h=>({...h,target:m(h.target)})),l.pipelines=t.filter(h=>h.pipeline).map(h=>h.pipeline.map(g=>({...g,level:h.level,target:m(g.target)})))):e&&(f=d["pino-worker"]||hl(__dirname,"worker.js"),l.pipelines=[e.map(h=>({...h,target:m(h.target)}))]),s&&(l.levels=s),r&&(l.dedupe=r),l.pinoWillSendConfig=!0;let p=t||e?"pino.transport":f;return AA(m(f),l,i,a,p);function m(h){if(h=d[h]||h,cm(h)||h.indexOf("file://")===0)return h;if(h==="pino/file")return hl(__dirname,"..","file.js");let g;for(let S of u)try{let k=S==="node:repl"?process.cwd()+gA:S;g=pA(k).resolve(h);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${h}"`);return g}}um.exports=CA});var Lr=j((wR,_m)=>{"use strict";var EA=require("node:diagnostics_channel"),dm=Ph(),{mapHttpRequest:TA,mapHttpResponse:RA}=Qa(),bl=jh(),fm=al(),{lsCacheSym:PA,chindingsSym:ym,writeSym:pm,serializersSym:bm,formatOptsSym:hm,endSym:OA,stringifiersSym:vm,stringifySym:wm,stringifySafeSym:vl,wildcardFirstSym:xm,nestedKeySym:IA,formattersSym:Sm,messageKeySym:MA,errorKeySym:LA,nestedKeyStrSym:DA,msgPrefixSym:Ir}=In(),{isMainThread:NA}=require("worker_threads"),FA=gl(),[jA]=process.versions.node.split(".").map(n=>Number(n)),mm=EA.tracingChannel("pino_asJson"),yl=jA>=25?n=>JSON.stringify(n):BA;function Ln(){}function HA(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=TA(s):typeof s.setHeader=="function"&&(s=RA(s)));let o;i===null&&r.length===0?o=[null]:(i=r.shift(),o=r),typeof this[Ir]=="string"&&i!==void 0&&i!==null&&(i=this[Ir]+i),this[pm](s,dm(i,o,this[hm]),n)}else{let i=s===void 0?r.shift():s;typeof this[Ir]=="string"&&i!==void 0&&i!==null&&(i=this[Ir]+i),this[pm](null,dm(i,r,this[hm]),n)}}}function BA(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 UA(n,e,t,s){if(mm.hasSubscribers===!1)return gm.call(this,n,e,t,s);let r={instance:this,arguments};return mm.traceSync(gm,r,this,n,e,t,s)}function gm(n,e,t,s){let r=this[wm],i=this[vl],o=this[vm],a=this[OA],l=this[ym],u=this[bm],d=this[Sm],f=this[MA],p=this[LA],m=this[PA][t]+s;m=m+l;let h;d.log&&(n=d.log(n));let g=o[xm],S="";for(let x in n)if(h=n[x],Object.prototype.hasOwnProperty.call(n,x)&&h!==void 0){u[x]?h=u[x](h):x===p&&u.err&&(h=u.err(h));let A=o[x]||g;switch(typeof h){case"undefined":case"function":continue;case"number":Number.isFinite(h)===!1&&(h=null);case"boolean":A&&(h=A(h));break;case"string":h=(A||yl)(h);break;default:h=(A||r)(h,i)}if(h===void 0)continue;let y=yl(x);S+=","+y+":"+h}let k="";if(e!==void 0){h=u[f]?u[f](e):e;let x=o[f]||g;switch(typeof h){case"function":break;case"number":Number.isFinite(h)===!1&&(h=null);case"boolean":x&&(h=x(h)),k=',"'+f+'":'+h;break;case"string":h=(x||yl)(h),k=',"'+f+'":'+h;break;default:h=(x||r)(h,i),k=',"'+f+'":'+h}}return this[IA]&&S?m+this[DA]+S.slice(1)+"}"+k+a:m+S+k+a}function qA(n,e){let t,s=n[ym],r=n[wm],i=n[vl],o=n[vm],a=o[xm],l=n[bm],u=n[Sm].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 KA(n){return n.write!==n.constructor.prototype.write}function Mr(n){let e=new bl(n);return e.on("error",t),!n.sync&&NA&&(fm.register(e,WA),e.on("close",function(){fm.unregister(e)})),e;function t(s){if(s.code==="EPIPE"){e.write=Ln,e.end=Ln,e.flushSync=Ln,e.destroy=Ln;return}e.removeListener("error",t),e.emit("error",s)}}function WA(n,e){n.destroyed||(e==="beforeExit"?(n.flush(),n.on("drain",function(){n.end()})):n.flushSync())}function GA(n){return function(t,s,r={},i){if(typeof r=="string")i=Mr({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=Mr({dest:i})}else if(r instanceof bl||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof bl||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=FA({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=Ln),i||(KA(process.stdout)?i=process.stdout:i=Mr({fd:process.stdout.fd||1})),{opts:r,stream:i}}}function VA(n,e){try{return JSON.stringify(n)}catch{try{return(e||this[vl])(n)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function zA(n,e,t){return{level:n,bindings:e,log:t}}function YA(n){let e=Number(n);return typeof n=="string"&&Number.isFinite(e)?e:n===void 0?1:n}_m.exports={noop:Ln,buildSafeSonicBoom:Mr,asChindings:qA,asJson:UA,genLog:HA,createArgsNormalizer:GA,stringify:VA,buildFormatters:zA,normalizeDestFileDescriptor:YA}});var Dr=j((xR,Am)=>{var JA={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},XA={ASC:"ASC",DESC:"DESC"};Am.exports={DEFAULT_LEVELS:JA,SORTING_ORDER:XA}});var Sl=j((SR,Em)=>{"use strict";var{lsCacheSym:QA,levelValSym:wl,useOnlyCustomLevelsSym:ZA,streamSym:ek,formattersSym:tk,hooksSym:nk,levelCompSym:km}=In(),{noop:sk,genLog:un}=Lr(),{DEFAULT_LEVELS:yt,SORTING_ORDER:$m}=Dr(),Cm={fatal:n=>{let e=un(yt.fatal,n);return function(...t){let s=this[ek];if(e.call(this,...t),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:n=>un(yt.error,n),warn:n=>un(yt.warn,n),info:n=>un(yt.info,n),debug:n=>un(yt.debug,n),trace:n=>un(yt.trace,n)},xl=Object.keys(yt).reduce((n,e)=>(n[yt[e]]=e,n),{}),rk=Object.keys(xl).reduce((n,e)=>(n[e]='{"level":'+Number(e),n),{});function ik(n){let e=n[tk].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[QA]=s,n}function ok(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 ak(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[wl],r=this[wl]=t[n],i=this[ZA],o=this[km],a=this[nk].logMethod;for(let l in t){if(o(t[l],r)===!1){this[l]=sk;continue}this[l]=ok(l,i)?Cm[l](a):un(t[l],a)}this.emit("level-change",n,r,e[s],s,this)}function lk(n){let{levels:e,levelVal:t}=this;return e&&e.labels?e.labels[t]:""}function ck(n){let{values:e}=this.levels,t=e[n];return t!==void 0&&this[km](t,this[wl])}function uk(n,e,t){return n===$m.DESC?e<=t:e>=t}function dk(n){return typeof n=="string"?uk.bind(null,n):n}function fk(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:xl,t),r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:yt,n);return{labels:s,values:r}}function pk(n,e,t){if(typeof n=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),t?[]:Object.keys(xl).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:yt,e);if(!(n in s))throw Error(`default level:${n} must be included in custom levels`)}function hk(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 mk(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')}Em.exports={initialLsCache:rk,genLsCache:ik,levelMethods:Cm,getLevel:lk,setLevel:ak,isLevelEnabled:ck,mappings:fk,assertNoLevelCollisions:hk,assertDefaultLevelFound:pk,genLevelComparison:dk,assertLevelComparison:mk}});var _l=j((_R,Tm)=>{"use strict";Tm.exports={version:"10.3.1"}});var Nm=j((kR,Dm)=>{"use strict";var{EventEmitter:gk}=require("node:events"),{lsCacheSym:yk,levelValSym:bk,setLevelSym:kl,getLevelSym:Rm,chindingsSym:Fr,mixinSym:vk,asJsonSym:Om,writeSym:wk,mixinMergeStrategySym:xk,timeSym:Sk,timeSliceIndexSym:_k,streamSym:Im,serializersSym:dn,formattersSym:bs,errorKeySym:Ak,messageKeySym:kk,useOnlyCustomLevelsSym:$k,needsMetadataGsym:Ck,redactFmtSym:Ek,stringifySym:Tk,formatOptsSym:Rk,stringifiersSym:Pk,msgPrefixSym:$l,hooksSym:Ok}=In(),{getLevel:Ik,setLevel:Mk,isLevelEnabled:Lk,mappings:Dk,initialLsCache:Nk,genLsCache:Fk,assertNoLevelCollisions:jk}=Sl(),{asChindings:Cl,asJson:Hk,buildFormatters:Al,stringify:Pm,noop:Mm}=Lr(),{version:Bk}=_l(),Uk=nl(),qk=class{},Lm={constructor:qk,child:Kk,bindings:Wk,setBindings:Gk,flush:Yk,isLevelEnabled:Lk,version:Bk,get level(){return this[Rm]()},set level(n){this[kl](n)},get levelVal(){return this[bk]},set levelVal(n){throw Error("levelVal is read-only")},get msgPrefix(){return this[$l]},get[Symbol.toStringTag](){return"Pino"},[yk]:Nk,[wk]:zk,[Om]:Hk,[Rm]:Ik,[kl]:Mk};Object.setPrototypeOf(Lm,gk.prototype);Dm.exports=function(){return Object.create(Lm)};var Nr=n=>n;function Kk(n,e){if(!n)throw Error("missing bindings for child Pino");let t=this[dn],s=this[bs],r=Object.create(this);if(e==null)return r[bs].bindings!==Nr&&(r[bs]=Al(s.level,Nr,s.log)),r[Fr]=Cl(r,n),this.onChild!==Mm&&this.onChild(r),r;if(e.hasOwnProperty("serializers")===!0){r[dn]=Object.create(null);for(let u in t)r[dn][u]=t[u];let a=Object.getOwnPropertySymbols(t);for(var i=0;i<a.length;i++){let u=a[i];r[dn][u]=t[u]}for(let u in e.serializers)r[dn][u]=e.serializers[u];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let u=l[o];r[dn][u]=e.serializers[u]}}else r[dn]=t;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:u}=e.formatters;r[bs]=Al(a||s.level,l||Nr,u||s.log)}else r[bs]=Al(s.level,Nr,s.log);if(e.hasOwnProperty("customLevels")===!0&&(jk(this.levels,e.customLevels),r.levels=Dk(e.customLevels,r[$k]),Fk(r)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){r.redact=e.redact;let a=Uk(r.redact,Pm),l={stringify:a[Ek]};r[Tk]=Pm,r[Pk]=a,r[Rk]=l}if(typeof e.msgPrefix=="string"&&(r[$l]=(this[$l]||"")+e.msgPrefix),r[Fr]=Cl(r,n),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;r[kl](a)}return this.onChild(r),r}function Wk(){let e=`{${this[Fr].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function Gk(n){let e=Cl(this,n);this[Fr]=e}function Vk(n,e){return Object.assign(e,n)}function zk(n,e,t){let s=this[Sk](),r=this[vk],i=this[Ak],o=this[kk],a=this[xk]||Vk,l,u=this[Ok].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[Om](l,e,t,s),f=this[Im];f[Ck]===!0&&(f.lastLevel=t,f.lastObj=l,f.lastMsg=e,f.lastTime=s.slice(this[_k]),f.lastLogger=this),f.write(u?u(d):d)}function Yk(n){if(n!=null&&typeof n!="function")throw Error("callback must be a function");let e=this[Im];typeof e.flush=="function"?e.flush(n||Mm):n&&n()}});var Bm=j((Pl,Hm)=>{"use strict";var{hasOwnProperty:vs}=Object.prototype,pn=Rl();pn.configure=Rl;pn.stringify=pn;pn.default=pn;Pl.stringify=pn;Pl.configure=Rl;Hm.exports=pn;var Jk=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function qt(n){return n.length<5e3&&!Jk.test(n)?`"${n}"`:JSON.stringify(n)}function El(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 Xk=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Tl(n){return Xk.call(n)!==void 0&&n.length!==0}function Fm(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 Qk(n){if(vs.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 Zk(n){let e;if(vs.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 e$(n,e){let t;if(vs.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 jm(n,e){let t;if(vs.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 fn(n){return n===1?"1 item":`${n} items`}function t$(n){let e=new Set;for(let t of n)(typeof t=="string"||typeof t=="number")&&e.add(String(t));return e}function n$(n){if(vs.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 Rl(n){n={...n};let e=n$(n);e&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let t=Qk(n),s=e$(n,"bigint"),r=Zk(n),i=typeof r=="function"?r:void 0,o=jm(n,"maximumDepth"),a=jm(n,"maximumBreadth");function l(m,h,g,S,k,x){let A=h[m];switch(typeof A=="object"&&A!==null&&typeof A.toJSON=="function"&&(A=A.toJSON(m)),A=S.call(h,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=x;if(Array.isArray(A)){if(A.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(A),k!==""&&(x+=k,y+=`
715
+ caused by: `+Xp(s,e)):t},hS=n=>Xp(n,new Set),Qp=(n,e,t)=>{if(!gs(n))return"";let s=t?"":n.message||"";if(e.has(n))return s+": ...";let r=qa(n);if(r){e.add(n);let i=typeof n.cause=="function";return s+(i?"":": ")+Qp(r,e,i)}else return s},mS=n=>Qp(n,new Set);Zp.exports={isErrorLike:gs,getErrorCause:qa,stackWithCauses:hS,messageWithCauses:mS}});var Wa=j((nR,th)=>{"use strict";var gS=Symbol("circular-ref-tag"),xr=Symbol("pino-raw-err-ref"),eh=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(eh,xr,{writable:!0,value:{}});th.exports={pinoErrProto:eh,pinoErrorSymbols:{seen:gS,rawSymbol:xr}}});var rh=j((sR,sh)=>{"use strict";sh.exports=Va;var{messageWithCauses:yS,stackWithCauses:bS,isErrorLike:nh}=Ka(),{pinoErrProto:vS,pinoErrorSymbols:wS}=Wa(),{seen:Ga}=wS,{toString:xS}=Object.prototype;function Va(n){if(!nh(n))return n;n[Ga]=void 0;let e=Object.create(vS);e.type=xS.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=yS(n),e.stack=bS(n),Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>Va(t)));for(let t in n)if(e[t]===void 0){let s=n[t];nh(s)?t!=="cause"&&!Object.prototype.hasOwnProperty.call(s,Ga)&&(e[t]=Va(s)):e[t]=s}return delete n[Ga],e.raw=n,e}});var oh=j((rR,ih)=>{"use strict";ih.exports=_r;var{isErrorLike:za}=Ka(),{pinoErrProto:SS,pinoErrorSymbols:_S}=Wa(),{seen:Sr}=_S,{toString:AS}=Object.prototype;function _r(n){if(!za(n))return n;n[Sr]=void 0;let e=Object.create(SS);e.type=AS.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))),za(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];za(s)?Object.prototype.hasOwnProperty.call(s,Sr)||(e[t]=_r(s)):e[t]=s}return delete n[Sr],e.raw=n,e}});var uh=j((iR,ch)=>{"use strict";ch.exports={mapHttpRequest:kS,reqSerializer:lh};var Ya=Symbol("pino-raw-req-ref"),ah=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[Ya]},set:function(n){this[Ya]=n}}});Object.defineProperty(ah,Ya,{writable:!0,value:{}});function lh(n){let e=n.info||n.socket,t=Object.create(ah);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 kS(n){return{req:lh(n)}}});var hh=j((oR,ph)=>{"use strict";ph.exports={mapHttpResponse:$S,resSerializer:fh};var Ja=Symbol("pino-raw-res-ref"),dh=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Ja]},set:function(n){this[Ja]=n}}});Object.defineProperty(dh,Ja,{writable:!0,value:{}});function fh(n){let e=Object.create(dh);return e.statusCode=n.headersSent?n.statusCode:null,e.headers=n.getHeaders?n.getHeaders():n._headers,e.raw=n,e}function $S(n){return{res:fh(n)}}});var Qa=j((aR,mh)=>{"use strict";var Xa=rh(),CS=oh(),Ar=uh(),kr=hh();mh.exports={err:Xa,errWithCause:CS,mapHttpRequest:Ar.mapHttpRequest,mapHttpResponse:kr.mapHttpResponse,req:Ar.reqSerializer,res:kr.resSerializer,wrapErrorSerializer:function(e){return e===Xa?e:function(s){return e(Xa(s))}},wrapRequestSerializer:function(e){return e===Ar.reqSerializer?e:function(s){return e(Ar.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===kr.resSerializer?e:function(s){return e(kr.resSerializer(s))}}}});var Za=j((lR,gh)=>{"use strict";function ES(n,e){return e}gh.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=ES;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 Sh=j((cR,xh)=>{"use strict";function el(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]=el(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]=el(n[t]));return e}return n}function yh(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 bh(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 vh(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 TS(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 RS(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 PS(n,e,t,s=!1){for(let r of e){let i=yh(r);if(i.includes("*"))wh(n,i,t,r,s);else if(s)vh(n,i);else{let o=TS(n,i);if(o===$r)continue;let a=typeof t=="function"?t(o,i):t;bh(n,i,a)}}}function wh(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 OS(n,e,t,i,s,r)}function OS(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 p=0;p<d.length;p++)l[f]=p.toString(),u(d[p],f+1);else if(typeof d=="object"&&d!==null)for(let p in d)l[f]=p,u(d[p],f+1)}else if(f<o.length){let p=o[f];d&&typeof d=="object"&&d!==null&&p in d&&(l[f]=p,u(d[p],f+1))}else if(a.includes("*"))wh(d,a,typeof t=="function"?(m,h)=>{let g=[...l.slice(0,f),...h];return t(m,g)}:t,r,i);else if(i)vh(d,a);else{let p=typeof t=="function"?t(RS(d,a),[...l.slice(0,f),...a]):t;bh(d,a,p)}}if(o.length===0)u(n,0);else{let d=n;for(let f=0;f<o.length;f++){let p=o[f];if(d==null||typeof d!="object"||d===null)return;d=d[p],l[f]=p}d!=null&&u(d,o.length)}}function IS(n){if(n.length===0)return null;let e=new Map;for(let t of n){let s=yh(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 MS(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 LS(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 DS(n){if(!Array.isArray(n))throw new TypeError("paths must be an array");for(let e of n)LS(e)}function NS(n={}){let{paths:e=[],censor:t="[REDACTED]",serialize:s=JSON.stringify,strict:r=!0,remove:i=!1}=n;DS(e);let o=IS(e);return function(l){if(r&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return s?s(l):l;let u=MS(l,o),d=l,f=t;return typeof t=="function"&&(f=t),PS(u,e,f,i),s===!1?(u.restore=function(){return el(d)},u):typeof s=="function"?s(u):JSON.stringify(u)}}xh.exports=NS});var In=j((uR,_h)=>{"use strict";var FS=Symbol("pino.setLevel"),jS=Symbol("pino.getLevel"),HS=Symbol("pino.levelVal"),BS=Symbol("pino.levelComp"),US=Symbol("pino.useLevelLabels"),qS=Symbol("pino.useOnlyCustomLevels"),KS=Symbol("pino.mixin"),WS=Symbol("pino.lsCache"),GS=Symbol("pino.chindings"),VS=Symbol("pino.asJson"),zS=Symbol("pino.write"),YS=Symbol("pino.redactFmt"),JS=Symbol("pino.time"),XS=Symbol("pino.timeSliceIndex"),QS=Symbol("pino.stream"),ZS=Symbol("pino.stringify"),e_=Symbol("pino.stringifySafe"),t_=Symbol("pino.stringifiers"),n_=Symbol("pino.end"),s_=Symbol("pino.formatOpts"),r_=Symbol("pino.messageKey"),i_=Symbol("pino.errorKey"),o_=Symbol("pino.nestedKey"),a_=Symbol("pino.nestedKeyStr"),l_=Symbol("pino.mixinMergeStrategy"),c_=Symbol("pino.msgPrefix"),u_=Symbol("pino.wildcardFirst"),d_=Symbol.for("pino.serializers"),f_=Symbol.for("pino.formatters"),p_=Symbol.for("pino.hooks"),h_=Symbol.for("pino.metadata");_h.exports={setLevelSym:FS,getLevelSym:jS,levelValSym:HS,levelCompSym:BS,useLevelLabelsSym:US,mixinSym:KS,lsCacheSym:WS,chindingsSym:GS,asJsonSym:VS,writeSym:zS,serializersSym:d_,redactFmtSym:YS,timeSym:JS,timeSliceIndexSym:XS,streamSym:QS,stringifySym:ZS,stringifySafeSym:e_,stringifiersSym:t_,endSym:n_,formatOptsSym:s_,messageKeySym:r_,errorKeySym:i_,nestedKeySym:o_,wildcardFirstSym:u_,needsMetadataGsym:h_,useOnlyCustomLevelsSym:qS,formattersSym:f_,hooksSym:p_,nestedKeyStrSym:a_,mixinMergeStrategySym:l_,msgPrefixSym:c_}});var nl=j((dR,Ch)=>{"use strict";var Ah=Sh(),{redactFmtSym:m_,wildcardFirstSym:Cr}=In(),tl=/[^.[\]]+|\[([^[\]]*?)\]/g,kh="[Redacted]",$h=!1;function g_(n,e){let{paths:t,censor:s,remove:r}=y_(n),i=t.reduce((l,u)=>{tl.lastIndex=0;let d=tl.exec(u),f=tl.exec(u),p=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(p==="*"&&(p=Cr),f===null)return l[p]=null,l;if(l[p]===null)return l;let{index:m}=f,h=`${u.substr(m,u.length-1)}`;return l[p]=l[p]||[],p!==Cr&&l[p].length===0&&l[p].push(...l[Cr]||[]),p===Cr&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(h)}),l[p].push(h),l},{}),o={[m_]:Ah({paths:t,censor:s,serialize:e,strict:$h,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,p)=>s(f,[u,...p]):s;l[u]=Ah({paths:i[u],censor:d,serialize:e,strict:$h,remove:r})}return l},o)}function y_(n){if(Array.isArray(n))return n={paths:n,censor:kh},n;let{paths:e,censor:t=kh,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}}Ch.exports=g_});var Rh=j((fR,Th)=>{"use strict";var b_=()=>"",v_=()=>`,"time":${Date.now()}`,w_=()=>`,"time":${Math.round(Date.now()/1e3)}`,x_=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,S_=1000000n,Eh=1000000000n,__=BigInt(Date.now())*S_,A_=process.hrtime.bigint(),k_=()=>{let n=process.hrtime.bigint()-A_,e=__+n,t=e/Eh,s=e%Eh,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"`};Th.exports={nullTime:b_,epochTime:v_,unixTime:w_,isoTime:x_,isoTimeNano:k_}});var Oh=j((pR,Ph)=>{"use strict";function $_(n){try{return JSON.stringify(n)}catch{return'"[Circular]"'}}Ph.exports=C_;function C_(n,e,t){var s=t&&t.stringify||$_,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,p=n&&n.length||0,m=0;m<p;){if(n.charCodeAt(m)===37&&m+1<p){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 h=typeof e[d];if(h==="string"){u+="'"+e[d]+"'",f=m+2,m++;break}if(h==="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<p&&(u+=n.slice(f)),u)}});var rl=j((hR,sl)=>{"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));sl.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(););};sl.exports=n}});var Hh=j((mR,jh)=>{"use strict";var fe=require("fs"),E_=require("events"),T_=require("util").inherits,Ih=require("path"),ol=rl(),R_=require("assert"),Er=100,Tr=Buffer.allocUnsafe(0),P_=16*1024,Mh="buffer",Lh="utf8",[O_,I_]=(process.versions.node||"0.0").split(".").map(Number),M_=O_>=22&&I_>=7;function Dh(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&&fe.mkdirSync(Ih.dirname(n),{recursive:!0});let i=fe.openSync(n,s,r);t(null,i)}catch(i){throw t(i),i}else e.mkdir?fe.mkdir(Ih.dirname(n),{recursive:!0},i=>{if(i)return t(i);fe.open(n,s,r,t)}):fe.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:p,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||P_,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 h,g;if(p===Mh)this._writingBuf=Tr,this.write=N_,this.flush=j_,this.flushSync=B_,this._actualWrite=q_,h=()=>fe.writeSync(this.fd,this._writingBuf),g=()=>fe.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===Lh)this._writingBuf="",this.write=D_,this.flush=F_,this.flushSync=H_,this._actualWrite=U_,h=()=>Buffer.isBuffer(this._writingBuf)?fe.writeSync(this.fd,this._writingBuf):fe.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>Buffer.isBuffer(this._writingBuf)?fe.write(this.fd,this._writingBuf,this.release):fe.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Lh}" and "${Mh}", but passed ${p}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Dh(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=(S,k)=>{if(S){if((S.code==="EAGAIN"||S.code==="EBUSY")&&this.retryEAGAIN(S,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{ol(Er),this.release(void 0,0)}catch(y){this.release(y)}else setTimeout(g,Er);else this._writing=!1,this.emit("error",S);return}this.emit("write",k);let x=il(this._writingBuf,this._len,k);if(this._len=x.len,this._writingBuf=x.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let y=h(),v=il(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&&fe.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(L_,this)):this.emit("drain"))},this.on("newListener",function(S){S==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function il(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 L_(n){n.listenerCount("drain")>0&&(n._asyncDrainScheduled=!1,n.emit("drain"))}T_(at,E_);function Nh(n,e){return n.length===0?Tr:n.length===1?n[0]:Buffer.concat(n,e)}function D_(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 N_(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 Fh(n){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,n();else try{fe.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 F_(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&&Fh.call(this,n),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function j_(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&&Fh.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&&fe.close(e,t=>{if(t)return this.emit("error",t)})}),Dh(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 H_(){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)?fe.writeSync(this.fd,n):fe.writeSync(this.fd,n,"utf8"),t=il(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;ol(Er)}}try{fe.fsyncSync(this.fd)}catch{}}function B_(){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=Nh(this._bufs[0],this._lens[0]));try{let e=fe.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;ol(Er)}}}at.prototype.destroy=function(){this.destroyed||Rr(this)};function U_(){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)?fe.writeSync(this.fd,this._writingBuf):fe.writeSync(this.fd,this._writingBuf,"utf8");n(null,e)}catch(e){n(e)}else fe.write(this.fd,this._writingBuf,n)}function q_(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Nh(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=fe.writeSync(this.fd,this._writingBuf);n(null,e)}catch(e){n(e)}else M_&&(this._writingBuf=Buffer.from(this._writingBuf)),fe.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=[],R_(typeof n.fd=="number",`sonic.fd must be a number, got ${typeof n.fd}`);try{fe.fsync(n.fd,e)}catch{}function e(){n.fd!==1&&n.fd!==2?fe.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;jh.exports=at});var al=j((gR,Wh)=>{"use strict";var lt={exit:[],beforeExit:[]},Bh={exit:G_,beforeExit:V_},Mn;function K_(){Mn===void 0&&(Mn=new FinalizationRegistry(z_))}function W_(n){lt[n].length>0||process.on(n,Bh[n])}function Uh(n){lt[n].length>0||(process.removeListener(n,Bh[n]),lt.exit.length===0&&lt.beforeExit.length===0&&(Mn=void 0))}function G_(){qh("exit")}function V_(){qh("beforeExit")}function qh(n){for(let e of lt[n]){let t=e.deref(),s=e.fn;t!==void 0&&s(t,n)}lt[n]=[]}function z_(n){for(let e of["exit","beforeExit"]){let t=lt[e].indexOf(n);lt[e].splice(t,t+1),Uh(e)}}function Kh(n,e,t){if(e===void 0)throw new Error("the object can't be undefined");W_(n);let s=new WeakRef(e);s.fn=t,K_(),Mn.register(e,s),lt[n].push(s)}function Y_(n,e){Kh("exit",n,e)}function J_(n,e){Kh("beforeExit",n,e)}function X_(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}),Uh(e)}}Wh.exports={register:Y_,registerBeforeExit:J_,unregister:X_}});var Gh=j((yR,Q_)=>{Q_.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 zh=j((bR,Vh)=>{"use strict";function Z_(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 eA(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()}Vh.exports={wait:Z_,waitDiff:eA}});var Jh=j((vR,Yh)=>{"use strict";Yh.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var lm=j((wR,am)=>{"use strict";var{version:tA}=Gh(),{EventEmitter:nA}=require("events"),{Worker:sA}=require("worker_threads"),{join:rA}=require("path"),{pathToFileURL:iA}=require("url"),{wait:oA}=zh(),{WRITE_INDEX:Ot,READ_INDEX:cn,SEQ_INDEX:ll}=Jh(),aA=require("buffer"),lA=require("assert"),R=Symbol("kImpl"),cA=aA.constants.MAX_STRING_LENGTH;function Xh(){}function fl(n,e){Atomics.add(n[R].state,ll,1),e(),Atomics.add(n[R].state,ll,1),Atomics.notify(n[R].state,ll)}function Qh(n){fl(n,()=>{Atomics.store(n[R].state,cn,0),Atomics.store(n[R].state,Ot,0)})}var ys=class{constructor(e){this._value=e}deref(){return this._value}},Pr=class{register(){}unregister(){}},uA=process.env.NODE_V8_COVERAGE?Pr:global.FinalizationRegistry||Pr,dA=process.env.NODE_V8_COVERAGE?ys:global.WeakRef||ys,Zh=new uA(n=>{n.exited||n.terminate()});function fA(n,e){let{filename:t,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||rA(__dirname,"lib","worker.js"),o=new sA(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:t.indexOf("file://")===0?t:iA(t).href,dataBuf:n[R].dataBuf,stateBuf:n[R].stateBuf,workerData:{$context:{threadStreamVersion:tA},...s}}});return o.stream=new ys(n),o.on("message",pA),o.on("exit",nm),Zh.register(n,o),o}function em(n){lA(!n[R].sync),n[R].needDrain&&(n[R].needDrain=!1,n.emit("drain"))}function tm(n){for(;;){let e=Atomics.load(n[R].state,Ot),t=n[R].data.length-e;if(t>0){if(n[R].bufLen===0){n[R].flushing=!1,n[R].ending?pl(n):n[R].needDrain&&process.nextTick(em,n);return}im(n,t,Xh);continue}if(t===0){if(e===0&&n[R].bufLen===0)return;Or(n,()=>{n.destroyed||(Qh(n),tm(n))});return}et(n,new Error("overwritten"));return}}function pA(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 dA(e),Or(e,()=>{e[R].ready=!0,e.emit("ready")});break;case"ERROR":et(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"){et(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:et(e,new Error("this should not happen: "+n.code))}}function nm(n){let e=this.stream.deref();e!==void 0&&(Zh.unregister(e),e.worker.exited=!0,e.worker.off("exit",nm),et(e,n!==0?new Error("the worker thread exited"):null))}var ul=class extends nA{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=fA(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 dl(this,new Error("the worker has exited")),!1;if(this[R].ending)return dl(this,new Error("the worker is ending")),!1;if(this[R].flushing&&this[R].bufLen+t.length>=cA)try{cl(this),this[R].flushing=!0}catch(s){return et(this,s),!1}if(this[R].buf.push(t),this[R].bufLen+=t.length,this[R].sync)try{return cl(this),!0}catch(s){return et(this,s),!1}return this[R].flushing||(this[R].flushing=!0,setImmediate(tm,this)),this[R].needDrain=this[R].data.length-this[R].bufLen-Atomics.load(this[R].state,Ot)<=0,!this[R].needDrain}end(){this[R].destroyed||(this[R].ending=!0,pl(this))}flush(e){e=typeof e=="function"?e:Xh,sm(this,t=>{if(t){process.nextTick(e,t);return}rm(this,e)})}flushSync(){this[R].destroyed||(cl(this),om(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 sm(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(sm,n,e);return}Or(n,e)}function Or(n,e){let t=Atomics.load(n[R].state,Ot);oA(n[R].state,cn,t,1/0,(s,r)=>{if(s){et(n,s),e(s);return}if(r!=="ok"){Or(n,e);return}e()})}function rm(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].ready){let s=()=>{i(),rm(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),et(n,s),process.nextTick(e,s)}}function hA(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 dl(n,e){setImmediate(()=>{n.emit("error",e)})}function et(n,e){n[R].destroyed||(n[R].destroyed=!0,hA(n,e),e&&(n[R].errored=e,dl(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 im(n,e,t){let r=Atomics.load(n[R].state,Ot),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 fl(n,()=>{Atomics.store(n[R].state,Ot,r)}),t(),!0}function pl(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,cn);fl(n,()=>{Atomics.store(n[R].state,Ot,-1)});let t=0;for(;e!==-1;){if(Atomics.wait(n[R].state,cn,e,1e3),e=Atomics.load(n[R].state,cn),e===-2){et(n,new Error("end() failed"));return}if(++t===10){et(n,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{n[R].finished=!0,n.emit("finish")})}catch(e){et(n,e)}}}function cl(n){let e=()=>{n[R].ending?pl(n):n[R].needDrain&&process.nextTick(em,n)};for(n[R].flushing=!1;n[R].bufLen!==0;){let t=Atomics.load(n[R].state,Ot),s=n[R].data.length-t;if(s===0){om(n),Qh(n);continue}else if(s<0)throw new Error("overwritten");im(n,s,e)}}function om(n){if(n[R].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(n[R].state,Ot),t=0;for(;;){let s=Atomics.load(n[R].state,cn);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(n[R].state,cn,s,1e3);else break;if(++t===10)throw new Error("_flushSync took too long (10s)")}}am.exports=ul});var gl=j((xR,dm)=>{"use strict";var{createRequire:mA}=require("module"),{existsSync:gA}=require("node:fs"),yA=Za(),{join:hl,isAbsolute:um,sep:bA}=require("node:path"),{fileURLToPath:vA}=require("node:url"),wA=rl(),ml=al(),xA=lm();function SA(n){ml.register(n,CA),ml.registerBeforeExit(n,EA),n.on("close",function(){ml.unregister(n)})}function _A(){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 AA(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&&cm(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(cm(o)){s=!0;continue}}t.push(i)}return s?t.join(" "):n}function cm(n){let e=kA(n);if(!e)return!1;let t=e;if(t.startsWith("file://"))try{t=vA(t)}catch{return!1}return um(t)&&!gA(t)}function kA(n){let e=n[0],t=n[n.length-1];return e==='"'&&t==='"'||e==="'"&&t==="'"?n.slice(1,-1):n}function $A(n,e,t,s,r){if(!t.execArgv&&_A()&&require.main===void 0&&(t={...t,execArgv:[]}),!t.env&&process.env.NODE_OPTIONS){let l=AA(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(t={...t,env:{...process.env,NODE_OPTIONS:l}})}t={...t,name:r};let i=new xA({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&&SA(i)}function a(){i.closed||(i.flushSync(),wA(100),i.end())}return i}function CA(n){n.ref(),n.flushSync(),n.end(),n.once("close",function(){n.unref()})}function EA(n){n.flushSync()}function TA(n){let{pipeline:e,targets:t,levels:s,dedupe:r,worker:i={},caller:o=yA(),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"]||hl(__dirname,"worker.js"),l.targets=t.filter(h=>h.target).map(h=>({...h,target:m(h.target)})),l.pipelines=t.filter(h=>h.pipeline).map(h=>h.pipeline.map(g=>({...g,level:h.level,target:m(g.target)})))):e&&(f=d["pino-worker"]||hl(__dirname,"worker.js"),l.pipelines=[e.map(h=>({...h,target:m(h.target)}))]),s&&(l.levels=s),r&&(l.dedupe=r),l.pinoWillSendConfig=!0;let p=t||e?"pino.transport":f;return $A(m(f),l,i,a,p);function m(h){if(h=d[h]||h,um(h)||h.indexOf("file://")===0)return h;if(h==="pino/file")return hl(__dirname,"..","file.js");let g;for(let S of u)try{let k=S==="node:repl"?process.cwd()+bA:S;g=mA(k).resolve(h);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${h}"`);return g}}dm.exports=TA});var Lr=j((SR,Am)=>{"use strict";var RA=require("node:diagnostics_channel"),fm=Oh(),{mapHttpRequest:PA,mapHttpResponse:OA}=Qa(),bl=Hh(),pm=al(),{lsCacheSym:IA,chindingsSym:bm,writeSym:hm,serializersSym:vm,formatOptsSym:mm,endSym:MA,stringifiersSym:wm,stringifySym:xm,stringifySafeSym:vl,wildcardFirstSym:Sm,nestedKeySym:LA,formattersSym:_m,messageKeySym:DA,errorKeySym:NA,nestedKeyStrSym:FA,msgPrefixSym:Ir}=In(),{isMainThread:jA}=require("worker_threads"),HA=gl(),[BA]=process.versions.node.split(".").map(n=>Number(n)),gm=RA.tracingChannel("pino_asJson"),yl=BA>=25?n=>JSON.stringify(n):qA;function Ln(){}function UA(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=PA(s):typeof s.setHeader=="function"&&(s=OA(s)));let o;i===null&&r.length===0?o=[null]:(i=r.shift(),o=r),typeof this[Ir]=="string"&&i!==void 0&&i!==null&&(i=this[Ir]+i),this[hm](s,fm(i,o,this[mm]),n)}else{let i=s===void 0?r.shift():s;typeof this[Ir]=="string"&&i!==void 0&&i!==null&&(i=this[Ir]+i),this[hm](null,fm(i,r,this[mm]),n)}}}function qA(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 KA(n,e,t,s){if(gm.hasSubscribers===!1)return ym.call(this,n,e,t,s);let r={instance:this,arguments};return gm.traceSync(ym,r,this,n,e,t,s)}function ym(n,e,t,s){let r=this[xm],i=this[vl],o=this[wm],a=this[MA],l=this[bm],u=this[vm],d=this[_m],f=this[DA],p=this[NA],m=this[IA][t]+s;m=m+l;let h;d.log&&(n=d.log(n));let g=o[Sm],S="";for(let x in n)if(h=n[x],Object.prototype.hasOwnProperty.call(n,x)&&h!==void 0){u[x]?h=u[x](h):x===p&&u.err&&(h=u.err(h));let A=o[x]||g;switch(typeof h){case"undefined":case"function":continue;case"number":Number.isFinite(h)===!1&&(h=null);case"boolean":A&&(h=A(h));break;case"string":h=(A||yl)(h);break;default:h=(A||r)(h,i)}if(h===void 0)continue;let y=yl(x);S+=","+y+":"+h}let k="";if(e!==void 0){h=u[f]?u[f](e):e;let x=o[f]||g;switch(typeof h){case"function":break;case"number":Number.isFinite(h)===!1&&(h=null);case"boolean":x&&(h=x(h)),k=',"'+f+'":'+h;break;case"string":h=(x||yl)(h),k=',"'+f+'":'+h;break;default:h=(x||r)(h,i),k=',"'+f+'":'+h}}return this[LA]&&S?m+this[FA]+S.slice(1)+"}"+k+a:m+S+k+a}function WA(n,e){let t,s=n[bm],r=n[xm],i=n[vl],o=n[wm],a=o[Sm],l=n[vm],u=n[_m].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 GA(n){return n.write!==n.constructor.prototype.write}function Mr(n){let e=new bl(n);return e.on("error",t),!n.sync&&jA&&(pm.register(e,VA),e.on("close",function(){pm.unregister(e)})),e;function t(s){if(s.code==="EPIPE"){e.write=Ln,e.end=Ln,e.flushSync=Ln,e.destroy=Ln;return}e.removeListener("error",t),e.emit("error",s)}}function VA(n,e){n.destroyed||(e==="beforeExit"?(n.flush(),n.on("drain",function(){n.end()})):n.flushSync())}function zA(n){return function(t,s,r={},i){if(typeof r=="string")i=Mr({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=Mr({dest:i})}else if(r instanceof bl||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof bl||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=HA({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=Ln),i||(GA(process.stdout)?i=process.stdout:i=Mr({fd:process.stdout.fd||1})),{opts:r,stream:i}}}function YA(n,e){try{return JSON.stringify(n)}catch{try{return(e||this[vl])(n)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function JA(n,e,t){return{level:n,bindings:e,log:t}}function XA(n){let e=Number(n);return typeof n=="string"&&Number.isFinite(e)?e:n===void 0?1:n}Am.exports={noop:Ln,buildSafeSonicBoom:Mr,asChindings:WA,asJson:KA,genLog:UA,createArgsNormalizer:zA,stringify:YA,buildFormatters:JA,normalizeDestFileDescriptor:XA}});var Dr=j((_R,km)=>{var QA={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},ZA={ASC:"ASC",DESC:"DESC"};km.exports={DEFAULT_LEVELS:QA,SORTING_ORDER:ZA}});var Sl=j((AR,Tm)=>{"use strict";var{lsCacheSym:ek,levelValSym:wl,useOnlyCustomLevelsSym:tk,streamSym:nk,formattersSym:sk,hooksSym:rk,levelCompSym:$m}=In(),{noop:ik,genLog:un}=Lr(),{DEFAULT_LEVELS:gt,SORTING_ORDER:Cm}=Dr(),Em={fatal:n=>{let e=un(gt.fatal,n);return function(...t){let s=this[nk];if(e.call(this,...t),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:n=>un(gt.error,n),warn:n=>un(gt.warn,n),info:n=>un(gt.info,n),debug:n=>un(gt.debug,n),trace:n=>un(gt.trace,n)},xl=Object.keys(gt).reduce((n,e)=>(n[gt[e]]=e,n),{}),ok=Object.keys(xl).reduce((n,e)=>(n[e]='{"level":'+Number(e),n),{});function ak(n){let e=n[sk].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[ek]=s,n}function lk(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 ck(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[wl],r=this[wl]=t[n],i=this[tk],o=this[$m],a=this[rk].logMethod;for(let l in t){if(o(t[l],r)===!1){this[l]=ik;continue}this[l]=lk(l,i)?Em[l](a):un(t[l],a)}this.emit("level-change",n,r,e[s],s,this)}function uk(n){let{levels:e,levelVal:t}=this;return e&&e.labels?e.labels[t]:""}function dk(n){let{values:e}=this.levels,t=e[n];return t!==void 0&&this[$m](t,this[wl])}function fk(n,e,t){return n===Cm.DESC?e<=t:e>=t}function pk(n){return typeof n=="string"?fk.bind(null,n):n}function hk(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:xl,t),r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:gt,n);return{labels:s,values:r}}function mk(n,e,t){if(typeof n=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),t?[]:Object.keys(xl).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:gt,e);if(!(n in s))throw Error(`default level:${n} must be included in custom levels`)}function gk(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 yk(n){if(typeof n!="function"&&!(typeof n=="string"&&Object.values(Cm).includes(n)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Tm.exports={initialLsCache:ok,genLsCache:ak,levelMethods:Em,getLevel:uk,setLevel:ck,isLevelEnabled:dk,mappings:hk,assertNoLevelCollisions:gk,assertDefaultLevelFound:mk,genLevelComparison:pk,assertLevelComparison:yk}});var _l=j((kR,Rm)=>{"use strict";Rm.exports={version:"10.3.1"}});var Fm=j((CR,Nm)=>{"use strict";var{EventEmitter:bk}=require("node:events"),{lsCacheSym:vk,levelValSym:wk,setLevelSym:kl,getLevelSym:Pm,chindingsSym:Fr,mixinSym:xk,asJsonSym:Im,writeSym:Sk,mixinMergeStrategySym:_k,timeSym:Ak,timeSliceIndexSym:kk,streamSym:Mm,serializersSym:dn,formattersSym:bs,errorKeySym:$k,messageKeySym:Ck,useOnlyCustomLevelsSym:Ek,needsMetadataGsym:Tk,redactFmtSym:Rk,stringifySym:Pk,formatOptsSym:Ok,stringifiersSym:Ik,msgPrefixSym:$l,hooksSym:Mk}=In(),{getLevel:Lk,setLevel:Dk,isLevelEnabled:Nk,mappings:Fk,initialLsCache:jk,genLsCache:Hk,assertNoLevelCollisions:Bk}=Sl(),{asChindings:Cl,asJson:Uk,buildFormatters:Al,stringify:Om,noop:Lm}=Lr(),{version:qk}=_l(),Kk=nl(),Wk=class{},Dm={constructor:Wk,child:Gk,bindings:Vk,setBindings:zk,flush:Xk,isLevelEnabled:Nk,version:qk,get level(){return this[Pm]()},set level(n){this[kl](n)},get levelVal(){return this[wk]},set levelVal(n){throw Error("levelVal is read-only")},get msgPrefix(){return this[$l]},get[Symbol.toStringTag](){return"Pino"},[vk]:jk,[Sk]:Jk,[Im]:Uk,[Pm]:Lk,[kl]:Dk};Object.setPrototypeOf(Dm,bk.prototype);Nm.exports=function(){return Object.create(Dm)};var Nr=n=>n;function Gk(n,e){if(!n)throw Error("missing bindings for child Pino");let t=this[dn],s=this[bs],r=Object.create(this);if(e==null)return r[bs].bindings!==Nr&&(r[bs]=Al(s.level,Nr,s.log)),r[Fr]=Cl(r,n),this.onChild!==Lm&&this.onChild(r),r;if(e.hasOwnProperty("serializers")===!0){r[dn]=Object.create(null);for(let u in t)r[dn][u]=t[u];let a=Object.getOwnPropertySymbols(t);for(var i=0;i<a.length;i++){let u=a[i];r[dn][u]=t[u]}for(let u in e.serializers)r[dn][u]=e.serializers[u];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let u=l[o];r[dn][u]=e.serializers[u]}}else r[dn]=t;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:u}=e.formatters;r[bs]=Al(a||s.level,l||Nr,u||s.log)}else r[bs]=Al(s.level,Nr,s.log);if(e.hasOwnProperty("customLevels")===!0&&(Bk(this.levels,e.customLevels),r.levels=Fk(e.customLevels,r[Ek]),Hk(r)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){r.redact=e.redact;let a=Kk(r.redact,Om),l={stringify:a[Rk]};r[Pk]=Om,r[Ik]=a,r[Ok]=l}if(typeof e.msgPrefix=="string"&&(r[$l]=(this[$l]||"")+e.msgPrefix),r[Fr]=Cl(r,n),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;r[kl](a)}return this.onChild(r),r}function Vk(){let e=`{${this[Fr].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function zk(n){let e=Cl(this,n);this[Fr]=e}function Yk(n,e){return Object.assign(e,n)}function Jk(n,e,t){let s=this[Ak](),r=this[xk],i=this[$k],o=this[Ck],a=this[_k]||Yk,l,u=this[Mk].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[Im](l,e,t,s),f=this[Mm];f[Tk]===!0&&(f.lastLevel=t,f.lastObj=l,f.lastMsg=e,f.lastTime=s.slice(this[kk]),f.lastLogger=this),f.write(u?u(d):d)}function Xk(n){if(n!=null&&typeof n!="function")throw Error("callback must be a function");let e=this[Mm];typeof e.flush=="function"?e.flush(n||Lm):n&&n()}});var Um=j((Pl,Bm)=>{"use strict";var{hasOwnProperty:vs}=Object.prototype,pn=Rl();pn.configure=Rl;pn.stringify=pn;pn.default=pn;Pl.stringify=pn;Pl.configure=Rl;Bm.exports=pn;var Qk=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function qt(n){return n.length<5e3&&!Qk.test(n)?`"${n}"`:JSON.stringify(n)}function El(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 Zk=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Tl(n){return Zk.call(n)!==void 0&&n.length!==0}function jm(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 e$(n){if(vs.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 t$(n){let e;if(vs.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 n$(n,e){let t;if(vs.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 Hm(n,e){let t;if(vs.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 fn(n){return n===1?"1 item":`${n} items`}function s$(n){let e=new Set;for(let t of n)(typeof t=="string"||typeof t=="number")&&e.add(String(t));return e}function r$(n){if(vs.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 Rl(n){n={...n};let e=r$(n);e&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let t=e$(n),s=n$(n,"bigint"),r=t$(n),i=typeof r=="function"?r:void 0,o=Hm(n,"maximumDepth"),a=Hm(n,"maximumBreadth");function l(m,h,g,S,k,x){let A=h[m];switch(typeof A=="object"&&A!==null&&typeof A.toJSON=="function"&&(A=A.toJSON(m)),A=S.call(h,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=x;if(Array.isArray(A)){if(A.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(A),k!==""&&(x+=k,y+=`
715
716
  ${x}`,v=`,
716
717
  ${x}`);let F=Math.min(A.length,a),H=0;for(;H<F-1;H++){let T=l(String(H),A,g,S,k,x);y+=T!==void 0?T:"null",y+=v}let X=l(String(H),A,g,S,k,x);if(y+=X!==void 0?X:"null",A.length-1>a){let T=A.length-a-1;y+=`${v}"... ${fn(T)} not stringified"`}return k!==""&&(y+=`
717
718
  ${b}`),g.pop(),`[${y}]`}let w=Object.keys(A),_=w.length;if(_===0)return"{}";if(o<g.length+1)return'"[Object]"';let E="",I="";k!==""&&(x+=k,v=`,
@@ -727,11 +728,11 @@ ${A}`),g.pop(),`{${y}}`}case"number":return isFinite(h)?String(h):e?e(h):"null";
727
728
  ${k}`,I=`,
728
729
  ${k}`,$=Math.min(h.length,a),F=0;for(;F<$-1;F++){let X=d(String(F),h[F],g,S,k);E+=X!==void 0?X:"null",E+=I}let H=d(String(F),h[F],g,S,k);if(E+=H!==void 0?H:"null",h.length-1>a){let X=h.length-a-1;E+=`${I}"... ${fn(X)} not stringified"`}return E+=`
729
730
  ${x}`,g.pop(),`[${E}]`}let A=Object.keys(h),y=A.length;if(y===0)return"{}";if(o<g.length+1)return'"[Object]"';k+=S;let v=`,
730
- ${k}`,b="",w="",_=Math.min(y,a);Tl(h)&&(b+=Fm(h,v,a),A=A.slice(h.length),_-=h.length,w=v),r&&(A=El(A,i)),g.push(h);for(let E=0;E<_;E++){let I=A[E],$=d(I,h[I],g,S,k);$!==void 0&&(b+=`${w}${qt(I)}: ${$}`,w=v)}if(y>a){let E=y-a;b+=`${w}"...": "${fn(E)} not stringified"`,w=v}return w!==""&&(b=`
731
+ ${k}`,b="",w="",_=Math.min(y,a);Tl(h)&&(b+=jm(h,v,a),A=A.slice(h.length),_-=h.length,w=v),r&&(A=El(A,i)),g.push(h);for(let E=0;E<_;E++){let I=A[E],$=d(I,h[I],g,S,k);$!==void 0&&(b+=`${w}${qt(I)}: ${$}`,w=v)}if(y>a){let E=y-a;b+=`${w}"...": "${fn(E)} not stringified"`,w=v}return w!==""&&(b=`
731
732
  ${k}${b}
732
- ${x}`),g.pop(),`{${b}}`}case"number":return isFinite(h)?String(h):e?e(h):"null";case"boolean":return h===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(h);default:return e?e(h):void 0}}function f(m,h,g){switch(typeof h){case"string":return qt(h);case"object":{if(h===null)return"null";if(typeof h.toJSON=="function"){if(h=h.toJSON(m),typeof h!="object")return f(m,h,g);if(h===null)return"null"}if(g.indexOf(h)!==-1)return t;let S="",k=h.length!==void 0;if(k&&Array.isArray(h)){if(h.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(h);let b=Math.min(h.length,a),w=0;for(;w<b-1;w++){let E=f(String(w),h[w],g);S+=E!==void 0?E:"null",S+=","}let _=f(String(w),h[w],g);if(S+=_!==void 0?_:"null",h.length-1>a){let E=h.length-a-1;S+=`,"... ${fn(E)} not stringified"`}return g.pop(),`[${S}]`}let x=Object.keys(h),A=x.length;if(A===0)return"{}";if(o<g.length+1)return'"[Object]"';let y="",v=Math.min(A,a);k&&Tl(h)&&(S+=Fm(h,",",a),x=x.slice(h.length),v-=h.length,y=","),r&&(x=El(x,i)),g.push(h);for(let b=0;b<v;b++){let w=x[b],_=f(w,h[w],g);_!==void 0&&(S+=`${y}${qt(w)}:${_}`,y=",")}if(A>a){let b=A-a;S+=`${y}"...":"${fn(b)} not stringified"`}return g.pop(),`{${S}}`}case"number":return isFinite(h)?String(h):e?e(h):"null";case"boolean":return h===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(h);default:return e?e(h):void 0}}function p(m,h,g){if(arguments.length>1){let S="";if(typeof g=="number"?S=" ".repeat(Math.min(g,10)):typeof g=="string"&&(S=g.slice(0,10)),h!=null){if(typeof h=="function")return l("",{"":m},[],h,S,"");if(Array.isArray(h))return u("",m,[],t$(h),S,"")}if(S.length!==0)return d("",m,[],S,"")}return f("",m,[])}return p}});var Wm=j(($R,Km)=>{"use strict";var Ol=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:qm}=Dr(),s$=qm.info;function r$(n,e){n=n||[],e=e||{dedupe:!1};let t=Object.create(qm);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,[Ol]:!0,streamLevels:t};return Array.isArray(n)?n.forEach(a,s):a.call(s,n),n=null,s;function r(f){let p,m=this.lastLevel,{streams:h}=this,g=0,S;for(let k=i$(h.length,e.dedupe);a$(k,h.length,e.dedupe);k=o$(k,e.dedupe))if(p=h[k],p.level<=m){if(g!==0&&g!==p.level)break;if(S=p.stream,S[Ol]){let{lastTime:x,lastMsg:A,lastObj:y,lastLogger:v}=this;S.lastLevel=m,S.lastTime=x,S.lastMsg=A,S.lastObj=y,S.lastLogger=v}S.write(f),e.dedupe&&(g=p.level)}else if(!e.dedupe)break}function i(...f){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.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 p=typeof f.write=="function"||f.stream,m=f.write?f:f.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:h,streamLevels:g}=this,S;typeof f.levelVal=="number"?S=f.levelVal:typeof f.level=="string"?S=g[f.level]:typeof f.level=="number"?S=f.level:S=s$;let k={stream:m,level:S,levelVal:void 0,id:++s.lastId};return h.unshift(k),h.sort(Um),this.minLevel=h[0].level,s}function l(f){let{streams:p}=this,m=p.findIndex(h=>h.id===f);return m>=0&&(p.splice(m,1),p.sort(Um),this.minLevel=p.length>0?p[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 p=new Array(this.streams.length);for(let m=0;m<p.length;m++)p[m]={level:f,stream:this.streams[m].stream};return{write:r,add:a,remove:l,minLevel:f,streams:p,clone:d,emit:i,flushSync:o,[Ol]:!0}}}function Um(n,e){return n.level-e.level}function i$(n,e){return e?n-1:0}function o$(n,e){return e?n-1:n+1}function a$(n,e,t){return t?n>=0:n<e}Km.exports=r$});var Dl=j((CR,tt)=>{"use strict";var l$=require("node:os"),Zm=Qa(),c$=Za(),u$=nl(),eg=Th(),d$=Nm(),tg=In(),{configure:f$}=Bm(),{assertDefaultLevelFound:p$,mappings:ng,genLsCache:h$,genLevelComparison:m$,assertLevelComparison:g$}=Sl(),{DEFAULT_LEVELS:sg,SORTING_ORDER:y$}=Dr(),{createArgsNormalizer:b$,asChindings:v$,buildSafeSonicBoom:Gm,buildFormatters:w$,stringify:Il,normalizeDestFileDescriptor:Vm,noop:x$}=Lr(),{version:S$}=_l(),{chindingsSym:zm,redactFmtSym:_$,serializersSym:Ym,timeSym:A$,timeSliceIndexSym:k$,streamSym:$$,stringifySym:Jm,stringifySafeSym:Ml,stringifiersSym:Xm,setLevelSym:C$,endSym:E$,formatOptsSym:T$,messageKeySym:R$,errorKeySym:P$,nestedKeySym:O$,mixinSym:I$,levelCompSym:M$,useOnlyCustomLevelsSym:L$,formattersSym:Qm,hooksSym:D$,nestedKeyStrSym:N$,mixinMergeStrategySym:F$,msgPrefixSym:j$}=tg,{epochTime:rg,nullTime:H$}=eg,{pid:B$}=process,U$=l$.hostname(),q$=Zm.err,K$={level:"info",levelComparison:y$.ASC,levels:sg,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:B$,hostname:U$},serializers:Object.assign(Object.create(null),{err:q$}),formatters:Object.assign(Object.create(null),{bindings(n){return n},level(n,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:rg,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},W$=b$(K$),G$=Object.assign(Object.create(null),Zm);function Ll(...n){let e={},{opts:t,stream:s}=W$(e,c$(),...n);t.level&&typeof t.level=="string"&&sg[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:p,level:m,customLevels:h,levelComparison:g,mixin:S,mixinMergeStrategy:k,useOnlyCustomLevels:x,formatters:A,hooks:y,depthLimit:v,edgeLimit:b,onChild:w,msgPrefix:_}=t,E=f$({maximumDepth:v,maximumBreadth:b}),I=w$(A.level,A.bindings,A.log),$=Il.bind({[Ml]:E}),F=r?u$(r,$):{},H=r?{stringify:F[_$]}:{stringify:$},X="}"+(i?`\r
733
+ ${x}`),g.pop(),`{${b}}`}case"number":return isFinite(h)?String(h):e?e(h):"null";case"boolean":return h===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(h);default:return e?e(h):void 0}}function f(m,h,g){switch(typeof h){case"string":return qt(h);case"object":{if(h===null)return"null";if(typeof h.toJSON=="function"){if(h=h.toJSON(m),typeof h!="object")return f(m,h,g);if(h===null)return"null"}if(g.indexOf(h)!==-1)return t;let S="",k=h.length!==void 0;if(k&&Array.isArray(h)){if(h.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(h);let b=Math.min(h.length,a),w=0;for(;w<b-1;w++){let E=f(String(w),h[w],g);S+=E!==void 0?E:"null",S+=","}let _=f(String(w),h[w],g);if(S+=_!==void 0?_:"null",h.length-1>a){let E=h.length-a-1;S+=`,"... ${fn(E)} not stringified"`}return g.pop(),`[${S}]`}let x=Object.keys(h),A=x.length;if(A===0)return"{}";if(o<g.length+1)return'"[Object]"';let y="",v=Math.min(A,a);k&&Tl(h)&&(S+=jm(h,",",a),x=x.slice(h.length),v-=h.length,y=","),r&&(x=El(x,i)),g.push(h);for(let b=0;b<v;b++){let w=x[b],_=f(w,h[w],g);_!==void 0&&(S+=`${y}${qt(w)}:${_}`,y=",")}if(A>a){let b=A-a;S+=`${y}"...":"${fn(b)} not stringified"`}return g.pop(),`{${S}}`}case"number":return isFinite(h)?String(h):e?e(h):"null";case"boolean":return h===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(h);default:return e?e(h):void 0}}function p(m,h,g){if(arguments.length>1){let S="";if(typeof g=="number"?S=" ".repeat(Math.min(g,10)):typeof g=="string"&&(S=g.slice(0,10)),h!=null){if(typeof h=="function")return l("",{"":m},[],h,S,"");if(Array.isArray(h))return u("",m,[],s$(h),S,"")}if(S.length!==0)return d("",m,[],S,"")}return f("",m,[])}return p}});var Gm=j((ER,Wm)=>{"use strict";var Ol=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Km}=Dr(),i$=Km.info;function o$(n,e){n=n||[],e=e||{dedupe:!1};let t=Object.create(Km);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,[Ol]:!0,streamLevels:t};return Array.isArray(n)?n.forEach(a,s):a.call(s,n),n=null,s;function r(f){let p,m=this.lastLevel,{streams:h}=this,g=0,S;for(let k=a$(h.length,e.dedupe);c$(k,h.length,e.dedupe);k=l$(k,e.dedupe))if(p=h[k],p.level<=m){if(g!==0&&g!==p.level)break;if(S=p.stream,S[Ol]){let{lastTime:x,lastMsg:A,lastObj:y,lastLogger:v}=this;S.lastLevel=m,S.lastTime=x,S.lastMsg=A,S.lastObj=y,S.lastLogger=v}S.write(f),e.dedupe&&(g=p.level)}else if(!e.dedupe)break}function i(...f){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.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 p=typeof f.write=="function"||f.stream,m=f.write?f:f.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:h,streamLevels:g}=this,S;typeof f.levelVal=="number"?S=f.levelVal:typeof f.level=="string"?S=g[f.level]:typeof f.level=="number"?S=f.level:S=i$;let k={stream:m,level:S,levelVal:void 0,id:++s.lastId};return h.unshift(k),h.sort(qm),this.minLevel=h[0].level,s}function l(f){let{streams:p}=this,m=p.findIndex(h=>h.id===f);return m>=0&&(p.splice(m,1),p.sort(qm),this.minLevel=p.length>0?p[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 p=new Array(this.streams.length);for(let m=0;m<p.length;m++)p[m]={level:f,stream:this.streams[m].stream};return{write:r,add:a,remove:l,minLevel:f,streams:p,clone:d,emit:i,flushSync:o,[Ol]:!0}}}function qm(n,e){return n.level-e.level}function a$(n,e){return e?n-1:0}function l$(n,e){return e?n-1:n+1}function c$(n,e,t){return t?n>=0:n<e}Wm.exports=o$});var Dl=j((TR,tt)=>{"use strict";var u$=require("node:os"),eg=Qa(),d$=Za(),f$=nl(),tg=Rh(),p$=Fm(),ng=In(),{configure:h$}=Um(),{assertDefaultLevelFound:m$,mappings:sg,genLsCache:g$,genLevelComparison:y$,assertLevelComparison:b$}=Sl(),{DEFAULT_LEVELS:rg,SORTING_ORDER:v$}=Dr(),{createArgsNormalizer:w$,asChindings:x$,buildSafeSonicBoom:Vm,buildFormatters:S$,stringify:Il,normalizeDestFileDescriptor:zm,noop:_$}=Lr(),{version:A$}=_l(),{chindingsSym:Ym,redactFmtSym:k$,serializersSym:Jm,timeSym:$$,timeSliceIndexSym:C$,streamSym:E$,stringifySym:Xm,stringifySafeSym:Ml,stringifiersSym:Qm,setLevelSym:T$,endSym:R$,formatOptsSym:P$,messageKeySym:O$,errorKeySym:I$,nestedKeySym:M$,mixinSym:L$,levelCompSym:D$,useOnlyCustomLevelsSym:N$,formattersSym:Zm,hooksSym:F$,nestedKeyStrSym:j$,mixinMergeStrategySym:H$,msgPrefixSym:B$}=ng,{epochTime:ig,nullTime:U$}=tg,{pid:q$}=process,K$=u$.hostname(),W$=eg.err,G$={level:"info",levelComparison:v$.ASC,levels:rg,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:q$,hostname:K$},serializers:Object.assign(Object.create(null),{err:W$}),formatters:Object.assign(Object.create(null),{bindings(n){return n},level(n,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:ig,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},V$=w$(G$),z$=Object.assign(Object.create(null),eg);function Ll(...n){let e={},{opts:t,stream:s}=V$(e,d$(),...n);t.level&&typeof t.level=="string"&&rg[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:p,level:m,customLevels:h,levelComparison:g,mixin:S,mixinMergeStrategy:k,useOnlyCustomLevels:x,formatters:A,hooks:y,depthLimit:v,edgeLimit:b,onChild:w,msgPrefix:_}=t,E=h$({maximumDepth:v,maximumBreadth:b}),I=S$(A.level,A.bindings,A.log),$=Il.bind({[Ml]:E}),F=r?f$(r,$):{},H=r?{stringify:F[k$]}:{stringify:$},X="}"+(i?`\r
733
734
  `:`
734
- `),T=v$.bind(null,{[zm]:"",[Ym]:o,[Xm]:F,[Jm]:Il,[Ml]:E,[Qm]:I}),C="";f!==null&&(p===void 0?C=T(f):C=T(Object.assign({},f,{name:p})));let ne=a instanceof Function?a:a?rg:H$,D=ne().indexOf(":")+1;if(x&&!h)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(S&&typeof S!="function")throw Error(`Unknown mixin type "${typeof S}" - expected "function"`);if(_&&typeof _!="string")throw Error(`Unknown msgPrefix type "${typeof _}" - expected "string"`);p$(m,h,x);let W=ng(h,x);typeof s.emit=="function"&&s.emit("message",{code:"PINO_CONFIG",config:{levels:W,messageKey:l,errorKey:u}}),g$(g);let ie=m$(g);return Object.assign(e,{levels:W,[M$]:ie,[L$]:x,[$$]:s,[A$]:ne,[k$]:D,[Jm]:Il,[Ml]:E,[Xm]:F,[E$]:X,[T$]:H,[R$]:l,[P$]:u,[O$]:d,[N$]:d?`,${JSON.stringify(d)}:{`:"",[Ym]:o,[I$]:S,[F$]:k,[zm]:C,[Qm]:I,[D$]:y,silent:x$,onChild:w,[j$]:_}),Object.setPrototypeOf(e,d$()),h$(e),e[C$](m),e}tt.exports=Ll;tt.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=Vm(n.dest||process.stdout.fd),Gm(n)):Gm({dest:Vm(n),minLength:0});tt.exports.transport=gl();tt.exports.multistream=Wm();tt.exports.levels=ng();tt.exports.stdSerializers=G$;tt.exports.stdTimeFunctions=Object.assign({},eg);tt.exports.symbols=tg;tt.exports.version=S$;tt.exports.default=Ll;tt.exports.pino=Ll});function ws(n){return new Nl(n)}var V$,z$,Y$,Nl,Fl=N(()=>{"use strict";V$={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},z$=`
735
+ `),T=x$.bind(null,{[Ym]:"",[Jm]:o,[Qm]:F,[Xm]:Il,[Ml]:E,[Zm]:I}),C="";f!==null&&(p===void 0?C=T(f):C=T(Object.assign({},f,{name:p})));let ne=a instanceof Function?a:a?ig:U$,D=ne().indexOf(":")+1;if(x&&!h)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(S&&typeof S!="function")throw Error(`Unknown mixin type "${typeof S}" - expected "function"`);if(_&&typeof _!="string")throw Error(`Unknown msgPrefix type "${typeof _}" - expected "string"`);m$(m,h,x);let W=sg(h,x);typeof s.emit=="function"&&s.emit("message",{code:"PINO_CONFIG",config:{levels:W,messageKey:l,errorKey:u}}),b$(g);let ie=y$(g);return Object.assign(e,{levels:W,[D$]:ie,[N$]:x,[E$]:s,[$$]:ne,[C$]:D,[Xm]:Il,[Ml]:E,[Qm]:F,[R$]:X,[P$]:H,[O$]:l,[I$]:u,[M$]:d,[j$]:d?`,${JSON.stringify(d)}:{`:"",[Jm]:o,[L$]:S,[H$]:k,[Ym]:C,[Zm]:I,[F$]:y,silent:_$,onChild:w,[B$]:_}),Object.setPrototypeOf(e,p$()),g$(e),e[T$](m),e}tt.exports=Ll;tt.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=zm(n.dest||process.stdout.fd),Vm(n)):Vm({dest:zm(n),minLength:0});tt.exports.transport=gl();tt.exports.multistream=Gm();tt.exports.levels=sg();tt.exports.stdSerializers=z$;tt.exports.stdTimeFunctions=Object.assign({},tg);tt.exports.symbols=ng;tt.exports.version=A$;tt.exports.default=Ll;tt.exports.pino=Ll});function ws(n){return new Nl(n)}var Y$,J$,X$,Nl,Fl=N(()=>{"use strict";Y$={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},J$=`
735
736
  ## Reasoning Protocol
736
737
 
737
738
  Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
@@ -760,15 +761,15 @@ After receiving a tool result, think again:
760
761
  - One tool call per turn. Wait for the result before the next call.
761
762
  - If a tool fails, analyze the error in <thinking> before retrying.
762
763
  - When done, give a concise final answer WITHOUT <thinking> tags.
763
- `.trim(),Y$=`
764
+ `.trim(),X$=`
764
765
  ## Reasoning
765
766
  For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
766
767
  The user will NOT see thinking blocks. One tool call per turn.
767
- `.trim(),Nl=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...V$,...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}
768
+ `.trim(),Nl=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...Y$,...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}
768
769
 
769
- ${Y$}`:`${e}
770
+ ${X$}`:`${e}
770
771
 
771
- ${z$}`}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(`
772
+ ${J$}`}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(`
772
773
 
773
774
  `).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`
774
775
  <self_eval>
@@ -791,11 +792,11 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
791
792
  }
792
793
  </self_eval>
793
794
  `.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(`
794
- `)}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 xs(n=3){return new jl(n)}var J$,jl,Hl=N(()=>{"use strict";J$=[{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}],jl=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 J$)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(`
795
- `)}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 X$(){try{if(Mt.existsSync(jr))return JSON.parse(Mt.readFileSync(jr,"utf-8"))}catch{}return{}}function Q$(n){try{let e=Hr.dirname(jr);Mt.existsSync(e)||Mt.mkdirSync(e,{recursive:!0}),Mt.writeFileSync(jr,JSON.stringify(n,null,2),"utf-8")}catch{}}function Kl(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 Ss(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 Z$(n){return n.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function e0(n){let e=[],t=/<<?action\s*>>?([\s\S]*?)(?:<<?\/action\s*>>?|$)/gi,s;for(;(s=t.exec(n))!==null;){let r=s[1].trim();if(r)try{let i=JSON.parse(r);i.tool&&i.args&&typeof i.args=="object"&&e.push({tool:i.tool,args:i.args,format:"action_tag_json",rawMatch:s[0]})}catch{let i=Kl(r,r.indexOf("{"));if(i)try{let o=JSON.parse(i);o.tool&&o.args&&typeof o.args=="object"&&e.push({tool:o.tool,args:o.args,format:"action_tag_json",rawMatch:s[0]})}catch{}}}return e}function t0(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=Ss(r);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function n0(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=Ss(r);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function s0(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=og(r);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function og(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 p=d[1].toLowerCase(),m=d[2]??d[3]??d[4];l[p]=Z$(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 r0(n){return og(n)}function i0(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=Ss(r);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function o0(n){let e=[],t=/\{\s*"function"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Kl(n,s.index);if(r)try{let i=JSON.parse(r),o=Ss(i);o&&e.push({...o,format:"function_call",rawMatch:r})}catch{}}return e}function a0(n){let e=[],t=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Kl(n,s.index);if(r)try{let i=JSON.parse(r),o=Ss(i);o&&e.push({...o,format:"json_object",rawMatch:r})}catch{}}return e}function l0(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(),p=d[2].trim();p==="true"?p=!0:p==="false"?p=!1:!isNaN(Number(p))&&p!==""&&(p=Number(p)),l[f]=p}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 ag(){return Ul||(Ul=new ql),Ul}var Mt,Hr,ig,jr,Bl,ql,Ul,lg=N(()=>{"use strict";Mt=O(require("fs")),Hr=O(require("path")),ig=O(require("os")),jr=Hr.join(ig.homedir(),".hablas","model-formats.json");Bl=[{format:"action_tag_json",parse:e0},{format:"xml_tool_call_wrapper",parse:s0},{format:"xml_prompt",parse:r0},{format:"xml_tags",parse:t0},{format:"xml_parameters",parse:l0},{format:"hermes",parse:n0},{format:"markdown_json",parse:i0},{format:"function_call",parse:o0},{format:"json_object",parse:a0}],ql=class{registry;constructor(){this.registry=X$()}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=Bl.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 Bl){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!!(/<<?action[\s>]/i.test(t)||/<<?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 Bl)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()},Q$(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(/<<?action>>?[\s\S]*?<<?\/action>>?/gi,""),r=r.replace(/\n{3,}/g,`
795
+ `)}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 xs(n=3){return new jl(n)}var Q$,jl,Hl=N(()=>{"use strict";Q$=[{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}],jl=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 Q$)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(`
796
+ `)}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 Z$(){try{if(It.existsSync(jr))return JSON.parse(It.readFileSync(jr,"utf-8"))}catch{}return{}}function e0(n){try{let e=Hr.dirname(jr);It.existsSync(e)||It.mkdirSync(e,{recursive:!0}),It.writeFileSync(jr,JSON.stringify(n,null,2),"utf-8")}catch{}}function Kl(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 Ss(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 t0(n){return n.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function n0(n){let e=[],t=/<<?action\s*>>?([\s\S]*?)(?:<<?\/action\s*>>?|$)/gi,s;for(;(s=t.exec(n))!==null;){let r=s[1].trim();if(r)try{let i=JSON.parse(r);i.tool&&i.args&&typeof i.args=="object"&&e.push({tool:i.tool,args:i.args,format:"action_tag_json",rawMatch:s[0]})}catch{let i=Kl(r,r.indexOf("{"));if(i)try{let o=JSON.parse(i);o.tool&&o.args&&typeof o.args=="object"&&e.push({tool:o.tool,args:o.args,format:"action_tag_json",rawMatch:s[0]})}catch{}}}return e}function s0(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=Ss(r);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function r0(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=Ss(r);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function i0(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=ag(r);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function ag(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 p=d[1].toLowerCase(),m=d[2]??d[3]??d[4];l[p]=t0(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 o0(n){return ag(n)}function a0(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=Ss(r);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function l0(n){let e=[],t=/\{\s*"function"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Kl(n,s.index);if(r)try{let i=JSON.parse(r),o=Ss(i);o&&e.push({...o,format:"function_call",rawMatch:r})}catch{}}return e}function c0(n){let e=[],t=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Kl(n,s.index);if(r)try{let i=JSON.parse(r),o=Ss(i);o&&e.push({...o,format:"json_object",rawMatch:r})}catch{}}return e}function u0(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(),p=d[2].trim();p==="true"?p=!0:p==="false"?p=!1:!isNaN(Number(p))&&p!==""&&(p=Number(p)),l[f]=p}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 lg(){return Ul||(Ul=new ql),Ul}var It,Hr,og,jr,Bl,ql,Ul,cg=N(()=>{"use strict";It=O(require("fs")),Hr=O(require("path")),og=O(require("os")),jr=Hr.join(og.homedir(),".hablas","model-formats.json");Bl=[{format:"action_tag_json",parse:n0},{format:"xml_tool_call_wrapper",parse:i0},{format:"xml_prompt",parse:o0},{format:"xml_tags",parse:s0},{format:"xml_parameters",parse:u0},{format:"hermes",parse:r0},{format:"markdown_json",parse:a0},{format:"function_call",parse:l0},{format:"json_object",parse:c0}],ql=class{registry;constructor(){this.registry=Z$()}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=Bl.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 Bl){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!!(/<<?action[\s>]/i.test(t)||/<<?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 Bl)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()},e0(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(/<<?action>>?[\s\S]*?<<?\/action>>?/gi,""),r=r.replace(/\n{3,}/g,`
796
797
 
797
- `),{toolCalls:s,displayContent:r.trim(),format:e[0]?.format??"unknown"}}},Ul=null});function u0(n,e,t){let r=ag().parse(e,n,t);return{toolCalls:r.toolCalls,displayContent:r.displayContent}}function d0(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 f0(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 dg(n,e,t,s){let r=0,i=Date.now();for(;r<=ug;){let o=await n.execute({name:e,arguments:t});if(o.success||r>=ug)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 Ur(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??ws(),p=n.errorRecovery??xs(),m=d?[]:s.getOllamaTools(),h=t.getModel(),g=n.maxIterations??150,S="IDLE",k=0,x=(E,I)=>{let $=c0[S];if(!$||!$.includes(E))throw new Error(`\u{1F6AB} Illegal State Transition Attempt: ${S} \u2501\u2501\u25B6 ${E} (Reason: ${I??"none"})`);o.info({from:S,to:E,reason:I},"FSM State Transition"),S=E},A=[],y=[],v=[],b="",w=0,_=!1;for(x("THINKING","Starting agentic turn");w<g;){if(w++,u?.aborted)return x("TERMINAL_ABORT","Operation aborted by signal"),{output:b,toolsUsed:De(A),toolResults:y,touchedFiles:De(v),iterations:w,success:!1,error:"Aborted",completedNaturally:_};let E=f.buildBudgetWarningPrompt();E&&r.addUserMessage(E,{priority:"critical",tags:["system-budget"]});let I;try{I=await t.chatWithTools(r.getMessages(),m,u)}catch(C){if(C.name==="AbortError"||u?.aborted)return x("TERMINAL_ABORT","Aborted during inference"),{output:b,toolsUsed:De(A),toolResults:y,touchedFiles:De(v),iterations:w,success:!1,error:"Aborted",completedNaturally:_};if(w<=1){a.onNotice?.(`Transient model error: ${C.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(ne=>setTimeout(ne,1e3)),w--;continue}return x("TERMINAL_ABORT","Inference failure"),a.onError?.(C.message??"Model request failed"),{output:b,toolsUsed:De(A),toolResults:y,touchedFiles:De(v),iterations:w,success:!1,error:C.message,completedNaturally:_}}let $=I.message?.content||"",F=I.message?.tool_calls,H=f.parseThinking($);H.hasThinking&&(f.recordStep({thought:H.thinking}),o.debug({thinking:H.thinking.slice(0,200)},"ReAct thinking")),x("PARSE_VALIDATING","Received model response, parsing");let{toolCalls:X,displayContent:T}=u0(F,$,h);if(X.length===0&&$.toLowerCase().includes("<action>")){if(k++,k>=Br){x("STATE_RECONCILIATION",`Self-correction loop exhausted after ${k} attempts`);let ne=`Failed to execute after ${Br} syntax corrections. Rollback initiated.`;a.onError?.(ne);try{let D=s.get("undo");D&&await D.execute({count:100})}catch{}return x("TERMINAL_ABORT","Fatal syntactic self-correction exhaustion"),{output:b,toolsUsed:De(A),toolResults:y,touchedFiles:De(v),iterations:w,success:!1,error:ne,completedNaturally:_}}let C=`[SYSTEM ERROR - RETRY ${k}/${Br}] Malformed action block detected inside <action> tags. Expected a valid JSON object matching the HEP-1 tool schema.
798
- Please correct your format and try again. Ensure all JSON keys/values are double-quoted and correctly escaped.`;x("ERROR_HEALING",`Syntax error inside action tags (attempt ${k})`),a.onNotice?.(`Malformed action block detected \u2014 healing attempt ${k}/${Br}\u2026`,"retry"),r.addToolMessage(C),x("THINKING","Error injected, waiting for next generation");continue}if(T&&T.trim()&&(b=T,await a.onAssistantText?.(T,e)),X.length===0){r.addAssistantMessage($,void 0,e.role),_=!0,x("SYNTHESIZING","Completed execution naturally");break}x("ACTION_READY","Action parsed and verified"),r.addAssistantMessage($,X,e.role);for(let C=0;C<X.length;C++){let ne=X[C];if(!ne?.function?.name)continue;let D=ne.function.name,W=ne.function.arguments||{},ie=s.getSafetyLevel(D)??"confirm";if(!s.get(D)){x("ERROR_HEALING",`Unknown tool execution: ${D}`),a.onNotice?.(`Unknown tool: ${D} \u2014 skipping`,"warn"),r.addToolMessage(`Error: Unknown tool "${D}". Available: ${s.getAll().map(re=>re.name).join(", ")}`),x("THINKING","Returning to thought loop");continue}if(await l(D,ie,W)==="skip"){r.addToolMessage(`Tool ${D} was skipped by policy/user.`);break}A.push(D),typeof W.path=="string"&&v.push(W.path);let ee=d0(D,W);a.onToolStart?.(D,ee,W),a.onToolCall?.(),f.recordStep({thought:H.hasThinking?`Executing: ${D}`:"",action:D,actionInput:W}),x("EXECUTING_TOOL",`Executing tool: ${D}`);let ge=await dg(s,D,W,o);a.onToolEnd?.(D,ge.success,ge.error||ge.output,ge.duration,W);let Ne;if(ge.success)Ne=ds(ge.output,cg),f.recordObservation(Ne.slice(0,300)),y.push({tool:D,success:!0,summary:ge.output.slice(0,150)}),x("THINKING",`Successfully executed tool: ${D}`);else{let re=ge.error||"Unknown error";if(f0(re)){x("STATE_RECONCILIATION",`Critical failure in tool ${D}: ${re}`),a.onNotice?.("Critical tool failure \u2014 aborting and rolling back changes.","warn");try{let se=s.get("undo");se&&await se.execute({count:100})}catch{}return x("TERMINAL_ABORT","State reverted due to critical failure"),{output:b,toolsUsed:De(A),toolResults:y,touchedFiles:De(v),iterations:w,success:!1,error:re,completedNaturally:_}}let K=p.analyze(D,re,W);if(Ne=p.buildRecoveryMessage(K,re),f.recordObservation(`FAILED: ${re}`,`Recovery: ${K.strategy} \u2014 ${K.suggestion}`),y.push({tool:D,success:!1,summary:re.slice(0,150)}),K.autoRetry&&!f.isOverBudget()){x("ERROR_HEALING","Attempting auto-recovery for transient error"),a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let se=await dg(s,D,W,o);a.onToolEnd?.(D,se.success,se.output,se.duration,W),se.success?(Ne=ds(se.output,cg),f.recordObservation(Ne.slice(0,300),"Auto-retry succeeded"),y[y.length-1]={tool:D,success:!0,summary:se.output.slice(0,150)},x("THINKING","Recovery successful")):x("THINKING","Recovery failed, continuing turn")}else x("THINKING","Continuing turn with failed step")}r.addToolMessage(Ne),ge.success&&D==="read_file"&&typeof W.path=="string"&&i?.addFile(W.path,ge.output),o.info({tool:D,success:ge.success,durationMs:ge.duration,retries:ge.retries},"Tool executed")}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return w>=g&&!_?(a.onNotice?.(`Reached max iterations (${g}). Stopping.`,"warn"),x("TERMINAL_ABORT","Max iterations boundary exceeded"),{output:b,toolsUsed:De(A),toolResults:y,touchedFiles:De(v),iterations:w,success:!1,error:"Max iterations exceeded",completedNaturally:_}):(x("TERMINAL_SUCCESS","Turn finalized successfully"),S="IDLE",{output:b,toolsUsed:De(A),toolResults:y,touchedFiles:De(v),iterations:w,success:!0,completedNaturally:_})}function De(n){return[...new Set(n)]}function fg(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 pg(){return(n,e)=>e==="dangerous"?"skip":"allow"}var cg,ug,Br,c0,Wl=N(()=>{"use strict";ba();Fl();Hl();lg();cg=2e3,ug=2,Br=3,c0={IDLE:["THINKING"],THINKING:["PARSE_VALIDATING","TERMINAL_ABORT"],PARSE_VALIDATING:["ACTION_READY","ERROR_HEALING","SYNTHESIZING","TERMINAL_ABORT"],ACTION_READY:["EXECUTING_TOOL","STATE_RECONCILIATION","TERMINAL_ABORT"],EXECUTING_TOOL:["THINKING","ERROR_HEALING","STATE_RECONCILIATION","TERMINAL_ABORT"],ERROR_HEALING:["THINKING","STATE_RECONCILIATION","TERMINAL_ABORT"],STATE_RECONCILIATION:["TERMINAL_ABORT"],SYNTHESIZING:["TERMINAL_SUCCESS","TERMINAL_ABORT"],TERMINAL_SUCCESS:["IDLE"],TERMINAL_ABORT:["IDLE"]}});var mg,p0,h0,m0,hg,qr,gg=N(()=>{"use strict";mg=O(Dl());Bn();wa();va();mn();Fi();Ua();Wl();p0={hablas:"planner",bob:"architect",alex:"coder",david:"researcher",emma:"product-manager"},h0=(0,mg.default)({level:"silent"}),m0=40,hg={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}},qr=class{baseConfig;agentModels;toolRegistry=null;onOutput=null;channel=null;mindsetRegistry=br();sharedContext=null;contextManager;constructor(e){this.baseConfig=e,this.agentModels=qn(),this.contextManager=new on(e)}setSharedContext(e){this.sharedContext=e}setChannel(e){this.channel=e}setToolRegistry(e){this.toolRegistry=e}setOutputCallback(e){this.onOutput=e}reloadModels(){this.agentModels=qn()}getAgentModel(e){let t=this.agentModels[e];if(t)return{model:t.model,temperature:t.temperature??hg[e]?.temperature??.5};let s=hg[e];return{model:s.model,temperature:s.temperature??.5}}async runAgent(e,t,s,r,i){let o=Date.now(),a=_e.find(x=>x.role===e),l=this.getAgentModel(e),u=i?.maxIterations||m0,d={...this.baseConfig,model:l.model},f=je(d),p=this.buildAgentPrompt(a,s),m=new an(p,30,this.baseConfig.contextBudget);m.addUserMessage(t);let h={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:x=>{this.emit(a.name,"speaking",x.slice(0,200))},onToolStart:(x,A,y)=>{this.emit(a.name,"tool",A),this.channel&&this.channel.emitEvent({type:"act",agent:a.name,toolName:x,toolArgs:this.safeArgs(y),content:A})},onToolEnd:(x,A,y)=>{this.channel&&this.channel.emitEvent({type:"observe",agent:a.name,toolName:x,success:A,content:A?this.summarizeOk(x,y):`error: ${y.slice(0,120)}`})},onError:x=>this.emit(a.name,"error",x)},S=await Ur({identity:h,client:f,registry:this.toolRegistry,session:m,contextManager:this.contextManager,logger:h0,io:g,safetyPolicy:pg(),abortSignal:i?.abortSignal,skipTools:(!r||r.length===0,!1),maxIterations:u});if(this.sharedContext&&S.touchedFiles.length)try{this.sharedContext.set(`files:@${a.name}`,S.touchedFiles.join(", "))}catch{}let k=S.touchedFiles.length?[`@${a.name} touched: ${S.touchedFiles.join(", ")}`]:[];return{agent:e,agentName:a.name,output:S.output||(S.success?"Done.":S.error??"No output"),toolsUsed:S.toolsUsed,toolResults:S.toolResults,duration:Date.now()-o,iterations:S.iterations,success:S.success,error:S.error,discoveries:k,touchedFiles:S.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(`
798
+ `),{toolCalls:s,displayContent:r.trim(),format:e[0]?.format??"unknown"}}},Ul=null});function f0(n,e,t){let r=lg().parse(e,n,t);return{toolCalls:r.toolCalls,displayContent:r.displayContent}}function p0(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 h0(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 fg(n,e,t,s){let r=0,i=Date.now();for(;r<=dg;){let o=await n.execute({name:e,arguments:t});if(o.success||r>=dg)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 Ur(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??ws(),p=n.errorRecovery??xs(),m=d?[]:s.getOllamaTools(),h=t.getModel(),g=n.maxIterations??150,S="IDLE",k=0,x=(E,I)=>{let $=d0[S];if(!$||!$.includes(E))throw new Error(`\u{1F6AB} Illegal State Transition Attempt: ${S} \u2501\u2501\u25B6 ${E} (Reason: ${I??"none"})`);o.info({from:S,to:E,reason:I},"FSM State Transition"),S=E},A=[],y=[],v=[],b="",w=0,_=!1;for(x("THINKING","Starting agentic turn");w<g;){if(w++,u?.aborted)return x("TERMINAL_ABORT","Operation aborted by signal"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:"Aborted",completedNaturally:_};let E=f.buildBudgetWarningPrompt();E&&r.addUserMessage(E,{priority:"critical",tags:["system-budget"]});let I;try{I=await t.chatWithTools(r.getMessages(),m,u)}catch(C){if(C.name==="AbortError"||u?.aborted)return x("TERMINAL_ABORT","Aborted during inference"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:"Aborted",completedNaturally:_};if(w<=1){a.onNotice?.(`Transient model error: ${C.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(ne=>setTimeout(ne,1e3)),w--;continue}return x("TERMINAL_ABORT","Inference failure"),a.onError?.(C.message??"Model request failed"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:C.message,completedNaturally:_}}let $=I.message?.content||"",F=I.message?.tool_calls,H=f.parseThinking($);H.hasThinking&&(f.recordStep({thought:H.thinking}),o.debug({thinking:H.thinking.slice(0,200)},"ReAct thinking")),x("PARSE_VALIDATING","Received model response, parsing");let{toolCalls:X,displayContent:T}=f0(F,$,h);if(X.length===0&&$.toLowerCase().includes("<action>")){if(k++,k>=Br){x("STATE_RECONCILIATION",`Self-correction loop exhausted after ${k} attempts`);let ne=`Failed to execute after ${Br} syntax corrections. Rollback initiated.`;a.onError?.(ne);try{let D=s.get("undo");D&&await D.execute({count:100})}catch{}return x("TERMINAL_ABORT","Fatal syntactic self-correction exhaustion"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:ne,completedNaturally:_}}let C=`[SYSTEM ERROR - RETRY ${k}/${Br}] Malformed action block detected inside <action> tags. Expected a valid JSON object matching the HEP-1 tool schema.
799
+ Please correct your format and try again. Ensure all JSON keys/values are double-quoted and correctly escaped.`;x("ERROR_HEALING",`Syntax error inside action tags (attempt ${k})`),a.onNotice?.(`Malformed action block detected \u2014 healing attempt ${k}/${Br}\u2026`,"retry"),r.addToolMessage(C),x("THINKING","Error injected, waiting for next generation");continue}if(T&&T.trim()&&(b=T,await a.onAssistantText?.(T,e)),X.length===0){r.addAssistantMessage($,void 0,e.role),_=!0,x("SYNTHESIZING","Completed execution naturally");break}x("ACTION_READY","Action parsed and verified"),r.addAssistantMessage($,X,e.role);for(let C=0;C<X.length;C++){let ne=X[C];if(!ne?.function?.name)continue;let D=ne.function.name,W=ne.function.arguments||{},ie=s.getSafetyLevel(D)??"confirm";if(!s.get(D)){x("ERROR_HEALING",`Unknown tool execution: ${D}`),a.onNotice?.(`Unknown tool: ${D} \u2014 skipping`,"warn"),r.addToolMessage(`Error: Unknown tool "${D}". Available: ${s.getAll().map(re=>re.name).join(", ")}`),x("THINKING","Returning to thought loop");continue}if(await l(D,ie,W)==="skip"){r.addToolMessage(`Tool ${D} was skipped by policy/user.`);break}A.push(D),typeof W.path=="string"&&v.push(W.path);let ee=p0(D,W);a.onToolStart?.(D,ee,W),a.onToolCall?.(),f.recordStep({thought:H.hasThinking?`Executing: ${D}`:"",action:D,actionInput:W}),x("EXECUTING_TOOL",`Executing tool: ${D}`);let ge=await fg(s,D,W,o);a.onToolEnd?.(D,ge.success,ge.error||ge.output,ge.duration,W);let Fe;if(ge.success)Fe=ds(ge.output,ug),f.recordObservation(Fe.slice(0,300)),y.push({tool:D,success:!0,summary:ge.output.slice(0,150)}),x("THINKING",`Successfully executed tool: ${D}`);else{let re=ge.error||"Unknown error";if(h0(re)){x("STATE_RECONCILIATION",`Critical failure in tool ${D}: ${re}`),a.onNotice?.("Critical tool failure \u2014 aborting and rolling back changes.","warn");try{let se=s.get("undo");se&&await se.execute({count:100})}catch{}return x("TERMINAL_ABORT","State reverted due to critical failure"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:re,completedNaturally:_}}let K=p.analyze(D,re,W);if(Fe=p.buildRecoveryMessage(K,re),f.recordObservation(`FAILED: ${re}`,`Recovery: ${K.strategy} \u2014 ${K.suggestion}`),y.push({tool:D,success:!1,summary:re.slice(0,150)}),K.autoRetry&&!f.isOverBudget()){x("ERROR_HEALING","Attempting auto-recovery for transient error"),a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let se=await fg(s,D,W,o);a.onToolEnd?.(D,se.success,se.output,se.duration,W),se.success?(Fe=ds(se.output,ug),f.recordObservation(Fe.slice(0,300),"Auto-retry succeeded"),y[y.length-1]={tool:D,success:!0,summary:se.output.slice(0,150)},x("THINKING","Recovery successful")):x("THINKING","Recovery failed, continuing turn")}else x("THINKING","Continuing turn with failed step")}r.addToolMessage(Fe),ge.success&&D==="read_file"&&typeof W.path=="string"&&i?.addFile(W.path,ge.output),o.info({tool:D,success:ge.success,durationMs:ge.duration,retries:ge.retries},"Tool executed")}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return w>=g&&!_?(a.onNotice?.(`Reached max iterations (${g}). Stopping.`,"warn"),x("TERMINAL_ABORT","Max iterations boundary exceeded"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:"Max iterations exceeded",completedNaturally:_}):(x("TERMINAL_SUCCESS","Turn finalized successfully"),S="IDLE",{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!0,completedNaturally:_})}function Ne(n){return[...new Set(n)]}function pg(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 hg(){return(n,e)=>e==="dangerous"?"skip":"allow"}var ug,dg,Br,d0,Wl=N(()=>{"use strict";ba();Fl();Hl();cg();ug=2e3,dg=2,Br=3,d0={IDLE:["THINKING"],THINKING:["PARSE_VALIDATING","TERMINAL_ABORT"],PARSE_VALIDATING:["ACTION_READY","ERROR_HEALING","SYNTHESIZING","TERMINAL_ABORT"],ACTION_READY:["EXECUTING_TOOL","STATE_RECONCILIATION","TERMINAL_ABORT"],EXECUTING_TOOL:["THINKING","ERROR_HEALING","STATE_RECONCILIATION","TERMINAL_ABORT"],ERROR_HEALING:["THINKING","STATE_RECONCILIATION","TERMINAL_ABORT"],STATE_RECONCILIATION:["TERMINAL_ABORT"],SYNTHESIZING:["TERMINAL_SUCCESS","TERMINAL_ABORT"],TERMINAL_SUCCESS:["IDLE"],TERMINAL_ABORT:["IDLE"]}});var gg,m0,g0,y0,mg,qr,yg=N(()=>{"use strict";gg=O(Dl());Bn();wa();va();mn();Ni();Ua();Wl();m0={hablas:"planner",bob:"architect",alex:"coder",david:"researcher",emma:"product-manager"},g0=(0,gg.default)({level:"silent"}),y0=40,mg={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}},qr=class{baseConfig;agentModels;toolRegistry=null;onOutput=null;channel=null;mindsetRegistry=br();sharedContext=null;contextManager;constructor(e){this.baseConfig=e,this.agentModels=qn(),this.contextManager=new on(e)}setSharedContext(e){this.sharedContext=e}setChannel(e){this.channel=e}setToolRegistry(e){this.toolRegistry=e}setOutputCallback(e){this.onOutput=e}reloadModels(){this.agentModels=qn()}getAgentModel(e){let t=this.agentModels[e];if(t)return{model:t.model,temperature:t.temperature??mg[e]?.temperature??.5};let s=mg[e];return{model:s.model,temperature:s.temperature??.5}}async runAgent(e,t,s,r,i){let o=Date.now(),a=_e.find(x=>x.role===e),l=this.getAgentModel(e),u=i?.maxIterations||y0,d={...this.baseConfig,model:l.model},f=He(d),p=this.buildAgentPrompt(a,s),m=new an(p,30,this.baseConfig.contextBudget);m.addUserMessage(t);let h={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:x=>{this.emit(a.name,"speaking",x.slice(0,200))},onToolStart:(x,A,y)=>{this.emit(a.name,"tool",A),this.channel&&this.channel.emitEvent({type:"act",agent:a.name,toolName:x,toolArgs:this.safeArgs(y),content:A})},onToolEnd:(x,A,y)=>{this.channel&&this.channel.emitEvent({type:"observe",agent:a.name,toolName:x,success:A,content:A?this.summarizeOk(x,y):`error: ${y.slice(0,120)}`})},onError:x=>this.emit(a.name,"error",x)},S=await Ur({identity:h,client:f,registry:this.toolRegistry,session:m,contextManager:this.contextManager,logger:g0,io:g,safetyPolicy:hg(),abortSignal:i?.abortSignal,skipTools:(!r||r.length===0,!1),maxIterations:u});if(this.sharedContext&&S.touchedFiles.length)try{this.sharedContext.set(`files:@${a.name}`,S.touchedFiles.join(", "))}catch{}let k=S.touchedFiles.length?[`@${a.name} touched: ${S.touchedFiles.join(", ")}`]:[];return{agent:e,agentName:a.name,output:S.output||(S.success?"Done.":S.error??"No output"),toolsUsed:S.toolsUsed,toolResults:S.toolResults,duration:Date.now()-o,iterations:S.iterations,success:S.success,error:S.error,discoveries:k,touchedFiles:S.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(`
799
800
  ## Handoff Chain`);for(let h of o)d.push(`- @${h.from} \u2192 @${h.to}: ${h.context.slice(0,100)}`)}let f=d.join(`
800
801
  `),p=_e.find(h=>h.role===l);if(p&&a>0){let h=e[a-1].role,g=_e.find(S=>S.role===h);this.emit(p.name,"thinking",`\u2605 Handoff: @${g?.name||h} \u2192 @${p.name} (${p.title})`)}let m=await this.runAgent(l,u,f,t,s);if(r.push(m),m.success&&m.output){let h=m.output.length>600?m.output.slice(0,600)+"...":m.output;i+=`
801
802
 
@@ -806,7 +807,7 @@ ${h}`,a<e.length-1&&o.push({from:l,to:e[a+1].role,context:m.output.slice(0,200),
806
807
  Error: ${i.error}
807
808
  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",`@${_e.find(l=>l.role===e)?.name} failed. Hablas taking over...`);let a=`Agent @${e} failed twice on this task.
808
809
  Original error: ${i.error}
809
- Please complete this task.`;return this.runAgent("hablas",t,a,r)}return i}buildAgentPrompt(e,t){let s=p0[e.role]??"coder",r=this.mindsetRegistry.get(s),o=(r?`${r.systemPrompt}
810
+ Please complete this task.`;return this.runAgent("hablas",t,a,r)}return i}buildAgentPrompt(e,t){let s=m0[e.role]??"coder",r=this.mindsetRegistry.get(s),o=(r?`${r.systemPrompt}
810
811
 
811
812
  ---
812
813
 
@@ -867,15 +868,15 @@ Expertise: ${e.expertise.join(", ")}
867
868
  ${t}`),this.sharedContext){let a=this.sharedContext.getSummary();a&&(o+=`
868
869
 
869
870
  ## Shared Team Context
870
- ${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 yg,Kr,bg=N(()=>{"use strict";yg=require("events"),Kr=class extends yg.EventEmitter{events=[];maxHistory;constructor(e=500){super(),this.setMaxListeners(50),this.maxHistory=e}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),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 g0,bt,Wr,Gr,vg=N(()=>{"use strict";Bn();g0={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."},bt={hablas:"Hablas",emma:"Emma",bob:"Bob",alex:"Alex",david:"David"},Wr={handoff:(n,e,t)=>{let s=bt[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, @${bt[e]}. Proceeding.`,review:(n,e)=>`@${bt[e]}, structurally sound. Watch the boundaries on the next pass.`,reviewAck:(n,e)=>`Noted, @${bt[e]}. Integrating.`},Gr=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=je(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),()=>Wr.handoff(e,t,s))}async generateAckLine(e,t){return this.generate(`ack:${e}:${t}`,this.buildPrompt(e,t,"ack"),()=>Wr.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)),()=>Wr.review(e,t))}async generateReviewAck(e,t){return this.generate(`reviewAck:${e}:${t}`,this.buildPrompt(e,t,"reviewAck"),()=>Wr.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 ${bt[e]}, speaking in your own voice.
871
- ${g0[e]}
871
+ ${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 bg,Kr,vg=N(()=>{"use strict";bg=require("events"),Kr=class extends bg.EventEmitter{events=[];maxHistory;constructor(e=500){super(),this.setMaxListeners(50),this.maxHistory=e}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),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 b0,yt,Wr,Gr,wg=N(()=>{"use strict";Bn();b0={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."},yt={hablas:"Hablas",emma:"Emma",bob:"Bob",alex:"Alex",david:"David"},Wr={handoff:(n,e,t)=>{let s=yt[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, @${yt[e]}. Proceeding.`,review:(n,e)=>`@${yt[e]}, structurally sound. Watch the boundaries on the next pass.`,reviewAck:(n,e)=>`Noted, @${yt[e]}. Integrating.`},Gr=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=He(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),()=>Wr.handoff(e,t,s))}async generateAckLine(e,t){return this.generate(`ack:${e}:${t}`,this.buildPrompt(e,t,"ack"),()=>Wr.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)),()=>Wr.review(e,t))}async generateReviewAck(e,t){return this.generate(`reviewAck:${e}:${t}`,this.buildPrompt(e,t,"reviewAck"),()=>Wr.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 ${yt[e]}, speaking in your own voice.
872
+ ${b0[e]}
872
873
 
873
874
  Hard constraints:
874
875
  - Output exactly ONE sentence.
875
876
  - No prefix, no quotes, no markdown, no emojis, no role labels.
876
877
  - Maximum ${this.opts.maxChars} characters.
877
- - Address @${bt[t]} directly.
878
- - Stay in character. Be useful, not chatty.`,o;switch(s){case"handoff":o=`You are about to hand the following task to @${bt[t]}. Write a single in-character line that briefly frames what you need from them. Task: "${(r||"").slice(0,300)}"`;break;case"ack":o=`@${bt[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 @${bt[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=`@${bt[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 ae,ct,y0,xg,b0,Sg,wg,Dn,Gl=N(()=>{"use strict";ae=O(require("fs")),ct=O(require("path")),y0=".hablas",xg=`# Project Context
878
+ - Address @${yt[t]} directly.
879
+ - Stay in character. Be useful, not chatty.`,o;switch(s){case"handoff":o=`You are about to hand the following task to @${yt[t]}. Write a single in-character line that briefly frames what you need from them. Task: "${(r||"").slice(0,300)}"`;break;case"ack":o=`@${yt[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 @${yt[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=`@${yt[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 ae,ct,v0,Sg,w0,_g,xg,Dn,Gl=N(()=>{"use strict";ae=O(require("fs")),ct=O(require("path")),v0=".hablas",Sg=`# Project Context
879
880
 
880
881
  ## Overview
881
882
  <!-- Auto-generated by hablas. Describe your project here. -->
@@ -888,31 +889,31 @@ Hard constraints:
888
889
 
889
890
  ## Notes
890
891
  <!-- Miscellaneous context for agents -->
891
- `,b0=`# Decisions Log
892
+ `,w0=`# Decisions Log
892
893
 
893
894
  | Date | Decision | By | Rationale |
894
895
  |------|----------|-----|-----------|
895
- `,Sg=`# Task Assignments
896
+ `,_g=`# Task Assignments
896
897
 
897
898
  ## Active Tasks
898
899
  <!-- Format: - [ ] Task description (@agent) -->
899
900
 
900
901
  ## Completed
901
902
  <!-- Format: - [x] Task description (@agent) \u2014 result -->
902
- `,wg={"CONTEXT.md":xg,"DECISIONS.md":b0,"TASKS.md":Sg},Dn=class{contextDir;constructor(e){this.contextDir=ct.join(e,y0)}init(){let e=ct.join(ct.dirname(this.contextDir),".flowagent");if(ae.existsSync(e)&&!ae.existsSync(this.contextDir))try{ae.renameSync(e,this.contextDir)}catch{}ae.existsSync(this.contextDir)||ae.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(wg)){let r=ct.join(this.contextDir,t);ae.existsSync(r)||ae.writeFileSync(r,s,"utf-8")}}exists(){return ae.existsSync(this.contextDir)}read(e){let t=ct.join(this.contextDir,e);return ae.existsSync(t)?ae.readFileSync(t,"utf-8"):null}write(e,t){this.ensureDir();let s=ct.join(this.contextDir,e);ae.writeFileSync(s,t,"utf-8")}append(e,t){this.ensureDir();let s=ct.join(this.contextDir,e),r=ae.existsSync(s)?ae.readFileSync(s,"utf-8"):"";ae.writeFileSync(s,r+`
903
- `+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")||Sg).replace(`## Active Tasks
903
+ `,xg={"CONTEXT.md":Sg,"DECISIONS.md":w0,"TASKS.md":_g},Dn=class{contextDir;constructor(e){this.contextDir=ct.join(e,v0)}init(){let e=ct.join(ct.dirname(this.contextDir),".flowagent");if(ae.existsSync(e)&&!ae.existsSync(this.contextDir))try{ae.renameSync(e,this.contextDir)}catch{}ae.existsSync(this.contextDir)||ae.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(xg)){let r=ct.join(this.contextDir,t);ae.existsSync(r)||ae.writeFileSync(r,s,"utf-8")}}exists(){return ae.existsSync(this.contextDir)}read(e){let t=ct.join(this.contextDir,e);return ae.existsSync(t)?ae.readFileSync(t,"utf-8"):null}write(e,t){this.ensureDir();let s=ct.join(this.contextDir,e);ae.writeFileSync(s,t,"utf-8")}append(e,t){this.ensureDir();let s=ct.join(this.contextDir,e),r=ae.existsSync(s)?ae.readFileSync(s,"utf-8"):"";ae.writeFileSync(s,r+`
904
+ `+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")||_g).replace(`## Active Tasks
904
905
  `,`## Active Tasks
905
906
  ${s}
906
907
  `);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 ae.existsSync(this.contextDir)?ae.readdirSync(this.contextDir).filter(t=>t.endsWith(".md")).map(t=>{let s=ct.join(this.contextDir,t),r=ae.statSync(s);return{file:t,content:ae.readFileSync(s,"utf-8"),lastModified:r.mtime}}):[]}getSummary(){let e=this.getAll();return e.length===0?"":e.map(t=>`### ${t.file}
907
908
  ${t.content}`).join(`
908
909
 
909
- `)}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(wg)){let s=ct.join(this.contextDir,e);ae.existsSync(s)&&ae.writeFileSync(s,t,"utf-8")}}getDecisions(){let e=this.read("DECISIONS.md");if(!e)return[];let t=e.split(`
910
+ `)}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(xg)){let s=ct.join(this.contextDir,e);ae.existsSync(s)&&ae.writeFileSync(s,t,"utf-8")}}getDecisions(){let e=this.read("DECISIONS.md");if(!e)return[];let t=e.split(`
910
911
  `),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(`
911
912
  `).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(`
912
- `)}persistKV(){if(this.kvStore.size===0)return;let e=this.read("CONTEXT.md")||xg,t=Array.from(this.kvStore.entries()).map(([i,o])=>`- **${i}**: ${o}`).join(`
913
+ `)}persistKV(){if(this.kvStore.size===0)return;let e=this.read("CONTEXT.md")||Sg,t=Array.from(this.kvStore.entries()).map(([i,o])=>`- **${i}**: ${o}`).join(`
913
914
  `),s=/## Notes\n[\s\S]*$/,r=e.replace(s,`## Notes
914
915
  ${t}
915
- `);this.write("CONTEXT.md",r)}ensureDir(){ae.existsSync(this.contextDir)||ae.mkdirSync(this.contextDir,{recursive:!0})}}});function Vl(n){return _e.find(e=>e.role===n)?.name||n}var Nn,_g=N(()=>{"use strict";mn();Gl();Nn=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=new Dn(process.cwd());this.runner.setSharedContext(o),this.channel.emitEvent({type:"phase",agent:"System",content:"Delegating to the team"});let a=t.tasks.filter(p=>p.role!=="hablas").map(p=>({role:p.role,task:`${p.description}
916
+ `);this.write("CONTEXT.md",r)}ensureDir(){ae.existsSync(this.contextDir)||ae.mkdirSync(this.contextDir,{recursive:!0})}}});function Vl(n){return _e.find(e=>e.role===n)?.name||n}var Nn,Ag=N(()=>{"use strict";mn();Gl();Nn=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=new Dn(process.cwd());this.runner.setSharedContext(o),this.channel.emitEvent({type:"phase",agent:"System",content:"Delegating to the team"});let a=t.tasks.filter(p=>p.role!=="hablas").map(p=>({role:p.role,task:`${p.description}
916
917
 
917
918
  Original request: ${e}`})),l=[],u="hablas",d=null;for(let p of a){if(r.abortSignal?.aborted)break;let m=_e.find(x=>x.role===p.role);if(!m)continue;this.channel.emitEvent({type:"handoff",agent:Vl(u),to:m.name});let h=await this.chat.generateHandoffLine(u,p.role,p.task);this.channel.emitEvent({type:"speak",agent:Vl(u),to:m.name,content:h});let g=await this.chat.generateAckLine(p.role,u);this.channel.emitEvent({type:"speak",agent:m.name,to:Vl(u),content:g});let S=Date.now(),k=await this.runner.runAgent(p.role,p.task,void 0,s,{abortSignal:r.abortSignal});l.push(k),k.success&&k.output?(this.channel.emitEvent({type:"summary",agent:m.name,durationMs:Date.now()-S}),p.role==="alex"&&(d=k.output),i&&p.role==="alex"&&t.tasks.some(x=>x.role==="bob")&&d&&await this.runPeerReview("bob","alex",d,r.abortSignal)):k.error&&this.channel.emitEvent({type:"error",agent:m.name,content:k.error}),u=p.role}this.channel.emitEvent({type:"phase",agent:"System",content:"Hablas compiling final report"});let f=await this.synthesize(e,l,s,r.abortSignal);return this.channel.emitEvent({type:"done",agent:"Hablas"}),f}async runPeerReview(e,t,s,r){let i=_e.find(u=>u.role===e),o=_e.find(u=>u.role===t);if(!i||!o)return;let a=await this.chat.generateReviewLine(e,t,s);this.channel.emitEvent({type:"review",agent:i.name,to:o.name,content:a});let l=await this.chat.generateReviewAck(t,e);this.channel.emitEvent({type:"speak",agent:o.name,to:i.name,content:l}),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=_e.find(p=>p.role===d.agent);return`### Report from @${d.agentName} (${f?.title??d.agent}):
918
919
  ${d.output}`}).join(`
@@ -927,10 +928,11 @@ ${o}
927
928
  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=_e.find(p=>p.role===d.agent);return`### @${d.agentName} (${f?.title??d.agent}):
928
929
  ${d.output}`}).join(`
929
930
 
930
- `);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 Vr(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 zr,Ag=N(()=>{"use strict";xn();zr=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(`
931
- ${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(Vr(t))} ${r(t)} ${c.muted("\u2501\u2501\u25B6")} ${i(Vr(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);this.print(` ${t("\u25C9")} [Active Agent: ${e.agent}] is thinking & formulating response\u2026`)}renderSpeak(e){let t=_s(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(Vr(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=_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=ut(t),o=ut(s);this.print(`
932
- ${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(Vr(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=ut(e.agent);this.print(` ${s("\u25C6")} ${s(e.agent)} ${c.muted("decision:")} ${c.secondary(t)}`)}renderDone(e){this.print(`
933
- ${c.chrome("\u2500".repeat(56))}`),this.lastThinking=null}renderError(e){let t=ut(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 Yr,kg=N(()=>{"use strict";Yr=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 pe,dt,v0,w0,x0,S0,_0,A0,k0,Jr,$g=N(()=>{"use strict";pe=O(require("fs")),dt=O(require("path")),v0=".hablas",w0=`# Project Context \u2014 Hablas AI
931
+ `);return{results:t,finalSynthesis:u,synthesisOk:!1}}}});function Mt(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 kg(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}function zl(n){return n==="Hablas"?"Team Leader":n==="Bob"?"Architect":n==="Alex"?"Engineer":n==="David"?"Data Analyst":n==="Emma"?"Product Manager":"Specialist"}var Vr,$g=N(()=>{"use strict";xn();Vr=class{channel;opts;attached=!1;listener;lastThinking=null;lastLine="";state={taskTitle:"Autonomous Codebase Engineering",currentPhase:"Initializing",activeAgent:"Hablas",activeAgentTitle:"Team Leader",currentActivity:"Analyzing workspace",roster:{Hablas:"active",Emma:"pending",Bob:"pending",Alex:"pending",David:"pending"}};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.state.currentPhase=t,(t.includes("compiling")||t.includes("report")||t.includes("synthesizing"))&&(this.state.activeAgent="Hablas",this.state.activeAgentTitle="Team Leader",this.state.roster.Hablas="active",this.state.currentActivity="Compiling individual reports and synthesizing final unified solution"),this.print(`
932
+ `+no(this.state)),this.lastThinking=null)}renderHandoff(e){let t=e.agent,s=e.to||"";s&&(this.state.roster[t]&&(this.state.roster[t]="done"),this.state.roster[s]="active",this.state.activeAgent=s,this.state.activeAgentTitle=zl(s),this.state.currentPhase=`Task Handoff to @${s}`,this.state.currentActivity=`Transitioning task context from @${t} to @${s}`,this.print(`
933
+ `+no(this.state)),this.lastThinking=null)}renderThinking(e){if(this.opts.hideThinking||this.lastThinking===e.agent)return;this.lastThinking=e.agent;let t=Mt(e.agent);this.state.activeAgent=e.agent,this.state.activeAgentTitle=zl(e.agent),this.state.roster[e.agent]="active",this.state.currentActivity="Analyzing workspace & formulating reasoning steps",this.print(` ${t("\u25C9")} [Active Agent: ${e.agent}] is thinking & formulating response\u2026`)}renderSpeak(e){let t=_s(e.content||"",this.opts.maxChars);if(!t)return;let s=Mt(e.agent),r=e.to?` ${c.muted("\u2192")} ${Mt(e.to)("@"+e.to)}`:"",i=`speak:${e.agent}:${e.to||""}:${t}`;i!==this.lastLine&&(this.lastLine=i,this.print(` ${s(kg(e.agent))} ${s(e.agent)}${r}${c.muted(":")} ${c.secondary(t)}`),this.lastThinking=null)}renderAct(e){if(this.opts.hideActs)return;let t=Mt(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.state.activeAgent=e.agent,this.state.activeAgentTitle=zl(e.agent),this.state.roster[e.agent]="active",this.state.currentActivity=`Executing ${s}${i}`,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=Mt(t),o=Mt(s);this.print(`
934
+ ${i("\u270E")} ${c.strong("@"+t)} ${c.muted("reviewing")} ${o("@"+s)}${c.muted(":")} ${c.secondary(r)}`),this.lastThinking=null}renderSummary(e){let t=Mt(e.agent),s=e.durationMs?` ${c.muted(`(${(e.durationMs/1e3).toFixed(1)}s)`)}`:"";this.print(` ${t(kg(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=Mt(e.agent);this.print(` ${s("\u25C6")} ${s(e.agent)} ${c.muted("decision:")} ${c.secondary(t)}`)}renderDone(e){this.print(`
935
+ ${c.chrome("\u2500".repeat(56))}`),this.lastThinking=null}renderError(e){let t=Mt(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 zr,Cg=N(()=>{"use strict";zr=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 pe,ut,x0,S0,_0,A0,k0,$0,C0,Yr,Eg=N(()=>{"use strict";pe=O(require("fs")),ut=O(require("path")),x0=".hablas",S0=`# Project Context \u2014 Hablas AI
934
936
 
935
937
  ## Project Overview
936
938
  <!-- Auto-populated by Hablas on first scan -->
@@ -947,7 +949,7 @@ ${d.output}`}).join(`
947
949
 
948
950
  ## Team Notes
949
951
  <!-- Freeform notes from agents and user -->
950
- `,x0=`# Requirements & Progress
952
+ `,_0=`# Requirements & Progress
951
953
 
952
954
  ## Current Sprint
953
955
  <!-- Active work items -->
@@ -964,7 +966,7 @@ ${d.output}`}).join(`
964
966
 
965
967
  ## Progress Log
966
968
  <!-- Chronological log of all actions taken -->
967
- `,S0=`# Architecture Design
969
+ `,A0=`# Architecture Design
968
970
 
969
971
  ## System Overview
970
972
  <!-- High-level architecture description -->
@@ -992,7 +994,7 @@ ${d.output}`}).join(`
992
994
 
993
995
  ## Implementation Guide
994
996
  <!-- Step-by-step implementation order -->
995
- `,_0=`# Agent Activity Log
997
+ `,k0=`# Agent Activity Log
996
998
 
997
999
  ## Session History
998
1000
  | Session | Date | Duration | Agents Used | Tasks Completed |
@@ -1008,7 +1010,7 @@ ${d.output}`}).join(`
1008
1010
 
1009
1011
  ## Inter-Agent Communication
1010
1012
  <!-- Messages exchanged between agents during complex tasks -->
1011
- `,A0=`# Learned Knowledge
1013
+ `,$0=`# Learned Knowledge
1012
1014
 
1013
1015
  ## Project Conventions
1014
1016
  <!-- Coding style, naming conventions, file organization patterns -->
@@ -1024,7 +1026,7 @@ ${d.output}`}).join(`
1024
1026
 
1025
1027
  ## Dependency Notes
1026
1028
  <!-- Important notes about dependencies and versions -->
1027
- `,k0={"HABLAS.md":w0,"PROGRESS.md":x0,"ARCHITECTURE.md":S0,"AGENTS.md":_0,"MEMORY.md":A0},Jr=class{contextDir;sessionDelegations=[];sessionDiscoveries=[];constructor(e){this.contextDir=dt.join(e,v0)}init(){let e=dt.join(dt.dirname(this.contextDir),".hablas-legacy");if(pe.existsSync(e)&&!pe.existsSync(this.contextDir))try{pe.renameSync(e,this.contextDir);let t=dt.join(this.contextDir,"LEGACY.md"),s=dt.join(this.contextDir,"HABLAS.md");pe.existsSync(t)&&!pe.existsSync(s)&&pe.renameSync(t,s)}catch{}pe.existsSync(this.contextDir)||pe.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(k0)){let r=dt.join(this.contextDir,t);pe.existsSync(r)||pe.writeFileSync(r,s,"utf-8")}}exists(){return pe.existsSync(this.contextDir)}readContext(e){let t=dt.join(this.contextDir,e);return pe.existsSync(t)?pe.readFileSync(t,"utf-8"):null}updateProgress(e){let t=new Date().toISOString().split("T")[0],s=new Date().toISOString().split("T")[1].split(".")[0],r=`- [${t} ${s}] ${e}`;this.appendToSection("PROGRESS.md","## Progress Log",r)}addTask(e,t){let s=new Date().toISOString().split("T")[0],r=`| ${e} | @${t} | \u{1F535} pending | ${s} | \u2014 |`;this.appendToSection("PROGRESS.md","## Task Breakdown",r)}updateSprint(e){this.updateSection("PROGRESS.md","## Current Sprint",e)}recordDecision(e,t,s,r="medium"){let o=`| ${new Date().toISOString().split("T")[0]} | ${e} | ${t} | ${s} | ${r} |`;this.appendToSection("HABLAS.md","## Key Decisions",o)}updateArchitecture(e,t){this.updateSection("ARCHITECTURE.md",e,t)}recordADR(e,t,s="accepted"){let r=new Date().toISOString().split("T")[0],a=`| ${((this.readContext("ARCHITECTURE.md")||"").match(/^\|/gm)||[]).length} | ${e} | ${s} | ${r} | ${t} |`;this.appendToSection("ARCHITECTURE.md","## Architecture Decision Records (ADRs)",a)}logDelegation(e){this.sessionDelegations.push(e);let t=`| ${e.time} | ${e.from} | ${e.to} | ${e.task.slice(0,50)} | ${e.model} | ${e.result} | ${e.durationMs}ms |`;this.appendToSection("AGENTS.md","## Delegation Log",t)}logSession(e){let t=`| ${e.sessionId} | ${e.date} | ${Math.round(e.duration/1e3)}s | ${e.agentsUsed.join(", ")} | ${e.tasksCompleted} |`;this.appendToSection("AGENTS.md","## Session History",t)}updateAgentPerformance(e,t,s,r,i){let o=`| @${e} | ${t} | ${Math.round(s*100)}% | ${Math.round(r)}ms | ${i.join(", ")} |`;this.appendToSection("AGENTS.md","## Agent Performance",o)}logAgentComm(e,t,s){let i=`- [${new Date().toISOString()}] **@${e}** \u2192 **@${t}**: ${s.slice(0,200)}`;this.appendToSection("AGENTS.md","## Inter-Agent Communication",i)}addConvention(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Project Conventions",r),this.sessionDiscoveries.push({type:"convention",description:e,source:t,date:s})}addPattern(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Discovered Patterns",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}addGotcha(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u26A0\uFE0F ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Known Gotchas",r),this.sessionDiscoveries.push({type:"gotcha",description:e,source:t,date:s})}addAutoDiscovery(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u{1F50D} ${e} *(by ${t})*`;this.appendToSection("MEMORY.md","## Auto-Discoveries",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}getSummary(e=8e3){let t=["HABLAS.md","PROGRESS.md","ARCHITECTURE.md","MEMORY.md"],s=[],r=0;for(let i of t){let o=this.readContext(i);if(o&&o.trim().length>0){let a=e-r;if(a<=200)break;let l=o.length>a?o.slice(0,a)+`
1029
+ `,C0={"HABLAS.md":S0,"PROGRESS.md":_0,"ARCHITECTURE.md":A0,"AGENTS.md":k0,"MEMORY.md":$0},Yr=class{contextDir;sessionDelegations=[];sessionDiscoveries=[];constructor(e){this.contextDir=ut.join(e,x0)}init(){let e=ut.join(ut.dirname(this.contextDir),".hablas-legacy");if(pe.existsSync(e)&&!pe.existsSync(this.contextDir))try{pe.renameSync(e,this.contextDir);let t=ut.join(this.contextDir,"LEGACY.md"),s=ut.join(this.contextDir,"HABLAS.md");pe.existsSync(t)&&!pe.existsSync(s)&&pe.renameSync(t,s)}catch{}pe.existsSync(this.contextDir)||pe.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(C0)){let r=ut.join(this.contextDir,t);pe.existsSync(r)||pe.writeFileSync(r,s,"utf-8")}}exists(){return pe.existsSync(this.contextDir)}readContext(e){let t=ut.join(this.contextDir,e);return pe.existsSync(t)?pe.readFileSync(t,"utf-8"):null}updateProgress(e){let t=new Date().toISOString().split("T")[0],s=new Date().toISOString().split("T")[1].split(".")[0],r=`- [${t} ${s}] ${e}`;this.appendToSection("PROGRESS.md","## Progress Log",r)}addTask(e,t){let s=new Date().toISOString().split("T")[0],r=`| ${e} | @${t} | \u{1F535} pending | ${s} | \u2014 |`;this.appendToSection("PROGRESS.md","## Task Breakdown",r)}updateSprint(e){this.updateSection("PROGRESS.md","## Current Sprint",e)}recordDecision(e,t,s,r="medium"){let o=`| ${new Date().toISOString().split("T")[0]} | ${e} | ${t} | ${s} | ${r} |`;this.appendToSection("HABLAS.md","## Key Decisions",o)}updateArchitecture(e,t){this.updateSection("ARCHITECTURE.md",e,t)}recordADR(e,t,s="accepted"){let r=new Date().toISOString().split("T")[0],a=`| ${((this.readContext("ARCHITECTURE.md")||"").match(/^\|/gm)||[]).length} | ${e} | ${s} | ${r} | ${t} |`;this.appendToSection("ARCHITECTURE.md","## Architecture Decision Records (ADRs)",a)}logDelegation(e){this.sessionDelegations.push(e);let t=`| ${e.time} | ${e.from} | ${e.to} | ${e.task.slice(0,50)} | ${e.model} | ${e.result} | ${e.durationMs}ms |`;this.appendToSection("AGENTS.md","## Delegation Log",t)}logSession(e){let t=`| ${e.sessionId} | ${e.date} | ${Math.round(e.duration/1e3)}s | ${e.agentsUsed.join(", ")} | ${e.tasksCompleted} |`;this.appendToSection("AGENTS.md","## Session History",t)}updateAgentPerformance(e,t,s,r,i){let o=`| @${e} | ${t} | ${Math.round(s*100)}% | ${Math.round(r)}ms | ${i.join(", ")} |`;this.appendToSection("AGENTS.md","## Agent Performance",o)}logAgentComm(e,t,s){let i=`- [${new Date().toISOString()}] **@${e}** \u2192 **@${t}**: ${s.slice(0,200)}`;this.appendToSection("AGENTS.md","## Inter-Agent Communication",i)}addConvention(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Project Conventions",r),this.sessionDiscoveries.push({type:"convention",description:e,source:t,date:s})}addPattern(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Discovered Patterns",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}addGotcha(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u26A0\uFE0F ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Known Gotchas",r),this.sessionDiscoveries.push({type:"gotcha",description:e,source:t,date:s})}addAutoDiscovery(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u{1F50D} ${e} *(by ${t})*`;this.appendToSection("MEMORY.md","## Auto-Discoveries",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}getSummary(e=8e3){let t=["HABLAS.md","PROGRESS.md","ARCHITECTURE.md","MEMORY.md"],s=[],r=0;for(let i of t){let o=this.readContext(i);if(o&&o.trim().length>0){let a=e-r;if(a<=200)break;let l=o.length>a?o.slice(0,a)+`
1028
1030
  ...(truncated)`:o;s.push(`### ${i}
1029
1031
  ${l}`),r+=l.length}}return s.length>0?s.join(`
1030
1032
 
@@ -1036,47 +1038,47 @@ ${a}`),r=s.join(`
1036
1038
  `)}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}
1037
1039
  ${d}`),o+=d.length}}}extractSection(e,t){let s=e.split(`
1038
1040
  `),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(`
1039
- `).trim()}updateSection(e,t,s){let r=dt.join(this.contextDir,e);if(!pe.existsSync(r))return;let o=pe.readFileSync(r,"utf-8").split(`
1041
+ `).trim()}updateSection(e,t,s){let r=ut.join(this.contextDir,e);if(!pe.existsSync(r))return;let o=pe.readFileSync(r,"utf-8").split(`
1040
1042
  `),a=o.findIndex(p=>p.trim()===t);if(a===-1)return;let l=o.length;for(let p=a+1;p<o.length;p++)if(/^#{1,2}\s/.test(o[p])){l=p;break}let u=o.slice(0,a+1),d=o.slice(l),f=[...u,s,"",...d].join(`
1041
- `);pe.writeFileSync(r,f,"utf-8")}appendToSection(e,t,s){let r=dt.join(this.contextDir,e);pe.existsSync(r)||this.init();let i=pe.readFileSync(r,"utf-8"),o=i.split(`
1043
+ `);pe.writeFileSync(r,f,"utf-8")}appendToSection(e,t,s){let r=ut.join(this.contextDir,e);pe.existsSync(r)||this.init();let i=pe.readFileSync(r,"utf-8"),o=i.split(`
1042
1044
  `),a=o.findIndex(u=>u.trim()===t);if(a===-1){pe.writeFileSync(r,i+`
1043
1045
  `+s+`
1044
1046
  `,"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),pe.writeFileSync(r,o.join(`
1045
- `),"utf-8")}}});function zl(n){let e=n.trim(),t=e.toLowerCase();if($0.test(e)||C0.test(e)||e.length<15&&!E0.test(e))return"XS";if(P0.test(t)||Cg.test(t)&&e.length>150)return"XL";let s=t.match(R0)||[],i=new Set(s.map(a=>a.toLowerCase())).size,o=e.split(/[.!?]+/).filter(a=>a.trim().length>5);return Cg.test(t)||o.length>=3&&i>=2||i>=3&&e.length>100?"L":O0.test(t)||i>=2&&e.length>=50||e.length>=50&&e.length<=150&&i>=1&&o.length>=2?"M":(e.length<50&&i<=1||T0.test(e)&&i<=1||i===1,"S")}function Eg(n,e,t){let s=`sp-${Date.now()}`,r=[],i=1,o=t.includes("emma"),a=t.includes("bob"),l=t.includes("alex"),u=t.includes("david");switch(e){case"XS":break;case"S":r.push({id:`${s}-t${i++}`,description:`Execute: ${n.substring(0,80)}`,assignee:l?"alex":t.find(f=>f!=="hablas")||"alex",dependencies:[]});break;case"M":{u&&r.push({id:`${s}-t${i++}`,description:"Research requirements and gather context",assignee:"david",dependencies:[]});let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:`Implement: ${n.substring(0,60)}`,assignee:l?"alex":"hablas",dependencies:f});break}case"L":{if(u&&r.push({id:`${s}-t${i++}`,description:"Research requirements, best practices, and relevant documentation",assignee:"david",dependencies:[]}),a){let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:"Design system architecture and structure",assignee:"bob",dependencies:f})}if(l){let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:"Implement the code based on architecture/requirements",assignee:"alex",dependencies:f})}break}case"XL":{if(o&&r.push({id:`${s}-t${i++}`,description:"Analyze requirements and create PRD with user stories",assignee:"emma",dependencies:[]}),u){let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:"Research best practices, technologies, and competitive landscape",assignee:"david",dependencies:f})}if(a){let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:"Design complete system architecture, database schema, and API structure",assignee:"bob",dependencies:f})}if(l){let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:"Implement the full system based on PRD and architecture",assignee:"alex",dependencies:f})}break}}let d;return r.length<=1?d="direct":r.every((f,p)=>p===0||f.dependencies.length>0)?d="sequential":d="mixed",{id:s,title:n.substring(0,100),complexity:e,tasks:r,strategy:d,requiresApproval:e==="L"||e==="XL",createdAt:Date.now()}}var $0,C0,E0,T0,R0,P0,Cg,O0,Tg=N(()=>{"use strict";$0=/^(hi|hello|hey|howdy|yo|sup|hiya|good\s*(morning|afternoon|evening|night)|what'?s\s*up|greetings|thanks?|thank\s*you|bye|goodbye|ok(ay)?|yes|no|cool|nice|great|got\s*it|sure|مرحبا|أهلا|هلا|السلام\s*عليكم|كيف\s*حالك)\b/i,C0=/^(how\s*are\s*you|what'?s\s*your\s*name|who\s*are\s*you|what\s*can\s*you\s*do|help|tell\s*me\s*about\s*yourself)\s*[?!.]*$/i,E0=/\b(create|build|implement|write|generate|code|make|develop|design|architect|setup|configure|install|deploy|fix|debug|refactor|rewrite|restructure|migrate|convert|add|remove|delete|update|change|modify|edit|move|rename|test|run|execute|analyze|research|find|search|compare|optimize)\b/i,T0=/[\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|toml|xml|env)/i,R0=/\b(create|build|implement|write|generate|design|architect|setup|configure|deploy|fix|debug|refactor|rewrite|restructure|migrate|add|remove|update|change|modify|test|analyze|research|optimize)\b/gi,P0=/\b(full\s+system|complete\s+project|from\s+scratch|entire\s+application|prd|product\s+requirements|architecture\s+.*implementation\s+.*deployment|end[\s-]*to[\s-]*end)\b/i,Cg=/\b(design|architect)\b.*\b(implement|build|create|develop)\b/i,O0=/\b(multiple\s+files|several\s+components|across\s+all|every\s+file|all\s+modules)\b/i});function Pg(n){let e=n.trim();if(e.length<20||Un(e)||Rg.test(e)||e.includes("```")||M0.test(e)||/\/[\w-]+\.[\w]+/.test(e)||e.length<60&&Rg.test(e))return null;for(let{pattern:t,question:s,choices:r}of I0)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 Og(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 I0,Rg,M0,Ig=N(()=>{"use strict";mn();I0=[{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"}]}],Rg=/[\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,M0=/\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 Xr,vt,Zr,Qr,Mg=N(()=>{"use strict";Xr=O(require("fs")),vt=O(require("fs/promises")),Zr=O(require("path")),Qr=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{Xr.existsSync(o)&&(a=await vt.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?(Xr.existsSync(i.absolutePath)&&await vt.unlink(i.absolutePath),t.push({file:i.filePath,success:!0})):(await vt.mkdir(Zr.dirname(i.absolutePath),{recursive:!0}),await vt.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?Xr.existsSync(r.absolutePath)&&await vt.unlink(r.absolutePath):await vt.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(`
1046
- `)}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 L0(n,e){let t=[],s;for(Lg.lastIndex=0;(s=Lg.exec(n))!==null;){let r=s[1],i=Re.resolve(e,r);ft.existsSync(i)&&t.push(r)}return[...new Set(t)]}function D0(n,e,t){let s=[],r=Re.extname(e),i=Re.dirname(Re.resolve(t,e));if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(r)){let o;for(Dg.lastIndex=0;(o=Dg.exec(n))!==null;){let a=o[1]||o[2];if(!a||!a.startsWith(".")&&!a.startsWith("/"))continue;let l=N0(a,i);l&&s.push(Re.relative(t,l))}}else if(r===".py"){let o;for(Ng.lastIndex=0;(o=Ng.exec(n))!==null;){let a=o[1]||o[2];if(!a)continue;let l=a.replace(/\./g,"/")+".py",u=Re.resolve(i,l);ft.existsSync(u)&&s.push(Re.relative(t,u))}}return[...new Set(s)]}function N0(n,e){let t=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],s=Re.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=Re.join(s,`index${r}`);if(ft.existsSync(i))return i}return null}function Fg(n,e,t){let s=t?.maxFiles||10,r=t?.maxTokens||8e3,i=t?.followImports!==!1,o=L0(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=Re.resolve(e,d),p=ft.readFileSync(f,"utf-8"),m=p.split(`
1047
+ `),"utf-8")}}});function Yl(n){let e=n.trim(),t=e.toLowerCase();if(E0.test(e)||T0.test(e)||e.length<15&&!R0.test(e))return"XS";if(I0.test(t)||Tg.test(t)&&e.length>150)return"XL";let s=t.match(O0)||[],i=new Set(s.map(a=>a.toLowerCase())).size,o=e.split(/[.!?]+/).filter(a=>a.trim().length>5);return Tg.test(t)||o.length>=3&&i>=2||i>=3&&e.length>100?"L":M0.test(t)||i>=2&&e.length>=50||e.length>=50&&e.length<=150&&i>=1&&o.length>=2?"M":(e.length<50&&i<=1||P0.test(e)&&i<=1||i===1,"S")}function Rg(n,e,t){let s=`sp-${Date.now()}`,r=[],i=1,o=t.includes("emma"),a=t.includes("bob"),l=t.includes("alex"),u=t.includes("david");switch(e){case"XS":break;case"S":r.push({id:`${s}-t${i++}`,description:`Execute: ${n.substring(0,80)}`,assignee:l?"alex":t.find(f=>f!=="hablas")||"alex",dependencies:[]});break;case"M":{u&&r.push({id:`${s}-t${i++}`,description:"Research requirements and gather context",assignee:"david",dependencies:[]});let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:`Implement: ${n.substring(0,60)}`,assignee:l?"alex":"hablas",dependencies:f});break}case"L":{if(u&&r.push({id:`${s}-t${i++}`,description:"Research requirements, best practices, and relevant documentation",assignee:"david",dependencies:[]}),a){let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:"Design system architecture and structure",assignee:"bob",dependencies:f})}if(l){let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:"Implement the code based on architecture/requirements",assignee:"alex",dependencies:f})}break}case"XL":{if(o&&r.push({id:`${s}-t${i++}`,description:"Analyze requirements and create PRD with user stories",assignee:"emma",dependencies:[]}),u){let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:"Research best practices, technologies, and competitive landscape",assignee:"david",dependencies:f})}if(a){let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:"Design complete system architecture, database schema, and API structure",assignee:"bob",dependencies:f})}if(l){let f=r.length>0?[r[r.length-1].id]:[];r.push({id:`${s}-t${i++}`,description:"Implement the full system based on PRD and architecture",assignee:"alex",dependencies:f})}break}}let d;return r.length<=1?d="direct":r.every((f,p)=>p===0||f.dependencies.length>0)?d="sequential":d="mixed",{id:s,title:n.substring(0,100),complexity:e,tasks:r,strategy:d,requiresApproval:e==="L"||e==="XL",createdAt:Date.now()}}var E0,T0,R0,P0,O0,I0,Tg,M0,Pg=N(()=>{"use strict";E0=/^(hi|hello|hey|howdy|yo|sup|hiya|good\s*(morning|afternoon|evening|night)|what'?s\s*up|greetings|thanks?|thank\s*you|bye|goodbye|ok(ay)?|yes|no|cool|nice|great|got\s*it|sure|مرحبا|أهلا|هلا|السلام\s*عليكم|كيف\s*حالك)\b/i,T0=/^(how\s*are\s*you|what'?s\s*your\s*name|who\s*are\s*you|what\s*can\s*you\s*do|help|tell\s*me\s*about\s*yourself)\s*[?!.]*$/i,R0=/\b(create|build|implement|write|generate|code|make|develop|design|architect|setup|configure|install|deploy|fix|debug|refactor|rewrite|restructure|migrate|convert|add|remove|delete|update|change|modify|edit|move|rename|test|run|execute|analyze|research|find|search|compare|optimize)\b/i,P0=/[\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|toml|xml|env)/i,O0=/\b(create|build|implement|write|generate|design|architect|setup|configure|deploy|fix|debug|refactor|rewrite|restructure|migrate|add|remove|update|change|modify|test|analyze|research|optimize)\b/gi,I0=/\b(full\s+system|complete\s+project|from\s+scratch|entire\s+application|prd|product\s+requirements|architecture\s+.*implementation\s+.*deployment|end[\s-]*to[\s-]*end)\b/i,Tg=/\b(design|architect)\b.*\b(implement|build|create|develop)\b/i,M0=/\b(multiple\s+files|several\s+components|across\s+all|every\s+file|all\s+modules)\b/i});function Ig(n){let e=n.trim();if(e.length<20||Un(e)||Og.test(e)||e.includes("```")||D0.test(e)||/\/[\w-]+\.[\w]+/.test(e)||e.length<60&&Og.test(e))return null;for(let{pattern:t,question:s,choices:r}of L0)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 Mg(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 L0,Og,D0,Lg=N(()=>{"use strict";mn();L0=[{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"}]}],Og=/[\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,D0=/\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 Jr,bt,Qr,Xr,Dg=N(()=>{"use strict";Jr=O(require("fs")),bt=O(require("fs/promises")),Qr=O(require("path")),Xr=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=Qr.resolve(this.workingDir,e),a=null;try{Jr.existsSync(o)&&(a=await bt.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?(Jr.existsSync(i.absolutePath)&&await bt.unlink(i.absolutePath),t.push({file:i.filePath,success:!0})):(await bt.mkdir(Qr.dirname(i.absolutePath),{recursive:!0}),await bt.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?Jr.existsSync(r.absolutePath)&&await bt.unlink(r.absolutePath):await bt.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(`
1048
+ `)}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 N0(n,e){let t=[],s;for(Ng.lastIndex=0;(s=Ng.exec(n))!==null;){let r=s[1],i=Re.resolve(e,r);dt.existsSync(i)&&t.push(r)}return[...new Set(t)]}function F0(n,e,t){let s=[],r=Re.extname(e),i=Re.dirname(Re.resolve(t,e));if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(r)){let o;for(Fg.lastIndex=0;(o=Fg.exec(n))!==null;){let a=o[1]||o[2];if(!a||!a.startsWith(".")&&!a.startsWith("/"))continue;let l=j0(a,i);l&&s.push(Re.relative(t,l))}}else if(r===".py"){let o;for(jg.lastIndex=0;(o=jg.exec(n))!==null;){let a=o[1]||o[2];if(!a)continue;let l=a.replace(/\./g,"/")+".py",u=Re.resolve(i,l);dt.existsSync(u)&&s.push(Re.relative(t,u))}}return[...new Set(s)]}function j0(n,e){let t=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],s=Re.resolve(e,n);if(dt.existsSync(s)&&dt.statSync(s).isFile())return s;for(let r of t){let i=s+r;if(dt.existsSync(i))return i}for(let r of t){let i=Re.join(s,`index${r}`);if(dt.existsSync(i))return i}return null}function Hg(n,e,t){let s=t?.maxFiles||10,r=t?.maxTokens||8e3,i=t?.followImports!==!1,o=N0(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=Re.resolve(e,d),p=dt.readFileSync(f,"utf-8"),m=p.split(`
1047
1049
  `).length,h=Math.ceil(p.length/4);if(h>4e3){let g=p.split(`
1048
1050
  `).slice(0,200).join(`
1049
1051
  `)+`
1050
- ...(truncated)`,S=Math.ceil(g.length/4);u+S<=r&&(a.push({path:d,content:g,source:"mentioned",lineCount:200}),u+=S)}else if(u+h<=r&&(a.push({path:d,content:p,source:"mentioned",lineCount:m}),u+=h,i)){let g=D0(p,d,e);for(let S of g.slice(0,5)){if(a.length>=s||u>=r)break;if(!l.has(S)){l.add(S);try{let k=Re.resolve(e,S),x=ft.readFileSync(k,"utf-8"),A=Math.ceil(x.length/4),y=x.split(`
1052
+ ...(truncated)`,S=Math.ceil(g.length/4);u+S<=r&&(a.push({path:d,content:g,source:"mentioned",lineCount:200}),u+=S)}else if(u+h<=r&&(a.push({path:d,content:p,source:"mentioned",lineCount:m}),u+=h,i)){let g=F0(p,d,e);for(let S of g.slice(0,5)){if(a.length>=s||u>=r)break;if(!l.has(S)){l.add(S);try{let k=Re.resolve(e,S),x=dt.readFileSync(k,"utf-8"),A=Math.ceil(x.length/4),y=x.split(`
1051
1053
  `).length;if(A>2e3){let v=x.split(`
1052
1054
  `).slice(0,100).join(`
1053
1055
  `)+`
1054
- ...(truncated)`,b=Math.ceil(v.length/4);u+b<=r&&(a.push({path:S,content:v,source:"imported",lineCount:100}),u+=b)}else u+A<=r&&(a.push({path:S,content:x,source:"imported",lineCount:y}),u+=A)}catch{}}}}}catch{}}}return{files:a,totalTokensEstimate:u,mentionedPaths:o}}function jg(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(`
1055
- `)}var ft,Re,Lg,Dg,Ng,Hg=N(()=>{"use strict";ft=O(require("fs")),Re=O(require("path")),Lg=/(?:^|\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,Dg=/(?:import\s+.*?\s+from\s+['"]([^'"]+)['"]|require\s*\(\s*['"]([^'"]+)['"]\s*\))/g,Ng=/(?:from\s+(\S+)\s+import|import\s+(\S+))/g});var Ug={};Fe(Ug,{runSetupWizard:()=>Yl});function xe(n,e){return new Promise(t=>{n.question(e,s=>t(s))})}function j0(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}async function Yl(n){let e=Bg.createInterface({input:process.stdin,output:process.stdout});switch(console.log(),console.log(`${Kt}${Ge} \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${L}`),console.log(`${Kt}${Ge} hablas \u2014 Setup Wizard${L}`),console.log(`${z} Configure your AI provider and model${L}`),console.log(`${Kt}${Ge} \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${L}`),console.log(),console.log(`${Kt} Choose your setup:${L}`),console.log(),console.log(` ${F0}${Kt}1${L}. ${Kt}Hablas Integrated Engine${L} ${wt}(instant \u2014 no setup needed)${L}`),console.log(` ${z}Pre-configured cloud AI, ready to use immediately${L}`),console.log(),console.log(` ${Ge}${Kt}2${L}. ${Kt}Custom Provider${L} ${z}(bring your own API key)${L}`),console.log(` ${z}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${L}`),console.log(),(await xe(e,` ${z}Your choice (1-2):${L} `)).trim()){case"1":{n.provider=Wt.provider,n.apiUrl=Wt.apiUrl,n.apiKey=j0(),n.model=Wt.model,gt(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(`${wt} \u2713 Hablas Integrated Engine activated!${L}`),console.log(`${z} Model: ${Wt.model}${L}`),console.log(`${z} API: ${Wt.apiUrl}${L}`),console.log(`${z} No API key needed \u2014 everything is pre-configured.${L}`);break}case"2":{switch(console.log(),console.log(`${z} Select your provider:${L}`),console.log(` ${Ge}a${L}. Ollama (local, free, private)`),console.log(` ${Ge}b${L}. OpenAI API`),console.log(` ${Ge}c${L}. Groq (fast, free tier)`),console.log(` ${Ge}d${L}. OpenRouter (many models)`),console.log(` ${Ge}e${L}. Together AI`),console.log(` ${Ge}f${L}. DeepSeek`),console.log(` ${Ge}g${L}. Custom OpenAI-compatible API`),console.log(` ${Ge}h${L}. NVIDIA NIM (powerful cloud models)`),console.log(),(await xe(e,` ${z}Your choice (a-h):${L} `)).trim().toLowerCase()){case"a":{n.provider="ollama";let r=await xe(e,` ${z}Ollama host [http://localhost:11434]:${L} `);r.trim()&&(n.ollamaHost=r.trim());let i=await xe(e,` ${z}Model [qwen2.5-coder:7b]:${L} `);i.trim()&&(n.model=i.trim()),gt(n),console.log(),console.log(`${wt} \u2713 Configured for Ollama${L}`),console.log(`${z} Model: ${n.model}${L}`),console.log(`${z} Host: ${n.ollamaHost}${L}`),console.log(`${z} Make sure Ollama is running: ollama serve${L}`);break}case"b":{let r=await xe(e,` ${z}OpenAI API Key (sk-...):${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await xe(e,` ${z}Model [gpt-4o]:${L} `);n.provider="custom",n.apiUrl="https://api.openai.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"gpt-4o",gt(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(`${wt} \u2713 Configured for OpenAI${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"c":{let r=await xe(e,` ${z}Groq API Key (gsk_...):${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await xe(e,` ${z}Model [llama-3.3-70b-versatile]:${L} `);n.provider="custom",n.apiUrl="https://api.groq.com/openai/v1",n.apiKey=r.trim(),n.model=i.trim()||"llama-3.3-70b-versatile",gt(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(`${wt} \u2713 Configured for Groq${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"d":{let r=await xe(e,` ${z}OpenRouter API Key (sk-or-...):${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await xe(e,` ${z}Model [anthropic/claude-3.5-sonnet]:${L} `);n.provider="custom",n.apiUrl="https://openrouter.ai/api/v1",n.apiKey=r.trim(),n.model=i.trim()||"anthropic/claude-3.5-sonnet",gt(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(`${wt} \u2713 Configured for OpenRouter${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"e":{let r=await xe(e,` ${z}Together API Key:${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await xe(e,` ${z}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${L} `);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",gt(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(`${wt} \u2713 Configured for Together AI${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"f":{let r=await xe(e,` ${z}DeepSeek API Key:${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await xe(e,` ${z}Model [deepseek-chat]:${L} `);n.provider="custom",n.apiUrl="https://api.deepseek.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"deepseek-chat",gt(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(`${wt} \u2713 Configured for DeepSeek${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"g":{let r=await xe(e,` ${z}Provider name:${L} `);if(!r.trim()){console.log(`${xt} \u26A0 Cancelled${L}`);break}let i=await xe(e,` ${z}API base URL:${L} `);if(!i.trim()){console.log(`${xt} \u26A0 URL is required \u2014 cancelled${L}`);break}let o=await xe(e,` ${z}API Key (leave empty if none):${L} `),a=await xe(e,` ${z}Default model ID:${L} `);n.provider="custom",n.apiUrl=i.trim(),n.apiKey=o.trim(),n.model=a.trim()||"default",gt(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(`${wt} \u2713 Configured for ${r.trim()}${L}`),console.log(`${z} URL: ${i.trim()}${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"h":{let r=await xe(e,` ${z}NVIDIA API Key (nvapi-...):${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`),console.log(`${z} Get your key at: https://build.nvidia.com/${L}`);break}let{NVIDIA_PROVIDER:i}=await Promise.resolve().then(()=>(Hn(),bc));console.log(),console.log(`${z} Available NVIDIA models:${L}`),i.models.forEach((u,d)=>{console.log(` ${Ge}${d+1}${L}. ${u}`)}),console.log();let o=await xe(e,` ${z}Model number [1]:${L} `),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,gt(n),nt({name:"NVIDIA",apiUrl:i.apiUrl,apiKey:r.trim(),models:i.models,defaultModel:l,addedAt:new Date().toISOString()}),console.log(),console.log(`${wt} \u2713 Configured for NVIDIA NIM${L}`),console.log(`${z} Model: ${l}${L}`),console.log(`${z} API: ${i.apiUrl}${L}`);break}default:console.log(`${xt} \u26A0 Invalid choice${L}`)}break}default:console.log(`${xt} \u26A0 Invalid choice \u2014 please select 1 or 2${L}`)}console.log(),console.log(`${z} Run 'hablas' to start chatting!${L}`),console.log(),e.close()}var Bg,Ge,wt,xt,z,Kt,L,F0,Wt,Jl=N(()=>{"use strict";Bg=O(require("readline"));yr();_i();Ge="\x1B[36m",wt="\x1B[32m",xt="\x1B[33m",z="\x1B[2m",Kt="\x1B[1m",L="\x1B[0m",F0="\x1B[35m";Wt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"}});var jt={};Fe(jt,{activeCollabManager:()=>Pe,runSingleCommand:()=>G0,startRepl:()=>Zl});function q0(){return!pt.existsSync(Xl)}function qg(){return pt.existsSync(H0)}function K0(){let n=Lt.dirname(Xl);pt.existsSync(n)||pt.mkdirSync(n,{recursive:!0}),pt.writeFileSync(Xl,new Date().toISOString(),"utf-8")}async function W0(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 Wg(n,e,t,s,r){let{interactive:i,autoMode:o,input:a,logger:l,abortSignal:u,onToolCall:d,skipTools:f}=r,p=r.reactEngine??ws(),m=r.errorRecovery??xs(),h=new ze("Hablas is thinking");h.start();let g=x=>{h&&(h.stop(x),h=null)},S=fg({autoMode:o,interactive:i,confirm:a?x=>a.confirm(x):void 0,confirmDangerous:a?x=>a.confirmDangerous(x):void 0});await Ur({identity:{name:"Hablas",title:"Team Leader",role:"hablas"},client:e,registry:t,session:n,contextManager:s,reactEngine:p,errorRecovery:m,logger:l,io:{onAssistantText:async x=>{g(),console.log(Jt("Hablas","Team Leader")),await W0(Xt(x))},onToolStart:(x,A)=>{g(),console.log(bu(x,A)),h=new ze("Continuing"),h.start()},onToolEnd:(x,A,y,v)=>{g(),console.log(vu(A,y,v))},onNotice:(x,A)=>{g(),console.log(A==="retry"?c.muted(` \u21BB ${x}`):B(x))},onError:x=>{g(),x.includes("ECONNREFUSED")?console.log(Ue("Connection lost","Check your provider connection or run /provider test")):/timeout/i.test(x)?console.log(Ue("Request timed out (120s)","The API is slow. Try again or use a faster model.")):x.includes("429")?console.log(Ue("Rate limited by API","Wait a moment and try again, or switch providers.")):x.includes("model")?console.log(Ue("Model error","Check model availability: /models")):console.log(Ue(`Error: ${x}`,"Try again or check /status"))},onToolCall:()=>{d&&d()}},safetyPolicy:S,abortSignal:u,skipTools:f,maxIterations:B0}),g()}async function Zl(n,e){Wp();let t=n.workingDirectory==="."?process.cwd():n.workingDirectory,s=W=>pt.existsSync(Lt.join(W,".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.")}
1056
+ ...(truncated)`,b=Math.ceil(v.length/4);u+b<=r&&(a.push({path:S,content:v,source:"imported",lineCount:100}),u+=b)}else u+A<=r&&(a.push({path:S,content:x,source:"imported",lineCount:y}),u+=A)}catch{}}}}}catch{}}}return{files:a,totalTokensEstimate:u,mentionedPaths:o}}function Bg(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(`
1057
+ `)}var dt,Re,Ng,Fg,jg,Ug=N(()=>{"use strict";dt=O(require("fs")),Re=O(require("path")),Ng=/(?:^|\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,Fg=/(?:import\s+.*?\s+from\s+['"]([^'"]+)['"]|require\s*\(\s*['"]([^'"]+)['"]\s*\))/g,jg=/(?:from\s+(\S+)\s+import|import\s+(\S+))/g});var Kg={};je(Kg,{runSetupWizard:()=>Jl});function xe(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 Jl(n){let e=qg.createInterface({input:process.stdin,output:process.stdout});switch(console.log(),console.log(`${Kt}${Ge} \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${L}`),console.log(`${Kt}${Ge} hablas \u2014 Setup Wizard${L}`),console.log(`${z} Configure your AI provider and model${L}`),console.log(`${Kt}${Ge} \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${L}`),console.log(),console.log(`${Kt} Choose your setup:${L}`),console.log(),console.log(` ${H0}${Kt}1${L}. ${Kt}Hablas Integrated Engine${L} ${vt}(instant \u2014 no setup needed)${L}`),console.log(` ${z}Pre-configured cloud AI, ready to use immediately${L}`),console.log(),console.log(` ${Ge}${Kt}2${L}. ${Kt}Custom Provider${L} ${z}(bring your own API key)${L}`),console.log(` ${z}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${L}`),console.log(),(await xe(e,` ${z}Your choice (1-2):${L} `)).trim()){case"1":{n.provider=Wt.provider,n.apiUrl=Wt.apiUrl,n.apiKey=B0(),n.model=Wt.model,mt(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(`${vt} \u2713 Hablas Integrated Engine activated!${L}`),console.log(`${z} Model: ${Wt.model}${L}`),console.log(`${z} API: ${Wt.apiUrl}${L}`),console.log(`${z} No API key needed \u2014 everything is pre-configured.${L}`);break}case"2":{switch(console.log(),console.log(`${z} Select your provider:${L}`),console.log(` ${Ge}a${L}. Ollama (local, free, private)`),console.log(` ${Ge}b${L}. OpenAI API`),console.log(` ${Ge}c${L}. Groq (fast, free tier)`),console.log(` ${Ge}d${L}. OpenRouter (many models)`),console.log(` ${Ge}e${L}. Together AI`),console.log(` ${Ge}f${L}. DeepSeek`),console.log(` ${Ge}g${L}. Custom OpenAI-compatible API`),console.log(` ${Ge}h${L}. NVIDIA NIM (powerful cloud models)`),console.log(),(await xe(e,` ${z}Your choice (a-h):${L} `)).trim().toLowerCase()){case"a":{n.provider="ollama";let r=await xe(e,` ${z}Ollama host [http://localhost:11434]:${L} `);r.trim()&&(n.ollamaHost=r.trim());let i=await xe(e,` ${z}Model [qwen2.5-coder:7b]:${L} `);i.trim()&&(n.model=i.trim()),mt(n),console.log(),console.log(`${vt} \u2713 Configured for Ollama${L}`),console.log(`${z} Model: ${n.model}${L}`),console.log(`${z} Host: ${n.ollamaHost}${L}`),console.log(`${z} Make sure Ollama is running: ollama serve${L}`);break}case"b":{let r=await xe(e,` ${z}OpenAI API Key (sk-...):${L} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await xe(e,` ${z}Model [gpt-4o]:${L} `);n.provider="custom",n.apiUrl="https://api.openai.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"gpt-4o",mt(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(`${vt} \u2713 Configured for OpenAI${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"c":{let r=await xe(e,` ${z}Groq API Key (gsk_...):${L} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await xe(e,` ${z}Model [llama-3.3-70b-versatile]:${L} `);n.provider="custom",n.apiUrl="https://api.groq.com/openai/v1",n.apiKey=r.trim(),n.model=i.trim()||"llama-3.3-70b-versatile",mt(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(`${vt} \u2713 Configured for Groq${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"d":{let r=await xe(e,` ${z}OpenRouter API Key (sk-or-...):${L} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await xe(e,` ${z}Model [anthropic/claude-3.5-sonnet]:${L} `);n.provider="custom",n.apiUrl="https://openrouter.ai/api/v1",n.apiKey=r.trim(),n.model=i.trim()||"anthropic/claude-3.5-sonnet",mt(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(`${vt} \u2713 Configured for OpenRouter${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"e":{let r=await xe(e,` ${z}Together API Key:${L} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await xe(e,` ${z}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${L} `);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",mt(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(`${vt} \u2713 Configured for Together AI${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"f":{let r=await xe(e,` ${z}DeepSeek API Key:${L} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await xe(e,` ${z}Model [deepseek-chat]:${L} `);n.provider="custom",n.apiUrl="https://api.deepseek.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"deepseek-chat",mt(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(`${vt} \u2713 Configured for DeepSeek${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"g":{let r=await xe(e,` ${z}Provider name:${L} `);if(!r.trim()){console.log(`${wt} \u26A0 Cancelled${L}`);break}let i=await xe(e,` ${z}API base URL:${L} `);if(!i.trim()){console.log(`${wt} \u26A0 URL is required \u2014 cancelled${L}`);break}let o=await xe(e,` ${z}API Key (leave empty if none):${L} `),a=await xe(e,` ${z}Default model ID:${L} `);n.provider="custom",n.apiUrl=i.trim(),n.apiKey=o.trim(),n.model=a.trim()||"default",mt(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(`${vt} \u2713 Configured for ${r.trim()}${L}`),console.log(`${z} URL: ${i.trim()}${L}`),console.log(`${z} Model: ${n.model}${L}`);break}case"h":{let r=await xe(e,` ${z}NVIDIA API Key (nvapi-...):${L} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${L}`),console.log(`${z} Get your key at: https://build.nvidia.com/${L}`);break}let{NVIDIA_PROVIDER:i}=await Promise.resolve().then(()=>(Hn(),vc));console.log(),console.log(`${z} Available NVIDIA models:${L}`),i.models.forEach((u,d)=>{console.log(` ${Ge}${d+1}${L}. ${u}`)}),console.log();let o=await xe(e,` ${z}Model number [1]:${L} `),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,mt(n),nt({name:"NVIDIA",apiUrl:i.apiUrl,apiKey:r.trim(),models:i.models,defaultModel:l,addedAt:new Date().toISOString()}),console.log(),console.log(`${vt} \u2713 Configured for NVIDIA NIM${L}`),console.log(`${z} Model: ${l}${L}`),console.log(`${z} API: ${i.apiUrl}${L}`);break}default:console.log(`${wt} \u26A0 Invalid choice${L}`)}break}default:console.log(`${wt} \u26A0 Invalid choice \u2014 please select 1 or 2${L}`)}console.log(),console.log(`${z} Run 'hablas' to start chatting!${L}`),console.log(),e.close()}var qg,Ge,vt,wt,z,Kt,L,H0,Wt,Xl=N(()=>{"use strict";qg=O(require("readline"));yr();Si();Ge="\x1B[36m",vt="\x1B[32m",wt="\x1B[33m",z="\x1B[2m",Kt="\x1B[1m",L="\x1B[0m",H0="\x1B[35m";Wt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"}});var jt={};je(jt,{activeCollabManager:()=>Pe,runSingleCommand:()=>z0,startRepl:()=>ec});function W0(){return!ft.existsSync(Ql)}function Wg(){return ft.existsSync(U0)}function G0(){let n=Lt.dirname(Ql);ft.existsSync(n)||ft.mkdirSync(n,{recursive:!0}),ft.writeFileSync(Ql,new Date().toISOString(),"utf-8")}async function V0(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 Vg(n,e,t,s,r){let{interactive:i,autoMode:o,input:a,logger:l,abortSignal:u,onToolCall:d,skipTools:f}=r,p=r.reactEngine??ws(),m=r.errorRecovery??xs(),h=new ze("Hablas is thinking");h.start();let g=x=>{h&&(h.stop(x),h=null)},S=pg({autoMode:o,interactive:i,confirm:a?x=>a.confirm(x):void 0,confirmDangerous:a?x=>a.confirmDangerous(x):void 0});await Ur({identity:{name:"Hablas",title:"Team Leader",role:"hablas"},client:e,registry:t,session:n,contextManager:s,reactEngine:p,errorRecovery:m,logger:l,io:{onAssistantText:async x=>{g(),console.log(Jt("Hablas","Team Leader")),await V0(Xt(x))},onToolStart:(x,A)=>{g(),console.log(vu(x,A)),h=new ze("Continuing"),h.start()},onToolEnd:(x,A,y,v)=>{g(),console.log(wu(A,y,v))},onNotice:(x,A)=>{g(),console.log(A==="retry"?c.muted(` \u21BB ${x}`):B(x))},onError:x=>{g(),x.includes("ECONNREFUSED")?console.log(Ue("Connection lost","Check your provider connection or run /provider test")):/timeout/i.test(x)?console.log(Ue("Request timed out (120s)","The API is slow. Try again or use a faster model.")):x.includes("429")?console.log(Ue("Rate limited by API","Wait a moment and try again, or switch providers.")):x.includes("model")?console.log(Ue("Model error","Check model availability: /models")):console.log(Ue(`Error: ${x}`,"Try again or check /status"))},onToolCall:()=>{d&&d()}},safetyPolicy:S,abortSignal:u,skipTools:f,maxIterations:q0}),g()}async function ec(n,e){Gp();let t=n.workingDirectory==="."?process.cwd():n.workingDirectory,s=W=>ft.existsSync(Lt.join(W,".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.")}
1056
1058
  `);else if(n.team?.enabled&&!s(t)){console.log(`
1057
1059
  ${c.accent("\u2726")} ${c.strong("Team Mode Strategy Required")}`),console.log(` ${c.muted("Collaboration requires a stable Git repository root.")}
1058
- `);let ie=await new ps(t).prompt(` ${c.primary("\u203A")} Specify repo path OR type 'init' to start here: `);if(ie.trim().toLowerCase()==="init")try{(0,Kg.execSync)("git init",{cwd:t,stdio:"ignore"}),console.log(` ${c.success("\u2713")} Git repository initialized in ${c.highlight(t)}
1059
- `)}catch{console.log(Ce("Failed to initialize Git. Please run git init manually.")),process.exit(1)}else{let ue=Lt.resolve(t,ie.trim());pt.existsSync(ue)&&s(ue)?(t=ue,n.workingDirectory=t,console.log(` ${c.success("\u2713")} Context switched to repository: ${c.highlight(t)}
1060
- `)):(console.log(Ce(`Path "${ue}" is not a valid Git repository.`)),process.exit(1))}}let r=je(n),i=new us(t,n),o=new on(n),a=new ps(t),l=br(),u=new vr,d=new ms(t),f=new Dn(t),p=new Yr,m=new qr(n);m.setToolRegistry(i);let h=new Kr,g=new zr(h).attach(),S=new Gr(n,{tokenBudget:500,maxChars:140});if(m.setChannel(h),n.team?.enabled){let W=n.team.user||"developer",ie=n.team.key||"default-key";Pe=new ls(t,n,W,ie),await Pe.init()&&console.log(` ${c.success("\u2713")} ${c.muted("[Team]")} Scoped cooperative sync initialized successfully.
1061
- `)}let k=new Qr(t);f.init();let x=null;n.context?.hablasCoreEnabled&&(x=new Jr(t),x.init());let A=await Qt(t,n),y=l.getActive(),v=y?y.systemPrompt:Yn,b=Zt(v,A,d,f),w=ws({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:150,minConfidence:.6}),_=xs(3),E=new an(b,n.historySize),I=Kn();I=Ui(I),$t(I);let $=0,F=0,H=Date.now(),X=n.autoMode||!1,T=0,C=new AbortController;process.on("SIGINT",()=>{let W=Date.now();if(W-T<U0){console.log(no({turns:$,duration:Date.now()-H,toolCalls:F}));let ie=Pe?Pe.shutdown():Promise.resolve();Promise.resolve(ie).finally(()=>process.exit(0)),setTimeout(()=>process.exit(0),2e3);return}T=W,C.abort(),C=new AbortController,process.stdout.write(`
1062
- `),console.log(B("Operation cancelled \u2014 press Ctrl+C again to exit"))});let ne=Rs(n);if(console.log(fu(n.model,t)),n.provider==="custom"&&console.log(le(`Provider: ${ne}`)),X&&console.log(le("Auto mode enabled \u2014 tool confirmations skipped (plan approval still required)")),(q0()||!qg())&&(console.log(mu()),console.log(""),console.log(le("First run detected \u2014 launching setup wizard...")),console.log(""),a.close(),await Yl(n),K0(),r=je(n),a.reinitialize()),qg()){let W=new ze("Connecting");W.start();let ie=await r.checkConnection();if(W.stop(ie?"ready":void 0),ie){let ue=await r.listModels();console.log(J(`Connected \xB7 ${ue.length} models available`)),n.provider==="ollama"&&!ue.includes(n.model)&&console.log(B(`Model "${n.model}" not found. Pull: ollama pull ${n.model}`))}else n.provider==="custom"?console.log(Ue(`Cannot connect to ${n.apiUrl}`,"Check your --api-url and --api-key, or run /provider test")):n.provider==="nvidia"?console.log(Ue("Cannot connect to NVIDIA NIM","Check your API key or run: hablas --setup")):console.log(Ue("Cannot connect to Ollama","Start it with: ollama serve \u2014 or switch provider: /provider"))}console.log(pu()),console.log();let D=!0;for(;D;)try{let ie=(await a.prompt(` ${c.primary("\u203A")} `)).trim();if(!ie)continue;if(ie.startsWith("/")){if(await Ku(ie,n,r,i,o,E,t,a,$,l,u,d,K=>{r=K},f,p,k,m)==="quit"){D=!1;break}continue}e.info({input:ie},"Processing user input");let ue=Lc(ie),ee=Gg(ue,t);if($++,console.log(wu($)),I=qi(I),$t(I),!X){let re=Pg(ee);if(re){console.log(_u(re));let K=await a.prompt(` ${c.muted("\u203A")} `),se=Og(K,re);ee=`${ee}
1063
- [Clarification: ${se.join(", ")}]`}}let ge=Fg(ee,t,{maxFiles:8,maxTokens:6e3});if(ge.files.length>0){let re=jg(ge);E.addUserMessage(`[Auto-loaded ${ge.files.length} file(s): ${ge.mentionedPaths.join(", ")}]
1060
+ `);let ie=await new ps(t).prompt(` ${c.primary("\u203A")} Specify repo path OR type 'init' to start here: `);if(ie.trim().toLowerCase()==="init")try{(0,Gg.execSync)("git init",{cwd:t,stdio:"ignore"}),console.log(` ${c.success("\u2713")} Git repository initialized in ${c.highlight(t)}
1061
+ `)}catch{console.log(Ce("Failed to initialize Git. Please run git init manually.")),process.exit(1)}else{let ue=Lt.resolve(t,ie.trim());ft.existsSync(ue)&&s(ue)?(t=ue,n.workingDirectory=t,console.log(` ${c.success("\u2713")} Context switched to repository: ${c.highlight(t)}
1062
+ `)):(console.log(Ce(`Path "${ue}" is not a valid Git repository.`)),process.exit(1))}}let r=He(n),i=new us(t,n),o=new on(n),a=new ps(t),l=br(),u=new vr,d=new ms(t),f=new Dn(t),p=new zr,m=new qr(n);m.setToolRegistry(i);let h=new Kr,g=new Vr(h).attach(),S=new Gr(n,{tokenBudget:500,maxChars:140});if(m.setChannel(h),n.team?.enabled){let W=n.team.user||"developer",ie=n.team.key||"default-key";Pe=new ls(t,n,W,ie),await Pe.init()&&console.log(` ${c.success("\u2713")} ${c.muted("[Team]")} Scoped cooperative sync initialized successfully.
1063
+ `)}let k=new Xr(t);f.init();let x=null;n.context?.hablasCoreEnabled&&(x=new Yr(t),x.init());let A=await Qt(t,n),y=l.getActive(),v=y?y.systemPrompt:Yn,b=Zt(v,A,d,f),w=ws({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:150,minConfidence:.6}),_=xs(3),E=new an(b,n.historySize),I=Kn();I=Bi(I),kt(I);let $=0,F=0,H=Date.now(),X=n.autoMode||!1,T=0,C=new AbortController;process.on("SIGINT",()=>{let W=Date.now();if(W-T<K0){console.log(to({turns:$,duration:Date.now()-H,toolCalls:F}));let ie=Pe?Pe.shutdown():Promise.resolve();Promise.resolve(ie).finally(()=>process.exit(0)),setTimeout(()=>process.exit(0),2e3);return}T=W,C.abort(),C=new AbortController,process.stdout.write(`
1064
+ `),console.log(B("Operation cancelled \u2014 press Ctrl+C again to exit"))});let ne=Rs(n);if(console.log(pu(n.model,t)),n.provider==="custom"&&console.log(le(`Provider: ${ne}`)),X&&console.log(le("Auto mode enabled \u2014 tool confirmations skipped (plan approval still required)")),(W0()||!Wg())&&(console.log(gu()),console.log(""),console.log(le("First run detected \u2014 launching setup wizard...")),console.log(""),a.close(),await Jl(n),G0(),r=He(n),a.reinitialize()),Wg()){let W=new ze("Connecting");W.start();let ie=await r.checkConnection();if(W.stop(ie?"ready":void 0),ie){let ue=await r.listModels();console.log(J(`Connected \xB7 ${ue.length} models available`)),n.provider==="ollama"&&!ue.includes(n.model)&&console.log(B(`Model "${n.model}" not found. Pull: ollama pull ${n.model}`))}else n.provider==="custom"?console.log(Ue(`Cannot connect to ${n.apiUrl}`,"Check your --api-url and --api-key, or run /provider test")):n.provider==="nvidia"?console.log(Ue("Cannot connect to NVIDIA NIM","Check your API key or run: hablas --setup")):console.log(Ue("Cannot connect to Ollama","Start it with: ollama serve \u2014 or switch provider: /provider"))}console.log(hu()),console.log();let D=!0;for(;D;)try{let ie=(await a.prompt(` ${c.primary("\u203A")} `)).trim();if(!ie)continue;if(ie.startsWith("/")){if(await Wu(ie,n,r,i,o,E,t,a,$,l,u,d,K=>{r=K},f,p,k,m)==="quit"){D=!1;break}continue}e.info({input:ie},"Processing user input");let ue=Dc(ie),ee=zg(ue,t);if($++,console.log(xu($)),I=Ui(I),kt(I),!X){let re=Ig(ee);if(re){console.log(Au(re));let K=await a.prompt(` ${c.muted("\u203A")} `),se=Mg(K,re);ee=`${ee}
1065
+ [Clarification: ${se.join(", ")}]`}}let ge=Hg(ee,t,{maxFiles:8,maxTokens:6e3});if(ge.files.length>0){let re=Bg(ge);E.addUserMessage(`[Auto-loaded ${ge.files.length} file(s): ${ge.mentionedPaths.join(", ")}]
1064
1066
  ${re}`,{priority:"low",tags:["auto-inject"]})}if(n.team?.enabled&&Pe){let re=n.team?.user||Pe.getLocalState().my_username,K=ge.mentionedPaths||[];if(K.length>0){let se=await Pe.fetchLocks(),ye=K.map(P=>se.find(q=>q.file_path===P&&q.locked_by!==re)).filter(P=>!!P);if(ye.length>0){let P=ye[0];console.log(`
1065
1067
  ${c.architect("\u25C6")} ${c.strong("@Consul")} [Coordinator] detected an active lock held by a teammate.`),console.log(`
1066
1068
  ${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 ye)await Pe.sendMessage(q.locked_by,`@${re} 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.")}
1067
1069
  `);continue}for(let P of K)if(!await Pe.acquireLock(P,ee.slice(0,100))){console.log(`
1068
1070
  ${c.warning("\u26A0")} ${c.strong("@Consul")}: a teammate locked ${c.highlight(P)} first. Halting to avoid a conflict.
1069
- `);continue}}Pe.setActivity(ee.slice(0,80))}if(n.agents.enabled&&n.agents.orchestration==="auto"){let re=zl(ee),K={bob:"architect",alex:"coder",david:"researcher",hablas:"planner",emma:"product-manager"};if(re==="XS"||Un(ee))E.addUserMessage(ee);else if(re==="S")E.addUserMessage(ee);else if(re==="M"){let se=Fs(ee),ye=se.find(V=>V!=="hablas")||"alex";I=yn(I,ye),$t(I),Eg(ee,re,se),x&&x.updateProgress(`Task started [M]: ${ee.substring(0,60)}`);let P=js(ee,[ye]),q=i.getOllamaTools();h.reset(),S.resetBudget();let M=new Nn(h,m,S,n),{finalSynthesis:G,synthesisOk:te}=await M.run(ee,P,q,{abortSignal:C?.signal});console.log(Jt("Hablas","Team Leader")),console.log(Xt(G)),E.addAssistantMessage(te?G:`[Team Execution Summary]
1071
+ `);continue}}Pe.setActivity(ee.slice(0,80))}if(n.agents.enabled&&n.agents.orchestration==="auto"){let re=Yl(ee),K={bob:"architect",alex:"coder",david:"researcher",hablas:"planner",emma:"product-manager"};if(re==="XS"||Un(ee))E.addUserMessage(ee);else if(re==="S")E.addUserMessage(ee);else if(re==="M"){let se=Fs(ee),ye=se.find(V=>V!=="hablas")||"alex";I=yn(I,ye),kt(I),Rg(ee,re,se),x&&x.updateProgress(`Task started [M]: ${ee.substring(0,60)}`);let P=js(ee,[ye]),q=i.getOllamaTools();h.reset(),S.resetBudget();let M=new Nn(h,m,S,n),{finalSynthesis:G,synthesisOk:te}=await M.run(ee,P,q,{abortSignal:C?.signal});console.log(Jt("Hablas","Team Leader")),console.log(Xt(G)),E.addAssistantMessage(te?G:`[Team Execution Summary]
1070
1072
 
1071
- ${G}`),await ei(n,t);continue}else if(re==="L"){let se=Fs(ee);if(se.length>1){let ye=js(ee,se),P=ye.tasks.map((V,Z)=>({description:V.description,assignee:V.role||"alex",assigneeName:V.agentName||V.role,dependent_task_ids:Z>0?[`plan_${p.nextPlanNum}_t${Z}`]:[]})),q=p.createPlan(ye.strategy||ee.slice(0,60),ye.strategy||"sequential",P),M=p.getProgress();console.log(Vn(q,{percent:M.percentage,done:M.done,total:M.total}));let te=(await a.prompt(` ${c.accent("?")} ${c.strong("approve")} / ${c.muted("edit")} / ${c.muted("skip")} ${c.muted("\u203A")} `)).trim().toLowerCase();if(te==="edit"||te==="e"){console.log(le("Edit mode: describe your changes and I will re-plan."));let V=await a.prompt(` ${c.muted("Edit \u203A")} `);if(V.trim()){let Z=`${ee}
1073
+ ${G}`),await Zr(n,t);continue}else if(re==="L"){let se=Fs(ee);if(se.length>1){let ye=js(ee,se),P=ye.tasks.map((V,Z)=>({description:V.description,assignee:V.role||"alex",assigneeName:V.agentName||V.role,dependent_task_ids:Z>0?[`plan_${p.nextPlanNum}_t${Z}`]:[]})),q=p.createPlan(ye.strategy||ee.slice(0,60),ye.strategy||"sequential",P),M=p.getProgress();console.log(Vn(q,{percent:M.percentage,done:M.done,total:M.total}));let te=(await a.prompt(` ${c.accent("?")} ${c.strong("approve")} / ${c.muted("edit")} / ${c.muted("skip")} ${c.muted("\u203A")} `)).trim().toLowerCase();if(te==="edit"||te==="e"){console.log(le("Edit mode: describe your changes and I will re-plan."));let V=await a.prompt(` ${c.muted("Edit \u203A")} `);if(V.trim()){let Z=`${ee}
1072
1074
 
1073
- User modification: ${V.trim()}`;E.addUserMessage(Z)}else E.addUserMessage(ee)}else if(te==="skip"||te==="s"){console.log(le("Plan skipped \u2014 executing directly without orchestration."));for(let V of q.tasks)p.skipTask(V.task_id);E.addUserMessage(ee)}else{console.log(J("Plan approved \u2014 executing...")),console.log(""),f.logDecision(`Plan approved: ${q.title}`,"Hablas",`${q.tasks.length} tasks for ${se.length} agents`),x&&(x.updateProgress(`Plan approved [L]: ${q.title}`),x.recordDecision(`Plan: ${q.title}`,"Hablas",`${q.tasks.length} tasks, ${se.length} agents`));for(let Gt of se)I=yn(I,Gt);$t(I),h.reset(),S.resetBudget();let V=i.getOllamaTools(),Z=new Nn(h,m,S,n),{results:Oe,finalSynthesis:Se,synthesisOk:ni}=await Z.run(ee,ye,V,{abortSignal:C?.signal,peerReview:!0});for(let Gt of q.tasks)p.finishTask(Gt.task_id);console.log(Jt("Hablas","Team Leader")),console.log(Xt(Se)),E.addAssistantMessage(ni?Se:`[Team Execution Summary]
1075
+ User modification: ${V.trim()}`;E.addUserMessage(Z)}else E.addUserMessage(ee)}else if(te==="skip"||te==="s"){console.log(le("Plan skipped \u2014 executing directly without orchestration."));for(let V of q.tasks)p.skipTask(V.task_id);E.addUserMessage(ee)}else{console.log(J("Plan approved \u2014 executing...")),console.log(""),f.logDecision(`Plan approved: ${q.title}`,"Hablas",`${q.tasks.length} tasks for ${se.length} agents`),x&&(x.updateProgress(`Plan approved [L]: ${q.title}`),x.recordDecision(`Plan: ${q.title}`,"Hablas",`${q.tasks.length} tasks, ${se.length} agents`));for(let Gt of se)I=yn(I,Gt);kt(I),h.reset(),S.resetBudget();let V=i.getOllamaTools(),Z=new Nn(h,m,S,n),{results:Oe,finalSynthesis:Se,synthesisOk:ti}=await Z.run(ee,ye,V,{abortSignal:C?.signal,peerReview:!0});for(let Gt of q.tasks)p.finishTask(Gt.task_id);console.log(Jt("Hablas","Team Leader")),console.log(Xt(Se)),E.addAssistantMessage(ti?Se:`[Team Execution Summary]
1074
1076
 
1075
- ${Se}`),await ei(n,t);continue}}else{let ye=se.find(q=>q!=="hablas")||"alex";I=yn(I,ye),$t(I);let P=K[ye]||"coder";if(l.has(P)&&l.getActiveName()!==P){l.setActive(P);let q=l.getActive(),M=await Qt(t,n),G=Zt(q.systemPrompt,M,d,f);E.updateSystemPrompt(G)}E.addUserMessage(ee)}}else{let se=Fs(ee);se.includes("emma")||se.push("emma");let ye=js(ee,se),P=ye.tasks.map((V,Z)=>({description:V.description,assignee:V.role||"alex",assigneeName:V.agentName||V.role,dependent_task_ids:Z>0?[`plan_${p.nextPlanNum}_t${Z}`]:[]})),q=p.createPlan(ye.strategy||ee.slice(0,60),ye.strategy||"sequential",P),M=p.getProgress();console.log(Vn(q,{percent:M.percentage,done:M.done,total:M.total})),console.log(le("XL project \u2014 Emma will create a PRD before implementation begins."));let te=(await a.prompt(` ${c.accent("?")} ${c.strong("approve")} / ${c.muted("edit")} / ${c.muted("skip")} ${c.muted("\u203A")} `)).trim().toLowerCase();if(te==="edit"||te==="e"){console.log(le("Edit mode: describe your changes and I will re-plan."));let V=await a.prompt(` ${c.muted("Edit \u203A")} `);if(V.trim()){let Z=`${ee}
1077
+ ${Se}`),await Zr(n,t);continue}}else{let ye=se.find(q=>q!=="hablas")||"alex";I=yn(I,ye),kt(I);let P=K[ye]||"coder";if(l.has(P)&&l.getActiveName()!==P){l.setActive(P);let q=l.getActive(),M=await Qt(t,n),G=Zt(q.systemPrompt,M,d,f);E.updateSystemPrompt(G)}E.addUserMessage(ee)}}else{let se=Fs(ee);se.includes("emma")||se.push("emma");let ye=js(ee,se),P=ye.tasks.map((V,Z)=>({description:V.description,assignee:V.role||"alex",assigneeName:V.agentName||V.role,dependent_task_ids:Z>0?[`plan_${p.nextPlanNum}_t${Z}`]:[]})),q=p.createPlan(ye.strategy||ee.slice(0,60),ye.strategy||"sequential",P),M=p.getProgress();console.log(Vn(q,{percent:M.percentage,done:M.done,total:M.total})),console.log(le("XL project \u2014 Emma will create a PRD before implementation begins."));let te=(await a.prompt(` ${c.accent("?")} ${c.strong("approve")} / ${c.muted("edit")} / ${c.muted("skip")} ${c.muted("\u203A")} `)).trim().toLowerCase();if(te==="edit"||te==="e"){console.log(le("Edit mode: describe your changes and I will re-plan."));let V=await a.prompt(` ${c.muted("Edit \u203A")} `);if(V.trim()){let Z=`${ee}
1076
1078
 
1077
- User modification: ${V.trim()}`;E.addUserMessage(Z)}else E.addUserMessage(ee)}else if(te==="skip"||te==="s"){console.log(le("Plan skipped \u2014 executing directly without orchestration."));for(let V of q.tasks)p.skipTask(V.task_id);E.addUserMessage(ee)}else{console.log(J("Plan approved \u2014 executing full workflow...")),console.log(""),f.logDecision(`XL Plan approved: ${q.title}`,"Hablas",`${q.tasks.length} tasks for ${se.length} agents (includes PRD)`),x&&(x.updateProgress(`XL Plan approved: ${q.title}`),x.recordDecision(`XL Plan: ${q.title}`,"Hablas",`Full system: ${q.tasks.length} tasks, ${se.length} agents`));for(let Gt of se)I=yn(I,Gt);$t(I),h.reset(),S.resetBudget();let V=i.getOllamaTools(),Z=new Nn(h,m,S,n),{results:Oe,finalSynthesis:Se,synthesisOk:ni}=await Z.run(ee,ye,V,{abortSignal:C?.signal,peerReview:!0});for(let Gt of q.tasks)p.finishTask(Gt.task_id);console.log(Jt("Hablas","Team Leader")),console.log(Xt(Se)),E.addAssistantMessage(ni?Se:`[XL Team Execution Summary]
1079
+ User modification: ${V.trim()}`;E.addUserMessage(Z)}else E.addUserMessage(ee)}else if(te==="skip"||te==="s"){console.log(le("Plan skipped \u2014 executing directly without orchestration."));for(let V of q.tasks)p.skipTask(V.task_id);E.addUserMessage(ee)}else{console.log(J("Plan approved \u2014 executing full workflow...")),console.log(""),f.logDecision(`XL Plan approved: ${q.title}`,"Hablas",`${q.tasks.length} tasks for ${se.length} agents (includes PRD)`),x&&(x.updateProgress(`XL Plan approved: ${q.title}`),x.recordDecision(`XL Plan: ${q.title}`,"Hablas",`Full system: ${q.tasks.length} tasks, ${se.length} agents`));for(let Gt of se)I=yn(I,Gt);kt(I),h.reset(),S.resetBudget();let V=i.getOllamaTools(),Z=new Nn(h,m,S,n),{results:Oe,finalSynthesis:Se,synthesisOk:ti}=await Z.run(ee,ye,V,{abortSignal:C?.signal,peerReview:!0});for(let Gt of q.tasks)p.finishTask(Gt.task_id);console.log(Jt("Hablas","Team Leader")),console.log(Xt(Se)),E.addAssistantMessage(ti?Se:`[XL Team Execution Summary]
1078
1080
 
1079
- ${Se}`),await ei(n,t);continue}}}else E.addUserMessage(ee);C=new AbortController,w.startTurn(),_.resetTurn();let Ne=n.agents.enabled&&n.agents.orchestration==="auto"?zl(ee)==="XS":!1;await Wg(E,r,i,o,{interactive:!0,autoMode:X,input:a,logger:e,config:n,abortSignal:C.signal,reactEngine:w,errorRecovery:_,skipTools:Ne,onToolCall:()=>{F++,I=Ki(I,"tool_call"),$t(I)}}),await ei(n,t)}catch(W){if(W.code==="ERR_USE_AFTER_CLOSE")break;if(W.name==="AbortError")continue;console.log(Ce(W.message)),e.error(W,"REPL error")}a.close(),Pe&&await Pe.shutdown(),console.log(no({turns:$,duration:Date.now()-H,toolCalls:F}))}async function G0(n,e,t){let s=e.workingDirectory==="."?process.cwd():e.workingDirectory,r=je(e),i=new us(s,e),o=new on(e),a=new ms(s),l=await Qt(s,e),u=Zt(Yn,l,a),d=new an(u,e.historySize),f=Gg(n,s);d.addUserMessage(f),await Wg(d,r,i,o,{interactive:!1,autoMode:e.autoMode||!1,logger:t,config:e})}function Gg(n,e){let t=/#([\w./-]+)/g,s=n,r;for(;(r=t.exec(n))!==null;){let i=r[1],o=Lt.resolve(e,i);pt.existsSync(o)&&(s=s.replace(`#${i}`,i))}return s}async function ei(n,e){if(!(n.team?.enabled&&Pe))return;if(await Pe.releaseAllMyLocks(),!n.workspace?.autoPush){console.log(`
1081
+ ${Se}`),await Zr(n,t);continue}}}else E.addUserMessage(ee);C=new AbortController,w.startTurn(),_.resetTurn();let Fe=n.agents.enabled&&n.agents.orchestration==="auto"?Yl(ee)==="XS":!1;await Vg(E,r,i,o,{interactive:!0,autoMode:X,input:a,logger:e,config:n,abortSignal:C.signal,reactEngine:w,errorRecovery:_,skipTools:Fe,onToolCall:()=>{F++,I=qi(I,"tool_call"),kt(I)}}),await Zr(n,t)}catch(W){if(W.code==="ERR_USE_AFTER_CLOSE")break;if(W.name==="AbortError")continue;console.log(Ce(W.message)),e.error(W,"REPL error")}a.close(),Pe&&await Pe.shutdown(),console.log(to({turns:$,duration:Date.now()-H,toolCalls:F}))}async function z0(n,e,t){let s=e.workingDirectory==="."?process.cwd():e.workingDirectory,r=He(e),i=new us(s,e),o=new on(e),a=new ms(s),l=await Qt(s,e),u=Zt(Yn,l,a),d=new an(u,e.historySize),f=zg(n,s);d.addUserMessage(f),await Vg(d,r,i,o,{interactive:!1,autoMode:e.autoMode||!1,logger:t,config:e})}function zg(n,e){let t=/#([\w./-]+)/g,s=n,r;for(;(r=t.exec(n))!==null;){let i=r[1],o=Lt.resolve(e,i);ft.existsSync(o)&&(s=s.replace(`#${i}`,i))}return s}async function Zr(n,e){if(!(n.team?.enabled&&Pe))return;if(await Pe.releaseAllMyLocks(),!n.workspace?.autoPush){console.log(`
1080
1082
  ${c.info("\u2139")} ${c.strong("@Consul")}: "Changes tracked. Auto-push is off \u2014 commit & push manually when ready."
1081
1083
  `);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(`
1082
1084
  ${c.muted("@Consul: workspace clean \u2014 nothing to push.")}
@@ -1087,16 +1089,16 @@ ${Se}`),await ei(n,t);continue}}}else E.addUserMessage(ee);C=new AbortController
1087
1089
  `),s("git add -A"),s('git commit -m "sync(team): automatic updates via @Consul" --no-verify');return}console.log(`
1088
1090
  ${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."
1089
1091
  `)}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)}
1090
- `)}}var pt,Kg,Lt,Ql,Pe,Xl,H0,B0,U0,Tt=N(()=>{"use strict";Wu();fa();pt=O(require("fs")),Kg=require("child_process"),Lt=O(require("path")),Ql=O(require("os"));Bn();jp();va();wa();qp();yr();Ua();Gp();Yp();Ai();mn();gg();bg();vg();_g();Ag();Wn();Gl();kg();$g();Tg();Ig();xn();Mg();Hg();Jl();Fl();Hl();Wl();Pe=null,Xl=Lt.join(Ql.homedir(),".hablas",".first_run_done"),H0=Lt.join(Ql.homedir(),".hablas","config.json"),B0=150,U0=1500});function Dt(n){let e=tc.join(Vg.homedir(),".hablas","logs");ti.existsSync(e)||ti.mkdirSync(e,{recursive:!0});let t=tc.join(e,`session-${Date.now()}.log`);return(0,ec.default)({level:"info"},ec.default.destination({dest:t,sync:!1}))}var ec,tc,Vg,ti,nc=N(()=>{"use strict";ec=O(Dl()),tc=O(require("path")),Vg=O(require("os")),ti=O(require("fs"))});var Qg={};Fe(Qg,{createApiServer:()=>Xg,startApiServer:()=>J0});function V0(){try{return JSON.parse(Yg.readFileSync(Jg.resolve(__dirname,"..","..","package.json"),"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function Xg(n){let e=Dt(n),t=Y0(n);return zg.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 Y0(n){return[{method:"GET",path:"/api/v1/health",handler:async()=>({status:200,body:{status:"ok",version:z0,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 J0(n){return new Promise((e,t)=>{let s=Xg(n);s.on("error",t),s.listen(n.api.port,n.api.host,()=>{e(s)})})}var zg,Yg,Jg,z0,Zg=N(()=>{"use strict";zg=O(require("http")),Yg=O(require("fs")),Jg=O(require("path"));nc();z0=V0()});var Q0={};Fe(Q0,{CLI_VERSION:()=>As});module.exports=ay(Q0);var gc=O(mc(),1),{program:aC,createCommand:lC,createArgument:cC,createOption:uC,CommanderError:dC,InvalidArgumentError:fC,InvalidOptionArgumentError:pC,Command:yc,Argument:hC,Option:mC,Help:gC}=gc.default;Tt();yr();nc();var ey=O(require("fs")),ty=O(require("path"));function X0(){try{let n=ty.resolve(__dirname,"..","package.json");return JSON.parse(ey.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}var As=X0(),ce=new yc;ce.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");ce.command("create <description>").description("Generate a full project from a description").option("--stack <stack>","Tech stack preference").option("--with-tests","Include test generation").option("--with-docker","Include Docker setup").action(async(n,e)=>{let t=ce.opts(),s=Ze({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=Dt(s),{runSingleCommand:i}=await Promise.resolve().then(()=>(Tt(),jt)),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)});ce.command("commit").description("Generate a smart commit message from staged changes").action(async()=>{let n=ce.opts(),e=Ze({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),t=Dt(e),{getGitStatus:s,getDetailedDiff:r,generateCommitPrompt:i}=await Promise.resolve().then(()=>(vn(),Gn)),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(()=>(Tt(),jt));await d(u,e,t)});ce.command("pr").description("Generate a PR description from branch commits").option("--base <branch>","Base branch","main").action(async n=>{let e=ce.opts(),t=Ze({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=Dt(t),{getGitStatus:r,getRecentCommits:i,generatePRPrompt:o}=await Promise.resolve().then(()=>(vn(),Gn)),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(()=>(Tt(),jt));await f(d,t,s)});ce.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=ce.opts(),t=Ze({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=Dt(t),{getRecentCommits:r,generateChangelogPrompt:i}=await Promise.resolve().then(()=>(vn(),Gn)),o=t.workingDirectory||process.cwd(),a=await r(o,parseInt(n.count)),l=i(a,n.version),{runSingleCommand:u}=await Promise.resolve().then(()=>(Tt(),jt));await u(l,t,s)});ce.command("security").description("Run security scan on the project").option("--fix","Auto-fix issues where possible").action(async n=>{let e=ce.opts(),t=Ze({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(()=>(zi(),Jc)),i=t.workingDirectory||process.cwd();console.log(`
1092
+ `)}}var ft,Gg,Lt,Zl,Pe,Ql,U0,q0,K0,Et=N(()=>{"use strict";Gu();fa();ft=O(require("fs")),Gg=require("child_process"),Lt=O(require("path")),Zl=O(require("os"));Bn();Hp();va();wa();Kp();yr();Ua();Vp();Jp();_i();mn();yg();vg();wg();Ag();$g();Wn();Gl();Cg();Eg();Pg();Lg();xn();Dg();Ug();Xl();Fl();Hl();Wl();Pe=null,Ql=Lt.join(Zl.homedir(),".hablas",".first_run_done"),U0=Lt.join(Zl.homedir(),".hablas","config.json"),q0=150,K0=1500});function Dt(n){let e=nc.join(Yg.homedir(),".hablas","logs");ei.existsSync(e)||ei.mkdirSync(e,{recursive:!0});let t=nc.join(e,`session-${Date.now()}.log`);return(0,tc.default)({level:"info"},tc.default.destination({dest:t,sync:!1}))}var tc,nc,Yg,ei,sc=N(()=>{"use strict";tc=O(Dl()),nc=O(require("path")),Yg=O(require("os")),ei=O(require("fs"))});var ey={};je(ey,{createApiServer:()=>Zg,startApiServer:()=>Q0});function Y0(){try{return JSON.parse(Xg.readFileSync(Qg.resolve(__dirname,"..","..","package.json"),"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function Zg(n){let e=Dt(n),t=X0(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 X0(n){return[{method:"GET",path:"/api/v1/health",handler:async()=>({status:200,body:{status:"ok",version:J0,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 Q0(n){return new Promise((e,t)=>{let s=Zg(n);s.on("error",t),s.listen(n.api.port,n.api.host,()=>{e(s)})})}var Jg,Xg,Qg,J0,ty=N(()=>{"use strict";Jg=O(require("http")),Xg=O(require("fs")),Qg=O(require("path"));sc();J0=Y0()});var eC={};je(eC,{CLI_VERSION:()=>As});module.exports=cy(eC);var yc=O(gc(),1),{program:cC,createCommand:uC,createArgument:dC,createOption:fC,CommanderError:pC,InvalidArgumentError:hC,InvalidOptionArgumentError:mC,Command:bc,Argument:gC,Option:yC,Help:bC}=yc.default;Et();yr();sc();var ny=O(require("fs")),sy=O(require("path"));function Z0(){try{let n=sy.resolve(__dirname,"..","package.json");return JSON.parse(ny.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}var As=Z0(),ce=new bc;ce.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");ce.command("create <description>").description("Generate a full project from a description").option("--stack <stack>","Tech stack preference").option("--with-tests","Include test generation").option("--with-docker","Include Docker setup").action(async(n,e)=>{let t=ce.opts(),s=Ze({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=Dt(s),{runSingleCommand:i}=await Promise.resolve().then(()=>(Et(),jt)),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)});ce.command("commit").description("Generate a smart commit message from staged changes").action(async()=>{let n=ce.opts(),e=Ze({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),t=Dt(e),{getGitStatus:s,getDetailedDiff:r,generateCommitPrompt:i}=await Promise.resolve().then(()=>(vn(),Gn)),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(()=>(Et(),jt));await d(u,e,t)});ce.command("pr").description("Generate a PR description from branch commits").option("--base <branch>","Base branch","main").action(async n=>{let e=ce.opts(),t=Ze({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=Dt(t),{getGitStatus:r,getRecentCommits:i,generatePRPrompt:o}=await Promise.resolve().then(()=>(vn(),Gn)),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(()=>(Et(),jt));await f(d,t,s)});ce.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=ce.opts(),t=Ze({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=Dt(t),{getRecentCommits:r,generateChangelogPrompt:i}=await Promise.resolve().then(()=>(vn(),Gn)),o=t.workingDirectory||process.cwd(),a=await r(o,parseInt(n.count)),l=i(a,n.version),{runSingleCommand:u}=await Promise.resolve().then(()=>(Et(),jt));await u(l,t,s)});ce.command("security").description("Run security scan on the project").option("--fix","Auto-fix issues where possible").action(async n=>{let e=ce.opts(),t=Ze({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(()=>(Vi(),Xc)),i=t.workingDirectory||process.cwd();console.log(`
1091
1093
  \u{1F512} Running security scan...
1092
- `);let o=s(i);console.log(r(o))});ce.command("stats").description("Show developer analytics and usage statistics").action(async()=>{let{loadStats:n,formatStats:e}=await Promise.resolve().then(()=>(Wn(),Wi)),t=n();console.log(e(t))});ce.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=ce.opts(),t=Ze({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(()=>(fa(),Yf)),l=t.workingDirectory||process.cwd();if(n.init)r(l,n.init),console.log(`
1094
+ `);let o=s(i);console.log(r(o))});ce.command("stats").description("Show developer analytics and usage statistics").action(async()=>{let{loadStats:n,formatStats:e}=await Promise.resolve().then(()=>(Wn(),Ki)),t=n();console.log(e(t))});ce.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=ce.opts(),t=Ze({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(()=>(fa(),Jf)),l=t.workingDirectory||process.cwd();if(n.init)r(l,n.init),console.log(`
1093
1095
  \u2713 Team "${n.init}" initialized.`),console.log(` Config saved to: .hablas/team.json
1094
- `);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))}});ce.command("info").description("Show workspace information and detected configuration").action(async()=>{let n=ce.opts(),e=Ze({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(()=>(Xi(),su)),r=e.workingDirectory||process.cwd();console.log(`
1096
+ `);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))}});ce.command("info").description("Show workspace information and detected configuration").action(async()=>{let n=ce.opts(),e=Ze({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(()=>(Ji(),ru)),r=e.workingDirectory||process.cwd();console.log(`
1095
1097
  \u25C6 Workspace Information
1096
- `);let i=t(r);console.log(s(i)),console.log("")});ce.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=ce.opts(),t=Ze({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(()=>(Zg(),Qg));console.log(`
1098
+ `);let i=t(r);console.log(s(i)),console.log("")});ce.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=ce.opts(),t=Ze({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(()=>(ty(),ey));console.log(`
1097
1099
  \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(`
1098
1100
  Press Ctrl+C to stop.
1099
- `)}catch(r){console.error(` \u2717 Failed to start API server: ${r}`)}});ce.command("run <prompt>").description("Run a single command non-interactively").action(async n=>{let e=ce.opts(),t=Ze({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=Dt(t),{runSingleCommand:r}=await Promise.resolve().then(()=>(Tt(),jt));await r(n,t,s)});ce.command("doctor").description("Run system diagnostics").action(async()=>{let n=ce.opts(),e=Ze({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(()=>(Mi(),Uc)),r=await t({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(s(r))});ce.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(()=>(Ri(),jc));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(`
1101
+ `)}catch(r){console.error(` \u2717 Failed to start API server: ${r}`)}});ce.command("run <prompt>").description("Run a single command non-interactively").action(async n=>{let e=ce.opts(),t=Ze({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=Dt(t),{runSingleCommand:r}=await Promise.resolve().then(()=>(Et(),jt));await r(n,t,s)});ce.command("doctor").description("Run system diagnostics").action(async()=>{let n=ce.opts(),e=Ze({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(()=>(Ii(),qc)),r=await t({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(s(r))});ce.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(()=>(Ti(),Hc));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(`
1100
1102
  \u{1F50D} Searching marketplace for "${n.search}"...`),console.log(" (Marketplace: https://registry.hablas.dev/plugins)"),console.log(`
1101
1103
  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(`
1102
1104
  Install: hablas plugins --install <name>
@@ -1106,7 +1108,7 @@ ${Se}`),await ei(n,t);continue}}}else E.addUserMessage(ee);C=new AbortController
1106
1108
  \u25C6 Installed Plugins
1107
1109
  `),console.log(s()),console.log(`
1108
1110
  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>
1109
- `))});ce.action(async()=>{let n=ce.opts(),e=Ze({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(()=>(Jl(),Ug));await s(e);return}let t=Dt(e);await Zl(e,t)});ce.parse();0&&(module.exports={CLI_VERSION});
1111
+ `))});ce.action(async()=>{let n=ce.opts(),e=Ze({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(()=>(Xl(),Kg));await s(e);return}let t=Dt(e);await ec(e,t)});ce.parse();0&&(module.exports={CLI_VERSION});
1110
1112
  /*! Bundled license information:
1111
1113
 
1112
1114
  normalize-path/index.js: