hablas-ai 1.2.4 → 1.2.6

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 +304 -377
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,106 +1,57 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var gg=Object.create;var ts=Object.defineProperty;var yg=Object.getOwnPropertyDescriptor;var bg=Object.getOwnPropertyNames;var vg=Object.getPrototypeOf,wg=Object.prototype.hasOwnProperty;var N=(n,e)=>()=>(n&&(e=n(n=0)),e);var H=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Re=(n,e)=>{for(var t in e)ts(n,t,{get:e[t],enumerable:!0})},kl=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of bg(e))!wg.call(n,r)&&r!==t&&ts(n,r,{get:()=>e[r],enumerable:!(s=yg(e,r))||s.enumerable});return n};var O=(n,e,t)=>(t=n!=null?gg(vg(n)):{},kl(e||!n||!n.__esModule?ts(t,"default",{value:n,enumerable:!0}):t,n)),xg=n=>kl(ts({},"__esModule",{value:!0}),n);var bn=H(Pr=>{var ns=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}},Or=class extends ns{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Pr.CommanderError=ns;Pr.InvalidArgumentError=Or});var ss=H(Mr=>{var{InvalidArgumentError:Sg}=bn(),Ir=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 Sg(`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 _g(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Mr.Argument=Ir;Mr.humanReadableArgName=_g});var Dr=H($l=>{var{humanReadableArgName:Ag}=ss(),Lr=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=>Ag(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((s,r)=>Math.max(s,t.subcommandTerm(r).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((s,r)=>Math.max(s,t.optionTerm(r).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((s,r)=>Math.max(s,t.optionTerm(r).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((s,r)=>Math.max(s,t.argumentTerm(r).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let s="";for(let r=e.parent;r;r=r.parent)s=r.name()+" "+s;return s+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let s=`(${t.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatHelp(e,t){let s=t.padWidth(e,t),r=t.helpWidth||80,i=2,o=2;function a(p,y){if(y){let S=`${p.padEnd(s+o)}${y}`;return t.wrap(S,r-i,s+o)}return p}function l(p){return p.join(`
3
- `).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(c=c.concat([t.wrap(d,r,0),""]));let f=t.visibleArguments(e).map(p=>a(t.argumentTerm(p),t.argumentDescription(p)));f.length>0&&(c=c.concat(["Arguments:",l(f),""]));let h=t.visibleOptions(e).map(p=>a(t.optionTerm(p),t.optionDescription(p)));if(h.length>0&&(c=c.concat(["Options:",l(h),""])),this.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(y=>a(t.optionTerm(y),t.optionDescription(y)));p.length>0&&(c=c.concat(["Global Options:",l(p),""]))}let m=t.visibleCommands(e).map(p=>a(t.subcommandTerm(p),t.subcommandDescription(p)));return m.length>0&&(c=c.concat(["Commands:",l(m),""])),c.join(`
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),c=e.slice(s).replace(`\r
2
+ "use strict";var vm=Object.create;var Rn=Object.defineProperty;var xm=Object.getOwnPropertyDescriptor;var _m=Object.getOwnPropertyNames;var Sm=Object.getPrototypeOf,Am=Object.prototype.hasOwnProperty;var M=(n,e)=>()=>(n&&(e=n(n=0)),e);var L=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ae=(n,e)=>{for(var t in e)Rn(n,t,{get:e[t],enumerable:!0})},Ca=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _m(e))!Am.call(n,s)&&s!==t&&Rn(n,s,{get:()=>e[s],enumerable:!(r=xm(e,s))||r.enumerable});return n};var C=(n,e,t)=>(t=n!=null?vm(Sm(n)):{},Ca(e||!n||!n.__esModule?Rn(t,"default",{value:n,enumerable:!0}):t,n)),km=n=>Ca(Rn({},"__esModule",{value:!0}),n);var Zt=L(Qr=>{var On=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},Xr=class extends On{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Qr.CommanderError=On;Qr.InvalidArgumentError=Xr});var Pn=L(es=>{var{InvalidArgumentError:$m}=Zt(),Zr=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,r)=>{if(!this.argChoices.includes(t))throw new $m(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Em(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}es.Argument=Zr;es.humanReadableArgName=Em});var ns=L(Ta=>{var{humanReadableArgName:Cm}=Pn(),ts=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!s&&!i?t.push(r):r.long&&!i?t.push(e.createOption(r.long,r.description)):r.short&&!s&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(i=>!i.hidden);t.push(...s)}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(r=>Cm(r)).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((r,s)=>Math.max(r,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,s)=>Math.max(r,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,s)=>Math.max(r,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+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(r=>JSON.stringify(r)).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(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),s=t.helpWidth||80,i=2,o=2;function a(f,g){if(g){let y=`${f.padEnd(r+o)}${g}`;return t.wrap(y,s-i,r+o)}return f}function l(f){return f.join(`
3
+ `).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${t.commandUsage(e)}`,""],u=t.commandDescription(e);u.length>0&&(c=c.concat([t.wrap(u,s,0),""]));let d=t.visibleArguments(e).map(f=>a(t.argumentTerm(f),t.argumentDescription(f)));d.length>0&&(c=c.concat(["Arguments:",l(d),""]));let p=t.visibleOptions(e).map(f=>a(t.optionTerm(f),t.optionDescription(f)));if(p.length>0&&(c=c.concat(["Options:",l(p),""])),this.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(g=>a(t.optionTerm(g),t.optionDescription(g)));f.length>0&&(c=c.concat(["Global Options:",l(f),""]))}let h=t.visibleCommands(e).map(f=>a(t.subcommandTerm(f),t.subcommandDescription(f)));return h.length>0&&(c=c.concat(["Commands:",l(h),""])),c.join(`
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,r,s=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-r;if(a<s)return e;let l=e.slice(0,r),c=e.slice(r).replace(`\r
5
5
  `,`
6
- `),d=" ".repeat(s),h="\\s\u200B",m=new RegExp(`
7
- |.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),p=c.match(m)||[];return l+p.map((y,S)=>y===`
8
- `?"":(S>0?d:"")+y.trimEnd()).join(`
9
- `)}};$l.Help=Lr});var jr=H(Hr=>{var{InvalidArgumentError:kg}=bn(),Nr=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=Eg(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 kg(`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 $g(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Fr=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 $g(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Eg(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}}Hr.Option=Nr;Hr.DualOptions=Fr});var Tl=H(El=>{function Tg(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 Cg(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=Tg(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
- (Did you mean one of ${s.join(", ")}?)`:s.length===1?`
11
- (Did you mean ${s[0]}?)`:""}El.suggestSimilar=Cg});var Il=H(Pl=>{var Rg=require("node:events").EventEmitter,Br=require("node:child_process"),ct=require("node:path"),Ur=require("node:fs"),oe=require("node:process"),{Argument:Og,humanReadableArgName:Pg}=ss(),{CommanderError:Kr}=bn(),{Help:Ig}=Dr(),{Option:Cl,DualOptions:Mg}=jr(),{suggestSimilar:Rl}=Tl(),qr=class n extends Rg{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=>oe.stdout.write(t),writeErr:t=>oe.stderr.write(t),getOutHelpWidth:()=>oe.stdout.isTTY?oe.stdout.columns:void 0,getErrHelpWidth:()=>oe.stderr.isTTY?oe.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 Ig,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 Og(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 Kr(e,t,s)),oe.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 Cl(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 Cl)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,c)=>{let d=a.exec(l);return d?d[0]:c},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){oe.versions?.electron&&(t.from="electron");let r=oe.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=oe.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":oe.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,t){let s=this._prepareUserArgs(e,t);return this._parseCommand([],s),this}async parseAsync(e,t){let s=this._prepareUserArgs(e,t);return await this._parseCommand([],s),this}_executeSubCommand(e,t){t=t.slice();let s=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,f){let h=ct.resolve(d,f);if(Ur.existsSync(h))return h;if(r.includes(ct.extname(f)))return;let m=r.find(p=>Ur.existsSync(`${h}${p}`));if(m)return`${h}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=Ur.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=ct.resolve(ct.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=ct.basename(this._scriptPath,ct.extname(this._scriptPath));f!==this._name&&(d=i(a,`${f}-${e._name}`))}o=d||o}s=r.includes(ct.extname(o));let l;oe.platform!=="win32"?s?(t.unshift(o),t=Ol(oe.execArgv).concat(t),l=Br.spawn(oe.argv[0],t,{stdio:"inherit"})):l=Br.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=Ol(oe.execArgv).concat(t),l=Br.spawn(oe.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{oe.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let c=this._exitCallback;l.on("close",d=>{d=d??1,c?c(new Kr(d,"commander.executeSubCommandAsync","(close)")):oe.exit(d)}),l.on("error",d=>{if(d.code==="ENOENT"){let f=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
6
+ `),u=" ".repeat(r),p="\\s\u200B",h=new RegExp(`
7
+ |.{1,${a-1}}([${p}]|$)|[^${p}]+?([${p}]|$)`,"g"),f=c.match(h)||[];return l+f.map((g,y)=>g===`
8
+ `?"":(y>0?u:"")+g.trimEnd()).join(`
9
+ `)}};Ta.Help=ts});var os=L(is=>{var{InvalidArgumentError:Tm}=Zt(),rs=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 r=Om(e);this.short=r.shortFlag,this.long=r.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,r)=>{if(!this.argChoices.includes(t))throw new Tm(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Rm(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ss=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,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function Rm(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Om(n){let e,t,r=n.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),t=r.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}is.Option=rs;is.DualOptions=ss});var Oa=L(Ra=>{function Pm(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let r=0;r<=n.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=n.length;s++){let i=1;n[s-1]===e[r-1]?i=0:i=1,t[s][r]=Math.min(t[s-1][r]+1,t[s][r-1]+1,t[s-1][r-1]+i),s>1&&r>1&&n[s-1]===e[r-2]&&n[s-2]===e[r-1]&&(t[s][r]=Math.min(t[s][r],t[s-2][r-2]+1))}return t[n.length][e.length]}function Mm(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 r=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Pm(n,o),l=Math.max(n.length,o.length);(l-a)/l>i&&(a<s?(s=a,r=[o]):a===s&&r.push(o))}),r.sort((o,a)=>o.localeCompare(a)),t&&(r=r.map(o=>`--${o}`)),r.length>1?`
10
+ (Did you mean one of ${r.join(", ")}?)`:r.length===1?`
11
+ (Did you mean ${r[0]}?)`:""}Ra.suggestSimilar=Mm});var Da=L(La=>{var Im=require("node:events").EventEmitter,as=require("node:child_process"),Xe=require("node:path"),ls=require("node:fs"),se=require("node:process"),{Argument:Lm,humanReadableArgName:Dm}=Pn(),{CommanderError:cs}=Zt(),{Help:Fm}=ns(),{Option:Pa,DualOptions:Nm}=os(),{suggestSimilar:Ma}=Oa(),us=class n extends Im{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=>se.stdout.write(t),writeErr:t=>se.stderr.write(t),getOutHelpWidth:()=>se.stdout.isTTY?se.stdout.columns:void 0,getErrHelpWidth:()=>se.stderr.isTTY?se.stderr.columns:void 0,outputError:(t,r)=>r(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,r){let s=t,i=r;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return s&&(l.description(s),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),s?this:l}createCommand(e){return new n(e)}createHelp(){return Object.assign(new Fm,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 Lm(e,t)}argument(e,t,r,s){let i=this.createArgument(e,t);return typeof r=="function"?i.default(s).argParser(r):i.default(r),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[,r,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(r);return o.helpOption(!1),s&&o.arguments(s),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 r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
+ Expecting one of '${r.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,r){this._exitCallback&&this._exitCallback(new cs(e,t,r)),se.exit(e)}action(e){let t=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new Pa(e,t)}_callParseArg(e,t,r,s){try{return e.parseArg(t,r)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${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 r=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 '${r}'
14
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),r=t(e).find(s=>this._findCommand(s));if(r){let s=t(this._findCommand(r)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(r);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(r,i,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,r,s,i){if(typeof t=="object"&&t instanceof Pa)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,r);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(l,c)=>{let u=a.exec(l);return u?u[0]:c},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,r,s){return this._optionEx({},e,t,r,s)}requiredOption(e,t,r,s){return this._optionEx({mandatory:!0},e,t,r,s)}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,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.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){se.versions?.electron&&(t.from="electron");let s=se.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=se.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":se.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=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",r}parse(e,t){let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_executeSubCommand(e,t){t=t.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let p=Xe.resolve(u,d);if(ls.existsSync(p))return p;if(s.includes(Xe.extname(d)))return;let h=s.find(f=>ls.existsSync(`${p}${f}`));if(h)return`${p}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=ls.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Xe.resolve(Xe.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=Xe.basename(this._scriptPath,Xe.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}r=s.includes(Xe.extname(o));let l;se.platform!=="win32"?r?(t.unshift(o),t=Ia(se.execArgv).concat(t),l=as.spawn(se.argv[0],t,{stdio:"inherit"})):l=as.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=Ia(se.execArgv).concat(t),l=as.spawn(se.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{se.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let c=this._exitCallback;l.on("close",u=>{u=u??1,c?c(new cs(u,"commander.executeSubCommandAsync","(close)")):se.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT"){let d=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(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)oe.exit(1);else{let f=new Kr(1,"commander.executeSubCommandAsync","(error)");f.nestedError=d,c(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 c=this._findOption(l);if(c){if(c.required){let d=i.shift();d===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,d)}else if(c.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${c.name()}`,d)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),d=this._findOption(l.slice(0,c));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,l.slice(c+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
+ - ${d}`;throw new Error(p)}else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)se.exit(1);else{let d=new cs(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,c(d)}}),this.runningCommand=l}_dispatchSubcommand(e,t,r){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(r));else return s._parseCommand(t,r)}),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=(r,s,i)=>{let o=s;if(s!==null&&r.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,s,i,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,s)=>{let i=r.defaultValue;r.variadic?s<this.args.length?(i=this.args.slice(s),r.parseArg&&(i=i.reduce((o,a)=>e(r,a,o),r.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],r.parseArg&&(i=e(r,i,r.defaultValue))),t[s]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.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(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),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))s(),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():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),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(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(i=>r.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],s=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==="--"){s===r&&s.push(l),s.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let c=this._findOption(l);if(c){if(c.required){let u=i.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;i.length>0&&!o(i[0])&&(u=i.shift()),this.emit(`option:${c.name()}`,u)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),u=this._findOption(l.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,l.slice(c+1));continue}}if(o(l)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(l)){t.push(l),i.length>0&&r.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){r.push(l),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(l),i.length>0&&s.push(...i);break}s.push(l)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}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 oe.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()}`,oe.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Mg(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),c=this.options.find(f=>f.negate&&a===f.attributeName()),d=this.options.find(f=>!f.negate&&a===f.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c: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=Rl(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=Rl(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=>Pg(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=ct.basename(e,ct.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=oe.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
- 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 Ol(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})}Pl.Command=qr});var Nl=H(De=>{var{Argument:Ml}=ss(),{Command:Wr}=Il(),{CommanderError:Lg,InvalidArgumentError:Ll}=bn(),{Help:Dg}=Dr(),{Option:Dl}=jr();De.program=new Wr;De.createCommand=n=>new Wr(n);De.createOption=(n,e)=>new Dl(n,e);De.createArgument=(n,e)=>new Ml(n,e);De.Command=Wr;De.Option=Dl;De.Argument=Ml;De.Help=Dg;De.CommanderError=Lg;De.InvalidArgumentError=Ll;De.InvalidOptionArgumentError=Ll});var jl={};Re(jl,{DEFAULT_CONFIG:()=>vn,NVIDIA_PROVIDER:()=>At});var vn,At,wn=N(()=>{"use strict";vn={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:""}},At={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.1-nemotron-70b-instruct","nvidia/nemotron-4-340b-instruct","meta/llama-3.1-405b-instruct","meta/llama-3.1-70b-instruct","meta/llama-3.1-8b-instruct","mistralai/mixtral-8x22b-instruct-v0.1","mistralai/mistral-large-latest","google/gemma-2-27b-it","microsoft/phi-3-medium-128k-instruct","deepseek-ai/deepseek-coder-33b-instruct","nvidia/llama-3.1-nemotron-51b-instruct","qwen/qwen2.5-coder-32b-instruct"]}});var rs,Bl=N(()=>{"use strict";rs=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(s=>s.name):[]}catch{return[]}}async chatWithTools(e,t,s){let r={model:this.model,messages:e,stream:!1};t.length>0&&(r.tools=t);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)};s&&(i.signal=s);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,t){let s=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:t});if(!s.ok)throw new Error(`Ollama error: ${s.status} ${s.statusText}`);let r=s.body?.getReader();if(!r)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await r.read();if(a)break;o+=i.decode(l,{stream:!0});let c=o.split(`
24
- `);o=c.pop()||"";for(let d of c)if(d.trim())try{let f=JSON.parse(d);f.message?.content&&(yield f.message.content)}catch{}}}}});function ql(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 Hg(n){return n.map(e=>({type:"function",function:e.function}))}function jg(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 Wl(n){return new Promise(e=>setTimeout(e,n))}function Gl(n,e){return!(n.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var Ul,Ng,is,Kl,Fg,Mt,Gr=N(()=>{"use strict";Ul=12e4,Ng=6e4,is=3,Kl=1e3,Fg=20;Mt=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<Fg;){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(Ng)});if(!l.ok)break;let c=await l.json();if(Array.isArray(c))e.push(...c.map(d=>d.id||d.name||d).filter(Boolean)),t=!1;else if(c.data&&Array.isArray(c.data)){let d=c.data.map(f=>f.id||f.name).filter(Boolean);e.push(...d),c.has_more&&d.length>0?(s=d[d.length-1],r++):t=!1}else c.models&&Array.isArray(c.models)&&e.push(...c.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:ql(e)};t.length>0&&(i.tools=Hg(t),i.tool_choice="auto");let o=null;for(let a=0;a<=is;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),Ul),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(c),!f.ok){let y=await f.text().catch(()=>"");if(!Gl(null,f.status))throw new Error(`API error: ${f.status} ${f.statusText} \u2014 ${y}`);if(o=new Error(`API error: ${f.status} ${f.statusText} \u2014 ${y}`),a<is){let S=Kl*Math.pow(2,a);await Wl(S);continue}throw o}let m=(await f.json()).choices?.[0];if(!m)throw new Error("API returned empty response");let p=m.message.tool_calls?jg(m.message.tool_calls):void 0;return{message:{role:m.message.role||"assistant",content:m.message.content||"",tool_calls:p},done:!0,done_reason:m.finish_reason}}catch(f){if(clearTimeout(c),f.name==="AbortError"&&s?.aborted)throw f;if(Gl(f)&&(o=f,a<is)){let h=Kl*Math.pow(2,a);await Wl(h);continue}throw f}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=is)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:ql(e),stream:!0}),signal:t||AbortSignal.timeout(Ul)});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:c}=await i.read();if(l)break;a+=o.decode(c,{stream:!0});let d=a.split(`
25
- `);a=d.pop()||"";for(let f of d){let h=f.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let p=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;p&&(yield p)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}}});function We(n){if(n.provider==="nvidia"){let e={...n,provider:"custom",apiUrl:At.apiUrl};return new Mt(e)}return n.provider==="custom"&&n.apiUrl?new Mt(n):new rs(n)}function Vl(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 xn=N(()=>{"use strict";wn();Bl();Gr()});var zl=N(()=>{"use strict"});function Lt(){let n={providers:[],activeProvider:null,activeModel:null};try{if(ut.existsSync(zr)){let e=ut.readFileSync(zr,"utf-8"),t=JSON.parse(e);return{...n,...t}}}catch{}return n}function Jr(n){ut.existsSync(Vr)||ut.mkdirSync(Vr,{recursive:!0}),ut.writeFileSync(zr,JSON.stringify(n,null,2),"utf-8")}function Ge(n){let e=Lt();e.providers=e.providers.filter(t=>t.name!==n.name),e.providers.push(n),Jr(e)}function Jl(n){let e=Lt(),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),Jr(e),!0):!1}function Ql(n){return Lt().providers.find(t=>t.name.toLowerCase()===n.toLowerCase())}function os(){return Lt().providers}function Xl(n,e){let t=Lt(),s=t.providers.find(r=>r.name===n);s&&(t.activeProvider=n,t.activeModel=e||s.defaultModel,Jr(t))}function Zl(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 ut,Yr,Yl,Vr,zr,Qr=N(()=>{"use strict";ut=O(require("fs")),Yr=O(require("path")),Yl=O(require("os"));zl();Vr=Yr.join(Yl.homedir(),".hablas"),zr=Yr.join(Vr,"models.json")});function cs(){try{if(dt.existsSync(as))return JSON.parse(dt.readFileSync(as,"utf-8"))}catch{}return{}}function tc(n){let e=ls.dirname(as);dt.existsSync(e)||dt.mkdirSync(e,{recursive:!0}),dt.writeFileSync(as,JSON.stringify(n,null,2),"utf-8")}function nc(n,e){let t=cs();t[n]=e,tc(t)}function sc(n){let e=cs();return e[n]?(delete e[n],tc(e),!0):!1}function rc(n){let e=cs(),t=n.trim();for(let[s,r]of Object.entries(e))if(t===s||t.startsWith(s+" "))return t.replace(s,r);return n}function ic(){let n=cs(),e=Object.entries(n);return e.length===0?` No aliases defined.
27
- Use: /alias set <name> <command>`:e.map(([t,s])=>` ${t} \u2192 ${s}`).join(`
28
- `)}var dt,ls,ec,as,Xr=N(()=>{"use strict";dt=O(require("fs")),ls=O(require("path")),ec=O(require("os")),as=ls.join(ec.homedir(),".hablas","aliases.json")});var lc={};Re(lc,{disablePlugin:()=>ni,enablePlugin:()=>ti,ensurePluginsDir:()=>fs,listPlugins:()=>ac,renderPlugins:()=>si});function ei(){try{if(Oe.existsSync(ds))return JSON.parse(Oe.readFileSync(ds,"utf-8"))}catch{}return{disabled:[]}}function oc(n){let e=zt.dirname(ds);Oe.existsSync(e)||Oe.mkdirSync(e,{recursive:!0}),Oe.writeFileSync(ds,JSON.stringify(n,null,2),"utf-8")}function fs(){Oe.existsSync(us)||Oe.mkdirSync(us,{recursive:!0})}function ac(){fs();let n=ei(),e=[];try{let t=Oe.readdirSync(us).filter(s=>s.endsWith(".js"));for(let s of t){let r=zt.join(us,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 ti(n){let e=ei(),t=e.disabled.indexOf(n);return t!==-1?(e.disabled.splice(t,1),oc(e),!0):!1}function ni(n){let e=ei();return e.disabled.includes(n)?!1:(e.disabled.push(n),oc(e),!0)}function si(){let n=ac();return n.length===0?` No plugins installed.
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
- ${e.description}`}).join(`
31
-
32
- `)}var Oe,zt,Zr,us,ds,ri=N(()=>{"use strict";Oe=O(require("fs")),zt=O(require("path")),Zr=O(require("os")),us=zt.join(Zr.homedir(),".hablas","plugins"),ds=zt.join(Zr.homedir(),".hablas","plugins.json")});var dc={};Re(dc,{renderDiagnostics:()=>ai,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=cc.join(Ve.homedir(),".hablas");if(e.push({name:"Config directory",status:ii.existsSync(r)?"ok":"warn",message:ii.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=Ve.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",c=a[4]||"?";e.push({name:"Disk space",status:parseInt(c)>90?"warn":"ok",message:`${l} available (${c} 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:`${Ve.platform()} ${Ve.arch()} \u2014 ${Ve.cpus().length} cores, ${Math.round(Ve.totalmem()/1024/1024/1024)}GB RAM`}),e}function ai(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 c=`${t[l.status]}${e[l.status]}${s}`,d=l.name.padEnd(18);i.push(` ${c} ${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 ii,cc,Ve,uc,li=N(()=>{"use strict";ii=O(require("fs")),cc=O(require("path")),Ve=O(require("os")),uc=require("child_process")});function ci(n){let e=n.trim();return!!(e.length<15&&!fc.test(e)||Bg.test(e)||Ug.test(e)||Kg.test(e)||qg.test(e))}function pc(n){let e=n.toLowerCase(),t=["hablas"];return ci(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&&fc.test(n)&&t.push("alex")),t}function hc(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(c=>c.role==="emma").id]:[],status:"pending"}),i){let c=[];a?c.push(t.find(d=>d.role==="david").id):r&&c.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:c,status:"pending"})}if(o){let c=[];i?c.push(t.find(d=>d.role==="bob").id):a?c.push(t.find(d=>d.role==="david").id):r&&c.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:c,status:"pending"})}let l="sequential";return t.length>2&&t.some(c=>c.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 mc(){let n=[];for(let e of he){let s=e.role==="hablas"?" \u2605":"";n.push(` @${e.name}${s} \u2014 ${e.title}`),n.push(` ${e.description}`)}return n.join(`
34
- `)}var he,Bg,Ug,Kg,qg,fc,Sn=N(()=>{"use strict";he=[{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"]}],Bg=/^(hi|hello|hey|howdy|yo|sup|hiya|good\s*(morning|afternoon|evening|night)|what'?s\s*up|greetings)\b/i,Ug=/^(مرحبا|أهلا|أهلاً|هلا|السلام\s*عليكم|وعليكم\s*السلام|كيف\s*حالك|كيفك|شلونك|صباح\s*الخير|مساء\s*الخير|شكرا|شكراً|يعطيك\s*العافية|تمام|اهلين|هلو|مرحبتين|الله\s*يسلمك|حياك|حياك\s*الله|يا\s*هلا|كيف\s*الحال|اخبارك|شخبارك)/i,Kg=/^(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,qg=/^(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,fc=/\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 _n(){try{if(Yt.existsSync(ui)){let n=Yt.readFileSync(ui,"utf-8"),e=JSON.parse(n);return{...gc,...e}}}catch{}return{...gc}}function bc(){return ui}var Yt,di,yc,ui,gc,fi=N(()=>{"use strict";Yt=O(require("fs")),di=O(require("path")),yc=O(require("os")),ui=di.join(yc.homedir(),".hablas","agents.json"),gc={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 bi={};Re(bi,{formatStats:()=>Jg,loadStats:()=>Jt,saveStats:()=>ps,trackAgentUsage:()=>Vg,trackFileModified:()=>zg,trackMessage:()=>gi,trackSession:()=>Gg,trackToolCall:()=>yi});function Jt(){try{if(ft.existsSync(hi))return JSON.parse(ft.readFileSync(hi,"utf-8"))}catch{}return Wg()}function ps(n){try{ft.existsSync(pi)||ft.mkdirSync(pi,{recursive:!0}),ft.writeFileSync(hi,JSON.stringify(n,null,2))}catch{}}function Wg(){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 Gg(n){return n.totalSessions++,n.lastUsed=new Date().toISOString(),Yg(n),n}function gi(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 yi(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 Vg(n,e){return n.agentUsage[e]=(n.agentUsage[e]||0)+1,n}function zg(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 Yg(n){let e=hs(),t=wc(new Date(Date.now()-864e5));n.dailyActivity[t]||n.dailyActivity[e]?n.streak++:n.streak=1,n.streak>n.longestStreak&&(n.longestStreak=n.streak)}function hs(){return wc(new Date)}function wc(n){return n.toISOString().split("T")[0]}function Jg(n){let e=[];e.push(`
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 ft,mi,vc,pi,hi,An=N(()=>{"use strict";ft=O(require("fs")),mi=O(require("path")),vc=O(require("os")),pi=mi.join(vc.homedir(),".hablas"),hi=mi.join(pi,"analytics.json")});var Sc={};Re(Sc,{formatScanResults:()=>wi,runSecurityScan:()=>vi});function ey(n,e){let t=[],s=e.split(`
37
- `);for(let{pattern:r,name:i,severity:o}of Qg){r.lastIndex=0;let a;for(;(a=r.exec(e))!==null;){let c=e.substring(0,a.index).split(`
38
- `).length,d=s[c-1]||"";d.trim().startsWith("#")||d.trim().startsWith("//")||n.includes(".example")||n.includes(".sample")||t.push({severity:o,type:"secret",file:n,line:c,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return t}function ty(n,e){let t=[],s=e.split(`
39
- `),r=Dt.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 xc(n,e=[]){try{let t=ms.readdirSync(n,{withFileTypes:!0});for(let s of t){if(Xg.has(s.name))continue;let r=Dt.join(n,s.name);if(s.isDirectory())xc(r,e);else if(s.isFile()){let i=Dt.extname(s.name);Zg.has(i)||e.push(r)}}}catch{}return e}function vi(n){let e=Date.now(),t=xc(n),s=[];for(let o of t)try{let a=ms.readFileSync(o,"utf-8"),l=Dt.relative(n,o),c=ey(l,a);s.push(...c);let d=ty(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 wi(n){let e=[];if(e.push(`
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 ms,Dt,Qg,Xg,Zg,xi=N(()=>{"use strict";ms=O(require("fs")),Dt=O(require("path")),Qg=[{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"}],Xg=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Zg=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"])});var kn={};Re(kn,{formatGitStatus:()=>ly,generateChangelogPrompt:()=>ay,generateCommitPrompt:()=>iy,generatePRPrompt:()=>oy,getDetailedDiff:()=>sy,getGitStatus:()=>Si,getRecentCommits:()=>ry,getStagedDiff:()=>ny});async function Si(n){try{let{stdout:e}=await Qt("git branch --show-current",{cwd:n}),{stdout:t}=await Qt("git status --porcelain",{cwd:n}),s=e.trim(),r=[],i=[],o=[];for(let c of t.split(`
42
- `).filter(Boolean)){let d=c.substring(0,2),f=c.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:c}=await Qt("git rev-list --left-right --count HEAD...@{upstream}",{cwd:n}),d=c.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 ny(n){try{let{stdout:e}=await Qt("git diff --cached --stat",{cwd:n});return e.trim()}catch{return""}}async function sy(n){try{let{stdout:e}=await Qt("git diff --cached",{cwd:n,maxBuffer:1048576});return e.length>1e4?e.substring(0,1e4)+`
43
- ... (truncated)`:e.trim()}catch{return""}}async function ry(n,e=20){try{let{stdout:t}=await Qt(`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 iy(n,e){return`Based on the following git diff, generate a concise, conventional commit message.
45
-
46
- Rules:
47
- - Use conventional commits format: type(scope): description
48
- - Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore
49
- - Keep the first line under 72 characters
50
- - Add a body if the change is complex (separated by blank line)
51
- - Be specific about what changed
52
-
53
- Staged files: ${e.join(", ")}
54
-
55
- Diff:
56
- ${n}
57
-
58
- Generate ONLY the commit message, nothing else.`}function oy(n,e,t){let s=n.map(r=>`- ${r.message}`).join(`
59
- `);return`Generate a comprehensive Pull Request description.
60
-
61
- Base branch: ${e}
62
- Head branch: ${t}
63
-
64
- Commits:
65
- ${s}
66
-
67
- Format:
68
- ## Summary
69
- (Brief overview of changes)
70
-
71
- ## Changes
72
- (Bullet list of specific changes)
73
-
74
- ## Testing
75
- (How to test these changes)
76
-
77
- ## Notes
78
- (Any additional context)
79
-
80
- Generate ONLY the PR description in markdown.`}function ay(n,e){let t=n.map(s=>`- ${s.hash.substring(0,7)} ${s.message} (${s.author})`).join(`
81
- `);return`Generate a changelog entry for version ${e} from these commits.
82
-
83
- Commits:
84
- ${t}
85
-
86
- Format:
87
- ## [${e}] - ${new Date().toISOString().split("T")[0]}
88
-
89
- ### Added
90
- - (new features)
20
+ `),this.outputHelp({error:!0}));let r=t||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in se.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()}`,se.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Nm(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"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 r=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:u||o},s=o=>{let a=r(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=Ma(e,s)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=Ma(e,s)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let s=this.createOption(t,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.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 r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}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(r=>Dm(r));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=Xe.basename(e,Xe.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},r;return t.error?r=s=>this._outputConfiguration.writeErr(s):r=s=>this._outputConfiguration.writeOut(s),t.write=e.write||r,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation(r);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",r))}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=se.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
+ Expecting one of '${r.join("', '")}'`);let s=`${e}Help`;return this.on(s,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(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ia(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",s="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])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],r=i[3],s=i[4]),t&&s!=="0"?`${t}=${r}:${parseInt(s)+1}`:e})}La.Command=us});var Ha=L(ke=>{var{Argument:Fa}=Pn(),{Command:ds}=Da(),{CommanderError:jm,InvalidArgumentError:Na}=Zt(),{Help:Hm}=ns(),{Option:ja}=os();ke.program=new ds;ke.createCommand=n=>new ds(n);ke.createOption=(n,e)=>new ja(n,e);ke.createArgument=(n,e)=>new Fa(n,e);ke.Command=ds;ke.Option=ja;ke.Argument=Fa;ke.Help=Hm;ke.CommanderError=jm;ke.InvalidArgumentError=Na;ke.InvalidOptionArgumentError=Na});function fs(n){let e=n.trim();return!!(e.length<15&&!Ua.test(e)||Bm.test(e)||qm.test(e)||Um.test(e)||Km.test(e))}function Ka(n){let e=n.toLowerCase(),t=["hablas"];return fs(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&&Ua.test(n)&&t.push("alex")),t}function Wa(n,e){let t=[],r=1,s=e.includes("emma"),i=e.includes("bob"),o=e.includes("alex"),a=e.includes("david");if(s&&t.push({id:`task-${r++}`,role:"emma",agentName:"Emma",description:"Analyze requirements, create PRD, and define user stories",input:n,dependencies:[],status:"pending"}),a&&t.push({id:`task-${r++}`,role:"david",agentName:"David",description:"Research requirements, best practices, and relevant documentation",input:n,dependencies:s?[t.find(c=>c.role==="emma").id]:[],status:"pending"}),i){let c=[];a?c.push(t.find(u=>u.role==="david").id):s&&c.push(t.find(u=>u.role==="emma").id),t.push({id:`task-${r++}`,role:"bob",agentName:"Bob",description:"Design system architecture and structure",input:n,dependencies:c,status:"pending"})}if(o){let c=[];i?c.push(t.find(u=>u.role==="bob").id):a?c.push(t.find(u=>u.role==="david").id):s&&c.push(t.find(u=>u.role==="emma").id),t.push({id:`task-${r++}`,role:"alex",agentName:"Alex",description:"Implement the code based on architecture/requirements",input:n,dependencies:c,status:"pending"})}let l="sequential";return t.length>2&&t.some(c=>c.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 Ga(){let n=[];for(let e of me){let r=e.role==="hablas"?" \u2605":"";n.push(` @${e.name}${r} \u2014 ${e.title}`),n.push(` ${e.description}`)}return n.join(`
24
+ `)}var me,Bm,qm,Um,Km,Ua,en=M(()=>{"use strict";me=[{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"]}],Bm=/^(hi|hello|hey|howdy|yo|sup|hiya|good\s*(morning|afternoon|evening|night)|what'?s\s*up|greetings)\b/i,qm=/^(مرحبا|أهلا|أهلاً|هلا|السلام\s*عليكم|وعليكم\s*السلام|كيف\s*حالك|كيفك|شلونك|صباح\s*الخير|مساء\s*الخير|شكرا|شكراً|يعطيك\s*العافية|تمام|اهلين|هلو|مرحبتين|الله\s*يسلمك|حياك|حياك\s*الله|يا\s*هلا|كيف\s*الحال|اخبارك|شخبارك)/i,Um=/^(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,Km=/^(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,Ua=/\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 Wm(){try{let n=Ya.resolve(__dirname,"..","..","package.json");return JSON.parse(za.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function ie(n,e){return Xa||!gs?n:`${e}${n}\x1B[0m`}function Gm(n){let e=yt();if(!n)return m.border("\u2500".repeat(e));let t=n.replace(/\x1b\[[0-9;]*m/g,""),r=Math.max(0,e-t.length-2),s=Math.floor(r/2),i=r-s;return m.border("\u2500".repeat(s))+" "+n+" "+m.border("\u2500".repeat(i))}function Vm(n,e=2){let t=yt()-e;if(t<=0)return" ".repeat(e)+n;let r=n.split(" "),s=[],i="";for(let o of r)(i+" "+o).trim().length>t&&i?(s.push(i.trim()),i=o):i+=(i?" ":"")+o;return i&&s.push(i.trim()),s.map(o=>" ".repeat(e)+o).join(`
25
+ `)}function zm(n){let e=Math.max(...n.map(([t])=>t.length));return n.map(([t,r])=>` ${m.muted(t.padEnd(e))} ${r}`).join(`
26
+ `)}function Ym(n){if(Xa||!gs)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 r=0;r<n.length;r++){let s=Math.floor(r/n.length*e.length);t+=e[s]+n[r]}return t+"\x1B[0m"}function Za(n,e){let t=yt(),r=e?e.replace(ms.homedir(),"~"):"",s=m.border("\u2554"+"\u2550".repeat(t-2)+"\u2557"),i=m.border("\u2560"+"\u2550".repeat(t-2)+"\u2563"),o=m.border("\u255A"+"\u2550".repeat(t-2)+"\u255D"),a="H A B L A S A I",l="EXECUTIVE SYSTEM COORDINATOR",c="developed by abdulmoin hablas",u=Math.max(0,Math.floor((t-2-a.length)/2)),d=m.border("\u2551")+" ".repeat(u)+m.strong(a)+" ".repeat(t-2-a.length-u)+m.border("\u2551"),p=Math.max(0,Math.floor((t-2-l.length)/2)),h=m.border("\u2551")+" ".repeat(p)+m.secondary(l)+" ".repeat(t-2-l.length-p)+m.border("\u2551"),f=Math.max(0,Math.floor((t-2-c.length)/2)),g=m.border("\u2551")+" ".repeat(f)+m.muted(c)+" ".repeat(t-2-c.length-f)+m.border("\u2551"),y=m.muted(`SYSTEM VERSION: v${Ja}`),w=m.warning(`CORE MODEL: ${n}`);return["",s,d,h,c?g:"",i,` ${m.muted("\u25B8")} ${y}`,` ${m.muted("\u25B8")} ${w}`,r?` ${m.muted("\u25B8")} ${m.muted(`WORKSPACE: ${r}`)}`:"",` ${m.chrome("\u251C"+"\u2500".repeat(t-2)+"\u2524")}`,` ${m.muted(" \u203A")} ${m.secondary("Type naturally to get started")}`,` ${m.muted(" \u203A")} ${m.secondary("/help for commands \xB7 Ctrl+C to cancel \xB7 Ctrl+C\xD72 to exit")}`,o,""].filter(Boolean).join(`
27
+ `)}function ys(n,e){return`
28
+ ${(n==="Hablas"?m.leader:n==="Bob"?m.architect:n==="Alex"?m.engineer:n==="David"?m.analyst:n==="Emma"?m.product:m.primary)("\u25C6")} ${m.strong(n)} ${m.muted(`[${e.toUpperCase()}]`)}`}function el(){let n=yt();return["",m.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E"),` ${m.strong("Abdulmoin Hablas")} ${m.muted("\u2014 Full-Stack Developer")}`,m.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),"",` ${m.accent("\u25C6")} ${m.primary("Portfolio")} ${m.muted("https://portfolio-monopoly63s-projects.vercel.app/")}`,` ${m.accent("\u25C6")} ${m.primary("GitHub")} ${m.muted("https://github.com/Monopoly63?tab=repositories")}`,` ${m.accent("\u25C6")} ${m.primary("Telegram")} ${m.muted("https://t.me/Hablas_Trade")}`,` ${m.accent("\u25C6")} ${m.primary("WhatsApp")} ${m.muted("https://wa.me/13232128875")}`,` ${m.accent("\u25C6")} ${m.primary("Instagram")} ${m.muted("https://www.instagram.com/li0vy_")}`,"",m.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),` ${m.strong("Projects")}`,"",` ${m.muted("\u25B8")} AI Search Engine ${m.muted("\u2192")} ${m.highlight("https://ai-search-engine-ashy.vercel.app/")}`,` ${m.muted("\u25B8")} Trade Tracker ${m.muted("\u2192")} ${m.highlight("https://trade-tracker-monopoly63s-projects.vercel.app/")}`,` ${m.muted("\u25B8")} Tree Algo Lab ${m.muted("\u2192")} ${m.highlight("https://tree-algorithms-lab.vercel.app/")}`,"",m.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F"),""].join(`
29
+ `)}function tl(){return["",` ${Ym("\u25C6 hablas")} ${m.success(`v${Ja}`)}`,"",` ${m.muted("Runtime")} ${m.secondary(`Node.js ${process.version}`)}`,` ${m.muted("Platform")} ${m.secondary(`${process.platform} ${process.arch}`)}`,` ${m.muted("Author")} ${m.secondary("Abdulmoin Hablas")}`,` ${m.muted("License")} ${m.secondary("MIT")}`,""].join(`
30
+ `)}function Va(n,e){let t=Math.min(yt()-8,60),r=e?` ${m.accent(e)} `:"",s=`${m.error("\u25CF")} ${m.warning("\u25CF")} ${m.success("\u25CF")}`,i=` ${m.chrome("\u250C"+"\u2500".repeat(4))} ${s} ${m.chrome("\u2500".repeat(Math.max(0,t-10-(e?e.length+2:0))))}${r}`,o=String(n.length).length,a=n.map((c,u)=>{let d=m.lineNum(String(u+1).padStart(o)+" \u2502 "),p=m.codeBlock(c);return` ${m.chrome("\u2502")} ${d}${p}`}),l=` ${m.chrome("\u2514"+"\u2500".repeat(t))}`;return[i,...a,l]}function bs(n){let e=n.split(`
31
+ `),t=[],r=!1,s="",i=[];for(let o of e){if(o.trimStart().startsWith("```")){r?(t.push(...Va(i,s)),r=!1,i=[]):(r=!0,s=o.trimStart().slice(3).trim(),i=[]);continue}if(r){i.push(o);continue}if(/^#{1,3}\s/.test(o)){let l=o.replace(/^#+\s/,"");t.push(""),t.push(` ${m.strong(m.primary(l))}`);continue}if(/^[-*]\s/.test(o.trim())){let l=o.trim().slice(2),c=ps(l);t.push(` ${m.accent("\u25B8")} ${c}`);continue}if(/^\d+\.\s/.test(o.trim())){let l=o.trim().match(/^(\d+)\.\s(.+)/);if(l){t.push(` ${m.muted(l[1]+".")} ${ps(l[2])}`);continue}}if(!o.trim()){t.push("");continue}let a=Vm(ps(o),2);t.push(...a.split(`
32
+ `))}return r&&i.length>0&&t.push(...Va(i,s)),`
33
+ `+t.join(`
34
+ `)+`
35
+ `}function ps(n){let e=n.replace(/`([^`]+)`/g,(t,r)=>m.highlight(r));return e=e.replace(/\*\*([^*]+)\*\*/g,(t,r)=>m.strong(m.primary(r))),e=e.replace(/\*([^*]+)\*/g,(t,r)=>`\x1B[3m${r}\x1B[23m`),e}function nl(n){let e=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"}),t=`${m.accent("\u25C6")} ${m.strong(m.primary(`Turn #${n}`))} ${m.muted(`\xB7 ${e} \xB7`)}`;return`
36
+ `+Gm(t)+`
37
+ `}function ws(n){return` ${m.error("\u2717")} ${n}`}function rl(n){return` ${m.warning("\u26A0")} ${n}`}function Jm(n,e){let r=Math.round(Math.min(n,e)/Math.max(e,1)*16),s=e>0?n/e:0;return(s>.85?m.error:s>.6?m.warning:m.success)("\u2588".repeat(r))+m.muted("\u2591".repeat(16-r))}function sl(n){let e=yt(),t=n.connected?m.success("\u25CF connected"):m.error("\u25CB offline"),r=Jm(n.cacheTokens,n.budgetTokens),s=[["model",m.highlight(n.model)],["mindset",m.accent(n.mindset||"coder")],["host",m.muted(n.host)],["directory",m.muted(n.directory.replace(ms.homedir(),"~"))],["context",`${r} ${m.muted(`${n.cacheFiles} files \xB7 ${n.cacheTokens}/${n.budgetTokens} tokens`)}`],["turns",m.muted(String(n.turnCount))],["status",t]];return`
38
+ `+m.chrome("\u256D"+"\u2500".repeat(e-2)+"\u256E")+`
39
+ ${m.accent("\u2726")} ${m.strong("Status")}
91
40
 
92
- ### Changed
93
- - (changes to existing features)
41
+ `+zm(s)+`
94
42
 
95
- ### Fixed
96
- - (bug fixes)
43
+ `+m.chrome("\u2570"+"\u2500".repeat(e-2)+"\u256F")+`
44
+ `}function il(){let n=yt(),e=Math.max(...hs.map(s=>s.cmd.length+(s.arg?s.arg.length+1:0))),t=hs.map(({cmd:s,arg:i,desc:o})=>{let a=s.length+(i?i.length+1:0),l=" ".repeat(e-a+3);return` ${m.primary(s)}${i?" "+m.muted(i):""}${l}${m.secondary(o)}`}),r=["",` ${m.accent("\u2726")} ${m.strong("Tips")}`,"",` ${m.muted("\u25B8")} Use ${m.highlight("#filename")} to reference files inline`,` ${m.muted("\u25B8")} Press ${m.highlight("Ctrl+C")} once to cancel current operation`,` ${m.muted("\u25B8")} Press ${m.highlight("Ctrl+C\xD72")} quickly to exit CLI`,` ${m.muted("\u25B8")} Use ${m.highlight("--auto")} flag to skip tool confirmations`,` ${m.muted("\u25B8")} All file edits are backed up to ${m.muted("~/.hablas/backup/")}`,` ${m.muted("\u25B8")} Complex tasks \u2192 Hablas creates a plan \u2192 approve/edit \u2192 execute`];return`
45
+ `+m.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E")+`
46
+ ${m.accent("\u2726")} ${m.strong("Commands")}
97
47
 
98
- ### Removed
99
- - (removed features)
48
+ `+t.join(`
49
+ `)+`
50
+ `+r.join(`
51
+ `)+`
100
52
 
101
- Only include sections that have entries. Generate ONLY the changelog markdown.`}function ly(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 _c,Ac,Qt,Xt=N(()=>{"use strict";_c=require("child_process"),Ac=require("util"),Qt=(0,Ac.promisify)(_c.exec)});var Cc={};Re(Cc,{detectFramework:()=>kc,detectLanguage:()=>Ec,detectPackageManager:()=>$c,formatWorkspaceInfo:()=>_i,getGitBranch:()=>Tc,scanWorkspace:()=>gs});function kc(n){let e=G.join(n,"package.json");if(W.existsSync(e))try{let t=JSON.parse(W.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(W.existsSync(G.join(n,"requirements.txt"))||W.existsSync(G.join(n,"pyproject.toml")))try{let t=W.existsSync(G.join(n,"requirements.txt"))?W.readFileSync(G.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(W.existsSync(G.join(n,"Cargo.toml")))try{if(W.readFileSync(G.join(n,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(W.existsSync(G.join(n,"go.mod")))try{if(W.readFileSync(G.join(n,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function $c(n){return W.existsSync(G.join(n,"pnpm-lock.yaml"))?"pnpm":W.existsSync(G.join(n,"yarn.lock"))?"yarn":W.existsSync(G.join(n,"bun.lockb"))?"bun":W.existsSync(G.join(n,"package-lock.json"))?"npm":W.existsSync(G.join(n,"Cargo.toml"))?"cargo":W.existsSync(G.join(n,"go.mod"))?"go":W.existsSync(G.join(n,"requirements.txt"))||W.existsSync(G.join(n,"pyproject.toml"))?"pip":"unknown"}function Ec(n){return W.existsSync(G.join(n,"tsconfig.json"))?"TypeScript":W.existsSync(G.join(n,"package.json"))?"JavaScript":W.existsSync(G.join(n,"Cargo.toml"))?"Rust":W.existsSync(G.join(n,"go.mod"))?"Go":W.existsSync(G.join(n,"pyproject.toml"))||W.existsSync(G.join(n,"requirements.txt"))?"Python":"Unknown"}function Tc(n){let e=G.join(n,".git","HEAD");if(!W.existsSync(e))return null;try{let t=W.readFileSync(e,"utf-8").trim();return t.startsWith("ref: refs/heads/")?t.replace("ref: refs/heads/",""):t.substring(0,8)}catch{return null}}function gs(n){let e=kc(n),t=$c(n),s=Ec(n),r=Tc(n),i=W.existsSync(G.join(n,"Dockerfile"))||W.existsSync(G.join(n,"docker-compose.yml"))||W.existsSync(G.join(n,"docker-compose.yaml")),o=W.existsSync(G.join(n,".github","workflows"))||W.existsSync(G.join(n,".gitlab-ci.yml"))||W.existsSync(G.join(n,"Jenkinsfile")),a=W.existsSync(G.join(n,"__tests__"))||W.existsSync(G.join(n,"tests"))||W.existsSync(G.join(n,"test"))||W.existsSync(G.join(n,"spec")),l=W.existsSync(G.join(n,".git")),c=[],d=[".env",".env.local",".env.development",".env.production",".env.example"];for(let y of d)W.existsSync(G.join(n,y))&&c.push(y);let f=[],h=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let y of h)W.existsSync(G.join(n,y))&&f.push(y);let m=[],p=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let y of p)W.existsSync(G.join(n,y))&&m.push(y);return{rootPath:n,framework:e,packageManager:t,language:s,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:r,envFiles:c,configFiles:f,entryPoints:m}}function _i(n){let e=[` Project: ${G.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 W,G,Ai=N(()=>{"use strict";W=O(require("fs")),G=O(require("path"))});function Rc(){return`
53
+ `+m.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F")+`
54
+ `}var ms,za,Ya,Ja,gs,Xa,Qa,yt,m,hs,Rk,vs,Ot=M(()=>{"use strict";ms=C(require("os")),za=C(require("fs")),Ya=C(require("path"));Ja=Wm(),gs=process.stdout.isTTY===!0,Xa=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",Qa=process.stdout.columns||80;gs&&process.stdout.on("resize",()=>{Qa=process.stdout.columns||80});yt=()=>Math.min(Qa-4,100);m={primary:n=>ie(n,"\x1B[38;5;253m"),secondary:n=>ie(n,"\x1B[38;5;247m"),muted:n=>ie(n,"\x1B[38;5;242m"),strong:n=>ie(n,"\x1B[1;38;5;255m"),accent:n=>ie(n,"\x1B[38;5;145m"),highlight:n=>ie(n,"\x1B[38;5;231m"),success:n=>ie(n,"\x1B[38;5;108m"),error:n=>ie(n,"\x1B[38;5;167m"),warning:n=>ie(n,"\x1B[38;5;179m"),info:n=>ie(n,"\x1B[38;5;110m"),codeBlock:n=>ie(n,"\x1B[38;5;188m"),lineNum:n=>ie(n,"\x1B[38;5;239m"),border:n=>ie(n,"\x1B[38;5;237m"),chrome:n=>ie(n,"\x1B[38;5;235m"),added:n=>ie(n,"\x1B[38;5;108m"),removed:n=>ie(n,"\x1B[38;5;167m"),hunk:n=>ie(n,"\x1B[38;5;145m"),leader:n=>ie(n,"\x1B[38;5;179m"),architect:n=>ie(n,"\x1B[38;5;250m"),engineer:n=>ie(n,"\x1B[38;5;145m"),analyst:n=>ie(n,"\x1B[38;5;108m"),product:n=>ie(n,"\x1B[38;5;180m")};hs=[{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"}];Rk={pending:m.muted,running:m.accent,done:m.success,failed:m.error,skipped:m.muted},vs=hs.map(n=>n.cmd).concat(["/exit","/addmodel","/listmodels","/removemodel","/usemodel","/provider","/task","/memory","/mindset","/mindsets","/alias","/doctor","/plugins","/team","/agents","/delegate"])});function ol(){return`
104
55
  ## Available Tools (HEP-1 Protocol)
105
56
 
106
57
  You can execute tools by outputting a strict JSON block wrapped inside <action>...</action> tags.
@@ -181,214 +132,100 @@ You MUST NOT write any conversational text or explanation outside of these tags
181
132
  1. ONLY ONE tool execution per turn. Wait for result before calling another.
182
133
  2. The JSON block inside <action>...</action> MUST be valid JSON (use double quotes, escape newlines properly).
183
134
  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 Oc=N(()=>{"use strict"});function cy(){try{let n=[ys.resolve(__dirname,"..","..","package.json"),ys.resolve(__dirname,"..","package.json"),ys.resolve(__dirname,"package.json")];for(let e of n)if(bs.existsSync(e)){let t=JSON.parse(bs.readFileSync(e,"utf-8"));if(t.version)return t.version}return"1.2.0"}catch{return"1.2.0"}}function ae(n,e){return Mc||!Zt?n:`${e}${n}\x1B[0m`}function uy(n){let e=pt();if(!n)return u.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 u.border("\u2500".repeat(r))+" "+n+" "+u.border("\u2500".repeat(i))}function dy(n,e=2){let t=pt()-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 fy(n){let e=Math.max(...n.map(([t])=>t.length));return n.map(([t,s])=>` ${u.muted(t.padEnd(e))} ${s}`).join(`
186
- `)}function py(n){if(Mc||!Zt)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 Dc(n,e){let t=pt(),s=e?e.replace(Ei.homedir(),"~"):"",r=u.border("\u2554"+"\u2550".repeat(t-2)+"\u2557"),i=u.border("\u2560"+"\u2550".repeat(t-2)+"\u2563"),o=u.border("\u255A"+"\u2550".repeat(t-2)+"\u255D"),a="H A B L A S A I",l="EXECUTIVE SYSTEM COORDINATOR",c="developed by abdulmoin hablas",d=Math.max(0,Math.floor((t-2-a.length)/2)),f=u.border("\u2551")+" ".repeat(d)+u.strong(a)+" ".repeat(t-2-a.length-d)+u.border("\u2551"),h=Math.max(0,Math.floor((t-2-l.length)/2)),m=u.border("\u2551")+" ".repeat(h)+u.secondary(l)+" ".repeat(t-2-l.length-h)+u.border("\u2551"),p=Math.max(0,Math.floor((t-2-c.length)/2)),y=u.border("\u2551")+" ".repeat(p)+u.muted(c)+" ".repeat(t-2-c.length-p)+u.border("\u2551"),S=u.muted(`SYSTEM VERSION: v${Ic}`),_=u.warning(`CORE MODEL: ${n}`);return["",r,f,m,c?y:"",i,` ${u.muted("\u25B8")} ${S}`,` ${u.muted("\u25B8")} ${_}`,s?` ${u.muted("\u25B8")} ${u.muted(`WORKSPACE: ${s}`)}`:"",` ${u.chrome("\u251C"+"\u2500".repeat(t-2)+"\u2524")}`,` ${u.muted(" \u203A")} ${u.secondary("Type naturally to get started")}`,` ${u.muted(" \u203A")} ${u.secondary("/help for commands \xB7 Ctrl+C to cancel \xB7 Ctrl+C\xD72 to exit")}`,o,""].filter(Boolean).join(`
187
- `)}function $n(n,e){return`
188
- ${(n==="Hablas"?u.leader:n==="Bob"?u.architect:n==="Alex"?u.engineer:n==="David"?u.analyst:n==="Emma"?u.product:u.primary)("\u25C6")} ${u.strong(n)} ${u.muted(`[${e.toUpperCase()}]`)}`}function Nc(n,e,t,s){let r=n==="Hablas"?u.leader:n==="Bob"?u.architect:n==="Alex"?u.engineer:n==="David"?u.analyst:n==="Emma"?u.product:u.primary,i=e==="Hablas"?u.leader:e==="Bob"?u.architect:e==="Alex"?u.engineer:e==="David"?u.analyst:e==="Emma"?u.product:u.primary,o=[];if(o.push(""),o.push(` ${r("\u2605")} ${r(n)} ${u.muted("\u2192")} ${u.strong("Delegating to")} ${i(`@${e}`)} ${u.muted(`(${t})`)}`),s){let a=s.length>80?s.slice(0,80)+"...":s;o.push(` ${u.muted(" \u2517")} ${u.secondary(a)}`)}return o.push(""),o.join(`
189
- `)}function Fc(){let n=pt();return["",u.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E"),` ${u.strong("Abdulmoin Hablas")} ${u.muted("\u2014 Full-Stack Developer")}`,u.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),"",` ${u.accent("\u25C6")} ${u.primary("Portfolio")} ${u.muted("https://portfolio-monopoly63s-projects.vercel.app/")}`,` ${u.accent("\u25C6")} ${u.primary("GitHub")} ${u.muted("https://github.com/Monopoly63?tab=repositories")}`,` ${u.accent("\u25C6")} ${u.primary("Telegram")} ${u.muted("https://t.me/Hablas_Trade")}`,` ${u.accent("\u25C6")} ${u.primary("WhatsApp")} ${u.muted("https://wa.me/13232128875")}`,` ${u.accent("\u25C6")} ${u.primary("Instagram")} ${u.muted("https://www.instagram.com/li0vy_")}`,"",u.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),` ${u.strong("Projects")}`,"",` ${u.muted("\u25B8")} AI Search Engine ${u.muted("\u2192")} ${u.highlight("https://ai-search-engine-ashy.vercel.app/")}`,` ${u.muted("\u25B8")} Trade Tracker ${u.muted("\u2192")} ${u.highlight("https://trade-tracker-monopoly63s-projects.vercel.app/")}`,` ${u.muted("\u25B8")} Tree Algo Lab ${u.muted("\u2192")} ${u.highlight("https://tree-algorithms-lab.vercel.app/")}`,"",u.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F"),""].join(`
190
- `)}function Hc(){return["",` ${py("\u25C6 hablas")} ${u.success(`v${Ic}`)}`,"",` ${u.muted("Runtime")} ${u.secondary(`Node.js ${process.version}`)}`,` ${u.muted("Platform")} ${u.secondary(`${process.platform} ${process.arch}`)}`,` ${u.muted("Author")} ${u.secondary("Abdulmoin Hablas")}`,` ${u.muted("License")} ${u.secondary("MIT")}`,""].join(`
191
- `)}function Pc(n,e){let t=Math.min(pt()-8,60),s=e?` ${u.accent(e)} `:"",r=`${u.error("\u25CF")} ${u.warning("\u25CF")} ${u.success("\u25CF")}`,i=` ${u.chrome("\u250C"+"\u2500".repeat(4))} ${r} ${u.chrome("\u2500".repeat(Math.max(0,t-10-(e?e.length+2:0))))}${s}`,o=String(n.length).length,a=n.map((c,d)=>{let f=u.lineNum(String(d+1).padStart(o)+" \u2502 "),h=u.codeBlock(c);return` ${u.chrome("\u2502")} ${f}${h}`}),l=` ${u.chrome("\u2514"+"\u2500".repeat(t))}`;return[i,...a,l]}function En(n){let e=n.split(`
192
- `),t=[],s=!1,r="",i=[];for(let o of e){if(o.trimStart().startsWith("```")){s?(t.push(...Pc(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(` ${u.strong(u.primary(l))}`);continue}if(/^[-*]\s/.test(o.trim())){let l=o.trim().slice(2),c=ki(l);t.push(` ${u.accent("\u25B8")} ${c}`);continue}if(/^\d+\.\s/.test(o.trim())){let l=o.trim().match(/^(\d+)\.\s(.+)/);if(l){t.push(` ${u.muted(l[1]+".")} ${ki(l[2])}`);continue}}if(!o.trim()){t.push("");continue}let a=dy(ki(o),2);t.push(...a.split(`
193
- `))}return s&&i.length>0&&t.push(...Pc(i,r)),`
194
- `+t.join(`
195
- `)+`
196
- `}function ki(n){let e=n.replace(/`([^`]+)`/g,(t,s)=>u.highlight(s));return e=e.replace(/\*\*([^*]+)\*\*/g,(t,s)=>u.strong(u.primary(s))),e=e.replace(/\*([^*]+)\*/g,(t,s)=>`\x1B[3m${s}\x1B[23m`),e}function Ti(n){let e=n.split(`
197
- `),t=[];for(let s of e)s.startsWith("+++")||s.startsWith("---")?t.push(` ${u.muted(s)}`):s.startsWith("+")?t.push(` ${u.added(s)}`):s.startsWith("-")?t.push(` ${u.removed(s)}`):s.startsWith("@@")?t.push(` ${u.hunk(s)}`):s.trim()&&t.push(` ${u.muted(s)}`);return t.join(`
198
- `)}function jc(n){let e=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"}),t=`${u.accent("\u25C6")} ${u.strong(u.primary(`Turn #${n}`))} ${u.muted(`\xB7 ${e} \xB7`)}`;return`
199
- `+uy(t)+`
200
- `}function ke(n){return` ${u.error("\u2717")} ${n}`}function vs(n,e){return` ${u.error("\u2717")} ${n}
201
- ${u.warning("\u2192")} ${u.muted(e)}`}function Y(n){return` ${u.success("\u2713")} ${n}`}function ye(n){return` ${u.muted(n)}`}function U(n){return` ${u.warning("\u26A0")} ${n}`}function hy(n,e){let s=Math.round(Math.min(n,e)/Math.max(e,1)*16),r=e>0?n/e:0;return(r>.85?u.error:r>.6?u.warning:u.success)("\u2588".repeat(s))+u.muted("\u2591".repeat(16-s))}function Bc(n){let e=pt(),t=n.connected?u.success("\u25CF connected"):u.error("\u25CB offline"),s=hy(n.cacheTokens,n.budgetTokens),r=[["model",u.highlight(n.model)],["mindset",u.accent(n.mindset||"coder")],["host",u.muted(n.host)],["directory",u.muted(n.directory.replace(Ei.homedir(),"~"))],["context",`${s} ${u.muted(`${n.cacheFiles} files \xB7 ${n.cacheTokens}/${n.budgetTokens} tokens`)}`],["turns",u.muted(String(n.turnCount))],["status",t]];return`
202
- `+u.chrome("\u256D"+"\u2500".repeat(e-2)+"\u256E")+`
203
- ${u.accent("\u2726")} ${u.strong("Status")}
204
-
205
- `+fy(r)+`
206
-
207
- `+u.chrome("\u2570"+"\u2500".repeat(e-2)+"\u256F")+`
208
- `}function Uc(){let n=pt(),e=Math.max(...$i.map(r=>r.cmd.length+(r.arg?r.arg.length+1:0))),t=$i.map(({cmd:r,arg:i,desc:o})=>{let a=r.length+(i?i.length+1:0),l=" ".repeat(e-a+3);return` ${u.primary(r)}${i?" "+u.muted(i):""}${l}${u.secondary(o)}`}),s=["",` ${u.accent("\u2726")} ${u.strong("Tips")}`,"",` ${u.muted("\u25B8")} Use ${u.highlight("#filename")} to reference files inline`,` ${u.muted("\u25B8")} Press ${u.highlight("Ctrl+C")} once to cancel current operation`,` ${u.muted("\u25B8")} Press ${u.highlight("Ctrl+C\xD72")} quickly to exit CLI`,` ${u.muted("\u25B8")} Use ${u.highlight("--auto")} flag to skip tool confirmations`,` ${u.muted("\u25B8")} All file edits are backed up to ${u.muted("~/.hablas/backup/")}`,` ${u.muted("\u25B8")} Complex tasks \u2192 Hablas creates a plan \u2192 approve/edit \u2192 execute`];return`
209
- `+u.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E")+`
210
- ${u.accent("\u2726")} ${u.strong("Commands")}
211
-
212
- `+t.join(`
213
- `)+`
214
- `+s.join(`
215
- `)+`
216
-
217
- `+u.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F")+`
218
- `}function Kc(n,e){let t=pt(),s=[];s.push(""),s.push(` ${u.chrome("\u256D"+"\u2500".repeat(t-4)+"\u256E")}`),s.push(` ${u.chrome("\u2502")} ${u.leader("\u2605")} ${u.strong("Hablas")} ${u.muted("\u2014 Execution Plan")}${" ".repeat(Math.max(0,t-35))}${u.chrome("\u2502")}`);let r=20,i=Math.round(e.percent/100*r),o=r-i,a=u.success("\u2588".repeat(i))+u.muted("\u2591".repeat(o));s.push(` ${u.chrome("\u2502")} ${a} ${u.muted(`${e.percent}%`)} ${u.muted(`(${e.done}/${e.total} tasks)`)}`),s.push(` ${u.chrome("\u251C"+"\u2500".repeat(t-4)+"\u2524")}`);for(let l=0;l<n.tasks.length;l++){let c=n.tasks[l],d=gy[c.status](my[c.status]),h=(c.assignee==="hablas"?u.leader:c.assignee==="bob"?u.architect:c.assignee==="alex"?u.engineer:c.assignee==="david"?u.analyst:c.assignee==="emma"?u.product:u.muted)(`@${c.assigneeName}`),m="";c.dependent_task_ids.length>0&&(m=u.muted(` \u2190 [${c.dependent_task_ids.join(", ")}]`));let p=u.secondary(c.description);s.push(` ${u.chrome("\u2502")} ${d} ${u.muted(`${c.task_id}.`)} ${h} ${u.muted("\u2192")} ${p}${m}`)}return s.push(` ${u.chrome("\u251C"+"\u2500".repeat(t-4)+"\u2524")}`),s.push(` ${u.chrome("\u2502")} ${u.muted("Strategy:")} ${u.highlight(n.strategy)} ${u.muted("\xB7")} ${u.muted(`${n.tasks.length} tasks`)}`),s.push(` ${u.chrome("\u2570"+"\u2500".repeat(t-4)+"\u256F")}`),s.push(""),s.join(`
219
- `)}function qc(n){let e=Math.min(pt(),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(` ${u.border(s)}`);let a=`\u2605 MISSION STATUS: ${n.taskTitle}`.slice(0,e-4).padEnd(e-4);t.push(` ${u.border("\u2502")} ${u.strong(a)} ${u.border("\u2502")}`),t.push(` ${u.border(r)}`);let c=`Phase: ${n.currentPhase}`.slice(0,e-4).padEnd(e-4);t.push(` ${u.border("\u2502")} ${u.primary(c)} ${u.border("\u2502")}`);let d=[];for(let[g,v]of Object.entries(n.roster)){let b=g==="Hablas"?u.leader:g==="Bob"?u.architect:g==="Alex"?u.engineer:g==="David"?u.analyst:u.product,w="";v==="done"?w=u.success("\u2713"):v==="active"?w=u.highlight("\u25CF"):w=u.muted("\u25CB"),d.push(`@${b(g)} ${w}`)}let f=`Roster: ${d.join(" ")}`,h=f.replace(/\x1b\[[0-9;]*m/g,""),m=Math.max(0,e-4-h.length);t.push(` ${u.border("\u2502")} ${f}${" ".repeat(m)} ${u.border("\u2502")}`);let p=`Active: @${n.activeAgent} (${n.activeAgentTitle})`,y=p.replace(/\x1b\[[0-9;]*m/g,""),S=Math.max(0,e-4-y.length);t.push(` ${u.border("\u2502")} ${p}${" ".repeat(S)} ${u.border("\u2502")}`);let _=`Action: ${n.currentActivity}`,k=_.replace(/\x1b\[[0-9;]*m/g,""),A=Math.max(0,e-4-k.length);return t.push(` ${u.border("\u2502")} ${u.secondary(_)}${" ".repeat(A)} ${u.border("\u2502")}`),t.push(` ${u.border(i)}`),t.join(`
220
- `)}var Ei,bs,ys,Ic,Zt,Mc,Lc,pt,u,kt,$i,my,gy,Ci,en=N(()=>{"use strict";Ei=O(require("os")),bs=O(require("fs")),ys=O(require("path"));Ic=cy(),Zt=process.stdout.isTTY===!0,Mc=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",Lc=process.stdout.columns||80;Zt&&process.stdout.on("resize",()=>{Lc=process.stdout.columns||80});pt=()=>Math.min(Lc-4,100);u={primary:n=>ae(n,"\x1B[38;5;253m"),secondary:n=>ae(n,"\x1B[38;5;247m"),muted:n=>ae(n,"\x1B[38;5;242m"),strong:n=>ae(n,"\x1B[1;38;5;255m"),accent:n=>ae(n,"\x1B[38;5;145m"),highlight:n=>ae(n,"\x1B[38;5;231m"),success:n=>ae(n,"\x1B[38;5;108m"),error:n=>ae(n,"\x1B[38;5;167m"),warning:n=>ae(n,"\x1B[38;5;179m"),info:n=>ae(n,"\x1B[38;5;110m"),codeBlock:n=>ae(n,"\x1B[38;5;188m"),lineNum:n=>ae(n,"\x1B[38;5;239m"),border:n=>ae(n,"\x1B[38;5;237m"),chrome:n=>ae(n,"\x1B[38;5;235m"),added:n=>ae(n,"\x1B[38;5;108m"),removed:n=>ae(n,"\x1B[38;5;167m"),hunk:n=>ae(n,"\x1B[38;5;145m"),leader:n=>ae(n,"\x1B[38;5;179m"),architect:n=>ae(n,"\x1B[38;5;250m"),engineer:n=>ae(n,"\x1B[38;5;145m"),analyst:n=>ae(n,"\x1B[38;5;108m"),product:n=>ae(n,"\x1B[38;5;180m")};kt=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(),!Zt){process.stderr.write(` ${this.message}...
221
- `);return}this.interval=setInterval(()=>{let e=((Date.now()-this.startTime)/1e3).toFixed(1),t=u.accent(this.frames[this.frameIndex]);process.stdout.write(`\r ${t} ${u.muted(this.message)} ${u.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(Zt&&process.stdout.write("\r"+" ".repeat(80)+"\r"),e&&Zt){let s=u.muted(`${t}ms`);console.log(` ${u.muted("\xB7")} ${u.secondary(e)} ${s}`)}}};$i=[{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"}];my={pending:"\u25CB",running:"\u25C9",done:"\u2713",failed:"\u2717",skipped:"\u2013"},gy={pending:u.muted,running:u.accent,done:u.success,failed:u.error,skipped:u.muted};Ci=$i.map(n=>n.cmd).concat(["/exit","/addmodel","/listmodels","/removemodel","/usemodel","/provider","/task","/memory","/mindset","/mindsets","/alias","/doctor","/plugins","/team","/agents","/delegate"])});function Ri(n){let e=ze.join(n,"package.json");if(Pe.existsSync(e))try{let t=JSON.parse(Pe.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(Pe.existsSync(ze.join(n,"pytest.ini"))||Pe.existsSync(ze.join(n,"pyproject.toml"))||Pe.existsSync(ze.join(n,"setup.py")))try{let t=Pe.existsSync(ze.join(n,"requirements.txt"))?Pe.readFileSync(ze.join(n,"requirements.txt"),"utf-8"):"",s=Pe.existsSync(ze.join(n,"pyproject.toml"))?Pe.readFileSync(ze.join(n,"pyproject.toml"),"utf-8"):"";if(t.includes("pytest")||s.includes("pytest"))return"pytest"}catch{}return Pe.existsSync(ze.join(n,"go.mod"))?"go":Pe.existsSync(ze.join(n,"Cargo.toml"))?"cargo":"unknown"}function yy(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 Gc(n,e){let t=Ri(n),s=yy(t,e),r=Date.now(),i="",o="",a=!1;try{i=(0,Wc.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:c,passedTests:d,failedTests:f,failedTestNames:h}=by(i+`
222
- `+o,t);return{framework:t,command:s,passed:a,output:i.slice(0,5e3),errorOutput:o.slice(0,3e3),totalTests:c,passedTests:d,failedTests:f,duration:l,failedTestNames:h}}function by(n,e){let t=0,s=0,r=0,i=[],o=n.split(`
223
- `);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 c=a.match(/(\d+)\s+passed/);c&&t===0&&(s=parseInt(c[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 Vc(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(`
224
- `)}function zc(n){return`The following tests are failing. Analyze the error output and fix the code.
225
-
226
- Test framework: ${n.framework}
227
- Command: ${n.command}
228
- Failed tests: ${n.failedTestNames.join(", ")}
229
-
230
- Error output:
231
- \`\`\`
232
- ${n.errorOutput.slice(0,3e3)}
233
- \`\`\`
234
-
235
- Test output:
236
- \`\`\`
237
- ${n.output.slice(0,2e3)}
238
- \`\`\`
239
-
240
- Instructions:
241
- 1. Read the failing test files to understand what's expected
242
- 2. Read the source files being tested
243
- 3. Fix the source code (not the tests) to make them pass
244
- 4. After fixing, explain what was wrong and what you changed`}var Wc,Pe,ze,Yc=N(()=>{"use strict";Wc=require("child_process"),Pe=O(require("fs")),ze=O(require("path"))});function xs(n){let e=Buffer.from(n).toString("base64url").slice(0,16);return $e.join(vy,e)}async function Qc(n,e,t){let s=xs(n);we.existsSync(s)||we.mkdirSync(s,{recursive:!0});let r=`cp_${Date.now()}`,i=[];for(let f of t){let h=$e.resolve(n,f);if(we.existsSync(h))try{let m=await ht.readFile(h,"utf-8");i.push({path:f,content:m})}catch{}}try{let f=(0,ws.execSync)("git ls-files -m",{cwd:n,encoding:"utf-8",timeout:5e3}).split(`
245
- `).filter(Boolean);for(let h of f)if(!i.find(m=>m.path===h))try{let m=await ht.readFile($e.resolve(n,h),"utf-8");i.push({path:h,content:m})}catch{}}catch{}let o,a;try{o=(0,ws.execSync)("git branch --show-current",{cwd:n,encoding:"utf-8",timeout:5e3}).trim(),a=(0,ws.execSync)("git rev-parse --short HEAD",{cwd:n,encoding:"utf-8",timeout:5e3}).trim()}catch{}let l={id:r,label:e,timestamp:Date.now(),files:i,gitBranch:o,gitHash:a,projectPath:n},c=$e.join(s,`${r}.json`);await ht.writeFile(c,JSON.stringify(l,null,2),"utf-8");let d=we.readdirSync(s).filter(f=>f.endsWith(".json")).sort();if(d.length>20)for(let f of d.slice(0,d.length-20))try{we.unlinkSync($e.join(s,f))}catch{}return{id:r,label:e,timestamp:l.timestamp,fileCount:i.length,projectPath:n}}function Xc(n){let e=xs(n);if(!we.existsSync(e))return[];let t=we.readdirSync(e).filter(r=>r.endsWith(".json")).sort().reverse(),s=[];for(let r of t)try{let i=JSON.parse(we.readFileSync($e.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 Zc(n,e){let t=xs(n),s=$e.join(t,`${e}.json`);if(!we.existsSync(s))return{success:!1,filesRestored:0,error:`Checkpoint ${e} not found`};try{let r=JSON.parse(await ht.readFile(s,"utf-8")),i=0;for(let o of r.files)try{let a=$e.resolve(n,o.path);await ht.mkdir($e.dirname(a),{recursive:!0}),await ht.writeFile(a,o.content,"utf-8"),i++}catch{}return{success:!0,filesRestored:i}}catch(r){return{success:!1,filesRestored:0,error:r.message}}}function eu(n,e){let t=xs(n),s=$e.join(t,`${e}.json`);try{if(we.existsSync(s))return we.unlinkSync(s),!0}catch{}return!1}function tu(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(`
246
- `)}var we,ht,$e,Jc,ws,vy,nu=N(()=>{"use strict";we=O(require("fs")),ht=O(require("fs/promises")),$e=O(require("path")),Jc=O(require("os")),ws=require("child_process"),vy=$e.join(Jc.homedir(),".hablas","checkpoints")});function mt(){}function wy(n,e,t,s,r){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,c=0,d=0;a<l;a++){var f=i[a];if(f.removed){if(f.value=n.join(s.slice(d,d+f.count)),d+=f.count,a&&i[a-1].added){var m=i[a-1];i[a-1]=i[a],i[a]=m}}else{if(!f.added&&r){var h=t.slice(c,c+f.count);h=h.map(function(y,S){var _=s[d+S];return _.length>y.length?_:y}),f.value=n.join(h)}else f.value=n.join(t.slice(c,c+f.count));c+=f.count,f.added||(d+=f.count)}}var p=i[l-1];return l>1&&typeof p.value=="string"&&(p.added||p.removed)&&n.equals("",p.value)&&(i[l-2].value+=p.value,i.pop()),i}function xy(n,e,t){return Li.diff(n,e,t)}function Ss(n){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ss=function(e){return typeof e}:Ss=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ss(n)}function Oi(n){return Ay(n)||ky(n)||$y(n)||Ey()}function Ay(n){if(Array.isArray(n))return Pi(n)}function ky(n){if(typeof Symbol<"u"&&Symbol.iterator in Object(n))return Array.from(n)}function $y(n,e){if(n){if(typeof n=="string")return Pi(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 Pi(n,e)}}function Pi(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 Ey(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
247
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ii(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(Ty.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]=Ii(n[i],e,t,s,r);return e.pop(),t.pop(),o}if(n&&n.toJSON&&(n=n.toJSON()),Ss(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]=Ii(n[l],e,t,s,l);e.pop(),t.pop()}else o=n;return o}function Cy(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 c={};for(r.push(c);i<t.length;){var d=t[i];if(/^(\-\-\-|\+\+\+|@@)\s/.test(d))break;var f=/^(?:Index:|diff(?: -r \w+)+)\s+/.exec(d);f&&(c.index=d.substring(f[0].length).trim()),i++}for(a(c),a(c),c.hunks=[];i<t.length;){var h=t[i];if(/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(h))break;if(/^@@/.test(h))c.hunks.push(l());else{if(h&&e.strict)throw new Error("Unknown line "+(i+1)+" "+JSON.stringify(h));i++}}}function a(c){var d=/^(---|\+\+\+)\s+/.exec(t[i]);if(d){var f=d[1]==="---"?"old":"new",h=t[i].substring(3).trim().split(" ",2),m=h[0].replace(/\\\\/g,"\\");m.startsWith('"')&&m.endsWith('"')&&(m=m.substr(1,m.length-2)),c[f+"FileName"]=m,c[f+"Header"]=(h[1]||"").trim(),i++}}function l(){var c=i,d=t[i++],f=d.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/),h={oldStart:+f[1],oldLines:typeof f[2]>"u"?1:+f[2],newStart:+f[3],newLines:typeof f[4]>"u"?1:+f[4],lines:[],linedelimiters:[]};h.oldLines===0&&(h.oldStart+=1),h.newLines===0&&(h.newStart+=1);for(var m=0,p=0;i<t.length&&!(t[i].indexOf("--- ")===0&&i+2<t.length&&t[i+1].indexOf("+++ ")===0&&t[i+2].indexOf("@@")===0);i++){var y=t[i].length==0&&i!=t.length-1?" ":t[i][0];if(y==="+"||y==="-"||y===" "||y==="\\")h.lines.push(t[i]),h.linedelimiters.push(s[i]||`
248
- `),y==="+"?m++:y==="-"?p++:y===" "&&(m++,p++);else break}if(!m&&h.newLines===1&&(h.newLines=0),!p&&h.oldLines===1&&(h.oldLines=0),e.strict){if(m!==h.newLines)throw new Error("Added line count did not match for hunk at line "+(c+1));if(p!==h.oldLines)throw new Error("Removed line count did not match for hunk at line "+(c+1))}return h}for(;i<t.length;)o();return r}function Ry(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 ou(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(typeof e=="string"&&(e=Cy(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(C,E,J,D){return E===D},a=0,l=t.fuzzFactor||0,c=0,d=0,f,h;function m(C,E){for(var J=0;J<C.lines.length;J++){var D=C.lines[J],Q=D.length>0?D[0]:" ",ve=D.length>0?D.substr(1):D;if(Q===" "||Q==="-"){if(!o(E+1,s[E],Q,ve)&&(a++,a>l))return!1;E++}}return!0}for(var p=0;p<i.length;p++){for(var y=i[p],S=s.length-y.oldLines,_=0,k=d+y.oldStart-1,A=Ry(k,c,S);_!==void 0;_=A())if(m(y,k+_)){y.offset=d+=_;break}if(_===void 0)return!1;c=y.offset+y.oldStart+y.oldLines}for(var g=0,v=0;v<i.length;v++){var b=i[v],w=b.oldStart+b.offset+g-1;g+=b.newLines-b.oldLines;for(var x=0;x<b.lines.length;x++){var T=b.lines[x],P=T.length>0?T[0]:" ",$=T.length>0?T.substr(1):T,F=b.linedelimiters&&b.linedelimiters[x]||`
249
- `;if(P===" ")w++;else if(P==="-")s.splice(w,1),r.splice(w,1);else if(P==="+")s.splice(w,0,$),r.splice(w,0,F),w++;else if(P==="\\"){var j=b.lines[x-1]?b.lines[x-1][0]:null;j==="+"?f=!0:j==="-"&&(h=!0)}}}if(f)for(;!s[s.length-1];)s.pop(),r.pop();else h&&(s.push(""),r.push(`
250
- `));for(var V=0;V<s.length-1;V++)s[V]=s[V]+r[V];return s.join("")}function Oy(n,e,t,s,r,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=xy(t,s,o);if(!a)return;a.push({value:"",lines:[]});function l(_){return _.map(function(k){return" "+k})}for(var c=[],d=0,f=0,h=[],m=1,p=1,y=function(k){var A=a[k],g=A.lines||A.value.replace(/\n$/,"").split(`
251
- `);if(A.lines=g,A.added||A.removed){var v;if(!d){var b=a[k-1];d=m,f=p,b&&(h=o.context>0?l(b.lines.slice(-o.context)):[],d-=h.length,f-=h.length)}(v=h).push.apply(v,Oi(g.map(function(V){return(A.added?"+":"-")+V}))),A.added?p+=g.length:m+=g.length}else{if(d)if(g.length<=o.context*2&&k<a.length-2){var w;(w=h).push.apply(w,Oi(l(g)))}else{var x,T=Math.min(g.length,o.context);(x=h).push.apply(x,Oi(l(g.slice(0,T))));var P={oldStart:d,oldLines:m-d+T,newStart:f,newLines:p-f+T,lines:h};if(k>=a.length-2&&g.length<=o.context){var $=/\n$/.test(t),F=/\n$/.test(s),j=g.length==0&&h.length>P.oldLines;!$&&j&&t.length>0&&h.splice(P.oldLines,0,"\"),(!$&&!j||!F)&&h.push("\")}c.push(P),d=0,f=0,h=[]}m+=g.length,p+=g.length}},S=0;S<a.length;S++)y(S);return{oldFileName:n,newFileName:e,oldHeader:r,newHeader:i,hunks:c}}function au(n){if(Array.isArray(n))return n.map(au).join(`
252
- `);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(`
135
+ `.trim()}var al=M(()=>{"use strict"});async function ul(n,e){return`Directory: ${n}
136
+ Structure: ${ll.readdirSync(n).slice(0,10).join(", ")}`}function dl(n,e,t,r){return`${n}
137
+
138
+ ## Context
139
+ ${e}
140
+
141
+ ${ol()}`}async function fl(n,e,t,r,s,i,o,a,l,c,u,d,p,h,f,g,y){let w=n.split(" ")[0];switch(w){case"/quit":return"quit";case"/help":console.log(il());break;case"/about":console.log(el());break;case"/version":console.log(tl());break;case"/status":console.log(sl({model:t.getModel(),host:"local",directory:o,cacheFiles:0,cacheTokens:0,budgetTokens:1e5,connected:!0,turnCount:l}));break;case"/team":console.log(`
142
+ `+Ga());break;default:console.log(rl(`Unknown command: ${w}`))}}var ll,cl,pl=M(()=>{"use strict";ll=C(require("fs"));en();Ot();al();cl="You are Hablas, INTJ Team Leader. Be cold, logical, and engineering-focused. Use tools for all file ops."});var hl={};Ae(hl,{DEFAULT_CONFIG:()=>tn,NVIDIA_PROVIDER:()=>xs});var tn,xs,Mn=M(()=>{"use strict";tn={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:""}},xs={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 In,ml=M(()=>{"use strict";In=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(r=>r.name):[]}catch{return[]}}async chatWithTools(e,t,r){let s={model:this.model,messages:e,stream:!1};t.length>0&&(s.tools=t);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)};r&&(i.signal=r);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 r=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(!r.ok)throw new Error(`Ollama error: ${r.status} ${r.statusText}`);let s=r.body?.getReader();if(!s)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await s.read();if(a)break;o+=i.decode(l,{stream:!0});let c=o.split(`
143
+ `);o=c.pop()||"";for(let u of c)if(u.trim())try{let d=JSON.parse(u);d.message?.content&&(yield d.message.content)}catch{}}}}});function bl(n){return n.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let t=e.tool_calls.filter(r=>r?.function?.name);if(t.length>0)return{role:"assistant",content:e.content||null,tool_calls:t.map((r,s)=>({id:`call_${s}`,type:"function",function:{name:r.function?.name||"",arguments:JSON.stringify(r.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function Zm(n){return n.map(e=>({type:"function",function:e.function}))}function eg(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 wl(n){return new Promise(e=>setTimeout(e,n))}function vl(n,e){return!(n.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var gl,Xm,Ln,yl,Qm,nn,xl=M(()=>{"use strict";gl=12e4,Xm=6e4,Ln=3,yl=1e3,Qm=20;nn=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,r,s=0;for(;t&&s<Qm;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;r&&o.set("after",r),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let l=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(Xm)});if(!l.ok)break;let c=await l.json();if(Array.isArray(c))e.push(...c.map(u=>u.id||u.name||u).filter(Boolean)),t=!1;else if(c.data&&Array.isArray(c.data)){let u=c.data.map(d=>d.id||d.name).filter(Boolean);e.push(...u),c.has_more&&u.length>0?(r=u[u.length-1],s++):t=!1}else c.models&&Array.isArray(c.models)&&e.push(...c.models.map(u=>u.name||u.id).filter(Boolean)),t=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,t,r){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:bl(e)};t.length>0&&(i.tools=Zm(t),i.tool_choice="auto");let o=null;for(let a=0;a<=Ln;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),gl),u={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:r||l.signal};try{let d=await fetch(s,u);if(clearTimeout(c),!d.ok){let g=await d.text().catch(()=>"");if(!vl(null,d.status))throw new Error(`API error: ${d.status} ${d.statusText} \u2014 ${g}`);if(o=new Error(`API error: ${d.status} ${d.statusText} \u2014 ${g}`),a<Ln){let y=yl*Math.pow(2,a);await wl(y);continue}throw o}let h=(await d.json()).choices?.[0];if(!h)throw new Error("API returned empty response");let f=h.message.tool_calls?eg(h.message.tool_calls):void 0;return{message:{role:h.message.role||"assistant",content:h.message.content||"",tool_calls:f},done:!0,done_reason:h.finish_reason}}catch(d){if(clearTimeout(c),d.name==="AbortError"&&r?.aborted)throw d;if(vl(d)&&(o=d,a<Ln)){let p=yl*Math.pow(2,a);await wl(p);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Ln)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,t){let r=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:bl(e),stream:!0}),signal:t||AbortSignal.timeout(gl)});if(!s.ok)throw new Error(`API error: ${s.status} ${s.statusText}`);let i=s.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:c}=await i.read();if(l)break;a+=o.decode(c,{stream:!0});let u=a.split(`
144
+ `);a=u.pop()||"";for(let d of u){let p=d.trim();if(!(!p||p==="data: [DONE]")&&p.startsWith("data: "))try{let f=JSON.parse(p.slice(6)).choices?.[0]?.delta?.content;f&&(yield f)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}}});function Pt(n){if(n.provider==="nvidia"){let e={...n,provider:"custom",apiUrl:xs.apiUrl};return new nn(e)}return n.provider==="custom"&&n.apiUrl?new nn(n):new In(n)}var Dn=M(()=>{"use strict";Mn();ml();xl()});function Qe(){}function tg(n,e,t,r,s){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,c=0,u=0;a<l;a++){var d=i[a];if(d.removed){if(d.value=n.join(r.slice(u,u+d.count)),u+=d.count,a&&i[a-1].added){var h=i[a-1];i[a-1]=i[a],i[a]=h}}else{if(!d.added&&s){var p=t.slice(c,c+d.count);p=p.map(function(g,y){var w=r[u+y];return w.length>g.length?w:g}),d.value=n.join(p)}else d.value=n.join(t.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}var f=i[l-1];return l>1&&typeof f.value=="string"&&(f.added||f.removed)&&n.equals("",f.value)&&(i[l-2].value+=f.value,i.pop()),i}function ng(n,e,t){return $s.diff(n,e,t)}function Fn(n){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Fn=function(e){return typeof e}:Fn=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Fn(n)}function _s(n){return ig(n)||og(n)||ag(n)||lg()}function ig(n){if(Array.isArray(n))return Ss(n)}function og(n){if(typeof Symbol<"u"&&Symbol.iterator in Object(n))return Array.from(n)}function ag(n,e){if(n){if(typeof n=="string")return Ss(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 Ss(n,e)}}function Ss(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,r=new Array(e);t<e;t++)r[t]=n[t];return r}function lg(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
145
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function As(n,e,t,r,s){e=e||[],t=t||[],r&&(n=r(s,n));var i;for(i=0;i<e.length;i+=1)if(e[i]===n)return t[i];var o;if(cg.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]=As(n[i],e,t,r,s);return e.pop(),t.pop(),o}if(n&&n.toJSON&&(n=n.toJSON()),Fn(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]=As(n[l],e,t,r,l);e.pop(),t.pop()}else o=n;return o}function ug(n,e,t,r,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=ng(t,r,o);if(!a)return;a.push({value:"",lines:[]});function l(w){return w.map(function(v){return" "+v})}for(var c=[],u=0,d=0,p=[],h=1,f=1,g=function(v){var S=a[v],k=S.lines||S.value.replace(/\n$/,"").split(`
146
+ `);if(S.lines=k,S.added||S.removed){var P;if(!u){var j=a[v-1];u=h,d=f,j&&(p=o.context>0?l(j.lines.slice(-o.context)):[],u-=p.length,d-=p.length)}(P=p).push.apply(P,_s(k.map(function(W){return(S.added?"+":"-")+W}))),S.added?f+=k.length:h+=k.length}else{if(u)if(k.length<=o.context*2&&v<a.length-2){var I;(I=p).push.apply(I,_s(l(k)))}else{var $,E=Math.min(k.length,o.context);($=p).push.apply($,_s(l(k.slice(0,E))));var N={oldStart:u,oldLines:h-u+E,newStart:d,newLines:f-d+E,lines:p};if(v>=a.length-2&&k.length<=o.context){var x=/\n$/.test(t),H=/\n$/.test(r),D=k.length==0&&p.length>N.oldLines;!x&&D&&t.length>0&&p.splice(N.oldLines,0,"\"),(!x&&!D||!H)&&p.push("\")}c.push(N),u=0,d=0,p=[]}h+=k.length,f+=k.length}},y=0;y<a.length;y++)g(y);return{oldFileName:n,newFileName:e,oldHeader:s,newHeader:i,hunks:c}}function kl(n){if(Array.isArray(n))return n.map(kl).join(`
147
+ `);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 r=n.hunks[t];r.oldLines===0&&(r.oldStart-=1),r.newLines===0&&(r.newStart-=1),e.push("@@ -"+r.oldStart+","+r.oldLines+" +"+r.newStart+","+r.newLines+" @@"),e.push.apply(e,r.lines)}return e.join(`
253
148
  `)+`
254
- `}function Py(n,e,t,s,r,i,o){return au(Oy(n,e,t,s,r,i,o))}function lu(n,e,t,s,r,i){return Py(n,n,e,t,s,r,i)}var F0,su,ru,iu,Li,Sy,_y,Ty,Tn,Mi,cu=N(()=>{mt.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(g){return i?(setTimeout(function(){i(void 0,g)},0),!0):g}e=this.castInput(e),t=this.castInput(t),e=this.removeEmpty(this.tokenize(e)),t=this.removeEmpty(this.tokenize(t));var l=t.length,c=e.length,d=1,f=l+c;r.maxEditLength&&(f=Math.min(f,r.maxEditLength));var h=(s=r.timeout)!==null&&s!==void 0?s:1/0,m=Date.now()+h,p=[{oldPos:-1,lastComponent:void 0}],y=this.extractCommon(p[0],t,e,0);if(p[0].oldPos+1>=c&&y+1>=l)return a([{value:this.join(t),count:t.length}]);var S=-1/0,_=1/0;function k(){for(var g=Math.max(S,-d);g<=Math.min(_,d);g+=2){var v=void 0,b=p[g-1],w=p[g+1];b&&(p[g-1]=void 0);var x=!1;if(w){var T=w.oldPos-g;x=w&&0<=T&&T<l}var P=b&&b.oldPos+1<c;if(!x&&!P){p[g]=void 0;continue}if(!P||x&&b.oldPos+1<w.oldPos?v=o.addToPath(w,!0,void 0,0):v=o.addToPath(b,void 0,!0,1),y=o.extractCommon(v,t,e,g),v.oldPos+1>=c&&y+1>=l)return a(wy(o,v.lastComponent,t,e,o.useLongestToken));p[g]=v,v.oldPos+1>=c&&(_=Math.min(_,g-1)),y+1>=l&&(S=Math.max(S,g+1))}d++}if(i)(function g(){setTimeout(function(){if(d>f||Date.now()>m)return i();k()||g()},0)})();else for(;d<=f&&Date.now()<=m;){var A=k();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,c=0;l+1<i&&a+1<o&&this.equals(t[l+1],s[a+1]);)l++,a++,c++;return c&&(e.lastComponent={count:c,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("")}};F0=new mt,su=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,ru=/\S/,iu=new mt;iu.equals=function(n,e){return this.options.ignoreCase&&(n=n.toLowerCase(),e=e.toLowerCase()),n===e||this.options.ignoreWhitespace&&!ru.test(n)&&!ru.test(e)};iu.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]&&su.test(e[t])&&su.test(e[t+2])&&(e[t]+=e[t+2],e.splice(t+1,2),t--);return e};Li=new mt;Li.tokenize=function(n){this.options.stripTrailingCr&&(n=n.replace(/\r\n/g,`
255
- `));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};Sy=new mt;Sy.tokenize=function(n){return n.split(/(\S.+?[.!?])(?=\s+|$)/)};_y=new mt;_y.tokenize=function(n){return n.split(/([{}:;,]|\s+)/)};Ty=Object.prototype.toString,Tn=new mt;Tn.useLongestToken=!0;Tn.tokenize=Li.tokenize;Tn.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(Ii(n,null,null,r),r," ")};Tn.equals=function(n,e){return mt.prototype.equals.call(Tn,n.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};Mi=new mt;Mi.tokenize=function(n){return n.slice()};Mi.join=Mi.removeEmpty=function(n){return n}});var uu={};Re(uu,{applyDiff:()=>Iy,formatDiffForDisplay:()=>My,generateDiff:()=>_s});function _s(n,e,t){return lu(n,e,t,"original","modified")}function Iy(n,e){return ou(n,e)}function My(n){return n.split(`
256
- `).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(`
257
- `)}var Di=N(()=>{"use strict";cu()});async function Cn(n,e){let t=[],s=be.join(n,"package.json");if(le.existsSync(s))try{let o=JSON.parse(le.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=gs(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 Si(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=>le.existsSync(be.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=>le.existsSync(be.join(n,o)));if(i.length>0&&t.push(`Config: ${i.join(", ")}`),e?.context?.projectGraph)try{let o=le.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=le.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(`
258
- `)}function Rn(n,e,t,s){let r=n+`
259
-
260
- ## Current Project
261
- `+e;if(t){let i=t.getSummary();i&&(r+=`
262
-
263
- `+i)}if(s){let i=s.getSummary();i&&(r+=`
264
-
265
- ## Shared Context
266
- `+i)}return r+=`
267
-
268
- `+Rc(),r}async function Ly(n){try{if(!le.existsSync(Ni))return null;let t=(await $t.readdir(Ni)).filter(f=>f.endsWith(".bak"));if(n){let f=be.basename(n);t=t.filter(h=>h.startsWith(`${f}.`))}if(t.length===0)return null;t.sort().reverse();let s=t[0],r=be.join(Ni,s),i=s.replace(".bak","").split("."),o=parseInt(i[i.length-1],10),a=i.slice(0,-1).join("."),l=Date.now()-o,c=Math.floor(l/6e4),d=c<1?"just now":c<60?`${c} minutes ago`:`${Math.floor(c/60)} hours ago`;return{backupPath:r,originalName:a,age:d}}catch{return null}}async function du(n,e,t,s,r,i,o,a,l,c,d,f,h,m,p,y,S){let _=n.split(/\s+/),k=_[0],A=_.slice(1).join(" ");switch(k){case"/quit":case"/exit":return"quit";case"/help":console.log(Uc()),console.log(u.muted(" Model & Provider:")),console.log(u.muted(" /addmodel Interactive wizard to add a custom API")),console.log(u.muted(" /listmodels Show saved providers")),console.log(u.muted(" /removemodel <name> Remove a saved provider")),console.log(u.muted(" /usemodel <name> Switch to a saved provider")),console.log(u.muted(" /models [page|search] Browse all available models")),console.log(u.muted(" /provider Show/switch API provider")),console.log(),console.log(u.muted(" Aliases & Plugins:")),console.log(u.muted(" /alias Show all aliases")),console.log(u.muted(" /alias set <n> <cmd> Create an alias")),console.log(u.muted(" /alias del <name> Remove an alias")),console.log(u.muted(" /plugins List installed plugins")),console.log(u.muted(" /doctor Run system diagnostics")),console.log(),console.log(u.muted(" Task & Memory:")),console.log(u.muted(" /task add <desc> Add a task to the queue")),console.log(u.muted(" /task list Show all tasks")),console.log(u.muted(" /task clear Clear task queue")),console.log(u.muted(" /memory Show project memory")),console.log(u.muted(" /memory set <k> <v> Store a memory")),console.log(u.muted(" /memory del <key> Delete a memory")),console.log(u.muted(" /memory clear Clear all memory")),console.log(),console.log(u.muted(" Multi-Agent & Tools:")),console.log(u.muted(" /team Show team roster")),console.log(u.muted(" /delegate <agent> <t> Manually assign task to agent")),console.log(u.muted(" /agents Multi-agent system control")),console.log(u.muted(" /agents on|off Enable/disable multi-agent")),console.log(u.muted(" /agents status Show agent details")),console.log(u.muted(" /security Run security scan")),console.log(u.muted(" /git status Show git status")),console.log(u.muted(" /workspace Show workspace info")),console.log(u.muted(" /stats Show usage analytics")),console.log();break;case"/about":console.log(Fc());break;case"/version":console.log(Hc());break;case"/model":if(A){let g=await t.listModels();t.setModel(A),g.includes(A)?console.log(Y(`Model: ${A}`)):console.log(U(`Model set to "${A}" (not found locally)`))}else console.log(ye(`Current model: ${t.getModel()}`)),console.log(u.muted(" Usage: /model <name>"));break;case"/models":{let g=A.trim(),v=1,b="";if(g){let E=parseInt(g);!isNaN(E)&&E>0?v=E:b=g.toLowerCase()}let w=new kt("Fetching models");w.start();let x=await t.listModels();if(w.stop(x.length>0?`${x.length} found`:void 0),x.length===0){console.log(U("No models found \u2014 check your connection")),console.log(u.muted(" Use /provider test to verify"));break}let T=x;if(b&&(T=x.filter(E=>E.toLowerCase().includes(b)),T.length===0)){console.log(U(`No models matching: "${b}"`)),console.log(u.muted(` ${x.length} models available. Try a different search.`));break}let P=20,$=Math.ceil(T.length/P),F=Math.max(1,Math.min(v,$)),j=(F-1)*P,V=j+P,C=T.slice(j,V);console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Available Models")} ${u.muted(`(${T.length} total \xB7 page ${F}/${$})`)}`),console.log();for(let E=0;E<C.length;E++){let J=j+E+1,Q=C[E]===t.getModel()?` ${u.success("\u25CF active")}`:"";console.log(` ${u.muted(String(J).padStart(3," "))}. ${u.secondary(C[E])}${Q}`)}console.log(),$>1&&console.log(u.muted(` /models ${F<$?F+1:1} \u2014 next page`)),b&&console.log(u.muted(` Filtered: ${T.length} of ${x.length} (query: "${b}")`)),console.log(u.muted(" /models <query> \u2014 search \xB7 /model <id> \u2014 switch")),console.log();break}case"/tree":{let g=s.get("list_dir");if(g){let v=await g.execute({path:".",depth:3});console.log(`
269
- ${v.output}
270
- `)}break}case"/status":{let g=await t.checkConnection(),v=c?c.getActiveName():"planner",b=f?f.size():0,w=d?d.getProgress():void 0;console.log(Bc({model:t.getModel(),host:e.ollamaHost,directory:o,cacheFiles:r.getCacheSize(),cacheTokens:r.getTotalTokens(),budgetTokens:e.contextBudget,connected:g,turnCount:l,mindset:v})),b>0&&console.log(u.muted(` Memory entries: ${b}`)),w&&w.total>0&&console.log(u.muted(` Tasks: ${w.done}/${w.total} done`)),console.log();break}case"/clear":r.clear(),i.clear(),console.log(Y("History cleared"));break;case"/history":{let g=parseInt(A)||10,v=i.getHistory().slice(-g);if(v.length===0){console.log(ye("No history yet"));break}console.log(),v.forEach(b=>{let w=b.role==="user"?u.primary("You"):b.role==="assistant"?u.success("Hablas"):u.muted("tool"),x=b.content.slice(0,120).replace(/\n/g," ");console.log(` ${w}: ${u.muted(x)}`)}),console.log();break}case"/undo":{if(!y){let g=await Ly(A||void 0);if(!g){console.log(U("No backups found"));break}let v=A?be.resolve(o,A):be.resolve(o,g.originalName);if(await a.confirm(`Restore ${g.originalName} from backup (${g.age})?`))try{let w=await $t.readFile(g.backupPath,"utf-8");await $t.writeFile(v,w,"utf-8"),console.log(Y(`Restored ${g.originalName} from backup (${g.age})`))}catch(w){console.log(ke(`Failed: ${w.message}`))}break}if(A==="list")console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Undo History")} (${y.getUndoableCount()} changes)`),console.log(),console.log(y.formatList(20)),console.log();else if(A==="all"){let g=y.getUndoableCount();if(g===0){console.log(ye("Nothing to undo"));break}if(await a.confirm(`Undo ALL ${g} changes?`)){let b=await y.undoAll(),w=b.filter(x=>x.success).length;console.log(Y(`Reverted ${w}/${b.length} changes`))}}else{let g=A&&parseInt(A)||1;if(y.getUndoableCount()===0){console.log(ye("Nothing to undo"));break}let v=await y.undo(g);for(let b of v)b.success?console.log(Y(`Reverted: ${b.file}`)):console.log(ke(`Failed to revert ${b.file}: ${b.error}`))}break}case"/config":console.log(`
271
- ${u.muted(JSON.stringify(e,null,2))}
272
- `),console.log(u.muted(" ~/.hablas/config.json")),console.log();break;case"/mindset":{if(!c){console.log(U("Mindset system not available"));break}if(A)if(c.setActive(A)){let v=c.getActive(),b=await Cn(o,e),w=Rn(v.systemPrompt,b,f,m);i.updateSystemPrompt(w),console.log(Y(`Mindset: ${v.name} \u2014 ${v.description}`))}else{let v=c.listNames().join(", ");console.log(vs(`Unknown mindset: "${A}"`,`Available: ${v}`))}else{let g=c.getActive();g&&console.log(ye(`Current mindset: ${g.name} \u2014 ${g.description}`)),console.log(u.muted(" Usage: /mindset <name>")),console.log(u.muted(" See /mindsets for available options"))}break}case"/mindsets":{if(!c){console.log(U("Mindset system not available"));break}let g=c.list(),v=c.getActiveName();console.log();for(let b of g){let x=b.name===v?u.success(" \u25CF active"):"";console.log(` ${u.accent("\u25C6")} ${u.primary(b.name)}${x}`),console.log(` ${u.muted(b.description)}`)}console.log(),console.log(u.muted(" Switch: /mindset <name>")),console.log();break}case"/task":{if(!d){console.log(U("Task queue not available"));break}let g=_[1],v=_.slice(2).join(" ");switch(g){case"add":if(v){let b=d.add(v);console.log(Y(`Task #${b.id} added: ${v}`))}else console.log(U("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(Y(`Task #${b} marked as done`))):console.log(U("Usage: /task done <id>"));break}case"fail":{let b=parseInt(v);b?(d.fail(b,"Manually marked as failed"),console.log(U(`Task #${b} marked as failed`))):console.log(U("Usage: /task fail <id>"));break}case"clear":d.clear(),console.log(Y("Task queue cleared"));break;default:console.log(),console.log(d.render()),console.log(),console.log(u.muted(" /task add <desc> \u2014 Add a task")),console.log(u.muted(" /task list \u2014 Show all tasks")),console.log(u.muted(" /task done <id> \u2014 Mark task as done")),console.log(u.muted(" /task fail <id> \u2014 Mark task as failed")),console.log(u.muted(" /task clear \u2014 Clear all tasks")),console.log()}break}case"/addmodel":{console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Add Custom API Provider")}`),console.log();let v=(await a.prompt(` ${u.muted("Provider name (e.g. OpenAI, Groq):")} `)).trim();if(!v){console.log(U("Cancelled \u2014 name is required"));break}let w=(await a.prompt(` ${u.muted("API URL (e.g. https://api.openai.com/v1):")} `)).trim();if(!w){console.log(U("Cancelled \u2014 URL is required"));break}let T=(await a.prompt(` ${u.muted("API Key (leave empty if none):")} `)).trim(),$=(await a.prompt(` ${u.muted("Default model ID (e.g. gpt-4o):")} `)).trim()||"default",F={name:v,apiUrl:w,apiKey:T,models:[$],defaultModel:$,addedAt:new Date().toISOString()};Ge(F),console.log(),console.log(Y(`Provider "${v}" saved!`)),console.log(u.muted(` Use: /usemodel ${v}`)),console.log();break}case"/listmodels":{let g=Lt();console.log(),console.log(Zl(g.providers,g.activeProvider));break}case"/removemodel":{let g=A.trim();if(!g){console.log(U("Usage: /removemodel <provider-name>"));break}if(Jl(g))console.log(Y(`Provider "${g}" removed`));else{console.log(U(`Provider "${g}" not found`));let b=os();b.length>0&&console.log(u.muted(` Available: ${b.map(w=>w.name).join(", ")}`))}break}case"/usemodel":{let g=A.trim();if(!g){console.log(U("Usage: /usemodel <provider-name> [model-id]"));let F=os();F.length>0&&console.log(u.muted(` Available: ${F.map(j=>j.name).join(", ")}`));break}let v=g.split(/\s+/),b=v[0],w=v[1],x=Ql(b);if(!x){console.log(U(`Provider "${b}" not found`));let F=os();F.length>0&&console.log(u.muted(` Available: ${F.map(j=>j.name).join(", ")}`));break}e.provider="custom",e.apiUrl=x.apiUrl,e.apiKey=x.apiKey,e.model=w||x.defaultModel;let T=We(e);h&&h(T),Xl(x.name,e.model),console.log(Y(`Switched to ${x.name} \xB7 Model: ${e.model}`));let P=new kt("Testing");P.start();let $=await T.checkConnection();P.stop($?"connected":void 0),$||console.log(U("Connection test failed \u2014 check URL and key"));break}case"/provider":{let g=_[1],v=_.slice(2).join(" ");if(!g){let b=Vl(e);console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Provider")}: ${b}`),console.log(` ${u.muted("Model")}: ${u.highlight(t.getModel())}`),e.provider==="custom"?(console.log(` ${u.muted("API URL")}: ${e.apiUrl}`),console.log(` ${u.muted("API Key")}: ${e.apiKey?"***"+e.apiKey.slice(-4):"not set"}`)):console.log(` ${u.muted("Host")}: ${e.ollamaHost}`),console.log(),console.log(u.muted(" /provider ollama \u2014 Switch to local Ollama")),console.log(u.muted(" /provider nvidia <key> \u2014 Switch to NVIDIA NIM")),console.log(u.muted(" /provider custom <url> [key] \u2014 Switch to custom API")),console.log(u.muted(" /provider test \u2014 Test current connection")),console.log();break}switch(g){case"ollama":{e.provider="ollama",e.apiUrl="",e.apiKey="";let b=We(e);h&&h(b),console.log(Y("Switched to Ollama (local)"));break}case"nvidia":{let b=_[2];if(!b&&!e.apiKey){console.log(U("Usage: /provider nvidia <api-key>")),console.log(u.muted(" Get your key at: https://build.nvidia.com/"));break}e.provider="nvidia",e.apiUrl=At.apiUrl,b&&(e.apiKey=b),(!e.model||!At.models.includes(e.model))&&(e.model=At.defaultModel);let w=We(e);h&&h(w),console.log(Y(`Switched to NVIDIA NIM \xB7 Model: ${e.model}`)),console.log(u.muted(` Available models: ${At.models.length}`));let x=new kt("Testing NVIDIA connection");x.start();let T=await w.checkConnection();x.stop(T?"connected":void 0),T||(console.log(U("Connection test failed \u2014 check your API key")),console.log(u.muted(" Get key: https://build.nvidia.com/")));break}case"custom":{let b=_[2],w=_[3];if(!b){console.log(U("Usage: /provider custom <api-url> [api-key]")),console.log(u.muted(" Example: /provider custom https://api.openai.com/v1 sk-..."));break}e.provider="custom",e.apiUrl=b,w&&(e.apiKey=w);let x=We(e);h&&h(x),console.log(Y(`Switched to Custom API: ${b}`)),!w&&!e.apiKey&&console.log(U("No API key set. Use: /provider custom <url> <key>"));break}case"test":{let b=new kt("Testing connection");b.start();let w=await t.checkConnection();if(b.stop(w?"connected":void 0),w){let x=await t.listModels();console.log(Y(`Connected! ${x.length} models available.`)),x.length>0&&console.log(u.muted(` Models: ${x.slice(0,5).join(", ")}${x.length>5?"...":""}`))}else console.log(ke("Connection failed"));break}case"key":{v?(e.apiKey=_[2],t instanceof Mt&&t.setApiKey(e.apiKey),console.log(Y("API key updated"))):console.log(U("Usage: /provider key <api-key>"));break}default:console.log(vs(`Unknown: /provider ${g}`,"Type /provider for help"))}break}case"/memory":{if(!f){console.log(U("Project memory not available"));break}let g=_[1],v=_.slice(2);switch(g){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");f.set(b,w),console.log(Y(`Memory stored: ${b}`));let x=c?.getActive(),T=x?x.systemPrompt:As,P=await Cn(o,e);i.updateSystemPrompt(Rn(T,P,f,m))}else console.log(U("Usage: /memory set <key> <value>"));break}case"del":case"delete":{if(v[0]){let b=f.delete(v[0]);console.log(b?Y(`Memory deleted: ${v[0]}`):U(`Memory key not found: ${v[0]}`))}else console.log(U("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(ye("No matching memories found"))}else console.log(U("Usage: /memory search <query>"));break}case"clear":f.clear(),console.log(Y("Project memory cleared"));break;default:console.log(),console.log(f.render()),console.log(),console.log(u.muted(" /memory set <k> <v> \u2014 Store a memory")),console.log(u.muted(" /memory del <key> \u2014 Delete a memory")),console.log(u.muted(" /memory search <q> \u2014 Search memories")),console.log(u.muted(" /memory clear \u2014 Clear all")),console.log()}break}case"/alias":{let g=_[1],v=_.slice(2);switch(g){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");nc(b,w),console.log(Y(`Alias set: ${b} \u2192 ${w}`))}else console.log(U("Usage: /alias set <name> <expansion>"));break}case"del":case"remove":{if(v[0]){let b=sc(v[0]);console.log(b?Y(`Alias removed: ${v[0]}`):U(`Alias not found: ${v[0]}`))}else console.log(U("Usage: /alias del <name>"));break}default:console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Aliases")}`),console.log(),console.log(ic()),console.log(),console.log(u.muted(" /alias set <name> <cmd> \u2014 Create alias")),console.log(u.muted(" /alias del <name> \u2014 Remove alias")),console.log()}break}case"/doctor":{let g=new kt("Running diagnostics");g.start();let v=await oi({ollamaHost:e.ollamaHost,model:t.getModel(),provider:e.provider,apiUrl:e.apiUrl});g.stop(),console.log(ai(v));break}case"/plugins":{let g=_[1],v=_.slice(2).join(" ");switch(g){case"enable":v?(ti(v),console.log(Y(`Plugin "${v}" enabled`))):console.log(U("Usage: /plugins enable <name>"));break;case"disable":v?(ni(v),console.log(U(`Plugin "${v}" disabled`))):console.log(U("Usage: /plugins disable <name>"));break;default:fs(),console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Plugins")}`),console.log(),console.log(si()),console.log(),console.log(u.muted(" /plugins enable <name> \u2014 Enable plugin")),console.log(u.muted(" /plugins disable <name> \u2014 Disable plugin")),console.log(u.muted(" Directory: ~/.hablas/plugins/")),console.log()}break}case"/agents":{let g=_[1];if(g==="on")e.agents.enabled=!0,console.log(Y("Multi-agent orchestration enabled"));else if(g==="off")e.agents.enabled=!1,console.log(Y("Multi-agent orchestration disabled"));else if(g==="status")console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Multi-Agent System")}`),console.log(` Status: ${e.agents.enabled?u.success("enabled"):u.muted("disabled")}`),console.log(` Orchestration: ${e.agents.orchestration}`),console.log(` Max concurrent: ${e.agents.maxConcurrent}`),console.log(),console.log(` ${u.strong("Team:")}`),console.log(mc()),console.log();else if(g==="models"){let v=_n();console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Agent Models")}`),console.log();for(let b of he){let w=v[b.role];console.log(w?` ${u.primary(b.name.padEnd(8))} \u2192 ${u.highlight(w.model)}${w.temperature!==void 0?u.muted(` (temp: ${w.temperature})`):""}`:` ${u.primary(b.name.padEnd(8))} \u2192 ${u.muted("(default)")}`)}console.log(),console.log(u.muted(` Config: ${bc()}`)),console.log(u.muted(" Edit the file to change models per agent.")),console.log()}else console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Multi-Agent System")}: ${e.agents.enabled?u.success("ON"):u.muted("OFF")}`),console.log(),console.log(u.muted(" /agents on \u2014 Enable multi-agent orchestration")),console.log(u.muted(" /agents off \u2014 Disable multi-agent orchestration")),console.log(u.muted(" /agents status \u2014 Show agent details")),console.log(u.muted(" /agents models \u2014 Show model per agent")),console.log(u.muted(" /team \u2014 Show team roster")),console.log();break}case"/security":{console.log(),console.log(` ${u.accent("\u{1F512}")} Running security scan...`);let g=vi(o);console.log(wi(g));break}case"/git":{if(_[1]==="status")try{let{getGitStatus:v,formatGitStatus:b}=await Promise.resolve().then(()=>(Xt(),kn)),w=await v(o);w?(console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Git Status")}`),console.log(b(w)),console.log()):console.log(U("Not a git repository"))}catch{console.log(U("Git not available"))}else console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Git Intelligence")}`),console.log(),console.log(u.muted(" /git status \u2014 Show git status")),console.log(u.muted(" hablas commit \u2014 Smart commit message")),console.log(u.muted(" hablas pr \u2014 Generate PR description")),console.log(u.muted(" hablas changelog \u2014 Generate changelog")),console.log();break}case"/workspace":{let g=gs(o);console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Workspace Information")}`),console.log(),console.log(_i(g)),console.log();break}case"/stats":{let{loadStats:g,formatStats:v}=await Promise.resolve().then(()=>(An(),bi)),b=g();console.log(v(b));break}case"/context":{if(!m){console.log(U("Shared context not available"));break}let g=_[1],v=_.slice(2);switch(g){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");m.set(b,w),console.log(Y(`Context stored: ${b}`))}else console.log(U("Usage: /context set <key> <value>"));break}case"get":{if(v[0]){let b=m.get(v[0]);b!==void 0?(console.log(),console.log(` ${u.accent("\u25C6")} ${u.strong(v[0])}: ${b}`),console.log()):console.log(U(`Context key not found: ${v[0]}`))}else console.log(U("Usage: /context get <key>"));break}case"del":case"delete":{if(v[0]){let b=m.delete(v[0]);console.log(b?Y(`Context deleted: ${v[0]}`):U(`Context key not found: ${v[0]}`))}else console.log(U("Usage: /context del <key>"));break}case"decisions":{let b=m.getDecisions();if(b.length===0)console.log(ye("No decisions logged yet"));else{console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Decisions")}`),console.log();for(let w of b)console.log(` ${u.muted(w.timestamp)} ${u.primary(w.by)}: ${w.decision}`),w.rationale&&console.log(` ${u.muted(w.rationale)}`);console.log()}break}case"clear":m.clear(),console.log(Y("Shared context cleared"));break;default:console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Shared Context")}`),console.log(),console.log(m.render()),console.log(),console.log(u.muted(" /context set <k> <v> \u2014 Store a context entry")),console.log(u.muted(" /context get <key> \u2014 Get a context entry")),console.log(u.muted(" /context del <key> \u2014 Delete a context entry")),console.log(u.muted(" /context decisions \u2014 Show logged decisions")),console.log(u.muted(" /context clear \u2014 Clear all context")),console.log()}break}case"/plan":{if(!p){console.log(U("Plan manager not available"));break}let g=_[1],v=_.slice(2).join(" ");switch(g){case"status":{let w=p.getActivePlan();if(!w){console.log(ye("No active plan"));break}let x=p.getProgress();console.log(Kc(w,{percent:x.percentage,done:x.done,total:x.total}));break}case"finish":{if(v){p.finishTask(v),console.log(Y(`Task finished: ${v}`));let w=p.getProgress();console.log(u.muted(` Progress: ${w.done}/${w.total} (${w.percentage}%)`))}else console.log(U("Usage: /plan finish <task_id>"));break}case"reset":{p.reset(),console.log(Y("Plan manager reset"));break}case"next":{let w=p.getNextTask();console.log(w?ye(`Next task: [${w.task_id}] ${w.description} \u2192 @${w.assignee}`):ye("No pending tasks"));break}default:console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Plan Manager")}`),console.log();let b=p.getActivePlan();if(b){let w=p.getProgress();console.log(` Active plan: ${b.title} (${w.percentage}% done)`),console.log(` Tasks: ${w.done}/${w.total}`)}else console.log(u.muted(" No active plan"));console.log(),console.log(u.muted(" /plan status \u2014 Show active plan with progress")),console.log(u.muted(" /plan finish <id> \u2014 Mark a task as finished")),console.log(u.muted(" /plan next \u2014 Show next pending task")),console.log(u.muted(" /plan reset \u2014 Reset plan manager")),console.log()}break}case"/learn":{if(!f||!A){console.log(U('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 Cn(o,e),b=c?.getActive(),w=b?b.systemPrompt:As,x=Rn(w,v,f,m);i.updateSystemPrompt(x)}console.log(Y(`Learned: "${A}"`)),console.log(u.muted(" This will be remembered across sessions and injected into every prompt."));break}case"/test":{let g=Ri(o);if(g==="unknown"&&!A){console.log(U("No test framework detected. Install jest, vitest, pytest, etc."));break}console.log(ye(`Running tests (${g})...`));let v=Gc(o,A==="--fix"?void 0:A||void 0);if(console.log(),console.log(Vc(v)),console.log(),!v.passed&&A==="--fix"){console.log(ye("Tests failed \u2014 adding fix request to conversation..."));let b=zc(v);i.addUserMessage(b),console.log(ye("Type your next message or let the agent work on the fix."))}break}case"/checkpoint":{let g=_[1],v=_.slice(2).join(" ");if(g==="save"){let b=v||`Checkpoint at turn ${l}`,w=y?.getModifiedFiles?.()||[],x=await Qc(o,b,w);console.log(Y(`Checkpoint saved: ${x.id} "${b}" (${x.fileCount} files)`))}else if(g==="list"){let b=Xc(o);console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Checkpoints")}`),console.log(),console.log(tu(b)),console.log()}else if(g==="restore"){if(!v){console.log(U("Usage: /checkpoint restore <id>"));break}let b=await Zc(o,v);b.success?console.log(Y(`Restored checkpoint: ${v} (${b.filesRestored} files)`)):console.log(ke(b.error||"Restore failed"))}else g==="delete"?v&&eu(o,v)?console.log(Y(`Deleted checkpoint: ${v}`)):console.log(U("Checkpoint not found")):(console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Checkpoint System")}`),console.log(),console.log(u.muted(' /checkpoint save "label" \u2014 Save current state')),console.log(u.muted(" /checkpoint list \u2014 List saved checkpoints")),console.log(u.muted(" /checkpoint restore <id> \u2014 Restore a checkpoint")),console.log(u.muted(" /checkpoint delete <id> \u2014 Delete a checkpoint")),console.log());break}case"/compare":{let g=_.slice(1);if(g.length===2)try{let v=await $t.readFile(be.resolve(o,g[0]),"utf-8"),b=await $t.readFile(be.resolve(o,g[1]),"utf-8"),{generateDiff:w}=await Promise.resolve().then(()=>(Di(),uu)),x=w(g[0]+" vs "+g[1],v,b);console.log(Ti(x))}catch(v){console.log(ke(`Compare failed: ${v.message}`))}else if(g.length===1&&g[0].startsWith("HEAD"))try{let{execSync:v}=await import("child_process"),b=v(`git diff ${g[0]}`,{cwd:o,encoding:"utf-8",timeout:1e4});console.log(Ti(b||"(no changes)"))}catch(v){console.log(ke(`Git diff failed: ${v.message}`))}else console.log(u.muted(" Usage: /compare file1.ts file2.ts or /compare HEAD~1"));break}case"/cost":{let g=Jt(),v="current";console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Session Cost & Usage")}`),console.log(),console.log(` Session duration: ${v} min`),console.log(` Messages: ${g.totalMessages}`),console.log(` Tool calls: ${g.totalToolCalls}`),console.log(` Tokens used: ${g.totalTokensUsed.toLocaleString()}`),console.log();let b=Object.entries(g.agentUsage);if(b.length>0){console.log(" Agent usage:");for(let[w,x]of b.sort((T,P)=>P[1]-T[1]))console.log(` @${w}: ${x} invocations`)}console.log();break}case"/delegate":{if(!e.agents.enabled){console.log(U("Multi-agent system is disabled. Enable with /agents on"));break}let g=_[1]?.toLowerCase(),v=_.slice(2).join(" ");if(!g||!v){console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Delegate Task to Agent")}`),console.log(),console.log(u.muted(" Usage: /delegate <agent> <task description>")),console.log(),console.log(u.muted(" Agents:")),console.log(` ${u.product("emma")} \u2014 Product Manager`),console.log(` ${u.architect("bob")} \u2014 Architect`),console.log(` ${u.engineer("alex")} \u2014 Engineer`),console.log(` ${u.analyst("david")} \u2014 Data Analyst`),console.log(),console.log(u.muted(" Example: /delegate alex create a login component")),console.log();break}let b=["emma","bob","alex","david","hablas"];if(!b.includes(g)){console.log(U(`Unknown agent: "${g}". Valid: ${b.join(", ")}`));break}let w=he.find(x=>x.role===g);if(w){if(!S){console.log(U("Agent runner not initialized. Cannot delegate."));break}console.log(Nc("Hablas",w.name,w.title,v)),console.log($n(w.name,w.title));let x=s.getOllamaTools(),T=await S.runAgent(g,v,void 0,x);T.success&&T.output?(console.log(En(T.output)),i.addAssistantMessage(`[@${w.name}]: ${T.output}`)):T.error?console.log(U(`${w.name} failed: ${T.error}`)):console.log(ye(`${w.name} completed without output.`))}break}case"/session":{let g=_[1],v=_.slice(2).join(" "),b=be.join(Fi.homedir(),".hablas","sessions");if(g==="save"){let w=v||`session_${Date.now()}`;try{le.existsSync(b)||le.mkdirSync(b,{recursive:!0});let x=i.toJSON(),T=be.join(b,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);le.writeFileSync(T,x,"utf-8"),console.log(Y(`Session saved: "${w}"`))}catch(x){console.log(ke(`Save failed: ${x.message}`))}}else if(g==="list")try{if(!le.existsSync(b)){console.log(ye("No saved sessions"));break}let w=le.readdirSync(b).filter(x=>x.endsWith(".json"));console.log();for(let x of w){let T=le.statSync(be.join(b,x));console.log(` ${x.replace(".json","")} (${new Date(T.mtime).toLocaleString()})`)}console.log()}catch{console.log(ye("No saved sessions"))}else if(g==="load"){let w=v;if(!w){console.log(ke("Please specify the session label to load: /session load <label>"));break}try{let x=be.join(b,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);if(!le.existsSync(x)){console.log(ke(`Session file not found: ${w}`));break}let T=le.readFileSync(x,"utf-8");i.fromJSON(T),console.log(Y(`Session successfully loaded: "${w}"`))}catch(x){console.log(ke(`Load failed: ${x.message}`))}}else console.log(),console.log(u.muted(' /session save "label" \u2014 Save current conversation')),console.log(u.muted(" /session list \u2014 List saved sessions")),console.log(u.muted(' /session load "label" \u2014 Load saved conversation')),console.log();break}case"/team":{let{activeCollabManager:g}=await Promise.resolve().then(()=>(gt(),Et));if(!g){console.log(U("Team mode is not active. Use hablas --team to start."));break}let v=g.getLocalState(),b=Math.min(process.stdout.columns-4,80);console.log(`
273
- `+u.border("\u2554"+"\u2550".repeat(b-2)+"\u2557")),console.log(u.border("\u2551")+" ".repeat(Math.floor((b-22)/2))+u.strong("HABLAS COLLABORATION SYNC")+" ".repeat(b-2-25-Math.floor((b-22)/2))+u.border("\u2551")),console.log(u.border("\u2560"+"\u2550".repeat(b-2)+"\u2563")),console.log(u.border("\u2551")+` ${u.strong("My Identity:")} ${u.highlight(`@${v.my_username}`)}`+" ".repeat(Math.max(1,b-21-(v.my_username?.length||0)))+u.border("\u2551")),console.log(u.border("\u2551")+` ${u.strong("Room Fingerprint:")} ${u.muted(v.project_team_token?.slice(0,12))}...`+" ".repeat(Math.max(1,b-34))+u.border("\u2551")),console.log(u.border("\u2551")+` ${u.strong("Status:")} ${u.success("\u25CF ACTIVE")}`+" ".repeat(Math.max(1,b-31))+u.border("\u2551")),console.log(u.border("\u2560"+"\u2550".repeat(b-2)+"\u2563")),console.log(u.border("\u2551")+` ${u.strong("Teammates Online:")}`+" ".repeat(Math.max(1,b-21))+u.border("\u2551"));let x=(v.sessions||[]).filter(T=>T.developer_name!==v.my_username);if(x.length===0)console.log(u.border("\u2551")+" (awaiting colleagues...)"+" ".repeat(Math.max(1,b-31))+u.border("\u2551"));else for(let T of x){let P=` @${T.developer_name} [${T.active_section||"idle"}] - ${T.current_task||"none"}`;console.log(u.border("\u2551")+` ${u.secondary(P.slice(0,b-6))}`+" ".repeat(Math.max(0,b-6-P.length))+u.border("\u2551"))}console.log(u.border("\u255A"+"\u2550".repeat(b-2)+"\u255D")+`
274
- `),console.log(u.muted(` Verify that "Room Fingerprint" matches on all devices to ensure connectivity.
275
- `));break}case"/msg":{let{activeCollabManager:g}=await Promise.resolve().then(()=>(gt(),Et));if(!g){console.log(U("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(U("Usage: /msg <username> <content>"));break}let x=await g.sendMessage(b,w);console.log(x?Y(`Message sent to @${b}`):ke(`Failed to send message to @${b}`));break}default:console.log(vs(`Unknown: ${k}`,"Type /help for commands"))}}var le,$t,be,Fi,As,Ni,fu=N(()=>{"use strict";le=O(require("fs")),$t=O(require("fs/promises")),be=O(require("path")),Fi=O(require("os"));wn();xn();Gr();Qr();Xr();ri();li();Sn();fi();An();xi();Xt();Ai();Oc();en();Yc();nu();As=`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.
276
-
277
- 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.
278
-
279
- ## Your Persona (INTJ + Engineering Lead)
280
- - **Tone:** Authoritative, direct, concise, cold-yet-highly-professional. You do not waste words on pleasantries.
281
- - **Vocabulary:** Use precise, systemic, and engineering-focused terminology (e.g., "optimal path established", "consensus verified", "dependency resolved", "mitigating structural overhead", "systemic alignment").
282
- - **Style:** Always think structurally. Present plans, results, and recommendations with bulletproof logic.
283
-
284
- ## Your Team
285
- - **Hablas (You)** \u2014 Team Leader & Coordinator. You receive requests, create plans, distribute tasks, and compile synthesized responses.
286
- - **Emma** \u2014 Product Manager. Analyzes requirements, creates PRDs, competitive analysis, market research.
287
- - **Bob** \u2014 Architect. Designs system architecture, schemas, API structures.
288
- - **Alex** \u2014 Engineer. Implements code, fixes bugs, handles deployment.
289
- - **David** \u2014 Data Analyst. Research, documentation, data analysis.
290
-
291
- ## Rules
292
- 1. ALWAYS use tools for file operations. Never claim you did something without calling a tool.
293
- 2. Read a file before editing it if you don't know its content.
294
- 3. One tool call at a time. Wait for the result before calling another.
295
- 4. Be concise and direct. Do not add conversational fluff.
296
- 5. After completing a task, summarize what was achieved with absolute logical clarity.
297
- 6. If a tool fails, analyze the error and retry with corrected arguments.
298
- 7. For multi-step tasks, break them down and execute step by step.
299
- 8. For complex requests, create a numbered plan before executing.
300
-
301
- ## Tool usage
302
- - To read a file: use read_file
303
- - To create/overwrite a file: use write_file
304
- - To make a small change: use edit_file (exact match) or patch_file (line numbers)
305
- - To find & replace all: use search_and_replace
306
- - To append content: use append_to_file
307
- - To run npm/git/node commands: use run_command
308
- - To find something in code: use search_codebase
309
-
310
- ## Important
311
- Never output tool calls as text or JSON in your response.
312
- Always use the tool_calls field provided by the API.
313
- If you cannot complete a task, explain why with absolute technical objectivity.`;Ni=be.join(Fi.homedir(),".hablas","backup")});async function Nt(n){try{if(!Hi.existsSync(n))return;Hi.existsSync(On)||await nt.mkdir(On,{recursive:!0});let e=await nt.readFile(n,"utf-8"),t=tn.basename(n),s=Date.now(),r=`${t}.${s}.bak`,i=tn.join(On,r);await nt.writeFile(i,e,"utf-8");let a=(await nt.readdir(On)).filter(l=>l.startsWith(`${t}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>pu)for(let l of a.slice(pu))await nt.unlink(tn.join(On,l))}catch{}}var nt,Hi,tn,hu,On,pu,mu=N(()=>{"use strict";nt=O(require("fs/promises")),Hi=O(require("fs")),tn=O(require("path")),hu=O(require("os")),On=tn.join(hu.homedir(),".hablas","backup"),pu=10});function bu(n){let e=m=>Tt.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 p=e(m.path),S=(await se.readFile(p,"utf-8")).split(`
314
- `),_=S.length,k=m.start_line?Math.max(1,m.start_line):1,A=m.end_line?Math.min(_,m.end_line):Math.min(_,k+gu-1),g=Math.min(A,k+gu-1),v=S.slice(k-1,g),b=String(g).length,w=v.map((P,$)=>`${String(k+$).padStart(b," ")} | ${P}`),x=`[${m.path} \u2014 lines ${k}-${g} of ${_}]`,T=g<_?`
315
- ... [File has ${_} total lines. Use start_line/end_line to read more.]`:"";return{success:!0,output:`${x}
316
- ${w.join(`
317
- `)}${T}`}}catch(p){return{success:!1,output:"",error:`[read_file]: ${p.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(m.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let p=e(m.path);return ji.existsSync(p)&&await Nt(p),await se.mkdir(Tt.dirname(p),{recursive:!0}),await se.writeFile(p,m.content,"utf-8"),{success:!0,output:`Written: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[write_file]: ${p.message}`}}}},{name:"edit_file",description:"Apply a surgical edit by replacing old content with new content. Must match exactly one location.",safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!m.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let p=e(m.path),y=await se.readFile(p,"utf-8"),S=m.old_content,_=m.new_content,k=yu(y,S);if(k===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(k>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${k} locations in the file. Provide more surrounding context to be specific.`};await Nt(p);let A=y.replace(S,_);await se.writeFile(p,A,"utf-8");let g=_s(m.path,y,A);return{success:!0,output:`Edited: ${m.path}
318
- ${g}`}}catch(p){return{success:!1,output:"",error:`[edit_file]: ${p.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!m.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!m.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(m.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let p=e(m.path),y=await se.readFile(p,"utf-8"),S=y.split(`
319
- `),_=S.length,k=m.start_line,A=m.end_line;if(k<1||k>_)return{success:!1,output:"",error:`[patch_file]: start_line ${k} is out of range (file has ${_} lines)`};if(A<k||A>_)return{success:!1,output:"",error:`[patch_file]: end_line ${A} is out of range (start_line=${k}, total=${_})`};await Nt(p);let g=S.slice(0,k-1),v=S.slice(A),b=m.new_content.split(`
320
- `),w=[...g,...b,...v].join(`
321
- `);await se.writeFile(p,w,"utf-8");let x=_s(m.path,y,w),T=A-k+1,P=b.length;return{success:!0,output:`Patched: ${m.path} (replaced ${T} lines with ${P})
322
- ${x}`}}catch(p){return{success:!1,output:"",error:`[patch_file]: ${p.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!m.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(m.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let p=e(m.path),y=await se.readFile(p,"utf-8"),S=m.search,_=m.replace,k=m.is_regex;await Nt(p);let A,g;if(k){let v=new RegExp(S,"g");g=(y.match(v)||[]).length,A=y.replace(v,_)}else g=yu(y,S),A=y.split(S).join(_);return g===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await se.writeFile(p,A,"utf-8"),{success:!0,output:`Replaced ${g} occurrence(s) in ${m.path}`})}catch(p){return{success:!1,output:"",error:`[search_and_replace]: ${p.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(m.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let p=e(m.path);return await se.mkdir(Tt.dirname(p),{recursive:!0}),ji.existsSync(p)&&await Nt(p),await se.appendFile(p,m.content,"utf-8"),{success:!0,output:`Appended to: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[append_to_file]: ${p.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let p=e(m.path);return await Nt(p),await se.unlink(p),{success:!0,output:`Deleted: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[delete_file]: ${p.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async m=>{try{if(!m.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!m.to)return{success:!1,output:"",error:"[move_file]: to is required"};let p=e(m.from),y=e(m.to);return await se.mkdir(Tt.dirname(y),{recursive:!0}),await se.rename(p,y),{success:!0,output:`Moved: ${m.from} \u2192 ${m.to}`}}catch(p){return{success:!1,output:"",error:`[move_file]: ${p.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let p=e(m.path);return await se.mkdir(p,{recursive:!0}),{success:!0,output:`Created directory: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[create_dir]: ${p.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async m=>{try{let p=e(m.path||"."),y=m.depth||3;return{success:!0,output:await vu(p,"",y,0)||"(empty directory)"}}catch(p){return{success:!1,output:"",error:`[list_dir]: ${p.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let p=e(m.path),y=await se.stat(p);return{success:!0,output:[`Path: ${m.path}`,`Size: ${Ny(y.size)}`,`Type: ${y.isDirectory()?"directory":"file"}`,`Modified: ${y.mtime.toISOString()}`,`Created: ${y.birthtime.toISOString()}`].join(`
323
- `)}}catch(p){return{success:!1,output:"",error:`[get_file_info]: ${p.message}`}}}}]}function yu(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 vu(n,e,t,s){if(s>=t)return"";let i=(await se.readdir(n,{withFileTypes:!0})).filter(a=>!Dy.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],c=a===i.length-1,d=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${d}${f} ${l.name}
324
- `,l.isDirectory()){let h=e+(c?" ":"\u2502 ");o+=await vu(Tt.join(n,l.name),h,t,s+1)}}return o}function Ny(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var se,ji,Tt,gu,Dy,wu=N(()=>{"use strict";se=O(require("fs/promises")),ji=O(require("fs")),Tt=O(require("path"));Di();mu();gu=300;Dy=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"])});var xu,ks,Su=N(()=>{"use strict";xu=require("child_process"),ks=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,xu.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+=`
325
- Error: ${a.message}`}),r>0&&setTimeout(()=>{o.status==="running"&&(this.kill(s),o.status="timeout",o.stderr+=`
326
- 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+=`
327
- `),i+=s.stderr),t?.lastLines&&(i=i.split(`
149
+ `}function dg(n,e,t,r,s,i,o){return kl(ug(n,e,t,r,s,i,o))}function $l(n,e,t,r,s,i){return dg(n,n,e,t,r,s,i)}var Zk,_l,Sl,Al,$s,rg,sg,cg,rn,ks,El=M(()=>{Qe.prototype={diff:function(e,t){var r,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=s.callback;typeof s=="function"&&(i=s,s={}),this.options=s;var o=this;function a(k){return i?(setTimeout(function(){i(void 0,k)},0),!0):k}e=this.castInput(e),t=this.castInput(t),e=this.removeEmpty(this.tokenize(e)),t=this.removeEmpty(this.tokenize(t));var l=t.length,c=e.length,u=1,d=l+c;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var p=(r=s.timeout)!==null&&r!==void 0?r:1/0,h=Date.now()+p,f=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(f[0],t,e,0);if(f[0].oldPos+1>=c&&g+1>=l)return a([{value:this.join(t),count:t.length}]);var y=-1/0,w=1/0;function v(){for(var k=Math.max(y,-u);k<=Math.min(w,u);k+=2){var P=void 0,j=f[k-1],I=f[k+1];j&&(f[k-1]=void 0);var $=!1;if(I){var E=I.oldPos-k;$=I&&0<=E&&E<l}var N=j&&j.oldPos+1<c;if(!$&&!N){f[k]=void 0;continue}if(!N||$&&j.oldPos+1<I.oldPos?P=o.addToPath(I,!0,void 0,0):P=o.addToPath(j,void 0,!0,1),g=o.extractCommon(P,t,e,k),P.oldPos+1>=c&&g+1>=l)return a(tg(o,P.lastComponent,t,e,o.useLongestToken));f[k]=P,P.oldPos+1>=c&&(w=Math.min(w,k-1)),g+1>=l&&(y=Math.max(y,k+1))}u++}if(i)(function k(){setTimeout(function(){if(u>d||Date.now()>h)return i();v()||k()},0)})();else for(;u<=d&&Date.now()<=h;){var S=v();if(S)return S}},addToPath:function(e,t,r,s){var i=e.lastComponent;return i&&i.added===t&&i.removed===r?{oldPos:e.oldPos+s,lastComponent:{count:i.count+1,added:t,removed:r,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+s,lastComponent:{count:1,added:t,removed:r,previousComponent:i}}},extractCommon:function(e,t,r,s){for(var i=t.length,o=r.length,a=e.oldPos,l=a-s,c=0;l+1<i&&a+1<o&&this.equals(t[l+1],r[a+1]);)l++,a++,c++;return c&&(e.lastComponent={count:c,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=[],r=0;r<e.length;r++)e[r]&&t.push(e[r]);return t},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};Zk=new Qe,_l=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Sl=/\S/,Al=new Qe;Al.equals=function(n,e){return this.options.ignoreCase&&(n=n.toLowerCase(),e=e.toLowerCase()),n===e||this.options.ignoreWhitespace&&!Sl.test(n)&&!Sl.test(e)};Al.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]&&_l.test(e[t])&&_l.test(e[t+2])&&(e[t]+=e[t+2],e.splice(t+1,2),t--);return e};$s=new Qe;$s.tokenize=function(n){this.options.stripTrailingCr&&(n=n.replace(/\r\n/g,`
150
+ `));var e=[],t=n.split(/(\n|\r\n)/);t[t.length-1]||t.pop();for(var r=0;r<t.length;r++){var s=t[r];r%2&&!this.options.newlineIsToken?e[e.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),e.push(s))}return e};rg=new Qe;rg.tokenize=function(n){return n.split(/(\S.+?[.!?])(?=\s+|$)/)};sg=new Qe;sg.tokenize=function(n){return n.split(/([{}:;,]|\s+)/)};cg=Object.prototype.toString,rn=new Qe;rn.useLongestToken=!0;rn.tokenize=$s.tokenize;rn.castInput=function(n){var e=this.options,t=e.undefinedReplacement,r=e.stringifyReplacer,s=r===void 0?function(i,o){return typeof o>"u"?t:o}:r;return typeof n=="string"?n:JSON.stringify(As(n,null,null,s),s," ")};rn.equals=function(n,e){return Qe.prototype.equals.call(rn,n.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};ks=new Qe;ks.tokenize=function(n){return n.slice()};ks.join=ks.removeEmpty=function(n){return n}});function Es(n,e,t){return $l(n,e,t,"original","modified")}var Cl=M(()=>{"use strict";El()});async function bt(n){try{if(!Cs.existsSync(n))return;Cs.existsSync(sn)||await Ke.mkdir(sn,{recursive:!0});let e=await Ke.readFile(n,"utf-8"),t=Mt.basename(n),r=Date.now(),s=`${t}.${r}.bak`,i=Mt.join(sn,s);await Ke.writeFile(i,e,"utf-8");let a=(await Ke.readdir(sn)).filter(l=>l.startsWith(`${t}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Tl)for(let l of a.slice(Tl))await Ke.unlink(Mt.join(sn,l))}catch{}}var Ke,Cs,Mt,Rl,sn,Tl,Ol=M(()=>{"use strict";Ke=C(require("fs/promises")),Cs=C(require("fs")),Mt=C(require("path")),Rl=C(require("os")),sn=Mt.join(Rl.homedir(),".hablas","backup"),Tl=10});function Il(n){let e=h=>ut.resolve(n,h);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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[read_file]: path is required"};let f=e(h.path),y=(await te.readFile(f,"utf-8")).split(`
151
+ `),w=y.length,v=h.start_line?Math.max(1,h.start_line):1,S=h.end_line?Math.min(w,h.end_line):Math.min(w,v+Pl-1),k=Math.min(S,v+Pl-1),P=y.slice(v-1,k),j=String(k).length,I=P.map((N,x)=>`${String(v+x).padStart(j," ")} | ${N}`),$=`[${h.path} \u2014 lines ${v}-${k} of ${w}]`,E=k<w?`
152
+ ... [File has ${w} total lines. Use start_line/end_line to read more.]`:"";return{success:!0,output:`${$}
153
+ ${I.join(`
154
+ `)}${E}`}}catch(f){return{success:!1,output:"",error:`[read_file]: ${f.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(h.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let f=e(h.path);return Ts.existsSync(f)&&await bt(f),await te.mkdir(ut.dirname(f),{recursive:!0}),await te.writeFile(f,h.content,"utf-8"),{success:!0,output:`Written: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[write_file]: ${f.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!h.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let f=e(h.path),g=await te.readFile(f,"utf-8"),y=h.old_content,w=h.new_content,v=Ml(g,y);if(v===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(v>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${v} locations in the file. Provide more surrounding context to be specific.`};await bt(f);let S=g.replace(y,w);await te.writeFile(f,S,"utf-8");let k=Es(h.path,g,S);return{success:!0,output:`Edited: ${h.path}
155
+ ${k}`}}catch(f){return{success:!1,output:"",error:`[edit_file]: ${f.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!h.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!h.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(h.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let f=e(h.path),g=await te.readFile(f,"utf-8"),y=g.split(`
156
+ `),w=y.length,v=h.start_line,S=h.end_line;if(v<1||v>w)return{success:!1,output:"",error:`[patch_file]: start_line ${v} is out of range (file has ${w} lines)`};if(S<v||S>w)return{success:!1,output:"",error:`[patch_file]: end_line ${S} is out of range (start_line=${v}, total=${w})`};await bt(f);let k=y.slice(0,v-1),P=y.slice(S),j=h.new_content.split(`
157
+ `),I=[...k,...j,...P].join(`
158
+ `);await te.writeFile(f,I,"utf-8");let $=Es(h.path,g,I),E=S-v+1,N=j.length;return{success:!0,output:`Patched: ${h.path} (replaced ${E} lines with ${N})
159
+ ${$}`}}catch(f){return{success:!1,output:"",error:`[patch_file]: ${f.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!h.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(h.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let f=e(h.path),g=await te.readFile(f,"utf-8"),y=h.search,w=h.replace,v=h.is_regex;await bt(f);let S,k;if(v){let P=new RegExp(y,"g");k=(g.match(P)||[]).length,S=g.replace(P,w)}else k=Ml(g,y),S=g.split(y).join(w);return k===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await te.writeFile(f,S,"utf-8"),{success:!0,output:`Replaced ${k} occurrence(s) in ${h.path}`})}catch(f){return{success:!1,output:"",error:`[search_and_replace]: ${f.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(h.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let f=e(h.path);return await te.mkdir(ut.dirname(f),{recursive:!0}),Ts.existsSync(f)&&await bt(f),await te.appendFile(f,h.content,"utf-8"),{success:!0,output:`Appended to: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[append_to_file]: ${f.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let f=e(h.path);return await bt(f),await te.unlink(f),{success:!0,output:`Deleted: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[delete_file]: ${f.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 h=>{try{if(!h.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!h.to)return{success:!1,output:"",error:"[move_file]: to is required"};let f=e(h.from),g=e(h.to);return await te.mkdir(ut.dirname(g),{recursive:!0}),await te.rename(f,g),{success:!0,output:`Moved: ${h.from} \u2192 ${h.to}`}}catch(f){return{success:!1,output:"",error:`[move_file]: ${f.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let f=e(h.path);return await te.mkdir(f,{recursive:!0}),{success:!0,output:`Created directory: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[create_dir]: ${f.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 h=>{try{let f=e(h.path||"."),g=h.depth||3;return{success:!0,output:await Ll(f,"",g,0)||"(empty directory)"}}catch(f){return{success:!1,output:"",error:`[list_dir]: ${f.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let f=e(h.path),g=await te.stat(f);return{success:!0,output:[`Path: ${h.path}`,`Size: ${pg(g.size)}`,`Type: ${g.isDirectory()?"directory":"file"}`,`Modified: ${g.mtime.toISOString()}`,`Created: ${g.birthtime.toISOString()}`].join(`
160
+ `)}}catch(f){return{success:!1,output:"",error:`[get_file_info]: ${f.message}`}}}}]}function Ml(n,e){let t=0,r=0;for(;;){let s=n.indexOf(e,r);if(s===-1)break;t++,r=s+e.length}return t}async function Ll(n,e,t,r){if(r>=t)return"";let i=(await te.readdir(n,{withFileTypes:!0})).filter(a=>!fg.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],c=a===i.length-1,u=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${u}${d} ${l.name}
161
+ `,l.isDirectory()){let p=e+(c?" ":"\u2502 ");o+=await Ll(ut.join(n,l.name),p,t,r+1)}}return o}function pg(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var te,Ts,ut,Pl,fg,Dl=M(()=>{"use strict";te=C(require("fs/promises")),Ts=C(require("fs")),ut=C(require("path"));Cl();Ol();Pl=300;fg=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"])});var Fl,Nn,Nl=M(()=>{"use strict";Fl=require("child_process"),Nn=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 r=`bg_${this.nextId++}`,s=t?.timeout||this.config.defaultTimeout,i=(0,Fl.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...t?.env}}),o={id:r,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+=`
162
+ Error: ${a.message}`}),s>0&&setTimeout(()=>{o.status==="running"&&(this.kill(r),o.status="timeout",o.stderr+=`
163
+ Process timed out after ${s}ms`)},s),this.processes.set(r,o),r}readOutput(e,t){let r=this.processes.get(e);if(!r)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let s=t?.type||"both",i="";return(s==="stdout"||s==="both")&&(i+=r.stdout),(s==="stderr"||s==="both")&&(i&&(i+=`
164
+ `),i+=r.stderr),t?.lastLines&&(i=i.split(`
328
165
  `).slice(-t.lastLines).join(`
329
- `)),{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 _u(n){return Bi||(Bi=new ks({workingDir:n})),Bi}function ku(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=[...Fy,...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=_u(n).start(s,{timeout:i});return{success:!0,output:`Background process started: ${l}
330
- PID: ${_u(n).getProcess(l)?.pid}
331
- Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,Au.exec)(s,{cwd:n,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),d="",f="";c.stdout?.on("data",h=>{d+=h}),c.stderr?.on("data",h=>{f+=h}),c.on("close",h=>{l(h===0?{success:!0,output:d||"(no output)"}:{success:!1,output:d,error:f||`Exit code: ${h}`})}),c.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var Au,Fy,Bi,$u=N(()=>{"use strict";Au=require("child_process");Su();Fy=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],Bi=null});function Eu(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=Ct.resolve(n,e.path||"."),r=new RegExp(t,"gi"),i=[];if(await Tu(s,r,i,n),i.length===0)return{success:!0,output:`No matches found for: "${t}"`};let o=i.slice(0,50).join(`
166
+ `)),{success:!0,output:i,status:r.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,r]of this.processes){let s=Date.now()-r.startTime,i=this.formatUptime(s);e.push({id:t,command:r.command,status:r.status,pid:r.pid,startTime:r.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[t,r]of this.processes)(r.status==="finished"||r.status==="killed"||r.status==="timeout")&&(this.processes.delete(t),e++);return e}formatUptime(e){let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let r=Math.floor(t/60);return r<60?`${r}m ${t%60}s`:`${Math.floor(r/60)}h ${r%60}m`}}});function jl(n){return Rs||(Rs=new Nn({workingDir:n})),Rs}function Bl(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 r=t.command,s=t.run_in_background===!0,i=t.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...hg,...o];if(a.length>0){for(let l of a)if(r.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(s){let l=jl(n).start(r,{timeout:i});return{success:!0,output:`Background process started: ${l}
167
+ PID: ${jl(n).getProcess(l)?.pid}
168
+ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,Hl.exec)(r,{cwd:n,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),u="",d="";c.stdout?.on("data",p=>{u+=p}),c.stderr?.on("data",p=>{d+=p}),c.on("close",p=>{l(p===0?{success:!0,output:u||"(no output)"}:{success:!1,output:u,error:d||`Exit code: ${p}`})}),c.on("error",p=>{l({success:!1,output:"",error:p.message})})})}}}var Hl,hg,Rs,ql=M(()=>{"use strict";Hl=require("child_process");Nl();hg=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],Rs=null});function Ul(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,r=dt.resolve(n,e.path||"."),s=new RegExp(t,"gi"),i=[];if(await Kl(r,s,i,n),i.length===0)return{success:!0,output:`No matches found for: "${t}"`};let o=i.slice(0,50).join(`
332
169
  `),a=i.length>50?`
333
- ... 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 Tu(n,e,t,s){let r=await $s.readdir(n,{withFileTypes:!0});for(let i of r){if(Hy.has(i.name)||i.name.startsWith("."))continue;let o=Ct.join(n,i.name);if(i.isDirectory())await Tu(o,e,t,s);else if(jy.has(Ct.extname(i.name)))try{let l=(await $s.readFile(o,"utf-8")).split(`
334
- `),c=Ct.relative(s,o);for(let d=0;d<l.length;d++)e.test(l[d])&&(t.push(`${c}:${d+1}: ${l[d].trim()}`),e.lastIndex=0)}catch{}}}var $s,Ct,Hy,jy,Cu=N(()=>{"use strict";$s=O(require("fs/promises")),Ct=O(require("path")),Hy=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),jy=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"])});function By(n){let e=[],t=Rt.join(n,"tsconfig.json");if(!Ne.existsSync(t))return e;try{(0,Ui.execSync)("npx tsc --noEmit 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(s){let r=s,o=(r.stdout||r.message||"").split(`
335
- `);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 Uy(n){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(s=>Ne.existsSync(Rt.join(n,s))))return e;try{(0,Ui.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:Rt.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(`
336
- `);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 Ky(n,e,t){let s;try{s=Ne.readFileSync(n,"utf-8")}catch{return}let r=Rt.relative(e,n),i=s.split(`
337
- `);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 qy(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=Ne.readdirSync(r)}catch{return}for(let l of a){if(o.includes(l))continue;let c=Rt.join(r,l),d;try{d=Ne.statSync(c)}catch{continue}d.isDirectory()?s(c,i+1):t.some(f=>l.endsWith(f))&&Ky(c,n,e)}}return s(n),e.slice(0,20)}function Wy(n){let e=[];e.push(...By(n)),e.push(...Uy(n)),e.push(...qy(n));let t={error:0,warning:1,info:2};return e.sort((s,r)=>t[s.severity]-t[r.severity]),e}function Ru(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(`
338
- `)}function Gy(n,e){let t=[];for(let s of n)if(s.source==="pattern"&&s.message.includes("console.log")){let r=Rt.join(e,s.file);try{let o=Ne.readFileSync(r,"utf-8").split(`
339
- `);s.line>0&&s.line<=o.length&&(o[s.line-1]="// "+o[s.line-1],Ne.writeFileSync(r,o.join(`
340
- `),"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 Ou(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=Wy(t);if(s&&r.length>0){let o=Gy(r,t).filter(l=>l.fixed).length;return{success:!0,output:`${Ru(r)}
341
-
342
- Auto-fixed: ${o}/${r.length} issues`}}return{success:!0,output:Ru(r)}}catch(r){return{success:!1,output:"",error:`Bug detection failed: ${r instanceof Error?r.message:String(r)}`}}}}}var Ui,Ne,Rt,Pu=N(()=>{"use strict";Ui=require("child_process"),Ne=O(require("fs")),Rt=O(require("path"))});function zy(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,`
170
+ ... 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 Kl(n,e,t,r){let s=await jn.readdir(n,{withFileTypes:!0});for(let i of s){if(mg.has(i.name)||i.name.startsWith("."))continue;let o=dt.join(n,i.name);if(i.isDirectory())await Kl(o,e,t,r);else if(gg.has(dt.extname(i.name)))try{let l=(await jn.readFile(o,"utf-8")).split(`
171
+ `),c=dt.relative(r,o);for(let u=0;u<l.length;u++)e.test(l[u])&&(t.push(`${c}:${u+1}: ${l[u].trim()}`),e.lastIndex=0)}catch{}}}var jn,dt,mg,gg,Wl=M(()=>{"use strict";jn=C(require("fs/promises")),dt=C(require("path")),mg=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),gg=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"])});function yg(n){let e=[],t=ft.join(n,"tsconfig.json");if(!$e.existsSync(t))return e;try{(0,Os.execSync)("npx tsc --noEmit 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(r){let s=r,o=(s.stdout||s.message||"").split(`
172
+ `);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 bg(n){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(r=>$e.existsSync(ft.join(n,r))))return e;try{(0,Os.execSync)("npx eslint . --format json 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(r){let i=r.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:ft.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(`
173
+ `);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 wg(n,e,t){let r;try{r=$e.readFileSync(n,"utf-8")}catch{return}let s=ft.relative(e,n),i=r.split(`
174
+ `);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:s,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:s,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:s,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:s,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 vg(n){let e=[],t=[".ts",".tsx",".js",".jsx"];function r(s,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=$e.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let c=ft.join(s,l),u;try{u=$e.statSync(c)}catch{continue}u.isDirectory()?r(c,i+1):t.some(d=>l.endsWith(d))&&wg(c,n,e)}}return r(n),e.slice(0,20)}function xg(n){let e=[];e.push(...yg(n)),e.push(...bg(n)),e.push(...vg(n));let t={error:0,warning:1,info:2};return e.sort((r,s)=>t[r.severity]-t[s.severity]),e}function Gl(n){if(n.length===0)return" \u2713 No bugs detected";let e=[],t=n.filter(i=>i.severity==="error").length,r=n.filter(i=>i.severity==="warning").length,s=n.filter(i=>i.severity==="info").length;e.push(` Found ${n.length} issue${n.length>1?"s":""}: ${t} errors, ${r} warnings, ${s} 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(`
175
+ `)}function _g(n,e){let t=[];for(let r of n)if(r.source==="pattern"&&r.message.includes("console.log")){let s=ft.join(e,r.file);try{let o=$e.readFileSync(s,"utf-8").split(`
176
+ `);r.line>0&&r.line<=o.length&&(o[r.line-1]="// "+o[r.line-1],$e.writeFileSync(s,o.join(`
177
+ `),"utf-8"),t.push({bug:r,fixed:!0,action:"Commented out console.log"}))}catch{t.push({bug:r,fixed:!1,action:"Failed to read/write file"})}}else t.push({bug:r,fixed:!1,action:"Requires manual fix or LLM assistance"});return t}function Vl(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,r=e.fix==="true"||e.fix===!0;try{let s=xg(t);if(r&&s.length>0){let o=_g(s,t).filter(l=>l.fixed).length;return{success:!0,output:`${Gl(s)}
178
+
179
+ Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:Gl(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Os,$e,ft,zl=M(()=>{"use strict";Os=require("child_process"),$e=C(require("fs")),ft=C(require("path"))});function Ag(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,`
343
180
  `),e=e.replace(/<(br|hr)\s*\/?>/gi,`
344
181
  `),e=e.replace(/<\/?(ul|ol)>/gi,`
345
- `),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(t,s,r)=>`
346
- ${"#".repeat(parseInt(s))} ${r.replace(/<[^>]+>/g,"").trim()}
347
- `),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,`
182
+ `),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(t,r,s)=>`
183
+ ${"#".repeat(parseInt(r))} ${s.replace(/<[^>]+>/g,"").trim()}
184
+ `),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(t,r,s)=>{let i=s.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${r})`:r}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(t,r)=>"\n```\n"+r.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,r)=>String.fromCharCode(parseInt(r))).replace(/&[a-z]+;/gi,""),e=e.replace(/[ \t]+/g," "),e=e.replace(/\n{3,}/g,`
348
185
 
349
- `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function Yy(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 Jy(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 Du(n){let e=new AbortController,t=setTimeout(()=>e.abort(),Mu);try{let s=await fetch(n,{signal:e.signal,headers:{"User-Agent":Vy,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<Iu;){let{done:d,value:f}=await i.read();if(d)break;o.push(f),a+=f.length}if(a>=Iu)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 ${Mu/1e3}s`):r}}function Nu(){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 Du(e);if(!t||r>=400)return{success:!1,output:"",error:`HTTP ${r} \u2014 could not fetch ${e}`};let i=Yy(t),o=zy(t);return o.length>Lu&&(o=o.slice(0,Lu)+`
186
+ `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function kg(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 $g(n,e){let t=[],r=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,s,i=new Set;for(;(s=r.exec(n))!==null;){let o=s[1].trim(),a=s[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 Ql(n){let e=new AbortController,t=setTimeout(()=>e.abort(),Jl);try{let r=await fetch(n,{signal:e.signal,headers:{"User-Agent":Sg,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(t),!r.ok)return{html:"",finalUrl:r.url||n,status:r.status};let s=r.headers.get("content-type")||"";if(!s.includes("text/")&&!s.includes("application/xhtml")&&!s.includes("application/json"))return{html:`[Binary content: ${s}]`,finalUrl:r.url||n,status:r.status};let i=r.body?.getReader();if(!i)return{html:"",finalUrl:r.url||n,status:r.status};let o=[],a=0;for(;a<Yl;){let{done:u,value:d}=await i.read();if(u)break;o.push(d),a+=d.length}if(a>=Yl)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(u=>l.decode(u,{stream:!0})).join("")+l.decode(),finalUrl:r.url||n,status:r.status}}catch(r){clearTimeout(t);let s=r instanceof Error?r:new Error(String(r));throw s.name==="AbortError"?new Error(`Timeout after ${Jl/1e3}s`):s}}function Zl(){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:r,status:s}=await Ql(e);if(!t||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=kg(t),o=Ag(t);return o.length>Xl&&(o=o.slice(0,Xl)+`
350
187
 
351
- [... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${s}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
352
- `)}}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 Du(e);if(!s||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Jy(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,c)=>`${c+1}. [${l.text}](${l.url})`).join(`
188
+ [... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${r}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
189
+ `)}}catch(t){let r=t instanceof Error?t.message:String(t);return{success:!1,output:"",error:`Failed to scrape ${e}: ${r}`}}}},{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:r,finalUrl:s,status:i}=await Ql(e);if(!r||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=$g(r,s);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,c)=>`${c+1}. [${l.text}](${l.url})`).join(`
353
190
  `);return{success:!0,output:`Found ${o.length} links:
354
191
 
355
- ${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 Iu,Mu,Lu,Vy,Fu=N(()=>{"use strict";Iu=2*1024*1024,Mu=15e3,Lu=32e3,Vy="HablasBot/2.0 (+https://hablas.dev)"});function Xy(n){let e=nn.get(n.toLowerCase().trim());return e?Date.now()-e.timestamp>Qy?(nn.delete(n.toLowerCase().trim()),null):e.results:null}function Zy(n,e){if(nn.size>200){let t=nn.keys().next().value;t!==void 0&&nn.delete(t)}nn.set(n.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function eb(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 tb(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],c=a[2].replace(/<[^>]+>/g,"").trim(),d=a[3].replace(/<[^>]+>/g,"").trim(),f=l.match(/uddg=([^&]+)/);if(f)try{l=decodeURIComponent(f[1])}catch{}c&&l&&!l.startsWith("/")&&i.push({title:c,url:l,snippet:d,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,c=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&&!c.has(d)&&!d.includes("duckduckgo.com")&&(c.add(d),i.push({title:f,url:d,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function nb(n,e=5){let t=Xy(n);if(t)return t.slice(0,e);let s=[{name:"brave",fn:()=>eb(n,e)},{name:"duckduckgo",fn:()=>tb(n,e)}];for(let r of s)try{let i=await r.fn();if(i&&i.length>0)return Zy(n,i),i}catch{}return[]}function Hu(){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 nb(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(`
356
- `)}}catch(s){return{success:!1,output:"",error:`Search failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Qy,nn,ju=N(()=>{"use strict";Qy=3600*1e3,nn=new Map});function Ku(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=Ft(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(t.author=Ft(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(t.subject=Ft(l[1]));let c=e.match(/\/Creator\s*\(([^)]*)\)/);c&&(t.creator=Ft(c[1]));let d=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=d.exec(e))!==null;){let m=f[1],p=qu(m);p.trim()&&s.push(p);try{let y=require("zlib"),S=Buffer.from(m,"latin1"),_=y.inflateSync(S).toString("latin1"),k=qu(_);k.trim()&&!s.includes(k)&&s.push(k)}catch{}}return{text:s.join(`
192
+ ${a}`}}catch(r){let s=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${s}`}}}}]}var Yl,Jl,Xl,Sg,ec=M(()=>{"use strict";Yl=2*1024*1024,Jl=15e3,Xl=32e3,Sg="HablasBot/2.0 (+https://hablas.dev)"});function Cg(n){let e=It.get(n.toLowerCase().trim());return e?Date.now()-e.timestamp>Eg?(It.delete(n.toLowerCase().trim()),null):e.results:null}function Tg(n,e){if(It.size>200){let t=It.keys().next().value;t!==void 0&&It.delete(t)}It.set(n.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Rg(n,e){let t=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!t)return null;try{let r=new URLSearchParams({q:n,count:String(Math.min(e,10))}),s=await fetch(`https://api.search.brave.com/res/v1/web/search?${r}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":t},signal:AbortSignal.timeout(1e4)});return s.ok?((await s.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 Og(n,e){try{let t=new URLSearchParams({q:n}),r=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(!r.ok)return null;let s=await r.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(s))!==null&&i.length<e;){let l=a[1],c=a[2].replace(/<[^>]+>/g,"").trim(),u=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}c&&l&&!l.startsWith("/")&&i.push({title:c,url:l,snippet:u,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,c=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let u=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!c.has(u)&&!u.includes("duckduckgo.com")&&(c.add(u),i.push({title:d,url:u,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function Pg(n,e=5){let t=Cg(n);if(t)return t.slice(0,e);let r=[{name:"brave",fn:()=>Rg(n,e)},{name:"duckduckgo",fn:()=>Og(n,e)}];for(let s of r)try{let i=await s.fn();if(i&&i.length>0)return Tg(n,i),i}catch{}return[]}function tc(){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 r=await Pg(e.trim(),t);if(r.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let s=[`Search results for: "${e}" (${r.length} results, source: ${r[0].source})`,""];for(let i=0;i<r.length;i++){let o=r[i];s.push(`[${i+1}] ${o.title}`),s.push(` ${o.url}`),o.snippet&&s.push(` ${o.snippet}`),s.push("")}return{success:!0,output:s.join(`
193
+ `)}}catch(r){return{success:!1,output:"",error:`Search failed: ${r instanceof Error?r.message:String(r)}`}}}}}var Eg,It,nc=M(()=>{"use strict";Eg=3600*1e3,It=new Map});function ic(n){let e=n.toString("latin1"),t={},r=[],s=0,i=e.match(/\/Type\s*\/Page\b/g);s=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(t.title=wt(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(t.author=wt(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(t.subject=wt(l[1]));let c=e.match(/\/Creator\s*\(([^)]*)\)/);c&&(t.creator=wt(c[1]));let u=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=u.exec(e))!==null;){let h=d[1],f=oc(h);f.trim()&&r.push(f);try{let g=require("zlib"),y=Buffer.from(h,"latin1"),w=g.inflateSync(y).toString("latin1"),v=oc(w);v.trim()&&!r.includes(v)&&r.push(v)}catch{}}return{text:r.join(`
357
194
  `).replace(/\r\n/g,`
358
195
  `).replace(/\n{3,}/g,`
359
196
 
360
- `).trim(),pages:r,metadata:t}}function qu(n){let e=[],t=/\(([^)]*)\)\s*Tj/g,s;for(;(s=t.exec(n))!==null;)e.push(Ft(s[1]));let r=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(s=r.exec(n))!==null;){let l=s[1].match(/\(([^)]*)\)/g);if(l){let c=l.map(d=>Ft(d.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(s=i.exec(n))!==null;)e.push(Ft(s[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
361
- `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function Ft(n){return n.replace(/\\n/g,`
362
- `).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 Gu(n){let e=t=>Wu.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(!yt.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=yt.statSync(s);if(r.size>Bu)return{success:!1,output:"",error:`File too large: ${(r.size/1024/1024).toFixed(1)}MB (max: ${Bu/1024/1024}MB)`};try{let i=yt.readFileSync(s),{text:o,pages:a,metadata:l}=Ku(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${t.path} (${a} pages)
197
+ `).trim(),pages:s,metadata:t}}function oc(n){let e=[],t=/\(([^)]*)\)\s*Tj/g,r;for(;(r=t.exec(n))!==null;)e.push(wt(r[1]));let s=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(r=s.exec(n))!==null;){let l=r[1].match(/\(([^)]*)\)/g);if(l){let c=l.map(u=>wt(u.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(r=i.exec(n))!==null;)e.push(wt(r[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
198
+ `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function wt(n){return n.replace(/\\n/g,`
199
+ `).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 lc(n){let e=t=>ac.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 r=e(t.path);if(!Ze.existsSync(r))return{success:!1,output:"",error:`File not found: ${t.path}`};if(!r.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${t.path}`};let s=Ze.statSync(r);if(s.size>rc)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${rc/1024/1024}MB)`};try{let i=Ze.readFileSync(r),{text:o,pages:a,metadata:l}=ic(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${t.path} (${a} pages)
363
200
 
364
- [No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let c=o;return c.length>Uu&&(c=c.slice(0,Uu)+`
201
+ [No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let c=o;return c.length>sc&&(c=c.slice(0,sc)+`
365
202
 
366
- [... 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(`
203
+ [... content truncated ...]`),{success:!0,output:`${[`PDF: ${t.path}`,`Pages: ${a}`,l.title?`Title: ${l.title}`:"",l.author?`Author: ${l.author}`:"",`Size: ${(s.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
367
204
  `)}
368
- ${c}`}}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(!yt.existsSync(s))return{success:!1,output:"",error:`File not found: ${t.path}`};try{let r=yt.statSync(s),i=yt.readFileSync(s),{pages:o,metadata:a}=Ku(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(`
369
- `)}}catch(r){return{success:!1,output:"",error:`Failed to read PDF metadata: ${r instanceof Error?r.message:String(r)}`}}}}]}var yt,Wu,Bu,Uu,Vu=N(()=>{"use strict";yt=O(require("fs")),Wu=O(require("path")),Bu=50*1024*1024,Uu=4e4});function sn(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 sb(n,e,t=Zu){let s=Yu[e];if(!s)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Yu).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=Qu.tmpdir(),i=Xu.join(r,`hablas_exec_${Date.now()}${s.extension}`);try{Es.writeFileSync(i,n,"utf-8");let o=s.command(i),a=Date.now();return await new Promise(l=>{let c=(0,Ju.exec)(o,{timeout:t,maxBuffer:5242880,cwd:r,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),d="",f="";c.stdout?.on("data",h=>{d+=h}),c.stderr?.on("data",h=>{f+=h}),c.on("close",h=>{let m=Date.now()-a;l({success:h===0,stdout:d.slice(0,zu),stderr:f.slice(0,zu/2),exitCode:h??1,duration:m,language:e})}),c.on("error",h=>{let m=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:m,language:e})})})}finally{try{Es.unlinkSync(i)}catch{}}}function rb(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 ed(){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()||rb(e),s=Math.min(Math.max(1e3,n.timeout||Zu),3e4),r=await sb(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?`
370
- Errors/Warnings:`:"Errors:"),i.push(r.stderr)),!r.stdout&&!r.stderr&&i.push("(no output)"),{success:r.success,output:i.join(`
371
- `),error:r.success?void 0:r.stderr||`Exit code: ${r.exitCode}`}}}]}var Ju,Es,Qu,Xu,Zu,zu,Yu,td=N(()=>{"use strict";Ju=require("child_process"),Es=O(require("fs")),Qu=O(require("os")),Xu=O(require("path")),Zu=1e4,zu=16e3;Yu={javascript:{extension:".js",command:n=>`node --no-warnings "${n}"`,available:()=>!0},typescript:{extension:".ts",command:n=>sn("tsx")?`tsx "${n}"`:sn("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=>sn("python3")?`python3 "${n}"`:`python "${n}"`,available:()=>sn("python3")||sn("python")},bash:{extension:".sh",command:n=>`bash "${n}"`,available:()=>sn("bash")}}});var Ts,nd=N(()=>{"use strict";wu();$u();Cu();Pu();Fu();ju();Vu();td();Ts=class{tools=new Map;constructor(e,t){let s=bu(e);for(let r of s)this.tools.set(r.name,r);this.tools.set("run_command",ku(e,t)),this.tools.set("search_codebase",Eu(e)),this.tools.set("detect_bugs",Ou(e)),this.tools.set("web_search",Hu());for(let r of Nu())this.tools.set(r.name,r);for(let r of Gu(e))this.tools.set(r.name,r);for(let r of ed())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(`
205
+ ${c}`}}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 r=e(t.path);if(!Ze.existsSync(r))return{success:!1,output:"",error:`File not found: ${t.path}`};try{let s=Ze.statSync(r),i=Ze.readFileSync(r),{pages:o,metadata:a}=ic(i);return{success:!0,output:[`File: ${t.path}`,`Size: ${(s.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: ${s.mtime.toISOString()}`].filter(Boolean).join(`
206
+ `)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var Ze,ac,rc,sc,cc=M(()=>{"use strict";Ze=C(require("fs")),ac=C(require("path")),rc=50*1024*1024,sc=4e4});function Lt(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 Mg(n,e,t=mc){let r=dc[e];if(!r)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(dc).join(", ")}`,exitCode:1,duration:0,language:e};if(!r.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 s=pc.tmpdir(),i=hc.join(s,`hablas_exec_${Date.now()}${r.extension}`);try{Hn.writeFileSync(i,n,"utf-8");let o=r.command(i),a=Date.now();return await new Promise(l=>{let c=(0,fc.exec)(o,{timeout:t,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),u="",d="";c.stdout?.on("data",p=>{u+=p}),c.stderr?.on("data",p=>{d+=p}),c.on("close",p=>{let h=Date.now()-a;l({success:p===0,stdout:u.slice(0,uc),stderr:d.slice(0,uc/2),exitCode:p??1,duration:h,language:e})}),c.on("error",p=>{let h=Date.now()-a;l({success:!1,stdout:"",stderr:p.message,exitCode:1,duration:h,language:e})})})}finally{try{Hn.unlinkSync(i)}catch{}}}function Ig(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 gc(){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()||Ig(e),r=Math.min(Math.max(1e3,n.timeout||mc),3e4),s=await Mg(e,t,r),i=[];return i.push(`Language: ${s.language} | Exit: ${s.exitCode} | Duration: ${s.duration}ms`),i.push(""),s.stdout&&(i.push("Output:"),i.push(s.stdout)),s.stderr&&(i.push(s.stdout?`
207
+ Errors/Warnings:`:"Errors:"),i.push(s.stderr)),!s.stdout&&!s.stderr&&i.push("(no output)"),{success:s.success,output:i.join(`
208
+ `),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var fc,Hn,pc,hc,mc,uc,dc,yc=M(()=>{"use strict";fc=require("child_process"),Hn=C(require("fs")),pc=C(require("os")),hc=C(require("path")),mc=1e4,uc=16e3;dc={javascript:{extension:".js",command:n=>`node --no-warnings "${n}"`,available:()=>!0},typescript:{extension:".ts",command:n=>Lt("tsx")?`tsx "${n}"`:Lt("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=>Lt("python3")?`python3 "${n}"`:`python "${n}"`,available:()=>Lt("python3")||Lt("python")},bash:{extension:".sh",command:n=>`bash "${n}"`,available:()=>Lt("bash")}}});var Bn,bc=M(()=>{"use strict";Dl();ql();Wl();zl();ec();nc();cc();yc();Bn=class{tools=new Map;constructor(e,t){let r=Il(e);for(let s of r)this.tools.set(s.name,s);this.tools.set("run_command",Bl(e,t)),this.tools.set("search_codebase",Ul(e)),this.tools.set("detect_bugs",Vl(e)),this.tools.set("web_search",tc());for(let s of Zl())this.tools.set(s.name,s);for(let s of lc(e))this.tools.set(s.name,s);for(let s of gc())this.tools.set(s.name,s)}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={},r=[];for(let[s,i]of Object.entries(e.parameters))t[s]={type:i.type==="number"?"number":"string",description:i.description},i.required&&r.push(s);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:t,required:r}}}})}getToolDescriptions(){return this.getAll().map(t=>{let r=Object.entries(t.parameters).map(([s,i])=>` ${s}: ${i.type} \u2014 ${i.description}`).join(`
372
209
  `);return`- ${t.name} [${t.safety}]: ${t.description}
373
- ${s}`}).join(`
210
+ ${r}`}).join(`
374
211
 
375
- `)}}});function Ki(n){return Math.ceil(n.length/3.5)}function Pn(n,e){let t=Math.floor(e*3.5);return n.length<=t?n:n.slice(0,t)+`
376
- ... [truncated to fit context budget]`}var qi=N(()=>{"use strict"});var sd,rn,Wi=N(()=>{"use strict";sd=O(require("crypto"));qi();rn=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=Ki(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=Pn(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
377
- ${l}`),r+=a}}continue}i.push(`--- ${o.path} ---
378
- ${o.content}`),r+=o.tokenCount}return i.join(`
212
+ `)}}});function Ps(n){return Math.ceil(n.length/3.5)}function on(n,e){let t=Math.floor(e*3.5);return n.length<=t?n:n.slice(0,t)+`
213
+ ... [truncated to fit context budget]`}var Ms=M(()=>{"use strict"});var wc,Dt,Is=M(()=>{"use strict";wc=C(require("crypto"));Ms();Dt=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,t,r){let s=this.computeHash(t),i=this.cache.get(e);if(i&&i.hash===s){i.lastUsed=Date.now(),i.accessCount++;return}let o=Ps(t),a=r?.importance??this.autoImportance(e,t);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:t,hash:s,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:r?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,t){let r=this.cache.get(e);return r?r.hash!==this.computeHash(t):!0}buildContext(e){let t=e||this.budget,r=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),s=0,i=[];for(let o of r){if(s+o.tokenCount>t){if(o.importance>=7){let a=t-s;if(a>200){let l=on(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
214
+ ${l}`),s+=a}}continue}i.push(`--- ${o.path} ---
215
+ ${o.content}`),s+=o.tokenCount}return i.join(`
379
216
 
380
- `)}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(c=>i.length===0?!0:i.some(d=>c.path.includes(d))).sort((c,d)=>this.computeScore(d)-this.computeScore(c)),a=0,l=[];for(let c of o){if(a+c.tokenCount>s)break;l.push(`--- ${c.path} ---
217
+ `)}buildAgentContext(e,t){let r=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(c=>i.length===0?!0:i.some(u=>c.path.includes(u))).sort((c,u)=>this.computeScore(u)-this.computeScore(c)),a=0,l=[];for(let c of o){if(a+c.tokenCount>r)break;l.push(`--- ${c.path} ---
381
218
  ${c.content}`),a+=c.tokenCount}return l.join(`
382
219
 
383
- `)}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=Ki(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 sd.createHash("md5").update(e).digest("hex")}}});function In(){return`msg_${Date.now()}_${++ib}`}function on(n){return Math.ceil(n.length/4)}var ib,an,Gi=N(()=>{"use strict";ib=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=on(e);this.messages.push({id:In(),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=In(),r=on(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=In(),i=on(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=In(),r=on(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=on(e),s=this.messages.filter(r=>r.priority==="critical"&&r.role!=="system");this.messages=[{id:In(),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)+`
220
+ `)}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(([s,i])=>({key:s,...i,score:this.computeScore(i)})).sort((s,i)=>s.score-i.score),r=0;for(let s of t){if(r>=e)break;s.importance>=9||(r+=s.tokenCount,this.usedTokens-=s.tokenCount,this.cache.delete(s.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let s=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-s/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,t){let r=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(r=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(r=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(r=3);let s=Ps(t);return s>2e3&&(r=Math.max(1,r-1)),s>5e3&&(r=Math.max(1,r-2)),r}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 r of t)if(r!==e){let s=this.cache.get(r);s&&!s.relatedFiles.includes(e)&&s.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return wc.createHash("md5").update(e).digest("hex")}}});function an(){return`msg_${Date.now()}_${++Lg}`}function Ft(n){return Math.ceil(n.length/4)}var Lg,vt,Ls=M(()=>{"use strict";Lg=0;vt=class n{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,t=50,r=32e3){this.maxMessages=t,this.maxTokens=r,this.sessionId=`session_${Date.now()}`;let s=Ft(e);this.messages.push({id:an(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:s,compressed:!1,tags:["system"]}),this.totalTokens=s}getSessionId(){return this.sessionId}addUserMessage(e,t){let r=an(),s=Ft(e);return this.messages.push({id:r,role:"user",content:e,timestamp:Date.now(),priority:t?.priority||"high",tokenEstimate:s,compressed:!1,tags:t?.tags||["user-input"]}),this.totalTokens+=s,this.trimIfNeeded(),r}addAssistantMessage(e,t,r){let s=an(),i=Ft(e),o={id:s,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:r||"hablas",tokenEstimate:i,compressed:!1,tags:r?[`agent:${r}`]:["assistant"]};return t&&t.length>0&&(o.tool_calls=t,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,r&&this.agentMessageCounts.set(r,(this.agentMessageCounts.get(r)||0)+1),this.trimIfNeeded(),s}addToolMessage(e,t){let r=an(),s=Ft(e);return this.messages.push({id:r,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:s,compressed:!1,tags:t?[`tool:${t}`]:["tool-result"]}),this.totalTokens+=s,this.trimIfNeeded(),r}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=Ft(e),r=this.messages.filter(s=>s.priority==="critical"&&s.role!=="system");this.messages=[{id:an(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:t,compressed:!1,tags:["system"]},...r],this.recalculateTokens()}takeSnapshot(e){let t={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(r=>({...r})),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(r=>r.id===e);return t?(this.messages=t.messages.map(r=>({...r})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,t){let r=this.messages.length,s=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"?s.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&s.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:r,session:s}),s}mergeFork(e,t){let r=this.forks.get(e);if(!r)return!1;let s=r.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(s.length>0){let i=s.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(r=>r.content.toLowerCase().includes(t))}getMessagesByTag(e){return this.messages.filter(t=>t.tags.includes(e))}getLastByRole(e,t=1){return this.messages.filter(r=>r.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(r=>r.role==="assistant"&&!r.compressed&&r.priority!=="critical"&&r.tokenEstimate>300);for(let r of t.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}}if(this.messages.length>this.maxMessages){let t=this.messages[0],r=this.messages.slice(1),s={critical:3,high:2,normal:1,low:0},i=r.sort((o,a)=>{let l=s[a.priority]-s[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,r=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
384
221
  ...(compressed from `+t+" chars)":e.content=e.content.slice(0,400)+`
385
- ...(compressed from `+t+" chars)",e.compressed=!0,e.originalLength=t,e.tokenEstimate=on(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 rd,Fe,Ie,id,Cs,Vi,ob,ab,lb,Rs,od=N(()=>{"use strict";rd=O(require("readline")),Fe=O(require("fs")),Ie=O(require("path")),id=O(require("os"));en();Cs=Ie.join(id.homedir(),".hablas","history"),Vi=500,ob=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"]),ab=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),lb=["read ","edit ","write ","delete ","open ","patch "],Rs=class{rl;history=[];workingDir;fileCache=[];fileCacheTime=0;constructor(e){this.workingDir=e||process.cwd(),this.loadHistory(),this.rl=this.createReadline()}createReadline(){return rd.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:this.history,historySize:Vi,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=` ${u.warning("?")} ${e} ${u.muted("[Y/n]")} `;return(await this.prompt(t)).toLowerCase()!=="n"}async confirmDangerous(e){console.log(`
386
- ${u.error("\u26A0")} ${u.error(u.strong(e))}`),console.log(` ${u.muted('This action cannot be undone. Type "yes" to confirm.')}
387
- `);let t=` ${u.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=Ci.filter(r=>r.startsWith(e));return[s.length?s:Ci,e]}for(let s of lb)if(e.toLowerCase().includes(s)){let r=e.split(s).pop()??"";if(r&&!r.includes(" "))try{let i=Ie.dirname(r)||".",o=Ie.basename(r),a=Ie.resolve(this.workingDir,i),l=Fe.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(r))+Ie.join(i,c));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=Fe.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||ab.has(a.name))continue;let l=t?`${t}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(Ie.join(e,a.name),l,s,r,i+1);else{let c=Ie.extname(a.name).toLowerCase();(ob.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&s.push(l)}}}catch{}}loadHistory(){try{if(Fe.existsSync(Cs)){let e=Fe.readFileSync(Cs,"utf-8");this.history=e.split(`
388
- `).filter(Boolean).slice(-Vi)}}catch{}}saveHistory(){try{let e=Ie.dirname(Cs);Fe.existsSync(e)||Fe.mkdirSync(e,{recursive:!0});let t=this.history.slice(-Vi);Fe.writeFileSync(Cs,t.join(`
389
- `),"utf-8")}catch{}}}});var Mn,zi=N(()=>{"use strict";Mn=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+`
222
+ ...(compressed from `+t+" chars)",e.compressed=!0,e.originalLength=t,e.tokenEstimate=Ft(e.content),this.totalTokens-=r-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 vc,Ee,ve,xc,qn,Ds,Dg,Fg,Ng,Un,_c=M(()=>{"use strict";vc=C(require("readline")),Ee=C(require("fs")),ve=C(require("path")),xc=C(require("os"));Ot();qn=ve.join(xc.homedir(),".hablas","history"),Ds=500,Dg=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"]),Fg=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Ng=["read ","edit ","write ","delete ","open ","patch "],Un=class{rl;history=[];workingDir;fileCache=[];fileCacheTime=0;constructor(e){this.workingDir=e||process.cwd(),this.loadHistory(),this.rl=this.createReadline()}createReadline(){return vc.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:this.history,historySize:Ds,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,r=>{r.trim()&&(this.history.push(r.trim()),this.saveHistory()),t(r)})})}async confirm(e){let t=` ${m.warning("?")} ${e} ${m.muted("[Y/n]")} `;return(await this.prompt(t)).toLowerCase()!=="n"}async confirmDangerous(e){console.log(`
223
+ ${m.error("\u26A0")} ${m.error(m.strong(e))}`),console.log(` ${m.muted('This action cannot be undone. Type "yes" to confirm.')}
224
+ `);let t=` ${m.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 s=["coder","planner","debugger","reviewer"],i=e.slice(9),o=s.filter(a=>a.startsWith(i)).map(a=>"/mindset "+a);return[o.length?o:s.map(a=>"/mindset "+a),e]}if(e.startsWith("/alias ")){let s=["/alias set","/alias del"],i=s.filter(o=>o.startsWith(e));return[i.length?i:s,e]}if(e.startsWith("/plugins ")){let s=["/plugins enable","/plugins disable"],i=s.filter(o=>o.startsWith(e));return[i.length?i:s,e]}let r=vs.filter(s=>s.startsWith(e));return[r.length?r:vs,e]}for(let r of Ng)if(e.toLowerCase().includes(r)){let s=e.split(r).pop()??"";if(s&&!s.includes(" "))try{let i=ve.dirname(s)||".",o=ve.basename(s),a=ve.resolve(this.workingDir,i),l=Ee.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(s))+ve.join(i,c));if(l.length)return[l,e]}catch{}}let t=e.match(/#([\w./-]*)$/);if(t){let r=t[1],s=this.getProjectFiles(),i=s.filter(a=>a.toLowerCase().startsWith(r.toLowerCase())).map(a=>e.slice(0,e.length-t[0].length)+"#"+a);return i.length>0?[i,e]:[s.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,r,s,i=0){if(!(i>=s))try{let o=Ee.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||Fg.has(a.name))continue;let l=t?`${t}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(ve.join(e,a.name),l,r,s,i+1);else{let c=ve.extname(a.name).toLowerCase();(Dg.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&r.push(l)}}}catch{}}loadHistory(){try{if(Ee.existsSync(qn)){let e=Ee.readFileSync(qn,"utf-8");this.history=e.split(`
225
+ `).filter(Boolean).slice(-Ds)}}catch{}}saveHistory(){try{let e=ve.dirname(qn);Ee.existsSync(e)||Ee.mkdirSync(e,{recursive:!0});let t=this.history.slice(-Ds);Ee.writeFileSync(qn,t.join(`
226
+ `),"utf-8")}catch{}}}});var ln,Fs=M(()=>{"use strict";ln=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 r=this.history[this.history.length-1];r.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 r of this.listeners)try{r(t,e)}catch{}return!0}has(e){return this.mindsets.has(e)}getHistory(){return[...this.history]}getMostUsed(){let e={};for(let r of this.history)e[r.name]=(e[r.name]||0)+1;let t=Object.entries(e).sort((r,s)=>s[1]-r[1]);return t.length>0?t[0][0]:null}onChange(e){this.listeners.push(e)}createComposite(e,t,r){let s=this.mindsets.get(t),i=this.mindsets.get(r);if(!s||!i)return null;let o={name:e,description:`${s.description} + ${i.description}`,systemPrompt:s.systemPrompt+`
390
227
 
391
- `+i.systemPrompt,toolPreferences:[...new Set([...i.toolPreferences,...r.toolPreferences])],behaviorModifiers:{...r.behaviorModifiers,...i.behaviorModifiers}};return this.register(o),o}}});var Yi,Ji=N(()=>{"use strict";Yi={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.
228
+ `+i.systemPrompt,toolPreferences:[...new Set([...i.toolPreferences,...s.toolPreferences])],behaviorModifiers:{...s.behaviorModifiers,...i.behaviorModifiers}};return this.register(o),o}}});var Ns,js=M(()=>{"use strict";Ns={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.
392
229
 
393
230
  ## Your Strengths
394
231
  - Writing clean, production-ready code with proper error handling
@@ -420,7 +257,7 @@ ${c.content}`),a+=c.tokenCount}return l.join(`
420
257
 
421
258
  ## Important
422
259
  Never output tool calls as text or JSON in your response.
423
- Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","patch_file","edit_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"concise",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py","*.go","*.rs","*.css","*.html"]}});var Qi,Xi=N(()=>{"use strict";Qi={name:"planner",description:"Team Leader \u2014 strategic planning, task breakdown, coordination, decision-making",systemPrompt:`You are Hablas, the inspiring Team Leader of a multi-agent AI development system. You are a highly supportive, communicative, and exceptionally competent Engineering Lead.
260
+ Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","patch_file","edit_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"concise",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py","*.go","*.rs","*.css","*.html"]}});var Hs,Bs=M(()=>{"use strict";Hs={name:"planner",description:"Team Leader \u2014 strategic planning, task breakdown, coordination, decision-making",systemPrompt:`You are Hablas, the inspiring Team Leader of a multi-agent AI development system. You are a highly supportive, communicative, and exceptionally competent Engineering Lead.
424
261
  You coordinate a team of specialized agents to help developers build and modify their codebase, and you love helping the developer succeed with high-quality engineering.
425
262
 
426
263
  ## Your Persona (Supportive, Empathetic & Expert Engineering Lead)
@@ -462,7 +299,7 @@ Then execute step by step.
462
299
 
463
300
  ## Important
464
301
  Never output tool calls as text or JSON in your response.
465
- Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","search_codebase","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!0,contextPriority:"all"}}});var Zi,eo=N(()=>{"use strict";Zi={name:"reviewer",description:"Code reviewer \u2014 quality audit, anti-patterns, security issues, performance bottlenecks",systemPrompt:`You are an expert code reviewer. You audit code quality and provide actionable feedback.
302
+ Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","search_codebase","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!0,contextPriority:"all"}}});var qs,Us=M(()=>{"use strict";qs={name:"reviewer",description:"Code reviewer \u2014 quality audit, anti-patterns, security issues, performance bottlenecks",systemPrompt:`You are an expert code reviewer. You audit code quality and provide actionable feedback.
466
303
 
467
304
  ## Review Checklist
468
305
  - Security vulnerabilities (injection, XSS, CSRF, auth bypass)
@@ -496,7 +333,7 @@ For each issue:
496
333
 
497
334
  ## Important
498
335
  Never output tool calls as text or JSON in your response.
499
- Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","search_codebase","list_dir","get_file_info"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py"]}});var to,no=N(()=>{"use strict";to={name:"debugger",description:"Bug hunter \u2014 traces errors, root cause analysis, targeted fixes, regression prevention",systemPrompt:`You are a systematic debugging expert. You find and fix bugs through methodical investigation.
336
+ Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","search_codebase","list_dir","get_file_info"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py"]}});var Ks,Ws=M(()=>{"use strict";Ks={name:"debugger",description:"Bug hunter \u2014 traces errors, root cause analysis, targeted fixes, regression prevention",systemPrompt:`You are a systematic debugging expert. You find and fix bugs through methodical investigation.
500
337
 
501
338
  ## Debugging Process
502
339
  1. **Reproduce**: Understand the symptom and error message
@@ -518,7 +355,7 @@ Always use the tool_calls field provided by the API.`,toolPreferences:["read_fil
518
355
  ## Important
519
356
  Never output tool calls as text or JSON in your response.
520
357
  Always use the tool_calls field provided by the API.
521
- Focus on the ROOT CAUSE, not symptoms.`,toolPreferences:["read_file","search_codebase","run_command","patch_file","edit_file"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.py","*.go","*.log","*.json"]}});var so,ro=N(()=>{"use strict";so={name:"architect",description:"System architecture \u2014 schemas, APIs, project structure, scalability, ADRs",systemPrompt:`You are Bob, the System Architect on the Hablas multi-agent team.
358
+ Focus on the ROOT CAUSE, not symptoms.`,toolPreferences:["read_file","search_codebase","run_command","patch_file","edit_file"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.py","*.go","*.log","*.json"]}});var Gs,Vs=M(()=>{"use strict";Gs={name:"architect",description:"System architecture \u2014 schemas, APIs, project structure, scalability, ADRs",systemPrompt:`You are Bob, the System Architect on the Hablas multi-agent team.
522
359
  Your role is to design robust, scalable, maintainable system architectures.
523
360
 
524
361
  ## Your Strengths
@@ -554,7 +391,7 @@ Your role is to design robust, scalable, maintainable system architectures.
554
391
 
555
392
  ## Important
556
393
  Never output tool calls as text or JSON in your response.
557
- Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","list_dir","write_file","search_codebase"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"architecture"},filePatterns:["*.md","*.json","*.yaml","*.yml","*.toml","*.xml","schema*","config*"]}});var io,oo=N(()=>{"use strict";io={name:"devops",description:"DevOps \u2014 Docker, CI/CD, cloud, monitoring, deployment, infrastructure as code",systemPrompt:`You are a DevOps expert. You handle infrastructure, deployment, and operational concerns.
394
+ Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","list_dir","write_file","search_codebase"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"architecture"},filePatterns:["*.md","*.json","*.yaml","*.yml","*.toml","*.xml","schema*","config*"]}});var zs,Ys=M(()=>{"use strict";zs={name:"devops",description:"DevOps \u2014 Docker, CI/CD, cloud, monitoring, deployment, infrastructure as code",systemPrompt:`You are a DevOps expert. You handle infrastructure, deployment, and operational concerns.
558
395
 
559
396
  ## Your Expertise
560
397
  - Docker & container orchestration (Kubernetes, Docker Compose)
@@ -585,7 +422,7 @@ Always use the tool_calls field provided by the API.`,toolPreferences:["read_fil
585
422
 
586
423
  ## Important
587
424
  Never output tool calls as text or JSON in your response.
588
- Always use the tool_calls field provided by the API.`,toolPreferences:["run_command","write_file","read_file","list_dir"],behaviorModifiers:{planFirst:!0,maxIterations:20,verbosity:"normal",autoConfirmSafe:!1,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!1,contextPriority:"all"},filePatterns:["Dockerfile*","docker-compose*","*.yml","*.yaml",".github/*","Makefile","*.sh"]}});var ao,lo=N(()=>{"use strict";ao={name:"researcher",description:"Research & analysis \u2014 documentation, APIs, best practices, data analysis, benchmarks",systemPrompt:`You are David, the Data & Research Specialist on the Hablas multi-agent team.
425
+ Always use the tool_calls field provided by the API.`,toolPreferences:["run_command","write_file","read_file","list_dir"],behaviorModifiers:{planFirst:!0,maxIterations:20,verbosity:"normal",autoConfirmSafe:!1,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!1,contextPriority:"all"},filePatterns:["Dockerfile*","docker-compose*","*.yml","*.yaml",".github/*","Makefile","*.sh"]}});var Js,Xs=M(()=>{"use strict";Js={name:"researcher",description:"Research & analysis \u2014 documentation, APIs, best practices, data analysis, benchmarks",systemPrompt:`You are David, the Data & Research Specialist on the Hablas multi-agent team.
589
426
  Your role is to find information, analyze data, and provide well-researched context.
590
427
 
591
428
  ## Your Strengths
@@ -622,7 +459,7 @@ Your role is to find information, analyze data, and provide well-researched cont
622
459
 
623
460
  ## Important
624
461
  Never output tool calls as text or JSON in your response.
625
- Always use the tool_calls field provided by the API.`,toolPreferences:["search_codebase","read_file","run_command","list_dir","web_search"],behaviorModifiers:{planFirst:!1,maxIterations:10,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"exploratory",askWhenUncertain:!0,canDelegate:!1,contextPriority:"data"},filePatterns:["*.md","*.txt","*.csv","*.json","*.sql","*.yml","*.yaml"]}});var co,uo=N(()=>{"use strict";co={name:"product-manager",description:"Product Manager \u2014 requirements, PRDs, user stories, market research, competitive analysis",systemPrompt:`You are Emma, the Product Manager on the Hablas multi-agent team.
462
+ Always use the tool_calls field provided by the API.`,toolPreferences:["search_codebase","read_file","run_command","list_dir","web_search"],behaviorModifiers:{planFirst:!1,maxIterations:10,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"exploratory",askWhenUncertain:!0,canDelegate:!1,contextPriority:"data"},filePatterns:["*.md","*.txt","*.csv","*.json","*.sql","*.yml","*.yaml"]}});var Qs,Zs=M(()=>{"use strict";Qs={name:"product-manager",description:"Product Manager \u2014 requirements, PRDs, user stories, market research, competitive analysis",systemPrompt:`You are Emma, the Product Manager on the Hablas multi-agent team.
626
463
  Your role is to analyze needs, create detailed specs, and ensure the team builds the right thing.
627
464
 
628
465
  ## Your Strengths
@@ -657,7 +494,7 @@ Every PRD you create should include:
657
494
 
658
495
  ## Important
659
496
  Never output tool calls as text or JSON in your response.
660
- Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"requirements"},filePatterns:["*.md","*.txt","*.json","package.json","README*"]}});var fo,po=N(()=>{"use strict";fo={name:"sync",description:"Team Coordinator & Diplomatic Consul \u2014 handles lock negotiations, git sync, and team messaging",systemPrompt:`You are @Consul, the Software Diplomat on the Hablas multi-agent team.
497
+ Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"requirements"},filePatterns:["*.md","*.txt","*.json","package.json","README*"]}});var ei,ti=M(()=>{"use strict";ei={name:"sync",description:"Team Coordinator & Diplomatic Consul \u2014 handles lock negotiations, git sync, and team messaging",systemPrompt:`You are @Consul, the Software Diplomat on the Hablas multi-agent team.
661
498
  Your absolute priority is to ensure smooth, conflict-free collaboration between human developers and machine agents.
662
499
 
663
500
  ## Your Personality (INTJ + Diplomatic Coordinator)
@@ -679,33 +516,33 @@ Your absolute priority is to ensure smooth, conflict-free collaboration between
679
516
 
680
517
  ## Important
681
518
  Never output tool calls as text or JSON in your response.
682
- 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 Os(){let n=new Mn;return n.register(Yi),n.register(Qi),n.register(Zi),n.register(to),n.register(so),n.register(io),n.register(ao),n.register(co),n.register(fo),n}var ho=N(()=>{"use strict";zi();Ji();Xi();eo();no();ro();oo();lo();uo();po();zi();Ji();Xi();eo();no();ro();oo();lo();uo();po()});var Ee,Ps,ad,ld,ln,Is,cd=N(()=>{"use strict";Ee=O(require("fs")),Ps=O(require("path")),ad=O(require("os")),ld=O(require("crypto")),ln=Ps.join(ad.homedir(),".hablas","memory"),Is=class{entries=new Map;agentLanes=new Map;projectHash;filePath;agentLanesPath;constructor(e){this.projectHash=ld.createHash("md5").update(e).digest("hex").slice(0,12),this.filePath=Ps.join(ln,`${this.projectHash}.json`),this.agentLanesPath=Ps.join(ln,`${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 c=a.importance*(1+a.useCount*.3);return l.importance*(1+l.useCount*.3)-c}).slice(0,t);return i.length===0?"":`## Agent Memory
519
+ 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 Kn(){let n=new ln;return n.register(Ns),n.register(Hs),n.register(qs),n.register(Ks),n.register(Gs),n.register(zs),n.register(Js),n.register(Qs),n.register(ei),n}var ni=M(()=>{"use strict";Fs();js();Bs();Us();Ws();Vs();Ys();Xs();Zs();ti();Fs();js();Bs();Us();Ws();Vs();Ys();Xs();Zs();ti()});var be,Wn,Sc,Ac,Nt,Gn,kc=M(()=>{"use strict";be=C(require("fs")),Wn=C(require("path")),Sc=C(require("os")),Ac=C(require("crypto")),Nt=Wn.join(Sc.homedir(),".hablas","memory"),Gn=class{entries=new Map;agentLanes=new Map;projectHash;filePath;agentLanesPath;constructor(e){this.projectHash=Ac.createHash("md5").update(e).digest("hex").slice(0,12),this.filePath=Wn.join(Nt,`${this.projectHash}.json`),this.agentLanesPath=Wn.join(Nt,`${this.projectHash}_agents.json`),this.load()}set(e,t,r){let s=this.entries.get(e),i=Date.now(),o=r?.category||"note";this.entries.set(e,{key:e,value:t,category:o,importance:r?.importance??this.autoImportance(o,t),createdBy:r?.createdBy||"hablas",accessCount:s?.accessCount??0,useCount:s?.useCount??0,tags:r?.tags||this.autoTag(t,o),relatedFiles:r?.relatedFiles||this.extractFileRefs(t),createdAt:s?.createdAt??i,updatedAt:i,lastAccessedAt:i,consolidatedFrom:s?.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,r,s="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:r,category:s,importance:this.autoImportance(s,r),createdBy:e,accessCount:a?.accessCount??0,useCount:a?.useCount??0,tags:this.autoTag(r,s),relatedFiles:this.extractFileRefs(r),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 r=this.getAgentMemories(e),s=this.getAll().filter(a=>a.importance>=5||a.useCount>=2),i=[...r,...s].sort((a,l)=>{let c=a.importance*(1+a.useCount*.3);return l.importance*(1+l.useCount*.3)-c}).slice(0,t);return i.length===0?"":`## Agent Memory
683
520
  `+i.map(a=>`- [${a.category}${a.importance>=7?" \u2605":""}] ${a.key}: ${a.value}`).join(`
684
- `)}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 c=0,d="partial";l.key.toLowerCase()===s&&(c+=10,d="exact"),l.key.toLowerCase().includes(s)&&(c+=5),l.value.toLowerCase().includes(s)&&(c+=3);for(let h of r)l.key.toLowerCase().includes(h)&&(c+=2),l.value.toLowerCase().includes(h)&&(c+=1),l.tags.some(m=>m.toLowerCase().includes(h))&&(c+=2,d=d==="exact"?"exact":"tag");c*=1+l.importance*.1,c*=1+l.useCount*.2;let f=(Date.now()-l.updatedAt)/(10080*60*1e3);c*=Math.max(.3,1-f*.1),c>.5&&o.push({entry:l,relevanceScore:c,matchType:d})}return o.sort((l,c)=>c.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(`
685
- `)}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)`,c=a.map(h=>`${h.key}: ${h.value}`).join("; "),d=a.map(h=>h.key);this.set(l,c.slice(0,500),{category:o,importance:3,tags:["consolidated"]});let f=this.entries.get(l);f&&(f.consolidatedFrom=d);for(let h of a)this.entries.delete(h.key),i++}return i>0&&this.save(),i}learnFromToolResult(e,t,s,r,i="hablas"){if(!(s.length<20)){if(!r){let o=`error:${e}:${JSON.stringify(t).slice(0,50)}`,a=this.entries.get(o);a?(a.useCount++,a.importance=Math.min(10,a.importance+1)):this.set(o,`${e} failed with: ${s.slice(0,200)}`,{category:"error",importance:6,createdBy:i,tags:["auto-learned","error",e]})}if(e==="list_dir"&&r){let o=t.path||".";this.set(`structure:${o}`,s.slice(0,300),{category:"pattern",importance:3,createdBy:i,tags:["auto-learned","structure"],relatedFiles:[o]})}}}size(){return this.entries.size}clear(){this.entries.clear(),this.agentLanes.clear(),this.save(),this.saveAgentLanes()}render(){if(this.getAll().length===0)return" No project memories stored";let t={convention:"\u{1F4CF}",decision:"\u{1F3AF}",pattern:"\u{1F504}",note:"\u{1F4DD}",error:"\u26A0\uFE0F","tool-result":"\u{1F527}","user-pref":"\u{1F464}",dependency:"\u{1F4E6}",performance:"\u26A1",security:"\u{1F512}",api:"\u{1F310}","agent-learning":"\u{1F916}"};return this.getTopMemories(20).map(i=>{let o=t[i.category]||"\xB7",a=i.importance>=7?" \u2605":"",l=i.useCount>0?` (used ${i.useCount}\xD7)`:"";return` ${o}${a} ${i.key}: ${i.value}${l}`}).join(`
686
- `)}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(Ee.existsSync(this.filePath)){let e=JSON.parse(Ee.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{Ee.existsSync(ln)||Ee.mkdirSync(ln,{recursive:!0});let e=Array.from(this.entries.values());Ee.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf-8")}catch{}}loadAgentLanes(){try{if(Ee.existsSync(this.agentLanesPath)){let e=JSON.parse(Ee.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{Ee.existsSync(ln)||Ee.mkdirSync(ln,{recursive:!0});let e={};for(let[t,s]of this.agentLanes)e[t]=Array.from(s.values());Ee.writeFileSync(this.agentLanesPath,JSON.stringify(e,null,2),"utf-8")}catch{}}}});var go=H((gT,fd)=>{"use strict";var Ln=n=>n&&typeof n.message=="string",mo=n=>{if(!n)return;let e=n.cause;if(typeof e=="function"){let t=n.cause();return Ln(t)?t:void 0}else return Ln(e)?e:void 0},ud=(n,e)=>{if(!Ln(n))return"";let t=n.stack||"";if(e.has(n))return t+`
687
- causes have become circular...`;let s=mo(n);return s?(e.add(n),t+`
688
- caused by: `+ud(s,e)):t},cb=n=>ud(n,new Set),dd=(n,e,t)=>{if(!Ln(n))return"";let s=t?"":n.message||"";if(e.has(n))return s+": ...";let r=mo(n);if(r){e.add(n);let i=typeof n.cause=="function";return s+(i?"":": ")+dd(r,e,i)}else return s},ub=n=>dd(n,new Set);fd.exports={isErrorLike:Ln,getErrorCause:mo,stackWithCauses:cb,messageWithCauses:ub}});var yo=H((yT,hd)=>{"use strict";var db=Symbol("circular-ref-tag"),Ms=Symbol("pino-raw-err-ref"),pd=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[Ms]},set:function(n){this[Ms]=n}}});Object.defineProperty(pd,Ms,{writable:!0,value:{}});hd.exports={pinoErrProto:pd,pinoErrorSymbols:{seen:db,rawSymbol:Ms}}});var yd=H((bT,gd)=>{"use strict";gd.exports=vo;var{messageWithCauses:fb,stackWithCauses:pb,isErrorLike:md}=go(),{pinoErrProto:hb,pinoErrorSymbols:mb}=yo(),{seen:bo}=mb,{toString:gb}=Object.prototype;function vo(n){if(!md(n))return n;n[bo]=void 0;let e=Object.create(hb);e.type=gb.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=fb(n),e.stack=pb(n),Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>vo(t)));for(let t in n)if(e[t]===void 0){let s=n[t];md(s)?t!=="cause"&&!Object.prototype.hasOwnProperty.call(s,bo)&&(e[t]=vo(s)):e[t]=s}return delete n[bo],e.raw=n,e}});var vd=H((vT,bd)=>{"use strict";bd.exports=Ds;var{isErrorLike:wo}=go(),{pinoErrProto:yb,pinoErrorSymbols:bb}=yo(),{seen:Ls}=bb,{toString:vb}=Object.prototype;function Ds(n){if(!wo(n))return n;n[Ls]=void 0;let e=Object.create(yb);e.type=vb.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=>Ds(t))),wo(n.cause)&&!Object.prototype.hasOwnProperty.call(n.cause,Ls)&&(e.cause=Ds(n.cause));for(let t in n)if(e[t]===void 0){let s=n[t];wo(s)?Object.prototype.hasOwnProperty.call(s,Ls)||(e[t]=Ds(s)):e[t]=s}return delete n[Ls],e.raw=n,e}});var _d=H((wT,Sd)=>{"use strict";Sd.exports={mapHttpRequest:wb,reqSerializer:xd};var xo=Symbol("pino-raw-req-ref"),wd=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[xo]},set:function(n){this[xo]=n}}});Object.defineProperty(wd,xo,{writable:!0,value:{}});function xd(n){let e=n.info||n.socket,t=Object.create(wd);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 wb(n){return{req:xd(n)}}});var Ed=H((xT,$d)=>{"use strict";$d.exports={mapHttpResponse:xb,resSerializer:kd};var So=Symbol("pino-raw-res-ref"),Ad=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[So]},set:function(n){this[So]=n}}});Object.defineProperty(Ad,So,{writable:!0,value:{}});function kd(n){let e=Object.create(Ad);return e.statusCode=n.headersSent?n.statusCode:null,e.headers=n.getHeaders?n.getHeaders():n._headers,e.raw=n,e}function xb(n){return{res:kd(n)}}});var Ao=H((ST,Td)=>{"use strict";var _o=yd(),Sb=vd(),Ns=_d(),Fs=Ed();Td.exports={err:_o,errWithCause:Sb,mapHttpRequest:Ns.mapHttpRequest,mapHttpResponse:Fs.mapHttpResponse,req:Ns.reqSerializer,res:Fs.resSerializer,wrapErrorSerializer:function(e){return e===_o?e:function(s){return e(_o(s))}},wrapRequestSerializer:function(e){return e===Ns.reqSerializer?e:function(s){return e(Ns.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===Fs.resSerializer?e:function(s){return e(Fs.resSerializer(s))}}}});var ko=H((_T,Cd)=>{"use strict";function _b(n,e){return e}Cd.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=_b;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 Ld=H((AT,Md)=>{"use strict";function $o(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]=$o(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]=$o(n[t]));return e}return n}function Rd(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 Od(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 Pd(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 Hs=Symbol("PATH_NOT_FOUND");function Ab(n,e){let t=n;for(let s of e){if(t==null||typeof t!="object"||t===null||!(s in t))return Hs;t=t[s]}return t}function kb(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 $b(n,e,t,s=!1){for(let r of e){let i=Rd(r);if(i.includes("*"))Id(n,i,t,r,s);else if(s)Pd(n,i);else{let o=Ab(n,i);if(o===Hs)continue;let a=typeof t=="function"?t(o,i):t;Od(n,i,a)}}}function Id(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 c=[...o,l.toString()],d=typeof t=="function"?t(a[l],c):t;a[l]=d}else if(typeof a=="object"&&a!==null)if(r){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],d=typeof t=="function"?t(a[l],c):t;a[l]=d}}else Eb(n,e,t,i,s,r)}function Eb(n,e,t,s,r,i=!1){let o=e.slice(0,s),a=e.slice(s+1),l=[];function c(d,f){if(f===o.length){if(Array.isArray(d))for(let h=0;h<d.length;h++)l[f]=h.toString(),c(d[h],f+1);else if(typeof d=="object"&&d!==null)for(let h in d)l[f]=h,c(d[h],f+1)}else if(f<o.length){let h=o[f];d&&typeof d=="object"&&d!==null&&h in d&&(l[f]=h,c(d[h],f+1))}else if(a.includes("*"))Id(d,a,typeof t=="function"?(m,p)=>{let y=[...l.slice(0,f),...p];return t(m,y)}:t,r,i);else if(i)Pd(d,a);else{let h=typeof t=="function"?t(kb(d,a),[...l.slice(0,f),...a]):t;Od(d,a,h)}}if(o.length===0)c(n,0);else{let d=n;for(let f=0;f<o.length;f++){let h=o[f];if(d==null||typeof d!="object"||d===null)return;d=d[h],l[f]=h}d!=null&&c(d,o.length)}}function Tb(n){if(n.length===0)return null;let e=new Map;for(let t of n){let s=Rd(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 Cb(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 c=l.toString();r.has(c)||r.has("*")?a[l]=t(s[l],r.get(c)||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 Rb(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 Ob(n){if(!Array.isArray(n))throw new TypeError("paths must be an array");for(let e of n)Rb(e)}function Pb(n={}){let{paths:e=[],censor:t="[REDACTED]",serialize:s=JSON.stringify,strict:r=!0,remove:i=!1}=n;Ob(e);let o=Tb(e);return function(l){if(r&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return s?s(l):l;let c=Cb(l,o),d=l,f=t;return typeof t=="function"&&(f=t),$b(c,e,f,i),s===!1?(c.restore=function(){return $o(d)},c):typeof s=="function"?s(c):JSON.stringify(c)}}Md.exports=Pb});var cn=H((kT,Dd)=>{"use strict";var Ib=Symbol("pino.setLevel"),Mb=Symbol("pino.getLevel"),Lb=Symbol("pino.levelVal"),Db=Symbol("pino.levelComp"),Nb=Symbol("pino.useLevelLabels"),Fb=Symbol("pino.useOnlyCustomLevels"),Hb=Symbol("pino.mixin"),jb=Symbol("pino.lsCache"),Bb=Symbol("pino.chindings"),Ub=Symbol("pino.asJson"),Kb=Symbol("pino.write"),qb=Symbol("pino.redactFmt"),Wb=Symbol("pino.time"),Gb=Symbol("pino.timeSliceIndex"),Vb=Symbol("pino.stream"),zb=Symbol("pino.stringify"),Yb=Symbol("pino.stringifySafe"),Jb=Symbol("pino.stringifiers"),Qb=Symbol("pino.end"),Xb=Symbol("pino.formatOpts"),Zb=Symbol("pino.messageKey"),ev=Symbol("pino.errorKey"),tv=Symbol("pino.nestedKey"),nv=Symbol("pino.nestedKeyStr"),sv=Symbol("pino.mixinMergeStrategy"),rv=Symbol("pino.msgPrefix"),iv=Symbol("pino.wildcardFirst"),ov=Symbol.for("pino.serializers"),av=Symbol.for("pino.formatters"),lv=Symbol.for("pino.hooks"),cv=Symbol.for("pino.metadata");Dd.exports={setLevelSym:Ib,getLevelSym:Mb,levelValSym:Lb,levelCompSym:Db,useLevelLabelsSym:Nb,mixinSym:Hb,lsCacheSym:jb,chindingsSym:Bb,asJsonSym:Ub,writeSym:Kb,serializersSym:ov,redactFmtSym:qb,timeSym:Wb,timeSliceIndexSym:Gb,streamSym:Vb,stringifySym:zb,stringifySafeSym:Yb,stringifiersSym:Jb,endSym:Qb,formatOptsSym:Xb,messageKeySym:Zb,errorKeySym:ev,nestedKeySym:tv,wildcardFirstSym:iv,needsMetadataGsym:cv,useOnlyCustomLevelsSym:Fb,formattersSym:av,hooksSym:lv,nestedKeyStrSym:nv,mixinMergeStrategySym:sv,msgPrefixSym:rv}});var To=H(($T,jd)=>{"use strict";var Nd=Ld(),{redactFmtSym:uv,wildcardFirstSym:js}=cn(),Eo=/[^.[\]]+|\[([^[\]]*?)\]/g,Fd="[Redacted]",Hd=!1;function dv(n,e){let{paths:t,censor:s,remove:r}=fv(n),i=t.reduce((l,c)=>{Eo.lastIndex=0;let d=Eo.exec(c),f=Eo.exec(c),h=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(h==="*"&&(h=js),f===null)return l[h]=null,l;if(l[h]===null)return l;let{index:m}=f,p=`${c.substr(m,c.length-1)}`;return l[h]=l[h]||[],h!==js&&l[h].length===0&&l[h].push(...l[js]||[]),h===js&&Object.keys(l).forEach(function(y){l[y]&&l[y].push(p)}),l[h].push(p),l},{}),o={[uv]:Nd({paths:t,censor:s,serialize:e,strict:Hd,remove:r})},a=(...l)=>e(typeof s=="function"?s(...l):s);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=d=>a(d,[c]);else{let d=typeof s=="function"?(f,h)=>s(f,[c,...h]):s;l[c]=Nd({paths:i[c],censor:d,serialize:e,strict:Hd,remove:r})}return l},o)}function fv(n){if(Array.isArray(n))return n={paths:n,censor:Fd},n;let{paths:e,censor:t=Fd,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}}jd.exports=dv});var Kd=H((ET,Ud)=>{"use strict";var pv=()=>"",hv=()=>`,"time":${Date.now()}`,mv=()=>`,"time":${Math.round(Date.now()/1e3)}`,gv=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,yv=1000000n,Bd=1000000000n,bv=BigInt(Date.now())*yv,vv=process.hrtime.bigint(),wv=()=>{let n=process.hrtime.bigint()-vv,e=bv+n,t=e/Bd,s=e%Bd,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"),c=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${c}:${d}:${f}.${s.toString().padStart(9,"0")}Z"`};Ud.exports={nullTime:pv,epochTime:hv,unixTime:mv,isoTime:gv,isoTimeNano:wv}});var Wd=H((TT,qd)=>{"use strict";function xv(n){try{return JSON.stringify(n)}catch{return'"[Circular]"'}}qd.exports=Sv;function Sv(n,e,t){var s=t&&t.stringify||xv,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 c="",d=1-r,f=-1,h=n&&n.length||0,m=0;m<h;){if(n.charCodeAt(m)===37&&m+1<h){switch(f=f>-1?f:0,n.charCodeAt(m+1)){case 100:case 102:if(d>=l||e[d]==null)break;f<m&&(c+=n.slice(f,m)),c+=Number(e[d]),f=m+2,m++;break;case 105:if(d>=l||e[d]==null)break;f<m&&(c+=n.slice(f,m)),c+=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&&(c+=n.slice(f,m));var p=typeof e[d];if(p==="string"){c+="'"+e[d]+"'",f=m+2,m++;break}if(p==="function"){c+=e[d].name||"<anonymous>",f=m+2,m++;break}c+=s(e[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(c+=n.slice(f,m)),c+=String(e[d]),f=m+2,m++;break;case 37:f<m&&(c+=n.slice(f,m)),c+="%",f=m+2,m++,d--;break}++d}++m}return f===-1?n:(f<h&&(c+=n.slice(f)),c)}});var Ro=H((CT,Co)=>{"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));Co.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(););};Co.exports=n}});var Zd=H((RT,Xd)=>{"use strict";var re=require("fs"),_v=require("events"),Av=require("util").inherits,Gd=require("path"),Po=Ro(),kv=require("assert"),Bs=100,Us=Buffer.allocUnsafe(0),$v=16*1024,Vd="buffer",zd="utf8",[Ev,Tv]=(process.versions.node||"0.0").split(".").map(Number),Cv=Ev>=22&&Tv>=7;function Yd(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&&re.mkdirSync(Gd.dirname(n),{recursive:!0});let i=re.openSync(n,s,r);t(null,i)}catch(i){throw t(i),i}else e.mkdir?re.mkdir(Gd.dirname(n),{recursive:!0},i=>{if(i)return t(i);re.open(n,s,r,t)}):re.open(n,s,r,t)}function Ye(n){if(!(this instanceof Ye))return new Ye(n);let{fd:e,dest:t,minLength:s,maxLength:r,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:d,fsync:f,contentMode:h,mode:m}=n||{};e=e||t,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(s||0,16387),this.file=null,this.destroyed=!1,this.minLength=s||0,this.maxLength=r||0,this.maxWrite=i||$v,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=c||!1;let p,y;if(h===Vd)this._writingBuf=Us,this.write=Pv,this.flush=Mv,this.flushSync=Dv,this._actualWrite=Fv,p=()=>re.writeSync(this.fd,this._writingBuf),y=()=>re.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===zd)this._writingBuf="",this.write=Ov,this.flush=Iv,this.flushSync=Lv,this._actualWrite=Nv,p=()=>Buffer.isBuffer(this._writingBuf)?re.writeSync(this.fd,this._writingBuf):re.writeSync(this.fd,this._writingBuf,"utf8"),y=()=>Buffer.isBuffer(this._writingBuf)?re.write(this.fd,this._writingBuf,this.release):re.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${zd}" and "${Vd}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Yd(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,_)=>{if(S){if((S.code==="EAGAIN"||S.code==="EBUSY")&&this.retryEAGAIN(S,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Po(Bs),this.release(void 0,0)}catch(g){this.release(g)}else setTimeout(y,Bs);else this._writing=!1,this.emit("error",S);return}this.emit("write",_);let k=Oo(this._writingBuf,this._len,_);if(this._len=k.len,this._writingBuf=k.writingBuf,this._writingBuf.length){if(!this.sync){y();return}try{do{let g=p(),v=Oo(this._writingBuf,this._len,g);this._len=v.len,this._writingBuf=v.writingBuf}while(this._writingBuf.length)}catch(g){this.release(g);return}}this._fsync&&re.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,Ks(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Rv,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 Oo(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 Rv(n){n.listenerCount("drain")>0&&(n._asyncDrainScheduled=!1,n.emit("drain"))}Av(Ye,_v);function Jd(n,e){return n.length===0?Us:n.length===1?n[0]:Buffer.concat(n,e)}function Ov(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 Pv(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 Qd(n){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,n();else try{re.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 Iv(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&&Qd.call(this,n),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function Mv(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&&Qd.call(this,n),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}Ye.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&&re.close(e,t=>{if(t)return this.emit("error",t)})}),Yd(this.file,this)};Ye.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():Ks(this)))};function Lv(){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)?re.writeSync(this.fd,n):re.writeSync(this.fd,n,"utf8"),t=Oo(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;Po(Bs)}}try{re.fsyncSync(this.fd)}catch{}}function Dv(){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=Us);let n=Us;for(;this._bufs.length||n.length;){n.length<=0&&(n=Jd(this._bufs[0],this._lens[0]));try{let e=re.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;Po(Bs)}}}Ye.prototype.destroy=function(){this.destroyed||Ks(this)};function Nv(){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)?re.writeSync(this.fd,this._writingBuf):re.writeSync(this.fd,this._writingBuf,"utf8");n(null,e)}catch(e){n(e)}else re.write(this.fd,this._writingBuf,n)}function Fv(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Jd(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=re.writeSync(this.fd,this._writingBuf);n(null,e)}catch(e){n(e)}else Cv&&(this._writingBuf=Buffer.from(this._writingBuf)),re.write(this.fd,this._writingBuf,n)}function Ks(n){if(n.fd===-1){n.once("ready",Ks.bind(null,n));return}n._periodicFlushTimer!==void 0&&clearInterval(n._periodicFlushTimer),n.destroyed=!0,n._bufs=[],n._lens=[],kv(typeof n.fd=="number",`sonic.fd must be a number, got ${typeof n.fd}`);try{re.fsync(n.fd,e)}catch{}function e(){n.fd!==1&&n.fd!==2?re.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")}}Ye.SonicBoom=Ye;Ye.default=Ye;Xd.exports=Ye});var Io=H((OT,rf)=>{"use strict";var Je={exit:[],beforeExit:[]},ef={exit:Bv,beforeExit:Uv},un;function Hv(){un===void 0&&(un=new FinalizationRegistry(Kv))}function jv(n){Je[n].length>0||process.on(n,ef[n])}function tf(n){Je[n].length>0||(process.removeListener(n,ef[n]),Je.exit.length===0&&Je.beforeExit.length===0&&(un=void 0))}function Bv(){nf("exit")}function Uv(){nf("beforeExit")}function nf(n){for(let e of Je[n]){let t=e.deref(),s=e.fn;t!==void 0&&s(t,n)}Je[n]=[]}function Kv(n){for(let e of["exit","beforeExit"]){let t=Je[e].indexOf(n);Je[e].splice(t,t+1),tf(e)}}function sf(n,e,t){if(e===void 0)throw new Error("the object can't be undefined");jv(n);let s=new WeakRef(e);s.fn=t,Hv(),un.register(e,s),Je[n].push(s)}function qv(n,e){sf("exit",n,e)}function Wv(n,e){sf("beforeExit",n,e)}function Gv(n){if(un!==void 0){un.unregister(n);for(let e of["exit","beforeExit"])Je[e]=Je[e].filter(t=>{let s=t.deref();return s&&s!==n}),tf(e)}}rf.exports={register:qv,registerBeforeExit:Wv,unregister:Gv}});var of=H((PT,Vv)=>{Vv.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 lf=H((IT,af)=>{"use strict";function zv(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())),c=Atomics.waitAsync(n,e,a,l);c.async?c.value.then(o):setImmediate(o)};o()}function Yv(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())),c=Atomics.waitAsync(n,e,t,l);c.async?c.value.then(d=>{if(d==="ok"){r(null,"ok");return}o()}):setImmediate(o)};o()}af.exports={wait:zv,waitDiff:Yv}});var uf=H((MT,cf)=>{"use strict";cf.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Sf=H((LT,xf)=>{"use strict";var{version:Jv}=of(),{EventEmitter:Qv}=require("events"),{Worker:Xv}=require("worker_threads"),{join:Zv}=require("path"),{pathToFileURL:ew}=require("url"),{wait:tw}=lf(),{WRITE_INDEX:bt,READ_INDEX:Ht,SEQ_INDEX:Mo}=uf(),nw=require("buffer"),sw=require("assert"),R=Symbol("kImpl"),rw=nw.constants.MAX_STRING_LENGTH;function df(){}function Fo(n,e){Atomics.add(n[R].state,Mo,1),e(),Atomics.add(n[R].state,Mo,1),Atomics.notify(n[R].state,Mo)}function ff(n){Fo(n,()=>{Atomics.store(n[R].state,Ht,0),Atomics.store(n[R].state,bt,0)})}var Dn=class{constructor(e){this._value=e}deref(){return this._value}},qs=class{register(){}unregister(){}},iw=process.env.NODE_V8_COVERAGE?qs:global.FinalizationRegistry||qs,ow=process.env.NODE_V8_COVERAGE?Dn:global.WeakRef||Dn,pf=new iw(n=>{n.exited||n.terminate()});function aw(n,e){let{filename:t,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Zv(__dirname,"lib","worker.js"),o=new Xv(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:t.indexOf("file://")===0?t:ew(t).href,dataBuf:n[R].dataBuf,stateBuf:n[R].stateBuf,workerData:{$context:{threadStreamVersion:Jv},...s}}});return o.stream=new Dn(n),o.on("message",lw),o.on("exit",gf),pf.register(n,o),o}function hf(n){sw(!n[R].sync),n[R].needDrain&&(n[R].needDrain=!1,n.emit("drain"))}function mf(n){for(;;){let e=Atomics.load(n[R].state,bt),t=n[R].data.length-e;if(t>0){if(n[R].bufLen===0){n[R].flushing=!1,n[R].ending?Ho(n):n[R].needDrain&&process.nextTick(hf,n);return}vf(n,t,df);continue}if(t===0){if(e===0&&n[R].bufLen===0)return;Ws(n,()=>{n.destroyed||(ff(n),mf(n))});return}He(n,new Error("overwritten"));return}}function lw(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 ow(e),Ws(e,()=>{e[R].ready=!0,e.emit("ready")});break;case"ERROR":He(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"){He(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:He(e,new Error("this should not happen: "+n.code))}}function gf(n){let e=this.stream.deref();e!==void 0&&(pf.unregister(e),e.worker.exited=!0,e.worker.off("exit",gf),He(e,n!==0?new Error("the worker thread exited"):null))}var Do=class extends Qv{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=aw(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 No(this,new Error("the worker has exited")),!1;if(this[R].ending)return No(this,new Error("the worker is ending")),!1;if(this[R].flushing&&this[R].bufLen+t.length>=rw)try{Lo(this),this[R].flushing=!0}catch(s){return He(this,s),!1}if(this[R].buf.push(t),this[R].bufLen+=t.length,this[R].sync)try{return Lo(this),!0}catch(s){return He(this,s),!1}return this[R].flushing||(this[R].flushing=!0,setImmediate(mf,this)),this[R].needDrain=this[R].data.length-this[R].bufLen-Atomics.load(this[R].state,bt)<=0,!this[R].needDrain}end(){this[R].destroyed||(this[R].ending=!0,Ho(this))}flush(e){e=typeof e=="function"?e:df,yf(this,t=>{if(t){process.nextTick(e,t);return}bf(this,e)})}flushSync(){this[R].destroyed||(Lo(this),wf(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 yf(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(yf,n,e);return}Ws(n,e)}function Ws(n,e){let t=Atomics.load(n[R].state,bt);tw(n[R].state,Ht,t,1/0,(s,r)=>{if(s){He(n,s),e(s);return}if(r!=="ok"){Ws(n,e);return}e()})}function bf(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].ready){let s=()=>{i(),bf(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),He(n,s),process.nextTick(e,s)}}function cw(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 No(n,e){setImmediate(()=>{n.emit("error",e)})}function He(n,e){n[R].destroyed||(n[R].destroyed=!0,cw(n,e),e&&(n[R].errored=e,No(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 vf(n,e,t){let r=Atomics.load(n[R].state,bt),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 Fo(n,()=>{Atomics.store(n[R].state,bt,r)}),t(),!0}function Ho(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,Ht);Fo(n,()=>{Atomics.store(n[R].state,bt,-1)});let t=0;for(;e!==-1;){if(Atomics.wait(n[R].state,Ht,e,1e3),e=Atomics.load(n[R].state,Ht),e===-2){He(n,new Error("end() failed"));return}if(++t===10){He(n,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{n[R].finished=!0,n.emit("finish")})}catch(e){He(n,e)}}}function Lo(n){let e=()=>{n[R].ending?Ho(n):n[R].needDrain&&process.nextTick(hf,n)};for(n[R].flushing=!1;n[R].bufLen!==0;){let t=Atomics.load(n[R].state,bt),s=n[R].data.length-t;if(s===0){wf(n),ff(n);continue}else if(s<0)throw new Error("overwritten");vf(n,s,e)}}function wf(n){if(n[R].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(n[R].state,bt),t=0;for(;;){let s=Atomics.load(n[R].state,Ht);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(n[R].state,Ht,s,1e3);else break;if(++t===10)throw new Error("_flushSync took too long (10s)")}}xf.exports=Do});var Uo=H((DT,kf)=>{"use strict";var{createRequire:uw}=require("module"),{existsSync:dw}=require("node:fs"),fw=ko(),{join:jo,isAbsolute:Af,sep:pw}=require("node:path"),{fileURLToPath:hw}=require("node:url"),mw=Ro(),Bo=Io(),gw=Sf();function yw(n){Bo.register(n,Sw),Bo.registerBeforeExit(n,_w),n.on("close",function(){Bo.unregister(n)})}function bw(){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 vw(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&&_f(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(_f(o)){s=!0;continue}}t.push(i)}return s?t.join(" "):n}function _f(n){let e=ww(n);if(!e)return!1;let t=e;if(t.startsWith("file://"))try{t=hw(t)}catch{return!1}return Af(t)&&!dw(t)}function ww(n){let e=n[0],t=n[n.length-1];return e==='"'&&t==='"'||e==="'"&&t==="'"?n.slice(1,-1):n}function xw(n,e,t,s,r){if(!t.execArgv&&bw()&&require.main===void 0&&(t={...t,execArgv:[]}),!t.env&&process.env.NODE_OPTIONS){let l=vw(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(t={...t,env:{...process.env,NODE_OPTIONS:l}})}t={...t,name:r};let i=new gw({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&&yw(i)}function a(){i.closed||(i.flushSync(),mw(100),i.end())}return i}function Sw(n){n.ref(),n.flushSync(),n.end(),n.once("close",function(){n.unref()})}function _w(n){n.flushSync()}function Aw(n){let{pipeline:e,targets:t,levels:s,dedupe:r,worker:i={},caller:o=fw(),sync:a=!1}=n,l={...n.options},c=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"]||jo(__dirname,"worker.js"),l.targets=t.filter(p=>p.target).map(p=>({...p,target:m(p.target)})),l.pipelines=t.filter(p=>p.pipeline).map(p=>p.pipeline.map(y=>({...y,level:p.level,target:m(y.target)})))):e&&(f=d["pino-worker"]||jo(__dirname,"worker.js"),l.pipelines=[e.map(p=>({...p,target:m(p.target)}))]),s&&(l.levels=s),r&&(l.dedupe=r),l.pinoWillSendConfig=!0;let h=t||e?"pino.transport":f;return xw(m(f),l,i,a,h);function m(p){if(p=d[p]||p,Af(p)||p.indexOf("file://")===0)return p;if(p==="pino/file")return jo(__dirname,"..","file.js");let y;for(let S of c)try{let _=S==="node:repl"?process.cwd()+pw:S;y=uw(_).resolve(p);break}catch{continue}if(!y)throw new Error(`unable to determine transport target for "${p}"`);return y}}kf.exports=Aw});var zs=H((NT,Ff)=>{"use strict";var kw=require("node:diagnostics_channel"),$f=Wd(),{mapHttpRequest:$w,mapHttpResponse:Ew}=Ao(),qo=Zd(),Ef=Io(),{lsCacheSym:Tw,chindingsSym:Pf,writeSym:Tf,serializersSym:If,formatOptsSym:Cf,endSym:Cw,stringifiersSym:Mf,stringifySym:Lf,stringifySafeSym:Wo,wildcardFirstSym:Df,nestedKeySym:Rw,formattersSym:Nf,messageKeySym:Ow,errorKeySym:Pw,nestedKeyStrSym:Iw,msgPrefixSym:Gs}=cn(),{isMainThread:Mw}=require("worker_threads"),Lw=Uo(),[Dw]=process.versions.node.split(".").map(n=>Number(n)),Rf=kw.tracingChannel("pino_asJson"),Ko=Dw>=25?n=>JSON.stringify(n):Fw;function dn(){}function Nw(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=$w(s):typeof s.setHeader=="function"&&(s=Ew(s)));let o;i===null&&r.length===0?o=[null]:(i=r.shift(),o=r),typeof this[Gs]=="string"&&i!==void 0&&i!==null&&(i=this[Gs]+i),this[Tf](s,$f(i,o,this[Cf]),n)}else{let i=s===void 0?r.shift():s;typeof this[Gs]=="string"&&i!==void 0&&i!==null&&(i=this[Gs]+i),this[Tf](null,$f(i,r,this[Cf]),n)}}}function Fw(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 Hw(n,e,t,s){if(Rf.hasSubscribers===!1)return Of.call(this,n,e,t,s);let r={instance:this,arguments};return Rf.traceSync(Of,r,this,n,e,t,s)}function Of(n,e,t,s){let r=this[Lf],i=this[Wo],o=this[Mf],a=this[Cw],l=this[Pf],c=this[If],d=this[Nf],f=this[Ow],h=this[Pw],m=this[Tw][t]+s;m=m+l;let p;d.log&&(n=d.log(n));let y=o[Df],S="";for(let k in n)if(p=n[k],Object.prototype.hasOwnProperty.call(n,k)&&p!==void 0){c[k]?p=c[k](p):k===h&&c.err&&(p=c.err(p));let A=o[k]||y;switch(typeof p){case"undefined":case"function":continue;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":A&&(p=A(p));break;case"string":p=(A||Ko)(p);break;default:p=(A||r)(p,i)}if(p===void 0)continue;let g=Ko(k);S+=","+g+":"+p}let _="";if(e!==void 0){p=c[f]?c[f](e):e;let k=o[f]||y;switch(typeof p){case"function":break;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":k&&(p=k(p)),_=',"'+f+'":'+p;break;case"string":p=(k||Ko)(p),_=',"'+f+'":'+p;break;default:p=(k||r)(p,i),_=',"'+f+'":'+p}}return this[Rw]&&S?m+this[Iw]+S.slice(1)+"}"+_+a:m+S+_+a}function jw(n,e){let t,s=n[Pf],r=n[Lf],i=n[Wo],o=n[Mf],a=o[Df],l=n[If],c=n[Nf].bindings;e=c(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 Bw(n){return n.write!==n.constructor.prototype.write}function Vs(n){let e=new qo(n);return e.on("error",t),!n.sync&&Mw&&(Ef.register(e,Uw),e.on("close",function(){Ef.unregister(e)})),e;function t(s){if(s.code==="EPIPE"){e.write=dn,e.end=dn,e.flushSync=dn,e.destroy=dn;return}e.removeListener("error",t),e.emit("error",s)}}function Uw(n,e){n.destroyed||(e==="beforeExit"?(n.flush(),n.on("drain",function(){n.end()})):n.flushSync())}function Kw(n){return function(t,s,r={},i){if(typeof r=="string")i=Vs({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=Vs({dest:i})}else if(r instanceof qo||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof qo||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=Lw({caller:s,...r.transport,levels:l})}if(r=Object.assign({},n,r),r.serializers=Object.assign({},n.serializers,r.serializers),r.formatters=Object.assign({},n.formatters,r.formatters),r.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=r;return o===!1&&(r.level="silent"),a||(r.onChild=dn),i||(Bw(process.stdout)?i=process.stdout:i=Vs({fd:process.stdout.fd||1})),{opts:r,stream:i}}}function qw(n,e){try{return JSON.stringify(n)}catch{try{return(e||this[Wo])(n)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Ww(n,e,t){return{level:n,bindings:e,log:t}}function Gw(n){let e=Number(n);return typeof n=="string"&&Number.isFinite(e)?e:n===void 0?1:n}Ff.exports={noop:dn,buildSafeSonicBoom:Vs,asChindings:jw,asJson:Hw,genLog:Nw,createArgsNormalizer:Kw,stringify:qw,buildFormatters:Ww,normalizeDestFileDescriptor:Gw}});var Ys=H((FT,Hf)=>{var Vw={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},zw={ASC:"ASC",DESC:"DESC"};Hf.exports={DEFAULT_LEVELS:Vw,SORTING_ORDER:zw}});var zo=H((HT,Kf)=>{"use strict";var{lsCacheSym:Yw,levelValSym:Go,useOnlyCustomLevelsSym:Jw,streamSym:Qw,formattersSym:Xw,hooksSym:Zw,levelCompSym:jf}=cn(),{noop:ex,genLog:jt}=zs(),{DEFAULT_LEVELS:st,SORTING_ORDER:Bf}=Ys(),Uf={fatal:n=>{let e=jt(st.fatal,n);return function(...t){let s=this[Qw];if(e.call(this,...t),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:n=>jt(st.error,n),warn:n=>jt(st.warn,n),info:n=>jt(st.info,n),debug:n=>jt(st.debug,n),trace:n=>jt(st.trace,n)},Vo=Object.keys(st).reduce((n,e)=>(n[st[e]]=e,n),{}),tx=Object.keys(Vo).reduce((n,e)=>(n[e]='{"level":'+Number(e),n),{});function nx(n){let e=n[Xw].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[Yw]=s,n}function sx(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 rx(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[Go],r=this[Go]=t[n],i=this[Jw],o=this[jf],a=this[Zw].logMethod;for(let l in t){if(o(t[l],r)===!1){this[l]=ex;continue}this[l]=sx(l,i)?Uf[l](a):jt(t[l],a)}this.emit("level-change",n,r,e[s],s,this)}function ix(n){let{levels:e,levelVal:t}=this;return e&&e.labels?e.labels[t]:""}function ox(n){let{values:e}=this.levels,t=e[n];return t!==void 0&&this[jf](t,this[Go])}function ax(n,e,t){return n===Bf.DESC?e<=t:e>=t}function lx(n){return typeof n=="string"?ax.bind(null,n):n}function cx(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:Vo,t),r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:st,n);return{labels:s,values:r}}function ux(n,e,t){if(typeof n=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),t?[]:Object.keys(Vo).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:st,e);if(!(n in s))throw Error(`default level:${n} must be included in custom levels`)}function dx(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 fx(n){if(typeof n!="function"&&!(typeof n=="string"&&Object.values(Bf).includes(n)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Kf.exports={initialLsCache:tx,genLsCache:nx,levelMethods:Uf,getLevel:ix,setLevel:rx,isLevelEnabled:ox,mappings:cx,assertNoLevelCollisions:dx,assertDefaultLevelFound:ux,genLevelComparison:lx,assertLevelComparison:fx}});var Yo=H((jT,qf)=>{"use strict";qf.exports={version:"10.3.1"}});var Xf=H((UT,Qf)=>{"use strict";var{EventEmitter:px}=require("node:events"),{lsCacheSym:hx,levelValSym:mx,setLevelSym:Qo,getLevelSym:Wf,chindingsSym:Qs,mixinSym:gx,asJsonSym:Vf,writeSym:yx,mixinMergeStrategySym:bx,timeSym:vx,timeSliceIndexSym:wx,streamSym:zf,serializersSym:Bt,formattersSym:Nn,errorKeySym:xx,messageKeySym:Sx,useOnlyCustomLevelsSym:_x,needsMetadataGsym:Ax,redactFmtSym:kx,stringifySym:$x,formatOptsSym:Ex,stringifiersSym:Tx,msgPrefixSym:Xo,hooksSym:Cx}=cn(),{getLevel:Rx,setLevel:Ox,isLevelEnabled:Px,mappings:Ix,initialLsCache:Mx,genLsCache:Lx,assertNoLevelCollisions:Dx}=zo(),{asChindings:Zo,asJson:Nx,buildFormatters:Jo,stringify:Gf,noop:Yf}=zs(),{version:Fx}=Yo(),Hx=To(),jx=class{},Jf={constructor:jx,child:Bx,bindings:Ux,setBindings:Kx,flush:Gx,isLevelEnabled:Px,version:Fx,get level(){return this[Wf]()},set level(n){this[Qo](n)},get levelVal(){return this[mx]},set levelVal(n){throw Error("levelVal is read-only")},get msgPrefix(){return this[Xo]},get[Symbol.toStringTag](){return"Pino"},[hx]:Mx,[yx]:Wx,[Vf]:Nx,[Wf]:Rx,[Qo]:Ox};Object.setPrototypeOf(Jf,px.prototype);Qf.exports=function(){return Object.create(Jf)};var Js=n=>n;function Bx(n,e){if(!n)throw Error("missing bindings for child Pino");let t=this[Bt],s=this[Nn],r=Object.create(this);if(e==null)return r[Nn].bindings!==Js&&(r[Nn]=Jo(s.level,Js,s.log)),r[Qs]=Zo(r,n),this.onChild!==Yf&&this.onChild(r),r;if(e.hasOwnProperty("serializers")===!0){r[Bt]=Object.create(null);for(let c in t)r[Bt][c]=t[c];let a=Object.getOwnPropertySymbols(t);for(var i=0;i<a.length;i++){let c=a[i];r[Bt][c]=t[c]}for(let c in e.serializers)r[Bt][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];r[Bt][c]=e.serializers[c]}}else r[Bt]=t;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;r[Nn]=Jo(a||s.level,l||Js,c||s.log)}else r[Nn]=Jo(s.level,Js,s.log);if(e.hasOwnProperty("customLevels")===!0&&(Dx(this.levels,e.customLevels),r.levels=Ix(e.customLevels,r[_x]),Lx(r)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){r.redact=e.redact;let a=Hx(r.redact,Gf),l={stringify:a[kx]};r[$x]=Gf,r[Tx]=a,r[Ex]=l}if(typeof e.msgPrefix=="string"&&(r[Xo]=(this[Xo]||"")+e.msgPrefix),r[Qs]=Zo(r,n),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;r[Qo](a)}return this.onChild(r),r}function Ux(){let e=`{${this[Qs].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function Kx(n){let e=Zo(this,n);this[Qs]=e}function qx(n,e){return Object.assign(e,n)}function Wx(n,e,t){let s=this[vx](),r=this[gx],i=this[xx],o=this[Sx],a=this[bx]||qx,l,c=this[Cx].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[Vf](l,e,t,s),f=this[zf];f[Ax]===!0&&(f.lastLevel=t,f.lastObj=l,f.lastMsg=e,f.lastTime=s.slice(this[wx]),f.lastLogger=this),f.write(c?c(d):d)}function Gx(n){if(n!=null&&typeof n!="function")throw Error("callback must be a function");let e=this[zf];typeof e.flush=="function"?e.flush(n||Yf):n&&n()}});var np=H((sa,tp)=>{"use strict";var{hasOwnProperty:Fn}=Object.prototype,Kt=na();Kt.configure=na;Kt.stringify=Kt;Kt.default=Kt;sa.stringify=Kt;sa.configure=na;tp.exports=Kt;var Vx=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function Ot(n){return n.length<5e3&&!Vx.test(n)?`"${n}"`:JSON.stringify(n)}function ea(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 zx=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function ta(n){return zx.call(n)!==void 0&&n.length!==0}function Zf(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 Yx(n){if(Fn.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 Jx(n){let e;if(Fn.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 Qx(n,e){let t;if(Fn.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 ep(n,e){let t;if(Fn.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 Ut(n){return n===1?"1 item":`${n} items`}function Xx(n){let e=new Set;for(let t of n)(typeof t=="string"||typeof t=="number")&&e.add(String(t));return e}function Zx(n){if(Fn.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 na(n){n={...n};let e=Zx(n);e&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let t=Yx(n),s=Qx(n,"bigint"),r=Jx(n),i=typeof r=="function"?r:void 0,o=ep(n,"maximumDepth"),a=ep(n,"maximumBreadth");function l(m,p,y,S,_,k){let A=p[m];switch(typeof A=="object"&&A!==null&&typeof A.toJSON=="function"&&(A=A.toJSON(m)),A=S.call(p,m,A),typeof A){case"string":return Ot(A);case"object":{if(A===null)return"null";if(y.indexOf(A)!==-1)return t;let g="",v=",",b=k;if(Array.isArray(A)){if(A.length===0)return"[]";if(o<y.length+1)return'"[Array]"';y.push(A),_!==""&&(k+=_,g+=`
689
- ${k}`,v=`,
690
- ${k}`);let F=Math.min(A.length,a),j=0;for(;j<F-1;j++){let C=l(String(j),A,y,S,_,k);g+=C!==void 0?C:"null",g+=v}let V=l(String(j),A,y,S,_,k);if(g+=V!==void 0?V:"null",A.length-1>a){let C=A.length-a-1;g+=`${v}"... ${Ut(C)} not stringified"`}return _!==""&&(g+=`
691
- ${b}`),y.pop(),`[${g}]`}let w=Object.keys(A),x=w.length;if(x===0)return"{}";if(o<y.length+1)return'"[Object]"';let T="",P="";_!==""&&(k+=_,v=`,
692
- ${k}`,T=" ");let $=Math.min(x,a);r&&!ta(A)&&(w=ea(w,i)),y.push(A);for(let F=0;F<$;F++){let j=w[F],V=l(j,A,y,S,_,k);V!==void 0&&(g+=`${P}${Ot(j)}:${T}${V}`,P=v)}if(x>a){let F=x-a;g+=`${P}"...":${T}"${Ut(F)} not stringified"`,P=v}return _!==""&&P.length>1&&(g=`
693
- ${k}${g}
694
- ${b}`),y.pop(),`{${g}}`}case"number":return isFinite(A)?String(A):e?e(A):"null";case"boolean":return A===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(A);default:return e?e(A):void 0}}function c(m,p,y,S,_,k){switch(typeof p=="object"&&p!==null&&typeof p.toJSON=="function"&&(p=p.toJSON(m)),typeof p){case"string":return Ot(p);case"object":{if(p===null)return"null";if(y.indexOf(p)!==-1)return t;let A=k,g="",v=",";if(Array.isArray(p)){if(p.length===0)return"[]";if(o<y.length+1)return'"[Array]"';y.push(p),_!==""&&(k+=_,g+=`
695
- ${k}`,v=`,
696
- ${k}`);let x=Math.min(p.length,a),T=0;for(;T<x-1;T++){let $=c(String(T),p[T],y,S,_,k);g+=$!==void 0?$:"null",g+=v}let P=c(String(T),p[T],y,S,_,k);if(g+=P!==void 0?P:"null",p.length-1>a){let $=p.length-a-1;g+=`${v}"... ${Ut($)} not stringified"`}return _!==""&&(g+=`
697
- ${A}`),y.pop(),`[${g}]`}y.push(p);let b="";_!==""&&(k+=_,v=`,
698
- ${k}`,b=" ");let w="";for(let x of S){let T=c(x,p[x],y,S,_,k);T!==void 0&&(g+=`${w}${Ot(x)}:${b}${T}`,w=v)}return _!==""&&w.length>1&&(g=`
699
- ${k}${g}
700
- ${A}`),y.pop(),`{${g}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function d(m,p,y,S,_){switch(typeof p){case"string":return Ot(p);case"object":{if(p===null)return"null";if(typeof p.toJSON=="function"){if(p=p.toJSON(m),typeof p!="object")return d(m,p,y,S,_);if(p===null)return"null"}if(y.indexOf(p)!==-1)return t;let k=_;if(Array.isArray(p)){if(p.length===0)return"[]";if(o<y.length+1)return'"[Array]"';y.push(p),_+=S;let T=`
701
- ${_}`,P=`,
702
- ${_}`,$=Math.min(p.length,a),F=0;for(;F<$-1;F++){let V=d(String(F),p[F],y,S,_);T+=V!==void 0?V:"null",T+=P}let j=d(String(F),p[F],y,S,_);if(T+=j!==void 0?j:"null",p.length-1>a){let V=p.length-a-1;T+=`${P}"... ${Ut(V)} not stringified"`}return T+=`
703
- ${k}`,y.pop(),`[${T}]`}let A=Object.keys(p),g=A.length;if(g===0)return"{}";if(o<y.length+1)return'"[Object]"';_+=S;let v=`,
704
- ${_}`,b="",w="",x=Math.min(g,a);ta(p)&&(b+=Zf(p,v,a),A=A.slice(p.length),x-=p.length,w=v),r&&(A=ea(A,i)),y.push(p);for(let T=0;T<x;T++){let P=A[T],$=d(P,p[P],y,S,_);$!==void 0&&(b+=`${w}${Ot(P)}: ${$}`,w=v)}if(g>a){let T=g-a;b+=`${w}"...": "${Ut(T)} not stringified"`,w=v}return w!==""&&(b=`
705
- ${_}${b}
706
- ${k}`),y.pop(),`{${b}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function f(m,p,y){switch(typeof p){case"string":return Ot(p);case"object":{if(p===null)return"null";if(typeof p.toJSON=="function"){if(p=p.toJSON(m),typeof p!="object")return f(m,p,y);if(p===null)return"null"}if(y.indexOf(p)!==-1)return t;let S="",_=p.length!==void 0;if(_&&Array.isArray(p)){if(p.length===0)return"[]";if(o<y.length+1)return'"[Array]"';y.push(p);let b=Math.min(p.length,a),w=0;for(;w<b-1;w++){let T=f(String(w),p[w],y);S+=T!==void 0?T:"null",S+=","}let x=f(String(w),p[w],y);if(S+=x!==void 0?x:"null",p.length-1>a){let T=p.length-a-1;S+=`,"... ${Ut(T)} not stringified"`}return y.pop(),`[${S}]`}let k=Object.keys(p),A=k.length;if(A===0)return"{}";if(o<y.length+1)return'"[Object]"';let g="",v=Math.min(A,a);_&&ta(p)&&(S+=Zf(p,",",a),k=k.slice(p.length),v-=p.length,g=","),r&&(k=ea(k,i)),y.push(p);for(let b=0;b<v;b++){let w=k[b],x=f(w,p[w],y);x!==void 0&&(S+=`${g}${Ot(w)}:${x}`,g=",")}if(A>a){let b=A-a;S+=`${g}"...":"${Ut(b)} not stringified"`}return y.pop(),`{${S}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function h(m,p,y){if(arguments.length>1){let S="";if(typeof y=="number"?S=" ".repeat(Math.min(y,10)):typeof y=="string"&&(S=y.slice(0,10)),p!=null){if(typeof p=="function")return l("",{"":m},[],p,S,"");if(Array.isArray(p))return c("",m,[],Xx(p),S,"")}if(S.length!==0)return d("",m,[],S,"")}return f("",m,[])}return h}});var op=H((KT,ip)=>{"use strict";var ra=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:rp}=Ys(),eS=rp.info;function tS(n,e){n=n||[],e=e||{dedupe:!1};let t=Object.create(rp);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:c,minLevel:0,lastId:0,streams:[],clone:d,[ra]:!0,streamLevels:t};return Array.isArray(n)?n.forEach(a,s):a.call(s,n),n=null,s;function r(f){let h,m=this.lastLevel,{streams:p}=this,y=0,S;for(let _=nS(p.length,e.dedupe);rS(_,p.length,e.dedupe);_=sS(_,e.dedupe))if(h=p[_],h.level<=m){if(y!==0&&y!==h.level)break;if(S=h.stream,S[ra]){let{lastTime:k,lastMsg:A,lastObj:g,lastLogger:v}=this;S.lastLevel=m,S.lastTime=k,S.lastMsg=A,S.lastObj=g,S.lastLogger=v}S.write(f),e.dedupe&&(y=h.level)}else if(!e.dedupe)break}function i(...f){for(let{stream:h}of this.streams)typeof h.emit=="function"&&h.emit(...f)}function o(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync()}function a(f){if(!f)return s;let h=typeof f.write=="function"||f.stream,m=f.write?f:f.stream;if(!h)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:p,streamLevels:y}=this,S;typeof f.levelVal=="number"?S=f.levelVal:typeof f.level=="string"?S=y[f.level]:typeof f.level=="number"?S=f.level:S=eS;let _={stream:m,level:S,levelVal:void 0,id:++s.lastId};return p.unshift(_),p.sort(sp),this.minLevel=p[0].level,s}function l(f){let{streams:h}=this,m=h.findIndex(p=>p.id===f);return m>=0&&(h.splice(m,1),h.sort(sp),this.minLevel=h.length>0?h[0].level:-1),s}function c(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync(),f.end()}function d(f){let h=new Array(this.streams.length);for(let m=0;m<h.length;m++)h[m]={level:f,stream:this.streams[m].stream};return{write:r,add:a,remove:l,minLevel:f,streams:h,clone:d,emit:i,flushSync:o,[ra]:!0}}}function sp(n,e){return n.level-e.level}function nS(n,e){return e?n-1:0}function sS(n,e){return e?n-1:n+1}function rS(n,e,t){return t?n>=0:n<e}ip.exports=tS});var la=H((qT,je)=>{"use strict";var iS=require("node:os"),hp=Ao(),oS=ko(),aS=To(),mp=Kd(),lS=Xf(),gp=cn(),{configure:cS}=np(),{assertDefaultLevelFound:uS,mappings:yp,genLsCache:dS,genLevelComparison:fS,assertLevelComparison:pS}=zo(),{DEFAULT_LEVELS:bp,SORTING_ORDER:hS}=Ys(),{createArgsNormalizer:mS,asChindings:gS,buildSafeSonicBoom:ap,buildFormatters:yS,stringify:ia,normalizeDestFileDescriptor:lp,noop:bS}=zs(),{version:vS}=Yo(),{chindingsSym:cp,redactFmtSym:wS,serializersSym:up,timeSym:xS,timeSliceIndexSym:SS,streamSym:_S,stringifySym:dp,stringifySafeSym:oa,stringifiersSym:fp,setLevelSym:AS,endSym:kS,formatOptsSym:$S,messageKeySym:ES,errorKeySym:TS,nestedKeySym:CS,mixinSym:RS,levelCompSym:OS,useOnlyCustomLevelsSym:PS,formattersSym:pp,hooksSym:IS,nestedKeyStrSym:MS,mixinMergeStrategySym:LS,msgPrefixSym:DS}=gp,{epochTime:vp,nullTime:NS}=mp,{pid:FS}=process,HS=iS.hostname(),jS=hp.err,BS={level:"info",levelComparison:hS.ASC,levels:bp,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:FS,hostname:HS},serializers:Object.assign(Object.create(null),{err:jS}),formatters:Object.assign(Object.create(null),{bindings(n){return n},level(n,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:vp,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},US=mS(BS),KS=Object.assign(Object.create(null),hp);function aa(...n){let e={},{opts:t,stream:s}=US(e,oS(),...n);t.level&&typeof t.level=="string"&&bp[t.level.toLowerCase()]!==void 0&&(t.level=t.level.toLowerCase());let{redact:r,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:d,base:f,name:h,level:m,customLevels:p,levelComparison:y,mixin:S,mixinMergeStrategy:_,useOnlyCustomLevels:k,formatters:A,hooks:g,depthLimit:v,edgeLimit:b,onChild:w,msgPrefix:x}=t,T=cS({maximumDepth:v,maximumBreadth:b}),P=yS(A.level,A.bindings,A.log),$=ia.bind({[oa]:T}),F=r?aS(r,$):{},j=r?{stringify:F[wS]}:{stringify:$},V="}"+(i?`\r
521
+ `)}search(e,t){let r=e.toLowerCase(),s=r.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 c=0,u="partial";l.key.toLowerCase()===r&&(c+=10,u="exact"),l.key.toLowerCase().includes(r)&&(c+=5),l.value.toLowerCase().includes(r)&&(c+=3);for(let p of s)l.key.toLowerCase().includes(p)&&(c+=2),l.value.toLowerCase().includes(p)&&(c+=1),l.tags.some(h=>h.toLowerCase().includes(p))&&(c+=2,u=u==="exact"?"exact":"tag");c*=1+l.importance*.1,c*=1+l.useCount*.2;let d=(Date.now()-l.updatedAt)/(10080*60*1e3);c*=Math.max(.3,1-d*.1),c>.5&&o.push({entry:l,relevanceScore:c,matchType:u})}return o.sort((l,c)=>c.relevanceScore-l.relevanceScore).slice(0,i)}getAll(e){let t=Array.from(this.entries.values());return e?t.filter(r=>r.category===e):t}getByFile(e){return Array.from(this.entries.values()).filter(t=>t.relatedFiles.some(r=>r.includes(e)||e.includes(r)))}getTopMemories(e=15){return Array.from(this.entries.values()).sort((t,r)=>{let s=t.importance*(1+t.useCount*.3)*(1+Math.log1p(t.accessCount)*.1);return r.importance*(1+r.useCount*.3)*(1+Math.log1p(r.accessCount)*.1)-s}).slice(0,e)}getSummary(){let e=this.getTopMemories(15);if(e.length===0)return"";let t={};for(let s of e){let i=s.category;t[i]||(t[i]=[]),t[i].push(`${s.key}: ${s.value}`)}let r=["## Project Memory"];for(let[s,i]of Object.entries(t)){r.push(`### ${s}`);for(let o of i)r.push(`- ${o}`)}return r.join(`
522
+ `)}getStats(){let e=this.getAll(),t={},r={};for(let s of e)t[s.category]=(t[s.category]||0)+1,r[s.createdBy]=(r[s.createdBy]||0)+1;return{totalEntries:e.length,byCategory:t,byAgent:r,topAccessed:e.sort((s,i)=>i.accessCount-s.accessCount).slice(0,5),recentlyAdded:e.sort((s,i)=>i.createdAt-s.createdAt).slice(0,5),totalAccessCount:e.reduce((s,i)=>s+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),r=t.slice(0,Math.max(10,t.length-e)),s={};for(let o of r){let a=o.category;s[a]||(s[a]=[]),s[a].push(o)}let i=0;for(let[o,a]of Object.entries(s)){if(a.length<2)continue;let l=`[consolidated] ${o} (${a.length} items)`,c=a.map(p=>`${p.key}: ${p.value}`).join("; "),u=a.map(p=>p.key);this.set(l,c.slice(0,500),{category:o,importance:3,tags:["consolidated"]});let d=this.entries.get(l);d&&(d.consolidatedFrom=u);for(let p of a)this.entries.delete(p.key),i++}return i>0&&this.save(),i}learnFromToolResult(e,t,r,s,i="hablas"){if(!(r.length<20)){if(!s){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: ${r.slice(0,200)}`,{category:"error",importance:6,createdBy:i,tags:["auto-learned","error",e]})}if(e==="list_dir"&&s){let o=t.path||".";this.set(`structure:${o}`,r.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(`
523
+ `)}autoImportance(e,t){let s={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)&&(s=Math.min(10,s+2)),s}autoTag(e,t){let r=[t];return/\b(react|vue|angular|svelte|next|nuxt)\b/i.test(e)&&r.push("frontend"),/\b(express|fastify|nest|koa|hapi)\b/i.test(e)&&r.push("backend"),/\b(postgres|mysql|mongo|redis|sqlite)\b/i.test(e)&&r.push("database"),/\b(docker|kubernetes|k8s|ci\/cd|deploy)\b/i.test(e)&&r.push("devops"),/\b(test|jest|vitest|cypress|playwright)\b/i.test(e)&&r.push("testing"),/\b(auth|jwt|oauth|session|token)\b/i.test(e)&&r.push("auth"),/\b(api|endpoint|route|rest|graphql)\b/i.test(e)&&r.push("api"),r}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,r=e.match(t);return r?[...new Set(r)]:[]}load(){try{if(be.existsSync(this.filePath)){let e=JSON.parse(be.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{be.existsSync(Nt)||be.mkdirSync(Nt,{recursive:!0});let e=Array.from(this.entries.values());be.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf-8")}catch{}}loadAgentLanes(){try{if(be.existsSync(this.agentLanesPath)){let e=JSON.parse(be.readFileSync(this.agentLanesPath,"utf-8"));for(let[t,r]of Object.entries(e)){let s=new Map;for(let i of r)s.set(i.key,i);this.agentLanes.set(t,s)}}}catch{}}saveAgentLanes(){try{be.existsSync(Nt)||be.mkdirSync(Nt,{recursive:!0});let e={};for(let[t,r]of this.agentLanes)e[t]=Array.from(r.values());be.writeFileSync(this.agentLanesPath,JSON.stringify(e,null,2),"utf-8")}catch{}}}});function jg(){try{if(jt.existsSync($c))return JSON.parse(jt.readFileSync($c,"utf-8"))}catch{}return{}}function Cc(n){let e=jg(),t=n.trim();for(let[r,s]of Object.entries(e))if(t===r||t.startsWith(r+" "))return t.replace(r,s);return n}var jt,ri,Ec,$c,Tc=M(()=>{"use strict";jt=C(require("fs")),ri=C(require("path")),Ec=C(require("os")),$c=ri.join(Ec.homedir(),".hablas","aliases.json")});var ii=L((fE,Pc)=>{"use strict";var cn=n=>n&&typeof n.message=="string",si=n=>{if(!n)return;let e=n.cause;if(typeof e=="function"){let t=n.cause();return cn(t)?t:void 0}else return cn(e)?e:void 0},Rc=(n,e)=>{if(!cn(n))return"";let t=n.stack||"";if(e.has(n))return t+`
524
+ causes have become circular...`;let r=si(n);return r?(e.add(n),t+`
525
+ caused by: `+Rc(r,e)):t},Hg=n=>Rc(n,new Set),Oc=(n,e,t)=>{if(!cn(n))return"";let r=t?"":n.message||"";if(e.has(n))return r+": ...";let s=si(n);if(s){e.add(n);let i=typeof n.cause=="function";return r+(i?"":": ")+Oc(s,e,i)}else return r},Bg=n=>Oc(n,new Set);Pc.exports={isErrorLike:cn,getErrorCause:si,stackWithCauses:Hg,messageWithCauses:Bg}});var oi=L((pE,Ic)=>{"use strict";var qg=Symbol("circular-ref-tag"),Vn=Symbol("pino-raw-err-ref"),Mc=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[Vn]},set:function(n){this[Vn]=n}}});Object.defineProperty(Mc,Vn,{writable:!0,value:{}});Ic.exports={pinoErrProto:Mc,pinoErrorSymbols:{seen:qg,rawSymbol:Vn}}});var Fc=L((hE,Dc)=>{"use strict";Dc.exports=li;var{messageWithCauses:Ug,stackWithCauses:Kg,isErrorLike:Lc}=ii(),{pinoErrProto:Wg,pinoErrorSymbols:Gg}=oi(),{seen:ai}=Gg,{toString:Vg}=Object.prototype;function li(n){if(!Lc(n))return n;n[ai]=void 0;let e=Object.create(Wg);e.type=Vg.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=Ug(n),e.stack=Kg(n),Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>li(t)));for(let t in n)if(e[t]===void 0){let r=n[t];Lc(r)?t!=="cause"&&!Object.prototype.hasOwnProperty.call(r,ai)&&(e[t]=li(r)):e[t]=r}return delete n[ai],e.raw=n,e}});var jc=L((mE,Nc)=>{"use strict";Nc.exports=Yn;var{isErrorLike:ci}=ii(),{pinoErrProto:zg,pinoErrorSymbols:Yg}=oi(),{seen:zn}=Yg,{toString:Jg}=Object.prototype;function Yn(n){if(!ci(n))return n;n[zn]=void 0;let e=Object.create(zg);e.type=Jg.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=>Yn(t))),ci(n.cause)&&!Object.prototype.hasOwnProperty.call(n.cause,zn)&&(e.cause=Yn(n.cause));for(let t in n)if(e[t]===void 0){let r=n[t];ci(r)?Object.prototype.hasOwnProperty.call(r,zn)||(e[t]=Yn(r)):e[t]=r}return delete n[zn],e.raw=n,e}});var Uc=L((gE,qc)=>{"use strict";qc.exports={mapHttpRequest:Xg,reqSerializer:Bc};var ui=Symbol("pino-raw-req-ref"),Hc=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[ui]},set:function(n){this[ui]=n}}});Object.defineProperty(Hc,ui,{writable:!0,value:{}});function Bc(n){let e=n.info||n.socket,t=Object.create(Hc);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 r=n.path;t.url=typeof r=="string"?r: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 Xg(n){return{req:Bc(n)}}});var Vc=L((yE,Gc)=>{"use strict";Gc.exports={mapHttpResponse:Qg,resSerializer:Wc};var di=Symbol("pino-raw-res-ref"),Kc=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[di]},set:function(n){this[di]=n}}});Object.defineProperty(Kc,di,{writable:!0,value:{}});function Wc(n){let e=Object.create(Kc);return e.statusCode=n.headersSent?n.statusCode:null,e.headers=n.getHeaders?n.getHeaders():n._headers,e.raw=n,e}function Qg(n){return{res:Wc(n)}}});var pi=L((bE,zc)=>{"use strict";var fi=Fc(),Zg=jc(),Jn=Uc(),Xn=Vc();zc.exports={err:fi,errWithCause:Zg,mapHttpRequest:Jn.mapHttpRequest,mapHttpResponse:Xn.mapHttpResponse,req:Jn.reqSerializer,res:Xn.resSerializer,wrapErrorSerializer:function(e){return e===fi?e:function(r){return e(fi(r))}},wrapRequestSerializer:function(e){return e===Jn.reqSerializer?e:function(r){return e(Jn.reqSerializer(r))}},wrapResponseSerializer:function(e){return e===Xn.resSerializer?e:function(r){return e(Xn.resSerializer(r))}}}});var hi=L((wE,Yc)=>{"use strict";function ey(n,e){return e}Yc.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=ey;let t=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let r=t.slice(2),s=[];for(let i of r)i&&s.push(i.getFileName());return s}});var tu=L((vE,eu)=>{"use strict";function mi(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]=mi(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]=mi(n[t]));return e}return n}function Jc(n){let e=[],t="",r=!1,s=!1,i="";for(let o=0;o<n.length;o++){let a=n[o];!r&&a==="."?t&&(e.push(t),t=""):a==="["?(t&&(e.push(t),t=""),r=!0):a==="]"&&r?(e.push(t),t="",r=!1,s=!1):(a==='"'||a==="'")&&r?s?a===i?(s=!1,i=""):t+=a:(s=!0,i=a):t+=a}return t&&e.push(t),e}function Xc(n,e,t){let r=n;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof r!="object"||r===null||!(o in r)||typeof r[o]!="object"||r[o]===null)return!1;r=r[o]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(r))for(let i=0;i<r.length;i++)r[i]=t;else if(typeof r=="object"&&r!==null)for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=t)}else typeof r=="object"&&r!==null&&s in r&&Object.prototype.hasOwnProperty.call(r,s)&&(r[s]=t);return!0}function Qc(n,e){let t=n;for(let s=0;s<e.length-1;s++){let i=e[s];if(typeof t!="object"||t===null||!(i in t)||typeof t[i]!="object"||t[i]===null)return!1;t=t[i]}let r=e[e.length-1];if(r==="*"){if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=void 0;else if(typeof t=="object"&&t!==null)for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&delete t[s]}else typeof t=="object"&&t!==null&&r in t&&Object.prototype.hasOwnProperty.call(t,r)&&delete t[r];return!0}var Qn=Symbol("PATH_NOT_FOUND");function ty(n,e){let t=n;for(let r of e){if(t==null||typeof t!="object"||t===null||!(r in t))return Qn;t=t[r]}return t}function ny(n,e){let t=n;for(let r of e){if(t==null||typeof t!="object"||t===null)return;t=t[r]}return t}function ry(n,e,t,r=!1){for(let s of e){let i=Jc(s);if(i.includes("*"))Zc(n,i,t,s,r);else if(r)Qc(n,i);else{let o=ty(n,i);if(o===Qn)continue;let a=typeof t=="function"?t(o,i):t;Xc(n,i,a)}}}function Zc(n,e,t,r,s=!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(s)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let c=[...o,l.toString()],u=typeof t=="function"?t(a[l],c):t;a[l]=u}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],u=typeof t=="function"?t(a[l],c):t;a[l]=u}}else sy(n,e,t,i,r,s)}function sy(n,e,t,r,s,i=!1){let o=e.slice(0,r),a=e.slice(r+1),l=[];function c(u,d){if(d===o.length){if(Array.isArray(u))for(let p=0;p<u.length;p++)l[d]=p.toString(),c(u[p],d+1);else if(typeof u=="object"&&u!==null)for(let p in u)l[d]=p,c(u[p],d+1)}else if(d<o.length){let p=o[d];u&&typeof u=="object"&&u!==null&&p in u&&(l[d]=p,c(u[p],d+1))}else if(a.includes("*"))Zc(u,a,typeof t=="function"?(h,f)=>{let g=[...l.slice(0,d),...f];return t(h,g)}:t,s,i);else if(i)Qc(u,a);else{let p=typeof t=="function"?t(ny(u,a),[...l.slice(0,d),...a]):t;Xc(u,a,p)}}if(o.length===0)c(n,0);else{let u=n;for(let d=0;d<o.length;d++){let p=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[p],l[d]=p}u!=null&&c(u,o.length)}}function iy(n){if(n.length===0)return null;let e=new Map;for(let t of n){let r=Jc(t),s=e;for(let i=0;i<r.length;i++){let o=r[i];s.has(o)||s.set(o,new Map),s=s.get(o)}}return e}function oy(n,e){if(!e)return n;function t(r,s,i=0){if(!s||s.size===0||r===null||typeof r!="object")return r;if(r instanceof Date)return new Date(r.getTime());if(Array.isArray(r)){let a=[];for(let l=0;l<r.length;l++){let c=l.toString();s.has(c)||s.has("*")?a[l]=t(r[l],s.get(c)||s.get("*")):a[l]=r[l]}return a}let o=Object.create(Object.getPrototypeOf(r));for(let a in r)Object.prototype.hasOwnProperty.call(r,a)&&(s.has(a)||s.has("*")?o[a]=t(r[a],s.get(a)||s.get("*")):o[a]=r[a]);return o}return t(n,e)}function ay(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,r="";for(let s=0;s<n.length;s++){let i=n[s];if((i==='"'||i==="'")&&e>0)t?i===r&&(t=!1,r=""):(t=!0,r=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 ly(n){if(!Array.isArray(n))throw new TypeError("paths must be an array");for(let e of n)ay(e)}function cy(n={}){let{paths:e=[],censor:t="[REDACTED]",serialize:r=JSON.stringify,strict:s=!0,remove:i=!1}=n;ly(e);let o=iy(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return r?r(l):l;let c=oy(l,o),u=l,d=t;return typeof t=="function"&&(d=t),ry(c,e,d,i),r===!1?(c.restore=function(){return mi(u)},c):typeof r=="function"?r(c):JSON.stringify(c)}}eu.exports=cy});var Ht=L((xE,nu)=>{"use strict";var uy=Symbol("pino.setLevel"),dy=Symbol("pino.getLevel"),fy=Symbol("pino.levelVal"),py=Symbol("pino.levelComp"),hy=Symbol("pino.useLevelLabels"),my=Symbol("pino.useOnlyCustomLevels"),gy=Symbol("pino.mixin"),yy=Symbol("pino.lsCache"),by=Symbol("pino.chindings"),wy=Symbol("pino.asJson"),vy=Symbol("pino.write"),xy=Symbol("pino.redactFmt"),_y=Symbol("pino.time"),Sy=Symbol("pino.timeSliceIndex"),Ay=Symbol("pino.stream"),ky=Symbol("pino.stringify"),$y=Symbol("pino.stringifySafe"),Ey=Symbol("pino.stringifiers"),Cy=Symbol("pino.end"),Ty=Symbol("pino.formatOpts"),Ry=Symbol("pino.messageKey"),Oy=Symbol("pino.errorKey"),Py=Symbol("pino.nestedKey"),My=Symbol("pino.nestedKeyStr"),Iy=Symbol("pino.mixinMergeStrategy"),Ly=Symbol("pino.msgPrefix"),Dy=Symbol("pino.wildcardFirst"),Fy=Symbol.for("pino.serializers"),Ny=Symbol.for("pino.formatters"),jy=Symbol.for("pino.hooks"),Hy=Symbol.for("pino.metadata");nu.exports={setLevelSym:uy,getLevelSym:dy,levelValSym:fy,levelCompSym:py,useLevelLabelsSym:hy,mixinSym:gy,lsCacheSym:yy,chindingsSym:by,asJsonSym:wy,writeSym:vy,serializersSym:Fy,redactFmtSym:xy,timeSym:_y,timeSliceIndexSym:Sy,streamSym:Ay,stringifySym:ky,stringifySafeSym:$y,stringifiersSym:Ey,endSym:Cy,formatOptsSym:Ty,messageKeySym:Ry,errorKeySym:Oy,nestedKeySym:Py,wildcardFirstSym:Dy,needsMetadataGsym:Hy,useOnlyCustomLevelsSym:my,formattersSym:Ny,hooksSym:jy,nestedKeyStrSym:My,mixinMergeStrategySym:Iy,msgPrefixSym:Ly}});var yi=L((_E,ou)=>{"use strict";var ru=tu(),{redactFmtSym:By,wildcardFirstSym:Zn}=Ht(),gi=/[^.[\]]+|\[([^[\]]*?)\]/g,su="[Redacted]",iu=!1;function qy(n,e){let{paths:t,censor:r,remove:s}=Uy(n),i=t.reduce((l,c)=>{gi.lastIndex=0;let u=gi.exec(c),d=gi.exec(c),p=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(p==="*"&&(p=Zn),d===null)return l[p]=null,l;if(l[p]===null)return l;let{index:h}=d,f=`${c.substr(h,c.length-1)}`;return l[p]=l[p]||[],p!==Zn&&l[p].length===0&&l[p].push(...l[Zn]||[]),p===Zn&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(f)}),l[p].push(f),l},{}),o={[By]:ru({paths:t,censor:r,serialize:e,strict:iu,remove:s})},a=(...l)=>e(typeof r=="function"?r(...l):r);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=u=>a(u,[c]);else{let u=typeof r=="function"?(d,p)=>r(d,[c,...p]):r;l[c]=ru({paths:i[c],censor:u,serialize:e,strict:iu,remove:s})}return l},o)}function Uy(n){if(Array.isArray(n))return n={paths:n,censor:su},n;let{paths:e,censor:t=su,remove:r}=n;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return r===!0&&(t=void 0),{paths:e,censor:t,remove:r}}ou.exports=qy});var cu=L((SE,lu)=>{"use strict";var Ky=()=>"",Wy=()=>`,"time":${Date.now()}`,Gy=()=>`,"time":${Math.round(Date.now()/1e3)}`,Vy=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,zy=1000000n,au=1000000000n,Yy=BigInt(Date.now())*zy,Jy=process.hrtime.bigint(),Xy=()=>{let n=process.hrtime.bigint()-Jy,e=Yy+n,t=e/au,r=e%au,s=Number(t*1000n+r/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${u}:${d}.${r.toString().padStart(9,"0")}Z"`};lu.exports={nullTime:Ky,epochTime:Wy,unixTime:Gy,isoTime:Vy,isoTimeNano:Xy}});var du=L((AE,uu)=>{"use strict";function Qy(n){try{return JSON.stringify(n)}catch{return'"[Circular]"'}}uu.exports=Zy;function Zy(n,e,t){var r=t&&t.stringify||Qy,s=1;if(typeof n=="object"&&n!==null){var i=e.length+s;if(i===1)return n;var o=new Array(i);o[0]=r(n);for(var a=1;a<i;a++)o[a]=r(e[a]);return o.join(" ")}if(typeof n!="string")return n;var l=e.length;if(l===0)return n;for(var c="",u=1-s,d=-1,p=n&&n.length||0,h=0;h<p;){if(n.charCodeAt(h)===37&&h+1<p){switch(d=d>-1?d:0,n.charCodeAt(h+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<h&&(c+=n.slice(d,h)),c+=Number(e[u]),d=h+2,h++;break;case 105:if(u>=l||e[u]==null)break;d<h&&(c+=n.slice(d,h)),c+=Math.floor(Number(e[u])),d=h+2,h++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<h&&(c+=n.slice(d,h));var f=typeof e[u];if(f==="string"){c+="'"+e[u]+"'",d=h+2,h++;break}if(f==="function"){c+=e[u].name||"<anonymous>",d=h+2,h++;break}c+=r(e[u]),d=h+2,h++;break;case 115:if(u>=l)break;d<h&&(c+=n.slice(d,h)),c+=String(e[u]),d=h+2,h++;break;case 37:d<h&&(c+=n.slice(d,h)),c+="%",d=h+2,h++,u--;break}++u}++h}return d===-1?n:(d<p&&(c+=n.slice(d)),c)}});var wi=L((kE,bi)=>{"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));bi.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 r=Date.now()+Number(e);for(;r>Date.now(););};bi.exports=n}});var wu=L(($E,bu)=>{"use strict";var ne=require("fs"),eb=require("events"),tb=require("util").inherits,fu=require("path"),xi=wi(),nb=require("assert"),er=100,tr=Buffer.allocUnsafe(0),rb=16*1024,pu="buffer",hu="utf8",[sb,ib]=(process.versions.node||"0.0").split(".").map(Number),ob=sb>=22&&ib>=7;function mu(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 r=e.append?"a":"w",s=e.mode;if(e.sync)try{e.mkdir&&ne.mkdirSync(fu.dirname(n),{recursive:!0});let i=ne.openSync(n,r,s);t(null,i)}catch(i){throw t(i),i}else e.mkdir?ne.mkdir(fu.dirname(n),{recursive:!0},i=>{if(i)return t(i);ne.open(n,r,s,t)}):ne.open(n,r,s,t)}function Le(n){if(!(this instanceof Le))return new Le(n);let{fd:e,dest:t,minLength:r,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:u,fsync:d,contentMode:p,mode:h}=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(r||0,16387),this.file=null,this.destroyed=!1,this.minLength=r||0,this.maxLength=s||0,this.maxWrite=i||rb,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=h,this.retryEAGAIN=u||(()=>!0),this.mkdir=c||!1;let f,g;if(p===pu)this._writingBuf=tr,this.write=cb,this.flush=db,this.flushSync=pb,this._actualWrite=mb,f=()=>ne.writeSync(this.fd,this._writingBuf),g=()=>ne.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===hu)this._writingBuf="",this.write=lb,this.flush=ub,this.flushSync=fb,this._actualWrite=hb,f=()=>Buffer.isBuffer(this._writingBuf)?ne.writeSync(this.fd,this._writingBuf):ne.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>Buffer.isBuffer(this._writingBuf)?ne.write(this.fd,this._writingBuf,this.release):ne.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${hu}" and "${pu}", but passed ${p}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")mu(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=(y,w)=>{if(y){if((y.code==="EAGAIN"||y.code==="EBUSY")&&this.retryEAGAIN(y,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{xi(er),this.release(void 0,0)}catch(k){this.release(k)}else setTimeout(g,er);else this._writing=!1,this.emit("error",y);return}this.emit("write",w);let v=vi(this._writingBuf,this._len,w);if(this._len=v.len,this._writingBuf=v.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let k=f(),P=vi(this._writingBuf,this._len,k);this._len=P.len,this._writingBuf=P.writingBuf}while(this._writingBuf.length)}catch(k){this.release(k);return}}this._fsync&&ne.fsyncSync(this.fd);let S=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):S>this.minLength?this._actualWrite():this._ending?S>0?this._actualWrite():(this._writing=!1,nr(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(ab,this)):this.emit("drain"))},this.on("newListener",function(y){y==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function vi(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 ab(n){n.listenerCount("drain")>0&&(n._asyncDrainScheduled=!1,n.emit("drain"))}tb(Le,eb);function gu(n,e){return n.length===0?tr:n.length===1?n[0]:Buffer.concat(n,e)}function lb(n){if(this.destroyed)throw new Error("SonicBoom destroyed");n=""+n;let e=Buffer.byteLength(n),t=this._len+e,r=this._bufs;return this.maxLength&&t>this.maxLength?(this.emit("drop",n),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+e>this.maxWrite?r.push(n):r[r.length-1]+=n,this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function cb(n){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+n.length,t=this._bufs,r=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",n),this._len<this._hwm):(t.length===0||r[r.length-1]+n.length>this.maxWrite?(t.push([n]),r.push(n.length)):(t[t.length-1].push(n),r[r.length-1]+=n.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function yu(n){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,n();else try{ne.fsync(this.fd,r=>{this._flushPending=!1,n(r)})}catch(r){n(r)}this.off("error",t)},t=r=>{this._flushPending=!1,n(r),this.off("drain",e)};this.once("drain",e),this.once("error",t)}function ub(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&&yu.call(this,n),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function db(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&&yu.call(this,n),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}Le.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&&ne.close(e,t=>{if(t)return this.emit("error",t)})}),mu(this.file,this)};Le.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():nr(this)))};function fb(){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)?ne.writeSync(this.fd,n):ne.writeSync(this.fd,n,"utf8"),t=vi(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;xi(er)}}try{ne.fsyncSync(this.fd)}catch{}}function pb(){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=gu(this._bufs[0],this._lens[0]));try{let e=ne.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;xi(er)}}}Le.prototype.destroy=function(){this.destroyed||nr(this)};function hb(){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)?ne.writeSync(this.fd,this._writingBuf):ne.writeSync(this.fd,this._writingBuf,"utf8");n(null,e)}catch(e){n(e)}else ne.write(this.fd,this._writingBuf,n)}function mb(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:gu(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=ne.writeSync(this.fd,this._writingBuf);n(null,e)}catch(e){n(e)}else ob&&(this._writingBuf=Buffer.from(this._writingBuf)),ne.write(this.fd,this._writingBuf,n)}function nr(n){if(n.fd===-1){n.once("ready",nr.bind(null,n));return}n._periodicFlushTimer!==void 0&&clearInterval(n._periodicFlushTimer),n.destroyed=!0,n._bufs=[],n._lens=[],nb(typeof n.fd=="number",`sonic.fd must be a number, got ${typeof n.fd}`);try{ne.fsync(n.fd,e)}catch{}function e(){n.fd!==1&&n.fd!==2?ne.close(n.fd,t):t()}function t(r){if(r){n.emit("error",r);return}n._ending&&!n._writing&&n.emit("finish"),n.emit("close")}}Le.SonicBoom=Le;Le.default=Le;bu.exports=Le});var _i=L((EE,Au)=>{"use strict";var De={exit:[],beforeExit:[]},vu={exit:bb,beforeExit:wb},Bt;function gb(){Bt===void 0&&(Bt=new FinalizationRegistry(vb))}function yb(n){De[n].length>0||process.on(n,vu[n])}function xu(n){De[n].length>0||(process.removeListener(n,vu[n]),De.exit.length===0&&De.beforeExit.length===0&&(Bt=void 0))}function bb(){_u("exit")}function wb(){_u("beforeExit")}function _u(n){for(let e of De[n]){let t=e.deref(),r=e.fn;t!==void 0&&r(t,n)}De[n]=[]}function vb(n){for(let e of["exit","beforeExit"]){let t=De[e].indexOf(n);De[e].splice(t,t+1),xu(e)}}function Su(n,e,t){if(e===void 0)throw new Error("the object can't be undefined");yb(n);let r=new WeakRef(e);r.fn=t,gb(),Bt.register(e,r),De[n].push(r)}function xb(n,e){Su("exit",n,e)}function _b(n,e){Su("beforeExit",n,e)}function Sb(n){if(Bt!==void 0){Bt.unregister(n);for(let e of["exit","beforeExit"])De[e]=De[e].filter(t=>{let r=t.deref();return r&&r!==n}),xu(e)}}Au.exports={register:xb,registerBeforeExit:_b,unregister:Sb}});var ku=L((CE,Ab)=>{Ab.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 Eu=L((TE,$u)=>{"use strict";function kb(n,e,t,r,s){let i=r===1/0?1/0:Date.now()+r,o=()=>{let a=Atomics.load(n,e);if(a===t){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(n,e,a,l);c.async?c.value.then(o):setImmediate(o)};o()}function $b(n,e,t,r,s){let i=r===1/0?1/0:Date.now()+r,o=()=>{if(Atomics.load(n,e)!==t){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(n,e,t,l);c.async?c.value.then(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}$u.exports={wait:kb,waitDiff:$b}});var Tu=L((RE,Cu)=>{"use strict";Cu.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Bu=L((OE,Hu)=>{"use strict";var{version:Eb}=ku(),{EventEmitter:Cb}=require("events"),{Worker:Tb}=require("worker_threads"),{join:Rb}=require("path"),{pathToFileURL:Ob}=require("url"),{wait:Pb}=Eu(),{WRITE_INDEX:et,READ_INDEX:xt,SEQ_INDEX:Si}=Tu(),Mb=require("buffer"),Ib=require("assert"),A=Symbol("kImpl"),Lb=Mb.constants.MAX_STRING_LENGTH;function Ru(){}function Ei(n,e){Atomics.add(n[A].state,Si,1),e(),Atomics.add(n[A].state,Si,1),Atomics.notify(n[A].state,Si)}function Ou(n){Ei(n,()=>{Atomics.store(n[A].state,xt,0),Atomics.store(n[A].state,et,0)})}var un=class{constructor(e){this._value=e}deref(){return this._value}},rr=class{register(){}unregister(){}},Db=process.env.NODE_V8_COVERAGE?rr:global.FinalizationRegistry||rr,Fb=process.env.NODE_V8_COVERAGE?un:global.WeakRef||un,Pu=new Db(n=>{n.exited||n.terminate()});function Nb(n,e){let{filename:t,workerData:r}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Rb(__dirname,"lib","worker.js"),o=new Tb(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:t.indexOf("file://")===0?t:Ob(t).href,dataBuf:n[A].dataBuf,stateBuf:n[A].stateBuf,workerData:{$context:{threadStreamVersion:Eb},...r}}});return o.stream=new un(n),o.on("message",jb),o.on("exit",Lu),Pu.register(n,o),o}function Mu(n){Ib(!n[A].sync),n[A].needDrain&&(n[A].needDrain=!1,n.emit("drain"))}function Iu(n){for(;;){let e=Atomics.load(n[A].state,et),t=n[A].data.length-e;if(t>0){if(n[A].bufLen===0){n[A].flushing=!1,n[A].ending?Ci(n):n[A].needDrain&&process.nextTick(Mu,n);return}Nu(n,t,Ru);continue}if(t===0){if(e===0&&n[A].bufLen===0)return;sr(n,()=>{n.destroyed||(Ou(n),Iu(n))});return}Ce(n,new Error("overwritten"));return}}function jb(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 Fb(e),sr(e,()=>{e[A].ready=!0,e.emit("ready")});break;case"ERROR":Ce(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"){Ce(e,new Error("this should not happen: "+n.code));break}let t=e[A].flushCallbacks.get(n.id);t&&(e[A].flushCallbacks.delete(n.id),process.nextTick(t));break}case"WARNING":process.emitWarning(n.err);break;default:Ce(e,new Error("this should not happen: "+n.code))}}function Lu(n){let e=this.stream.deref();e!==void 0&&(Pu.unregister(e),e.worker.exited=!0,e.worker.off("exit",Lu),Ce(e,n!==0?new Error("the worker thread exited"):null))}var ki=class extends Cb{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[A]={},this[A].stateBuf=new SharedArrayBuffer(128),this[A].state=new Int32Array(this[A].stateBuf),this[A].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[A].data=Buffer.from(this[A].dataBuf),this[A].sync=e.sync||!1,this[A].ending=!1,this[A].ended=!1,this[A].needDrain=!1,this[A].destroyed=!1,this[A].flushing=!1,this[A].ready=!1,this[A].finished=!1,this[A].errored=null,this[A].closed=!1,this[A].buf=[],this[A].bufHead=0,this[A].bufLen=0,this[A].flushCallbacks=new Map,this[A].nextFlushId=0,this.worker=Nb(this,e),this.on("message",(t,r)=>{this.worker.postMessage(t,r)})}write(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[A].destroyed)return $i(this,new Error("the worker has exited")),!1;if(this[A].ending)return $i(this,new Error("the worker is ending")),!1;if(this[A].flushing&&this[A].bufLen+t.length>=Lb)try{Ai(this),this[A].flushing=!0}catch(r){return Ce(this,r),!1}if(this[A].buf.push(t),this[A].bufLen+=t.length,this[A].sync)try{return Ai(this),!0}catch(r){return Ce(this,r),!1}return this[A].flushing||(this[A].flushing=!0,setImmediate(Iu,this)),this[A].needDrain=this[A].data.length-this[A].bufLen-Atomics.load(this[A].state,et)<=0,!this[A].needDrain}end(){this[A].destroyed||(this[A].ending=!0,Ci(this))}flush(e){e=typeof e=="function"?e:Ru,Du(this,t=>{if(t){process.nextTick(e,t);return}Fu(this,e)})}flushSync(){this[A].destroyed||(Ai(this),ju(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[A].ready}get destroyed(){return this[A].destroyed}get closed(){return this[A].closed}get writable(){return!this[A].destroyed&&!this[A].ending}get writableEnded(){return this[A].ending}get writableFinished(){return this[A].finished}get writableNeedDrain(){return this[A].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[A].errored}};function Du(n,e){if(n[A].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[A].sync&&(n[A].flushing||n[A].bufLen>0)){setImmediate(Du,n,e);return}sr(n,e)}function sr(n,e){let t=Atomics.load(n[A].state,et);Pb(n[A].state,xt,t,1/0,(r,s)=>{if(r){Ce(n,r),e(r);return}if(s!=="ok"){sr(n,e);return}e()})}function Fu(n,e){if(n[A].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[A].ready){let r=()=>{i(),Fu(n,e)},s=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{n.off("ready",r),n.off("close",s)};n.once("ready",r),n.once("close",s);return}let t=++n[A].nextFlushId;n[A].flushCallbacks.set(t,e);try{n.worker.postMessage({code:"FLUSH",context:"thread-stream",id:t})}catch(r){n[A].flushCallbacks.delete(t),Ce(n,r),process.nextTick(e,r)}}function Hb(n,e){let t=n[A].flushCallbacks;if(t.size===0)return;let r=e||new Error("the worker has exited");for(let s of t.values())process.nextTick(s,r);t.clear()}function $i(n,e){setImmediate(()=>{n.emit("error",e)})}function Ce(n,e){n[A].destroyed||(n[A].destroyed=!0,Hb(n,e),e&&(n[A].errored=e,$i(n,e)),n.worker.exited?setImmediate(()=>{n[A].closed=!0,n.emit("close")}):n.worker.terminate().catch(()=>{}).then(()=>{n[A].closed=!0,n.emit("close")}))}function Nu(n,e,t){let s=Atomics.load(n[A].state,et),i=e;for(;i>0&&n[A].bufLen!==0;){let o=n[A].bufHead,a=n[A].buf[o];if(a.length<=i){a.copy(n[A].data,s),s+=a.length,i-=a.length,n[A].bufLen-=a.length,n[A].bufHead=o+1,n[A].bufHead===n[A].buf.length?(n[A].buf.length=0,n[A].bufHead=0):n[A].bufHead>=1024&&n[A].bufHead*2>=n[A].buf.length&&(n[A].buf.splice(0,n[A].bufHead),n[A].bufHead=0);continue}a.copy(n[A].data,s,0,i),n[A].buf[o]=a.subarray(i),n[A].bufLen-=i,s+=i,i=0}return Ei(n,()=>{Atomics.store(n[A].state,et,s)}),t(),!0}function Ci(n){if(!(n[A].ended||!n[A].ending||n[A].flushing)){n[A].ended=!0;try{n.flushSync();let e=Atomics.load(n[A].state,xt);Ei(n,()=>{Atomics.store(n[A].state,et,-1)});let t=0;for(;e!==-1;){if(Atomics.wait(n[A].state,xt,e,1e3),e=Atomics.load(n[A].state,xt),e===-2){Ce(n,new Error("end() failed"));return}if(++t===10){Ce(n,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{n[A].finished=!0,n.emit("finish")})}catch(e){Ce(n,e)}}}function Ai(n){let e=()=>{n[A].ending?Ci(n):n[A].needDrain&&process.nextTick(Mu,n)};for(n[A].flushing=!1;n[A].bufLen!==0;){let t=Atomics.load(n[A].state,et),r=n[A].data.length-t;if(r===0){ju(n),Ou(n);continue}else if(r<0)throw new Error("overwritten");Nu(n,r,e)}}function ju(n){if(n[A].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(n[A].state,et),t=0;for(;;){let r=Atomics.load(n[A].state,xt);if(r===-2)throw Error("_flushSync failed");if(r!==e)Atomics.wait(n[A].state,xt,r,1e3);else break;if(++t===10)throw new Error("_flushSync took too long (10s)")}}Hu.exports=ki});var Oi=L((PE,Ku)=>{"use strict";var{createRequire:Bb}=require("module"),{existsSync:qb}=require("node:fs"),Ub=hi(),{join:Ti,isAbsolute:Uu,sep:Kb}=require("node:path"),{fileURLToPath:Wb}=require("node:url"),Gb=wi(),Ri=_i(),Vb=Bu();function zb(n){Ri.register(n,Zb),Ri.registerBeforeExit(n,ew),n.on("close",function(){Ri.unregister(n)})}function Yb(){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 Jb(n){let e=n.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return n;let t=[],r=!1;for(let s=0;s<e.length;s++){let i=e[s];if(i==="--require"||i==="-r"||i==="--import"){let o=e[s+1];if(o&&qu(o)){r=!0,s++;continue}t.push(i),o&&(t.push(o),s++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(qu(o)){r=!0;continue}}t.push(i)}return r?t.join(" "):n}function qu(n){let e=Xb(n);if(!e)return!1;let t=e;if(t.startsWith("file://"))try{t=Wb(t)}catch{return!1}return Uu(t)&&!qb(t)}function Xb(n){let e=n[0],t=n[n.length-1];return e==='"'&&t==='"'||e==="'"&&t==="'"?n.slice(1,-1):n}function Qb(n,e,t,r,s){if(!t.execArgv&&Yb()&&require.main===void 0&&(t={...t,execArgv:[]}),!t.env&&process.env.NODE_OPTIONS){let l=Jb(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(t={...t,env:{...process.env,NODE_OPTIONS:l}})}t={...t,name:s};let i=new Vb({filename:n,workerData:e,workerOpts:t,sync:r});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&&zb(i)}function a(){i.closed||(i.flushSync(),Gb(100),i.end())}return i}function Zb(n){n.ref(),n.flushSync(),n.end(),n.once("close",function(){n.unref()})}function ew(n){n.flushSync()}function tw(n){let{pipeline:e,targets:t,levels:r,dedupe:s,worker:i={},caller:o=Ub(),sync:a=!1}=n,l={...n.options},c=typeof o=="string"?[o]:o,u=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=n.target;if(d&&t)throw new Error("only one of target or targets can be specified");t?(d=u["pino-worker"]||Ti(__dirname,"worker.js"),l.targets=t.filter(f=>f.target).map(f=>({...f,target:h(f.target)})),l.pipelines=t.filter(f=>f.pipeline).map(f=>f.pipeline.map(g=>({...g,level:f.level,target:h(g.target)})))):e&&(d=u["pino-worker"]||Ti(__dirname,"worker.js"),l.pipelines=[e.map(f=>({...f,target:h(f.target)}))]),r&&(l.levels=r),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let p=t||e?"pino.transport":d;return Qb(h(d),l,i,a,p);function h(f){if(f=u[f]||f,Uu(f)||f.indexOf("file://")===0)return f;if(f==="pino/file")return Ti(__dirname,"..","file.js");let g;for(let y of c)try{let w=y==="node:repl"?process.cwd()+Kb:y;g=Bb(w).resolve(f);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${f}"`);return g}}Ku.exports=tw});var ar=L((ME,rd)=>{"use strict";var nw=require("node:diagnostics_channel"),Wu=du(),{mapHttpRequest:rw,mapHttpResponse:sw}=pi(),Mi=wu(),Gu=_i(),{lsCacheSym:iw,chindingsSym:Xu,writeSym:Vu,serializersSym:Qu,formatOptsSym:zu,endSym:ow,stringifiersSym:Zu,stringifySym:ed,stringifySafeSym:Ii,wildcardFirstSym:td,nestedKeySym:aw,formattersSym:nd,messageKeySym:lw,errorKeySym:cw,nestedKeyStrSym:uw,msgPrefixSym:ir}=Ht(),{isMainThread:dw}=require("worker_threads"),fw=Oi(),[pw]=process.versions.node.split(".").map(n=>Number(n)),Yu=nw.tracingChannel("pino_asJson"),Pi=pw>=25?n=>JSON.stringify(n):mw;function qt(){}function hw(n,e){if(!e)return t;return function(...s){e.call(this,s,t,n)};function t(r,...s){if(typeof r=="object"){let i=r;r!==null&&(r.method&&r.headers&&r.socket?r=rw(r):typeof r.setHeader=="function"&&(r=sw(r)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[ir]=="string"&&i!==void 0&&i!==null&&(i=this[ir]+i),this[Vu](r,Wu(i,o,this[zu]),n)}else{let i=r===void 0?s.shift():r;typeof this[ir]=="string"&&i!==void 0&&i!==null&&(i=this[ir]+i),this[Vu](null,Wu(i,s,this[zu]),n)}}}function mw(n){let e="",t=0,r=!1,s=255,i=n.length;if(i>100)return JSON.stringify(n);for(var o=0;o<i&&s>=32;o++)s=n.charCodeAt(o),(s===34||s===92)&&(e+=n.slice(t,o)+"\\",t=o,r=!0);return r?e+=n.slice(t):e=n,s<32?JSON.stringify(n):'"'+e+'"'}function gw(n,e,t,r){if(Yu.hasSubscribers===!1)return Ju.call(this,n,e,t,r);let s={instance:this,arguments};return Yu.traceSync(Ju,s,this,n,e,t,r)}function Ju(n,e,t,r){let s=this[ed],i=this[Ii],o=this[Zu],a=this[ow],l=this[Xu],c=this[Qu],u=this[nd],d=this[lw],p=this[cw],h=this[iw][t]+r;h=h+l;let f;u.log&&(n=u.log(n));let g=o[td],y="";for(let v in n)if(f=n[v],Object.prototype.hasOwnProperty.call(n,v)&&f!==void 0){c[v]?f=c[v](f):v===p&&c.err&&(f=c.err(f));let S=o[v]||g;switch(typeof f){case"undefined":case"function":continue;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":S&&(f=S(f));break;case"string":f=(S||Pi)(f);break;default:f=(S||s)(f,i)}if(f===void 0)continue;let k=Pi(v);y+=","+k+":"+f}let w="";if(e!==void 0){f=c[d]?c[d](e):e;let v=o[d]||g;switch(typeof f){case"function":break;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":v&&(f=v(f)),w=',"'+d+'":'+f;break;case"string":f=(v||Pi)(f),w=',"'+d+'":'+f;break;default:f=(v||s)(f,i),w=',"'+d+'":'+f}}return this[aw]&&y?h+this[uw]+y.slice(1)+"}"+w+a:h+y+w+a}function yw(n,e){let t,r=n[Xu],s=n[ed],i=n[Ii],o=n[Zu],a=o[td],l=n[Qu],c=n[nd].bindings;e=c(e);for(let u in e)if(t=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&t!==void 0)===!0){if(t=l[u]?l[u](t):t,t=(o[u]||a||s)(t,i),t===void 0)continue;r+=',"'+u+'":'+t}return r}function bw(n){return n.write!==n.constructor.prototype.write}function or(n){let e=new Mi(n);return e.on("error",t),!n.sync&&dw&&(Gu.register(e,ww),e.on("close",function(){Gu.unregister(e)})),e;function t(r){if(r.code==="EPIPE"){e.write=qt,e.end=qt,e.flushSync=qt,e.destroy=qt;return}e.removeListener("error",t),e.emit("error",r)}}function ww(n,e){n.destroyed||(e==="beforeExit"?(n.flush(),n.on("drain",function(){n.end()})):n.flushSync())}function vw(n){return function(t,r,s={},i){if(typeof s=="string")i=or({dest:s}),s={};else if(typeof i=="string"){if(s&&s.transport)throw Error("only one of option.transport or stream can be specified");i=or({dest:i})}else if(s instanceof Mi||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof Mi||s.transport.writable||s.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(s.transport.targets&&s.transport.targets.length&&s.formatters&&typeof s.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;s.customLevels&&(l=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=fw({caller:r,...s.transport,levels:l})}if(s=Object.assign({},n,s),s.serializers=Object.assign({},n.serializers,s.serializers),s.formatters=Object.assign({},n.formatters,s.formatters),s.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}=s;return o===!1&&(s.level="silent"),a||(s.onChild=qt),i||(bw(process.stdout)?i=process.stdout:i=or({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function xw(n,e){try{return JSON.stringify(n)}catch{try{return(e||this[Ii])(n)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function _w(n,e,t){return{level:n,bindings:e,log:t}}function Sw(n){let e=Number(n);return typeof n=="string"&&Number.isFinite(e)?e:n===void 0?1:n}rd.exports={noop:qt,buildSafeSonicBoom:or,asChindings:yw,asJson:gw,genLog:hw,createArgsNormalizer:vw,stringify:xw,buildFormatters:_w,normalizeDestFileDescriptor:Sw}});var lr=L((IE,sd)=>{var Aw={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},kw={ASC:"ASC",DESC:"DESC"};sd.exports={DEFAULT_LEVELS:Aw,SORTING_ORDER:kw}});var Fi=L((LE,ld)=>{"use strict";var{lsCacheSym:$w,levelValSym:Li,useOnlyCustomLevelsSym:Ew,streamSym:Cw,formattersSym:Tw,hooksSym:Rw,levelCompSym:id}=Ht(),{noop:Ow,genLog:_t}=ar(),{DEFAULT_LEVELS:We,SORTING_ORDER:od}=lr(),ad={fatal:n=>{let e=_t(We.fatal,n);return function(...t){let r=this[Cw];if(e.call(this,...t),typeof r.flushSync=="function")try{r.flushSync()}catch{}}},error:n=>_t(We.error,n),warn:n=>_t(We.warn,n),info:n=>_t(We.info,n),debug:n=>_t(We.debug,n),trace:n=>_t(We.trace,n)},Di=Object.keys(We).reduce((n,e)=>(n[We[e]]=e,n),{}),Pw=Object.keys(Di).reduce((n,e)=>(n[e]='{"level":'+Number(e),n),{});function Mw(n){let e=n[Tw].level,{labels:t}=n.levels,r={};for(let s in t){let i=e(t[s],Number(s));r[s]=JSON.stringify(i).slice(0,-1)}return n[$w]=r,n}function Iw(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 Lw(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 r=this[Li],s=this[Li]=t[n],i=this[Ew],o=this[id],a=this[Rw].logMethod;for(let l in t){if(o(t[l],s)===!1){this[l]=Ow;continue}this[l]=Iw(l,i)?ad[l](a):_t(t[l],a)}this.emit("level-change",n,s,e[r],r,this)}function Dw(n){let{levels:e,levelVal:t}=this;return e&&e.labels?e.labels[t]:""}function Fw(n){let{values:e}=this.levels,t=e[n];return t!==void 0&&this[id](t,this[Li])}function Nw(n,e,t){return n===od.DESC?e<=t:e>=t}function jw(n){return typeof n=="string"?Nw.bind(null,n):n}function Hw(n=null,e=!1){let t=n?Object.keys(n).reduce((i,o)=>(i[n[o]]=o,i),{}):null,r=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:Di,t),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:We,n);return{labels:r,values:s}}function Bw(n,e,t){if(typeof n=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),t?[]:Object.keys(Di).map(i=>+i),1/0).includes(n))throw Error(`default level:${n} must be included in custom levels`);return}let r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:We,e);if(!(n in r))throw Error(`default level:${n} must be included in custom levels`)}function qw(n,e){let{labels:t,values:r}=n;for(let s in e){if(s in r)throw Error("levels cannot be overridden");if(e[s]in t)throw Error("pre-existing level values cannot be used for new levels")}}function Uw(n){if(typeof n!="function"&&!(typeof n=="string"&&Object.values(od).includes(n)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}ld.exports={initialLsCache:Pw,genLsCache:Mw,levelMethods:ad,getLevel:Dw,setLevel:Lw,isLevelEnabled:Fw,mappings:Hw,assertNoLevelCollisions:qw,assertDefaultLevelFound:Bw,genLevelComparison:jw,assertLevelComparison:Uw}});var Ni=L((DE,cd)=>{"use strict";cd.exports={version:"10.3.1"}});var yd=L((NE,gd)=>{"use strict";var{EventEmitter:Kw}=require("node:events"),{lsCacheSym:Ww,levelValSym:Gw,setLevelSym:Hi,getLevelSym:ud,chindingsSym:ur,mixinSym:Vw,asJsonSym:fd,writeSym:zw,mixinMergeStrategySym:Yw,timeSym:Jw,timeSliceIndexSym:Xw,streamSym:pd,serializersSym:St,formattersSym:dn,errorKeySym:Qw,messageKeySym:Zw,useOnlyCustomLevelsSym:ev,needsMetadataGsym:tv,redactFmtSym:nv,stringifySym:rv,formatOptsSym:sv,stringifiersSym:iv,msgPrefixSym:Bi,hooksSym:ov}=Ht(),{getLevel:av,setLevel:lv,isLevelEnabled:cv,mappings:uv,initialLsCache:dv,genLsCache:fv,assertNoLevelCollisions:pv}=Fi(),{asChindings:qi,asJson:hv,buildFormatters:ji,stringify:dd,noop:hd}=ar(),{version:mv}=Ni(),gv=yi(),yv=class{},md={constructor:yv,child:bv,bindings:wv,setBindings:vv,flush:Sv,isLevelEnabled:cv,version:mv,get level(){return this[ud]()},set level(n){this[Hi](n)},get levelVal(){return this[Gw]},set levelVal(n){throw Error("levelVal is read-only")},get msgPrefix(){return this[Bi]},get[Symbol.toStringTag](){return"Pino"},[Ww]:dv,[zw]:_v,[fd]:hv,[ud]:av,[Hi]:lv};Object.setPrototypeOf(md,Kw.prototype);gd.exports=function(){return Object.create(md)};var cr=n=>n;function bv(n,e){if(!n)throw Error("missing bindings for child Pino");let t=this[St],r=this[dn],s=Object.create(this);if(e==null)return s[dn].bindings!==cr&&(s[dn]=ji(r.level,cr,r.log)),s[ur]=qi(s,n),this.onChild!==hd&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[St]=Object.create(null);for(let c in t)s[St][c]=t[c];let a=Object.getOwnPropertySymbols(t);for(var i=0;i<a.length;i++){let c=a[i];s[St][c]=t[c]}for(let c in e.serializers)s[St][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];s[St][c]=e.serializers[c]}}else s[St]=t;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;s[dn]=ji(a||r.level,l||cr,c||r.log)}else s[dn]=ji(r.level,cr,r.log);if(e.hasOwnProperty("customLevels")===!0&&(pv(this.levels,e.customLevels),s.levels=uv(e.customLevels,s[ev]),fv(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=gv(s.redact,dd),l={stringify:a[nv]};s[rv]=dd,s[iv]=a,s[sv]=l}if(typeof e.msgPrefix=="string"&&(s[Bi]=(this[Bi]||"")+e.msgPrefix),s[ur]=qi(s,n),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[Hi](a)}return this.onChild(s),s}function wv(){let e=`{${this[ur].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function vv(n){let e=qi(this,n);this[ur]=e}function xv(n,e){return Object.assign(e,n)}function _v(n,e,t){let r=this[Jw](),s=this[Vw],i=this[Qw],o=this[Zw],a=this[Yw]||xv,l,c=this[ov].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)),s&&(l=a(l,s(l,t,this)));let u=this[fd](l,e,t,r),d=this[pd];d[tv]===!0&&(d.lastLevel=t,d.lastObj=l,d.lastMsg=e,d.lastTime=r.slice(this[Xw]),d.lastLogger=this),d.write(c?c(u):u)}function Sv(n){if(n!=null&&typeof n!="function")throw Error("callback must be a function");let e=this[pd];typeof e.flush=="function"?e.flush(n||hd):n&&n()}});var xd=L((Gi,vd)=>{"use strict";var{hasOwnProperty:fn}=Object.prototype,kt=Wi();kt.configure=Wi;kt.stringify=kt;kt.default=kt;Gi.stringify=kt;Gi.configure=Wi;vd.exports=kt;var Av=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function pt(n){return n.length<5e3&&!Av.test(n)?`"${n}"`:JSON.stringify(n)}function Ui(n,e){if(n.length>200||e)return n.sort(e);for(let t=1;t<n.length;t++){let r=n[t],s=t;for(;s!==0&&n[s-1]>r;)n[s]=n[s-1],s--;n[s]=r}return n}var kv=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Ki(n){return kv.call(n)!==void 0&&n.length!==0}function bd(n,e,t){n.length<t&&(t=n.length);let r=e===","?"":" ",s=`"0":${r}${n[0]}`;for(let i=1;i<t;i++)s+=`${e}"${i}":${r}${n[i]}`;return s}function $v(n){if(fn.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 Ev(n){let e;if(fn.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 Cv(n,e){let t;if(fn.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 wd(n,e){let t;if(fn.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 At(n){return n===1?"1 item":`${n} items`}function Tv(n){let e=new Set;for(let t of n)(typeof t=="string"||typeof t=="number")&&e.add(String(t));return e}function Rv(n){if(fn.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 r=`Object can not safely be stringified. Received type ${typeof t}`;throw typeof t!="function"&&(r+=` (${t.toString()})`),new Error(r)}}}function Wi(n){n={...n};let e=Rv(n);e&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let t=$v(n),r=Cv(n,"bigint"),s=Ev(n),i=typeof s=="function"?s:void 0,o=wd(n,"maximumDepth"),a=wd(n,"maximumBreadth");function l(h,f,g,y,w,v){let S=f[h];switch(typeof S=="object"&&S!==null&&typeof S.toJSON=="function"&&(S=S.toJSON(h)),S=y.call(f,h,S),typeof S){case"string":return pt(S);case"object":{if(S===null)return"null";if(g.indexOf(S)!==-1)return t;let k="",P=",",j=v;if(Array.isArray(S)){if(S.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(S),w!==""&&(v+=w,k+=`
526
+ ${v}`,P=`,
527
+ ${v}`);let H=Math.min(S.length,a),D=0;for(;D<H-1;D++){let _=l(String(D),S,g,y,w,v);k+=_!==void 0?_:"null",k+=P}let W=l(String(D),S,g,y,w,v);if(k+=W!==void 0?W:"null",S.length-1>a){let _=S.length-a-1;k+=`${P}"... ${At(_)} not stringified"`}return w!==""&&(k+=`
528
+ ${j}`),g.pop(),`[${k}]`}let I=Object.keys(S),$=I.length;if($===0)return"{}";if(o<g.length+1)return'"[Object]"';let E="",N="";w!==""&&(v+=w,P=`,
529
+ ${v}`,E=" ");let x=Math.min($,a);s&&!Ki(S)&&(I=Ui(I,i)),g.push(S);for(let H=0;H<x;H++){let D=I[H],W=l(D,S,g,y,w,v);W!==void 0&&(k+=`${N}${pt(D)}:${E}${W}`,N=P)}if($>a){let H=$-a;k+=`${N}"...":${E}"${At(H)} not stringified"`,N=P}return w!==""&&N.length>1&&(k=`
530
+ ${v}${k}
531
+ ${j}`),g.pop(),`{${k}}`}case"number":return isFinite(S)?String(S):e?e(S):"null";case"boolean":return S===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(S);default:return e?e(S):void 0}}function c(h,f,g,y,w,v){switch(typeof f=="object"&&f!==null&&typeof f.toJSON=="function"&&(f=f.toJSON(h)),typeof f){case"string":return pt(f);case"object":{if(f===null)return"null";if(g.indexOf(f)!==-1)return t;let S=v,k="",P=",";if(Array.isArray(f)){if(f.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(f),w!==""&&(v+=w,k+=`
532
+ ${v}`,P=`,
533
+ ${v}`);let $=Math.min(f.length,a),E=0;for(;E<$-1;E++){let x=c(String(E),f[E],g,y,w,v);k+=x!==void 0?x:"null",k+=P}let N=c(String(E),f[E],g,y,w,v);if(k+=N!==void 0?N:"null",f.length-1>a){let x=f.length-a-1;k+=`${P}"... ${At(x)} not stringified"`}return w!==""&&(k+=`
534
+ ${S}`),g.pop(),`[${k}]`}g.push(f);let j="";w!==""&&(v+=w,P=`,
535
+ ${v}`,j=" ");let I="";for(let $ of y){let E=c($,f[$],g,y,w,v);E!==void 0&&(k+=`${I}${pt($)}:${j}${E}`,I=P)}return w!==""&&I.length>1&&(k=`
536
+ ${v}${k}
537
+ ${S}`),g.pop(),`{${k}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(f);default:return e?e(f):void 0}}function u(h,f,g,y,w){switch(typeof f){case"string":return pt(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(h),typeof f!="object")return u(h,f,g,y,w);if(f===null)return"null"}if(g.indexOf(f)!==-1)return t;let v=w;if(Array.isArray(f)){if(f.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(f),w+=y;let E=`
538
+ ${w}`,N=`,
539
+ ${w}`,x=Math.min(f.length,a),H=0;for(;H<x-1;H++){let W=u(String(H),f[H],g,y,w);E+=W!==void 0?W:"null",E+=N}let D=u(String(H),f[H],g,y,w);if(E+=D!==void 0?D:"null",f.length-1>a){let W=f.length-a-1;E+=`${N}"... ${At(W)} not stringified"`}return E+=`
540
+ ${v}`,g.pop(),`[${E}]`}let S=Object.keys(f),k=S.length;if(k===0)return"{}";if(o<g.length+1)return'"[Object]"';w+=y;let P=`,
541
+ ${w}`,j="",I="",$=Math.min(k,a);Ki(f)&&(j+=bd(f,P,a),S=S.slice(f.length),$-=f.length,I=P),s&&(S=Ui(S,i)),g.push(f);for(let E=0;E<$;E++){let N=S[E],x=u(N,f[N],g,y,w);x!==void 0&&(j+=`${I}${pt(N)}: ${x}`,I=P)}if(k>a){let E=k-a;j+=`${I}"...": "${At(E)} not stringified"`,I=P}return I!==""&&(j=`
542
+ ${w}${j}
543
+ ${v}`),g.pop(),`{${j}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(f);default:return e?e(f):void 0}}function d(h,f,g){switch(typeof f){case"string":return pt(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(h),typeof f!="object")return d(h,f,g);if(f===null)return"null"}if(g.indexOf(f)!==-1)return t;let y="",w=f.length!==void 0;if(w&&Array.isArray(f)){if(f.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(f);let j=Math.min(f.length,a),I=0;for(;I<j-1;I++){let E=d(String(I),f[I],g);y+=E!==void 0?E:"null",y+=","}let $=d(String(I),f[I],g);if(y+=$!==void 0?$:"null",f.length-1>a){let E=f.length-a-1;y+=`,"... ${At(E)} not stringified"`}return g.pop(),`[${y}]`}let v=Object.keys(f),S=v.length;if(S===0)return"{}";if(o<g.length+1)return'"[Object]"';let k="",P=Math.min(S,a);w&&Ki(f)&&(y+=bd(f,",",a),v=v.slice(f.length),P-=f.length,k=","),s&&(v=Ui(v,i)),g.push(f);for(let j=0;j<P;j++){let I=v[j],$=d(I,f[I],g);$!==void 0&&(y+=`${k}${pt(I)}:${$}`,k=",")}if(S>a){let j=S-a;y+=`${k}"...":"${At(j)} not stringified"`}return g.pop(),`{${y}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(f);default:return e?e(f):void 0}}function p(h,f,g){if(arguments.length>1){let y="";if(typeof g=="number"?y=" ".repeat(Math.min(g,10)):typeof g=="string"&&(y=g.slice(0,10)),f!=null){if(typeof f=="function")return l("",{"":h},[],f,y,"");if(Array.isArray(f))return c("",h,[],Tv(f),y,"")}if(y.length!==0)return u("",h,[],y,"")}return d("",h,[])}return p}});var kd=L((jE,Ad)=>{"use strict";var Vi=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Sd}=lr(),Ov=Sd.info;function Pv(n,e){n=n||[],e=e||{dedupe:!1};let t=Object.create(Sd);t.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(d=>{t[d]=e.levels[d]});let r={write:s,add:a,remove:l,emit:i,flushSync:o,end:c,minLevel:0,lastId:0,streams:[],clone:u,[Vi]:!0,streamLevels:t};return Array.isArray(n)?n.forEach(a,r):a.call(r,n),n=null,r;function s(d){let p,h=this.lastLevel,{streams:f}=this,g=0,y;for(let w=Mv(f.length,e.dedupe);Lv(w,f.length,e.dedupe);w=Iv(w,e.dedupe))if(p=f[w],p.level<=h){if(g!==0&&g!==p.level)break;if(y=p.stream,y[Vi]){let{lastTime:v,lastMsg:S,lastObj:k,lastLogger:P}=this;y.lastLevel=h,y.lastTime=v,y.lastMsg=S,y.lastObj=k,y.lastLogger=P}y.write(d),e.dedupe&&(g=p.level)}else if(!e.dedupe)break}function i(...d){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.emit(...d)}function o(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync()}function a(d){if(!d)return r;let p=typeof d.write=="function"||d.stream,h=d.write?d:d.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:f,streamLevels:g}=this,y;typeof d.levelVal=="number"?y=d.levelVal:typeof d.level=="string"?y=g[d.level]:typeof d.level=="number"?y=d.level:y=Ov;let w={stream:h,level:y,levelVal:void 0,id:++r.lastId};return f.unshift(w),f.sort(_d),this.minLevel=f[0].level,r}function l(d){let{streams:p}=this,h=p.findIndex(f=>f.id===d);return h>=0&&(p.splice(h,1),p.sort(_d),this.minLevel=p.length>0?p[0].level:-1),r}function c(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function u(d){let p=new Array(this.streams.length);for(let h=0;h<p.length;h++)p[h]={level:d,stream:this.streams[h].stream};return{write:s,add:a,remove:l,minLevel:d,streams:p,clone:u,emit:i,flushSync:o,[Vi]:!0}}}function _d(n,e){return n.level-e.level}function Mv(n,e){return e?n-1:0}function Iv(n,e){return e?n-1:n+1}function Lv(n,e,t){return t?n>=0:n<e}Ad.exports=Pv});var Xi=L((HE,Te)=>{"use strict";var Dv=require("node:os"),Md=pi(),Fv=hi(),Nv=yi(),Id=cu(),jv=yd(),Ld=Ht(),{configure:Hv}=xd(),{assertDefaultLevelFound:Bv,mappings:Dd,genLsCache:qv,genLevelComparison:Uv,assertLevelComparison:Kv}=Fi(),{DEFAULT_LEVELS:Fd,SORTING_ORDER:Wv}=lr(),{createArgsNormalizer:Gv,asChindings:Vv,buildSafeSonicBoom:$d,buildFormatters:zv,stringify:zi,normalizeDestFileDescriptor:Ed,noop:Yv}=ar(),{version:Jv}=Ni(),{chindingsSym:Cd,redactFmtSym:Xv,serializersSym:Td,timeSym:Qv,timeSliceIndexSym:Zv,streamSym:ex,stringifySym:Rd,stringifySafeSym:Yi,stringifiersSym:Od,setLevelSym:tx,endSym:nx,formatOptsSym:rx,messageKeySym:sx,errorKeySym:ix,nestedKeySym:ox,mixinSym:ax,levelCompSym:lx,useOnlyCustomLevelsSym:cx,formattersSym:Pd,hooksSym:ux,nestedKeyStrSym:dx,mixinMergeStrategySym:fx,msgPrefixSym:px}=Ld,{epochTime:Nd,nullTime:hx}=Id,{pid:mx}=process,gx=Dv.hostname(),yx=Md.err,bx={level:"info",levelComparison:Wv.ASC,levels:Fd,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:mx,hostname:gx},serializers:Object.assign(Object.create(null),{err:yx}),formatters:Object.assign(Object.create(null),{bindings(n){return n},level(n,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Nd,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},wx=Gv(bx),vx=Object.assign(Object.create(null),Md);function Ji(...n){let e={},{opts:t,stream:r}=wx(e,Fv(),...n);t.level&&typeof t.level=="string"&&Fd[t.level.toLowerCase()]!==void 0&&(t.level=t.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:u,base:d,name:p,level:h,customLevels:f,levelComparison:g,mixin:y,mixinMergeStrategy:w,useOnlyCustomLevels:v,formatters:S,hooks:k,depthLimit:P,edgeLimit:j,onChild:I,msgPrefix:$}=t,E=Hv({maximumDepth:P,maximumBreadth:j}),N=zv(S.level,S.bindings,S.log),x=zi.bind({[Yi]:E}),H=s?Nv(s,x):{},D=s?{stringify:H[Xv]}:{stringify:x},W="}"+(i?`\r
707
544
  `:`
708
- `),C=gS.bind(null,{[cp]:"",[up]:o,[fp]:F,[dp]:ia,[oa]:T,[pp]:P}),E="";f!==null&&(h===void 0?E=C(f):E=C(Object.assign({},f,{name:h})));let J=a instanceof Function?a:a?vp:NS,D=J().indexOf(":")+1;if(k&&!p)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(x&&typeof x!="string")throw Error(`Unknown msgPrefix type "${typeof x}" - expected "string"`);uS(m,p,k);let Q=yp(p,k);typeof s.emit=="function"&&s.emit("message",{code:"PINO_CONFIG",config:{levels:Q,messageKey:l,errorKey:c}}),pS(y);let ve=fS(y);return Object.assign(e,{levels:Q,[OS]:ve,[PS]:k,[_S]:s,[xS]:J,[SS]:D,[dp]:ia,[oa]:T,[fp]:F,[kS]:V,[$S]:j,[ES]:l,[TS]:c,[CS]:d,[MS]:d?`,${JSON.stringify(d)}:{`:"",[up]:o,[RS]:S,[LS]:_,[cp]:E,[pp]:P,[IS]:g,silent:bS,onChild:w,[DS]:x}),Object.setPrototypeOf(e,lS()),dS(e),e[AS](m),e}je.exports=aa;je.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=lp(n.dest||process.stdout.fd),ap(n)):ap({dest:lp(n),minLength:0});je.exports.transport=Uo();je.exports.multistream=op();je.exports.levels=yp();je.exports.stdSerializers=KS;je.exports.stdTimeFunctions=Object.assign({},mp);je.exports.symbols=gp;je.exports.version=vS;je.exports.default=aa;je.exports.pino=aa});function wp(n){return new ca(n)}var qS,WS,GS,ca,xp=N(()=>{"use strict";qS={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},WS=`
545
+ `),_=Vv.bind(null,{[Cd]:"",[Td]:o,[Od]:H,[Rd]:zi,[Yi]:E,[Pd]:N}),b="";d!==null&&(p===void 0?b=_(d):b=_(Object.assign({},d,{name:p})));let z=a instanceof Function?a:a?Nd:hx,V=z().indexOf(":")+1;if(v&&!f)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(y&&typeof y!="function")throw Error(`Unknown mixin type "${typeof y}" - expected "function"`);if($&&typeof $!="string")throw Error(`Unknown msgPrefix type "${typeof $}" - expected "string"`);Bv(h,f,v);let ge=Dd(f,v);typeof r.emit=="function"&&r.emit("message",{code:"PINO_CONFIG",config:{levels:ge,messageKey:l,errorKey:c}}),Kv(g);let ye=Uv(g);return Object.assign(e,{levels:ge,[lx]:ye,[cx]:v,[ex]:r,[Qv]:z,[Zv]:V,[Rd]:zi,[Yi]:E,[Od]:H,[nx]:W,[rx]:D,[sx]:l,[ix]:c,[ox]:u,[dx]:u?`,${JSON.stringify(u)}:{`:"",[Td]:o,[ax]:y,[fx]:w,[Cd]:b,[Pd]:N,[ux]:k,silent:Yv,onChild:I,[px]:$}),Object.setPrototypeOf(e,jv()),qv(e),e[tx](h),e}Te.exports=Ji;Te.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=Ed(n.dest||process.stdout.fd),$d(n)):$d({dest:Ed(n),minLength:0});Te.exports.transport=Oi();Te.exports.multistream=kd();Te.exports.levels=Dd();Te.exports.stdSerializers=vx;Te.exports.stdTimeFunctions=Object.assign({},Id);Te.exports.symbols=Ld;Te.exports.version=Jv;Te.exports.default=Ji;Te.exports.pino=Ji});function Zi(){try{if(Ut.existsSync(jd)){let n=Ut.readFileSync(jd,"utf-8"),e=JSON.parse(n);return{...Hd,...e}}}catch{}return{...Hd}}var Ut,Qi,Bd,jd,Hd,qd=M(()=>{"use strict";Ut=C(require("fs")),Qi=C(require("path")),Bd=C(require("os")),jd=Qi.join(Bd.homedir(),".hablas","agents.json"),Hd={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}}});function Ud(n){return new eo(n)}var xx,_x,Sx,eo,Kd=M(()=>{"use strict";xx={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},_x=`
709
546
  ## Reasoning Protocol
710
547
 
711
548
  Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
@@ -734,17 +571,17 @@ After receiving a tool result, think again:
734
571
  - One tool call per turn. Wait for the result before the next call.
735
572
  - If a tool fails, analyze the error in <thinking> before retrying.
736
573
  - When done, give a concise final answer WITHOUT <thinking> tags.
737
- `.trim(),GS=`
574
+ `.trim(),Sx=`
738
575
  ## Reasoning
739
576
  For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
740
577
  The user will NOT see thinking blocks. One tool call per turn.
741
- `.trim(),ca=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...qS,...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}
578
+ `.trim(),eo=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...xx,...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}
742
579
 
743
- ${GS}`:`${e}
580
+ ${Sx}`:`${e}
744
581
 
745
- ${WS}`}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(`
582
+ ${_x}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let t=[],r=e,s=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=s.exec(e))!==null;)t.push(i[1].trim());r=r.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)t.push(i[1].trim());r=r.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(r);a&&(t.push(a[1].trim()),r=r.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(r);return l&&(t.push(l[1].trim()),r=r.replace(/<think>[\s\S]*$/i,"")),{thinking:t.join(`
746
583
 
747
- `).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`
584
+ `).trim(),visibleContent:r.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 r=this.turnSteps[this.turnSteps.length-1];r&&(r.observation=e,t&&(r.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,r){return`
748
585
  <self_eval>
749
586
  You just completed this task: "${e}"
750
587
 
@@ -753,7 +590,7 @@ Your answer was:
753
590
  ${t.slice(0,1500)}
754
591
  """
755
592
 
756
- Tools used: ${s.length>0?s.join(", "):"none"}
593
+ Tools used: ${r.length>0?r.join(", "):"none"}
757
594
 
758
595
  Rate your work. Reply with ONLY a JSON object \u2014 no other text:
759
596
  {
@@ -764,23 +601,23 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
764
601
  "confidence": "<high|medium|low>"
765
602
  }
766
603
  </self_eval>
767
- `.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(`
768
- `)}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 Sp(n=3){return new ua(n)}var VS,ua,_p=N(()=>{"use strict";VS=[{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}],ua=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 VS)if(a.test(t)){let l=r?.lastStrategy===a.strategy&&i>=2,c=l?"decompose_task":a.strategy;return o.lastStrategy=c,this.failures.set(e,o),{errorClass:a.errorClass,strategy:c,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(`
769
- `)}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 zS(){try{if(vt.existsSync(Xs))return JSON.parse(vt.readFileSync(Xs,"utf-8"))}catch{}return{}}function YS(n){try{let e=Zs.dirname(Xs);vt.existsSync(e)||vt.mkdirSync(e,{recursive:!0}),vt.writeFileSync(Xs,JSON.stringify(n,null,2),"utf-8")}catch{}}function ha(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 Hn(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 JS(n){return n.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function QS(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=ha(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 XS(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=Hn(r);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function ZS(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=Hn(r);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function e_(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=kp(r);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function kp(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={},c=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,d;for(;(d=c.exec(o))!==null;){let h=d[1].toLowerCase(),m=d[2]??d[3]??d[4];l[h]=JS(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 t_(n){return kp(n)}function n_(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=Hn(r);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function s_(n){let e=[],t=/\{\s*"function"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=ha(n,s.index);if(r)try{let i=JSON.parse(r),o=Hn(i);o&&e.push({...o,format:"function_call",rawMatch:r})}catch{}}return e}function r_(n){let e=[],t=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=ha(n,s.index);if(r)try{let i=JSON.parse(r),o=Hn(i);o&&e.push({...o,format:"json_object",rawMatch:r})}catch{}}return e}function i_(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={},c=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,d;for(;(d=c.exec(i))!==null;){let f=d[1].trim(),h=d[2].trim();h==="true"?h=!0:h==="false"?h=!1:!isNaN(Number(h))&&h!==""&&(h=Number(h)),l[f]=h}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:s[0]})}}if(!r&&/<function=([^>]+)>/i.test(n)){let i=/<function=([^>]+)>/i.exec(n);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,c;for(;(c=l.exec(n))!==null;){let d=c[1].trim(),f=c[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 $p(){return fa||(fa=new pa),fa}var vt,Zs,Ap,Xs,da,pa,fa,Ep=N(()=>{"use strict";vt=O(require("fs")),Zs=O(require("path")),Ap=O(require("os")),Xs=Zs.join(Ap.homedir(),".hablas","model-formats.json");da=[{format:"action_tag_json",parse:QS},{format:"xml_tool_call_wrapper",parse:e_},{format:"xml_prompt",parse:t_},{format:"xml_tags",parse:XS},{format:"xml_parameters",parse:i_},{format:"hermes",parse:ZS},{format:"markdown_json",parse:n_},{format:"function_call",parse:s_},{format:"json_object",parse:r_}],pa=class{registry;constructor(){this.registry=zS()}parse(e,t,s){if(t&&Array.isArray(t)&&t.length>0){let o=t.filter(a=>a?.function?.name&&typeof a.function.name=="string");if(o.length>0){let a=o.map(l=>({function:{name:l.function.name,arguments:l.function.arguments||{}}}));return s&&this.learnFormat(s,"native"),{toolCalls:a,displayContent:(e||"").trim(),format:"native"}}}let r=e||"";if(!r.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(s){let o=this.registry[s];if(o&&o.format!=="native"){let a=da.find(l=>l.format===o.format);if(a){let l=a.parse(r);if(l.length>0)return this.learnFormat(s,o.format),this.buildResult(l,r)}}}for(let{parse:o}of da){let a=o(r);if(a.length>0){let l=a[0].format;return s&&this.learnFormat(s,l),this.buildResult(a,r)}}let i=r.trim();return i=i.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),i=i.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),i=i.replace(/<<?action>>?[\s\S]*?<<?\/action>>?/gi,""),i=i.replace(/<<?response>>?/gi,"").replace(/<<?\/response>>?/gi,""),{toolCalls:[],displayContent:i.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 da)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()},YS(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(/<<?response>>?/gi,"").replace(/<<?\/response>>?/gi,""),r=r.replace(/\n{3,}/g,`
604
+ `.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 r of t){let s=e.match(r);if(s)try{let i=JSON.parse(s[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,r=typeof e.completed=="boolean"?e.completed:t>=7,s=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:r,rationale:s,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,r){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: ${r.slice(0,300)}`,"</thinking>"].join(`
605
+ `)}getTurnSummary(){let e=this.turnSteps.length,t=this.turnSteps.filter(s=>s.action).length,r=this.turnSteps.filter(s=>s.reflection).length;return`${e} steps, ${t} actions, ${r} reflections`}}});function Wd(n=3){return new to(n)}var Ax,to,Gd=M(()=>{"use strict";Ax=[{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}],to=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,t,r){let s=this.failures.get(e),i=s?s.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 Ax)if(a.test(t)){let l=s?.lastStrategy===a.strategy&&i>=2,c=l?"decompose_task":a.strategy;return o.lastStrategy=c,this.failures.set(e,o),{errorClass:a.errorClass,strategy:c,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 r=[`ERROR: ${t}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&r.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":r.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":r.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":r.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":r.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":r.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":r.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return r.join(`
606
+ `)}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 kx(){try{if(tt.existsSync(dr))return JSON.parse(tt.readFileSync(dr,"utf-8"))}catch{}return{}}function $x(n){try{let e=fr.dirname(dr);tt.existsSync(e)||tt.mkdirSync(e,{recursive:!0}),tt.writeFileSync(dr,JSON.stringify(n,null,2),"utf-8")}catch{}}function io(n,e){let t=0,r=!1,s=!1;for(let i=e;i<n.length;i++){let o=n[i];if(s){s=!1;continue}if(o==="\\"&&r){s=!0;continue}if(o==='"'){r=!r;continue}if(!r&&(o==="{"&&t++,o==="}"&&(t--,t===0)))return n.slice(e,i+1)}return null}function pn(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 Ex(n){return n.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Cx(n){let e=[],t=/<<?action\s*>>?([\s\S]*?)(?:<<?\/action\s*>>?|$)/gi,r;for(;(r=t.exec(n))!==null;){let s=r[1].trim();if(s)try{let i=JSON.parse(s);i.tool&&i.args&&typeof i.args=="object"&&e.push({tool:i.tool,args:i.args,format:"action_tag_json",rawMatch:r[0]})}catch{let i=io(s,s.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:r[0]})}catch{}}}return e}function Tx(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,r;for(;(r=t.exec(n))!==null;)try{let s=JSON.parse(r[1].trim()),i=pn(s);i&&e.push({...i,format:"xml_tags",rawMatch:r[0]})}catch{}return e}function Rx(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,r;for(;(r=t.exec(n))!==null;)try{let s=JSON.parse(r[1].trim());if(s.parameters||s.name){let i=pn(s);i&&e.push({...i,format:"hermes",rawMatch:r[0]})}}catch{}return e}function Ox(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,r;for(;(r=t.exec(n))!==null;){let s=r[1],i=zd(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:r[0]})}return e}function zd(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 r of t){let s=new RegExp(`<<?${r}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${r}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(n))!==null;){let o=i[1]||"",a=i[2]||"",l={},c=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,u;for(;(u=c.exec(o))!==null;){let p=u[1].toLowerCase(),h=u[2]??u[3]??u[4];l[p]=Ex(h)}let d=a.trim();d&&(r==="write_file"||r==="append_to_file"?l.content=a:r==="run_command"?l.command=d:r==="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)),r==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:r,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function Px(n){return zd(n)}function Mx(n){let e=[],t=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,r;for(;(r=t.exec(n))!==null;)try{let s=JSON.parse(r[1].trim()),i=pn(s);i&&e.push({...i,format:"markdown_json",rawMatch:r[0]})}catch{}return e}function Ix(n){let e=[],t=/\{\s*"function"\s*:/g,r;for(;(r=t.exec(n))!==null;){let s=io(n,r.index);if(s)try{let i=JSON.parse(s),o=pn(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function Lx(n){let e=[],t=/\{\s*"(?:name|tool)"\s*:/g,r;for(;(r=t.exec(n))!==null;){let s=io(n,r.index);if(s)try{let i=JSON.parse(s),o=pn(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function Dx(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,r,s=!1;for(;(r=t.exec(n))!==null;){let i=r[1],o=/<function=([^>]+)>/i.exec(i);if(o){s=!0;let a=o[1].trim(),l={},c=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=c.exec(i))!==null;){let d=u[1].trim(),p=u[2].trim();p==="true"?p=!0:p==="false"?p=!1:!isNaN(Number(p))&&p!==""&&(p=Number(p)),l[d]=p}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:r[0]})}}if(!s&&/<function=([^>]+)>/i.test(n)){let i=/<function=([^>]+)>/i.exec(n);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,c;for(;(c=l.exec(n))!==null;){let u=c[1].trim(),d=c[2].trim();d==="true"?d=!0:d==="false"?d=!1:!isNaN(Number(d))&&d!==""&&(d=Number(d)),a[u]=d}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:n})}}return e}function Yd(){return ro||(ro=new so),ro}var tt,fr,Vd,dr,no,so,ro,Jd=M(()=>{"use strict";tt=C(require("fs")),fr=C(require("path")),Vd=C(require("os")),dr=fr.join(Vd.homedir(),".hablas","model-formats.json");no=[{format:"action_tag_json",parse:Cx},{format:"xml_tool_call_wrapper",parse:Ox},{format:"xml_prompt",parse:Px},{format:"xml_tags",parse:Tx},{format:"xml_parameters",parse:Dx},{format:"hermes",parse:Rx},{format:"markdown_json",parse:Mx},{format:"function_call",parse:Ix},{format:"json_object",parse:Lx}],so=class{registry;constructor(){this.registry=kx()}parse(e,t,r){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 r&&this.learnFormat(r,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let s=e||"";if(!s.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(r){let i=this.registry[r];if(i&&i.format!=="native"){let o=no.find(a=>a.format===i.format);if(o){let a=o.parse(s);if(a.length>0)return this.learnFormat(r,i.format),this.buildResult(a,s)}}}for(let{parse:i}of no){let o=i(s);if(o.length>0){let a=o[0].format;return r&&this.learnFormat(r,a),this.buildResult(o,s)}}return{toolCalls:[],displayContent:s.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:r}of no)if(r(e).length>0)return t;return"unknown"}learnFormat(e,t){let r=this.registry[e];r&&r.format===t?(r.successCount++,r.lastUsed=new Date().toISOString()):this.registry[e]={format:t,successCount:1,lastUsed:new Date().toISOString()},$x(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[t,r]of Object.entries(this.registry))e[t]={format:r.format,successCount:r.successCount};return e}buildResult(e,t){let r=e.map(o=>({function:{name:o.tool,arguments:o.args}})),s=t,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)s=s.replace(o.rawMatch,"");return s=s.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),s=s.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),s=s.replace(/<<?action>>?[\s\S]*?<<?\/action>>?/gi,""),s=s.replace(/\n{3,}/g,`
770
607
 
771
- `),{toolCalls:s,displayContent:r.trim(),format:e[0]?.format??"unknown"}}},fa=null});function a_(n,e,t){let r=$p().parse(e,n,t);return{toolCalls:r.toolCalls,displayContent:r.displayContent}}function l_(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 c_(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 Rp(n,e,t,s){let r=0,i=Date.now();for(;r<=Cp;){let o=await n.execute({name:e,arguments:t});if(o.success||r>=Cp)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 tr(n){let{identity:e,client:t,registry:s,session:r,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:d}=n,f=n.reactEngine??wp(),h=n.errorRecovery??Sp(),m=d?[]:s.getOllamaTools(),p=t.getModel(),y=n.maxIterations??150,S="IDLE",_=0,k=(T,P)=>{let $=o_[S];if(!$||!$.includes(T))throw new Error(`\u{1F6AB} Illegal State Transition Attempt: ${S} \u2501\u2501\u25B6 ${T} (Reason: ${P??"none"})`);o.info({from:S,to:T,reason:P},"FSM State Transition"),S=T},A=[],g=[],v=[],b="",w=0,x=!1;for(k("THINKING","Starting agentic turn");w<y;){if(w++,c?.aborted)return k("TERMINAL_ABORT","Operation aborted by signal"),{output:b,toolsUsed:Te(A),toolResults:g,touchedFiles:Te(v),iterations:w,success:!1,error:"Aborted",completedNaturally:x};let T=f.buildBudgetWarningPrompt();T&&r.addUserMessage(T,{priority:"critical",tags:["system-budget"]});let P;try{P=await t.chatWithTools(r.getMessages(),m,c)}catch(E){if(E.name==="AbortError"||c?.aborted)return k("TERMINAL_ABORT","Aborted during inference"),{output:b,toolsUsed:Te(A),toolResults:g,touchedFiles:Te(v),iterations:w,success:!1,error:"Aborted",completedNaturally:x};if(w<=1){a.onNotice?.(`Transient model error: ${E.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(J=>setTimeout(J,1e3)),w--;continue}return k("TERMINAL_ABORT","Inference failure"),a.onError?.(E.message??"Model request failed"),{output:b,toolsUsed:Te(A),toolResults:g,touchedFiles:Te(v),iterations:w,success:!1,error:E.message,completedNaturally:x}}let $=P.message?.content||"",F=P.message?.tool_calls,j=f.parseThinking($);j.hasThinking&&(f.recordStep({thought:j.thinking}),o.debug({thinking:j.thinking.slice(0,200)},"ReAct thinking")),k("PARSE_VALIDATING","Received model response, parsing");let{toolCalls:V,displayContent:C}=a_(F,$,p);if(V.length===0&&$.toLowerCase().includes("<action>")){if(_++,_>=er){k("STATE_RECONCILIATION",`Self-correction loop exhausted after ${_} attempts`);let J=`Failed to execute after ${er} syntax corrections. Rollback initiated.`;a.onError?.(J);try{let D=s.get("undo");D&&await D.execute({count:100})}catch{}return k("TERMINAL_ABORT","Fatal syntactic self-correction exhaustion"),{output:b,toolsUsed:Te(A),toolResults:g,touchedFiles:Te(v),iterations:w,success:!1,error:J,completedNaturally:x}}let E=`[SYSTEM ERROR - RETRY ${_}/${er}] Malformed action block detected inside <action> tags. Expected a valid JSON object matching the HEP-1 tool schema.
772
- Please correct your format and try again. Ensure all JSON keys/values are double-quoted and correctly escaped.`;k("ERROR_HEALING",`Syntax error inside action tags (attempt ${_})`),a.onNotice?.(`Malformed action block detected \u2014 healing attempt ${_}/${er}\u2026`,"retry"),r.addToolMessage(E),k("THINKING","Error injected, waiting for next generation");continue}if(C&&C.trim()&&(b=C,await a.onAssistantText?.(C,e)),$.includes("ESCALATE_SCOPE")||v.length>3){k("ESCALATING","Detected need for scope escalation"),a.onNotice?.("Escalating scope: Task requires more specialized agents.","info"),r.addAssistantMessage($,V,e.role),x=!0;break}if(V.length===0){r.addAssistantMessage($,void 0,e.role),x=!0,k("SYNTHESIZING","Completed execution naturally");break}k("ACTION_READY","Action parsed and verified"),r.addAssistantMessage($,V,e.role);for(let E=0;E<V.length;E++){let J=V[E];if(!J?.function?.name)continue;let D=J.function.name,Q=J.function.arguments||{},ve=s.getSafetyLevel(D)??"confirm";if(!s.get(D)){k("ERROR_HEALING",`Unknown tool execution: ${D}`),a.onNotice?.(`Unknown tool: ${D} \u2014 skipping`,"warn"),r.addToolMessage(`Error: Unknown tool "${D}". Available: ${s.getAll().map(pe=>pe.name).join(", ")}`),k("THINKING","Returning to thought loop");continue}if(await l(D,ve,Q)==="skip"){r.addToolMessage(`Tool ${D} was skipped by policy/user.`);break}A.push(D),typeof Q.path=="string"&&v.push(Q.path);let Vt=l_(D,Q);a.onToolStart?.(D,Vt,Q),a.onToolCall?.(),f.recordStep({thought:j.hasThinking?`Executing: ${D}`:"",action:D,actionInput:Q}),k("EXECUTING_TOOL",`Executing tool: ${D}`);let Se=await Rp(s,D,Q,o);a.onToolEnd?.(D,Se.success,Se.error||Se.output,Se.duration,Q);let qe;if(Se.success)qe=Pn(Se.output,Tp),f.recordObservation(qe.slice(0,300)),g.push({tool:D,success:!0,summary:Se.output.slice(0,150)}),k("THINKING",`Successfully executed tool: ${D}`);else{let pe=Se.error||"Unknown error";if(c_(pe)){k("STATE_RECONCILIATION",`Critical failure in tool ${D}: ${pe}`),a.onNotice?.("Critical tool failure \u2014 aborting and rolling back changes.","warn");try{let Ae=s.get("undo");Ae&&await Ae.execute({count:100})}catch{}return k("TERMINAL_ABORT","State reverted due to critical failure"),{output:b,toolsUsed:Te(A),toolResults:g,touchedFiles:Te(v),iterations:w,success:!1,error:pe,completedNaturally:x}}let q=h.analyze(D,pe,Q);if(qe=h.buildRecoveryMessage(q,pe),f.recordObservation(`FAILED: ${pe}`,`Recovery: ${q.strategy} \u2014 ${q.suggestion}`),g.push({tool:D,success:!1,summary:pe.slice(0,150)}),q.autoRetry&&!f.isOverBudget()){k("ERROR_HEALING","Attempting auto-recovery for transient error"),a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let Ae=await Rp(s,D,Q,o);a.onToolEnd?.(D,Ae.success,Ae.output,Ae.duration,Q),Ae.success?(qe=Pn(Ae.output,Tp),f.recordObservation(qe.slice(0,300),"Auto-retry succeeded"),g[g.length-1]={tool:D,success:!0,summary:Ae.output.slice(0,150)},k("THINKING","Recovery successful")):k("THINKING","Recovery failed, continuing turn")}else k("THINKING","Continuing turn with failed step")}r.addToolMessage(qe),Se.success&&D==="read_file"&&typeof Q.path=="string"&&i?.addFile(Q.path,Se.output),o.info({tool:D,success:Se.success,durationMs:Se.duration,retries:Se.retries},"Tool executed")}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return w>=y&&!x?(a.onNotice?.(`Reached max iterations (${y}). Stopping.`,"warn"),k("TERMINAL_ABORT","Max iterations boundary exceeded"),{output:b,toolsUsed:Te(A),toolResults:g,touchedFiles:Te(v),iterations:w,success:!1,error:"Max iterations exceeded",completedNaturally:x}):(k("TERMINAL_SUCCESS","Turn finalized successfully"),S="IDLE",{output:b,toolsUsed:Te(A),toolResults:g,touchedFiles:Te(v),iterations:w,success:!0,completedNaturally:x})}function Te(n){return[...new Set(n)]}function Op(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 Pp(){return(n,e)=>e==="dangerous"?"skip":"allow"}var Tp,Cp,er,o_,ma=N(()=>{"use strict";qi();xp();_p();Ep();Tp=2e3,Cp=2,er=3,o_={IDLE:["THINKING"],THINKING:["PARSE_VALIDATING","TERMINAL_ABORT","ESCALATING"],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","ESCALATING"],ERROR_HEALING:["THINKING","STATE_RECONCILIATION","TERMINAL_ABORT"],STATE_RECONCILIATION:["TERMINAL_ABORT"],SYNTHESIZING:["TERMINAL_SUCCESS","TERMINAL_ABORT"],ESCALATING:["SYNTHESIZING","TERMINAL_ABORT"],TERMINAL_SUCCESS:["IDLE"],TERMINAL_ABORT:["IDLE"]}});var Mp,u_,d_,f_,Ip,nr,Lp=N(()=>{"use strict";Mp=O(la());xn();Gi();Wi();Sn();fi();ho();ma();u_={hablas:"planner",bob:"architect",alex:"coder",david:"researcher",emma:"product-manager"},d_=(0,Mp.default)({level:"silent"}),f_=40,Ip={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}},nr=class{baseConfig;agentModels;toolRegistry=null;onOutput=null;channel=null;mindsetRegistry=Os();sharedContext=null;contextManager;constructor(e){this.baseConfig=e,this.agentModels=_n(),this.contextManager=new rn(e)}setSharedContext(e){this.sharedContext=e}setChannel(e){this.channel=e}setToolRegistry(e){this.toolRegistry=e}setOutputCallback(e){this.onOutput=e}reloadModels(){this.agentModels=_n()}getAgentModel(e){let t=this.agentModels[e];if(t)return{model:t.model,temperature:t.temperature??Ip[e]?.temperature??.5};let s=Ip[e];return{model:s.model,temperature:s.temperature??.5}}async runAgent(e,t,s,r,i){let o=Date.now(),a=he.find(k=>k.role===e),l=this.getAgentModel(e),c=i?.maxIterations||f_,d={...this.baseConfig,model:l.model},f=We(d),h=this.buildAgentPrompt(a,s),m=new an(h,30,this.baseConfig.contextBudget);m.addUserMessage(t);let p={name:a.name,title:a.title,role:e};this.emit(a.name,"thinking",`\u2605 Hablas \u2192 Delegating to @${a.name} (${a.title})...`);let y={onAssistantText:k=>{this.emit(a.name,"speaking",k.slice(0,200))},onToolStart:(k,A,g)=>{this.emit(a.name,"tool",A),this.channel&&this.channel.emitEvent({type:"act",agent:a.name,toolName:k,toolArgs:this.safeArgs(g),content:A})},onToolEnd:(k,A,g)=>{this.channel&&this.channel.emitEvent({type:"observe",agent:a.name,toolName:k,success:A,content:A?this.summarizeOk(k,g):`error: ${g.slice(0,120)}`})},onError:k=>this.emit(a.name,"error",k)},S=await tr({identity:p,client:f,registry:this.toolRegistry,session:m,contextManager:this.contextManager,logger:d_,io:y,safetyPolicy:Pp(),abortSignal:i?.abortSignal,skipTools:(!r||r.length===0,!1),maxIterations:c});if(this.sharedContext&&S.touchedFiles.length)try{this.sharedContext.set(`files:@${a.name}`,S.touchedFiles.join(", "))}catch{}let _=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:_,touchedFiles:S.touchedFiles}}async runSequential(e,t,s){let r=[],i="",o=[];for(let a=0;a<e.length;a++){let{role:l,task:c}=e[a];if(s?.abortSignal?.aborted)break;let d=[];if(i&&(d.push("## Previous Agent Results"),d.push(i)),o.length>0){d.push(`
773
- ## Handoff Chain`);for(let p of o)d.push(`- @${p.from} \u2192 @${p.to}: ${p.context.slice(0,100)}`)}let f=d.join(`
774
- `),h=he.find(p=>p.role===l);if(h&&a>0){let p=e[a-1].role,y=he.find(S=>S.role===p);this.emit(h.name,"thinking",`\u2605 Handoff: @${y?.name||p} \u2192 @${h.name} (${h.title})`)}let m=await this.runAgent(l,c,f,t,s);if(r.push(m),m.success&&m.output){let p=m.output.length>600?m.output.slice(0,600)+"...":m.output;i+=`
608
+ `),{toolCalls:r,displayContent:s.trim(),format:e[0]?.format??"unknown"}}},ro=null});function Nx(n,e,t){let s=Yd().parse(e,n,t);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function jx(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 Hx(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 Zd(n,e,t,r){let s=0,i=Date.now();for(;s<=Qd;){let o=await n.execute({name:e,arguments:t});if(o.success||s>=Qd)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:s};s++,r.info({tool:e,retry:s,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:s}}async function pr(n){let{identity:e,client:t,registry:r,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:u}=n,d=n.reactEngine??Ud(),p=n.errorRecovery??Wd(),h=u?[]:r.getOllamaTools(),f=t.getModel(),g=n.maxIterations??Fx,y=[],w=[],v=[],S="",k=0,P=!1;for(;k<g;){if(k++,c?.aborted)return{output:S,toolsUsed:ht(y),toolResults:w,touchedFiles:ht(v),iterations:k,success:!1,error:"Aborted",completedNaturally:P};let j=d.buildBudgetWarningPrompt();j&&s.addUserMessage(j,{priority:"critical",tags:["system-budget"]});let I;try{I=await t.chatWithTools(s.getMessages(),h,c)}catch(W){let _=W;if(_.name==="AbortError"||c?.aborted)return{output:S,toolsUsed:ht(y),toolResults:w,touchedFiles:ht(v),iterations:k,success:!1,error:"Aborted",completedNaturally:P};if(k<=1){a.onNotice?.(`Transient model error: ${_.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(b=>setTimeout(b,1e3)),k--;continue}return a.onError?.(_.message??"Model request failed"),{output:S,toolsUsed:ht(y),toolResults:w,touchedFiles:ht(v),iterations:k,success:!1,error:_.message,completedNaturally:P}}let $=I.message?.content||"",E=I.message?.tool_calls,N=d.parseThinking($);N.hasThinking&&(d.recordStep({thought:N.thinking}),o.debug({thinking:N.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:x,displayContent:H}=Nx(E,$,f);if(x.length===0&&$.toLowerCase().includes("<action>")){let W=`[SYSTEM ERROR] Malformed action block detected inside <action> tags. Expected a valid JSON object matching the HEP-1 tool schema.
609
+ Please correct your format and try again. Ensure all JSON keys/values are double-quoted and correctly escaped.`;a.onNotice?.("Malformed action block detected \u2014 triggering self-correction loop\u2026","retry"),s.addToolMessage(W);continue}if(H&&H.trim()&&(S=H,await a.onAssistantText?.(H,e)),x.length===0){s.addAssistantMessage($,void 0,e.role),P=!0;break}s.addAssistantMessage($,x,e.role);let D=x.length;for(let W=0;W<x.length;W++){let _=x[W];if(!_?.function?.name)continue;let b=_.function.name,z=_.function.arguments||{},V=r.getSafetyLevel(b)??"confirm";if(!r.get(b)){a.onNotice?.(`Unknown tool: ${b} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${b}". Available: ${r.getAll().map(ct=>ct.name).join(", ")}`);continue}if(await l(b,V,z)==="skip"){s.addToolMessage(`Tool ${b} was skipped by policy/user.`);break}y.push(b),typeof z.path=="string"&&v.push(z.path);let ye=jx(b,z);a.onToolStart?.(b,ye,z),a.onToolCall?.(),d.recordStep({thought:N.hasThinking?`Executing: ${b}`:"",action:b,actionInput:z});let Y=await Zd(r,b,z,o);a.onToolEnd?.(b,Y.success,Y.error||Y.output,Y.duration,z);let Me;if(Y.success)Me=on(Y.output,Xd),d.recordObservation(Me.slice(0,300)),w.push({tool:b,success:!0,summary:Y.output.slice(0,150)});else{let ct=Y.error||"Unknown error",Ie=p.analyze(b,ct,z);if(Me=p.buildRecoveryMessage(Ie,ct),d.recordObservation(`FAILED: ${ct}`,`Recovery: ${Ie.strategy} \u2014 ${Ie.suggestion}`),o.info({tool:b,errorClass:Ie.errorClass,strategy:Ie.strategy},"Error recovery analysis"),w.push({tool:b,success:!1,summary:ct.slice(0,150)}),Ie.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let he=await Zd(r,b,z,o);a.onToolEnd?.(b,he.success,he.output,he.duration,z),he.success&&(Me=on(he.output,Xd),d.recordObservation(Me.slice(0,300),"Auto-retry succeeded"),w[w.length-1]={tool:b,success:!0,summary:he.output.slice(0,150)})}}if(s.addToolMessage(Me),Y.success&&b==="read_file"&&typeof z.path=="string"&&i?.addFile(z.path,Y.output),o.info({tool:b,success:Y.success,durationMs:Y.duration,retries:Y.retries},"Tool executed"),!Y.success&&Hx(Y.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}D>1&&W<D-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return k>=g&&!P&&a.onNotice?.(`Reached max iterations (${g}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:S,toolsUsed:ht(y),toolResults:w,touchedFiles:ht(v),iterations:k,success:!0,completedNaturally:P}}function ht(n){return[...new Set(n)]}function ef(n){return async(e,t)=>{let r=e.replace(/_/g," ");return!n.autoMode&&n.interactive?t==="confirm"&&n.confirm?await n.confirm(`Proceed with ${r}?`)?"allow":"skip":t==="dangerous"&&n.confirmDangerous?await n.confirmDangerous(`Dangerous: ${r}`)?"allow":"skip":"allow":!n.autoMode&&t==="dangerous"?"skip":"allow"}}function tf(){return(n,e)=>e==="dangerous"?"skip":"allow"}var Fx,Xd,Qd,oo=M(()=>{"use strict";Ms();Kd();Gd();Jd();Fx=150,Xd=2e3,Qd=2});var rf,Bx,qx,Ux,nf,hr,sf=M(()=>{"use strict";rf=C(Xi());Dn();Ls();Is();en();qd();ni();oo();Bx={hablas:"planner",bob:"architect",alex:"coder",david:"researcher",emma:"product-manager"},qx=(0,rf.default)({level:"silent"}),Ux=40,nf={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}},hr=class{baseConfig;agentModels;toolRegistry=null;onOutput=null;channel=null;mindsetRegistry=Kn();sharedContext=null;contextManager;constructor(e){this.baseConfig=e,this.agentModels=Zi(),this.contextManager=new Dt(e)}setSharedContext(e){this.sharedContext=e}setChannel(e){this.channel=e}setToolRegistry(e){this.toolRegistry=e}setOutputCallback(e){this.onOutput=e}reloadModels(){this.agentModels=Zi()}getAgentModel(e){let t=this.agentModels[e];if(t)return{model:t.model,temperature:t.temperature??nf[e]?.temperature??.5};let r=nf[e];return{model:r.model,temperature:r.temperature??.5}}async runAgent(e,t,r,s,i){let o=Date.now(),a=me.find(v=>v.role===e),l=this.getAgentModel(e),c=i?.maxIterations||Ux,u={...this.baseConfig,model:l.model},d=Pt(u),p=this.buildAgentPrompt(a,r),h=new vt(p,30,this.baseConfig.contextBudget);h.addUserMessage(t);let f={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:v=>{this.emit(a.name,"speaking",v.slice(0,200))},onToolStart:(v,S,k)=>{this.emit(a.name,"tool",S),this.channel&&this.channel.emitEvent({type:"act",agent:a.name,toolName:v,toolArgs:this.safeArgs(k),content:S})},onToolEnd:(v,S,k)=>{this.channel&&this.channel.emitEvent({type:"observe",agent:a.name,toolName:v,success:S,content:S?this.summarizeOk(v,k):`error: ${k.slice(0,120)}`})},onError:v=>this.emit(a.name,"error",v)},y=await pr({identity:f,client:d,registry:this.toolRegistry,session:h,contextManager:this.contextManager,logger:qx,io:g,safetyPolicy:tf(),abortSignal:i?.abortSignal,skipTools:(!s||s.length===0,!1),maxIterations:c});if(this.sharedContext&&y.touchedFiles.length)try{this.sharedContext.set(`files:@${a.name}`,y.touchedFiles.join(", "))}catch{}let w=y.touchedFiles.length?[`@${a.name} touched: ${y.touchedFiles.join(", ")}`]:[];return{agent:e,agentName:a.name,output:y.output||(y.success?"Done.":y.error??"No output"),toolsUsed:y.toolsUsed,toolResults:y.toolResults,duration:Date.now()-o,iterations:y.iterations,success:y.success,error:y.error,discoveries:w,touchedFiles:y.touchedFiles}}async runSequential(e,t,r){let s=[],i="",o=[];for(let a=0;a<e.length;a++){let{role:l,task:c}=e[a];if(r?.abortSignal?.aborted)break;let u=[];if(i&&(u.push("## Previous Agent Results"),u.push(i)),o.length>0){u.push(`
610
+ ## Handoff Chain`);for(let f of o)u.push(`- @${f.from} \u2192 @${f.to}: ${f.context.slice(0,100)}`)}let d=u.join(`
611
+ `),p=me.find(f=>f.role===l);if(p&&a>0){let f=e[a-1].role,g=me.find(y=>y.role===f);this.emit(p.name,"thinking",`\u2605 Handoff: @${g?.name||f} \u2192 @${p.name} (${p.title})`)}let h=await this.runAgent(l,c,d,t,r);if(s.push(h),h.success&&h.output){let f=h.output.length>600?h.output.slice(0,600)+"...":h.output;i+=`
775
612
 
776
- ### @${m.agentName} (${he.find(y=>y.role===l)?.title||l})
777
- ${p}`,a<e.length-1&&o.push({from:l,to:e[a+1].role,context:m.output.slice(0,200),artifacts:m.touchedFiles})}}return r}async runParallel(e,t,s){let r=s?.maxConcurrent||3,i=[];for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r),l=await Promise.all(a.map(({role:c,task:d})=>this.runAgent(c,d,void 0,t,s)));i.push(...l)}return i}async runWithEscalation(e,t,s,r){let i=await this.runAgent(e,t,s,r);if(i.success)return i;this.emit(he.find(a=>a.role===e)?.name||e,"error",`First attempt failed: ${i.error}. Retrying...`);let o=(s||"")+`
613
+ ### @${h.agentName} (${me.find(g=>g.role===l)?.title||l})
614
+ ${f}`,a<e.length-1&&o.push({from:l,to:e[a+1].role,context:h.output.slice(0,200),artifacts:h.touchedFiles})}}return s}async runParallel(e,t,r){let s=r?.maxConcurrent||3,i=[];for(let o=0;o<e.length;o+=s){let a=e.slice(o,o+s),l=await Promise.all(a.map(({role:c,task:u})=>this.runAgent(c,u,void 0,t,r)));i.push(...l)}return i}async runWithEscalation(e,t,r,s){let i=await this.runAgent(e,t,r,s);if(i.success)return i;this.emit(me.find(a=>a.role===e)?.name||e,"error",`First attempt failed: ${i.error}. Retrying...`);let o=(r||"")+`
778
615
 
779
616
  ## Previous Attempt Failed
780
617
  Error: ${i.error}
781
- 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",`@${he.find(l=>l.role===e)?.name} failed. Hablas taking over...`);let a=`Agent @${e} failed twice on this task.
618
+ Please try a different approach.`;if(i=await this.runAgent(e,t,o,s),i.success)return i;if(e!=="hablas"){this.emit("Hablas","thinking",`@${me.find(l=>l.role===e)?.name} failed. Hablas taking over...`);let a=`Agent @${e} failed twice on this task.
782
619
  Original error: ${i.error}
783
- Please complete this task.`;return this.runAgent("hablas",t,a,r)}return i}buildAgentPrompt(e,t){let s=u_[e.role]??"coder",r=this.mindsetRegistry.get(s),o=(r?`${r.systemPrompt}
620
+ Please complete this task.`;return this.runAgent("hablas",t,a,s)}return i}buildAgentPrompt(e,t){let r=Bx[e.role]??"coder",s=this.mindsetRegistry.get(r),o=(s?`${s.systemPrompt}
784
621
 
785
622
  ---
786
623
 
@@ -841,15 +678,15 @@ Expertise: ${e.expertise.join(", ")}
841
678
  ${t}`),this.sharedContext){let a=this.sharedContext.getSummary();a&&(o+=`
842
679
 
843
680
  ## Shared Team Context
844
- ${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 Dp,sr,Np=N(()=>{"use strict";Dp=require("events"),sr=class extends Dp.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 p_,rt,rr,ir,Fp=N(()=>{"use strict";xn();p_={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."},rt={hablas:"Hablas",emma:"Emma",bob:"Bob",alex:"Alex",david:"David"},rr={handoff:(n,e,t)=>{let s=rt[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, @${rt[e]}. Proceeding.`,review:(n,e)=>`@${rt[e]}, structurally sound. Watch the boundaries on the next pass.`,reviewAck:(n,e)=>`Noted, @${rt[e]}. Integrating.`},ir=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=We(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),()=>rr.handoff(e,t,s))}async generateAckLine(e,t){return this.generate(`ack:${e}:${t}`,this.buildPrompt(e,t,"ack"),()=>rr.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)),()=>rr.review(e,t))}async generateReviewAck(e,t){return this.generate(`reviewAck:${e}:${t}`,this.buildPrompt(e,t,"reviewAck"),()=>rr.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 ${rt[e]}, speaking in your own voice.
845
- ${p_[e]}
681
+ ${a}`)}return o}emit(e,t,r){if(this.onOutput&&this.onOutput(e,t,r),this.channel){let s=t==="speaking"?"speak":t==="tool"?"act":t;this.channel.emitEvent({type:s,agent:e,content:r})}}safeArgs(e){let t={};for(let[r,s]of Object.entries(e||{}))typeof s=="string"?t[r]=s.length>160?s.slice(0,160)+"\u2026":s:(typeof s=="number"||typeof s=="boolean")&&(t[r]=s);return t}summarizeOk(e,t){let r=t.split(/\r?\n/).length;return e==="write_file"||e==="edit_file"||e==="patch_file"?`ok \xB7 ${r} line${r===1?"":"s"}`:e==="run_command"?`ok \xB7 ${t.split(/\r?\n/).find(i=>i.trim())?.slice(0,80)||"ok"}`:e==="read_file"?`ok \xB7 ${r} line${r===1?"":"s"} read`:"ok"}}});var of,mr,af=M(()=>{"use strict";of=require("events"),mr=class extends of.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 Kx,Ge,gr,yr,lf=M(()=>{"use strict";Dn();Kx={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."},Ge={hablas:"Hablas",emma:"Emma",bob:"Bob",alex:"Alex",david:"David"},gr={handoff:(n,e,t)=>{let r=Ge[e];return{hablas:`Routing this to you, @${r}.`,emma:`@${r}, I need the requirements framed before we move.`,bob:`@${r}, design the structure for this. Keep boundaries clean.`,alex:`@${r}, you have the implementation. Stay surgical.`,david:`@${r}, gather the context we need on this.`}[e]||`@${r}, taking this from here.`},ack:(n,e)=>`Acknowledged, @${Ge[e]}. Proceeding.`,review:(n,e)=>`@${Ge[e]}, structurally sound. Watch the boundaries on the next pass.`,reviewAck:(n,e)=>`Noted, @${Ge[e]}. Integrating.`},yr=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 r={...e,model:this.opts.lightModel||e.model};this.client=Pt(r)}resetBudget(){this.spent=0,this.cache.clear()}setAbortSignal(e){this.opts.abortSignal=e}async generateHandoffLine(e,t,r){return this.generate(`handoff:${e}:${t}:${this.hash(r)}`,this.buildPrompt(e,t,"handoff",r),()=>gr.handoff(e,t,r))}async generateAckLine(e,t){return this.generate(`ack:${e}:${t}`,this.buildPrompt(e,t,"ack"),()=>gr.ack(e,t))}async generateReviewLine(e,t,r){return this.generate(`review:${e}:${t}:${this.hash(r.slice(0,200))}`,this.buildPrompt(e,t,"review",r.slice(0,400)),()=>gr.review(e,t))}async generateReviewAck(e,t){return this.generate(`reviewAck:${e}:${t}`,this.buildPrompt(e,t,"reviewAck"),()=>gr.reviewAck(e,t))}async generate(e,t,r){let s=this.cache.get(e);if(s)return s;if(this.spent>=this.opts.tokenBudget||this.opts.abortSignal?.aborted)return r();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):r()}catch{return r()}}buildPrompt(e,t,r,s){let i=`You are ${Ge[e]}, speaking in your own voice.
682
+ ${Kx[e]}
846
683
 
847
684
  Hard constraints:
848
685
  - Output exactly ONE sentence.
849
686
  - No prefix, no quotes, no markdown, no emojis, no role labels.
850
687
  - Maximum ${this.opts.maxChars} characters.
851
- - Address @${rt[t]} directly.
852
- - Stay in character. Be useful, not chatty.`,o;switch(s){case"handoff":o=`You are about to hand the following task to @${rt[t]}. Write a single in-character line that briefly frames what you need from them. Task: "${(r||"").slice(0,300)}"`;break;case"ack":o=`@${rt[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 @${rt[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=`@${rt[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 X,Qe,h_,jp,m_,Bp,Hp,fn,ga=N(()=>{"use strict";X=O(require("fs")),Qe=O(require("path")),h_=".hablas",jp=`# Project Context
688
+ - Address @${Ge[t]} directly.
689
+ - Stay in character. Be useful, not chatty.`,o;switch(r){case"handoff":o=`You are about to hand the following task to @${Ge[t]}. Write a single in-character line that briefly frames what you need from them. Task: "${(s||"").slice(0,300)}"`;break;case"ack":o=`@${Ge[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 @${Ge[t]}'s output below. Write a single in-character line of feedback \u2014 substantive but extremely brief. Output excerpt: """${(s||"").slice(0,400)}"""`;break;case"reviewAck":o=`@${Ge[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 r=0;r<e.length;r++)t^=e.charCodeAt(r),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t.toString(36)}}});var J,Fe,Wx,uf,Gx,df,cf,Kt,ao=M(()=>{"use strict";J=C(require("fs")),Fe=C(require("path")),Wx=".hablas",uf=`# Project Context
853
690
 
854
691
  ## Overview
855
692
  <!-- Auto-generated by hablas. Describe your project here. -->
@@ -862,34 +699,34 @@ Hard constraints:
862
699
 
863
700
  ## Notes
864
701
  <!-- Miscellaneous context for agents -->
865
- `,m_=`# Decisions Log
702
+ `,Gx=`# Decisions Log
866
703
 
867
704
  | Date | Decision | By | Rationale |
868
705
  |------|----------|-----|-----------|
869
- `,Bp=`# Task Assignments
706
+ `,df=`# Task Assignments
870
707
 
871
708
  ## Active Tasks
872
709
  <!-- Format: - [ ] Task description (@agent) -->
873
710
 
874
711
  ## Completed
875
712
  <!-- Format: - [x] Task description (@agent) \u2014 result -->
876
- `,Hp={"CONTEXT.md":jp,"DECISIONS.md":m_,"TASKS.md":Bp},fn=class{contextDir;constructor(e){this.contextDir=Qe.join(e,h_)}init(){let e=Qe.join(Qe.dirname(this.contextDir),".flowagent");if(X.existsSync(e)&&!X.existsSync(this.contextDir))try{X.renameSync(e,this.contextDir)}catch{}X.existsSync(this.contextDir)||X.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(Hp)){let r=Qe.join(this.contextDir,t);X.existsSync(r)||X.writeFileSync(r,s,"utf-8")}}exists(){return X.existsSync(this.contextDir)}read(e){let t=Qe.join(this.contextDir,e);return X.existsSync(t)?X.readFileSync(t,"utf-8"):null}write(e,t){this.ensureDir();let s=Qe.join(this.contextDir,e);X.writeFileSync(s,t,"utf-8")}append(e,t){this.ensureDir();let s=Qe.join(this.contextDir,e),r=X.existsSync(s)?X.readFileSync(s,"utf-8"):"";X.writeFileSync(s,r+`
877
- `+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")||Bp).replace(`## Active Tasks
713
+ `,cf={"CONTEXT.md":uf,"DECISIONS.md":Gx,"TASKS.md":df},Kt=class{contextDir;constructor(e){this.contextDir=Fe.join(e,Wx)}init(){let e=Fe.join(Fe.dirname(this.contextDir),".flowagent");if(J.existsSync(e)&&!J.existsSync(this.contextDir))try{J.renameSync(e,this.contextDir)}catch{}J.existsSync(this.contextDir)||J.mkdirSync(this.contextDir,{recursive:!0});for(let[t,r]of Object.entries(cf)){let s=Fe.join(this.contextDir,t);J.existsSync(s)||J.writeFileSync(s,r,"utf-8")}}exists(){return J.existsSync(this.contextDir)}read(e){let t=Fe.join(this.contextDir,e);return J.existsSync(t)?J.readFileSync(t,"utf-8"):null}write(e,t){this.ensureDir();let r=Fe.join(this.contextDir,e);J.writeFileSync(r,t,"utf-8")}append(e,t){this.ensureDir();let r=Fe.join(this.contextDir,e),s=J.existsSync(r)?J.readFileSync(r,"utf-8"):"";J.writeFileSync(r,s+`
714
+ `+t,"utf-8")}logDecision(e,t,r){let i=`| ${new Date().toISOString().split("T")[0]} | ${e} | ${t} | ${r} |`;this.append("DECISIONS.md",i)}addTask(e,t){let r=`- [ ] ${e} (@${t})`,i=(this.read("TASKS.md")||df).replace(`## Active Tasks
878
715
  `,`## Active Tasks
879
- ${s}
880
- `);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 X.existsSync(this.contextDir)?X.readdirSync(this.contextDir).filter(t=>t.endsWith(".md")).map(t=>{let s=Qe.join(this.contextDir,t),r=X.statSync(s);return{file:t,content:X.readFileSync(s,"utf-8"),lastModified:r.mtime}}):[]}getSummary(){let e=this.getAll();return e.length===0?"":e.map(t=>`### ${t.file}
716
+ ${r}
717
+ `);this.write("TASKS.md",i)}completeTask(e,t){let r=this.read("TASKS.md");if(!r)return;let s=`- [ ] ${e}`,i=`- [x] ${e}${t?" \u2014 "+t:""}`,o=r.replace(s,i);this.write("TASKS.md",o)}getAll(){return J.existsSync(this.contextDir)?J.readdirSync(this.contextDir).filter(t=>t.endsWith(".md")).map(t=>{let r=Fe.join(this.contextDir,t),s=J.statSync(r);return{file:t,content:J.readFileSync(r,"utf-8"),lastModified:s.mtime}}):[]}getSummary(){let e=this.getAll();return e.length===0?"":e.map(t=>`### ${t.file}
881
718
  ${t.content}`).join(`
882
719
 
883
- `)}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(Hp)){let s=Qe.join(this.contextDir,e);X.existsSync(s)&&X.writeFileSync(s,t,"utf-8")}}getDecisions(){let e=this.read("DECISIONS.md");if(!e)return[];let t=e.split(`
884
- `),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(`
885
- `).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(`
886
- `)}persistKV(){if(this.kvStore.size===0)return;let e=this.read("CONTEXT.md")||jp,t=Array.from(this.kvStore.entries()).map(([i,o])=>`- **${i}**: ${o}`).join(`
887
- `),s=/## Notes\n[\s\S]*$/,r=e.replace(s,`## Notes
720
+ `)}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(cf)){let r=Fe.join(this.contextDir,e);J.existsSync(r)&&J.writeFileSync(r,t,"utf-8")}}getDecisions(){let e=this.read("DECISIONS.md");if(!e)return[];let t=e.split(`
721
+ `),r=[];for(let s of t){let i=s.match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|$/);i&&r.push({timestamp:i[1],decision:i[2].trim(),by:i[3].trim(),rationale:i[4].trim()})}return r}render(){let e=[];if(this.kvStore.size>0){e.push(" Key-Value Store:");for(let[s,i]of this.kvStore)e.push(` ${s}: ${i}`)}else e.push(" No key-value entries");let t=this.getAll();if(t.length>0){e.push(""),e.push(" Context Files:");for(let s of t){let i=s.content.split(`
722
+ `).length;e.push(` ${s.file} (${i} lines)`)}}let r=this.getDecisions();return r.length>0&&(e.push(""),e.push(` Decisions: ${r.length} logged`)),e.join(`
723
+ `)}persistKV(){if(this.kvStore.size===0)return;let e=this.read("CONTEXT.md")||uf,t=Array.from(this.kvStore.entries()).map(([i,o])=>`- **${i}**: ${o}`).join(`
724
+ `),r=/## Notes\n[\s\S]*$/,s=e.replace(r,`## Notes
888
725
  ${t}
889
- `);this.write("CONTEXT.md",r)}ensureDir(){X.existsSync(this.contextDir)||X.mkdirSync(this.contextDir,{recursive:!0})}}});function ya(n){return he.find(e=>e.role===n)?.name||n}var or,Up=N(()=>{"use strict";Sn();ga();or=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 fn(process.cwd());this.runner.setSharedContext(o),this.channel.emitEvent({type:"phase",agent:"System",content:"Delegating to the team"});let a=t.tasks.filter(h=>h.role!=="hablas").map(h=>({role:h.role,task:`${h.description}
726
+ `);this.write("CONTEXT.md",s)}ensureDir(){J.existsSync(this.contextDir)||J.mkdirSync(this.contextDir,{recursive:!0})}}});function lo(n){return me.find(e=>e.role===n)?.name||n}var br,ff=M(()=>{"use strict";en();ao();br=class{channel;runner;chat;constructor(e,t,r,s){this.channel=e,this.runner=t,this.chat=r,this.runner.setChannel(e),this.chat.resetBudget()}async run(e,t,r,s={}){this.chat.setAbortSignal(s.abortSignal);let i=s.peerReview!==!1,o=new Kt(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}
890
727
 
891
- Original request: ${e}`})),l=[],c="hablas",d=null;for(let h of a){if(r.abortSignal?.aborted)break;let m=he.find(k=>k.role===h.role);if(!m)continue;this.channel.emitEvent({type:"handoff",agent:ya(c),to:m.name});let p=await this.chat.generateHandoffLine(c,h.role,h.task);this.channel.emitEvent({type:"speak",agent:ya(c),to:m.name,content:p});let y=await this.chat.generateAckLine(h.role,c);this.channel.emitEvent({type:"speak",agent:m.name,to:ya(c),content:y});let S=Date.now(),_=await this.runner.runAgent(h.role,h.task,void 0,s,{abortSignal:r.abortSignal});l.push(_),_.success&&_.output?(this.channel.emitEvent({type:"summary",agent:m.name,durationMs:Date.now()-S}),h.role==="alex"&&(d=_.output),i&&h.role==="alex"&&t.tasks.some(k=>k.role==="bob")&&d&&await this.runPeerReview("bob","alex",d,r.abortSignal)):_.error&&this.channel.emitEvent({type:"error",agent:m.name,content:_.error}),c=h.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=he.find(c=>c.role===e),o=he.find(c=>c.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=he.find(h=>h.role===d.agent);return`### Report from @${d.agentName} (${f?.title??d.agent}):
892
- ${d.output}`}).join(`
728
+ Original request: ${e}`})),l=[],c="hablas",u=null;for(let p of a){if(s.abortSignal?.aborted)break;let h=me.find(v=>v.role===p.role);if(!h)continue;this.channel.emitEvent({type:"handoff",agent:lo(c),to:h.name});let f=await this.chat.generateHandoffLine(c,p.role,p.task);this.channel.emitEvent({type:"speak",agent:lo(c),to:h.name,content:f});let g=await this.chat.generateAckLine(p.role,c);this.channel.emitEvent({type:"speak",agent:h.name,to:lo(c),content:g});let y=Date.now(),w=await this.runner.runAgent(p.role,p.task,void 0,r,{abortSignal:s.abortSignal});l.push(w),w.success&&w.output?(this.channel.emitEvent({type:"summary",agent:h.name,durationMs:Date.now()-y}),p.role==="alex"&&(u=w.output),i&&p.role==="alex"&&t.tasks.some(v=>v.role==="bob")&&u&&await this.runPeerReview("bob","alex",u,s.abortSignal)):w.error&&this.channel.emitEvent({type:"error",agent:h.name,content:w.error}),c=p.role}this.channel.emitEvent({type:"phase",agent:"System",content:"Hablas compiling final report"});let d=await this.synthesize(e,l,r,s.abortSignal);return this.channel.emitEvent({type:"done",agent:"Hablas"}),d}async runPeerReview(e,t,r,s){let i=me.find(c=>c.role===e),o=me.find(c=>c.role===t);if(!i||!o)return;let a=await this.chat.generateReviewLine(e,t,r);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}),s?.aborted}async synthesize(e,t,r,s){let i=t.filter(u=>u.success&&u.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(u=>{let d=me.find(p=>p.role===u.agent);return`### Report from @${u.agentName} (${d?.title??u.agent}):
729
+ ${u.output}`}).join(`
893
730
 
894
731
  `),a=`You are Hablas, the Team Leader. Your team has completed a multi-agent workflow for the user's request: "${e}".
895
732
 
@@ -898,39 +735,129 @@ Here are the individual execution reports from your team members:
898
735
  ${o}
899
736
  """
900
737
 
901
- 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 c=i.map(d=>{let f=he.find(h=>h.role===d.agent);return`### @${d.agentName} (${f?.title??d.agent}):
902
- ${d.output}`}).join(`
903
-
904
- `);return{results:t,finalSynthesis:c,synthesisOk:!1}}}});function Xe(n){switch(n){case"Hablas":return u.leader;case"Bob":return u.architect;case"Alex":return u.engineer;case"David":return u.analyst;case"Emma":return u.product;default:return u.primary}}function ar(n){return n==="Hablas"?"\u2605":"\u25C6"}function jn(n,e=140){let t=(n||"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e-1)+"\u2026":t}function ba(n){return n==="Hablas"?"Team Leader":n==="Bob"?"Architect":n==="Alex"?"Engineer":n==="David"?"Data Analyst":n==="Emma"?"Product Manager":"Specialist"}var lr,Kp=N(()=>{"use strict";en();lr=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(`
905
- ${u.accent("\u25B8")} ${u.strong(t.toUpperCase())}`),this.lastThinking=null)}renderHandoff(e){let t=e.agent,s=e.to||"";if(!s)return;let r=Xe(t),i=Xe(s);this.state.roster[t]&&(this.state.roster[t]="done"),this.state.roster[s]="active",this.state.activeAgent=s,this.state.activeAgentTitle=ba(s),this.state.currentPhase=`Task Handoff to @${s}`,this.state.currentActivity=`Transitioning task context from @${t} to @${s}`,this.print(` ${r(ar(t))} ${r(t)} ${u.muted("\u2501\u2501\u25B6")} ${i(ar(s))} ${i(s)}`),this.lastThinking=null}renderThinking(e){if(this.opts.hideThinking||this.lastThinking===e.agent)return;this.lastThinking=e.agent;let t=Xe(e.agent);this.state.activeAgent=e.agent,this.state.activeAgentTitle=ba(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=jn(e.content||"",this.opts.maxChars);if(!t)return;let s=Xe(e.agent),r=e.to?` ${u.muted("\u2192")} ${Xe(e.to)("@"+e.to)}`:"",i=`speak:${e.agent}:${e.to||""}:${t}`;i!==this.lastLine&&(this.lastLine=i,this.print(` ${s(ar(e.agent))} ${s(e.agent)}${r}${u.muted(":")} ${u.secondary(t)}`),this.lastThinking=null)}renderAct(e){if(this.opts.hideActs)return;let t=Xe(e.agent),s=e.toolName||"tool",r=e.toolArgs||{},i="";typeof r.path=="string"?i=` ${u.primary(r.path)}`:typeof r.command=="string"?i=` ${u.primary(r.command)}`:typeof r.query=="string"&&(i=` "${u.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=ba(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 ${u.strong(s)}${i}...`),this.lastThinking=null}renderObserve(e){if(this.opts.hideActs)return;let t=e.success!==!1,s=t?u.success("\u2713 COMPLETED"):u.error("\u2717 FAILED"),r=jn(e.content||(t?"Execution succeeded":"Execution failed"),this.opts.maxChars);this.print(` ${u.muted("\u21B3")} ${s}: ${u.muted(r)}`)}renderReview(e){let t=e.agent,s=e.to||"",r=jn(e.content||"",this.opts.maxChars);if(!r)return;let i=Xe(t),o=Xe(s);this.print(`
906
- ${i("\u270E")} ${u.strong("@"+t)} ${u.muted("reviewing")} ${o("@"+s)}${u.muted(":")} ${u.secondary(r)}`),this.lastThinking=null}renderSummary(e){let t=Xe(e.agent),s=e.durationMs?` ${u.muted(`(${(e.durationMs/1e3).toFixed(1)}s)`)}`:"";this.print(` ${t(ar(e.agent))} ${t(e.agent)} ${u.muted("\u2500\u2500\u25BA")} ${u.leader("\u2605 Hablas")} ${u.muted("\xB7 report submitted")}${s}`),this.lastThinking=null}renderDecision(e){let t=jn(e.content||"",this.opts.maxChars);if(!t)return;let s=Xe(e.agent);this.print(` ${s("\u25C6")} ${s(e.agent)} ${u.muted("decision:")} ${u.secondary(t)}`)}renderDone(e){this.print(`
907
- ${u.chrome("\u2500".repeat(56))}`),this.lastThinking=null}renderError(e){let t=Xe(e.agent),s=jn(e.content||"unknown error",this.opts.maxChars);this.print(` ${t("\u25C6")} ${t(e.agent)} ${u.error("\u2717")} ${u.error(s)}`),this.lastThinking=null}print(e){console.log(e)}}});var cr,qp=N(()=>{"use strict";cr=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(c=>c.status==="done").length,r=e.tasks.filter(c=>c.status==="failed").length,i=e.tasks.filter(c=>c.status==="pending").length,o=e.tasks.filter(c=>c.status==="running").length,a=e.tasks.filter(c=>c.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())}}});function Wp(n){let t=n.trim().toLowerCase(),s=/[\w-]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|html|env|vue|svelte|go|rs|sh|toml)/gi,r=t.match(s)||[];return g_.test(t)?"ECOSYSTEM":y_.test(t)?"APPLICATION":b_.test(t)||r.length>=3?"SERVICE":v_.test(t)||r.length===2?"COMPONENT":"FILE"}var g_,y_,b_,v_,Gp=N(()=>{"use strict";g_=/\b(deploy|ci|cd|docker|docker-compose|gvisor|kubernetes|aws|gcp|vercel|heroku|server|cloud)\b/i,y_=/\b(full\s+system|complete\s+project|from\s+scratch|entire\s+application|prd|end-to-end|database.*api.*frontend)\b/i,b_=/\b(service|module|auth|login|session|api|controller|middleware|backend|database|schema)\b/i,v_=/\b(component|widget|screen|page|interface|view|button|sidebar|header|footer|form|ui)\b/i});function Vp(n){let e=n.toLowerCase();return/\b(how|why|what|tell\s+me|explain)\b/i.test(e)&&!/\b(build|fix|add)\b/i.test(e)?"QUESTION":/\b(research|find|search|docs|compare|analyze)\b/i.test(e)?"RESEARCH":/\b(fix|bug|issue|error|solve|debug)\b/i.test(e)?"DEBUGGING":/\b(refactor|cleanup|restructure|rewrite)\b/i.test(e)?"REFACTORING":/\b(design|architect|schema|blueprint|structure)\b/i.test(e)?"ARCHITECTURE":/\b(review|check|audit|verify)\b/i.test(e)?"REVIEW":"IMPLEMENTATION"}function zp(n){let e=n.trim(),t=e.toLowerCase();if(!e)return 0;let r=/[\w-]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|html|env|vue|svelte|go|rs|sh|toml)/i.test(e)?1:0,o=/\b(read_file|write_file|run_command|edit_file|search_codebase|list_dir|create_dir|delete_file|patch_file|search_and_replace)\b/i.test(e)?1:0,a=e.startsWith("/")?1:0,c=/\b(something|fix\s+it|make\s+better|do\s+stuff|change\s+things|some\s+file|مشكلة|شيء)\b/i.test(t)?1:0,d=.4*r+.3*o+.3*a-.5*c;return Math.max(0,Math.min(1,d))}var Yp=N(()=>{"use strict"});var Et={};Re(Et,{activeCollabManager:()=>w_,startRepl:()=>va});async function va(n,e){let t=n.workingDirectory==="."?process.cwd():n.workingDirectory,s=We(n),r=new Ts(t,n),i=new rn(n),o=new Rs(t),a=Os(),l=new Is(t),c=new fn(t),d=new cr,f=new nr(n);f.setToolRegistry(r);let h=new sr;new lr(h).attach();let m=new ir(n,{tokenBudget:500,maxChars:140}),p=await Cn(t,n),y=Rn(As,p,l,c),S=new an(y,n.historySize);console.log(Dc(n.model,t));let _=0;for(;;)try{let k=await o.prompt(` ${u.primary("\u203A")} `);if(!k.trim())continue;if(k.startsWith("/")){if(await du(k,n,s,r,i,S,t,o,_,a,void 0,l,P=>{s=P},c,d,void 0,f)==="quit")break;continue}let A=x_(rc(k),t);_++,console.log(jc(_)),ps(gi(Jt()));let g=Vp(A),v=zp(A),b=Wp(A);if(!ci(A)&&g!=="QUESTION"&&v<.8&&b!=="FILE"&&b!=="COMPONENT"){let T=pc(A),P=hc(A,T);console.log(`
908
- `+qc({taskTitle:A.slice(0,40),currentPhase:"Team Coordination",activeAgent:"Hablas",activeAgentTitle:"Team Leader",currentActivity:"Executing multi-agent plan",roster:{Hablas:"active",Emma:T.includes("emma")?"pending":"done",Bob:T.includes("bob")?"pending":"done",Alex:T.includes("alex")?"pending":"done",David:T.includes("david")?"pending":"done"}}));let $=new or(h,f,m,n),{finalSynthesis:F}=await $.run(A,P,r.getOllamaTools());console.log($n("Hablas","Team Leader")),console.log(En(F)),S.addAssistantMessage(F)}else S.addUserMessage(A),await tr({identity:{name:"Hablas",title:"Team Leader",role:"hablas"},client:s,registry:r,session:S,contextManager:i,logger:e,safetyPolicy:Op({autoMode:n.autoMode,interactive:!0,confirm:T=>o.confirm(T),confirmDangerous:T=>o.confirmDangerous(T)}),io:{onAssistantText:async T=>{console.log($n("Hablas","Team Leader")),console.log(En(T))},onToolStart:(T,P)=>console.log(u.muted(` \u2699 Executing ${T}: ${P}`)),onToolEnd:(T,P)=>console.log(P?u.success(` \u2713 ${T} done`):u.error(` \u2717 ${T} failed`)),onToolCall:()=>ps(yi(Jt(),"tool_call"))}})}catch(k){console.log(ke(k.message))}}function x_(n,e){return n.replace(/#([\w./-]+)/g,(t,s)=>{let r=Qp.resolve(e,s);return Jp.existsSync(r)?s:t})}var Jp,Qp,w_,gt=N(()=>{"use strict";fu();Jp=O(require("fs")),Qp=O(require("path"));xn();nd();Wi();Gi();od();ho();cd();Xr();Sn();Lp();Np();Fp();Up();Kp();An();ga();qp();Gp();Yp();en();ma();w_=null});function Be(n={}){let e={};if(wt.existsSync(xa))try{let s=wt.readFileSync(xa,"utf-8");e=JSON.parse(s)}catch{}let t={...vn,...e,tools:{...vn.tools,...e.tools||{}},ui:{...vn.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=Bn.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 it(n){wt.existsSync(wa)||wt.mkdirSync(wa,{recursive:!0}),wt.writeFileSync(xa,JSON.stringify(n,null,2),"utf-8")}var wt,Bn,Xp,wa,xa,Sa=N(()=>{"use strict";wt=O(require("fs")),Bn=O(require("path")),Xp=O(require("os"));wn();wa=Bn.join(Xp.homedir(),".hablas"),xa=Bn.join(wa,"config.json")});function xt(n){let e=Aa.join(Zp.homedir(),".hablas","logs");ur.existsSync(e)||ur.mkdirSync(e,{recursive:!0});let t=Aa.join(e,`session-${Date.now()}.log`);return(0,_a.default)({level:"info"},_a.default.destination({dest:t,sync:!1}))}var _a,Aa,Zp,ur,ka=N(()=>{"use strict";_a=O(la()),Aa=O(require("path")),Zp=O(require("os")),ur=O(require("fs"))});var Un=H((lR,rh)=>{"use strict";var S_=require("path"),ot="\\\\/",eh=`[^${ot}]`,__=0,St="\\.",A_="\\+",k_="\\?",dr="\\/",$_="(?=.)",th="[^/]",$a=`(?:${dr}|$)`,nh=`(?:^|${dr})`,Ea=`${St}{1,2}${$a}`,E_=`(?!${St})`,T_=`(?!${nh}${Ea})`,C_=`(?!${St}{0,1}${$a})`,R_=`(?!${Ea})`,O_=`[^.${dr}]`,P_=`${th}*?`,sh={DOT_LITERAL:St,PLUS_LITERAL:A_,QMARK_LITERAL:k_,SLASH_LITERAL:dr,ONE_CHAR:$_,QMARK:th,END_ANCHOR:$a,DOTS_SLASH:Ea,NO_DOT:E_,NO_DOTS:T_,NO_DOT_SLASH:C_,NO_DOTS_SLASH:R_,QMARK_NO_DOT:O_,STAR:P_,START_ANCHOR:nh},I_={...sh,SLASH_LITERAL:`[${ot}]`,QMARK:eh,STAR:`${eh}*?`,DOTS_SLASH:`${St}{1,2}(?:[${ot}]|$)`,NO_DOT:`(?!${St})`,NO_DOTS:`(?!(?:^|[${ot}])${St}{1,2}(?:[${ot}]|$))`,NO_DOT_SLASH:`(?!${St}{0,1}(?:[${ot}]|$))`,NO_DOTS_SLASH:`(?!${St}{1,2}(?:[${ot}]|$))`,QMARK_NO_DOT:`[^.${ot}]`,START_ANCHOR:`(?:^|[${ot}])`,END_ANCHOR:`(?:[${ot}]|$)`},M_={__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"};rh.exports={DEFAULT_MAX_EXTGLOB_RECURSION:__,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:M_,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:S_.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?I_:sh}}});var fr=H(Ce=>{"use strict";var L_=require("path"),D_=process.platform==="win32",{REGEX_BACKSLASH:N_,REGEX_REMOVE_BACKSLASH:F_,REGEX_SPECIAL_CHARS:H_,REGEX_SPECIAL_CHARS_GLOBAL:j_}=Un();Ce.isObject=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);Ce.hasRegexChars=n=>H_.test(n);Ce.isRegexChar=n=>n.length===1&&Ce.hasRegexChars(n);Ce.escapeRegex=n=>n.replace(j_,"\\$1");Ce.toPosixSlashes=n=>n.replace(N_,"/");Ce.removeBackslashes=n=>n.replace(F_,e=>e==="\\"?"":e);Ce.supportsLookbehinds=()=>{let n=process.version.slice(1).split(".").map(Number);return n.length===3&&n[0]>=9||n[0]===8&&n[1]>=10};Ce.isWindows=n=>n&&typeof n.windows=="boolean"?n.windows:D_===!0||L_.sep==="\\";Ce.escapeLast=(n,e,t)=>{let s=n.lastIndexOf(e,t);return s===-1?n:n[s-1]==="\\"?Ce.escapeLast(n,e,s-1):`${n.slice(0,s)}\\${n.slice(s)}`};Ce.removePrefix=(n,e={})=>{let t=n;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Ce.wrapOutput=(n,e={},t={})=>{let s=t.contains?"":"^",r=t.contains?"":"$",i=`${s}(?:${n})${r}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var fh=H((uR,dh)=>{"use strict";var ih=fr(),{CHAR_ASTERISK:Ta,CHAR_AT:B_,CHAR_BACKWARD_SLASH:Kn,CHAR_COMMA:U_,CHAR_DOT:Ca,CHAR_EXCLAMATION_MARK:Ra,CHAR_FORWARD_SLASH:uh,CHAR_LEFT_CURLY_BRACE:Oa,CHAR_LEFT_PARENTHESES:Pa,CHAR_LEFT_SQUARE_BRACKET:K_,CHAR_PLUS:q_,CHAR_QUESTION_MARK:oh,CHAR_RIGHT_CURLY_BRACE:W_,CHAR_RIGHT_PARENTHESES:ah,CHAR_RIGHT_SQUARE_BRACKET:G_}=Un(),lh=n=>n===uh||n===Kn,ch=n=>{n.isPrefix!==!0&&(n.depth=n.isGlobstar?1/0:1)},V_=(n,e)=>{let t=e||{},s=n.length-1,r=t.parts===!0||t.scanToEnd===!0,i=[],o=[],a=[],l=n,c=-1,d=0,f=0,h=!1,m=!1,p=!1,y=!1,S=!1,_=!1,k=!1,A=!1,g=!1,v=!1,b=0,w,x,T={value:"",depth:0,isGlob:!1},P=()=>c>=s,$=()=>l.charCodeAt(c+1),F=()=>(w=x,l.charCodeAt(++c));for(;c<s;){x=F();let J;if(x===Kn){k=T.backslashes=!0,x=F(),x===Oa&&(_=!0);continue}if(_===!0||x===Oa){for(b++;P()!==!0&&(x=F());){if(x===Kn){k=T.backslashes=!0,F();continue}if(x===Oa){b++;continue}if(_!==!0&&x===Ca&&(x=F())===Ca){if(h=T.isBrace=!0,p=T.isGlob=!0,v=!0,r===!0)continue;break}if(_!==!0&&x===U_){if(h=T.isBrace=!0,p=T.isGlob=!0,v=!0,r===!0)continue;break}if(x===W_&&(b--,b===0)){_=!1,h=T.isBrace=!0,v=!0;break}}if(r===!0)continue;break}if(x===uh){if(i.push(c),o.push(T),T={value:"",depth:0,isGlob:!1},v===!0)continue;if(w===Ca&&c===d+1){d+=2;continue}f=c+1;continue}if(t.noext!==!0&&(x===q_||x===B_||x===Ta||x===oh||x===Ra)===!0&&$()===Pa){if(p=T.isGlob=!0,y=T.isExtglob=!0,v=!0,x===Ra&&c===d&&(g=!0),r===!0){for(;P()!==!0&&(x=F());){if(x===Kn){k=T.backslashes=!0,x=F();continue}if(x===ah){p=T.isGlob=!0,v=!0;break}}continue}break}if(x===Ta){if(w===Ta&&(S=T.isGlobstar=!0),p=T.isGlob=!0,v=!0,r===!0)continue;break}if(x===oh){if(p=T.isGlob=!0,v=!0,r===!0)continue;break}if(x===K_){for(;P()!==!0&&(J=F());){if(J===Kn){k=T.backslashes=!0,F();continue}if(J===G_){m=T.isBracket=!0,p=T.isGlob=!0,v=!0;break}}if(r===!0)continue;break}if(t.nonegate!==!0&&x===Ra&&c===d){A=T.negated=!0,d++;continue}if(t.noparen!==!0&&x===Pa){if(p=T.isGlob=!0,r===!0){for(;P()!==!0&&(x=F());){if(x===Pa){k=T.backslashes=!0,x=F();continue}if(x===ah){v=!0;break}}continue}break}if(p===!0){if(v=!0,r===!0)continue;break}}t.noext===!0&&(y=!1,p=!1);let j=l,V="",C="";d>0&&(V=l.slice(0,d),l=l.slice(d),f-=d),j&&p===!0&&f>0?(j=l.slice(0,f),C=l.slice(f)):p===!0?(j="",C=l):j=l,j&&j!==""&&j!=="/"&&j!==l&&lh(j.charCodeAt(j.length-1))&&(j=j.slice(0,-1)),t.unescape===!0&&(C&&(C=ih.removeBackslashes(C)),j&&k===!0&&(j=ih.removeBackslashes(j)));let E={prefix:V,input:n,start:d,base:j,glob:C,isBrace:h,isBracket:m,isGlob:p,isExtglob:y,isGlobstar:S,negated:A,negatedExtglob:g};if(t.tokens===!0&&(E.maxDepth=0,lh(x)||o.push(T),E.tokens=o),t.parts===!0||t.tokens===!0){let J;for(let D=0;D<i.length;D++){let Q=J?J+1:d,ve=i[D],_e=n.slice(Q,ve);t.tokens&&(D===0&&d!==0?(o[D].isPrefix=!0,o[D].value=V):o[D].value=_e,ch(o[D]),E.maxDepth+=o[D].depth),(D!==0||_e!=="")&&a.push(_e),J=ve}if(J&&J+1<n.length){let D=n.slice(J+1);a.push(D),t.tokens&&(o[o.length-1].value=D,ch(o[o.length-1]),E.maxDepth+=o[o.length-1].depth)}E.slashes=i,E.parts=a}return E};dh.exports=V_});var yh=H((dR,gh)=>{"use strict";var qn=Un(),xe=fr(),{MAX_LENGTH:pr,POSIX_REGEX_SOURCE:z_,REGEX_NON_SPECIAL_CHARS:Y_,REGEX_SPECIAL_CHARS_BACKREF:J_,REPLACEMENTS:ph}=qn,Q_=(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=>xe.escapeRegex(r)).join("..")}return t},pn=(n,e)=>`Missing ${n}: "${e}" - use "\\\\${e}" to match literal characters`,hh=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},X_=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},mh=n=>{let e=n.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(X_(e))return e.replace(/\\(.)/g,"$1")},Z_=n=>{let e=n.map(mh).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},Ia=(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}}}}},eA=n=>{let e=0,t=[];for(;e<n.length;){let r=Ia(n.slice(e),!1);if(!r||r.type!=="*")return;let i=hh(r.body).map(a=>a.trim());if(i.length!==1)return;let o=mh(i[0]);if(!o||o.length!==1)return;t.push(o),e+=r.end+1}return t.length<1?void 0:`${t.length===1?xe.escapeRegex(t[0]):`[${t.map(r=>xe.escapeRegex(r)).join("")}]`}*`},tA=n=>{let e=0,t=n.trim(),s=Ia(t);for(;s;)e++,t=s.body.trim(),s=Ia(t);return e},nA=(n,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:qn.DEFAULT_MAX_EXTGLOB_RECURSION,s=hh(n).map(r=>r.trim());if(s.length>1&&(s.some(r=>r==="")||s.some(r=>/^[*?]+$/.test(r))||Z_(s)))return{risky:!0};for(let r of s){let i=eA(r);if(i)return{risky:!0,safeOutput:i};if(tA(r)>t)return{risky:!0}}return{risky:!1}},Ma=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a string");n=ph[n]||n;let t={...e},s=typeof t.maxLength=="number"?Math.min(pr,t.maxLength):pr,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=xe.isWindows(e),c=qn.globChars(l),d=qn.extglobChars(c),{DOT_LITERAL:f,PLUS_LITERAL:h,SLASH_LITERAL:m,ONE_CHAR:p,DOTS_SLASH:y,NO_DOT:S,NO_DOT_SLASH:_,NO_DOTS_SLASH:k,QMARK:A,QMARK_NO_DOT:g,STAR:v,START_ANCHOR:b}=c,w=L=>`(${a}(?:(?!${b}${L.dot?y:f}).)*?)`,x=t.dot?"":S,T=t.dot?A:g,P=t.bash===!0?w(t):v;t.capture&&(P=`(${P})`),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=xe.removePrefix(n,$),r=n.length;let F=[],j=[],V=[],C=i,E,J=()=>$.index===r-1,D=$.peek=(L=1)=>n[$.index+L],Q=$.advance=()=>n[++$.index]||"",ve=()=>n.slice($.index+1),_e=(L="",ie=0)=>{$.consumed+=L,$.index+=ie},Vt=L=>{$.output+=L.output!=null?L.output:L.value,_e(L.value)},Se=()=>{let L=1;for(;D()==="!"&&(D(2)!=="("||D(3)==="?");)Q(),$.start++,L++;return L%2===0?!1:($.negated=!0,$.start++,!0)},qe=L=>{$[L]++,V.push(L)},pe=L=>{$[L]--,V.pop()},q=L=>{if(C.type==="globstar"){let ie=$.braces>0&&(L.type==="comma"||L.type==="brace"),M=L.extglob===!0||F.length&&(L.type==="pipe"||L.type==="paren");L.type!=="slash"&&L.type!=="paren"&&!ie&&!M&&($.output=$.output.slice(0,-C.output.length),C.type="star",C.value="*",C.output=P,$.output+=C.output)}if(F.length&&L.type!=="paren"&&(F[F.length-1].inner+=L.value),(L.value||L.output)&&Vt(L),C&&C.type==="text"&&L.type==="text"){C.value+=L.value,C.output=(C.output||"")+L.value;return}L.prev=C,o.push(L),C=L},Ae=(L,ie)=>{let M={...d[ie],conditions:1,inner:""};M.prev=C,M.parens=$.parens,M.output=$.output,M.startIndex=$.index,M.tokensIndex=o.length;let z=(t.capture?"(":"")+M.open;qe("parens"),q({type:L,value:ie,output:$.output?"":p}),q({type:"paren",extglob:!0,value:Q(),output:z}),F.push(M)},mg=L=>{let ie=n.slice(L.startIndex,$.index+1),M=n.slice(L.startIndex+2,$.index),z=nA(M,t);if((L.type==="plus"||L.type==="star")&&z.risky){let ee=z.safeOutput?(L.output?"":p)+(t.capture?`(${z.safeOutput})`:z.safeOutput):void 0,et=o[L.tokensIndex];et.type="text",et.value=ie,et.output=ee||xe.escapeRegex(ie);for(let tt=L.tokensIndex+1;tt<o.length;tt++)o[tt].value="",o[tt].output="",delete o[tt].suffix;$.output=L.output+et.output,$.backtrack=!0,q({type:"paren",extglob:!0,value:E,output:""}),pe("parens");return}let ne=L.close+(t.capture?")":""),fe;if(L.type==="negate"){let ee=P;if(L.inner&&L.inner.length>1&&L.inner.includes("/")&&(ee=w(t)),(ee!==P||J()||/^\)+$/.test(ve()))&&(ne=L.close=`)$))${ee}`),L.inner.includes("*")&&(fe=ve())&&/^\.[^\\/.]+$/.test(fe)){let et=Ma(fe,{...e,fastpaths:!1}).output;ne=L.close=`)${et})${ee})`}L.prev.type==="bos"&&($.negatedExtglob=!0)}q({type:"paren",extglob:!0,value:E,output:ne}),pe("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(n)){let L=!1,ie=n.replace(J_,(M,z,ne,fe,ee,et)=>fe==="\\"?(L=!0,M):fe==="?"?z?z+fe+(ee?A.repeat(ee.length):""):et===0?T+(ee?A.repeat(ee.length):""):A.repeat(ne.length):fe==="."?f.repeat(ne.length):fe==="*"?z?z+fe+(ee?P:""):P:z?M:`\\${M}`);return L===!0&&(t.unescape===!0?ie=ie.replace(/\\/g,""):ie=ie.replace(/\\+/g,M=>M.length%2===0?"\\\\":M?"\\":"")),ie===n&&t.contains===!0?($.output=n,$):($.output=xe.wrapOutput(ie,$,e),$)}for(;!J();){if(E=Q(),E==="\0")continue;if(E==="\\"){let M=D();if(M==="/"&&t.bash!==!0||M==="."||M===";")continue;if(!M){E+="\\",q({type:"text",value:E});continue}let z=/^\\+/.exec(ve()),ne=0;if(z&&z[0].length>2&&(ne=z[0].length,$.index+=ne,ne%2!==0&&(E+="\\")),t.unescape===!0?E=Q():E+=Q(),$.brackets===0){q({type:"text",value:E});continue}}if($.brackets>0&&(E!=="]"||C.value==="["||C.value==="[^")){if(t.posix!==!1&&E===":"){let M=C.value.slice(1);if(M.includes("[")&&(C.posix=!0,M.includes(":"))){let z=C.value.lastIndexOf("["),ne=C.value.slice(0,z),fe=C.value.slice(z+2),ee=z_[fe];if(ee){C.value=ne+ee,$.backtrack=!0,Q(),!i.output&&o.indexOf(C)===1&&(i.output=p);continue}}}(E==="["&&D()!==":"||E==="-"&&D()==="]")&&(E=`\\${E}`),E==="]"&&(C.value==="["||C.value==="[^")&&(E=`\\${E}`),t.posix===!0&&E==="!"&&C.value==="["&&(E="^"),C.value+=E,Vt({value:E});continue}if($.quotes===1&&E!=='"'){E=xe.escapeRegex(E),C.value+=E,Vt({value:E});continue}if(E==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&q({type:"text",value:E});continue}if(E==="("){qe("parens"),q({type:"paren",value:E});continue}if(E===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(pn("opening","("));let M=F[F.length-1];if(M&&$.parens===M.parens+1){mg(F.pop());continue}q({type:"paren",value:E,output:$.parens?")":"\\)"}),pe("parens");continue}if(E==="["){if(t.nobracket===!0||!ve().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(pn("closing","]"));E=`\\${E}`}else qe("brackets");q({type:"bracket",value:E});continue}if(E==="]"){if(t.nobracket===!0||C&&C.type==="bracket"&&C.value.length===1){q({type:"text",value:E,output:`\\${E}`});continue}if($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(pn("opening","["));q({type:"text",value:E,output:`\\${E}`});continue}pe("brackets");let M=C.value.slice(1);if(C.posix!==!0&&M[0]==="^"&&!M.includes("/")&&(E=`/${E}`),C.value+=E,Vt({value:E}),t.literalBrackets===!1||xe.hasRegexChars(M))continue;let z=xe.escapeRegex(C.value);if($.output=$.output.slice(0,-C.value.length),t.literalBrackets===!0){$.output+=z,C.value=z;continue}C.value=`(${a}${z}|${C.value})`,$.output+=C.value;continue}if(E==="{"&&t.nobrace!==!0){qe("braces");let M={type:"brace",value:E,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};j.push(M),q(M);continue}if(E==="}"){let M=j[j.length-1];if(t.nobrace===!0||!M){q({type:"text",value:E,output:E});continue}let z=")";if(M.dots===!0){let ne=o.slice(),fe=[];for(let ee=ne.length-1;ee>=0&&(o.pop(),ne[ee].type!=="brace");ee--)ne[ee].type!=="dots"&&fe.unshift(ne[ee].value);z=Q_(fe,t),$.backtrack=!0}if(M.comma!==!0&&M.dots!==!0){let ne=$.output.slice(0,M.outputIndex),fe=$.tokens.slice(M.tokensIndex);M.value=M.output="\\{",E=z="\\}",$.output=ne;for(let ee of fe)$.output+=ee.output||ee.value}q({type:"brace",value:E,output:z}),pe("braces"),j.pop();continue}if(E==="|"){F.length>0&&F[F.length-1].conditions++,q({type:"text",value:E});continue}if(E===","){let M=E,z=j[j.length-1];z&&V[V.length-1]==="braces"&&(z.comma=!0,M="|"),q({type:"comma",value:E,output:M});continue}if(E==="/"){if(C.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),C=i;continue}q({type:"slash",value:E,output:m});continue}if(E==="."){if($.braces>0&&C.type==="dot"){C.value==="."&&(C.output=f);let M=j[j.length-1];C.type="dots",C.output+=E,C.value+=E,M.dots=!0;continue}if($.braces+$.parens===0&&C.type!=="bos"&&C.type!=="slash"){q({type:"text",value:E,output:f});continue}q({type:"dot",value:E,output:f});continue}if(E==="?"){if(!(C&&C.value==="(")&&t.noextglob!==!0&&D()==="("&&D(2)!=="?"){Ae("qmark",E);continue}if(C&&C.type==="paren"){let z=D(),ne=E;if(z==="<"&&!xe.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(C.value==="("&&!/[!=<:]/.test(z)||z==="<"&&!/<([!=]|\w+>)/.test(ve()))&&(ne=`\\${E}`),q({type:"text",value:E,output:ne});continue}if(t.dot!==!0&&(C.type==="slash"||C.type==="bos")){q({type:"qmark",value:E,output:g});continue}q({type:"qmark",value:E,output:A});continue}if(E==="!"){if(t.noextglob!==!0&&D()==="("&&(D(2)!=="?"||!/[!=<:]/.test(D(3)))){Ae("negate",E);continue}if(t.nonegate!==!0&&$.index===0){Se();continue}}if(E==="+"){if(t.noextglob!==!0&&D()==="("&&D(2)!=="?"){Ae("plus",E);continue}if(C&&C.value==="("||t.regex===!1){q({type:"plus",value:E,output:h});continue}if(C&&(C.type==="bracket"||C.type==="paren"||C.type==="brace")||$.parens>0){q({type:"plus",value:E});continue}q({type:"plus",value:h});continue}if(E==="@"){if(t.noextglob!==!0&&D()==="("&&D(2)!=="?"){q({type:"at",extglob:!0,value:E,output:""});continue}q({type:"text",value:E});continue}if(E!=="*"){(E==="$"||E==="^")&&(E=`\\${E}`);let M=Y_.exec(ve());M&&(E+=M[0],$.index+=M[0].length),q({type:"text",value:E});continue}if(C&&(C.type==="globstar"||C.star===!0)){C.type="star",C.star=!0,C.value+=E,C.output=P,$.backtrack=!0,$.globstar=!0,_e(E);continue}let L=ve();if(t.noextglob!==!0&&/^\([^?]/.test(L)){Ae("star",E);continue}if(C.type==="star"){if(t.noglobstar===!0){_e(E);continue}let M=C.prev,z=M.prev,ne=M.type==="slash"||M.type==="bos",fe=z&&(z.type==="star"||z.type==="globstar");if(t.bash===!0&&(!ne||L[0]&&L[0]!=="/")){q({type:"star",value:E,output:""});continue}let ee=$.braces>0&&(M.type==="comma"||M.type==="brace"),et=F.length&&(M.type==="pipe"||M.type==="paren");if(!ne&&M.type!=="paren"&&!ee&&!et){q({type:"star",value:E,output:""});continue}for(;L.slice(0,3)==="/**";){let tt=n[$.index+4];if(tt&&tt!=="/")break;L=L.slice(3),_e("/**",3)}if(M.type==="bos"&&J()){C.type="globstar",C.value+=E,C.output=w(t),$.output=C.output,$.globstar=!0,_e(E);continue}if(M.type==="slash"&&M.prev.type!=="bos"&&!fe&&J()){$.output=$.output.slice(0,-(M.output+C.output).length),M.output=`(?:${M.output}`,C.type="globstar",C.output=w(t)+(t.strictSlashes?")":"|$)"),C.value+=E,$.globstar=!0,$.output+=M.output+C.output,_e(E);continue}if(M.type==="slash"&&M.prev.type!=="bos"&&L[0]==="/"){let tt=L[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(M.output+C.output).length),M.output=`(?:${M.output}`,C.type="globstar",C.output=`${w(t)}${m}|${m}${tt})`,C.value+=E,$.output+=M.output+C.output,$.globstar=!0,_e(E+Q()),q({type:"slash",value:"/",output:""});continue}if(M.type==="bos"&&L[0]==="/"){C.type="globstar",C.value+=E,C.output=`(?:^|${m}|${w(t)}${m})`,$.output=C.output,$.globstar=!0,_e(E+Q()),q({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-C.output.length),C.type="globstar",C.output=w(t),C.value+=E,$.output+=C.output,$.globstar=!0,_e(E);continue}let ie={type:"star",value:E,output:P};if(t.bash===!0){ie.output=".*?",(C.type==="bos"||C.type==="slash")&&(ie.output=x+ie.output),q(ie);continue}if(C&&(C.type==="bracket"||C.type==="paren")&&t.regex===!0){ie.output=E,q(ie);continue}($.index===$.start||C.type==="slash"||C.type==="dot")&&(C.type==="dot"?($.output+=_,C.output+=_):t.dot===!0?($.output+=k,C.output+=k):($.output+=x,C.output+=x),D()!=="*"&&($.output+=p,C.output+=p)),q(ie)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(pn("closing","]"));$.output=xe.escapeLast($.output,"["),pe("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(pn("closing",")"));$.output=xe.escapeLast($.output,"("),pe("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(pn("closing","}"));$.output=xe.escapeLast($.output,"{"),pe("braces")}if(t.strictSlashes!==!0&&(C.type==="star"||C.type==="bracket")&&q({type:"maybe_slash",value:"",output:`${m}?`}),$.backtrack===!0){$.output="";for(let L of $.tokens)$.output+=L.output!=null?L.output:L.value,L.suffix&&($.output+=L.suffix)}return $};Ma.fastpaths=(n,e)=>{let t={...e},s=typeof t.maxLength=="number"?Math.min(pr,t.maxLength):pr,r=n.length;if(r>s)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${s}`);n=ph[n]||n;let i=xe.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:l,DOTS_SLASH:c,NO_DOT:d,NO_DOTS:f,NO_DOTS_SLASH:h,STAR:m,START_ANCHOR:p}=qn.globChars(i),y=t.dot?f:d,S=t.dot?h:d,_=t.capture?"":"?:",k={negated:!1,prefix:""},A=t.bash===!0?".*?":m;t.capture&&(A=`(${A})`);let g=x=>x.noglobstar===!0?A:`(${_}(?:(?!${p}${x.dot?c:o}).)*?)`,v=x=>{switch(x){case"*":return`${y}${l}${A}`;case".*":return`${o}${l}${A}`;case"*.*":return`${y}${A}${o}${l}${A}`;case"*/*":return`${y}${A}${a}${l}${S}${A}`;case"**":return y+g(t);case"**/*":return`(?:${y}${g(t)}${a})?${S}${l}${A}`;case"**/*.*":return`(?:${y}${g(t)}${a})?${S}${A}${o}${l}${A}`;case"**/.*":return`(?:${y}${g(t)}${a})?${o}${l}${A}`;default:{let T=/^(.*?)\.(\w+)$/.exec(x);if(!T)return;let P=v(T[1]);return P?P+o+T[2]:void 0}}},b=xe.removePrefix(n,k),w=v(b);return w&&t.strictSlashes!==!0&&(w+=`${a}?`),w};gh.exports=Ma});var vh=H((fR,bh)=>{"use strict";var sA=require("path"),rA=fh(),La=yh(),Da=fr(),iA=Un(),oA=n=>n&&typeof n=="object"&&!Array.isArray(n),ce=(n,e,t=!1)=>{if(Array.isArray(n)){let d=n.map(h=>ce(h,e,t));return h=>{for(let m of d){let p=m(h);if(p)return p}return!1}}let s=oA(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=Da.isWindows(e),o=s?ce.compileRe(n,e):ce.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=ce(r.ignore,d,t)}let c=(d,f=!1)=>{let{isMatch:h,match:m,output:p}=ce.test(d,o,e,{glob:n,posix:i}),y={glob:n,state:a,regex:o,posix:i,input:d,output:p,match:m,isMatch:h};return typeof r.onResult=="function"&&r.onResult(y),h===!1?(y.isMatch=!1,f?y:!1):l(d)?(typeof r.onIgnore=="function"&&r.onIgnore(y),y.isMatch=!1,f?y:!1):(typeof r.onMatch=="function"&&r.onMatch(y),f?y:!0)};return t&&(c.state=a),c};ce.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?Da.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=ce.matchBase(n,e,t,r):a=e.exec(l)),{isMatch:!!a,match:a,output:l}};ce.matchBase=(n,e,t,s=Da.isWindows(t))=>(e instanceof RegExp?e:ce.makeRe(e,t)).test(sA.basename(n));ce.isMatch=(n,e,t)=>ce(e,t)(n);ce.parse=(n,e)=>Array.isArray(n)?n.map(t=>ce.parse(t,e)):La(n,{...e,fastpaths:!1});ce.scan=(n,e)=>rA(n,e);ce.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=ce.toRegex(a,e);return s===!0&&(l.state=n),l};ce.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=La.fastpaths(n,e)),r.output||(r=La(n,e)),ce.compileRe(r,e,t,s)};ce.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/$^/}};ce.constants=iA;bh.exports=ce});var Na=H((pR,wh)=>{"use strict";wh.exports=vh()});var Th=H((hR,Eh)=>{"use strict";var Gn=require("fs"),{Readable:aA}=require("stream"),Wn=require("path"),{promisify:yr}=require("util"),Fa=Na(),lA=yr(Gn.readdir),cA=yr(Gn.stat),xh=yr(Gn.lstat),uA=yr(Gn.realpath),dA="!",kh="READDIRP_RECURSIVE_ERROR",fA=new Set(["ENOENT","EPERM","EACCES","ELOOP",kh]),Ha="files",$h="directories",mr="files_directories",hr="all",Sh=[Ha,$h,mr,hr],pA=n=>fA.has(n.code),[_h,hA]=process.versions.node.split(".").slice(0,2).map(n=>Number.parseInt(n,10)),mA=process.platform==="win32"&&(_h>10||_h===10&&hA>=5),Ah=n=>{if(n!==void 0){if(typeof n=="function")return n;if(typeof n=="string"){let e=Fa(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)===dA?t.push(Fa(r.slice(1))):e.push(Fa(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))}}},gr=class n extends aA{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:Ha,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=Ah(t.fileFilter),this._directoryFilter=Ah(t.directoryFilter);let i=t.lstat?xh:cA;mA?this._stat=o=>i(o,{bigint:!0}):this._stat=i,this._maxDepth=t.depth,this._wantsDir=[$h,mr,hr].includes(r),this._wantsFile=[Ha,mr,hr].includes(r),this._wantsEverything=r===hr,this._root=Wn.resolve(s),this._isDirent="Dirent"in Gn&&!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 lA(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=Wn.resolve(Wn.join(t,r));s={path:Wn.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){pA(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 uA(s),i=await xh(r);if(i.isFile())return"file";if(i.isDirectory()){let o=r.length;if(s.startsWith(r)&&s.substr(o,1)===Wn.sep){let a=new Error(`Circular symlink detected: "${s}" points to "${r}"`);return a.code=kh,this._onError(a)}return"directory"}}catch(r){this._onError(r)}}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}},hn=(n,e={})=>{let t=e.entryType||e.type;if(t==="both"&&(t=mr),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&&!Sh.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${Sh.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=n,new gr(e)},gA=(n,e={})=>new Promise((t,s)=>{let r=[];hn(n,e).on("data",i=>r.push(i)).on("end",()=>t(r)).on("error",i=>s(i))});hn.promise=gA;hn.ReaddirpStream=gr;hn.default=hn;Eh.exports=hn});var ja=H((mR,Ch)=>{Ch.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 Lh=H((Ih,Mh)=>{"use strict";Object.defineProperty(Ih,"__esModule",{value:!0});var Ph=Na(),yA=ja(),Rh="!",bA={returnIndex:!1},vA=n=>Array.isArray(n)?n:[n],wA=(n,e)=>{if(typeof n=="function")return n;if(typeof n=="string"){let t=Ph(n,e);return s=>n===s||t(s)}return n instanceof RegExp?t=>n.test(t):t=>!1},Oh=(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=yA(i,!1);for(let l=0;l<e.length;l++){let c=e[l];if(c(o))return s?-1:!1}let a=r&&[o].concat(t.slice(1));for(let l=0;l<n.length;l++){let c=n[l];if(r?c(...a):c(o))return s?l:!0}return s?-1:!1},Ba=(n,e,t=bA)=>{if(n==null)throw new TypeError("anymatch: specify first argument");let s=typeof t=="boolean"?{returnIndex:t}:t,r=s.returnIndex||!1,i=vA(n),o=i.filter(l=>typeof l=="string"&&l.charAt(0)===Rh).map(l=>l.slice(1)).map(l=>Ph(l,s)),a=i.filter(l=>typeof l!="string"||typeof l=="string"&&l.charAt(0)!==Rh).map(l=>wA(l,s));return e==null?(l,c=!1)=>Oh(a,o,l,typeof c=="boolean"?c:!1):Oh(a,o,e,r)};Ba.default=Ba;Mh.exports=Ba});var Nh=H((gR,Dh)=>{Dh.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 Ua=H((yR,Hh)=>{var xA=Nh(),Fh={"{":"}","(":")","[":"]"},SA=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=Fh[a];if(l){var c=n.indexOf(l,e);c!==-1&&(e=c+1)}if(n[e]==="!")return!0}else e++}return!1},_A=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=Fh[t];if(s){var r=n.indexOf(s,e);r!==-1&&(e=r+1)}if(n[e]==="!")return!0}else e++}return!1};Hh.exports=function(e,t){if(typeof e!="string"||e==="")return!1;if(xA(e))return!0;var s=SA;return t&&t.strict===!1&&(s=_A),s(e)}});var Bh=H((bR,jh)=>{"use strict";var AA=Ua(),kA=require("path").posix.dirname,$A=require("os").platform()==="win32",Ka="/",EA=/\\/g,TA=/[\{\[].*[\}\]]$/,CA=/(^|[^\\])([\{\[]|\([^\)]+$)/,RA=/\\([\!\*\?\|\[\]\(\)\{\}])/g;jh.exports=function(e,t){var s=Object.assign({flipBackslashes:!0},t);s.flipBackslashes&&$A&&e.indexOf(Ka)<0&&(e=e.replace(EA,Ka)),TA.test(e)&&(e+=Ka),e+="a";do e=kA(e);while(AA(e)||CA.test(e));return e.replace(RA,"$1")}});var br=H(Ue=>{"use strict";Ue.isInteger=n=>typeof n=="number"?Number.isInteger(n):typeof n=="string"&&n.trim()!==""?Number.isInteger(Number(n)):!1;Ue.find=(n,e)=>n.nodes.find(t=>t.type===e);Ue.exceedsLimit=(n,e,t=1,s)=>s===!1||!Ue.isInteger(n)||!Ue.isInteger(e)?!1:(Number(e)-Number(n))/Number(t)>=s;Ue.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)};Ue.encloseBrace=n=>n.type!=="brace"?!1:n.commas>>0+n.ranges>>0===0?(n.invalid=!0,!0):!1;Ue.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;Ue.isOpenOrClose=n=>n.type==="open"||n.type==="close"?!0:n.open===!0||n.close===!0;Ue.reduce=n=>n.reduce((e,t)=>(t.type==="text"&&e.push(t.value),t.type==="range"&&(t.type="text"),e),[]);Ue.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 vr=H((wR,Kh)=>{"use strict";var Uh=br();Kh.exports=(n,e={})=>{let t=(s,r={})=>{let i=e.escapeInvalid&&Uh.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(i||o)&&Uh.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 Wh=H((xR,qh)=>{"use strict";qh.exports=function(n){return typeof n=="number"?n-n===0:typeof n=="string"&&n.trim()!==""?Number.isFinite?Number.isFinite(+n):isFinite(+n):!1}});var em=H((SR,Zh)=>{"use strict";var Gh=Wh(),qt=(n,e,t)=>{if(Gh(n)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||n===e)return String(n);if(Gh(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(qt.cache.hasOwnProperty(l))return qt.cache[l].result;let c=Math.min(n,e),d=Math.max(n,e);if(Math.abs(c-d)===1){let y=n+"|"+e;return s.capture?`(${y})`:s.wrap===!1?y:`(?:${y})`}let f=Xh(n)||Xh(e),h={min:n,max:e,a:c,b:d},m=[],p=[];if(f&&(h.isPadded=f,h.maxLen=String(h.max).length),c<0){let y=d<0?Math.abs(d):1;p=Vh(y,Math.abs(c),h,s),c=h.a=0}return d>=0&&(m=Vh(c,d,h,s)),h.negatives=p,h.positives=m,h.result=OA(p,m,s),s.capture===!0?h.result=`(${h.result})`:s.wrap!==!1&&m.length+p.length>1&&(h.result=`(?:${h.result})`),qt.cache[l]=h,h.result};function OA(n,e,t){let s=qa(n,e,"-",!1,t)||[],r=qa(e,n,"",!1,t)||[],i=qa(n,e,"-?",!0,t)||[];return s.concat(i).concat(r).join("|")}function PA(n,e){let t=1,s=1,r=Yh(n,t),i=new Set([e]);for(;n<=r&&r<=e;)i.add(r),t+=1,r=Yh(n,t);for(r=Jh(e+1,s)-1;n<r&&r<=e;)i.add(r),s+=1,r=Jh(e+1,s)-1;return i=[...i],i.sort(LA),i}function IA(n,e,t){if(n===e)return{pattern:n,count:[],digits:0};let s=MA(n,e),r=s.length,i="",o=0;for(let a=0;a<r;a++){let[l,c]=s[a];l===c?i+=l:l!=="0"||c!=="9"?i+=DA(l,c,t):o++}return o&&(i+=t.shorthand===!0?"\\d":"[0-9]"),{pattern:i,count:[o],digits:r}}function Vh(n,e,t,s){let r=PA(n,e),i=[],o=n,a;for(let l=0;l<r.length;l++){let c=r[l],d=IA(String(o),String(c),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+Qh(a.count),o=c+1;continue}t.isPadded&&(f=NA(c,t,s)),d.string=f+d.pattern+Qh(d.count),i.push(d),o=c+1,a=d}return i}function qa(n,e,t,s,r){let i=[];for(let o of n){let{string:a}=o;!s&&!zh(e,"string",a)&&i.push(t+a),s&&zh(e,"string",a)&&i.push(t+a)}return i}function MA(n,e){let t=[];for(let s=0;s<n.length;s++)t.push([n[s],e[s]]);return t}function LA(n,e){return n>e?1:e>n?-1:0}function zh(n,e,t){return n.some(s=>s[e]===t)}function Yh(n,e){return Number(String(n).slice(0,-e)+"9".repeat(e))}function Jh(n,e){return n-n%Math.pow(10,e)}function Qh(n){let[e=0,t=""]=n;return t||e>1?`{${e+(t?","+t:"")}}`:""}function DA(n,e,t){return`[${n}${e-n===1?"":"-"}${e}]`}function Xh(n){return/^-?(0+)\d/.test(n)}function NA(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}}`}}qt.cache={};qt.clearCache=()=>qt.cache={};Zh.exports=qt});var Va=H((_R,am)=>{"use strict";var FA=require("util"),nm=em(),tm=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),HA=n=>e=>n===!0?Number(e):String(e),Wa=n=>typeof n=="number"||typeof n=="string"&&n!=="",Vn=n=>Number.isInteger(+n),Ga=n=>{let e=`${n}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},jA=(n,e,t)=>typeof n=="string"||typeof e=="string"?!0:t.stringify===!0,BA=(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},xr=(n,e)=>{let t=n[0]==="-"?"-":"";for(t&&(n=n.slice(1),e--);n.length<e;)n="0"+n;return t?"-"+n:n},UA=(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=>xr(String(a),t)).join("|")),n.negatives.length&&(i=`-(${s}${n.negatives.map(a=>xr(String(a),t)).join("|")})`),r&&i?o=`${r}|${i}`:o=r||i,e.wrap?`(${s}${o})`:o},sm=(n,e,t,s)=>{if(t)return nm(n,e,{wrap:!1,...s});let r=String.fromCharCode(n);if(n===e)return r;let i=String.fromCharCode(e);return`[${r}-${i}]`},rm=(n,e,t)=>{if(Array.isArray(n)){let s=t.wrap===!0,r=t.capture?"":"?:";return s?`(${r}${n.join("|")})`:n.join("|")}return nm(n,e,t)},im=(...n)=>new RangeError("Invalid range arguments: "+FA.inspect(...n)),om=(n,e,t)=>{if(t.strictRanges===!0)throw im([n,e]);return[]},KA=(n,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${n}" to be a number`);return[]},qA=(n,e,t=1,s={})=>{let r=Number(n),i=Number(e);if(!Number.isInteger(r)||!Number.isInteger(i)){if(s.strictRanges===!0)throw im([n,e]);return[]}r===0&&(r=0),i===0&&(i=0);let o=r>i,a=String(n),l=String(e),c=String(t);t=Math.max(Math.abs(t),1);let d=Ga(a)||Ga(l)||Ga(c),f=d?Math.max(a.length,l.length,c.length):0,h=d===!1&&jA(n,e,s)===!1,m=s.transform||HA(h);if(s.toRegex&&t===1)return sm(xr(n,f),xr(e,f),!0,s);let p={negatives:[],positives:[]},y=k=>p[k<0?"negatives":"positives"].push(Math.abs(k)),S=[],_=0;for(;o?r>=i:r<=i;)s.toRegex===!0&&t>1?y(r):S.push(BA(m(r,_),f,h)),r=o?r-t:r+t,_++;return s.toRegex===!0?t>1?UA(p,s,f):rm(S,null,{wrap:!1,...s}):S},WA=(n,e,t=1,s={})=>{if(!Vn(n)&&n.length>1||!Vn(e)&&e.length>1)return om(n,e,s);let r=s.transform||(h=>String.fromCharCode(h)),i=`${n}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=i>o,l=Math.min(i,o),c=Math.max(i,o);if(s.toRegex&&t===1)return sm(l,c,!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?rm(d,null,{wrap:!1,options:s}):d},wr=(n,e,t,s={})=>{if(e==null&&Wa(n))return[n];if(!Wa(n)||!Wa(e))return om(n,e,s);if(typeof t=="function")return wr(n,e,1,{transform:t});if(tm(t))return wr(n,e,0,t);let r={...s};return r.capture===!0&&(r.wrap=!0),t=t||r.step||1,Vn(t)?Vn(n)&&Vn(e)?qA(n,e,t,r):WA(n,e,Math.max(Math.abs(t),1),r):t!=null&&!tm(t)?KA(t,r):wr(n,e,1,t)};am.exports=wr});var um=H((AR,cm)=>{"use strict";var GA=Va(),lm=br(),VA=(n,e={})=>{let t=(s,r={})=>{let i=lm.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a=i===!0||o===!0,l=e.escapeInvalid===!0?"\\":"",c="";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=lm.reduce(s.nodes),f=GA(...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)c+=t(d,s);return c};return t(n)};cm.exports=VA});var pm=H((kR,fm)=>{"use strict";var zA=Va(),dm=vr(),mn=br(),Wt=(n="",e="",t=!1)=>{let s=[];if(n=[].concat(n),e=[].concat(e),!e.length)return n;if(!n.length)return t?mn.flatten(e).map(r=>`{${r}}`):e;for(let r of n)if(Array.isArray(r))for(let i of r)s.push(Wt(i,e,t));else for(let i of e)t===!0&&typeof i=="string"&&(i=`{${i}}`),s.push(Array.isArray(i)?Wt(r,i,t):r+i);return mn.flatten(s)},YA=(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(Wt(a.pop(),dm(r,e)));return}if(r.type==="brace"&&r.invalid!==!0&&r.nodes.length===2){a.push(Wt(a.pop(),["{}"]));return}if(r.nodes&&r.ranges>0){let f=mn.reduce(r.nodes);if(mn.exceedsLimit(...f,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let h=zA(...f,e);h.length===0&&(h=dm(r,e)),a.push(Wt(a.pop(),h)),r.nodes=[];return}let l=mn.encloseBrace(r),c=r.queue,d=r;for(;d.type!=="brace"&&d.type!=="root"&&d.parent;)d=d.parent,c=d.queue;for(let f=0;f<r.nodes.length;f++){let h=r.nodes[f];if(h.type==="comma"&&r.type==="brace"){f===1&&c.push(""),c.push("");continue}if(h.type==="close"){a.push(Wt(a.pop(),c,l));continue}if(h.value&&h.type!=="open"){c.push(Wt(c.pop(),h.value));continue}h.nodes&&s(h,r)}return c};return mn.flatten(s(n))};fm.exports=YA});var mm=H(($R,hm)=>{"use strict";hm.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:`
909
- `,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 wm=H((ER,vm)=>{"use strict";var JA=vr(),{MAX_LENGTH:gm,CHAR_BACKSLASH:za,CHAR_BACKTICK:QA,CHAR_COMMA:XA,CHAR_DOT:ZA,CHAR_LEFT_PARENTHESES:ek,CHAR_RIGHT_PARENTHESES:tk,CHAR_LEFT_CURLY_BRACE:nk,CHAR_RIGHT_CURLY_BRACE:sk,CHAR_LEFT_SQUARE_BRACKET:ym,CHAR_RIGHT_SQUARE_BRACKET:bm,CHAR_DOUBLE_QUOTE:rk,CHAR_SINGLE_QUOTE:ik,CHAR_NO_BREAK_SPACE:ok,CHAR_ZERO_WIDTH_NOBREAK_SPACE:ak}=mm(),lk=(n,e={})=>{if(typeof n!="string")throw new TypeError("Expected a string");let t=e||{},s=typeof t.maxLength=="number"?Math.min(gm,t.maxLength):gm;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,c=n.length,d=0,f=0,h,m=()=>n[d++],p=y=>{if(y.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&y.type==="text"){a.value+=y.value;return}return o.nodes.push(y),y.parent=o,y.prev=a,a=y,y};for(p({type:"bos"});d<c;)if(o=i[i.length-1],h=m(),!(h===ak||h===ok)){if(h===za){p({type:"text",value:(e.keepEscaping?h:"")+m()});continue}if(h===bm){p({type:"text",value:"\\"+h});continue}if(h===ym){l++;let y;for(;d<c&&(y=m());){if(h+=y,y===ym){l++;continue}if(y===za){h+=m();continue}if(y===bm&&(l--,l===0))break}p({type:"text",value:h});continue}if(h===ek){o=p({type:"paren",nodes:[]}),i.push(o),p({type:"text",value:h});continue}if(h===tk){if(o.type!=="paren"){p({type:"text",value:h});continue}o=i.pop(),p({type:"text",value:h}),o=i[i.length-1];continue}if(h===rk||h===ik||h===QA){let y=h,S;for(e.keepQuotes!==!0&&(h="");d<c&&(S=m());){if(S===za){h+=S+m();continue}if(S===y){e.keepQuotes===!0&&(h+=S);break}h+=S}p({type:"text",value:h});continue}if(h===nk){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=p(S),i.push(o),p({type:"open",value:h});continue}if(h===sk){if(o.type!=="brace"){p({type:"text",value:h});continue}let y="close";o=i.pop(),o.close=!0,p({type:y,value:h}),f--,o=i[i.length-1];continue}if(h===XA&&f>0){if(o.ranges>0){o.ranges=0;let y=o.nodes.shift();o.nodes=[y,{type:"text",value:JA(o)}]}p({type:"comma",value:h}),o.commas++;continue}if(h===ZA&&f>0&&o.commas===0){let y=o.nodes;if(f===0||y.length===0){p({type:"text",value:h});continue}if(a.type==="dot"){if(o.range=[],a.value+=h,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){y.pop();let S=y[y.length-1];S.value+=a.value+h,a=S,o.ranges--;continue}p({type:"dot",value:h});continue}p({type:"text",value:h})}do if(o=i.pop(),o.type!=="root"){o.nodes.forEach(_=>{_.nodes||(_.type==="open"&&(_.isOpen=!0),_.type==="close"&&(_.isClose=!0),_.nodes||(_.type="text"),_.invalid=!0)});let y=i[i.length-1],S=y.nodes.indexOf(o);y.nodes.splice(S,1,...o.nodes)}while(i.length>0);return p({type:"eos"}),r};vm.exports=lk});var _m=H((TR,Sm)=>{"use strict";var xm=vr(),ck=um(),uk=pm(),dk=wm(),Me=(n,e={})=>{let t=[];if(Array.isArray(n))for(let s of n){let r=Me.create(s,e);Array.isArray(r)?t.push(...r):t.push(r)}else t=[].concat(Me.create(n,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};Me.parse=(n,e={})=>dk(n,e);Me.stringify=(n,e={})=>xm(typeof n=="string"?Me.parse(n,e):n,e);Me.compile=(n,e={})=>(typeof n=="string"&&(n=Me.parse(n,e)),ck(n,e));Me.expand=(n,e={})=>{typeof n=="string"&&(n=Me.parse(n,e));let t=uk(n,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};Me.create=(n,e={})=>n===""||n.length<3?[n]:e.expand!==!0?Me.compile(n,e):Me.expand(n,e);Sm.exports=Me});var Am=H((CR,fk)=>{fk.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 $m=H((RR,km)=>{km.exports=Am()});var Tm=H((OR,Em)=>{"use strict";var pk=require("path"),hk=$m(),mk=new Set(hk);Em.exports=n=>mk.has(pk.extname(n).slice(1).toLowerCase())});var Sr=H(B=>{"use strict";var{sep:gk}=require("path"),{platform:Ya}=process,yk=require("os");B.EV_ALL="all";B.EV_READY="ready";B.EV_ADD="add";B.EV_CHANGE="change";B.EV_ADD_DIR="addDir";B.EV_UNLINK="unlink";B.EV_UNLINK_DIR="unlinkDir";B.EV_RAW="raw";B.EV_ERROR="error";B.STR_DATA="data";B.STR_END="end";B.STR_CLOSE="close";B.FSEVENT_CREATED="created";B.FSEVENT_MODIFIED="modified";B.FSEVENT_DELETED="deleted";B.FSEVENT_MOVED="moved";B.FSEVENT_CLONED="cloned";B.FSEVENT_UNKNOWN="unknown";B.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;B.FSEVENT_TYPE_FILE="file";B.FSEVENT_TYPE_DIRECTORY="directory";B.FSEVENT_TYPE_SYMLINK="symlink";B.KEY_LISTENERS="listeners";B.KEY_ERR="errHandlers";B.KEY_RAW="rawEmitters";B.HANDLER_KEYS=[B.KEY_LISTENERS,B.KEY_ERR,B.KEY_RAW];B.DOT_SLASH=`.${gk}`;B.BACK_SLASH_RE=/\\/g;B.DOUBLE_SLASH_RE=/\/\//;B.SLASH_OR_BACK_SLASH_RE=/[/\\]/;B.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;B.REPLACER_RE=/^\.[/\\]/;B.SLASH="/";B.SLASH_SLASH="//";B.BRACE_START="{";B.BANG="!";B.ONE_DOT=".";B.TWO_DOTS="..";B.STAR="*";B.GLOBSTAR="**";B.ROOT_GLOBSTAR="/**/*";B.SLASH_GLOBSTAR="/**";B.DIR_SUFFIX="Dir";B.ANYMATCH_OPTS={dot:!0};B.STRING_TYPE="string";B.FUNCTION_TYPE="function";B.EMPTY_STR="";B.EMPTY_FN=()=>{};B.IDENTITY_FN=n=>n;B.isWindows=Ya==="win32";B.isMacos=Ya==="darwin";B.isLinux=Ya==="linux";B.isIBMi=yk.type()==="OS400"});var Mm=H((IR,Im)=>{"use strict";var _t=require("fs"),me=require("path"),{promisify:Qn}=require("util"),bk=Tm(),{isWindows:vk,isLinux:wk,EMPTY_FN:xk,EMPTY_STR:Sk,KEY_LISTENERS:gn,KEY_ERR:Ja,KEY_RAW:zn,HANDLER_KEYS:_k,EV_CHANGE:Ar,EV_ADD:_r,EV_ADD_DIR:Ak,EV_ERROR:Rm,STR_DATA:kk,STR_END:$k,BRACE_START:Ek,STAR:Tk}=Sr(),Ck="watch",Rk=Qn(_t.open),Om=Qn(_t.stat),Ok=Qn(_t.lstat),Pk=Qn(_t.close),Qa=Qn(_t.realpath),Ik={lstat:Ok,stat:Om},Za=(n,e)=>{n instanceof Set?n.forEach(e):e(n)},Yn=(n,e,t)=>{let s=n[e];s instanceof Set||(n[e]=s=new Set([s])),s.add(t)},Mk=n=>e=>{let t=n[e];t instanceof Set?t.clear():delete n[e]},Jn=(n,e,t)=>{let s=n[e];s instanceof Set?s.delete(t):s===t&&delete n[e]},Pm=n=>n instanceof Set?n.size===0:!n,kr=new Map;function Cm(n,e,t,s,r){let i=(o,a)=>{t(n),r(o,a,{watchedPath:n}),a&&n!==a&&$r(me.resolve(n,a),gn,me.join(n,a))};try{return _t.watch(n,e,i)}catch(o){s(o)}}var $r=(n,e,t,s,r)=>{let i=kr.get(n);i&&Za(i[e],o=>{o(t,s,r)})},Lk=(n,e,t,s)=>{let{listener:r,errHandler:i,rawEmitter:o}=s,a=kr.get(e),l;if(!t.persistent)return l=Cm(n,t,r,i,o),l.close.bind(l);if(a)Yn(a,gn,r),Yn(a,Ja,i),Yn(a,zn,o);else{if(l=Cm(n,t,$r.bind(null,e,gn),i,$r.bind(null,e,zn)),!l)return;l.on(Rm,async c=>{let d=$r.bind(null,e,Ja);if(a.watcherUnusable=!0,vk&&c.code==="EPERM")try{let f=await Rk(n,"r");await Pk(f),d(c)}catch{}else d(c)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:l},kr.set(e,a)}return()=>{Jn(a,gn,r),Jn(a,Ja,i),Jn(a,zn,o),Pm(a.listeners)&&(a.watcher.close(),kr.delete(e),_k.forEach(Mk(a)),a.watcher=void 0,Object.freeze(a))}},Xa=new Map,Dk=(n,e,t,s)=>{let{listener:r,rawEmitter:i}=s,o=Xa.get(e),a=new Set,l=new Set,c=o&&o.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&(a=o.listeners,l=o.rawEmitters,_t.unwatchFile(e),o=void 0),o?(Yn(o,gn,r),Yn(o,zn,i)):(o={listeners:r,rawEmitters:i,options:t,watcher:_t.watchFile(e,t,(d,f)=>{Za(o.rawEmitters,m=>{m(Ar,e,{curr:d,prev:f})});let h=d.mtimeMs;(d.size!==f.size||h>f.mtimeMs||h===0)&&Za(o.listeners,m=>m(n,d))})},Xa.set(e,o)),()=>{Jn(o,gn,r),Jn(o,zn,i),Pm(o.listeners)&&(Xa.delete(e),_t.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},el=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let s=this.fsw.options,r=me.dirname(e),i=me.basename(e);this.fsw._getWatchedDir(r).add(i);let a=me.resolve(e),l={persistent:s.persistent};t||(t=xk);let c;return s.usePolling?(l.interval=s.enableBinaryInterval&&bk(i)?s.binaryInterval:s.interval,c=Dk(e,a,l,{listener:t,rawEmitter:this.fsw._emitRaw})):c=Lk(e,a,l,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),c}_handleFile(e,t,s){if(this.fsw.closed)return;let r=me.dirname(e),i=me.basename(e),o=this.fsw._getWatchedDir(r),a=t;if(o.has(i))return;let l=async(d,f)=>{if(this.fsw._throttle(Ck,e,5)){if(!f||f.mtimeMs===0)try{let h=await Om(e);if(this.fsw.closed)return;let m=h.atimeMs,p=h.mtimeMs;(!m||m<=p||p!==a.mtimeMs)&&this.fsw._emit(Ar,e,h),wk&&a.ino!==h.ino?(this.fsw._closeFile(d),a=h,this.fsw._addPathCloser(d,this._watchWithNodeFs(e,l))):a=h}catch{this.fsw._remove(r,i)}else if(o.has(i)){let h=f.atimeMs,m=f.mtimeMs;(!h||h<=m||m!==a.mtimeMs)&&this.fsw._emit(Ar,e,f),a=f}}},c=this._watchWithNodeFs(e,l);if(!(s&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(_r,e,0))return;this.fsw._emit(_r,e,t)}return c}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 Qa(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(Ar,s,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(_r,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=me.join(e,Sk),!s.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let l=this.fsw._getWatchedDir(s.path),c=new Set,d=this.fsw._readdirp(e,{fileFilter:f=>s.filterPath(f),directoryFilter:f=>s.filterDir(f),depth:0}).on(kk,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,m=me.join(e,h);if(c.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===r||!r&&!l.has(h))&&(this.fsw._incrReadyCount(),m=me.join(i,me.relative(i,m)),this._addToNodeFs(m,t,s,o+1))}}).on(Rm,this._boundHandleError);return new Promise(f=>d.once($k,()=>{if(this.fsw.closed){d=void 0;return}let h=a?a.clear():!1;f(),l.getChildren().filter(m=>m!==e&&!c.has(m)&&(!s.hasGlob||s.filterPath({fullPath:me.resolve(e,m)}))).forEach(m=>{this.fsw._remove(e,m)}),d=void 0,h&&this._handleRead(e,!1,s,r,i,o,a)}))}async _handleDir(e,t,s,r,i,o,a){let l=this.fsw._getWatchedDir(me.dirname(e)),c=l.has(me.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!i&&!c&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(Ak,e,t),l.add(me.basename(e)),this.fsw._getWatchedDir(e);let d,f,h=this.fsw.options.depth;if((h==null||r<=h)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,s,o,i,e,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(m,p)=>{p&&p.mtimeMs===0||this._handleRead(m,!1,o,i,e,r,d)})}return f}async _addToNodeFs(e,t,s,r,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,r);!a.hasGlob&&s&&(a.hasGlob=s.hasGlob,a.globFilter=s.globFilter,a.filterPath=l=>s.filterPath(l),a.filterDir=l=>s.filterDir(l));try{let l=await Ik[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))return o(),!1;let c=this.fsw.options.followSymlinks&&!e.includes(Tk)&&!e.includes(Ek),d;if(l.isDirectory()){let f=me.resolve(e),h=c?await Qa(e):e;if(this.fsw.closed||(d=await this._handleDir(a.watchPath,l,t,r,i,a,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(l.isSymbolicLink()){let f=c?await Qa(e):e;if(this.fsw.closed)return;let h=me.dirname(a.watchPath);if(this.fsw._getWatchedDir(h).add(a.watchPath),this.fsw._emit(_r,a.watchPath,l),d=await this._handleDir(h,l,t,r,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(me.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}}};Im.exports=el});var Bm=H((MR,ll)=>{"use strict";var ol=require("fs"),ge=require("path"),{promisify:al}=require("util"),yn;try{yn=require("fsevents")}catch(n){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(n)}if(yn){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&&(yn=void 0)}}var{EV_ADD:tl,EV_CHANGE:Nk,EV_ADD_DIR:Lm,EV_UNLINK:Er,EV_ERROR:Fk,STR_DATA:Hk,STR_END:jk,FSEVENT_CREATED:Bk,FSEVENT_MODIFIED:Uk,FSEVENT_DELETED:Kk,FSEVENT_MOVED:qk,FSEVENT_UNKNOWN:Wk,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:Gk,FSEVENT_TYPE_FILE:Vk,FSEVENT_TYPE_DIRECTORY:Xn,FSEVENT_TYPE_SYMLINK:jm,ROOT_GLOBSTAR:Dm,DIR_SUFFIX:zk,DOT_SLASH:Nm,FUNCTION_TYPE:nl,EMPTY_FN:Yk,IDENTITY_FN:Jk}=Sr(),Qk=n=>isNaN(n)?{}:{depth:n},rl=al(ol.stat),Xk=al(ol.lstat),Fm=al(ol.realpath),Zk={stat:rl,lstat:Xk},Gt=new Map,e$=10,t$=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),n$=(n,e)=>({stop:yn.watch(n,e)});function s$(n,e,t,s){let r=ge.extname(e)?ge.dirname(e):e,i=ge.dirname(r),o=Gt.get(r);r$(i)&&(r=i);let a=ge.resolve(n),l=a!==e,c=(f,h,m)=>{l&&(f=f.replace(e,a)),(f===a||!f.indexOf(a+ge.sep))&&t(f,h,m)},d=!1;for(let f of Gt.keys())if(e.indexOf(ge.resolve(f)+ge.sep)===0){r=f,o=Gt.get(r),d=!0;break}return o||d?o.listeners.add(c):(o={listeners:new Set([c]),rawEmitter:s,watcher:n$(r,(f,h)=>{if(!o.listeners.size||h&Gk)return;let m=yn.getInfo(f,h);o.listeners.forEach(p=>{p(f,h,m)}),o.rawEmitter(m.event,f,m)})},Gt.set(r,o)),()=>{let f=o.listeners;if(f.delete(c),!f.size&&(Gt.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var r$=n=>{let e=0;for(let t of Gt.keys())if(t.indexOf(n)===0&&(e++,e>=e$))return!0;return!1},i$=()=>yn&&Gt.size<128,sl=(n,e)=>{let t=0;for(;!n.indexOf(e)&&(n=ge.dirname(n))!==e;)t++;return t},Hm=(n,e)=>n.type===Xn&&e.isDirectory()||n.type===jm&&e.isSymbolicLink()||n.type===Vk&&e.isFile(),il=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+Dm),!0;s.delete(e),s.delete(e+Dm)}addOrChange(e,t,s,r,i,o,a,l){let c=i.has(o)?Nk:tl;this.handleEvent(c,e,t,s,r,i,o,a,l)}async checkExists(e,t,s,r,i,o,a,l){try{let c=await rl(e);if(this.fsw.closed)return;Hm(a,c)?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(Er,e,t,s,r,i,o,a,l)}catch(c){c.code==="EACCES"?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(Er,e,t,s,r,i,o,a,l)}}handleEvent(e,t,s,r,i,o,a,l,c){if(!(this.fsw.closed||this.checkIgnored(t)))if(e===Er){let d=l.type===Xn;(d||o.has(a))&&this.fsw._remove(i,a,d)}else{if(e===tl){if(l.type===Xn&&this.fsw._getWatchedDir(t),l.type===jm&&c.followSymlinks){let f=c.depth===void 0?void 0:sl(s,r)+1;return this._addToFsEvents(t,!1,!0,f)}this.fsw._getWatchedDir(i).add(a)}let d=l.type===Xn?e+zk:e;this.fsw._emit(d,t),d===Lm&&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=s$(e,t,async(l,c,d)=>{if(this.fsw.closed||i.depth!==void 0&&sl(l,t)>i.depth)return;let f=s(ge.join(e,ge.relative(e,l)));if(r&&!r(f))return;let h=ge.dirname(f),m=ge.basename(f),p=this.fsw._getWatchedDir(d.type===Xn?f:h);if(t$.has(c)||d.event===Wk)if(typeof i.ignored===nl){let y;try{y=await rl(f)}catch{}if(this.fsw.closed||this.checkIgnored(f,y))return;Hm(d,y)?this.addOrChange(f,l,t,h,p,m,d,i):this.handleEvent(Er,f,l,t,h,p,m,d,i)}else this.checkExists(f,l,t,h,p,m,d,i);else switch(d.event){case Bk:case Uk:return this.addOrChange(f,l,t,h,p,m,d,i);case Kk:case qk:return this.checkExists(f,l,t,h,p,m,d,i)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,t,s,r){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(t))){this.fsw._symlinkPaths.set(t,!0),this.fsw._incrReadyCount();try{let i=await Fm(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!==Nm?a=o.replace(i,e):o!==Nm&&(a=ge.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(ge.dirname(o)),c=ge.basename(o);a&&this.fsw._getWatchedDir(o),!l.has(c)&&(l.add(c),(!r.ignoreInitial||i===!0)&&this.fsw._emit(a?Lm:tl,o,t))}initWatch(e,t,s,r){if(this.fsw.closed)return;let i=this._watchWithFsEvents(s.watchPath,ge.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===nl?t:Jk,a=this.fsw._getWatchHelpers(e);try{let l=await Zk[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:c=>a.filterPath(c),directoryFilter:c=>a.filterDir(c),...Qk(i.depth-(r||0))}).on(Hk,c=>{if(this.fsw.closed||c.stats.isDirectory()&&!a.filterPath(c))return;let d=ge.join(a.watchPath,c.path),{fullPath:f}=c;if(a.followSymlinks&&c.stats.isSymbolicLink()){let h=i.depth===void 0?void 0:sl(d,ge.resolve(a.watchPath))+1;this._handleFsEventsSymlink(d,f,o,h)}else this.emitAdd(d,c.stats,o,i,s)}).on(Fk,Yk).on(jk,()=>{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===nl)this.initWatch(void 0,e,a,o);else{let l;try{l=await Fm(a.watchPath)}catch{}this.initWatch(l,e,a,o)}}};ll.exports=il;ll.exports.canUse=i$});var Xm=H(_l=>{"use strict";var{EventEmitter:o$}=require("events"),xl=require("fs"),Z=require("path"),{promisify:zm}=require("util"),a$=Th(),hl=Lh().default,l$=Bh(),cl=Ua(),c$=_m(),u$=ja(),d$=Mm(),Um=Bm(),{EV_ALL:ul,EV_READY:f$,EV_ADD:Tr,EV_CHANGE:Zn,EV_UNLINK:Km,EV_ADD_DIR:p$,EV_UNLINK_DIR:h$,EV_RAW:m$,EV_ERROR:dl,STR_CLOSE:g$,STR_END:y$,BACK_SLASH_RE:b$,DOUBLE_SLASH_RE:qm,SLASH_OR_BACK_SLASH_RE:v$,DOT_RE:w$,REPLACER_RE:x$,SLASH:fl,SLASH_SLASH:S$,BRACE_START:_$,BANG:ml,ONE_DOT:Ym,TWO_DOTS:A$,GLOBSTAR:k$,SLASH_GLOBSTAR:pl,ANYMATCH_OPTS:gl,STRING_TYPE:Sl,FUNCTION_TYPE:$$,EMPTY_STR:yl,EMPTY_FN:E$,isWindows:T$,isMacos:C$,isIBMi:R$}=Sr(),O$=zm(xl.stat),P$=zm(xl.readdir),bl=(n=[])=>Array.isArray(n)?n:[n],Jm=(n,e=[])=>(n.forEach(t=>{Array.isArray(t)?Jm(t,e):e.push(t)}),e),Wm=n=>{let e=Jm(bl(n));if(!e.every(t=>typeof t===Sl))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Qm)},Gm=n=>{let e=n.replace(b$,fl),t=!1;for(e.startsWith(S$)&&(t=!0);e.match(qm);)e=e.replace(qm,fl);return t&&(e=fl+e),e},Qm=n=>Gm(Z.normalize(Gm(n))),Vm=(n=yl)=>e=>typeof e!==Sl?e:Qm(Z.isAbsolute(e)?e:Z.join(n,e)),I$=(n,e)=>Z.isAbsolute(n)?n:n.startsWith(ml)?ml+Z.join(e,n.slice(1)):Z.join(e,n),Ze=(n,e)=>n[e]===void 0,vl=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Ym&&e!==A$&&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 P$(s)}catch{this._removeWatcher&&this._removeWatcher(Z.dirname(s),Z.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)}},M$="stat",L$="lstat",wl=class{constructor(e,t,s,r){this.fsw=r,this.path=e=e.replace(x$,yl),this.watchPath=t,this.fullWatchPath=Z.resolve(t),this.hasGlob=t!==e,e===yl&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&s?void 0:!1,this.globFilter=this.hasGlob?hl(e,void 0,gl):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=s,this.statMethod=s?M$:L$}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 Z.join(this.watchPath,Z.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===$$?this.globFilter(s):!0)&&this.fsw._isntIgnored(s,t)&&this.fsw._hasReadPermissions(t)}getDirParts(e){if(!this.hasGlob)return[];let t=[];return(e.includes(_$)?c$.expand(e):[e]).forEach(r=>{t.push(Z.relative(this.watchPath,r).split(v$))}),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===k$&&(s=!0),s||!t[0][o]||hl(i,t[0][o],gl))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Cr=class extends o${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,Ze(t,"persistent")&&(t.persistent=!0),Ze(t,"ignoreInitial")&&(t.ignoreInitial=!1),Ze(t,"ignorePermissionErrors")&&(t.ignorePermissionErrors=!1),Ze(t,"interval")&&(t.interval=100),Ze(t,"binaryInterval")&&(t.binaryInterval=300),Ze(t,"disableGlobbing")&&(t.disableGlobbing=!1),t.enableBinaryInterval=t.binaryInterval!==t.interval,Ze(t,"useFsEvents")&&(t.useFsEvents=!t.usePolling),Um.canUse()||(t.useFsEvents=!1),Ze(t,"usePolling")&&!t.useFsEvents&&(t.usePolling=C$),R$&&(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)),Ze(t,"atomic")&&(t.atomic=!t.usePolling&&!t.useFsEvents),t.atomic&&(this._pendingUnlinks=new Map),Ze(t,"followSymlinks")&&(t.followSymlinks=!0),Ze(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=bl(t.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=E$,this._readyEmitted=!0,process.nextTick(()=>this.emit(f$)))},this._emitRaw=(...l)=>this.emit(m$,...l),this._readyEmitted=!1,this.options=t,t.useFsEvents?this._fsEventsHandler=new Um(this):this._nodeFsHandler=new d$(this),Object.freeze(t)}add(e,t,s){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=Wm(e);return r&&(o=o.map(a=>{let l=I$(a,r);return i||!cl(a)?l:u$(l)})),o=o.filter(a=>a.startsWith(ml)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+pl),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(Z.dirname(l),Z.basename(t||l))})})),this}unwatch(e){if(this.closed)return this;let t=Wm(e),{cwd:s}=this.options;return t.forEach(r=>{!Z.isAbsolute(r)&&!this._closers.has(r)&&(s&&(r=Z.join(s,r)),r=Z.resolve(r)),this._closePath(r),this._ignoredPaths.add(r),this._watched.has(r)&&this._ignoredPaths.add(r+pl),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?Z.relative(this.options.cwd,s):s;e[r||Ym]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(...t),e!==dl&&this.emit(ul,...t)}async _emit(e,t,s,r,i){if(this.closed)return;let o=this.options;T$&&(t=Z.normalize(t)),o.cwd&&(t=Z.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,c;if(l&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(o.atomic){if(e===Km)return this._pendingUnlinks.set(t,a),setTimeout(()=>{this._pendingUnlinks.forEach((d,f)=>{this.emit(...d),this.emit(ul,...d),this._pendingUnlinks.delete(f)})},typeof o.atomic=="number"?o.atomic:100),this;e===Tr&&this._pendingUnlinks.has(t)&&(e=a[0]=Zn,this._pendingUnlinks.delete(t))}if(l&&(e===Tr||e===Zn)&&this._readyEmitted){let d=(f,h)=>{f?(e=a[0]=dl,a[1]=f,this.emitWithAll(e,a)):h&&(a.length>2?a[2]=h:a.push(h),this.emitWithAll(e,a))};return this._awaitWriteFinish(t,l.stabilityThreshold,e,d),this}if(e===Zn&&!this._throttle(Zn,t,50))return this;if(o.alwaysStat&&s===void 0&&(e===Tr||e===p$||e===Zn)){let d=o.cwd?Z.join(o.cwd,t):t,f;try{f=await O$(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(dl,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 c=r.get(t),d=c?c.count:0;return r.delete(t),clearTimeout(o),c&&clearTimeout(c.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&&!Z.isAbsolute(e)&&(o=Z.join(this.options.cwd,e));let a=new Date,l=c=>{xl.stat(o,(d,f)=>{if(d||!this._pendingWrites.has(e)){d&&d.code!=="ENOENT"&&r(d);return}let h=Number(new Date);c&&f.size!==c.size&&(this._pendingWrites.get(e).lastChange=h);let m=this._pendingWrites.get(e);h-m.lastChange>=t?(this._pendingWrites.delete(e),r(void 0,f)):i=setTimeout(l,this.options.awaitWriteFinish.pollInterval,f)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(i),s)}),i=setTimeout(l,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,t){if(this.options.atomic&&w$.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,r=this.options.ignored,i=r&&r.map(Vm(s)),o=bl(i).filter(l=>typeof l===Sl&&!cl(l)).map(l=>l+pl),a=this._getGlobIgnored().map(Vm(s)).concat(i,o);this._userIgnored=hl(a,void 0,gl)}return this._userIgnored([e,t])}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e,t){let s=t||this.options.disableGlobbing||!cl(e)?e:l$(e),r=this.options.followSymlinks;return new wl(e,s,r,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let t=Z.resolve(e);return this._watched.has(t)||this._watched.set(t,new vl(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=Z.join(e,t),i=Z.resolve(r);if(s=s??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!s&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(h=>this._remove(r,h));let l=this._getWatchedDir(e),c=l.has(t);l.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=Z.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===Tr)return;this._watched.delete(r),this._watched.delete(i);let f=s?h$:Km;c&&!this._isIgnored(r)&&this._emit(f,r),this.options.useFsEvents||this._closePath(r)}_closePath(e){this._closeFile(e);let t=Z.dirname(e);this._getWatchedDir(t).remove(Z.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:ul,alwaysStat:!0,lstat:!0,...t},r=a$(e,s);return this._streams.add(r),r.once(g$,()=>{r=void 0}),r.once(y$,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};_l.FSWatcher=Cr;var D$=(n,e)=>{let t=new Cr(e);return t.add(n),t};_l.watch=D$});var ng={};Re(ng,{CollaborationManager:()=>Al,addTeamMember:()=>H$,formatTeamConfig:()=>j$,initTeamConfig:()=>F$,loadTeamConfig:()=>N$,saveTeamConfig:()=>tg});function N$(n){let e=Ke.join(n,".hablas","team.json");if(ue.existsSync(e))try{return JSON.parse(ue.readFileSync(e,"utf-8"))}catch{return null}return null}function F$(n,e){let t={name:e,members:[]};return tg(n,t),t}function tg(n,e){let t=Ke.join(n,".hablas","team.json"),s=Ke.dirname(t);ue.existsSync(s)||ue.mkdirSync(s,{recursive:!0}),ue.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}function H$(n,e,t){return n.members.push({name:e,email:t}),n}function j$(n){return[`Team: ${n.name}`,"Members:",...n.members.map(t=>` - ${t.name} (${t.email})`)].join(`
910
- `)}var ue,Ke,Rr,Zm,eg,Al,sg=N(()=>{"use strict";ue=O(require("fs")),Ke=O(require("path")),Rr=O(require("os")),Zm=O(require("crypto")),eg=O(Xm());en();Al=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||Rr.userInfo().username||"developer",this.teamKey=r||"default-team",this.localStatePath=Ke.join(this.workingDir,".hablas","collaboration.json");let i=this.getProjectIdentifier();console.log(`
911
- ${u.muted("[Debug] Project Context:")} ${u.highlight(i)}`),this.projectTeamToken=Zm.createHash("sha256").update(`${i}:${this.teamKey}`).digest("hex"),console.log(` ${u.muted("[Debug] Session Fingerprint:")} ${u.muted(this.projectTeamToken.slice(0,16))}...
912
- `),this.loadSupabaseConfig()}async init(){if(!this.isConfigured)return console.log(` ${u.warning("\u26A0")} ${u.secondary("Supabase is not configured in .env. Collaboration mode operates locally.")}`),!1;let e=Ke.dirname(this.localStatePath);return ue.existsSync(e)||ue.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 c=0;c<a;c++)try{let d=await fetch(i,{method:t,headers:o,body:s?JSON.stringify(s):void 0,signal:AbortSignal.timeout(1e4)});if(!d.ok){let h=await d.text().catch(()=>"");if(l=new Error(`[Supabase ${d.status}] ${h}`),(d.status>=500||d.status===429)&&c<a-1){await this.delay(400*(c+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,c<a-1){await this.delay(400*(c+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};ue.writeFileSync(this.localStatePath,JSON.stringify(s,null,2),"utf-8")}getLocalState(){if(ue.existsSync(this.localStatePath))try{return JSON.parse(ue.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(`
913
- ${u.success("\u2713")} ${u.muted("[Team]")} Cloud sync reconnected \u2014 session restored.
738
+ 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,r,{abortSignal:s});if(l.success&&l.output)return{results:t,finalSynthesis:l.output,synthesisOk:!0};let c=i.map(u=>{let d=me.find(p=>p.role===u.agent);return`### @${u.agentName} (${d?.title??u.agent}):
739
+ ${u.output}`}).join(`
740
+
741
+ `);return{results:t,finalSynthesis:c,synthesisOk:!1}}}});function Ne(n){switch(n){case"Hablas":return m.leader;case"Bob":return m.architect;case"Alex":return m.engineer;case"David":return m.analyst;case"Emma":return m.product;default:return m.primary}}function wr(n){return n==="Hablas"?"\u2605":"\u25C6"}function hn(n,e=140){let t=(n||"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e-1)+"\u2026":t}var vr,pf=M(()=>{"use strict";Ot();vr=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=r=>this.handle(r)}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(`
742
+ ${m.muted("\u25B8")} ${m.secondary(t)}`),this.lastThinking=null)}renderHandoff(e){let t=e.agent,r=e.to||"";if(!r)return;let s=Ne(t),i=Ne(r);this.print(` ${s(wr(t))} ${s(t)} ${m.muted("\u2501\u2501\u25B6")} ${i(wr(r))} ${i(r)}`),this.lastThinking=null}renderThinking(e){if(this.opts.hideThinking||this.lastThinking===e.agent)return;this.lastThinking=e.agent;let t=Ne(e.agent);this.print(` ${t("\u25C9")} [Active Agent: ${e.agent}] is thinking & formulating response\u2026`)}renderSpeak(e){let t=hn(e.content||"",this.opts.maxChars);if(!t)return;let r=Ne(e.agent),s=e.to?` ${m.muted("\u2192")} ${Ne(e.to)("@"+e.to)}`:"",i=`speak:${e.agent}:${e.to||""}:${t}`;i!==this.lastLine&&(this.lastLine=i,this.print(` ${r(wr(e.agent))} ${r(e.agent)}${s}${m.muted(":")} ${m.secondary(t)}`),this.lastThinking=null)}renderAct(e){if(this.opts.hideActs)return;let t=Ne(e.agent),r=e.toolName||"tool",s=e.toolArgs||{},i="";typeof s.path=="string"?i=` ${m.primary(s.path)}`:typeof s.command=="string"?i=` ${m.primary(s.command)}`:typeof s.query=="string"&&(i=` "${m.primary(s.query)}"`);let o=r==="write_file"||r==="edit_file"||r==="patch_file"?"\u270E":r==="run_command"?"\u2318":r==="read_file"?"\u{1F4D6}":r==="search_codebase"?"\u{1F50E}":"\u{1F527}";this.print(` ${t(o)} [Running Tool]: ${t(e.agent)} is executing ${m.strong(r)}${i}...`),this.lastThinking=null}renderObserve(e){if(this.opts.hideActs)return;let t=e.success!==!1,r=t?m.success("\u2713 COMPLETED"):m.error("\u2717 FAILED"),s=hn(e.content||(t?"Execution succeeded":"Execution failed"),this.opts.maxChars);this.print(` ${m.muted("\u21B3")} ${r}: ${m.muted(s)}`)}renderReview(e){let t=e.agent,r=e.to||"",s=hn(e.content||"",this.opts.maxChars);if(!s)return;let i=Ne(t),o=Ne(r);this.print(`
743
+ ${i("\u270E")} ${m.strong("@"+t)} ${m.muted("reviewing")} ${o("@"+r)}${m.muted(":")} ${m.secondary(s)}`),this.lastThinking=null}renderSummary(e){let t=Ne(e.agent),r=e.durationMs?` ${m.muted(`(${(e.durationMs/1e3).toFixed(1)}s)`)}`:"";this.print(` ${t(wr(e.agent))} ${t(e.agent)} ${m.muted("\u2500\u2500\u25BA")} ${m.leader("\u2605 Hablas")} ${m.muted("\xB7 report submitted")}${r}`),this.lastThinking=null}renderDecision(e){let t=hn(e.content||"",this.opts.maxChars);if(!t)return;let r=Ne(e.agent);this.print(` ${r("\u25C6")} ${r(e.agent)} ${m.muted("decision:")} ${m.secondary(t)}`)}renderDone(e){this.print(`
744
+ ${m.chrome("\u2500".repeat(56))}`),this.lastThinking=null}renderError(e){let t=Ne(e.agent),r=hn(e.content||"unknown error",this.opts.maxChars);this.print(` ${t("\u25C6")} ${t(e.agent)} ${m.error("\u2717")} ${m.error(r)}`),this.lastThinking=null}print(e){console.log(e)}}});var gf={};Ae(gf,{formatStats:()=>Qx,loadStats:()=>xr,saveStats:()=>_r,trackAgentUsage:()=>Yx,trackFileModified:()=>Jx,trackMessage:()=>po,trackSession:()=>zx,trackToolCall:()=>ho});function xr(){try{if(nt.existsSync(uo))return JSON.parse(nt.readFileSync(uo,"utf-8"))}catch{}return Vx()}function _r(n){try{nt.existsSync(co)||nt.mkdirSync(co,{recursive:!0}),nt.writeFileSync(uo,JSON.stringify(n,null,2))}catch{}}function Vx(){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 zx(n){return n.totalSessions++,n.lastUsed=new Date().toISOString(),Xx(n),n}function po(n,e=0){n.totalMessages++,n.totalTokensUsed+=e;let t=Sr();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 ho(n,e){n.totalToolCalls++,n.commandUsage[e]=(n.commandUsage[e]||0)+1;let t=Sr();return n.dailyActivity[t]||(n.dailyActivity[t]={messages:0,tokens:0,toolCalls:0,filesModified:0,linesWritten:0}),n.dailyActivity[t].toolCalls++,n}function Yx(n,e){return n.agentUsage[e]=(n.agentUsage[e]||0)+1,n}function Jx(n,e=0){n.totalFilesModified++,n.totalLinesWritten+=e;let t=Sr();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 Xx(n){let e=Sr(),t=mf(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 Sr(){return mf(new Date)}function mf(n){return n.toISOString().split("T")[0]}function Qx(n){let e=[];e.push(`
745
+ \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((s,i)=>i[1]-s[1]).slice(0,5);if(t.length>0){e.push(" Top Agents:");for(let[s,i]of t)e.push(` @${s}: ${i} uses`);e.push("")}let r=Object.entries(n.commandUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(r.length>0){e.push(" Top Commands:");for(let[s,i]of r)e.push(` ${s}: ${i} calls`)}return e.join(`
746
+ `)}var nt,fo,hf,co,uo,mo=M(()=>{"use strict";nt=C(require("fs")),fo=C(require("path")),hf=C(require("os")),co=fo.join(hf.homedir(),".hablas"),uo=fo.join(co,"analytics.json")});var Ar,yf=M(()=>{"use strict";Ar=class{plans=new Map;activePlanId=null;nextPlanNum=1;createPlan(e,t,r){let s=`plan_${this.nextPlanNum++}`,i={hablas:"Hablas",bob:"Bob",alex:"Alex",david:"David"},o={id:s,title:e,strategy:t,tasks:r.map((a,l)=>({task_id:`${s}_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(s,o),this.activePlanId=s,o}getActivePlan(){return this.activePlanId&&this.plans.get(this.activePlanId)||null}getTask(e){let t=this.getActivePlan();return t&&t.tasks.find(r=>r.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 r=this.getTask(e);return r?(r.status="done",r.result=t,r.completedAt=Date.now(),this.touch(),!0):!1}failTask(e,t){let r=this.getTask(e);return r?(r.status="failed",r.error=t,r.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,r){let s=this.getTask(e);return s?(s.description=t,r&&(s.assignee=r),s.status="pending",s.result=void 0,s.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 r=this.getActivePlan();return r?t.dependent_task_ids.every(s=>{let i=r.tasks.find(o=>o.task_id===s);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,r=[],s=new Map(e.tasks.map(o=>[o.task_id,o])),i=o=>{if(t.has(o))return;t.add(o);let a=s.get(o);if(a){for(let l of a.dependent_task_ids)i(l);r.push(a)}};for(let o of e.tasks)i(o.task_id);return r}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,r=e.tasks.filter(c=>c.status==="done").length,s=e.tasks.filter(c=>c.status==="failed").length,i=e.tasks.filter(c=>c.status==="pending").length,o=e.tasks.filter(c=>c.status==="running").length,a=e.tasks.filter(c=>c.status==="skipped").length,l=t>0?Math.round((r+a)/t*100):0;return{total:t,done:r,failed:s,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())}}});function wf(n){let e=n.trim(),t=e.toLowerCase();if(Zx.test(e)||e_.test(e)||e.length<15&&!t_.test(e))return"XS";if(s_.test(t)||bf.test(t)&&e.length>150)return"XL";let r=t.match(r_)||[],i=new Set(r.map(a=>a.toLowerCase())).size,o=e.split(/[.!?]+/).filter(a=>a.trim().length>5);return bf.test(t)||o.length>=3&&i>=2||i>=3&&e.length>100?"L":i_.test(t)||i>=2&&e.length>=50||e.length>=50&&e.length<=150&&i>=1&&o.length>=2?"M":(e.length<50&&i<=1||n_.test(e)&&i<=1||i===1,"S")}var Zx,e_,t_,n_,r_,s_,bf,i_,vf=M(()=>{"use strict";Zx=/^(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,e_=/^(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,t_=/\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,n_=/[\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,r_=/\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,s_=/\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,bf=/\b(design|architect)\b.*\b(implement|build|create|develop)\b/i,i_=/\b(multiple\s+files|several\s+components|across\s+all|every\s+file|all\s+modules)\b/i});function xf(n){let e=n.toLowerCase();return/\b(how|why|what|tell\s+me|explain)\b/i.test(e)?"QUESTION":/\b(research|find|search|docs|compare|analyze)\b/i.test(e)?"RESEARCH":/\b(fix|bug|issue|error|solve|debug)\b/i.test(e)?"DEBUGGING":/\b(refactor|cleanup|restructure|rewrite)\b/i.test(e)?"REFACTORING":/\b(design|architect|schema|blueprint|structure)\b/i.test(e)?"ARCHITECTURE":"IMPLEMENTATION"}function _f(n){let e=n.trim();if(!e)return 0;let t=/[\w-]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|html|env)/i.test(e)?.4:0,r=/\b(read|write|run|edit|search|list|delete|patch)\b/i.test(e)?.3:0,s=e.startsWith("/")?.3:0;return Math.min(1,t+r+s)}var Sf=M(()=>{"use strict"});function o_(n,e){let t=[],r;for(Af.lastIndex=0;(r=Af.exec(n))!==null;){let s=r[1],i=fe.resolve(e,s);je.existsSync(i)&&t.push(s)}return[...new Set(t)]}function a_(n,e,t){let r=[],s=fe.extname(e),i=fe.dirname(fe.resolve(t,e));if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(s)){let o;for(kf.lastIndex=0;(o=kf.exec(n))!==null;){let a=o[1]||o[2];if(!a||!a.startsWith(".")&&!a.startsWith("/"))continue;let l=l_(a,i);l&&r.push(fe.relative(t,l))}}else if(s===".py"){let o;for($f.lastIndex=0;(o=$f.exec(n))!==null;){let a=o[1]||o[2];if(!a)continue;let l=a.replace(/\./g,"/")+".py",c=fe.resolve(i,l);je.existsSync(c)&&r.push(fe.relative(t,c))}}return[...new Set(r)]}function l_(n,e){let t=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],r=fe.resolve(e,n);if(je.existsSync(r)&&je.statSync(r).isFile())return r;for(let s of t){let i=r+s;if(je.existsSync(i))return i}for(let s of t){let i=fe.join(r,`index${s}`);if(je.existsSync(i))return i}return null}function Ef(n,e,t){let r=t?.maxFiles||10,s=t?.maxTokens||8e3,i=t?.followImports!==!1,o=o_(n,e),a=[],l=new Set,c=0;for(let u of o){if(a.length>=r||c>=s)break;if(!l.has(u)){l.add(u);try{let d=fe.resolve(e,u),p=je.readFileSync(d,"utf-8"),h=p.split(`
747
+ `).length,f=Math.ceil(p.length/4);if(f>4e3){let g=p.split(`
748
+ `).slice(0,200).join(`
749
+ `)+`
750
+ ...(truncated)`,y=Math.ceil(g.length/4);c+y<=s&&(a.push({path:u,content:g,source:"mentioned",lineCount:200}),c+=y)}else if(c+f<=s&&(a.push({path:u,content:p,source:"mentioned",lineCount:h}),c+=f,i)){let g=a_(p,u,e);for(let y of g.slice(0,5)){if(a.length>=r||c>=s)break;if(!l.has(y)){l.add(y);try{let w=fe.resolve(e,y),v=je.readFileSync(w,"utf-8"),S=Math.ceil(v.length/4),k=v.split(`
751
+ `).length;if(S>2e3){let P=v.split(`
752
+ `).slice(0,100).join(`
753
+ `)+`
754
+ ...(truncated)`,j=Math.ceil(P.length/4);c+j<=s&&(a.push({path:y,content:P,source:"imported",lineCount:100}),c+=j)}else c+S<=s&&(a.push({path:y,content:v,source:"imported",lineCount:k}),c+=S)}catch{}}}}}catch{}}}return{files:a,totalTokensEstimate:c,mentionedPaths:o}}function Cf(n){if(n.files.length===0)return"";let e=["## Referenced Files"];for(let t of n.files){let r=t.source==="imported"?" (imported)":"";e.push(`### ${t.path}${r} (${t.lineCount} lines)`),e.push("```"),e.push(t.content),e.push("```")}return e.join(`
755
+ `)}var je,fe,Af,kf,$f,Tf=M(()=>{"use strict";je=C(require("fs")),fe=C(require("path")),Af=/(?:^|\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,kf=/(?:import\s+.*?\s+from\s+['"]([^'"]+)['"]|require\s*\(\s*['"]([^'"]+)['"]\s*\))/g,$f=/(?:from\s+(\S+)\s+import|import\s+(\S+))/g});var Wt={};Ae(Wt,{activeCollabManager:()=>c_,startRepl:()=>go});function Rf(n,e,t,r){let s=` ${m.accent("\u25C6")} [${m.strong(n)}] | ${m.muted("Phase:")} ${e.padEnd(10)} | ${m.muted("Action:")} ${t.slice(0,30).padEnd(30)} | ${r==="RUN"?m.warning("\u25CF"):m.success("\u2713")}`;process.stdout.write(`\r\x1B[K${s}`)}async function go(n,e){let t=n.workingDirectory==="."?process.cwd():n.workingDirectory,r=Pt(n),s=new Bn(t,n),i=new Dt(n),o=new Un(t),a=Kn(),l=new Gn(t),c=new Kt(t),u=new Ar,d=new hr(n);d.setToolRegistry(s);let p=new mr;new vr(p).attach();let h=new yr(n,{tokenBudget:500,maxChars:140});console.log(Za(n.model,t));let f=0,g=0,y=new AbortController;for(process.on("SIGINT",()=>{let w=Date.now();w-g<u_&&process.exit(0),g=w,y.abort(),y=new AbortController,console.log(`
756
+ `+ws("Interrupted."))});;)try{let w=await o.prompt(`
757
+ ${m.primary("\u203A")} `);if(!w.trim())continue;if(w.startsWith("/")){await fl(w,n,r,s,i,new vt("",10),t,o,f,a,void 0,l,D=>{r=D},c,u,void 0,d);continue}let v=d_(Cc(w),t),S=Ef(v,t,{maxFiles:5,maxTokens:4e3}),k=S.files.length>0?`[Context Attached: ${S.mentionedPaths.join(", ")}]
758
+ ${Cf(S)}
759
+
760
+ Request: ${v}`:v,P=await ul(t,n),j=dl(a.getActive()?.systemPrompt||cl,P,l,c),I=new vt(j,n.historySize);f++,console.log(nl(f)),_r(po(xr()));let $=xf(v),E=_f(v),N=wf(v);if(!fs(v)&&$!=="QUESTION"&&E<.7&&N!=="FILE"){let D=Ka(v),W=Wa(v,D),_=new br(p,d,h,n),{finalSynthesis:b}=await _.run(k,W,s.getOllamaTools(),{abortSignal:y.signal});console.log(`
761
+ `+ys("Hablas","Team Leader")),console.log(bs(b))}else I.addUserMessage(k),await pr({identity:{name:"Hablas",title:"Team Leader",role:"hablas"},client:r,registry:s,session:I,contextManager:i,logger:e,safetyPolicy:ef({autoMode:n.autoMode,interactive:!0,confirm:D=>o.confirm(D),confirmDangerous:D=>o.confirmDangerous(D)}),io:{onAssistantText:async D=>{process.stdout.write(`
762
+ `),console.log(ys("Hablas","Team Leader")),console.log(bs(D))},onToolStart:(D,W)=>Rf("Hablas","EXECUTING",D,"RUN"),onToolEnd:(D,W)=>Rf("Hablas","EXECUTING",D,W?"OK":"FAIL"),onToolCall:()=>_r(ho(xr(),"tool_call"))},abortSignal:y.signal}),process.stdout.write(`
763
+ `)}catch(w){console.log(ws(w.message))}}function d_(n,e){return n.replace(/#([\w./-]+)/g,(t,r)=>Of.existsSync(Pf.resolve(e,r))?r:t)}var Of,Pf,c_,u_,$t=M(()=>{"use strict";pl();Of=C(require("fs")),Pf=C(require("path"));Dn();bc();Is();Ls();_c();ni();kc();Tc();en();sf();af();lf();ff();pf();mo();ao();yf();vf();Sf();Ot();oo();Tf();c_=null,u_=1500});function Re(n={}){let e={};if(rt.existsSync(bo))try{let r=rt.readFileSync(bo,"utf-8");e=JSON.parse(r)}catch{}let t={...tn,...e,tools:{...tn.tools,...e.tools||{}},ui:{...tn.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 r=process.env.HABLAS_PROVIDER;(r==="ollama"||r==="custom")&&(t.provider=r)}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=mn.resolve(n.project)),n.provider){let r=n.provider;(r==="ollama"||r==="custom")&&(t.provider=r)}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 Ve(n){rt.existsSync(yo)||rt.mkdirSync(yo,{recursive:!0}),rt.writeFileSync(bo,JSON.stringify(n,null,2),"utf-8")}var rt,mn,Mf,yo,bo,wo=M(()=>{"use strict";rt=C(require("fs")),mn=C(require("path")),Mf=C(require("os"));Mn();yo=mn.join(Mf.homedir(),".hablas"),bo=mn.join(yo,"config.json")});function st(n){let e=xo.join(If.homedir(),".hablas","logs");kr.existsSync(e)||kr.mkdirSync(e,{recursive:!0});let t=xo.join(e,`session-${Date.now()}.log`);return(0,vo.default)({level:"info"},vo.default.destination({dest:t,sync:!1}))}var vo,xo,If,kr,_o=M(()=>{"use strict";vo=C(Xi()),xo=C(require("path")),If=C(require("os")),kr=C(require("fs"))});var $r={};Ae($r,{formatGitStatus:()=>w_,generateChangelogPrompt:()=>b_,generateCommitPrompt:()=>g_,generatePRPrompt:()=>y_,getDetailedDiff:()=>h_,getGitStatus:()=>f_,getRecentCommits:()=>m_,getStagedDiff:()=>p_});async function f_(n){try{let{stdout:e}=await Gt("git branch --show-current",{cwd:n}),{stdout:t}=await Gt("git status --porcelain",{cwd:n}),r=e.trim(),s=[],i=[],o=[];for(let c of t.split(`
764
+ `).filter(Boolean)){let u=c.substring(0,2),d=c.substring(3);(u.startsWith("A")||u.startsWith("M")||u.startsWith("R"))&&u[0]!==" "&&s.push(d),(u[1]==="M"||u[1]==="D")&&i.push(d),u==="??"&&o.push(d)}let a=0,l=0;try{let{stdout:c}=await Gt("git rev-list --left-right --count HEAD...@{upstream}",{cwd:n}),u=c.trim().split(" ");a=parseInt(u[0])||0,l=parseInt(u[1])||0}catch{}return{branch:r,staged:s,modified:i,untracked:o,ahead:a,behind:l}}catch{return null}}async function p_(n){try{let{stdout:e}=await Gt("git diff --cached --stat",{cwd:n});return e.trim()}catch{return""}}async function h_(n){try{let{stdout:e}=await Gt("git diff --cached",{cwd:n,maxBuffer:1048576});return e.length>1e4?e.substring(0,1e4)+`
765
+ ... (truncated)`:e.trim()}catch{return""}}async function m_(n,e=20){try{let{stdout:t}=await Gt(`git log --oneline --format="%H|%s|%an|%ai" -n ${e}`,{cwd:n});return t.trim().split(`
766
+ `).filter(Boolean).map(r=>{let[s,i,o,a]=r.split("|");return{hash:s,message:i,author:o,date:a,files:[]}})}catch{return[]}}function g_(n,e){return`Based on the following git diff, generate a concise, conventional commit message.
767
+
768
+ Rules:
769
+ - Use conventional commits format: type(scope): description
770
+ - Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore
771
+ - Keep the first line under 72 characters
772
+ - Add a body if the change is complex (separated by blank line)
773
+ - Be specific about what changed
774
+
775
+ Staged files: ${e.join(", ")}
776
+
777
+ Diff:
778
+ ${n}
779
+
780
+ Generate ONLY the commit message, nothing else.`}function y_(n,e,t){let r=n.map(s=>`- ${s.message}`).join(`
781
+ `);return`Generate a comprehensive Pull Request description.
782
+
783
+ Base branch: ${e}
784
+ Head branch: ${t}
785
+
786
+ Commits:
787
+ ${r}
788
+
789
+ Format:
790
+ ## Summary
791
+ (Brief overview of changes)
792
+
793
+ ## Changes
794
+ (Bullet list of specific changes)
795
+
796
+ ## Testing
797
+ (How to test these changes)
798
+
799
+ ## Notes
800
+ (Any additional context)
801
+
802
+ Generate ONLY the PR description in markdown.`}function b_(n,e){let t=n.map(r=>`- ${r.hash.substring(0,7)} ${r.message} (${r.author})`).join(`
803
+ `);return`Generate a changelog entry for version ${e} from these commits.
804
+
805
+ Commits:
806
+ ${t}
807
+
808
+ Format:
809
+ ## [${e}] - ${new Date().toISOString().split("T")[0]}
810
+
811
+ ### Added
812
+ - (new features)
813
+
814
+ ### Changed
815
+ - (changes to existing features)
816
+
817
+ ### Fixed
818
+ - (bug fixes)
819
+
820
+ ### Removed
821
+ - (removed features)
822
+
823
+ Only include sections that have entries. Generate ONLY the changelog markdown.`}function w_(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(`
824
+ `)}var Lf,Df,Gt,Er=M(()=>{"use strict";Lf=require("child_process"),Df=require("util"),Gt=(0,Df.promisify)(Lf.exec)});var Nf={};Ae(Nf,{formatScanResults:()=>$_,runSecurityScan:()=>k_});function S_(n,e){let t=[],r=e.split(`
825
+ `);for(let{pattern:s,name:i,severity:o}of v_){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let c=e.substring(0,a.index).split(`
826
+ `).length,u=r[c-1]||"";u.trim().startsWith("#")||u.trim().startsWith("//")||n.includes(".example")||n.includes(".sample")||t.push({severity:o,type:"secret",file:n,line:c,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return t}function A_(n,e){let t=[],r=e.split(`
827
+ `),s=Et.extname(n);return[".ts",".js",".tsx",".jsx"].includes(s)&&r.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 Ff(n,e=[]){try{let t=Cr.readdirSync(n,{withFileTypes:!0});for(let r of t){if(x_.has(r.name))continue;let s=Et.join(n,r.name);if(r.isDirectory())Ff(s,e);else if(r.isFile()){let i=Et.extname(r.name);__.has(i)||e.push(s)}}}catch{}return e}function k_(n){let e=Date.now(),t=Ff(n),r=[];for(let o of t)try{let a=Cr.readFileSync(o,"utf-8"),l=Et.relative(n,o),c=S_(l,a);r.push(...c);let u=A_(l,a);r.push(...u)}catch{}let s=Date.now()-e,i={critical:r.filter(o=>o.severity==="critical").length,high:r.filter(o=>o.severity==="high").length,medium:r.filter(o=>o.severity==="medium").length,low:r.filter(o=>o.severity==="low").length,info:r.filter(o=>o.severity==="info").length};return{issues:r,scannedFiles:t.length,duration:s,summary:i}}function $_(n){let e=[];if(e.push(`
828
+ 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((r,s)=>{let i={critical:0,high:1,medium:2,low:3,info:4};return i[r.severity]-i[s.severity]}).slice(0,10);for(let r of t){let s=r.severity==="critical"?"\u{1F534}":r.severity==="high"?"\u{1F7E0}":r.severity==="medium"?"\u{1F7E1}":"\u{1F535}";e.push(` ${s} [${r.severity.toUpperCase()}] ${r.message}`),e.push(` File: ${r.file}${r.line?`:${r.line}`:""}`),e.push(` Fix: ${r.suggestion}`),e.push("")}}return e.join(`
829
+ `)}var Cr,Et,v_,x_,__,jf=M(()=>{"use strict";Cr=C(require("fs")),Et=C(require("path")),v_=[{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"}],x_=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),__=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"])});var gn=L((oT,Kf)=>{"use strict";var E_=require("path"),ze="\\\\/",Hf=`[^${ze}]`,C_=0,it="\\.",T_="\\+",R_="\\?",Tr="\\/",O_="(?=.)",Bf="[^/]",So=`(?:${Tr}|$)`,qf=`(?:^|${Tr})`,Ao=`${it}{1,2}${So}`,P_=`(?!${it})`,M_=`(?!${qf}${Ao})`,I_=`(?!${it}{0,1}${So})`,L_=`(?!${Ao})`,D_=`[^.${Tr}]`,F_=`${Bf}*?`,Uf={DOT_LITERAL:it,PLUS_LITERAL:T_,QMARK_LITERAL:R_,SLASH_LITERAL:Tr,ONE_CHAR:O_,QMARK:Bf,END_ANCHOR:So,DOTS_SLASH:Ao,NO_DOT:P_,NO_DOTS:M_,NO_DOT_SLASH:I_,NO_DOTS_SLASH:L_,QMARK_NO_DOT:D_,STAR:F_,START_ANCHOR:qf},N_={...Uf,SLASH_LITERAL:`[${ze}]`,QMARK:Hf,STAR:`${Hf}*?`,DOTS_SLASH:`${it}{1,2}(?:[${ze}]|$)`,NO_DOT:`(?!${it})`,NO_DOTS:`(?!(?:^|[${ze}])${it}{1,2}(?:[${ze}]|$))`,NO_DOT_SLASH:`(?!${it}{0,1}(?:[${ze}]|$))`,NO_DOTS_SLASH:`(?!${it}{1,2}(?:[${ze}]|$))`,QMARK_NO_DOT:`[^.${ze}]`,START_ANCHOR:`(?:^|[${ze}])`,END_ANCHOR:`(?:[${ze}]|$)`},j_={__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"};Kf.exports={DEFAULT_MAX_EXTGLOB_RECURSION:C_,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:j_,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:E_.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?N_:Uf}}});var Rr=L(we=>{"use strict";var H_=require("path"),B_=process.platform==="win32",{REGEX_BACKSLASH:q_,REGEX_REMOVE_BACKSLASH:U_,REGEX_SPECIAL_CHARS:K_,REGEX_SPECIAL_CHARS_GLOBAL:W_}=gn();we.isObject=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);we.hasRegexChars=n=>K_.test(n);we.isRegexChar=n=>n.length===1&&we.hasRegexChars(n);we.escapeRegex=n=>n.replace(W_,"\\$1");we.toPosixSlashes=n=>n.replace(q_,"/");we.removeBackslashes=n=>n.replace(U_,e=>e==="\\"?"":e);we.supportsLookbehinds=()=>{let n=process.version.slice(1).split(".").map(Number);return n.length===3&&n[0]>=9||n[0]===8&&n[1]>=10};we.isWindows=n=>n&&typeof n.windows=="boolean"?n.windows:B_===!0||H_.sep==="\\";we.escapeLast=(n,e,t)=>{let r=n.lastIndexOf(e,t);return r===-1?n:n[r-1]==="\\"?we.escapeLast(n,e,r-1):`${n.slice(0,r)}\\${n.slice(r)}`};we.removePrefix=(n,e={})=>{let t=n;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};we.wrapOutput=(n,e={},t={})=>{let r=t.contains?"":"^",s=t.contains?"":"$",i=`${r}(?:${n})${s}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var Qf=L((lT,Xf)=>{"use strict";var Wf=Rr(),{CHAR_ASTERISK:ko,CHAR_AT:G_,CHAR_BACKWARD_SLASH:yn,CHAR_COMMA:V_,CHAR_DOT:$o,CHAR_EXCLAMATION_MARK:Eo,CHAR_FORWARD_SLASH:Jf,CHAR_LEFT_CURLY_BRACE:Co,CHAR_LEFT_PARENTHESES:To,CHAR_LEFT_SQUARE_BRACKET:z_,CHAR_PLUS:Y_,CHAR_QUESTION_MARK:Gf,CHAR_RIGHT_CURLY_BRACE:J_,CHAR_RIGHT_PARENTHESES:Vf,CHAR_RIGHT_SQUARE_BRACKET:X_}=gn(),zf=n=>n===Jf||n===yn,Yf=n=>{n.isPrefix!==!0&&(n.depth=n.isGlobstar?1/0:1)},Q_=(n,e)=>{let t=e||{},r=n.length-1,s=t.parts===!0||t.scanToEnd===!0,i=[],o=[],a=[],l=n,c=-1,u=0,d=0,p=!1,h=!1,f=!1,g=!1,y=!1,w=!1,v=!1,S=!1,k=!1,P=!1,j=0,I,$,E={value:"",depth:0,isGlob:!1},N=()=>c>=r,x=()=>l.charCodeAt(c+1),H=()=>(I=$,l.charCodeAt(++c));for(;c<r;){$=H();let z;if($===yn){v=E.backslashes=!0,$=H(),$===Co&&(w=!0);continue}if(w===!0||$===Co){for(j++;N()!==!0&&($=H());){if($===yn){v=E.backslashes=!0,H();continue}if($===Co){j++;continue}if(w!==!0&&$===$o&&($=H())===$o){if(p=E.isBrace=!0,f=E.isGlob=!0,P=!0,s===!0)continue;break}if(w!==!0&&$===V_){if(p=E.isBrace=!0,f=E.isGlob=!0,P=!0,s===!0)continue;break}if($===J_&&(j--,j===0)){w=!1,p=E.isBrace=!0,P=!0;break}}if(s===!0)continue;break}if($===Jf){if(i.push(c),o.push(E),E={value:"",depth:0,isGlob:!1},P===!0)continue;if(I===$o&&c===u+1){u+=2;continue}d=c+1;continue}if(t.noext!==!0&&($===Y_||$===G_||$===ko||$===Gf||$===Eo)===!0&&x()===To){if(f=E.isGlob=!0,g=E.isExtglob=!0,P=!0,$===Eo&&c===u&&(k=!0),s===!0){for(;N()!==!0&&($=H());){if($===yn){v=E.backslashes=!0,$=H();continue}if($===Vf){f=E.isGlob=!0,P=!0;break}}continue}break}if($===ko){if(I===ko&&(y=E.isGlobstar=!0),f=E.isGlob=!0,P=!0,s===!0)continue;break}if($===Gf){if(f=E.isGlob=!0,P=!0,s===!0)continue;break}if($===z_){for(;N()!==!0&&(z=H());){if(z===yn){v=E.backslashes=!0,H();continue}if(z===X_){h=E.isBracket=!0,f=E.isGlob=!0,P=!0;break}}if(s===!0)continue;break}if(t.nonegate!==!0&&$===Eo&&c===u){S=E.negated=!0,u++;continue}if(t.noparen!==!0&&$===To){if(f=E.isGlob=!0,s===!0){for(;N()!==!0&&($=H());){if($===To){v=E.backslashes=!0,$=H();continue}if($===Vf){P=!0;break}}continue}break}if(f===!0){if(P=!0,s===!0)continue;break}}t.noext===!0&&(g=!1,f=!1);let D=l,W="",_="";u>0&&(W=l.slice(0,u),l=l.slice(u),d-=u),D&&f===!0&&d>0?(D=l.slice(0,d),_=l.slice(d)):f===!0?(D="",_=l):D=l,D&&D!==""&&D!=="/"&&D!==l&&zf(D.charCodeAt(D.length-1))&&(D=D.slice(0,-1)),t.unescape===!0&&(_&&(_=Wf.removeBackslashes(_)),D&&v===!0&&(D=Wf.removeBackslashes(D)));let b={prefix:W,input:n,start:u,base:D,glob:_,isBrace:p,isBracket:h,isGlob:f,isExtglob:g,isGlobstar:y,negated:S,negatedExtglob:k};if(t.tokens===!0&&(b.maxDepth=0,zf($)||o.push(E),b.tokens=o),t.parts===!0||t.tokens===!0){let z;for(let V=0;V<i.length;V++){let ge=z?z+1:u,ye=i[V],Y=n.slice(ge,ye);t.tokens&&(V===0&&u!==0?(o[V].isPrefix=!0,o[V].value=W):o[V].value=Y,Yf(o[V]),b.maxDepth+=o[V].depth),(V!==0||Y!=="")&&a.push(Y),z=ye}if(z&&z+1<n.length){let V=n.slice(z+1);a.push(V),t.tokens&&(o[o.length-1].value=V,Yf(o[o.length-1]),b.maxDepth+=o[o.length-1].depth)}b.slashes=i,b.parts=a}return b};Xf.exports=Q_});var rp=L((cT,np)=>{"use strict";var bn=gn(),pe=Rr(),{MAX_LENGTH:Or,POSIX_REGEX_SOURCE:Z_,REGEX_NON_SPECIAL_CHARS:eS,REGEX_SPECIAL_CHARS_BACKREF:tS,REPLACEMENTS:Zf}=bn,nS=(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(s=>pe.escapeRegex(s)).join("..")}return t},Vt=(n,e)=>`Missing ${n}: "${e}" - use "\\\\${e}" to match literal characters`,ep=n=>{let e=[],t=0,r=0,s=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==='"'){s=s===1?0:1,i+=a;continue}if(s===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")r++;else if(a===")"&&r>0)r--;else if(a==="|"&&r===0){e.push(i),i="";continue}}}i+=a}return e.push(i),e},rS=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},tp=n=>{let e=n.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(rS(e))return e.replace(/\\(.)/g,"$1")},sS=n=>{let e=n.map(tp).filter(Boolean);for(let t=0;t<e.length;t++)for(let r=t+1;r<e.length;r++){let s=e[t],i=e[r],o=s[0];if(!(!o||s!==o.repeat(s.length)||i!==o.repeat(i.length))&&(s===i||s.startsWith(i)||i.startsWith(s)))return!0}return!1},Ro=(n,e=!0)=>{if(n[0]!=="+"&&n[0]!=="*"||n[1]!=="(")return;let t=0,r=0,s=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==='"'){s=s===1?0:1;continue}if(s!==1){if(a==="["){t++;continue}if(a==="]"&&t>0){t--;continue}if(!(t>0)){if(a==="("){r++;continue}if(a===")"&&(r--,r===0))return e===!0&&o!==n.length-1?void 0:{type:n[0],body:n.slice(2,o),end:o}}}}},iS=n=>{let e=0,t=[];for(;e<n.length;){let s=Ro(n.slice(e),!1);if(!s||s.type!=="*")return;let i=ep(s.body).map(a=>a.trim());if(i.length!==1)return;let o=tp(i[0]);if(!o||o.length!==1)return;t.push(o),e+=s.end+1}return t.length<1?void 0:`${t.length===1?pe.escapeRegex(t[0]):`[${t.map(s=>pe.escapeRegex(s)).join("")}]`}*`},oS=n=>{let e=0,t=n.trim(),r=Ro(t);for(;r;)e++,t=r.body.trim(),r=Ro(t);return e},aS=(n,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:bn.DEFAULT_MAX_EXTGLOB_RECURSION,r=ep(n).map(s=>s.trim());if(r.length>1&&(r.some(s=>s==="")||r.some(s=>/^[*?]+$/.test(s))||sS(r)))return{risky:!0};for(let s of r){let i=iS(s);if(i)return{risky:!0,safeOutput:i};if(oS(s)>t)return{risky:!0}}return{risky:!1}},Oo=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a string");n=Zf[n]||n;let t={...e},r=typeof t.maxLength=="number"?Math.min(Or,t.maxLength):Or,s=n.length;if(s>r)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${r}`);let i={type:"bos",value:"",output:t.prepend||""},o=[i],a=t.capture?"":"?:",l=pe.isWindows(e),c=bn.globChars(l),u=bn.extglobChars(c),{DOT_LITERAL:d,PLUS_LITERAL:p,SLASH_LITERAL:h,ONE_CHAR:f,DOTS_SLASH:g,NO_DOT:y,NO_DOT_SLASH:w,NO_DOTS_SLASH:v,QMARK:S,QMARK_NO_DOT:k,STAR:P,START_ANCHOR:j}=c,I=O=>`(${a}(?:(?!${j}${O.dot?g:d}).)*?)`,$=t.dot?"":y,E=t.dot?S:k,N=t.bash===!0?I(t):P;t.capture&&(N=`(${N})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let x={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=pe.removePrefix(n,x),s=n.length;let H=[],D=[],W=[],_=i,b,z=()=>x.index===s-1,V=x.peek=(O=1)=>n[x.index+O],ge=x.advance=()=>n[++x.index]||"",ye=()=>n.slice(x.index+1),Y=(O="",re=0)=>{x.consumed+=O,x.index+=re},Me=O=>{x.output+=O.output!=null?O.output:O.value,Y(O.value)},ct=()=>{let O=1;for(;V()==="!"&&(V(2)!=="("||V(3)==="?");)ge(),x.start++,O++;return O%2===0?!1:(x.negated=!0,x.start++,!0)},Ie=O=>{x[O]++,W.push(O)},he=O=>{x[O]--,W.pop()},G=O=>{if(_.type==="globstar"){let re=x.braces>0&&(O.type==="comma"||O.type==="brace"),R=O.extglob===!0||H.length&&(O.type==="pipe"||O.type==="paren");O.type!=="slash"&&O.type!=="paren"&&!re&&!R&&(x.output=x.output.slice(0,-_.output.length),_.type="star",_.value="*",_.output=N,x.output+=_.output)}if(H.length&&O.type!=="paren"&&(H[H.length-1].inner+=O.value),(O.value||O.output)&&Me(O),_&&_.type==="text"&&O.type==="text"){_.value+=O.value,_.output=(_.output||"")+O.value;return}O.prev=_,o.push(O),_=O},Tn=(O,re)=>{let R={...u[re],conditions:1,inner:""};R.prev=_,R.parens=x.parens,R.output=x.output,R.startIndex=x.index,R.tokensIndex=o.length;let K=(t.capture?"(":"")+R.open;Ie("parens"),G({type:O,value:re,output:x.output?"":f}),G({type:"paren",extglob:!0,value:ge(),output:K}),H.push(R)},wm=O=>{let re=n.slice(O.startIndex,x.index+1),R=n.slice(O.startIndex+2,x.index),K=aS(R,t);if((O.type==="plus"||O.type==="star")&&K.risky){let Q=K.safeOutput?(O.output?"":f)+(t.capture?`(${K.safeOutput})`:K.safeOutput):void 0,qe=o[O.tokensIndex];qe.type="text",qe.value=re,qe.output=Q||pe.escapeRegex(re);for(let Ue=O.tokensIndex+1;Ue<o.length;Ue++)o[Ue].value="",o[Ue].output="",delete o[Ue].suffix;x.output=O.output+qe.output,x.backtrack=!0,G({type:"paren",extglob:!0,value:b,output:""}),he("parens");return}let ee=O.close+(t.capture?")":""),ce;if(O.type==="negate"){let Q=N;if(O.inner&&O.inner.length>1&&O.inner.includes("/")&&(Q=I(t)),(Q!==N||z()||/^\)+$/.test(ye()))&&(ee=O.close=`)$))${Q}`),O.inner.includes("*")&&(ce=ye())&&/^\.[^\\/.]+$/.test(ce)){let qe=Oo(ce,{...e,fastpaths:!1}).output;ee=O.close=`)${qe})${Q})`}O.prev.type==="bos"&&(x.negatedExtglob=!0)}G({type:"paren",extglob:!0,value:b,output:ee}),he("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(n)){let O=!1,re=n.replace(tS,(R,K,ee,ce,Q,qe)=>ce==="\\"?(O=!0,R):ce==="?"?K?K+ce+(Q?S.repeat(Q.length):""):qe===0?E+(Q?S.repeat(Q.length):""):S.repeat(ee.length):ce==="."?d.repeat(ee.length):ce==="*"?K?K+ce+(Q?N:""):N:K?R:`\\${R}`);return O===!0&&(t.unescape===!0?re=re.replace(/\\/g,""):re=re.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),re===n&&t.contains===!0?(x.output=n,x):(x.output=pe.wrapOutput(re,x,e),x)}for(;!z();){if(b=ge(),b==="\0")continue;if(b==="\\"){let R=V();if(R==="/"&&t.bash!==!0||R==="."||R===";")continue;if(!R){b+="\\",G({type:"text",value:b});continue}let K=/^\\+/.exec(ye()),ee=0;if(K&&K[0].length>2&&(ee=K[0].length,x.index+=ee,ee%2!==0&&(b+="\\")),t.unescape===!0?b=ge():b+=ge(),x.brackets===0){G({type:"text",value:b});continue}}if(x.brackets>0&&(b!=="]"||_.value==="["||_.value==="[^")){if(t.posix!==!1&&b===":"){let R=_.value.slice(1);if(R.includes("[")&&(_.posix=!0,R.includes(":"))){let K=_.value.lastIndexOf("["),ee=_.value.slice(0,K),ce=_.value.slice(K+2),Q=Z_[ce];if(Q){_.value=ee+Q,x.backtrack=!0,ge(),!i.output&&o.indexOf(_)===1&&(i.output=f);continue}}}(b==="["&&V()!==":"||b==="-"&&V()==="]")&&(b=`\\${b}`),b==="]"&&(_.value==="["||_.value==="[^")&&(b=`\\${b}`),t.posix===!0&&b==="!"&&_.value==="["&&(b="^"),_.value+=b,Me({value:b});continue}if(x.quotes===1&&b!=='"'){b=pe.escapeRegex(b),_.value+=b,Me({value:b});continue}if(b==='"'){x.quotes=x.quotes===1?0:1,t.keepQuotes===!0&&G({type:"text",value:b});continue}if(b==="("){Ie("parens"),G({type:"paren",value:b});continue}if(b===")"){if(x.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Vt("opening","("));let R=H[H.length-1];if(R&&x.parens===R.parens+1){wm(H.pop());continue}G({type:"paren",value:b,output:x.parens?")":"\\)"}),he("parens");continue}if(b==="["){if(t.nobracket===!0||!ye().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Vt("closing","]"));b=`\\${b}`}else Ie("brackets");G({type:"bracket",value:b});continue}if(b==="]"){if(t.nobracket===!0||_&&_.type==="bracket"&&_.value.length===1){G({type:"text",value:b,output:`\\${b}`});continue}if(x.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Vt("opening","["));G({type:"text",value:b,output:`\\${b}`});continue}he("brackets");let R=_.value.slice(1);if(_.posix!==!0&&R[0]==="^"&&!R.includes("/")&&(b=`/${b}`),_.value+=b,Me({value:b}),t.literalBrackets===!1||pe.hasRegexChars(R))continue;let K=pe.escapeRegex(_.value);if(x.output=x.output.slice(0,-_.value.length),t.literalBrackets===!0){x.output+=K,_.value=K;continue}_.value=`(${a}${K}|${_.value})`,x.output+=_.value;continue}if(b==="{"&&t.nobrace!==!0){Ie("braces");let R={type:"brace",value:b,output:"(",outputIndex:x.output.length,tokensIndex:x.tokens.length};D.push(R),G(R);continue}if(b==="}"){let R=D[D.length-1];if(t.nobrace===!0||!R){G({type:"text",value:b,output:b});continue}let K=")";if(R.dots===!0){let ee=o.slice(),ce=[];for(let Q=ee.length-1;Q>=0&&(o.pop(),ee[Q].type!=="brace");Q--)ee[Q].type!=="dots"&&ce.unshift(ee[Q].value);K=nS(ce,t),x.backtrack=!0}if(R.comma!==!0&&R.dots!==!0){let ee=x.output.slice(0,R.outputIndex),ce=x.tokens.slice(R.tokensIndex);R.value=R.output="\\{",b=K="\\}",x.output=ee;for(let Q of ce)x.output+=Q.output||Q.value}G({type:"brace",value:b,output:K}),he("braces"),D.pop();continue}if(b==="|"){H.length>0&&H[H.length-1].conditions++,G({type:"text",value:b});continue}if(b===","){let R=b,K=D[D.length-1];K&&W[W.length-1]==="braces"&&(K.comma=!0,R="|"),G({type:"comma",value:b,output:R});continue}if(b==="/"){if(_.type==="dot"&&x.index===x.start+1){x.start=x.index+1,x.consumed="",x.output="",o.pop(),_=i;continue}G({type:"slash",value:b,output:h});continue}if(b==="."){if(x.braces>0&&_.type==="dot"){_.value==="."&&(_.output=d);let R=D[D.length-1];_.type="dots",_.output+=b,_.value+=b,R.dots=!0;continue}if(x.braces+x.parens===0&&_.type!=="bos"&&_.type!=="slash"){G({type:"text",value:b,output:d});continue}G({type:"dot",value:b,output:d});continue}if(b==="?"){if(!(_&&_.value==="(")&&t.noextglob!==!0&&V()==="("&&V(2)!=="?"){Tn("qmark",b);continue}if(_&&_.type==="paren"){let K=V(),ee=b;if(K==="<"&&!pe.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(_.value==="("&&!/[!=<:]/.test(K)||K==="<"&&!/<([!=]|\w+>)/.test(ye()))&&(ee=`\\${b}`),G({type:"text",value:b,output:ee});continue}if(t.dot!==!0&&(_.type==="slash"||_.type==="bos")){G({type:"qmark",value:b,output:k});continue}G({type:"qmark",value:b,output:S});continue}if(b==="!"){if(t.noextglob!==!0&&V()==="("&&(V(2)!=="?"||!/[!=<:]/.test(V(3)))){Tn("negate",b);continue}if(t.nonegate!==!0&&x.index===0){ct();continue}}if(b==="+"){if(t.noextglob!==!0&&V()==="("&&V(2)!=="?"){Tn("plus",b);continue}if(_&&_.value==="("||t.regex===!1){G({type:"plus",value:b,output:p});continue}if(_&&(_.type==="bracket"||_.type==="paren"||_.type==="brace")||x.parens>0){G({type:"plus",value:b});continue}G({type:"plus",value:p});continue}if(b==="@"){if(t.noextglob!==!0&&V()==="("&&V(2)!=="?"){G({type:"at",extglob:!0,value:b,output:""});continue}G({type:"text",value:b});continue}if(b!=="*"){(b==="$"||b==="^")&&(b=`\\${b}`);let R=eS.exec(ye());R&&(b+=R[0],x.index+=R[0].length),G({type:"text",value:b});continue}if(_&&(_.type==="globstar"||_.star===!0)){_.type="star",_.star=!0,_.value+=b,_.output=N,x.backtrack=!0,x.globstar=!0,Y(b);continue}let O=ye();if(t.noextglob!==!0&&/^\([^?]/.test(O)){Tn("star",b);continue}if(_.type==="star"){if(t.noglobstar===!0){Y(b);continue}let R=_.prev,K=R.prev,ee=R.type==="slash"||R.type==="bos",ce=K&&(K.type==="star"||K.type==="globstar");if(t.bash===!0&&(!ee||O[0]&&O[0]!=="/")){G({type:"star",value:b,output:""});continue}let Q=x.braces>0&&(R.type==="comma"||R.type==="brace"),qe=H.length&&(R.type==="pipe"||R.type==="paren");if(!ee&&R.type!=="paren"&&!Q&&!qe){G({type:"star",value:b,output:""});continue}for(;O.slice(0,3)==="/**";){let Ue=n[x.index+4];if(Ue&&Ue!=="/")break;O=O.slice(3),Y("/**",3)}if(R.type==="bos"&&z()){_.type="globstar",_.value+=b,_.output=I(t),x.output=_.output,x.globstar=!0,Y(b);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!ce&&z()){x.output=x.output.slice(0,-(R.output+_.output).length),R.output=`(?:${R.output}`,_.type="globstar",_.output=I(t)+(t.strictSlashes?")":"|$)"),_.value+=b,x.globstar=!0,x.output+=R.output+_.output,Y(b);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&O[0]==="/"){let Ue=O[1]!==void 0?"|$":"";x.output=x.output.slice(0,-(R.output+_.output).length),R.output=`(?:${R.output}`,_.type="globstar",_.output=`${I(t)}${h}|${h}${Ue})`,_.value+=b,x.output+=R.output+_.output,x.globstar=!0,Y(b+ge()),G({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&O[0]==="/"){_.type="globstar",_.value+=b,_.output=`(?:^|${h}|${I(t)}${h})`,x.output=_.output,x.globstar=!0,Y(b+ge()),G({type:"slash",value:"/",output:""});continue}x.output=x.output.slice(0,-_.output.length),_.type="globstar",_.output=I(t),_.value+=b,x.output+=_.output,x.globstar=!0,Y(b);continue}let re={type:"star",value:b,output:N};if(t.bash===!0){re.output=".*?",(_.type==="bos"||_.type==="slash")&&(re.output=$+re.output),G(re);continue}if(_&&(_.type==="bracket"||_.type==="paren")&&t.regex===!0){re.output=b,G(re);continue}(x.index===x.start||_.type==="slash"||_.type==="dot")&&(_.type==="dot"?(x.output+=w,_.output+=w):t.dot===!0?(x.output+=v,_.output+=v):(x.output+=$,_.output+=$),V()!=="*"&&(x.output+=f,_.output+=f)),G(re)}for(;x.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Vt("closing","]"));x.output=pe.escapeLast(x.output,"["),he("brackets")}for(;x.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Vt("closing",")"));x.output=pe.escapeLast(x.output,"("),he("parens")}for(;x.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Vt("closing","}"));x.output=pe.escapeLast(x.output,"{"),he("braces")}if(t.strictSlashes!==!0&&(_.type==="star"||_.type==="bracket")&&G({type:"maybe_slash",value:"",output:`${h}?`}),x.backtrack===!0){x.output="";for(let O of x.tokens)x.output+=O.output!=null?O.output:O.value,O.suffix&&(x.output+=O.suffix)}return x};Oo.fastpaths=(n,e)=>{let t={...e},r=typeof t.maxLength=="number"?Math.min(Or,t.maxLength):Or,s=n.length;if(s>r)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${r}`);n=Zf[n]||n;let i=pe.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:l,DOTS_SLASH:c,NO_DOT:u,NO_DOTS:d,NO_DOTS_SLASH:p,STAR:h,START_ANCHOR:f}=bn.globChars(i),g=t.dot?d:u,y=t.dot?p:u,w=t.capture?"":"?:",v={negated:!1,prefix:""},S=t.bash===!0?".*?":h;t.capture&&(S=`(${S})`);let k=$=>$.noglobstar===!0?S:`(${w}(?:(?!${f}${$.dot?c:o}).)*?)`,P=$=>{switch($){case"*":return`${g}${l}${S}`;case".*":return`${o}${l}${S}`;case"*.*":return`${g}${S}${o}${l}${S}`;case"*/*":return`${g}${S}${a}${l}${y}${S}`;case"**":return g+k(t);case"**/*":return`(?:${g}${k(t)}${a})?${y}${l}${S}`;case"**/*.*":return`(?:${g}${k(t)}${a})?${y}${S}${o}${l}${S}`;case"**/.*":return`(?:${g}${k(t)}${a})?${o}${l}${S}`;default:{let E=/^(.*?)\.(\w+)$/.exec($);if(!E)return;let N=P(E[1]);return N?N+o+E[2]:void 0}}},j=pe.removePrefix(n,v),I=P(j);return I&&t.strictSlashes!==!0&&(I+=`${a}?`),I};np.exports=Oo});var ip=L((uT,sp)=>{"use strict";var lS=require("path"),cS=Qf(),Po=rp(),Mo=Rr(),uS=gn(),dS=n=>n&&typeof n=="object"&&!Array.isArray(n),oe=(n,e,t=!1)=>{if(Array.isArray(n)){let u=n.map(p=>oe(p,e,t));return p=>{for(let h of u){let f=h(p);if(f)return f}return!1}}let r=dS(n)&&n.tokens&&n.input;if(n===""||typeof n!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let s=e||{},i=Mo.isWindows(e),o=r?oe.compileRe(n,e):oe.makeRe(n,e,!1,!0),a=o.state;delete o.state;let l=()=>!1;if(s.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};l=oe(s.ignore,u,t)}let c=(u,d=!1)=>{let{isMatch:p,match:h,output:f}=oe.test(u,o,e,{glob:n,posix:i}),g={glob:n,state:a,regex:o,posix:i,input:u,output:f,match:h,isMatch:p};return typeof s.onResult=="function"&&s.onResult(g),p===!1?(g.isMatch=!1,d?g:!1):l(u)?(typeof s.onIgnore=="function"&&s.onIgnore(g),g.isMatch=!1,d?g:!1):(typeof s.onMatch=="function"&&s.onMatch(g),d?g:!0)};return t&&(c.state=a),c};oe.test=(n,e,t,{glob:r,posix:s}={})=>{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||(s?Mo.toPosixSlashes:null),a=n===r,l=a&&o?o(n):n;return a===!1&&(l=o?o(n):n,a=l===r),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=oe.matchBase(n,e,t,s):a=e.exec(l)),{isMatch:!!a,match:a,output:l}};oe.matchBase=(n,e,t,r=Mo.isWindows(t))=>(e instanceof RegExp?e:oe.makeRe(e,t)).test(lS.basename(n));oe.isMatch=(n,e,t)=>oe(e,t)(n);oe.parse=(n,e)=>Array.isArray(n)?n.map(t=>oe.parse(t,e)):Po(n,{...e,fastpaths:!1});oe.scan=(n,e)=>cS(n,e);oe.compileRe=(n,e,t=!1,r=!1)=>{if(t===!0)return n.output;let s=e||{},i=s.contains?"":"^",o=s.contains?"":"$",a=`${i}(?:${n.output})${o}`;n&&n.negated===!0&&(a=`^(?!${a}).*$`);let l=oe.toRegex(a,e);return r===!0&&(l.state=n),l};oe.makeRe=(n,e={},t=!1,r=!1)=>{if(!n||typeof n!="string")throw new TypeError("Expected a non-empty string");let s={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(n[0]==="."||n[0]==="*")&&(s.output=Po.fastpaths(n,e)),s.output||(s=Po(n,e)),oe.compileRe(s,e,t,r)};oe.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/$^/}};oe.constants=uS;sp.exports=oe});var Io=L((dT,op)=>{"use strict";op.exports=ip()});var hp=L((fT,pp)=>{"use strict";var vn=require("fs"),{Readable:fS}=require("stream"),wn=require("path"),{promisify:Lr}=require("util"),Lo=Io(),pS=Lr(vn.readdir),hS=Lr(vn.stat),ap=Lr(vn.lstat),mS=Lr(vn.realpath),gS="!",dp="READDIRP_RECURSIVE_ERROR",yS=new Set(["ENOENT","EPERM","EACCES","ELOOP",dp]),Do="files",fp="directories",Mr="files_directories",Pr="all",lp=[Do,fp,Mr,Pr],bS=n=>yS.has(n.code),[cp,wS]=process.versions.node.split(".").slice(0,2).map(n=>Number.parseInt(n,10)),vS=process.platform==="win32"&&(cp>10||cp===10&&wS>=5),up=n=>{if(n!==void 0){if(typeof n=="function")return n;if(typeof n=="string"){let e=Lo(n.trim());return t=>e(t.basename)}if(Array.isArray(n)){let e=[],t=[];for(let r of n){let s=r.trim();s.charAt(0)===gS?t.push(Lo(s.slice(1))):e.push(Lo(s))}return t.length>0?e.length>0?r=>e.some(s=>s(r.basename))&&!t.some(s=>s(r.basename)):r=>!t.some(s=>s(r.basename)):r=>e.some(s=>s(r.basename))}}},Ir=class n extends fS{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:Do,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let t={...n.defaultOptions,...e},{root:r,type:s}=t;this._fileFilter=up(t.fileFilter),this._directoryFilter=up(t.directoryFilter);let i=t.lstat?ap:hS;vS?this._stat=o=>i(o,{bigint:!0}):this._stat=i,this._maxDepth=t.depth,this._wantsDir=[fp,Mr,Pr].includes(s),this._wantsFile=[Do,Mr,Pr].includes(s),this._wantsEverything=s===Pr,this._root=wn.resolve(r),this._isDirent="Dirent"in vn&&!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(r,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:r,files:s=[]}=this.parent||{};if(s.length>0){let i=s.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)?(r<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,r+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 r;try{r=await pS(e,this._rdOptions)}catch(s){this._onError(s)}return{files:r,depth:t,path:e}}async _formatEntry(e,t){let r;try{let s=this._isDirent?e.name:e,i=wn.resolve(wn.join(t,s));r={path:wn.relative(this._root,i),fullPath:i,basename:s},r[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(s){this._onError(s)}return r}_onError(e){bS(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 r=e.fullPath;try{let s=await mS(r),i=await ap(s);if(i.isFile())return"file";if(i.isDirectory()){let o=s.length;if(r.startsWith(s)&&r.substr(o,1)===wn.sep){let a=new Error(`Circular symlink detected: "${r}" points to "${s}"`);return a.code=dp,this._onError(a)}return"directory"}}catch(s){this._onError(s)}}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}},zt=(n,e={})=>{let t=e.entryType||e.type;if(t==="both"&&(t=Mr),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&&!lp.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${lp.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=n,new Ir(e)},xS=(n,e={})=>new Promise((t,r)=>{let s=[];zt(n,e).on("data",i=>s.push(i)).on("end",()=>t(s)).on("error",i=>r(i))});zt.promise=xS;zt.ReaddirpStream=Ir;zt.default=zt;pp.exports=zt});var Fo=L((pT,mp)=>{mp.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 r="";if(t>4&&n[3]==="\\"){var s=n[2];(s==="?"||s===".")&&n.slice(0,2)==="\\\\"&&(n=n.slice(2),r="//")}var i=n.split(/[/\\]+/);return e!==!1&&i[i.length-1]===""&&i.pop(),r+i.join("/")}});var xp=L((wp,vp)=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});var bp=Io(),_S=Fo(),gp="!",SS={returnIndex:!1},AS=n=>Array.isArray(n)?n:[n],kS=(n,e)=>{if(typeof n=="function")return n;if(typeof n=="string"){let t=bp(n,e);return r=>n===r||t(r)}return n instanceof RegExp?t=>n.test(t):t=>!1},yp=(n,e,t,r)=>{let s=Array.isArray(t),i=s?t[0]:t;if(!s&&typeof i!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(i));let o=_S(i,!1);for(let l=0;l<e.length;l++){let c=e[l];if(c(o))return r?-1:!1}let a=s&&[o].concat(t.slice(1));for(let l=0;l<n.length;l++){let c=n[l];if(s?c(...a):c(o))return r?l:!0}return r?-1:!1},No=(n,e,t=SS)=>{if(n==null)throw new TypeError("anymatch: specify first argument");let r=typeof t=="boolean"?{returnIndex:t}:t,s=r.returnIndex||!1,i=AS(n),o=i.filter(l=>typeof l=="string"&&l.charAt(0)===gp).map(l=>l.slice(1)).map(l=>bp(l,r)),a=i.filter(l=>typeof l!="string"||typeof l=="string"&&l.charAt(0)!==gp).map(l=>kS(l,r));return e==null?(l,c=!1)=>yp(a,o,l,typeof c=="boolean"?c:!1):yp(a,o,e,s)};No.default=No;vp.exports=No});var Sp=L((hT,_p)=>{_p.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 jo=L((mT,kp)=>{var $S=Sp(),Ap={"{":"}","(":")","[":"]"},ES=function(n){if(n[0]==="!")return!0;for(var e=0,t=-2,r=-2,s=-2,i=-2,o=-2;e<n.length;){if(n[e]==="*"||n[e+1]==="?"&&/[\].+)]/.test(n[e])||r!==-1&&n[e]==="["&&n[e+1]!=="]"&&(r<e&&(r=n.indexOf("]",e)),r>e&&(o===-1||o>r||(o=n.indexOf("\\",e),o===-1||o>r)))||s!==-1&&n[e]==="{"&&n[e+1]!=="}"&&(s=n.indexOf("}",e),s>e&&(o=n.indexOf("\\",e),o===-1||o>s))||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=Ap[a];if(l){var c=n.indexOf(l,e);c!==-1&&(e=c+1)}if(n[e]==="!")return!0}else e++}return!1},CS=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 r=Ap[t];if(r){var s=n.indexOf(r,e);s!==-1&&(e=s+1)}if(n[e]==="!")return!0}else e++}return!1};kp.exports=function(e,t){if(typeof e!="string"||e==="")return!1;if($S(e))return!0;var r=ES;return t&&t.strict===!1&&(r=CS),r(e)}});var Ep=L((gT,$p)=>{"use strict";var TS=jo(),RS=require("path").posix.dirname,OS=require("os").platform()==="win32",Ho="/",PS=/\\/g,MS=/[\{\[].*[\}\]]$/,IS=/(^|[^\\])([\{\[]|\([^\)]+$)/,LS=/\\([\!\*\?\|\[\]\(\)\{\}])/g;$p.exports=function(e,t){var r=Object.assign({flipBackslashes:!0},t);r.flipBackslashes&&OS&&e.indexOf(Ho)<0&&(e=e.replace(PS,Ho)),MS.test(e)&&(e+=Ho),e+="a";do e=RS(e);while(TS(e)||IS.test(e));return e.replace(LS,"$1")}});var Dr=L(Oe=>{"use strict";Oe.isInteger=n=>typeof n=="number"?Number.isInteger(n):typeof n=="string"&&n.trim()!==""?Number.isInteger(Number(n)):!1;Oe.find=(n,e)=>n.nodes.find(t=>t.type===e);Oe.exceedsLimit=(n,e,t=1,r)=>r===!1||!Oe.isInteger(n)||!Oe.isInteger(e)?!1:(Number(e)-Number(n))/Number(t)>=r;Oe.escapeNode=(n,e=0,t)=>{let r=n.nodes[e];r&&(t&&r.type===t||r.type==="open"||r.type==="close")&&r.escaped!==!0&&(r.value="\\"+r.value,r.escaped=!0)};Oe.encloseBrace=n=>n.type!=="brace"?!1:n.commas>>0+n.ranges>>0===0?(n.invalid=!0,!0):!1;Oe.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;Oe.isOpenOrClose=n=>n.type==="open"||n.type==="close"?!0:n.open===!0||n.close===!0;Oe.reduce=n=>n.reduce((e,t)=>(t.type==="text"&&e.push(t.value),t.type==="range"&&(t.type="text"),e),[]);Oe.flatten=(...n)=>{let e=[],t=r=>{for(let s=0;s<r.length;s++){let i=r[s];if(Array.isArray(i)){t(i);continue}i!==void 0&&e.push(i)}return e};return t(n),e}});var Fr=L((bT,Tp)=>{"use strict";var Cp=Dr();Tp.exports=(n,e={})=>{let t=(r,s={})=>{let i=e.escapeInvalid&&Cp.isInvalidBrace(s),o=r.invalid===!0&&e.escapeInvalid===!0,a="";if(r.value)return(i||o)&&Cp.isOpenOrClose(r)?"\\"+r.value:r.value;if(r.value)return r.value;if(r.nodes)for(let l of r.nodes)a+=t(l);return a};return t(n)}});var Op=L((wT,Rp)=>{"use strict";Rp.exports=function(n){return typeof n=="number"?n-n===0:typeof n=="string"&&n.trim()!==""?Number.isFinite?Number.isFinite(+n):isFinite(+n):!1}});var Hp=L((vT,jp)=>{"use strict";var Pp=Op(),Ct=(n,e,t)=>{if(Pp(n)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||n===e)return String(n);if(Pp(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let r={relaxZeros:!0,...t};typeof r.strictZeros=="boolean"&&(r.relaxZeros=r.strictZeros===!1);let s=String(r.relaxZeros),i=String(r.shorthand),o=String(r.capture),a=String(r.wrap),l=n+":"+e+"="+s+i+o+a;if(Ct.cache.hasOwnProperty(l))return Ct.cache[l].result;let c=Math.min(n,e),u=Math.max(n,e);if(Math.abs(c-u)===1){let g=n+"|"+e;return r.capture?`(${g})`:r.wrap===!1?g:`(?:${g})`}let d=Np(n)||Np(e),p={min:n,max:e,a:c,b:u},h=[],f=[];if(d&&(p.isPadded=d,p.maxLen=String(p.max).length),c<0){let g=u<0?Math.abs(u):1;f=Mp(g,Math.abs(c),p,r),c=p.a=0}return u>=0&&(h=Mp(c,u,p,r)),p.negatives=f,p.positives=h,p.result=DS(f,h,r),r.capture===!0?p.result=`(${p.result})`:r.wrap!==!1&&h.length+f.length>1&&(p.result=`(?:${p.result})`),Ct.cache[l]=p,p.result};function DS(n,e,t){let r=Bo(n,e,"-",!1,t)||[],s=Bo(e,n,"",!1,t)||[],i=Bo(n,e,"-?",!0,t)||[];return r.concat(i).concat(s).join("|")}function FS(n,e){let t=1,r=1,s=Lp(n,t),i=new Set([e]);for(;n<=s&&s<=e;)i.add(s),t+=1,s=Lp(n,t);for(s=Dp(e+1,r)-1;n<s&&s<=e;)i.add(s),r+=1,s=Dp(e+1,r)-1;return i=[...i],i.sort(HS),i}function NS(n,e,t){if(n===e)return{pattern:n,count:[],digits:0};let r=jS(n,e),s=r.length,i="",o=0;for(let a=0;a<s;a++){let[l,c]=r[a];l===c?i+=l:l!=="0"||c!=="9"?i+=BS(l,c,t):o++}return o&&(i+=t.shorthand===!0?"\\d":"[0-9]"),{pattern:i,count:[o],digits:s}}function Mp(n,e,t,r){let s=FS(n,e),i=[],o=n,a;for(let l=0;l<s.length;l++){let c=s[l],u=NS(String(o),String(c),r),d="";if(!t.isPadded&&a&&a.pattern===u.pattern){a.count.length>1&&a.count.pop(),a.count.push(u.count[0]),a.string=a.pattern+Fp(a.count),o=c+1;continue}t.isPadded&&(d=qS(c,t,r)),u.string=d+u.pattern+Fp(u.count),i.push(u),o=c+1,a=u}return i}function Bo(n,e,t,r,s){let i=[];for(let o of n){let{string:a}=o;!r&&!Ip(e,"string",a)&&i.push(t+a),r&&Ip(e,"string",a)&&i.push(t+a)}return i}function jS(n,e){let t=[];for(let r=0;r<n.length;r++)t.push([n[r],e[r]]);return t}function HS(n,e){return n>e?1:e>n?-1:0}function Ip(n,e,t){return n.some(r=>r[e]===t)}function Lp(n,e){return Number(String(n).slice(0,-e)+"9".repeat(e))}function Dp(n,e){return n-n%Math.pow(10,e)}function Fp(n){let[e=0,t=""]=n;return t||e>1?`{${e+(t?","+t:"")}}`:""}function BS(n,e,t){return`[${n}${e-n===1?"":"-"}${e}]`}function Np(n){return/^-?(0+)\d/.test(n)}function qS(n,e,t){if(!e.isPadded)return n;let r=Math.abs(e.maxLen-String(n).length),s=t.relaxZeros!==!1;switch(r){case 0:return"";case 1:return s?"0?":"0";case 2:return s?"0{0,2}":"00";default:return s?`0{0,${r}}`:`0{${r}}`}}Ct.cache={};Ct.clearCache=()=>Ct.cache={};jp.exports=Ct});var Ko=L((xT,Vp)=>{"use strict";var US=require("util"),qp=Hp(),Bp=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),KS=n=>e=>n===!0?Number(e):String(e),qo=n=>typeof n=="number"||typeof n=="string"&&n!=="",xn=n=>Number.isInteger(+n),Uo=n=>{let e=`${n}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},WS=(n,e,t)=>typeof n=="string"||typeof e=="string"?!0:t.stringify===!0,GS=(n,e,t)=>{if(e>0){let r=n[0]==="-"?"-":"";r&&(n=n.slice(1)),n=r+n.padStart(r?e-1:e,"0")}return t===!1?String(n):n},jr=(n,e)=>{let t=n[0]==="-"?"-":"";for(t&&(n=n.slice(1),e--);n.length<e;)n="0"+n;return t?"-"+n:n},VS=(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 r=e.capture?"":"?:",s="",i="",o;return n.positives.length&&(s=n.positives.map(a=>jr(String(a),t)).join("|")),n.negatives.length&&(i=`-(${r}${n.negatives.map(a=>jr(String(a),t)).join("|")})`),s&&i?o=`${s}|${i}`:o=s||i,e.wrap?`(${r}${o})`:o},Up=(n,e,t,r)=>{if(t)return qp(n,e,{wrap:!1,...r});let s=String.fromCharCode(n);if(n===e)return s;let i=String.fromCharCode(e);return`[${s}-${i}]`},Kp=(n,e,t)=>{if(Array.isArray(n)){let r=t.wrap===!0,s=t.capture?"":"?:";return r?`(${s}${n.join("|")})`:n.join("|")}return qp(n,e,t)},Wp=(...n)=>new RangeError("Invalid range arguments: "+US.inspect(...n)),Gp=(n,e,t)=>{if(t.strictRanges===!0)throw Wp([n,e]);return[]},zS=(n,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${n}" to be a number`);return[]},YS=(n,e,t=1,r={})=>{let s=Number(n),i=Number(e);if(!Number.isInteger(s)||!Number.isInteger(i)){if(r.strictRanges===!0)throw Wp([n,e]);return[]}s===0&&(s=0),i===0&&(i=0);let o=s>i,a=String(n),l=String(e),c=String(t);t=Math.max(Math.abs(t),1);let u=Uo(a)||Uo(l)||Uo(c),d=u?Math.max(a.length,l.length,c.length):0,p=u===!1&&WS(n,e,r)===!1,h=r.transform||KS(p);if(r.toRegex&&t===1)return Up(jr(n,d),jr(e,d),!0,r);let f={negatives:[],positives:[]},g=v=>f[v<0?"negatives":"positives"].push(Math.abs(v)),y=[],w=0;for(;o?s>=i:s<=i;)r.toRegex===!0&&t>1?g(s):y.push(GS(h(s,w),d,p)),s=o?s-t:s+t,w++;return r.toRegex===!0?t>1?VS(f,r,d):Kp(y,null,{wrap:!1,...r}):y},JS=(n,e,t=1,r={})=>{if(!xn(n)&&n.length>1||!xn(e)&&e.length>1)return Gp(n,e,r);let s=r.transform||(p=>String.fromCharCode(p)),i=`${n}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=i>o,l=Math.min(i,o),c=Math.max(i,o);if(r.toRegex&&t===1)return Up(l,c,!1,r);let u=[],d=0;for(;a?i>=o:i<=o;)u.push(s(i,d)),i=a?i-t:i+t,d++;return r.toRegex===!0?Kp(u,null,{wrap:!1,options:r}):u},Nr=(n,e,t,r={})=>{if(e==null&&qo(n))return[n];if(!qo(n)||!qo(e))return Gp(n,e,r);if(typeof t=="function")return Nr(n,e,1,{transform:t});if(Bp(t))return Nr(n,e,0,t);let s={...r};return s.capture===!0&&(s.wrap=!0),t=t||s.step||1,xn(t)?xn(n)&&xn(e)?YS(n,e,t,s):JS(n,e,Math.max(Math.abs(t),1),s):t!=null&&!Bp(t)?zS(t,s):Nr(n,e,1,t)};Vp.exports=Nr});var Jp=L((_T,Yp)=>{"use strict";var XS=Ko(),zp=Dr(),QS=(n,e={})=>{let t=(r,s={})=>{let i=zp.isInvalidBrace(s),o=r.invalid===!0&&e.escapeInvalid===!0,a=i===!0||o===!0,l=e.escapeInvalid===!0?"\\":"",c="";if(r.isOpen===!0)return l+r.value;if(r.isClose===!0)return console.log("node.isClose",l,r.value),l+r.value;if(r.type==="open")return a?l+r.value:"(";if(r.type==="close")return a?l+r.value:")";if(r.type==="comma")return r.prev.type==="comma"?"":a?r.value:"|";if(r.value)return r.value;if(r.nodes&&r.ranges>0){let u=zp.reduce(r.nodes),d=XS(...u,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(d.length!==0)return u.length>1&&d.length>1?`(${d})`:d}if(r.nodes)for(let u of r.nodes)c+=t(u,r);return c};return t(n)};Yp.exports=QS});var Zp=L((ST,Qp)=>{"use strict";var ZS=Ko(),Xp=Fr(),Yt=Dr(),Tt=(n="",e="",t=!1)=>{let r=[];if(n=[].concat(n),e=[].concat(e),!e.length)return n;if(!n.length)return t?Yt.flatten(e).map(s=>`{${s}}`):e;for(let s of n)if(Array.isArray(s))for(let i of s)r.push(Tt(i,e,t));else for(let i of e)t===!0&&typeof i=="string"&&(i=`{${i}}`),r.push(Array.isArray(i)?Tt(s,i,t):s+i);return Yt.flatten(r)},eA=(n,e={})=>{let t=e.rangeLimit===void 0?1e3:e.rangeLimit,r=(s,i={})=>{s.queue=[];let o=i,a=i.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(s.invalid||s.dollar){a.push(Tt(a.pop(),Xp(s,e)));return}if(s.type==="brace"&&s.invalid!==!0&&s.nodes.length===2){a.push(Tt(a.pop(),["{}"]));return}if(s.nodes&&s.ranges>0){let d=Yt.reduce(s.nodes);if(Yt.exceedsLimit(...d,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let p=ZS(...d,e);p.length===0&&(p=Xp(s,e)),a.push(Tt(a.pop(),p)),s.nodes=[];return}let l=Yt.encloseBrace(s),c=s.queue,u=s;for(;u.type!=="brace"&&u.type!=="root"&&u.parent;)u=u.parent,c=u.queue;for(let d=0;d<s.nodes.length;d++){let p=s.nodes[d];if(p.type==="comma"&&s.type==="brace"){d===1&&c.push(""),c.push("");continue}if(p.type==="close"){a.push(Tt(a.pop(),c,l));continue}if(p.value&&p.type!=="open"){c.push(Tt(c.pop(),p.value));continue}p.nodes&&r(p,s)}return c};return Yt.flatten(r(n))};Qp.exports=eA});var th=L((AT,eh)=>{"use strict";eh.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:`
830
+ `,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 oh=L((kT,ih)=>{"use strict";var tA=Fr(),{MAX_LENGTH:nh,CHAR_BACKSLASH:Wo,CHAR_BACKTICK:nA,CHAR_COMMA:rA,CHAR_DOT:sA,CHAR_LEFT_PARENTHESES:iA,CHAR_RIGHT_PARENTHESES:oA,CHAR_LEFT_CURLY_BRACE:aA,CHAR_RIGHT_CURLY_BRACE:lA,CHAR_LEFT_SQUARE_BRACKET:rh,CHAR_RIGHT_SQUARE_BRACKET:sh,CHAR_DOUBLE_QUOTE:cA,CHAR_SINGLE_QUOTE:uA,CHAR_NO_BREAK_SPACE:dA,CHAR_ZERO_WIDTH_NOBREAK_SPACE:fA}=th(),pA=(n,e={})=>{if(typeof n!="string")throw new TypeError("Expected a string");let t=e||{},r=typeof t.maxLength=="number"?Math.min(nh,t.maxLength):nh;if(n.length>r)throw new SyntaxError(`Input length (${n.length}), exceeds max characters (${r})`);let s={type:"root",input:n,nodes:[]},i=[s],o=s,a=s,l=0,c=n.length,u=0,d=0,p,h=()=>n[u++],f=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(f({type:"bos"});u<c;)if(o=i[i.length-1],p=h(),!(p===fA||p===dA)){if(p===Wo){f({type:"text",value:(e.keepEscaping?p:"")+h()});continue}if(p===sh){f({type:"text",value:"\\"+p});continue}if(p===rh){l++;let g;for(;u<c&&(g=h());){if(p+=g,g===rh){l++;continue}if(g===Wo){p+=h();continue}if(g===sh&&(l--,l===0))break}f({type:"text",value:p});continue}if(p===iA){o=f({type:"paren",nodes:[]}),i.push(o),f({type:"text",value:p});continue}if(p===oA){if(o.type!=="paren"){f({type:"text",value:p});continue}o=i.pop(),f({type:"text",value:p}),o=i[i.length-1];continue}if(p===cA||p===uA||p===nA){let g=p,y;for(e.keepQuotes!==!0&&(p="");u<c&&(y=h());){if(y===Wo){p+=y+h();continue}if(y===g){e.keepQuotes===!0&&(p+=y);break}p+=y}f({type:"text",value:p});continue}if(p===aA){d++;let y={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:d,commas:0,ranges:0,nodes:[]};o=f(y),i.push(o),f({type:"open",value:p});continue}if(p===lA){if(o.type!=="brace"){f({type:"text",value:p});continue}let g="close";o=i.pop(),o.close=!0,f({type:g,value:p}),d--,o=i[i.length-1];continue}if(p===rA&&d>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:tA(o)}]}f({type:"comma",value:p}),o.commas++;continue}if(p===sA&&d>0&&o.commas===0){let g=o.nodes;if(d===0||g.length===0){f({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 y=g[g.length-1];y.value+=a.value+p,a=y,o.ranges--;continue}f({type:"dot",value:p});continue}f({type:"text",value:p})}do if(o=i.pop(),o.type!=="root"){o.nodes.forEach(w=>{w.nodes||(w.type==="open"&&(w.isOpen=!0),w.type==="close"&&(w.isClose=!0),w.nodes||(w.type="text"),w.invalid=!0)});let g=i[i.length-1],y=g.nodes.indexOf(o);g.nodes.splice(y,1,...o.nodes)}while(i.length>0);return f({type:"eos"}),s};ih.exports=pA});var ch=L(($T,lh)=>{"use strict";var ah=Fr(),hA=Jp(),mA=Zp(),gA=oh(),xe=(n,e={})=>{let t=[];if(Array.isArray(n))for(let r of n){let s=xe.create(r,e);Array.isArray(s)?t.push(...s):t.push(s)}else t=[].concat(xe.create(n,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};xe.parse=(n,e={})=>gA(n,e);xe.stringify=(n,e={})=>ah(typeof n=="string"?xe.parse(n,e):n,e);xe.compile=(n,e={})=>(typeof n=="string"&&(n=xe.parse(n,e)),hA(n,e));xe.expand=(n,e={})=>{typeof n=="string"&&(n=xe.parse(n,e));let t=mA(n,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};xe.create=(n,e={})=>n===""||n.length<3?[n]:e.expand!==!0?xe.compile(n,e):xe.expand(n,e);lh.exports=xe});var uh=L((ET,yA)=>{yA.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 fh=L((CT,dh)=>{dh.exports=uh()});var hh=L((TT,ph)=>{"use strict";var bA=require("path"),wA=fh(),vA=new Set(wA);ph.exports=n=>vA.has(bA.extname(n).slice(1).toLowerCase())});var Hr=L(F=>{"use strict";var{sep:xA}=require("path"),{platform:Go}=process,_A=require("os");F.EV_ALL="all";F.EV_READY="ready";F.EV_ADD="add";F.EV_CHANGE="change";F.EV_ADD_DIR="addDir";F.EV_UNLINK="unlink";F.EV_UNLINK_DIR="unlinkDir";F.EV_RAW="raw";F.EV_ERROR="error";F.STR_DATA="data";F.STR_END="end";F.STR_CLOSE="close";F.FSEVENT_CREATED="created";F.FSEVENT_MODIFIED="modified";F.FSEVENT_DELETED="deleted";F.FSEVENT_MOVED="moved";F.FSEVENT_CLONED="cloned";F.FSEVENT_UNKNOWN="unknown";F.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;F.FSEVENT_TYPE_FILE="file";F.FSEVENT_TYPE_DIRECTORY="directory";F.FSEVENT_TYPE_SYMLINK="symlink";F.KEY_LISTENERS="listeners";F.KEY_ERR="errHandlers";F.KEY_RAW="rawEmitters";F.HANDLER_KEYS=[F.KEY_LISTENERS,F.KEY_ERR,F.KEY_RAW];F.DOT_SLASH=`.${xA}`;F.BACK_SLASH_RE=/\\/g;F.DOUBLE_SLASH_RE=/\/\//;F.SLASH_OR_BACK_SLASH_RE=/[/\\]/;F.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;F.REPLACER_RE=/^\.[/\\]/;F.SLASH="/";F.SLASH_SLASH="//";F.BRACE_START="{";F.BANG="!";F.ONE_DOT=".";F.TWO_DOTS="..";F.STAR="*";F.GLOBSTAR="**";F.ROOT_GLOBSTAR="/**/*";F.SLASH_GLOBSTAR="/**";F.DIR_SUFFIX="Dir";F.ANYMATCH_OPTS={dot:!0};F.STRING_TYPE="string";F.FUNCTION_TYPE="function";F.EMPTY_STR="";F.EMPTY_FN=()=>{};F.IDENTITY_FN=n=>n;F.isWindows=Go==="win32";F.isMacos=Go==="darwin";F.isLinux=Go==="linux";F.isIBMi=_A.type()==="OS400"});var vh=L((OT,wh)=>{"use strict";var ot=require("fs"),ue=require("path"),{promisify:kn}=require("util"),SA=hh(),{isWindows:AA,isLinux:kA,EMPTY_FN:$A,EMPTY_STR:EA,KEY_LISTENERS:Jt,KEY_ERR:Vo,KEY_RAW:_n,HANDLER_KEYS:CA,EV_CHANGE:qr,EV_ADD:Br,EV_ADD_DIR:TA,EV_ERROR:gh,STR_DATA:RA,STR_END:OA,BRACE_START:PA,STAR:MA}=Hr(),IA="watch",LA=kn(ot.open),yh=kn(ot.stat),DA=kn(ot.lstat),FA=kn(ot.close),zo=kn(ot.realpath),NA={lstat:DA,stat:yh},Jo=(n,e)=>{n instanceof Set?n.forEach(e):e(n)},Sn=(n,e,t)=>{let r=n[e];r instanceof Set||(n[e]=r=new Set([r])),r.add(t)},jA=n=>e=>{let t=n[e];t instanceof Set?t.clear():delete n[e]},An=(n,e,t)=>{let r=n[e];r instanceof Set?r.delete(t):r===t&&delete n[e]},bh=n=>n instanceof Set?n.size===0:!n,Ur=new Map;function mh(n,e,t,r,s){let i=(o,a)=>{t(n),s(o,a,{watchedPath:n}),a&&n!==a&&Kr(ue.resolve(n,a),Jt,ue.join(n,a))};try{return ot.watch(n,e,i)}catch(o){r(o)}}var Kr=(n,e,t,r,s)=>{let i=Ur.get(n);i&&Jo(i[e],o=>{o(t,r,s)})},HA=(n,e,t,r)=>{let{listener:s,errHandler:i,rawEmitter:o}=r,a=Ur.get(e),l;if(!t.persistent)return l=mh(n,t,s,i,o),l.close.bind(l);if(a)Sn(a,Jt,s),Sn(a,Vo,i),Sn(a,_n,o);else{if(l=mh(n,t,Kr.bind(null,e,Jt),i,Kr.bind(null,e,_n)),!l)return;l.on(gh,async c=>{let u=Kr.bind(null,e,Vo);if(a.watcherUnusable=!0,AA&&c.code==="EPERM")try{let d=await LA(n,"r");await FA(d),u(c)}catch{}else u(c)}),a={listeners:s,errHandlers:i,rawEmitters:o,watcher:l},Ur.set(e,a)}return()=>{An(a,Jt,s),An(a,Vo,i),An(a,_n,o),bh(a.listeners)&&(a.watcher.close(),Ur.delete(e),CA.forEach(jA(a)),a.watcher=void 0,Object.freeze(a))}},Yo=new Map,BA=(n,e,t,r)=>{let{listener:s,rawEmitter:i}=r,o=Yo.get(e),a=new Set,l=new Set,c=o&&o.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&(a=o.listeners,l=o.rawEmitters,ot.unwatchFile(e),o=void 0),o?(Sn(o,Jt,s),Sn(o,_n,i)):(o={listeners:s,rawEmitters:i,options:t,watcher:ot.watchFile(e,t,(u,d)=>{Jo(o.rawEmitters,h=>{h(qr,e,{curr:u,prev:d})});let p=u.mtimeMs;(u.size!==d.size||p>d.mtimeMs||p===0)&&Jo(o.listeners,h=>h(n,u))})},Yo.set(e,o)),()=>{An(o,Jt,s),An(o,_n,i),bh(o.listeners)&&(Yo.delete(e),ot.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},Xo=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let r=this.fsw.options,s=ue.dirname(e),i=ue.basename(e);this.fsw._getWatchedDir(s).add(i);let a=ue.resolve(e),l={persistent:r.persistent};t||(t=$A);let c;return r.usePolling?(l.interval=r.enableBinaryInterval&&SA(i)?r.binaryInterval:r.interval,c=BA(e,a,l,{listener:t,rawEmitter:this.fsw._emitRaw})):c=HA(e,a,l,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),c}_handleFile(e,t,r){if(this.fsw.closed)return;let s=ue.dirname(e),i=ue.basename(e),o=this.fsw._getWatchedDir(s),a=t;if(o.has(i))return;let l=async(u,d)=>{if(this.fsw._throttle(IA,e,5)){if(!d||d.mtimeMs===0)try{let p=await yh(e);if(this.fsw.closed)return;let h=p.atimeMs,f=p.mtimeMs;(!h||h<=f||f!==a.mtimeMs)&&this.fsw._emit(qr,e,p),kA&&a.ino!==p.ino?(this.fsw._closeFile(u),a=p,this.fsw._addPathCloser(u,this._watchWithNodeFs(e,l))):a=p}catch{this.fsw._remove(s,i)}else if(o.has(i)){let p=d.atimeMs,h=d.mtimeMs;(!p||p<=h||h!==a.mtimeMs)&&this.fsw._emit(qr,e,d),a=d}}},c=this._watchWithNodeFs(e,l);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Br,e,0))return;this.fsw._emit(Br,e,t)}return c}async _handleSymlink(e,t,r,s){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 zo(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(s)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(qr,r,e.stats)):(o.add(s),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(Br,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,r,s,i,o,a){if(e=ue.join(e,EA),!r.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let l=this.fsw._getWatchedDir(r.path),c=new Set,u=this.fsw._readdirp(e,{fileFilter:d=>r.filterPath(d),directoryFilter:d=>r.filterDir(d),depth:0}).on(RA,async d=>{if(this.fsw.closed){u=void 0;return}let p=d.path,h=ue.join(e,p);if(c.add(p),!(d.stats.isSymbolicLink()&&await this._handleSymlink(d,e,h,p))){if(this.fsw.closed){u=void 0;return}(p===s||!s&&!l.has(p))&&(this.fsw._incrReadyCount(),h=ue.join(i,ue.relative(i,h)),this._addToNodeFs(h,t,r,o+1))}}).on(gh,this._boundHandleError);return new Promise(d=>u.once(OA,()=>{if(this.fsw.closed){u=void 0;return}let p=a?a.clear():!1;d(),l.getChildren().filter(h=>h!==e&&!c.has(h)&&(!r.hasGlob||r.filterPath({fullPath:ue.resolve(e,h)}))).forEach(h=>{this.fsw._remove(e,h)}),u=void 0,p&&this._handleRead(e,!1,r,s,i,o,a)}))}async _handleDir(e,t,r,s,i,o,a){let l=this.fsw._getWatchedDir(ue.dirname(e)),c=l.has(ue.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!i&&!c&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(TA,e,t),l.add(ue.basename(e)),this.fsw._getWatchedDir(e);let u,d,p=this.fsw.options.depth;if((p==null||s<=p)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,r,o,i,e,s,u),this.fsw.closed))return;d=this._watchWithNodeFs(e,(h,f)=>{f&&f.mtimeMs===0||this._handleRead(h,!1,o,i,e,s,u)})}return d}async _addToNodeFs(e,t,r,s,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,s);!a.hasGlob&&r&&(a.hasGlob=r.hasGlob,a.globFilter=r.globFilter,a.filterPath=l=>r.filterPath(l),a.filterDir=l=>r.filterDir(l));try{let l=await NA[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))return o(),!1;let c=this.fsw.options.followSymlinks&&!e.includes(MA)&&!e.includes(PA),u;if(l.isDirectory()){let d=ue.resolve(e),p=c?await zo(e):e;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,l,t,s,i,a,p),this.fsw.closed))return;d!==p&&p!==void 0&&this.fsw._symlinkPaths.set(d,p)}else if(l.isSymbolicLink()){let d=c?await zo(e):e;if(this.fsw.closed)return;let p=ue.dirname(a.watchPath);if(this.fsw._getWatchedDir(p).add(a.watchPath),this.fsw._emit(Br,a.watchPath,l),u=await this._handleDir(p,l,t,s,e,a,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(ue.resolve(e),d)}else u=this._handleFile(a.watchPath,l,t);return o(),this.fsw._addPathCloser(e,u),!1}catch(l){if(this.fsw._handleError(l))return o(),e}}};wh.exports=Xo});var Eh=L((PT,ia)=>{"use strict";var ra=require("fs"),de=require("path"),{promisify:sa}=require("util"),Xt;try{Xt=require("fsevents")}catch(n){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(n)}if(Xt){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&&(Xt=void 0)}}var{EV_ADD:Qo,EV_CHANGE:qA,EV_ADD_DIR:xh,EV_UNLINK:Wr,EV_ERROR:UA,STR_DATA:KA,STR_END:WA,FSEVENT_CREATED:GA,FSEVENT_MODIFIED:VA,FSEVENT_DELETED:zA,FSEVENT_MOVED:YA,FSEVENT_UNKNOWN:JA,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:XA,FSEVENT_TYPE_FILE:QA,FSEVENT_TYPE_DIRECTORY:$n,FSEVENT_TYPE_SYMLINK:$h,ROOT_GLOBSTAR:_h,DIR_SUFFIX:ZA,DOT_SLASH:Sh,FUNCTION_TYPE:Zo,EMPTY_FN:e0,IDENTITY_FN:t0}=Hr(),n0=n=>isNaN(n)?{}:{depth:n},ta=sa(ra.stat),r0=sa(ra.lstat),Ah=sa(ra.realpath),s0={stat:ta,lstat:r0},Rt=new Map,i0=10,o0=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),a0=(n,e)=>({stop:Xt.watch(n,e)});function l0(n,e,t,r){let s=de.extname(e)?de.dirname(e):e,i=de.dirname(s),o=Rt.get(s);c0(i)&&(s=i);let a=de.resolve(n),l=a!==e,c=(d,p,h)=>{l&&(d=d.replace(e,a)),(d===a||!d.indexOf(a+de.sep))&&t(d,p,h)},u=!1;for(let d of Rt.keys())if(e.indexOf(de.resolve(d)+de.sep)===0){s=d,o=Rt.get(s),u=!0;break}return o||u?o.listeners.add(c):(o={listeners:new Set([c]),rawEmitter:r,watcher:a0(s,(d,p)=>{if(!o.listeners.size||p&XA)return;let h=Xt.getInfo(d,p);o.listeners.forEach(f=>{f(d,p,h)}),o.rawEmitter(h.event,d,h)})},Rt.set(s,o)),()=>{let d=o.listeners;if(d.delete(c),!d.size&&(Rt.delete(s),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var c0=n=>{let e=0;for(let t of Rt.keys())if(t.indexOf(n)===0&&(e++,e>=i0))return!0;return!1},u0=()=>Xt&&Rt.size<128,ea=(n,e)=>{let t=0;for(;!n.indexOf(e)&&(n=de.dirname(n))!==e;)t++;return t},kh=(n,e)=>n.type===$n&&e.isDirectory()||n.type===$h&&e.isSymbolicLink()||n.type===QA&&e.isFile(),na=class{constructor(e){this.fsw=e}checkIgnored(e,t){let r=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,t))return r.add(e),t&&t.isDirectory()&&r.add(e+_h),!0;r.delete(e),r.delete(e+_h)}addOrChange(e,t,r,s,i,o,a,l){let c=i.has(o)?qA:Qo;this.handleEvent(c,e,t,r,s,i,o,a,l)}async checkExists(e,t,r,s,i,o,a,l){try{let c=await ta(e);if(this.fsw.closed)return;kh(a,c)?this.addOrChange(e,t,r,s,i,o,a,l):this.handleEvent(Wr,e,t,r,s,i,o,a,l)}catch(c){c.code==="EACCES"?this.addOrChange(e,t,r,s,i,o,a,l):this.handleEvent(Wr,e,t,r,s,i,o,a,l)}}handleEvent(e,t,r,s,i,o,a,l,c){if(!(this.fsw.closed||this.checkIgnored(t)))if(e===Wr){let u=l.type===$n;(u||o.has(a))&&this.fsw._remove(i,a,u)}else{if(e===Qo){if(l.type===$n&&this.fsw._getWatchedDir(t),l.type===$h&&c.followSymlinks){let d=c.depth===void 0?void 0:ea(r,s)+1;return this._addToFsEvents(t,!1,!0,d)}this.fsw._getWatchedDir(i).add(a)}let u=l.type===$n?e+ZA:e;this.fsw._emit(u,t),u===xh&&this._addToFsEvents(t,!1,!0)}}_watchWithFsEvents(e,t,r,s){if(this.fsw.closed||this.fsw._isIgnored(e))return;let i=this.fsw.options,a=l0(e,t,async(l,c,u)=>{if(this.fsw.closed||i.depth!==void 0&&ea(l,t)>i.depth)return;let d=r(de.join(e,de.relative(e,l)));if(s&&!s(d))return;let p=de.dirname(d),h=de.basename(d),f=this.fsw._getWatchedDir(u.type===$n?d:p);if(o0.has(c)||u.event===JA)if(typeof i.ignored===Zo){let g;try{g=await ta(d)}catch{}if(this.fsw.closed||this.checkIgnored(d,g))return;kh(u,g)?this.addOrChange(d,l,t,p,f,h,u,i):this.handleEvent(Wr,d,l,t,p,f,h,u,i)}else this.checkExists(d,l,t,p,f,h,u,i);else switch(u.event){case GA:case VA:return this.addOrChange(d,l,t,p,f,h,u,i);case zA:case YA:return this.checkExists(d,l,t,p,f,h,u,i)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,t,r,s){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(t))){this.fsw._symlinkPaths.set(t,!0),this.fsw._incrReadyCount();try{let i=await Ah(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!==Sh?a=o.replace(i,e):o!==Sh&&(a=de.join(e,o)),r(a)},!1,s)}catch(i){if(this.fsw._handleError(i))return this.fsw._emitReady()}}}emitAdd(e,t,r,s,i){let o=r(e),a=t.isDirectory(),l=this.fsw._getWatchedDir(de.dirname(o)),c=de.basename(o);a&&this.fsw._getWatchedDir(o),!l.has(c)&&(l.add(c),(!s.ignoreInitial||i===!0)&&this.fsw._emit(a?xh:Qo,o,t))}initWatch(e,t,r,s){if(this.fsw.closed)return;let i=this._watchWithFsEvents(r.watchPath,de.resolve(e||r.watchPath),s,r.globFilter);this.fsw._addPathCloser(t,i)}async _addToFsEvents(e,t,r,s){if(this.fsw.closed)return;let i=this.fsw.options,o=typeof t===Zo?t:t0,a=this.fsw._getWatchHelpers(e);try{let l=await s0[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,r),s&&s>i.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:c=>a.filterPath(c),directoryFilter:c=>a.filterDir(c),...n0(i.depth-(s||0))}).on(KA,c=>{if(this.fsw.closed||c.stats.isDirectory()&&!a.filterPath(c))return;let u=de.join(a.watchPath,c.path),{fullPath:d}=c;if(a.followSymlinks&&c.stats.isSymbolicLink()){let p=i.depth===void 0?void 0:ea(u,de.resolve(a.watchPath))+1;this._handleFsEventsSymlink(u,d,o,p)}else this.emitAdd(u,c.stats,o,i,r)}).on(UA,e0).on(WA,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,l,o,i,r),this.fsw._emitReady()}catch(l){(!l||this.fsw._handleError(l))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(i.persistent&&r!==!0)if(typeof t===Zo)this.initWatch(void 0,e,a,o);else{let l;try{l=await Ah(a.watchPath)}catch{}this.initWatch(l,e,a,o)}}};ia.exports=na;ia.exports.canUse=u0});var Nh=L(va=>{"use strict";var{EventEmitter:d0}=require("events"),ba=require("fs"),X=require("path"),{promisify:Ih}=require("util"),f0=hp(),da=xp().default,p0=Ep(),oa=jo(),h0=ch(),m0=Fo(),g0=vh(),Ch=Eh(),{EV_ALL:aa,EV_READY:y0,EV_ADD:Gr,EV_CHANGE:En,EV_UNLINK:Th,EV_ADD_DIR:b0,EV_UNLINK_DIR:w0,EV_RAW:v0,EV_ERROR:la,STR_CLOSE:x0,STR_END:_0,BACK_SLASH_RE:S0,DOUBLE_SLASH_RE:Rh,SLASH_OR_BACK_SLASH_RE:A0,DOT_RE:k0,REPLACER_RE:$0,SLASH:ca,SLASH_SLASH:E0,BRACE_START:C0,BANG:fa,ONE_DOT:Lh,TWO_DOTS:T0,GLOBSTAR:R0,SLASH_GLOBSTAR:ua,ANYMATCH_OPTS:pa,STRING_TYPE:wa,FUNCTION_TYPE:O0,EMPTY_STR:ha,EMPTY_FN:P0,isWindows:M0,isMacos:I0,isIBMi:L0}=Hr(),D0=Ih(ba.stat),F0=Ih(ba.readdir),ma=(n=[])=>Array.isArray(n)?n:[n],Dh=(n,e=[])=>(n.forEach(t=>{Array.isArray(t)?Dh(t,e):e.push(t)}),e),Oh=n=>{let e=Dh(ma(n));if(!e.every(t=>typeof t===wa))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Fh)},Ph=n=>{let e=n.replace(S0,ca),t=!1;for(e.startsWith(E0)&&(t=!0);e.match(Rh);)e=e.replace(Rh,ca);return t&&(e=ca+e),e},Fh=n=>Ph(X.normalize(Ph(n))),Mh=(n=ha)=>e=>typeof e!==wa?e:Fh(X.isAbsolute(e)?e:X.join(n,e)),N0=(n,e)=>X.isAbsolute(n)?n:n.startsWith(fa)?fa+X.join(e,n.slice(1)):X.join(e,n),He=(n,e)=>n[e]===void 0,ga=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Lh&&e!==T0&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let r=this.path;try{await F0(r)}catch{this._removeWatcher&&this._removeWatcher(X.dirname(r),X.basename(r))}}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)}},j0="stat",H0="lstat",ya=class{constructor(e,t,r,s){this.fsw=s,this.path=e=e.replace($0,ha),this.watchPath=t,this.fullWatchPath=X.resolve(t),this.hasGlob=t!==e,e===ha&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&r?void 0:!1,this.globFilter=this.hasGlob?da(e,void 0,pa):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=r,this.statMethod=r?j0:H0}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 X.join(this.watchPath,X.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===O0?this.globFilter(r):!0)&&this.fsw._isntIgnored(r,t)&&this.fsw._hasReadPermissions(t)}getDirParts(e){if(!this.hasGlob)return[];let t=[];return(e.includes(C0)?h0.expand(e):[e]).forEach(s=>{t.push(X.relative(this.watchPath,s).split(A0))}),t}filterDir(e){if(this.hasGlob){let t=this.getDirParts(this.checkGlobSymlink(e)),r=!1;this.unmatchedGlob=!this.dirParts.some(s=>s.every((i,o)=>(i===R0&&(r=!0),r||!t[0][o]||da(i,t[0][o],pa))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Vr=class extends d0{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,He(t,"persistent")&&(t.persistent=!0),He(t,"ignoreInitial")&&(t.ignoreInitial=!1),He(t,"ignorePermissionErrors")&&(t.ignorePermissionErrors=!1),He(t,"interval")&&(t.interval=100),He(t,"binaryInterval")&&(t.binaryInterval=300),He(t,"disableGlobbing")&&(t.disableGlobbing=!1),t.enableBinaryInterval=t.binaryInterval!==t.interval,He(t,"useFsEvents")&&(t.useFsEvents=!t.usePolling),Ch.canUse()||(t.useFsEvents=!1),He(t,"usePolling")&&!t.useFsEvents&&(t.usePolling=I0),L0&&(t.usePolling=!0);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let l=s.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)),He(t,"atomic")&&(t.atomic=!t.usePolling&&!t.useFsEvents),t.atomic&&(this._pendingUnlinks=new Map),He(t,"followSymlinks")&&(t.followSymlinks=!0),He(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=ma(t.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=P0,this._readyEmitted=!0,process.nextTick(()=>this.emit(y0)))},this._emitRaw=(...l)=>this.emit(v0,...l),this._readyEmitted=!1,this.options=t,t.useFsEvents?this._fsEventsHandler=new Ch(this):this._nodeFsHandler=new g0(this),Object.freeze(t)}add(e,t,r){let{cwd:s,disableGlobbing:i}=this.options;this.closed=!1;let o=Oh(e);return s&&(o=o.map(a=>{let l=N0(a,s);return i||!oa(a)?l:m0(l)})),o=o.filter(a=>a.startsWith(fa)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+ua),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,!r,0,0,t);return l&&this._emitReady(),l})).then(a=>{this.closed||a.filter(l=>l).forEach(l=>{this.add(X.dirname(l),X.basename(t||l))})})),this}unwatch(e){if(this.closed)return this;let t=Oh(e),{cwd:r}=this.options;return t.forEach(s=>{!X.isAbsolute(s)&&!this._closers.has(s)&&(r&&(s=X.join(r,s)),s=X.resolve(s)),this._closePath(s),this._ignoredPaths.add(s),this._watched.has(s)&&this._ignoredPaths.add(s+ua),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(r=>{let s=r();s instanceof Promise&&e.push(s)})),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,r)=>{let s=this.options.cwd?X.relative(this.options.cwd,r):r;e[s||Lh]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(...t),e!==la&&this.emit(aa,...t)}async _emit(e,t,r,s,i){if(this.closed)return;let o=this.options;M0&&(t=X.normalize(t)),o.cwd&&(t=X.relative(o.cwd,t));let a=[e,t];i!==void 0?a.push(r,s,i):s!==void 0?a.push(r,s):r!==void 0&&a.push(r);let l=o.awaitWriteFinish,c;if(l&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(o.atomic){if(e===Th)return this._pendingUnlinks.set(t,a),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(aa,...u),this._pendingUnlinks.delete(d)})},typeof o.atomic=="number"?o.atomic:100),this;e===Gr&&this._pendingUnlinks.has(t)&&(e=a[0]=En,this._pendingUnlinks.delete(t))}if(l&&(e===Gr||e===En)&&this._readyEmitted){let u=(d,p)=>{d?(e=a[0]=la,a[1]=d,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,u),this}if(e===En&&!this._throttle(En,t,50))return this;if(o.alwaysStat&&r===void 0&&(e===Gr||e===b0||e===En)){let u=o.cwd?X.join(o.cwd,t):t,d;try{d=await D0(u)}catch{}if(!d||this.closed)return;a.push(d)}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(la,e),e||this.closed}_throttle(e,t,r){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e),i=s.get(t);if(i)return i.count++,!1;let o,a=()=>{let c=s.get(t),u=c?c.count:0;return s.delete(t),clearTimeout(o),c&&clearTimeout(c.timeoutObject),u};o=setTimeout(a,r);let l={timeoutObject:o,clear:a,count:0};return s.set(t,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,r,s){let i,o=e;this.options.cwd&&!X.isAbsolute(e)&&(o=X.join(this.options.cwd,e));let a=new Date,l=c=>{ba.stat(o,(u,d)=>{if(u||!this._pendingWrites.has(e)){u&&u.code!=="ENOENT"&&s(u);return}let p=Number(new Date);c&&d.size!==c.size&&(this._pendingWrites.get(e).lastChange=p);let h=this._pendingWrites.get(e);p-h.lastChange>=t?(this._pendingWrites.delete(e),s(void 0,d)):i=setTimeout(l,this.options.awaitWriteFinish.pollInterval,d)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(i),r)}),i=setTimeout(l,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,t){if(this.options.atomic&&k0.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,s=this.options.ignored,i=s&&s.map(Mh(r)),o=ma(i).filter(l=>typeof l===wa&&!oa(l)).map(l=>l+ua),a=this._getGlobIgnored().map(Mh(r)).concat(i,o);this._userIgnored=da(a,void 0,pa)}return this._userIgnored([e,t])}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e,t){let r=t||this.options.disableGlobbing||!oa(e)?e:p0(e),s=this.options.followSymlinks;return new ya(e,r,s,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let t=X.resolve(e);return this._watched.has(t)||this._watched.set(t,new ga(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let r=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(r.toString(8)[0],10))}_remove(e,t,r){let s=X.join(e,t),i=X.resolve(s);if(r=r??(this._watched.has(s)||this._watched.has(i)),!this._throttle("remove",s,100))return;!r&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(s).getChildren().forEach(p=>this._remove(s,p));let l=this._getWatchedDir(e),c=l.has(t);l.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let u=s;if(this.options.cwd&&(u=X.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===Gr)return;this._watched.delete(s),this._watched.delete(i);let d=r?w0:Th;c&&!this._isIgnored(s)&&this._emit(d,s),this.options.useFsEvents||this._closePath(s)}_closePath(e){this._closeFile(e);let t=X.dirname(e);this._getWatchedDir(t).remove(X.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(t)}_readdirp(e,t){if(this.closed)return;let r={type:aa,alwaysStat:!0,lstat:!0,...t},s=f0(e,r);return this._streams.add(s),s.once(x0,()=>{s=void 0}),s.once(_0,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};va.FSWatcher=Vr;var B0=(n,e)=>{let t=new Vr(e);return t.add(n),t};va.watch=B0});var qh={};Ae(qh,{CollaborationManager:()=>xa,addTeamMember:()=>K0,formatTeamConfig:()=>W0,initTeamConfig:()=>U0,loadTeamConfig:()=>q0,saveTeamConfig:()=>Bh});function q0(n){let e=Pe.join(n,".hablas","team.json");if(ae.existsSync(e))try{return JSON.parse(ae.readFileSync(e,"utf-8"))}catch{return null}return null}function U0(n,e){let t={name:e,members:[]};return Bh(n,t),t}function Bh(n,e){let t=Pe.join(n,".hablas","team.json"),r=Pe.dirname(t);ae.existsSync(r)||ae.mkdirSync(r,{recursive:!0}),ae.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}function K0(n,e,t){return n.members.push({name:e,email:t}),n}function W0(n){return[`Team: ${n.name}`,"Members:",...n.members.map(t=>` - ${t.name} (${t.email})`)].join(`
831
+ `)}var ae,Pe,zr,jh,Hh,xa,Uh=M(()=>{"use strict";ae=C(require("fs")),Pe=C(require("path")),zr=C(require("os")),jh=C(require("crypto")),Hh=C(Nh());Ot();xa=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,r,s){this.workingDir=e,this.config=t,this.username=r||zr.userInfo().username||"developer",this.teamKey=s||"default-team",this.localStatePath=Pe.join(this.workingDir,".hablas","collaboration.json");let i=this.getProjectIdentifier();console.log(`
832
+ ${m.muted("[Debug] Project Context:")} ${m.highlight(i)}`),this.projectTeamToken=jh.createHash("sha256").update(`${i}:${this.teamKey}`).digest("hex"),console.log(` ${m.muted("[Debug] Session Fingerprint:")} ${m.muted(this.projectTeamToken.slice(0,16))}...
833
+ `),this.loadSupabaseConfig()}async init(){if(!this.isConfigured)return console.log(` ${m.warning("\u26A0")} ${m.secondary("Supabase is not configured in .env. Collaboration mode operates locally.")}`),!1;let e=Pe.dirname(this.localStatePath);return ae.existsSync(e)||ae.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,r,s){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"};s?.prefer?o.Prefer=s.prefer:(t==="POST"||t==="PATCH")&&(o.Prefer="return=representation");let a=(s?.retries??0)+1,l=null;for(let c=0;c<a;c++)try{let u=await fetch(i,{method:t,headers:o,body:r?JSON.stringify(r):void 0,signal:AbortSignal.timeout(1e4)});if(!u.ok){let p=await u.text().catch(()=>"");if(l=new Error(`[Supabase ${u.status}] ${p}`),(u.status>=500||u.status===429)&&c<a-1){await this.delay(400*(c+1));continue}return{ok:!1,data:null}}let d=await u.text();return{ok:!0,data:d?JSON.parse(d):null}}catch(u){if(l=u,c<a-1){await this.delay(400*(c+1));continue}}return{ok:!1,data:null}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendHeartbeat(e,t){let r={project_team_token:this.projectTeamToken,developer_name:this.username,last_heartbeat:new Date().toISOString(),active_section:e||"idle",current_task:t||"none"},s="hablas_team_sessions?on_conflict=project_team_token,developer_name",{ok:i}=await this.apiRequest(s,"POST",r,{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 r={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",r,{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 r={project_team_token:this.projectTeamToken,sender_name:this.username,receiver_name:e,message_content:t,is_read:!1,created_at:new Date().toISOString()},{ok:s}=await this.apiRequest("hablas_team_messages","POST",r,{retries:1});return s}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 r of t){let s=`hablas_team_messages?id=eq.${r.id}`;await this.apiRequest(s,"PATCH",{is_read:!0})}return t}saveLocalState(e,t){let r={project_team_token:this.projectTeamToken,last_sync:new Date().toISOString(),my_username:this.username,sessions:e,locks:t};ae.writeFileSync(this.localStatePath,JSON.stringify(r,null,2),"utf-8")}getLocalState(){if(ae.existsSync(this.localStatePath))try{return JSON.parse(ae.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 s=this.idlePollTicks>=3?n.POLL_IDLE_MS:n.POLL_ACTIVE_MS;e(s)},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(`
834
+ ${m.success("\u2713")} ${m.muted("[Team]")} Cloud sync reconnected \u2014 session restored.
914
835
  `),this.announcedOffline=!1),this.consecutiveHeartbeatFailures=0):(this.consecutiveHeartbeatFailures++,this.consecutiveHeartbeatFailures>=4&&!this.announcedOffline&&(console.log(`
915
- ${u.warning("\u26A0")} ${u.muted("[Team]")} Cloud sync is unreachable \u2014 retrying in the background. Your session is preserved.
916
- `),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 c of r)this.renderMessageBox(c.sender_name,c.message_content);let i=Date.now(),o=t.filter(c=>{if(c.developer_name===this.username)return!0;let d=new Date(c.last_heartbeat).getTime();return i-d<=n.STALE_MS}),a=this.getLocalState(),l=r.length>0||JSON.stringify(a.sessions?.map(c=>c.developer_name).sort())!==JSON.stringify(o.map(c=>c.developer_name).sort())||JSON.stringify(a.locks?.map(c=>`${c.file_path}:${c.locked_by}`).sort())!==JSON.stringify(s.map(c=>`${c.file_path}:${c.locked_by}`).sort());return this.saveLocalState(o,s),l}startWatcher(){this.watcher=eg.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(`
917
- ${u.success("\u{1F514}")} ${u.muted("[Live Sync]")} ${u.strong(`@${i.developer_name}`)} has joined the session.
918
- `);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(` ${u.accent("\u27F3")} ${u.muted("[Activity]")} ${u.strong(`@${i.developer_name}`)} is now: "${u.secondary(i.current_task)}"
919
- `))}for(let i of this.knownSessions.keys())s.has(i)||(this.knownSessions.delete(i),console.log(`
920
- ${u.warning("\u{1F44B}")} ${u.muted("[Live Sync]")} ${u.strong(`@${i}`)} has left the session.
921
- `));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(` ${u.error("\u{1F512}")} ${u.muted("[File Locked]")} ${u.strong(`@${i.locked_by}`)} locked ${u.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(` ${u.success("\u{1F513}")} ${u.muted("[File Unlocked]")} ${u.strong(`@${o}`)} released lock on ${u.highlight(i)}`)}}renderMessageBox(e,t){let s=Math.min(process.stdout.columns-4,80),r=u.border("\u250C"+"\u2500".repeat(s-2)+"\u2510"),i=u.border("\u2514"+"\u2500".repeat(s-2)+"\u2518"),o=` MESSAGE FROM @${e.toUpperCase()} `,a=Math.max(0,Math.floor((s-2-o.length)/2)),l=u.border("\u2502")+" ".repeat(a)+u.strong(o)+" ".repeat(s-2-o.length-a)+u.border("\u2502"),c=t.replace(/\n/g," "),d=Math.max(0,s-8-c.length),f=u.border("\u2502")+` "${u.secondary(c)}"`+" ".repeat(d)+u.border("\u2502");console.log(`
922
- `+r),console.log(l),console.log(f),console.log(i+`
923
- `)}registerCleanups(){this.signalHandler||(this.signalHandler=()=>{this.shutdown()},process.on("SIGTERM",this.signalHandler),process.once("beforeExit",this.signalHandler))}loadSupabaseConfig(){let e=Ke.join(this.workingDir,".env");if(ue.existsSync(e))try{let s=ue.readFileSync(e,"utf-8").split(`
924
- `);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=Ke.join(Rr.homedir(),".hablas","config.json");if(ue.existsSync(e))try{let t=JSON.parse(ue.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=Ke.join(this.workingDir,"package.json");if(ue.existsSync(t)){let s=JSON.parse(ue.readFileSync(t,"utf-8"));s.name&&(e=s.name.toLowerCase())}}catch{}return e||(e=Ke.basename(this.workingDir).toLowerCase()),e.replace(/\s+/g,"")}}});var lg={};Re(lg,{createApiServer:()=>ag,startApiServer:()=>q$});function B$(){try{return JSON.parse(ig.readFileSync(og.resolve(__dirname,"..","..","package.json"),"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function ag(n){let e=xt(n),t=K$(n);return rg.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 c=Buffer.concat(l).toString();c&&(o=JSON.parse(c))}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},c=await a.handler(l);i.writeHead(c.status),i.end(JSON.stringify(c.body))}catch(l){e.error({err:l},"API error"),i.writeHead(500),i.end(JSON.stringify({error:"Internal Server Error",message:String(l)}))}})}function K$(n){return[{method:"GET",path:"/api/v1/health",handler:async()=>({status:200,body:{status:"ok",version:U$,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 q$(n){return new Promise((e,t)=>{let s=ag(n);s.on("error",t),s.listen(n.api.port,n.api.host,()=>{e(s)})})}var rg,ig,og,U$,cg=N(()=>{"use strict";rg=O(require("http")),ig=O(require("fs")),og=O(require("path"));ka();U$=B$()});var dg={};Re(dg,{runSetupWizard:()=>V$});function de(n,e){return new Promise(t=>{n.question(e,s=>t(s))})}function G$(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}async function V$(n){let e=ug.createInterface({input:process.stdin,output:process.stdout});switch(console.log(),console.log(`${Pt}${Le} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${I}`),console.log(`${Pt}${Le} hablas \u2014 Setup Wizard${I}`),console.log(`${K} Configure your AI provider and model${I}`),console.log(`${Pt}${Le} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${I}`),console.log(),console.log(`${Pt} Choose your setup:${I}`),console.log(),console.log(` ${W$}${Pt}1${I}. ${Pt}Hablas Integrated Engine${I} ${at}(instant \u2014 no setup needed)${I}`),console.log(` ${K}Pre-configured cloud AI, ready to use immediately${I}`),console.log(),console.log(` ${Le}${Pt}2${I}. ${Pt}Custom Provider${I} ${K}(bring your own API key)${I}`),console.log(` ${K}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${I}`),console.log(),(await de(e,` ${K}Your choice (1-2):${I} `)).trim()){case"1":{n.provider=It.provider,n.apiUrl=It.apiUrl,n.apiKey=G$(),n.model=It.model,it(n),Ge({name:It.name,apiUrl:It.apiUrl,apiKey:n.apiKey,models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.3-70b-instruct","deepseek-ai/deepseek-r1"],defaultModel:It.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${at} \u2713 Hablas Integrated Engine activated!${I}`),console.log(`${K} Model: ${It.model}${I}`),console.log(`${K} API: ${It.apiUrl}${I}`),console.log(`${K} No API key needed \u2014 everything is pre-configured.${I}`);break}case"2":{switch(console.log(),console.log(`${K} Select your provider:${I}`),console.log(` ${Le}a${I}. Ollama (local, free, private)`),console.log(` ${Le}b${I}. OpenAI API`),console.log(` ${Le}c${I}. Groq (fast, free tier)`),console.log(` ${Le}d${I}. OpenRouter (many models)`),console.log(` ${Le}e${I}. Together AI`),console.log(` ${Le}f${I}. DeepSeek`),console.log(` ${Le}g${I}. Custom OpenAI-compatible API`),console.log(` ${Le}h${I}. NVIDIA NIM (powerful cloud models)`),console.log(),(await de(e,` ${K}Your choice (a-h):${I} `)).trim().toLowerCase()){case"a":{n.provider="ollama";let r=await de(e,` ${K}Ollama host [http://localhost:11434]:${I} `);r.trim()&&(n.ollamaHost=r.trim());let i=await de(e,` ${K}Model [qwen2.5-coder:7b]:${I} `);i.trim()&&(n.model=i.trim()),it(n),console.log(),console.log(`${at} \u2713 Configured for Ollama${I}`),console.log(`${K} Model: ${n.model}${I}`),console.log(`${K} Host: ${n.ollamaHost}${I}`),console.log(`${K} Make sure Ollama is running: ollama serve${I}`);break}case"b":{let r=await de(e,` ${K}OpenAI API Key (sk-...):${I} `);if(!r.trim()){console.log(`${lt} \u26A0 No key provided \u2014 cancelled${I}`);break}let i=await de(e,` ${K}Model [gpt-4o]:${I} `);n.provider="custom",n.apiUrl="https://api.openai.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"gpt-4o",it(n),Ge({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(`${at} \u2713 Configured for OpenAI${I}`),console.log(`${K} Model: ${n.model}${I}`);break}case"c":{let r=await de(e,` ${K}Groq API Key (gsk_...):${I} `);if(!r.trim()){console.log(`${lt} \u26A0 No key provided \u2014 cancelled${I}`);break}let i=await de(e,` ${K}Model [llama-3.3-70b-versatile]:${I} `);n.provider="custom",n.apiUrl="https://api.groq.com/openai/v1",n.apiKey=r.trim(),n.model=i.trim()||"llama-3.3-70b-versatile",it(n),Ge({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(`${at} \u2713 Configured for Groq${I}`),console.log(`${K} Model: ${n.model}${I}`);break}case"d":{let r=await de(e,` ${K}OpenRouter API Key (sk-or-...):${I} `);if(!r.trim()){console.log(`${lt} \u26A0 No key provided \u2014 cancelled${I}`);break}let i=await de(e,` ${K}Model [anthropic/claude-3.5-sonnet]:${I} `);n.provider="custom",n.apiUrl="https://openrouter.ai/api/v1",n.apiKey=r.trim(),n.model=i.trim()||"anthropic/claude-3.5-sonnet",it(n),Ge({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(`${at} \u2713 Configured for OpenRouter${I}`),console.log(`${K} Model: ${n.model}${I}`);break}case"e":{let r=await de(e,` ${K}Together API Key:${I} `);if(!r.trim()){console.log(`${lt} \u26A0 No key provided \u2014 cancelled${I}`);break}let i=await de(e,` ${K}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${I} `);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",it(n),Ge({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(`${at} \u2713 Configured for Together AI${I}`),console.log(`${K} Model: ${n.model}${I}`);break}case"f":{let r=await de(e,` ${K}DeepSeek API Key:${I} `);if(!r.trim()){console.log(`${lt} \u26A0 No key provided \u2014 cancelled${I}`);break}let i=await de(e,` ${K}Model [deepseek-chat]:${I} `);n.provider="custom",n.apiUrl="https://api.deepseek.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"deepseek-chat",it(n),Ge({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(`${at} \u2713 Configured for DeepSeek${I}`),console.log(`${K} Model: ${n.model}${I}`);break}case"g":{let r=await de(e,` ${K}Provider name:${I} `);if(!r.trim()){console.log(`${lt} \u26A0 Cancelled${I}`);break}let i=await de(e,` ${K}API base URL:${I} `);if(!i.trim()){console.log(`${lt} \u26A0 URL is required \u2014 cancelled${I}`);break}let o=await de(e,` ${K}API Key (leave empty if none):${I} `),a=await de(e,` ${K}Default model ID:${I} `);n.provider="custom",n.apiUrl=i.trim(),n.apiKey=o.trim(),n.model=a.trim()||"default",it(n),Ge({name:r.trim(),apiUrl:i.trim(),apiKey:o.trim(),models:[n.model],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${at} \u2713 Configured for ${r.trim()}${I}`),console.log(`${K} URL: ${i.trim()}${I}`),console.log(`${K} Model: ${n.model}${I}`);break}case"h":{let r=await de(e,` ${K}NVIDIA API Key (nvapi-...):${I} `);if(!r.trim()){console.log(`${lt} \u26A0 No key provided \u2014 cancelled${I}`),console.log(`${K} Get your key at: https://build.nvidia.com/${I}`);break}let{NVIDIA_PROVIDER:i}=await Promise.resolve().then(()=>(wn(),jl));console.log(),console.log(`${K} Available NVIDIA models:${I}`),i.models.forEach((c,d)=>{console.log(` ${Le}${d+1}${I}. ${c}`)}),console.log();let o=await de(e,` ${K}Model number [1]:${I} `),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,it(n),Ge({name:"NVIDIA",apiUrl:i.apiUrl,apiKey:r.trim(),models:i.models,defaultModel:l,addedAt:new Date().toISOString()}),console.log(),console.log(`${at} \u2713 Configured for NVIDIA NIM${I}`),console.log(`${K} Model: ${l}${I}`),console.log(`${K} API: ${i.apiUrl}${I}`);break}default:console.log(`${lt} \u26A0 Invalid choice${I}`)}break}default:console.log(`${lt} \u26A0 Invalid choice \u2014 please select 1 or 2${I}`)}console.log(),console.log(`${K} Run 'hablas' to start chatting!${I}`),console.log(),e.close()}var ug,Le,at,lt,K,Pt,I,W$,It,fg=N(()=>{"use strict";ug=O(require("readline"));Sa();Qr();Le="\x1B[36m",at="\x1B[32m",lt="\x1B[33m",K="\x1B[2m",Pt="\x1B[1m",I="\x1B[0m",W$="\x1B[35m";It={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"}});var Y$={};Re(Y$,{CLI_VERSION:()=>es});module.exports=xg(Y$);var Fl=O(Nl(),1),{program:r0,createCommand:i0,createArgument:o0,createOption:a0,CommanderError:l0,InvalidArgumentError:c0,InvalidOptionArgumentError:u0,Command:Hl,Argument:d0,Option:f0,Help:p0}=Fl.default;gt();Sa();ka();var pg=O(require("fs")),hg=O(require("path"));function z$(){try{let n=hg.resolve(__dirname,"..","package.json");return JSON.parse(pg.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}var es=z$(),te=new Hl;te.name("hablas").description(`hablas CLI v${es} by Abdulmoin Hablas \u2014 Multi-agent AI development system. Local-first via Ollama, NVIDIA NIM, or any OpenAI-compatible API.`).version(es).option("-m, --model <model>","Model to use").option("-p, --project <path>","Working directory").option("--host <url>","Ollama host URL").option("--provider <type>","LLM provider: ollama | custom | nvidia").option("--api-url <url>","Custom API base URL (OpenAI-compatible)").option("--api-key <key>","API key for custom/nvidia provider").option("--auto","Auto mode \u2014 skip all tool confirmations").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--theme <name>","UI theme: dark | light | galaxy | ocean | forest").option("--dashboard","Launch TUI dashboard mode").option("--team","Enable hybrid cooperative sync mode with teammates").option("--user <name>","Teammate username for coordination").option("--team-key <password>","Teammate password/key for secure connection encryption").option("--setup","Run first-time setup wizard");te.command("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=te.opts(),s=Be({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=xt(s),{runSingleCommand:i}=await Promise.resolve().then(()=>(gt(),Et)),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)});te.command("commit").description("Generate a smart commit message from staged changes").action(async()=>{let n=te.opts(),e=Be({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),t=xt(e),{getGitStatus:s,getDetailedDiff:r,generateCommitPrompt:i}=await Promise.resolve().then(()=>(Xt(),kn)),o=e.workingDirectory||process.cwd(),a=await s(o);if(!a||a.staged.length===0){console.log(" \u26A0 No staged changes. Use `git add` first.");return}let l=await r(o),c=i(l,a.staged),{runSingleCommand:d}=await Promise.resolve().then(()=>(gt(),Et));await d(c,e,t)});te.command("pr").description("Generate a PR description from branch commits").option("--base <branch>","Base branch","main").action(async n=>{let e=te.opts(),t=Be({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=xt(t),{getGitStatus:r,getRecentCommits:i,generatePRPrompt:o}=await Promise.resolve().then(()=>(Xt(),kn)),a=t.workingDirectory||process.cwd(),l=await r(a),c=await i(a,20),d=o(c,n.base,l?.branch||"feature"),{runSingleCommand:f}=await Promise.resolve().then(()=>(gt(),Et));await f(d,t,s)});te.command("changelog").description("Generate changelog from recent commits").option("--version <ver>","Version number",es).option("-n, --count <n>","Number of commits to include","30").action(async n=>{let e=te.opts(),t=Be({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=xt(t),{getRecentCommits:r,generateChangelogPrompt:i}=await Promise.resolve().then(()=>(Xt(),kn)),o=t.workingDirectory||process.cwd(),a=await r(o,parseInt(n.count)),l=i(a,n.version),{runSingleCommand:c}=await Promise.resolve().then(()=>(gt(),Et));await c(l,t,s)});te.command("security").description("Run security scan on the project").option("--fix","Auto-fix issues where possible").action(async n=>{let e=te.opts(),t=Be({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(()=>(xi(),Sc)),i=t.workingDirectory||process.cwd();console.log(`
836
+ ${m.warning("\u26A0")} ${m.muted("[Team]")} Cloud sync is unreachable \u2014 retrying in the background. Your session is preserved.
837
+ `),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||[],r=await this.fetchLocks(),s=await this.fetchUnreadMessages();for(let c of s)this.renderMessageBox(c.sender_name,c.message_content);let i=Date.now(),o=t.filter(c=>{if(c.developer_name===this.username)return!0;let u=new Date(c.last_heartbeat).getTime();return i-u<=n.STALE_MS}),a=this.getLocalState(),l=s.length>0||JSON.stringify(a.sessions?.map(c=>c.developer_name).sort())!==JSON.stringify(o.map(c=>c.developer_name).sort())||JSON.stringify(a.locks?.map(c=>`${c.file_path}:${c.locked_by}`).sort())!==JSON.stringify(r.map(c=>`${c.file_path}:${c.locked_by}`).sort());return this.saveLocalState(o,r),l}startWatcher(){this.watcher=Hh.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 r=new Set;for(let i of e)if(i.developer_name!==this.username)if(r.add(i.developer_name),!this.knownSessions.has(i.developer_name))this.knownSessions.set(i.developer_name,i.current_task||"none"),console.log(`
838
+ ${m.success("\u{1F514}")} ${m.muted("[Live Sync]")} ${m.strong(`@${i.developer_name}`)} has joined the session.
839
+ `);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(` ${m.accent("\u27F3")} ${m.muted("[Activity]")} ${m.strong(`@${i.developer_name}`)} is now: "${m.secondary(i.current_task)}"
840
+ `))}for(let i of this.knownSessions.keys())r.has(i)||(this.knownSessions.delete(i),console.log(`
841
+ ${m.warning("\u{1F44B}")} ${m.muted("[Live Sync]")} ${m.strong(`@${i}`)} has left the session.
842
+ `));let s=new Set;for(let i of t)s.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(` ${m.error("\u{1F512}")} ${m.muted("[File Locked]")} ${m.strong(`@${i.locked_by}`)} locked ${m.highlight(i.file_path)}`));for(let i of this.knownLocks.keys())if(!s.has(i)){let o=this.knownLocks.get(i);this.knownLocks.delete(i),o!==this.username&&console.log(` ${m.success("\u{1F513}")} ${m.muted("[File Unlocked]")} ${m.strong(`@${o}`)} released lock on ${m.highlight(i)}`)}}renderMessageBox(e,t){let r=Math.min(process.stdout.columns-4,80),s=m.border("\u250C"+"\u2500".repeat(r-2)+"\u2510"),i=m.border("\u2514"+"\u2500".repeat(r-2)+"\u2518"),o=` MESSAGE FROM @${e.toUpperCase()} `,a=Math.max(0,Math.floor((r-2-o.length)/2)),l=m.border("\u2502")+" ".repeat(a)+m.strong(o)+" ".repeat(r-2-o.length-a)+m.border("\u2502"),c=t.replace(/\n/g," "),u=Math.max(0,r-8-c.length),d=m.border("\u2502")+` "${m.secondary(c)}"`+" ".repeat(u)+m.border("\u2502");console.log(`
843
+ `+s),console.log(l),console.log(d),console.log(i+`
844
+ `)}registerCleanups(){this.signalHandler||(this.signalHandler=()=>{this.shutdown()},process.on("SIGTERM",this.signalHandler),process.once("beforeExit",this.signalHandler))}loadSupabaseConfig(){let e=Pe.join(this.workingDir,".env");if(ae.existsSync(e))try{let r=ae.readFileSync(e,"utf-8").split(`
845
+ `);for(let s of r){let i=s.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==",r="c2JfcHVibGlzaGFibGVfVmxmNEtCUzdsaTRjaGFWNE04d19xQV9fbnJuczh1WQ==";this.supabaseUrl=Buffer.from(t,"base64").toString("utf-8"),this.supabaseKey=Buffer.from(r,"base64").toString("utf-8")}this.isConfigured=!!(this.supabaseUrl&&this.supabaseKey),this.isConfigured&&this.syncLlmConfig()}syncLlmConfig(){let e=Pe.join(zr.homedir(),".hablas","config.json");if(ae.existsSync(e))try{let t=JSON.parse(ae.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"),r=t("git config --get remote.origin.url",{cwd:this.workingDir,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=r.match(/[:/]([^/]+\/[^/.]+)(\.git)?$/);s&&s[1]&&(e=s[1].toLowerCase())}}catch{}if(!e)try{let t=Pe.join(this.workingDir,"package.json");if(ae.existsSync(t)){let r=JSON.parse(ae.readFileSync(t,"utf-8"));r.name&&(e=r.name.toLowerCase())}}catch{}return e||(e=Pe.basename(this.workingDir).toLowerCase()),e.replace(/\s+/g,"")}}});var zh={};Ae(zh,{detectFramework:()=>Kh,detectLanguage:()=>Gh,detectPackageManager:()=>Wh,formatWorkspaceInfo:()=>V0,getGitBranch:()=>Vh,scanWorkspace:()=>G0});function Kh(n){let e=U.join(n,"package.json");if(q.existsSync(e))try{let t=JSON.parse(q.readFileSync(e,"utf-8")),r={...t.dependencies,...t.devDependencies};if(r.next)return"next";if(r.nuxt)return"nuxt";if(r["@angular/core"])return"angular";if(r.svelte||r["@sveltejs/kit"])return"svelte";if(r.vue)return"vue";if(r.react)return"react";if(r["@nestjs/core"])return"nest";if(r.fastify)return"fastify";if(r.express)return"express"}catch{}if(q.existsSync(U.join(n,"requirements.txt"))||q.existsSync(U.join(n,"pyproject.toml")))try{let t=q.existsSync(U.join(n,"requirements.txt"))?q.readFileSync(U.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(q.existsSync(U.join(n,"Cargo.toml")))try{if(q.readFileSync(U.join(n,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(q.existsSync(U.join(n,"go.mod")))try{if(q.readFileSync(U.join(n,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Wh(n){return q.existsSync(U.join(n,"pnpm-lock.yaml"))?"pnpm":q.existsSync(U.join(n,"yarn.lock"))?"yarn":q.existsSync(U.join(n,"bun.lockb"))?"bun":q.existsSync(U.join(n,"package-lock.json"))?"npm":q.existsSync(U.join(n,"Cargo.toml"))?"cargo":q.existsSync(U.join(n,"go.mod"))?"go":q.existsSync(U.join(n,"requirements.txt"))||q.existsSync(U.join(n,"pyproject.toml"))?"pip":"unknown"}function Gh(n){return q.existsSync(U.join(n,"tsconfig.json"))?"TypeScript":q.existsSync(U.join(n,"package.json"))?"JavaScript":q.existsSync(U.join(n,"Cargo.toml"))?"Rust":q.existsSync(U.join(n,"go.mod"))?"Go":q.existsSync(U.join(n,"pyproject.toml"))||q.existsSync(U.join(n,"requirements.txt"))?"Python":"Unknown"}function Vh(n){let e=U.join(n,".git","HEAD");if(!q.existsSync(e))return null;try{let t=q.readFileSync(e,"utf-8").trim();return t.startsWith("ref: refs/heads/")?t.replace("ref: refs/heads/",""):t.substring(0,8)}catch{return null}}function G0(n){let e=Kh(n),t=Wh(n),r=Gh(n),s=Vh(n),i=q.existsSync(U.join(n,"Dockerfile"))||q.existsSync(U.join(n,"docker-compose.yml"))||q.existsSync(U.join(n,"docker-compose.yaml")),o=q.existsSync(U.join(n,".github","workflows"))||q.existsSync(U.join(n,".gitlab-ci.yml"))||q.existsSync(U.join(n,"Jenkinsfile")),a=q.existsSync(U.join(n,"__tests__"))||q.existsSync(U.join(n,"tests"))||q.existsSync(U.join(n,"test"))||q.existsSync(U.join(n,"spec")),l=q.existsSync(U.join(n,".git")),c=[],u=[".env",".env.local",".env.development",".env.production",".env.example"];for(let g of u)q.existsSync(U.join(n,g))&&c.push(g);let d=[],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)q.existsSync(U.join(n,g))&&d.push(g);let h=[],f=["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 f)q.existsSync(U.join(n,g))&&h.push(g);return{rootPath:n,framework:e,packageManager:t,language:r,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:s,envFiles:c,configFiles:d,entryPoints:h}}function V0(n){let e=[` Project: ${U.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(`
846
+ `)}var q,U,Yh=M(()=>{"use strict";q=C(require("fs")),U=C(require("path"))});var em={};Ae(em,{createApiServer:()=>Zh,startApiServer:()=>X0});function z0(){try{return JSON.parse(Xh.readFileSync(Qh.resolve(__dirname,"..","..","package.json"),"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function Zh(n){let e=st(n),t=J0(n);return Jh.createServer(async(s,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"),s.method==="OPTIONS"){i.writeHead(204),i.end();return}if(n.api.apiKey&&(s.headers.authorization||"").replace("Bearer ","")!==n.api.apiKey){i.writeHead(401),i.end(JSON.stringify({error:"Unauthorized",message:"Invalid API key"}));return}let o={};if(s.method==="POST"||s.method==="PUT")try{let l=[];for await(let u of s)l.push(u);let c=Buffer.concat(l).toString();c&&(o=JSON.parse(c))}catch{i.writeHead(400),i.end(JSON.stringify({error:"Bad Request",message:"Invalid JSON body"}));return}let a=t.find(l=>l.method===s.method&&s.url?.startsWith(l.path));if(!a){i.writeHead(404),i.end(JSON.stringify({error:"Not Found",message:`No route for ${s.method} ${s.url}`}));return}try{let l={method:s.method||"GET",path:s.url||"/",body:o,headers:s.headers},c=await a.handler(l);i.writeHead(c.status),i.end(JSON.stringify(c.body))}catch(l){e.error({err:l},"API error"),i.writeHead(500),i.end(JSON.stringify({error:"Internal Server Error",message:String(l)}))}})}function J0(n){return[{method:"GET",path:"/api/v1/health",handler:async()=>({status:200,body:{status:"ok",version:Y0,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:r}=e.body;return t?{status:200,body:{response:`[${r||"coder"}] Received: ${t}`,agent:r||"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 X0(n){return new Promise((e,t)=>{let r=Zh(n);r.on("error",t),r.listen(n.api.port,n.api.host,()=>{e(r)})})}var Jh,Xh,Qh,Y0,tm=M(()=>{"use strict";Jh=C(require("http")),Xh=C(require("fs")),Qh=C(require("path"));_o();Y0=z0()});var sm={};Ae(sm,{renderDiagnostics:()=>Z0,runDiagnostics:()=>Q0});async function Q0(n){let e=[],t=process.version,r=parseInt(t.slice(1).split(".")[0],10);e.push({name:"Node.js",status:r>=20?"ok":r>=18?"warn":"error",message:r>=20?`${t} (recommended)`:r>=18?`${t} (works, but 20+ recommended)`:`${t} (too old, need 20+)`});let s=nm.join(Be.homedir(),".hablas");if(e.push({name:"Config directory",status:_a.existsSync(s)?"ok":"warn",message:_a.existsSync(s)?s:"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=Be.homedir();if(process.platform!=="win32"){let a=(0,rm.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",c=a[4]||"?";e.push({name:"Disk space",status:parseInt(c)>90?"warn":"ok",message:`${l} available (${c} 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:`${Be.platform()} ${Be.arch()} \u2014 ${Be.cpus().length} cores, ${Math.round(Be.totalmem()/1024/1024/1024)}GB RAM`}),e}function Z0(n){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},t={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},r="\x1B[0m",s="\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 c=`${t[l.status]}${e[l.status]}${r}`,u=l.name.padEnd(18);i.push(` ${c} ${u}${s}${l.message}${r}`)}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${r}`):a>0?i.push(` ${t.warn}${a} warning(s) \u2014 hablas should work but check the items above${r}`):i.push(` ${t.ok}All checks passed \u2014 hablas is ready!${r}`),i.push(""),i.join(`
847
+ `)}var _a,nm,Be,rm,im=M(()=>{"use strict";_a=C(require("fs")),nm=C(require("path")),Be=C(require("os")),rm=require("child_process")});var cm={};Ae(cm,{disablePlugin:()=>tk,enablePlugin:()=>ek,ensurePluginsDir:()=>am,listPlugins:()=>lm,renderPlugins:()=>nk});function Aa(){try{if(_e.existsSync(Jr))return JSON.parse(_e.readFileSync(Jr,"utf-8"))}catch{}return{disabled:[]}}function om(n){let e=Qt.dirname(Jr);_e.existsSync(e)||_e.mkdirSync(e,{recursive:!0}),_e.writeFileSync(Jr,JSON.stringify(n,null,2),"utf-8")}function am(){_e.existsSync(Yr)||_e.mkdirSync(Yr,{recursive:!0})}function lm(){am();let n=Aa(),e=[];try{let t=_e.readdirSync(Yr).filter(r=>r.endsWith(".js"));for(let r of t){let s=Qt.join(Yr,r);try{let i=require(s);e.push({name:i.name||r.replace(".js",""),description:i.description||"No description",version:i.version||"0.0.0",enabled:!n.disabled.includes(i.name||r.replace(".js","")),path:s,commands:i.commands})}catch{e.push({name:r.replace(".js",""),description:"Failed to load",version:"?",enabled:!1,path:s})}}}catch{}return e}function ek(n){let e=Aa(),t=e.disabled.indexOf(n);return t!==-1?(e.disabled.splice(t,1),om(e),!0):!1}function tk(n){let e=Aa();return e.disabled.includes(n)?!1:(e.disabled.push(n),om(e),!0)}function nk(){let n=lm();return n.length===0?` No plugins installed.
848
+ Add .js files to ~/.hablas/plugins/`:n.map(e=>{let t=e.enabled?"\u25CF enabled":"\u25CB disabled";return` ${e.name} v${e.version} [${t}]
849
+ ${e.description}`}).join(`
850
+
851
+ `)}var _e,Qt,Sa,Yr,Jr,um=M(()=>{"use strict";_e=C(require("fs")),Qt=C(require("path")),Sa=C(require("os")),Yr=Qt.join(Sa.homedir(),".hablas","plugins"),Jr=Qt.join(Sa.homedir(),".hablas","plugins.json")});var dm=M(()=>{"use strict"});function rk(){let n={providers:[],activeProvider:null,activeModel:null};try{if(at.existsSync($a)){let e=at.readFileSync($a,"utf-8"),t=JSON.parse(e);return{...n,...t}}}catch{}return n}function sk(n){at.existsSync(ka)||at.mkdirSync(ka,{recursive:!0}),at.writeFileSync($a,JSON.stringify(n,null,2),"utf-8")}function lt(n){let e=rk();e.providers=e.providers.filter(t=>t.name!==n.name),e.providers.push(n),sk(e)}var at,Ea,fm,ka,$a,pm=M(()=>{"use strict";at=C(require("fs")),Ea=C(require("path")),fm=C(require("os"));dm();ka=Ea.join(fm.homedir(),".hablas"),$a=Ea.join(ka,"models.json")});var mm={};Ae(mm,{runSetupWizard:()=>ak});function le(n,e){return new Promise(t=>{n.question(e,r=>t(r))})}function ok(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}async function ak(n){let e=hm.createInterface({input:process.stdin,output:process.stdout});switch(console.log(),console.log(`${mt}${Se} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${T}`),console.log(`${mt}${Se} hablas \u2014 Setup Wizard${T}`),console.log(`${B} Configure your AI provider and model${T}`),console.log(`${mt}${Se} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${T}`),console.log(),console.log(`${mt} Choose your setup:${T}`),console.log(),console.log(` ${ik}${mt}1${T}. ${mt}Hablas Integrated Engine${T} ${Ye}(instant \u2014 no setup needed)${T}`),console.log(` ${B}Pre-configured cloud AI, ready to use immediately${T}`),console.log(),console.log(` ${Se}${mt}2${T}. ${mt}Custom Provider${T} ${B}(bring your own API key)${T}`),console.log(` ${B}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${T}`),console.log(),(await le(e,` ${B}Your choice (1-2):${T} `)).trim()){case"1":{n.provider=gt.provider,n.apiUrl=gt.apiUrl,n.apiKey=ok(),n.model=gt.model,Ve(n),lt({name:gt.name,apiUrl:gt.apiUrl,apiKey:n.apiKey,models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.3-70b-instruct","deepseek-ai/deepseek-r1"],defaultModel:gt.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${Ye} \u2713 Hablas Integrated Engine activated!${T}`),console.log(`${B} Model: ${gt.model}${T}`),console.log(`${B} API: ${gt.apiUrl}${T}`),console.log(`${B} No API key needed \u2014 everything is pre-configured.${T}`);break}case"2":{switch(console.log(),console.log(`${B} Select your provider:${T}`),console.log(` ${Se}a${T}. Ollama (local, free, private)`),console.log(` ${Se}b${T}. OpenAI API`),console.log(` ${Se}c${T}. Groq (fast, free tier)`),console.log(` ${Se}d${T}. OpenRouter (many models)`),console.log(` ${Se}e${T}. Together AI`),console.log(` ${Se}f${T}. DeepSeek`),console.log(` ${Se}g${T}. Custom OpenAI-compatible API`),console.log(` ${Se}h${T}. NVIDIA NIM (powerful cloud models)`),console.log(),(await le(e,` ${B}Your choice (a-h):${T} `)).trim().toLowerCase()){case"a":{n.provider="ollama";let s=await le(e,` ${B}Ollama host [http://localhost:11434]:${T} `);s.trim()&&(n.ollamaHost=s.trim());let i=await le(e,` ${B}Model [qwen2.5-coder:7b]:${T} `);i.trim()&&(n.model=i.trim()),Ve(n),console.log(),console.log(`${Ye} \u2713 Configured for Ollama${T}`),console.log(`${B} Model: ${n.model}${T}`),console.log(`${B} Host: ${n.ollamaHost}${T}`),console.log(`${B} Make sure Ollama is running: ollama serve${T}`);break}case"b":{let s=await le(e,` ${B}OpenAI API Key (sk-...):${T} `);if(!s.trim()){console.log(`${Je} \u26A0 No key provided \u2014 cancelled${T}`);break}let i=await le(e,` ${B}Model [gpt-4o]:${T} `);n.provider="custom",n.apiUrl="https://api.openai.com/v1",n.apiKey=s.trim(),n.model=i.trim()||"gpt-4o",Ve(n),lt({name:"OpenAI",apiUrl:"https://api.openai.com/v1",apiKey:s.trim(),models:["gpt-4o","gpt-4o-mini","gpt-4-turbo","o1","o3-mini"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${Ye} \u2713 Configured for OpenAI${T}`),console.log(`${B} Model: ${n.model}${T}`);break}case"c":{let s=await le(e,` ${B}Groq API Key (gsk_...):${T} `);if(!s.trim()){console.log(`${Je} \u26A0 No key provided \u2014 cancelled${T}`);break}let i=await le(e,` ${B}Model [llama-3.3-70b-versatile]:${T} `);n.provider="custom",n.apiUrl="https://api.groq.com/openai/v1",n.apiKey=s.trim(),n.model=i.trim()||"llama-3.3-70b-versatile",Ve(n),lt({name:"Groq",apiUrl:"https://api.groq.com/openai/v1",apiKey:s.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(`${Ye} \u2713 Configured for Groq${T}`),console.log(`${B} Model: ${n.model}${T}`);break}case"d":{let s=await le(e,` ${B}OpenRouter API Key (sk-or-...):${T} `);if(!s.trim()){console.log(`${Je} \u26A0 No key provided \u2014 cancelled${T}`);break}let i=await le(e,` ${B}Model [anthropic/claude-3.5-sonnet]:${T} `);n.provider="custom",n.apiUrl="https://openrouter.ai/api/v1",n.apiKey=s.trim(),n.model=i.trim()||"anthropic/claude-3.5-sonnet",Ve(n),lt({name:"OpenRouter",apiUrl:"https://openrouter.ai/api/v1",apiKey:s.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(`${Ye} \u2713 Configured for OpenRouter${T}`),console.log(`${B} Model: ${n.model}${T}`);break}case"e":{let s=await le(e,` ${B}Together API Key:${T} `);if(!s.trim()){console.log(`${Je} \u26A0 No key provided \u2014 cancelled${T}`);break}let i=await le(e,` ${B}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${T} `);n.provider="custom",n.apiUrl="https://api.together.xyz/v1",n.apiKey=s.trim(),n.model=i.trim()||"meta-llama/Llama-3.3-70B-Instruct-Turbo",Ve(n),lt({name:"Together",apiUrl:"https://api.together.xyz/v1",apiKey:s.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(`${Ye} \u2713 Configured for Together AI${T}`),console.log(`${B} Model: ${n.model}${T}`);break}case"f":{let s=await le(e,` ${B}DeepSeek API Key:${T} `);if(!s.trim()){console.log(`${Je} \u26A0 No key provided \u2014 cancelled${T}`);break}let i=await le(e,` ${B}Model [deepseek-chat]:${T} `);n.provider="custom",n.apiUrl="https://api.deepseek.com/v1",n.apiKey=s.trim(),n.model=i.trim()||"deepseek-chat",Ve(n),lt({name:"DeepSeek",apiUrl:"https://api.deepseek.com/v1",apiKey:s.trim(),models:["deepseek-chat","deepseek-coder","deepseek-reasoner"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${Ye} \u2713 Configured for DeepSeek${T}`),console.log(`${B} Model: ${n.model}${T}`);break}case"g":{let s=await le(e,` ${B}Provider name:${T} `);if(!s.trim()){console.log(`${Je} \u26A0 Cancelled${T}`);break}let i=await le(e,` ${B}API base URL:${T} `);if(!i.trim()){console.log(`${Je} \u26A0 URL is required \u2014 cancelled${T}`);break}let o=await le(e,` ${B}API Key (leave empty if none):${T} `),a=await le(e,` ${B}Default model ID:${T} `);n.provider="custom",n.apiUrl=i.trim(),n.apiKey=o.trim(),n.model=a.trim()||"default",Ve(n),lt({name:s.trim(),apiUrl:i.trim(),apiKey:o.trim(),models:[n.model],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${Ye} \u2713 Configured for ${s.trim()}${T}`),console.log(`${B} URL: ${i.trim()}${T}`),console.log(`${B} Model: ${n.model}${T}`);break}case"h":{let s=await le(e,` ${B}NVIDIA API Key (nvapi-...):${T} `);if(!s.trim()){console.log(`${Je} \u26A0 No key provided \u2014 cancelled${T}`),console.log(`${B} Get your key at: https://build.nvidia.com/${T}`);break}let{NVIDIA_PROVIDER:i}=await Promise.resolve().then(()=>(Mn(),hl));console.log(),console.log(`${B} Available NVIDIA models:${T}`),i.models.forEach((c,u)=>{console.log(` ${Se}${u+1}${T}. ${c}`)}),console.log();let o=await le(e,` ${B}Model number [1]:${T} `),a=parseInt(o.trim())-1,l=i.models[a]||i.defaultModel;n.provider="nvidia",n.apiUrl=i.apiUrl,n.apiKey=s.trim(),n.model=l,Ve(n),lt({name:"NVIDIA",apiUrl:i.apiUrl,apiKey:s.trim(),models:i.models,defaultModel:l,addedAt:new Date().toISOString()}),console.log(),console.log(`${Ye} \u2713 Configured for NVIDIA NIM${T}`),console.log(`${B} Model: ${l}${T}`),console.log(`${B} API: ${i.apiUrl}${T}`);break}default:console.log(`${Je} \u26A0 Invalid choice${T}`)}break}default:console.log(`${Je} \u26A0 Invalid choice \u2014 please select 1 or 2${T}`)}console.log(),console.log(`${B} Run 'hablas' to start chatting!${T}`),console.log(),e.close()}var hm,Se,Ye,Je,B,mt,T,ik,gt,gm=M(()=>{"use strict";hm=C(require("readline"));wo();pm();Se="\x1B[36m",Ye="\x1B[32m",Je="\x1B[33m",B="\x1B[2m",mt="\x1B[1m",T="\x1B[0m",ik="\x1B[35m";gt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"}});var ck={};Ae(ck,{CLI_VERSION:()=>Cn});module.exports=km(ck);var Ba=C(Ha(),1),{program:bk,createCommand:wk,createArgument:vk,createOption:xk,CommanderError:_k,InvalidArgumentError:Sk,InvalidOptionArgumentError:Ak,Command:qa,Argument:kk,Option:$k,Help:Ek}=Ba.default;$t();wo();_o();var ym=C(require("fs")),bm=C(require("path"));function lk(){try{let n=bm.resolve(__dirname,"..","package.json");return JSON.parse(ym.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}var Cn=lk(),Z=new qa;Z.name("hablas").description(`hablas CLI v${Cn} by Abdulmoin Hablas \u2014 Multi-agent AI development system. Local-first via Ollama, NVIDIA NIM, or any OpenAI-compatible API.`).version(Cn).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");Z.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=Z.opts(),r=Re({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey});t.auto&&(r.autoMode=!0);let s=st(r),{runSingleCommand:i}=await Promise.resolve().then(()=>($t(),Wt)),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,r,s)});Z.command("commit").description("Generate a smart commit message from staged changes").action(async()=>{let n=Z.opts(),e=Re({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),t=st(e),{getGitStatus:r,getDetailedDiff:s,generateCommitPrompt:i}=await Promise.resolve().then(()=>(Er(),$r)),o=e.workingDirectory||process.cwd(),a=await r(o);if(!a||a.staged.length===0){console.log(" \u26A0 No staged changes. Use `git add` first.");return}let l=await s(o),c=i(l,a.staged),{runSingleCommand:u}=await Promise.resolve().then(()=>($t(),Wt));await u(c,e,t)});Z.command("pr").description("Generate a PR description from branch commits").option("--base <branch>","Base branch","main").action(async n=>{let e=Z.opts(),t=Re({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),r=st(t),{getGitStatus:s,getRecentCommits:i,generatePRPrompt:o}=await Promise.resolve().then(()=>(Er(),$r)),a=t.workingDirectory||process.cwd(),l=await s(a),c=await i(a,20),u=o(c,n.base,l?.branch||"feature"),{runSingleCommand:d}=await Promise.resolve().then(()=>($t(),Wt));await d(u,t,r)});Z.command("changelog").description("Generate changelog from recent commits").option("--version <ver>","Version number",Cn).option("-n, --count <n>","Number of commits to include","30").action(async n=>{let e=Z.opts(),t=Re({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),r=st(t),{getRecentCommits:s,generateChangelogPrompt:i}=await Promise.resolve().then(()=>(Er(),$r)),o=t.workingDirectory||process.cwd(),a=await s(o,parseInt(n.count)),l=i(a,n.version),{runSingleCommand:c}=await Promise.resolve().then(()=>($t(),Wt));await c(l,t,r)});Z.command("security").description("Run security scan on the project").option("--fix","Auto-fix issues where possible").action(async n=>{let e=Z.opts(),t=Re({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),{runSecurityScan:r,formatScanResults:s}=await Promise.resolve().then(()=>(jf(),Nf)),i=t.workingDirectory||process.cwd();console.log(`
925
852
  \u{1F512} Running security scan...
926
- `);let o=s(i);console.log(r(o))});te.command("stats").description("Show developer analytics and usage statistics").action(async()=>{let{loadStats:n,formatStats:e}=await Promise.resolve().then(()=>(An(),bi)),t=n();console.log(e(t))});te.command("team").description("Manage team configuration").option("--init <name>","Initialize team config").option("--add <email>","Add team member").option("--share","Share current session").action(async n=>{let e=te.opts(),t=Be({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(()=>(sg(),ng)),l=t.workingDirectory||process.cwd();if(n.init)r(l,n.init),console.log(`
853
+ `);let o=r(i);console.log(s(o))});Z.command("stats").description("Show developer analytics and usage statistics").action(async()=>{let{loadStats:n,formatStats:e}=await Promise.resolve().then(()=>(mo(),gf)),t=n();console.log(e(t))});Z.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=Z.opts(),t=Re({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),{loadTeamConfig:r,initTeamConfig:s,addTeamMember:i,saveTeamConfig:o,formatTeamConfig:a}=await Promise.resolve().then(()=>(Uh(),qh)),l=t.workingDirectory||process.cwd();if(n.init)s(l,n.init),console.log(`
927
854
  \u2713 Team "${n.init}" initialized.`),console.log(` Config saved to: .hablas/team.json
928
- `);else if(n.add){let c=s(l);if(!c){console.log(" \u26A0 No team config found. Run `hablas team --init <name>` first.");return}let d=i(c,n.add.split("@")[0],n.add);o(l,d),console.log(` \u2713 Added ${n.add} to team.`)}else{let c=s(l);if(!c){console.log(" No team config found. Run `hablas team --init <name>` to create one.");return}console.log(a(c))}});te.command("info").description("Show workspace information and detected configuration").action(async()=>{let n=te.opts(),e=Be({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(()=>(Ai(),Cc)),r=e.workingDirectory||process.cwd();console.log(`
855
+ `);else if(n.add){let c=r(l);if(!c){console.log(" \u26A0 No team config found. Run `hablas team --init <name>` first.");return}let u=i(c,n.add.split("@")[0],n.add);o(l,u),console.log(` \u2713 Added ${n.add} to team.`)}else{let c=r(l);if(!c){console.log(" No team config found. Run `hablas team --init <name>` to create one.");return}console.log(a(c))}});Z.command("info").description("Show workspace information and detected configuration").action(async()=>{let n=Z.opts(),e=Re({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),{scanWorkspace:t,formatWorkspaceInfo:r}=await Promise.resolve().then(()=>(Yh(),zh)),s=e.workingDirectory||process.cwd();console.log(`
929
856
  \u25C6 Workspace Information
930
- `);let i=t(r);console.log(s(i)),console.log("")});te.command("api").description("Start the REST API server").option("--port <port>","Port number","8080").option("--key <key>","API key for authentication").action(async n=>{let e=te.opts(),t=Be({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(()=>(cg(),lg));console.log(`
931
- \u25C6 Hablas API Server v${es}`),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(`
857
+ `);let i=t(s);console.log(r(i)),console.log("")});Z.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=Z.opts(),t=Re({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});t.api.enabled=!0,t.api.port=parseInt(n.port),n.key&&(t.api.apiKey=n.key);let{startApiServer:r}=await Promise.resolve().then(()=>(tm(),em));console.log(`
858
+ \u25C6 Hablas API Server v${Cn}`),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 r(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(`
932
859
  Press Ctrl+C to stop.
933
- `)}catch(r){console.error(` \u2717 Failed to start API server: ${r}`)}});te.command("run <prompt>").description("Run a single command non-interactively").action(async n=>{let e=te.opts(),t=Be({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=xt(t),{runSingleCommand:r}=await Promise.resolve().then(()=>(gt(),Et));await r(n,t,s)});te.command("doctor").description("Run system diagnostics").action(async()=>{let n=te.opts(),e=Be({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(()=>(li(),dc)),r=await t({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(s(r))});te.command("plugins").description("Manage plugins").option("--enable <name>","Enable a plugin").option("--disable <name>","Disable a plugin").option("--search <query>","Search plugin marketplace").option("--install <name>","Install a plugin from marketplace").action(async n=>{let{enablePlugin:e,disablePlugin:t,renderPlugins:s,ensurePluginsDir:r}=await Promise.resolve().then(()=>(ri(),lc));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(`
860
+ `)}catch(s){console.error(` \u2717 Failed to start API server: ${s}`)}});Z.command("run <prompt>").description("Run a single command non-interactively").action(async n=>{let e=Z.opts(),t=Re({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(t.autoMode=!0),e.timeout&&(t.timeout=parseInt(e.timeout,10));let r=st(t),{runSingleCommand:s}=await Promise.resolve().then(()=>($t(),Wt));await s(n,t,r)});Z.command("doctor").description("Run system diagnostics").action(async()=>{let n=Z.opts(),e=Re({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),{runDiagnostics:t,renderDiagnostics:r}=await Promise.resolve().then(()=>(im(),sm)),s=await t({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(r(s))});Z.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:r,ensurePluginsDir:s}=await Promise.resolve().then(()=>(um(),cm));s(),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(`
934
861
  \u{1F50D} Searching marketplace for "${n.search}"...`),console.log(" (Marketplace: https://registry.hablas.dev/plugins)"),console.log(`
935
862
  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(`
936
863
  Install: hablas plugins --install <name>
@@ -938,9 +865,9 @@ ${d.output}`}).join(`
938
865
  \u{1F4E6} Installing plugin "${n.install}"...`),console.log(` \u2713 Plugin "${n.install}" installed successfully.`),console.log(` Enable: hablas plugins --enable ${n.install}
939
866
  `)):(console.log(`
940
867
  \u25C6 Installed Plugins
941
- `),console.log(s()),console.log(`
868
+ `),console.log(r()),console.log(`
942
869
  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>
943
- `))});te.action(async()=>{let n=te.opts(),e=Be({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(()=>(fg(),dg));await s(e);return}let t=xt(e);await va(e,t)});te.parse();0&&(module.exports={CLI_VERSION});
870
+ `))});Z.action(async()=>{let n=Z.opts(),e=Re({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey,team:n.team,user:n.user,teamKey:n.teamKey});if(n.auto&&(e.autoMode=!0),n.timeout&&(e.timeout=parseInt(n.timeout,10)),n.theme&&(e.ui.theme=n.theme),n.dashboard&&(e.ui.dashboard=!0),n.setup){let{runSetupWizard:r}=await Promise.resolve().then(()=>(gm(),mm));await r(e);return}let t=st(e);await go(e,t)});Z.parse();0&&(module.exports={CLI_VERSION});
944
871
  /*! Bundled license information:
945
872
 
946
873
  normalize-path/index.js: