hablas-ai 1.3.21 → 2.0.0

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 (4) hide show
  1. package/CHANGELOG.md +25 -151
  2. package/README.md +120 -290
  3. package/dist/index.js +173 -1222
  4. package/package.json +6 -11
package/dist/index.js CHANGED
@@ -1,869 +1,172 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var oy=Object.create;var Ps=Object.defineProperty;var ay=Object.getOwnPropertyDescriptor;var ly=Object.getOwnPropertyNames;var cy=Object.getPrototypeOf,uy=Object.prototype.hasOwnProperty;var L=(n,e)=>()=>(n&&(e=n(n=0)),e);var N=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Le=(n,e)=>{for(var t in e)Ps(n,t,{get:e[t],enumerable:!0})},ac=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ly(e))!uy.call(n,r)&&r!==t&&Ps(n,r,{get:()=>e[r],enumerable:!(s=ay(e,r))||s.enumerable});return n};var O=(n,e,t)=>(t=n!=null?oy(cy(n)):{},ac(e||!n||!n.__esModule?Ps(t,"default",{value:n,enumerable:!0}):t,n)),dy=n=>ac(Ps({},"__esModule",{value:!0}),n);var Un=N(oi=>{var Ms=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}},ii=class extends Ms{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};oi.CommanderError=Ms;oi.InvalidArgumentError=ii});var Is=N(li=>{var{InvalidArgumentError:fy}=Un(),ai=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 fy(`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 py(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}li.Argument=ai;li.humanReadableArgName=py});var ui=N(lc=>{var{humanReadableArgName:hy}=Is(),ci=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=>hy(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((s,r)=>Math.max(s,t.subcommandTerm(r).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((s,r)=>Math.max(s,t.optionTerm(r).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((s,r)=>Math.max(s,t.optionTerm(r).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((s,r)=>Math.max(s,t.argumentTerm(r).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let s="";for(let r=e.parent;r;r=r.parent)s=r.name()+" "+s;return s+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let s=`(${t.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatHelp(e,t){let s=t.padWidth(e,t),r=t.helpWidth||80,i=2,o=2;function a(p,g){if(g){let S=`${p.padEnd(s+o)}${g}`;return t.wrap(S,r-i,s+o)}return p}function l(p){return p.join(`
3
- `).replace(/^/gm," ".repeat(i))}let u=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(u=u.concat([t.wrap(d,r,0),""]));let f=t.visibleArguments(e).map(p=>a(t.argumentTerm(p),t.argumentDescription(p)));f.length>0&&(u=u.concat(["Arguments:",l(f),""]));let h=t.visibleOptions(e).map(p=>a(t.optionTerm(p),t.optionDescription(p)));if(h.length>0&&(u=u.concat(["Options:",l(h),""])),this.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(g=>a(t.optionTerm(g),t.optionDescription(g)));p.length>0&&(u=u.concat(["Global Options:",l(p),""]))}let m=t.visibleCommands(e).map(p=>a(t.subcommandTerm(p),t.subcommandDescription(p)));return m.length>0&&(u=u.concat(["Commands:",l(m),""])),u.join(`
4
- `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,s,r=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=t-s;if(a<r)return e;let l=e.slice(0,s),u=e.slice(s).replace(`\r
2
+ "use strict";var qa=Object.create;var Mn=Object.defineProperty;var Ua=Object.getOwnPropertyDescriptor;var Ba=Object.getOwnPropertyNames;var Ha=Object.getPrototypeOf,Wa=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Va=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ba(e))!Wa.call(t,s)&&s!==r&&Mn(t,s,{get:()=>e[s],enumerable:!(n=Ua(e,s))||n.enumerable});return t};var k=(t,e,r)=>(r=t!=null?qa(Ha(t)):{},Va(e||!t||!t.__esModule?Mn(r,"default",{value:t,enumerable:!0}):r,t));var Ye=R(sr=>{var dt=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},nr=class extends dt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};sr.CommanderError=dt;sr.InvalidArgumentError=nr});var ht=R(or=>{var{InvalidArgumentError:za}=Ye(),ir=class{constructor(e,r){switch(this.description=r||"",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,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new za(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Ka(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}or.Argument=ir;or.humanReadableArgName=Ka});var lr=R(Dn=>{var{humanReadableArgName:Ja}=ht(),ar=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,i)=>s.name().localeCompare(i.name())),r}compareOptions(e,r){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?r.push(n):n.long&&!i?r.push(e.createOption(n.long,n.description)):n.short&&!s&&r.push(e.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>Ja(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,s)=>Math.max(n,r.subcommandTerm(s).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,s)=>Math.max(n,r.argumentTerm(s).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),s=r.helpWidth||80,i=2,o=2;function a(c,m){if(m){let y=`${c.padEnd(n+o)}${m}`;return r.wrap(y,s-i,n+o)}return c}function l(c){return c.join(`
3
+ `).replace(/^/gm," ".repeat(i))}let u=[`Usage: ${r.commandUsage(e)}`,""],d=r.commandDescription(e);d.length>0&&(u=u.concat([r.wrap(d,s,0),""]));let f=r.visibleArguments(e).map(c=>a(r.argumentTerm(c),r.argumentDescription(c)));f.length>0&&(u=u.concat(["Arguments:",l(f),""]));let p=r.visibleOptions(e).map(c=>a(r.optionTerm(c),r.optionDescription(c)));if(p.length>0&&(u=u.concat(["Options:",l(p),""])),this.showGlobalOptions){let c=r.visibleGlobalOptions(e).map(m=>a(r.optionTerm(m),r.optionDescription(m)));c.length>0&&(u=u.concat(["Global Options:",l(c),""]))}let h=r.visibleCommands(e).map(c=>a(r.subcommandTerm(c),r.subcommandDescription(c)));return h.length>0&&(u=u.concat(["Commands:",l(h),""])),u.join(`
4
+ `)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,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=r-n;if(a<s)return e;let l=e.slice(0,n),u=e.slice(n).replace(`\r
5
5
  `,`
6
- `),d=" ".repeat(s),h="\\s\u200B",m=new RegExp(`
7
- |.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),p=u.match(m)||[];return l+p.map((g,S)=>g===`
8
- `?"":(S>0?d:"")+g.trimEnd()).join(`
9
- `)}};lc.Help=ci});var hi=N(pi=>{var{InvalidArgumentError:my}=Un(),di=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=yy(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 my(`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 gy(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},fi=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 gy(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function yy(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}}pi.Option=di;pi.DualOptions=fi});var uc=N(cc=>{function by(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 vy(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=by(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]}?)`:""}cc.suggestSimilar=vy});var mc=N(hc=>{var wy=require("node:events").EventEmitter,mi=require("node:child_process"),St=require("node:path"),gi=require("node:fs"),pe=require("node:process"),{Argument:xy,humanReadableArgName:Sy}=Is(),{CommanderError:yi}=Un(),{Help:_y}=ui(),{Option:dc,DualOptions:Ay}=hi(),{suggestSimilar:fc}=uc(),bi=class n extends wy{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=>pe.stdout.write(t),writeErr:t=>pe.stderr.write(t),getOutHelpWidth:()=>pe.stdout.isTTY?pe.stdout.columns:void 0,getErrHelpWidth:()=>pe.stderr.isTTY?pe.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 _y,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 xy(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 yi(e,t,s)),pe.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 dc(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 dc)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,s);if(o.makeOptionMandatory(!!e.mandatory),typeof r=="function")o.default(i).argParser(r);else if(r instanceof RegExp){let a=r;r=(l,u)=>{let d=a.exec(l);return d?d[0]:u},o.default(i).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,s,r){return this._optionEx({},e,t,s,r)}requiredOption(e,t,s,r){return this._optionEx({mandatory:!0},e,t,s,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,s){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(t=s.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){pe.versions?.electron&&(t.from="electron");let r=pe.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=pe.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":pe.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=St.resolve(d,f);if(gi.existsSync(h))return h;if(r.includes(St.extname(f)))return;let m=r.find(p=>gi.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=gi.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=St.resolve(St.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=St.basename(this._scriptPath,St.extname(this._scriptPath));f!==this._name&&(d=i(a,`${f}-${e._name}`))}o=d||o}s=r.includes(St.extname(o));let l;pe.platform!=="win32"?s?(t.unshift(o),t=pc(pe.execArgv).concat(t),l=mi.spawn(pe.argv[0],t,{stdio:"inherit"})):l=mi.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=pc(pe.execArgv).concat(t),l=mi.spawn(pe.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{pe.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let u=this._exitCallback;l.on("close",d=>{d=d??1,u?u(new yi(d,"commander.executeSubCommandAsync","(close)")):pe.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
+ `),d=" ".repeat(n),p="\\s\u200B",h=new RegExp(`
7
+ |.{1,${a-1}}([${p}]|$)|[^${p}]+?([${p}]|$)`,"g"),c=u.match(h)||[];return l+c.map((m,y)=>m===`
8
+ `?"":(y>0?d:"")+m.trimEnd()).join(`
9
+ `)}};Dn.Help=ar});var dr=R(fr=>{var{InvalidArgumentError:Ga}=Ye(),cr=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Ya(e);this.short=n.shortFlag,this.long=n.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,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),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,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new Ga(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Xa(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ur=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return r.negate===(i===e)}};function Xa(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Ya(t){let e,r,n=t.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),r=n.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}fr.Option=cr;fr.DualOptions=ur});var jn=R(Ln=>{function Za(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=t.length;s++){let i=1;t[s-1]===e[n-1]?i=0:i=1,r[s][n]=Math.min(r[s-1][n]+1,r[s][n-1]+1,r[s-1][n-1]+i),s>1&&n>1&&t[s-1]===e[n-2]&&t[s-2]===e[n-1]&&(r[s][n]=Math.min(r[s][n],r[s-2][n-2]+1))}return r[t.length][e.length]}function Qa(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Za(t,o),l=Math.max(t.length,o.length);(l-a)/l>i&&(a<s?(s=a,n=[o]):a===s&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),r&&(n=n.map(o=>`--${o}`)),n.length>1?`
10
+ (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
11
+ (Did you mean ${n[0]}?)`:""}Ln.suggestSimilar=Qa});var Hn=R(Bn=>{var el=require("node:events").EventEmitter,hr=require("node:child_process"),re=require("node:path"),pr=require("node:fs"),j=require("node:process"),{Argument:tl,humanReadableArgName:rl}=ht(),{CommanderError:mr}=Ye(),{Help:nl}=lr(),{Option:Nn,DualOptions:sl}=dr(),{suggestSimilar:qn}=jn(),gr=class t extends el{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:r=>j.stdout.write(r),writeErr:r=>j.stderr.write(r),getOutHelpWidth:()=>j.stdout.isTTY?j.stdout.columns:void 0,getErrHelpWidth:()=>j.stderr.isTTY?j.stderr.columns:void 0,outputError:(r,n)=>n(r)},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 r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let s=r,i=n;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 t(e)}createHelp(){return Object.assign(new nl,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,r){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 r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new tl(e,r)}argument(e,r,n,s){let i=this.createArgument(e,r);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.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,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=r??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),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,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new mr(e,r,n)),j.exit(e)}action(e){let r=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=r,this}createOption(e,r){return new Nn(e,r)}_callParseArg(e,r,n,s){try{return e.parseArg(r,n)}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 r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let n=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 '${n}'
14
+ - already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=s=>[s.name()].concat(s.aliases()),n=r(e).find(s=>this._findCommand(s));if(n){let s=r(this._findCommand(n)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(n);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(n,i,a)};return this.on("option:"+r,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,r,n,s,i){if(typeof r=="object"&&r instanceof Nn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(r,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(l,u)=>{let d=a.exec(l);return d?d[0]:u},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,r,n,s){return this._optionEx({},e,r,n,s)}requiredOption(e,r,n,s){return this._optionEx({mandatory:!0},e,r,n,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,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){j.versions?.electron&&(r.from="electron");let s=j.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(r.from="eval")}e===void 0&&(e=j.argv),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":j.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,f){let p=re.resolve(d,f);if(pr.existsSync(p))return p;if(s.includes(re.extname(f)))return;let h=s.find(c=>pr.existsSync(`${p}${c}`));if(h)return`${p}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=pr.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=re.resolve(re.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=re.basename(this._scriptPath,re.extname(this._scriptPath));f!==this._name&&(d=i(a,`${f}-${e._name}`))}o=d||o}n=s.includes(re.extname(o));let l;j.platform!=="win32"?n?(r.unshift(o),r=Un(j.execArgv).concat(r),l=hr.spawn(j.argv[0],r,{stdio:"inherit"})):l=hr.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=Un(j.execArgv).concat(r),l=hr.spawn(j.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{j.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let u=this._exitCallback;l.on("close",d=>{d=d??1,u?u(new mr(d,"commander.executeSubCommandAsync","(close)")):j.exit(d)}),l.on("error",d=>{if(d.code==="ENOENT"){let f=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",p=`'${o}' does not exist
15
15
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${f}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)pe.exit(1);else{let f=new yi(1,"commander.executeSubCommandAsync","(error)");f.nestedError=d,u(f)}}),this.runningCommand=l}_dispatchSubcommand(e,t,s){let r=this._findCommand(e);r||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,r,"preSubcommand"),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(s));else return r._parseCommand(t,s)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,r,i)=>{let o=r;if(r!==null&&s.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,r,i,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((s,r)=>{let i=s.defaultValue;s.variadic?r<this.args.length?(i=this.args.slice(r),s.parseArg&&(i=i.reduce((o,a)=>e(s,a,o),s.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],s.parseArg&&(i=e(s,i,s.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let s=e,r=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{r.push({hookedCommand:i,callback:o})})}),t==="postAction"&&r.reverse(),r.forEach(i=>{s=this._chainOrCall(s,()=>i.callback(i.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,t,s){let r=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(i=>{r=this._chainOrCall(r,()=>i(this,t))}),r}_parseCommand(e,t){let s=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),t=s.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let r=s.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let r=e.find(i=>s.conflictsWith.includes(i.attributeName()));r&&this._conflictingOption(s,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],s=[],r=t,i=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){r===s&&r.push(l),r.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let u=this._findOption(l);if(u){if(u.required){let d=i.shift();d===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,d)}else if(u.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${u.name()}`,d)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),d=this._findOption(l.slice(0,u));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,l.slice(u+1));continue}}if(o(l)&&(r=s),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&s.length===0){if(this._findCommand(l)){t.push(l),i.length>0&&s.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){s.push(l),i.length>0&&s.push(...i);break}}if(this._passThroughOptions){r.push(l),i.length>0&&r.push(...i);break}r.push(l)}return{operands:t,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let s=0;s<t;s++){let r=this.options[s].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
17
+ - ${f}`;throw new Error(p)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)j.exit(1);else{let f=new mr(1,"commander.executeSubCommandAsync","(error)");f.nestedError=d,u(f)}}),this.runningCommand=l}_dispatchSubcommand(e,r,n){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,r.concat(n));else return s._parseCommand(r,n)}),i}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==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=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,a)=>e(n,a,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),r[s]=i}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[r]!==void 0).forEach(i=>{i._lifeCycleHooks[r].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),r==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,r))}),s}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.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,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):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(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],s=r,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===n&&s.push(l),s.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let u=this._findOption(l);if(u){if(u.required){let d=i.shift();d===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,d)}else if(u.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${u.name()}`,d)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),d=this._findOption(l.slice(0,u));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,l.slice(u+1));continue}}if(o(l)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(l)){r.push(l),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){r.push(l),i.length>0&&r.push(...i);break}else if(this._defaultCommandName){n.push(l),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(l),i.length>0&&s.push(...i);break}s.push(l)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){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 pe.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()}`,pe.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ay(this.options),t=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&t(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(r=>!t(r)).forEach(r=>{this.setOptionValueWithSource(r,s.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let s=o=>{let a=o.attributeName(),l=this.getOptionValue(a),u=this.options.find(f=>f.negate&&a===f.attributeName()),d=this.options.find(f=>!f.negate&&a===f.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:d||o},r=o=>{let a=s(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);r=r.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=fc(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=fc(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=>Sy(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=St.basename(e,St.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},s;return t.error?s=r=>this._outputConfiguration.writeErr(r):s=r=>this._outputConfiguration.writeOut(r),t.write=e.write||s,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let s=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let r=this.helpInformation(s);if(t&&(r=t(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",s))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=pe.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 pc(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})}hc.Command=bi});var vc=N(Ke=>{var{Argument:gc}=Is(),{Command:vi}=mc(),{CommanderError:ky,InvalidArgumentError:yc}=Un(),{Help:$y}=ui(),{Option:bc}=hi();Ke.program=new vi;Ke.createCommand=n=>new vi(n);Ke.createOption=(n,e)=>new bc(n,e);Ke.createArgument=(n,e)=>new gc(n,e);Ke.Command=vi;Ke.Option=bc;Ke.Argument=gc;Ke.Help=$y;Ke.CommanderError=ky;Ke.InvalidArgumentError=yc;Ke.InvalidOptionArgumentError=yc});var Sc={};Le(Sc,{DEFAULT_CONFIG:()=>qn,NVIDIA_PROVIDER:()=>Ft});var qn,Ft,Kn=L(()=>{"use strict";qn={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",contextBudget:2e5,streamingEnabled:!0,autoConfirmSafe:!0,autoMode:!1,workingDirectory:".",historySize:1e4,timeout:12e4,maxRetries:3,tools:{runCommand:{allowedCommands:[],blocklist:[],timeout:12e4}},ui:{theme:"dark",showTokenCount:!0,diffPreview:!0,compactMode:!1,dashboard:!1},cache:{enabled:!0,maxEntries:100,ttlMs:3e5},logging:{level:"info",file:!0},plugins:{enabled:!0,directory:"~/.hablas/plugins",marketplace:"https://registry.hablas.dev/plugins"},agents:{enabled:!0,orchestration:"auto",maxConcurrent:3},context:{astParsing:!0,projectGraph:!0,longTermMemory:!0,fileWatcher:!0},workspace:{frameworkDetection:!0,gitAwareness:!0,envParsing:!0,autoPush:!1},security:{scanOnCommit:!1,secretDetection:!0,dependencyAudit:!0},analytics:{enabled:!0,trackUsage:!0,weeklyReports:!1},collaboration:{enabled:!1,teamConfigPath:".hablas/team.json",sharedMemory:!1},team:{enabled:!1,user:"",key:""},api:{enabled:!1,port:8080,host:"0.0.0.0",apiKey:""},license:{tier:"free",key:""}},Ft={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.1-nemotron-70b-instruct","nvidia/nemotron-4-340b-instruct","meta/llama-3.1-405b-instruct","meta/llama-3.1-70b-instruct","meta/llama-3.1-8b-instruct","mistralai/mixtral-8x22b-instruct-v0.1","mistralai/mistral-large-latest","google/gemma-2-27b-it","microsoft/phi-3-medium-128k-instruct","deepseek-ai/deepseek-coder-33b-instruct","nvidia/llama-3.1-nemotron-51b-instruct","qwen/qwen2.5-coder-32b-instruct"]}});var Ds,_c=L(()=>{"use strict";Ds=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(s=>s.name):[]}catch{return[]}}async chatWithTools(e,t,s){let r={model:this.model,messages:e,stream:!1};t.length>0&&(r.tools=t);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)};s&&(i.signal=s);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,t){let s=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:t});if(!s.ok)throw new Error(`Ollama error: ${s.status} ${s.statusText}`);let r=s.body?.getReader();if(!r)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await r.read();if(a)break;o+=i.decode(l,{stream:!0});let u=o.split(`
24
- `);o=u.pop()||"";for(let d of u)if(d.trim())try{let f=JSON.parse(d);f.message?.content&&(yield f.message.content)}catch{}}}}});function $c(n){return n.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let t=e.tool_calls.filter(s=>s?.function?.name);if(t.length>0)return{role:"assistant",content:e.content||null,tool_calls:t.map((s,r)=>({id:`call_${r}`,type:"function",function:{name:s.function?.name||"",arguments:JSON.stringify(s.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function Ty(n){return n.map(e=>({type:"function",function:e.function}))}function Ry(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 Cc(n){return new Promise(e=>setTimeout(e,n))}function Ec(n,e){return!(n.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var Ac,Cy,Ls,kc,Ey,Gt,wi=L(()=>{"use strict";Ac=12e4,Cy=6e4,Ls=3,kc=1e3,Ey=20;Gt=class{apiUrl;apiKey;model;constructor(e){this.apiUrl=e.apiUrl||"https://api.openai.com/v1",this.apiKey=e.apiKey,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}setApiUrl(e){this.apiUrl=e}getApiUrl(){return this.apiUrl}setApiKey(e){this.apiKey=e}async checkConnection(){try{let e=this.apiUrl.replace(/\/+$/,"")+"/models";return(await fetch(e,{headers:this.getHeaders(),signal:AbortSignal.timeout(15e3)})).ok}catch{return!1}}async listModels(){try{let e=[],t=!0,s,r=0;for(;t&&r<Ey;){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(Cy)});if(!l.ok)break;let u=await l.json();if(Array.isArray(u))e.push(...u.map(d=>d.id||d.name||d).filter(Boolean)),t=!1;else if(u.data&&Array.isArray(u.data)){let d=u.data.map(f=>f.id||f.name).filter(Boolean);e.push(...d),u.has_more&&d.length>0?(s=d[d.length-1],r++):t=!1}else u.models&&Array.isArray(u.models)&&e.push(...u.models.map(d=>d.name||d.id).filter(Boolean)),t=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,t,s){let r=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:$c(e)};t.length>0&&(i.tools=Ty(t),i.tool_choice="auto");let o=null;for(let a=0;a<=Ls;a++)try{let l=new AbortController,u=setTimeout(()=>l.abort(),Ac),d={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:s||l.signal};try{let f=await fetch(r,d);if(clearTimeout(u),!f.ok){let g=await f.text().catch(()=>"");if(!Ec(null,f.status))throw new Error(`API error: ${f.status} ${f.statusText} \u2014 ${g}`);if(o=new Error(`API error: ${f.status} ${f.statusText} \u2014 ${g}`),a<Ls){let S=kc*Math.pow(2,a);await Cc(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?Ry(m.message.tool_calls):void 0;return{message:{role:m.message.role||"assistant",content:m.message.content||"",tool_calls:p},done:!0,done_reason:m.finish_reason}}catch(f){if(clearTimeout(u),f.name==="AbortError"&&s?.aborted)throw f;if(Ec(f)&&(o=f,a<Ls)){let h=kc*Math.pow(2,a);await Cc(h);continue}throw f}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Ls)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,t){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:$c(e),stream:!0}),signal:t||AbortSignal.timeout(Ac)});if(!r.ok)throw new Error(`API error: ${r.status} ${r.statusText}`);let i=r.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:u}=await i.read();if(l)break;a+=o.decode(u,{stream:!0});let d=a.split(`
25
- `);a=d.pop()||"";for(let f of d){let h=f.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let p=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;p&&(yield p)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}}});function Pe(n){if(n.provider==="nvidia"){let e={...n,provider:"custom",apiUrl:Ft.apiUrl};return new Gt(e)}return n.provider==="custom"&&n.apiUrl?new Gt(n):new Ds(n)}function Fs(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 Wn=L(()=>{"use strict";Kn();_c();wi()});var Tc=L(()=>{"use strict"});function Vt(){let n={providers:[],activeProvider:null,activeModel:null};try{if(_t.existsSync(Si)){let e=_t.readFileSync(Si,"utf-8"),t=JSON.parse(e);return{...n,...t}}}catch{}return n}function Ai(n){_t.existsSync(xi)||_t.mkdirSync(xi,{recursive:!0}),_t.writeFileSync(Si,JSON.stringify(n,null,2),"utf-8")}function Qe(n){let e=Vt();e.providers=e.providers.filter(t=>t.name!==n.name),e.providers.push(n),Ai(e)}function Oc(n){let e=Vt(),t=e.providers.length;return e.providers=e.providers.filter(s=>s.name!==n),e.providers.length<t?(e.activeProvider===n&&(e.activeProvider=null,e.activeModel=null),Ai(e),!0):!1}function Pc(n){return Vt().providers.find(t=>t.name.toLowerCase()===n.toLowerCase())}function Ns(){return Vt().providers}function Mc(n,e){let t=Vt(),s=t.providers.find(r=>r.name===n);s&&(t.activeProvider=n,t.activeModel=e||s.defaultModel,Ai(t))}function Ic(n,e){if(n.length===0)return" No saved providers. Use /addmodel to add one.";let t=[];t.push(" Saved Providers:"),t.push("");for(let s of n){let r=s.name===e,i=r?" \u25CF active":"",o=s.apiKey?"***"+s.apiKey.slice(-4):"no key";t.push(` ${r?"\u25B8":"\xB7"} ${s.name}${i}`),t.push(` URL: ${s.apiUrl}`),t.push(` Key: ${o}`),t.push(` Model: ${s.defaultModel}`),t.push(` Added: ${new Date(s.addedAt).toLocaleDateString()}`),t.push("")}return t.join(`
26
- `)}var _t,_i,Rc,xi,Si,ki=L(()=>{"use strict";_t=O(require("fs")),_i=O(require("path")),Rc=O(require("os"));Tc();xi=_i.join(Rc.homedir(),".hablas"),Si=_i.join(xi,"models.json")});function Bs(){try{if(At.existsSync(js))return JSON.parse(At.readFileSync(js,"utf-8"))}catch{}return{}}function Lc(n){let e=Hs.dirname(js);At.existsSync(e)||At.mkdirSync(e,{recursive:!0}),At.writeFileSync(js,JSON.stringify(n,null,2),"utf-8")}function Fc(n,e){let t=Bs();t[n]=e,Lc(t)}function Nc(n){let e=Bs();return e[n]?(delete e[n],Lc(e),!0):!1}function jc(n){let e=Bs(),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 Hc(){let n=Bs(),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 At,Hs,Dc,js,$i=L(()=>{"use strict";At=O(require("fs")),Hs=O(require("path")),Dc=O(require("os")),js=Hs.join(Dc.homedir(),".hablas","aliases.json")});var qc={};Le(qc,{disablePlugin:()=>Ri,enablePlugin:()=>Ti,ensurePluginsDir:()=>Ks,listPlugins:()=>Uc,renderPlugins:()=>Oi});function Ei(){try{if(Fe.existsSync(qs))return JSON.parse(Fe.readFileSync(qs,"utf-8"))}catch{}return{disabled:[]}}function Bc(n){let e=fn.dirname(qs);Fe.existsSync(e)||Fe.mkdirSync(e,{recursive:!0}),Fe.writeFileSync(qs,JSON.stringify(n,null,2),"utf-8")}function Ks(){Fe.existsSync(Us)||Fe.mkdirSync(Us,{recursive:!0})}function Uc(){Ks();let n=Ei(),e=[];try{let t=Fe.readdirSync(Us).filter(s=>s.endsWith(".js"));for(let s of t){let r=fn.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),Bc(e),!0):!1}function Ri(n){let e=Ei();return e.disabled.includes(n)?!1:(e.disabled.push(n),Bc(e),!0)}function Oi(){let n=Uc();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 Fe,fn,Ci,Us,qs,Pi=L(()=>{"use strict";Fe=O(require("fs")),fn=O(require("path")),Ci=O(require("os")),Us=fn.join(Ci.homedir(),".hablas","plugins"),qs=fn.join(Ci.homedir(),".hablas","plugins.json")});var Gc={};Le(Gc,{renderDiagnostics:()=>Di,runDiagnostics:()=>Ii});async function Ii(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=Kc.join(Ze.homedir(),".hablas");if(e.push({name:"Config directory",status:Mi.existsSync(r)?"ok":"warn",message:Mi.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=Ze.homedir();if(process.platform!=="win32"){let a=(0,Wc.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",u=a[4]||"?";e.push({name:"Disk space",status:parseInt(u)>90?"warn":"ok",message:`${l} available (${u} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:n.model?"ok":"warn",message:n.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${Ze.platform()} ${Ze.arch()} \u2014 ${Ze.cpus().length} cores, ${Math.round(Ze.totalmem()/1024/1024/1024)}GB RAM`}),e}function Di(n){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},t={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},s="\x1B[0m",r="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of n){let u=`${t[l.status]}${e[l.status]}${s}`,d=l.name.padEnd(18);i.push(` ${u} ${d}${r}${l.message}${s}`)}let o=n.filter(l=>l.status==="error").length,a=n.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${t.error}${o} error(s) found \u2014 fix these for hablas to work properly${s}`):a>0?i.push(` ${t.warn}${a} warning(s) \u2014 hablas should work but check the items above${s}`):i.push(` ${t.ok}All checks passed \u2014 hablas is ready!${s}`),i.push(""),i.join(`
33
- `)}var Mi,Kc,Ze,Wc,Li=L(()=>{"use strict";Mi=O(require("fs")),Kc=O(require("path")),Ze=O(require("os")),Wc=require("child_process")});function Vc(){let n=[];for(let e of we){let s=e.role==="hablas"?" \u2605":"";n.push(` @${e.name}${s} \u2014 ${e.title}`),n.push(` ${e.description}`)}return n.join(`
34
- `)}var we,Ws=L(()=>{"use strict";we=[{role:"hablas",name:"Hablas",title:"Team Leader",description:"Software Engineer & Team Coordinator. Receives user requests, creates plans, distributes tasks, and compiles final responses.",expertise:["planning","coordination","architecture","code-review","decision-making"]},{role:"bob",name:"Bob",title:"Architect",description:"System Architect. Designs software architecture, database schemas, API structures, and system blueprints.",expertise:["system-design","architecture","database","api-design","scalability"]},{role:"alex",name:"Alex",title:"Engineer",description:"Full-Stack Engineer. Implements code, builds features, fixes bugs, handles DevOps and deployment.",expertise:["coding","implementation","debugging","devops","testing","deployment"]},{role:"david",name:"David",title:"Data Analyst",description:"Data & Research Specialist. Handles research, data analysis, documentation, and information gathering.",expertise:["research","data-analysis","documentation","ml","optimization"]},{role:"emma",name:"Emma",title:"Product Manager",description:"Product Manager. Analyzes user needs, creates PRDs, competitive analysis, market research, and requirement specifications.",expertise:["product-management","requirements","prd","market-research","competitive-analysis","user-stories"]}]});function zt(){try{if(kt.existsSync(Gn)){let n=kt.readFileSync(Gn,"utf-8"),e=JSON.parse(n);return{...zc,...e}}}catch{}return{...zc}}function Fi(n){let e=Gs.dirname(Gn);kt.existsSync(e)||kt.mkdirSync(e,{recursive:!0}),kt.writeFileSync(Gn,JSON.stringify(n,null,2),"utf-8")}function Ni(){return Gn}var kt,Gs,Yc,Gn,zc,ji=L(()=>{"use strict";kt=O(require("fs")),Gs=O(require("path")),Yc=O(require("os")),Gn=Gs.join(Yc.homedir(),".hablas","agents.json"),zc={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 Vi={};Le(Vi,{formatStats:()=>Iy,loadStats:()=>Vn,saveStats:()=>pn,trackAgentUsage:()=>Gi,trackFileModified:()=>Py,trackMessage:()=>Ki,trackSession:()=>qi,trackToolCall:()=>Wi});function Vn(){try{if($t.existsSync(Bi))return JSON.parse($t.readFileSync(Bi,"utf-8"))}catch{}return Oy()}function pn(n){try{$t.existsSync(Hi)||$t.mkdirSync(Hi,{recursive:!0}),$t.writeFileSync(Bi,JSON.stringify(n,null,2))}catch{}}function Oy(){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 qi(n){return n.totalSessions++,n.lastUsed=new Date().toISOString(),My(n),n}function Ki(n,e=0){n.totalMessages++,n.totalTokensUsed+=e;let t=Vs();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 Wi(n,e){n.totalToolCalls++,n.commandUsage[e]=(n.commandUsage[e]||0)+1;let t=Vs();return n.dailyActivity[t]||(n.dailyActivity[t]={messages:0,tokens:0,toolCalls:0,filesModified:0,linesWritten:0}),n.dailyActivity[t].toolCalls++,n}function Gi(n,e){return n.agentUsage[e]=(n.agentUsage[e]||0)+1,n}function Py(n,e=0){n.totalFilesModified++,n.totalLinesWritten+=e;let t=Vs();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 My(n){let e=Vs(),t=Xc(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 Vs(){return Xc(new Date)}function Xc(n){return n.toISOString().split("T")[0]}function Iy(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 $t,Ui,Jc,Hi,Bi,zn=L(()=>{"use strict";$t=O(require("fs")),Ui=O(require("path")),Jc=O(require("os")),Hi=Ui.join(Jc.homedir(),".hablas"),Bi=Ui.join(Hi,"analytics.json")});var Zc={};Le(Zc,{formatScanResults:()=>Yi,runSecurityScan:()=>zi});function Ny(n,e){let t=[],s=e.split(`
37
- `);for(let{pattern:r,name:i,severity:o}of Dy){r.lastIndex=0;let a;for(;(a=r.exec(e))!==null;){let u=e.substring(0,a.index).split(`
38
- `).length,d=s[u-1]||"";d.trim().startsWith("#")||d.trim().startsWith("//")||n.includes(".example")||n.includes(".sample")||t.push({severity:o,type:"secret",file:n,line:u,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return t}function jy(n,e){let t=[],s=e.split(`
39
- `),r=Yt.extname(n);return[".ts",".js",".tsx",".jsx"].includes(r)&&s.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&t.push({severity:"high",type:"code",file:n,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&t.push({severity:"medium",type:"code",file:n,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&t.push({severity:"high",type:"code",file:n,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),t}function Qc(n,e=[]){try{let t=zs.readdirSync(n,{withFileTypes:!0});for(let s of t){if(Ly.has(s.name))continue;let r=Yt.join(n,s.name);if(s.isDirectory())Qc(r,e);else if(s.isFile()){let i=Yt.extname(s.name);Fy.has(i)||e.push(r)}}}catch{}return e}function zi(n){let e=Date.now(),t=Qc(n),s=[];for(let o of t)try{let a=zs.readFileSync(o,"utf-8"),l=Yt.relative(n,o),u=Ny(l,a);s.push(...u);let d=jy(l,a);s.push(...d)}catch{}let r=Date.now()-e,i={critical:s.filter(o=>o.severity==="critical").length,high:s.filter(o=>o.severity==="high").length,medium:s.filter(o=>o.severity==="medium").length,low:s.filter(o=>o.severity==="low").length,info:s.filter(o=>o.severity==="info").length};return{issues:s,scannedFiles:t.length,duration:r,summary:i}}function Yi(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 zs,Yt,Dy,Ly,Fy,Ji=L(()=>{"use strict";zs=O(require("fs")),Yt=O(require("path")),Dy=[{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"}],Ly=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Fy=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"])});var Yn={};Le(Yn,{formatGitStatus:()=>Gy,generateChangelogPrompt:()=>Wy,generateCommitPrompt:()=>qy,generatePRPrompt:()=>Ky,getDetailedDiff:()=>By,getGitStatus:()=>Xi,getRecentCommits:()=>Uy,getStagedDiff:()=>Hy});async function Xi(n){try{let{stdout:e}=await hn("git branch --show-current",{cwd:n}),{stdout:t}=await hn("git status --porcelain",{cwd:n}),s=e.trim(),r=[],i=[],o=[];for(let u of t.split(`
42
- `).filter(Boolean)){let d=u.substring(0,2),f=u.substring(3);(d.startsWith("A")||d.startsWith("M")||d.startsWith("R"))&&d[0]!==" "&&r.push(f),(d[1]==="M"||d[1]==="D")&&i.push(f),d==="??"&&o.push(f)}let a=0,l=0;try{let{stdout:u}=await hn("git rev-list --left-right --count HEAD...@{upstream}",{cwd:n}),d=u.trim().split(" ");a=parseInt(d[0])||0,l=parseInt(d[1])||0}catch{}return{branch:s,staged:r,modified:i,untracked:o,ahead:a,behind:l}}catch{return null}}async function Hy(n){try{let{stdout:e}=await hn("git diff --cached --stat",{cwd:n});return e.trim()}catch{return""}}async function By(n){try{let{stdout:e}=await hn("git diff --cached",{cwd:n,maxBuffer:1048576});return e.length>1e4?e.substring(0,1e4)+`
43
- ... (truncated)`:e.trim()}catch{return""}}async function Uy(n,e=20){try{let{stdout:t}=await hn(`git log --oneline --format="%H|%s|%an|%ai" -n ${e}`,{cwd:n});return t.trim().split(`
44
- `).filter(Boolean).map(s=>{let[r,i,o,a]=s.split("|");return{hash:r,message:i,author:o,date:a,files:[]}})}catch{return[]}}function qy(n,e){return`Based on the following git diff, generate a concise, conventional commit message.
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 Ky(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 Wy(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)
91
-
92
- ### Changed
93
- - (changes to existing features)
94
-
95
- ### Fixed
96
- - (bug fixes)
97
-
98
- ### Removed
99
- - (removed features)
100
-
101
- Only include sections that have entries. Generate ONLY the changelog markdown.`}function Gy(n){let e=[];return e.push(` Branch: ${n.branch}`),(n.ahead>0||n.behind>0)&&e.push(` Sync: \u2191${n.ahead} \u2193${n.behind}`),n.staged.length>0&&e.push(` Staged: ${n.staged.length} file(s)`),n.modified.length>0&&e.push(` Modified: ${n.modified.length} file(s)`),n.untracked.length>0&&e.push(` Untracked: ${n.untracked.length} file(s)`),e.join(`
102
- `)}var eu,tu,hn,mn=L(()=>{"use strict";eu=require("child_process"),tu=require("util"),hn=(0,tu.promisify)(eu.exec)});var ou={};Le(ou,{detectFramework:()=>nu,detectLanguage:()=>ru,detectPackageManager:()=>su,formatWorkspaceInfo:()=>Qi,getGitBranch:()=>iu,scanWorkspace:()=>Ys});function nu(n){let e=z.join(n,"package.json");if(G.existsSync(e))try{let t=JSON.parse(G.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(G.existsSync(z.join(n,"requirements.txt"))||G.existsSync(z.join(n,"pyproject.toml")))try{let t=G.existsSync(z.join(n,"requirements.txt"))?G.readFileSync(z.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(G.existsSync(z.join(n,"Cargo.toml")))try{if(G.readFileSync(z.join(n,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(G.existsSync(z.join(n,"go.mod")))try{if(G.readFileSync(z.join(n,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function su(n){return G.existsSync(z.join(n,"pnpm-lock.yaml"))?"pnpm":G.existsSync(z.join(n,"yarn.lock"))?"yarn":G.existsSync(z.join(n,"bun.lockb"))?"bun":G.existsSync(z.join(n,"package-lock.json"))?"npm":G.existsSync(z.join(n,"Cargo.toml"))?"cargo":G.existsSync(z.join(n,"go.mod"))?"go":G.existsSync(z.join(n,"requirements.txt"))||G.existsSync(z.join(n,"pyproject.toml"))?"pip":"unknown"}function ru(n){return G.existsSync(z.join(n,"tsconfig.json"))?"TypeScript":G.existsSync(z.join(n,"package.json"))?"JavaScript":G.existsSync(z.join(n,"Cargo.toml"))?"Rust":G.existsSync(z.join(n,"go.mod"))?"Go":G.existsSync(z.join(n,"pyproject.toml"))||G.existsSync(z.join(n,"requirements.txt"))?"Python":"Unknown"}function iu(n){let e=z.join(n,".git","HEAD");if(!G.existsSync(e))return null;try{let t=G.readFileSync(e,"utf-8").trim();return t.startsWith("ref: refs/heads/")?t.replace("ref: refs/heads/",""):t.substring(0,8)}catch{return null}}function Ys(n){let e=nu(n),t=su(n),s=ru(n),r=iu(n),i=G.existsSync(z.join(n,"Dockerfile"))||G.existsSync(z.join(n,"docker-compose.yml"))||G.existsSync(z.join(n,"docker-compose.yaml")),o=G.existsSync(z.join(n,".github","workflows"))||G.existsSync(z.join(n,".gitlab-ci.yml"))||G.existsSync(z.join(n,"Jenkinsfile")),a=G.existsSync(z.join(n,"__tests__"))||G.existsSync(z.join(n,"tests"))||G.existsSync(z.join(n,"test"))||G.existsSync(z.join(n,"spec")),l=G.existsSync(z.join(n,".git")),u=[],d=[".env",".env.local",".env.development",".env.production",".env.example"];for(let g of d)G.existsSync(z.join(n,g))&&u.push(g);let f=[],h=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let g of h)G.existsSync(z.join(n,g))&&f.push(g);let m=[],p=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let g of p)G.existsSync(z.join(n,g))&&m.push(g);return{rootPath:n,framework:e,packageManager:t,language:s,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:r,envFiles:u,configFiles:f,entryPoints:m}}function Qi(n){let e=[` Project: ${z.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 G,z,Zi=L(()=>{"use strict";G=O(require("fs")),z=O(require("path"))});function au(){return`
104
- ## Available Tools (XML Format)
105
-
106
- You can use tools by outputting XML tags in your response. The system will parse and execute them.
107
-
108
- ### read_file \u2014 Read a file's contents
109
- \`\`\`
110
- <read_file path="src/index.ts" />
111
- \`\`\`
112
-
113
- ### write_file \u2014 Create or overwrite a file
114
- \`\`\`
115
- <write_file path="src/hello.ts">
116
- export function hello() {
117
- return "Hello, world!";
118
- }
119
- </write_file>
120
- \`\`\`
121
-
122
- ### edit_file \u2014 Search and replace in a file
123
- \`\`\`
124
- <edit_file path="src/index.ts" search="old code here" replace="new code here" />
125
- \`\`\`
126
-
127
- ### run_command \u2014 Execute a shell command
128
- \`\`\`
129
- <run_command>npm install express</run_command>
130
- \`\`\`
131
-
132
- ### search_codebase \u2014 Search for patterns in the project
133
- \`\`\`
134
- <search_codebase query="function handleAuth" />
135
- \`\`\`
136
-
137
- ### list_dir \u2014 List directory contents
138
- \`\`\`
139
- <list_dir path="src/" />
140
- \`\`\`
141
-
142
- ### create_dir \u2014 Create a directory
143
- \`\`\`
144
- <create_dir path="src/utils/" />
145
- \`\`\`
146
-
147
- ### delete_file \u2014 Delete a file
148
- \`\`\`
149
- <delete_file path="src/old-file.ts" />
150
- \`\`\`
151
-
152
- ### Rules:
153
- 1. You may use multiple tools in a single response.
154
- 2. Include explanation text before/after tool tags.
155
- 3. Wait for tool results before using dependent tools.
156
- 4. Use exact file paths relative to the working directory.
157
- 5. Do NOT wrap tool tags in <tool_call > tags \u2014 use them directly.
158
- `.trim()}var lu=L(()=>{"use strict"});function Vy(){let n=[Jn.resolve(__dirname,"..","..","package.json"),Jn.resolve(__dirname,"..","package.json"),Jn.resolve(process.cwd(),"package.json"),Jn.resolve(__dirname,"..","..","..","package.json")];for(let e of n)try{if(Js.existsSync(e)){let t=JSON.parse(Js.readFileSync(e,"utf-8"));if(t.version)return t.version}}catch{}return"0.0.0"}function he(n,e){return du||!gn?n:`${e}${n}\x1B[0m`}function zy(n){let e=je();if(!n)return c.border("\u2500".repeat(e));let t=n.replace(/\x1b\[[0-9;]*m/g,""),s=Math.max(0,e-t.length-2),r=Math.floor(s/2),i=s-r;return c.border("\u2500".repeat(r))+" "+n+" "+c.border("\u2500".repeat(i))}function Yy(n,e=2){let t=je()-e;if(t<=0)return" ".repeat(e)+n;let s=n.split(" "),r=[],i="";for(let o of s)(i+" "+o).trim().length>t&&i?(r.push(i.trim()),i=o):i+=(i?" ":"")+o;return i&&r.push(i.trim()),r.map(o=>" ".repeat(e)+o).join(`
159
- `)}function Jy(n){let e=Math.max(...n.map(([t])=>t.length));return n.map(([t,s])=>` ${c.muted(t.padEnd(e))} ${s}`).join(`
160
- `)}function Xy(n){if(du||!gn)return n;let e=["\x1B[38;5;111m","\x1B[38;5;111m","\x1B[38;5;141m","\x1B[38;5;141m","\x1B[38;5;117m","\x1B[38;5;117m"],t="";for(let s=0;s<n.length;s++){let r=Math.floor(s/n.length*e.length);t+=e[r]+n[s]}return t+"\x1B[0m"}function pu(n,e){let t=je(),s=e?e.replace(no.homedir(),"~"):"",r=c.border("\u2554"+"\u2550".repeat(t-2)+"\u2557"),i=c.border("\u2560"+"\u2550".repeat(t-2)+"\u2563"),o=c.border("\u255A"+"\u2550".repeat(t-2)+"\u255D"),a="H A B L A S A I",l="EXECUTIVE SYSTEM COORDINATOR",u="developed by abdulmoin hablas",d=Math.max(0,Math.floor((t-2-a.length)/2)),f=c.border("\u2551")+" ".repeat(d)+c.strong(a)+" ".repeat(t-2-a.length-d)+c.border("\u2551"),h=Math.max(0,Math.floor((t-2-l.length)/2)),m=c.border("\u2551")+" ".repeat(h)+c.secondary(l)+" ".repeat(t-2-l.length-h)+c.border("\u2551"),p=Math.max(0,Math.floor((t-2-u.length)/2)),g=c.border("\u2551")+" ".repeat(p)+c.muted(u)+" ".repeat(t-2-u.length-p)+c.border("\u2551"),S=c.muted(`SYSTEM VERSION: v${uu}`),x=c.warning(`CORE MODEL: ${n}`);return["",r,f,m,u?g:"",i,` ${c.muted("\u25B8")} ${S}`,` ${c.muted("\u25B8")} ${x}`,s?` ${c.muted("\u25B8")} ${c.muted(`WORKSPACE: ${s}`)}`:"",` ${c.chrome("\u251C"+"\u2500".repeat(t-2)+"\u2524")}`,` ${c.muted(" \u203A")} ${c.secondary("Type naturally to get started")}`,` ${c.muted(" \u203A")} ${c.secondary("/help for commands \xB7 Ctrl+C to cancel \xB7 Ctrl+C\xD72 to exit")}`,o,""].filter(Boolean).join(`
161
- `)}function hu(){let n=je();return[` ${c.border("\u2554"+"\u2550".repeat(n-4)+"\u2557")}`,` ${c.border("\u2551")} ${c.leader("\u2605 Hablas")} ${c.muted("Leader")} ${c.border("\u2551")} ${c.product("\u25C6 Emma")} ${c.muted("Product")} ${c.border("\u2551")} ${c.architect("\u25C6 Bob")} ${c.muted("Architect")} ${c.border("\u2551")} ${c.engineer("\u25C6 Alex")} ${c.muted("Engineer")} ${c.border("\u2551")} ${c.analyst("\u25C6 David")} ${c.muted("Analyst")} ${c.border("\u2551")}`,` ${c.border("\u255A"+"\u2550".repeat(n-4)+"\u255D")}`].join(`
162
- `)}function Jt(n,e){return`
163
- ${(n==="Hablas"?c.leader:n==="Bob"?c.architect:n==="Alex"?c.engineer:n==="David"?c.analyst:n==="Emma"?c.product:c.primary)("\u25C6")} ${c.strong(n)} ${c.muted(`[${e.toUpperCase()}]`)}`}function mu(n,e,t,s){let r=n==="Hablas"?c.leader:n==="Bob"?c.architect:n==="Alex"?c.engineer:n==="David"?c.analyst:n==="Emma"?c.product:c.primary,i=e==="Hablas"?c.leader:e==="Bob"?c.architect:e==="Alex"?c.engineer:e==="David"?c.analyst:e==="Emma"?c.product:c.primary,o=[];if(o.push(""),o.push(` ${r("\u2605")} ${r(n)} ${c.muted("\u2192")} ${c.strong("Delegating to")} ${i(`@${e}`)} ${c.muted(`(${t})`)}`),s){let a=s.length>80?s.slice(0,80)+"...":s;o.push(` ${c.muted(" \u2517")} ${c.secondary(a)}`)}return o.push(""),o.join(`
164
- `)}function gu(){let n=je(),t=[` ${c.accent("\u2726")} ${c.strong("Welcome to hablas")}`,"",` ${c.muted("Try:")} ${c.highlight('"read package.json and list deps"')}`,` ${c.muted("Or:")} ${c.highlight('"create a new component for user auth"')}`,"",` ${c.primary("/tree")} ${c.muted("\u2014 see project structure")}`,` ${c.primary("/model")} ${c.muted("\u2014 switch AI model")}`,` ${c.primary("/models")} ${c.muted("\u2014 browse all available models")}`,` ${c.primary("/team")} ${c.muted("\u2014 see your agent team")}`,` ${c.primary("/about")} ${c.muted("\u2014 developer info")}`,"",` ${c.muted("All file changes are backed up automatically.")}`].map(s=>{let r=s.replace(/\x1b\[[0-9;]*m/g,""),i=Math.max(0,n-8-r.length);return` ${c.border("\u2502")} ${s}${" ".repeat(i)} ${c.border("\u2502")}`});return["",` ${c.border("\u250C"+"\u2500".repeat(n-6)+"\u2510")}`,...t,` ${c.border("\u2514"+"\u2500".repeat(n-6)+"\u2518")}`,""].join(`
165
- `)}function yu(){let n=je();return["",c.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E"),` ${c.strong("Abdulmoin Hablas")} ${c.muted("\u2014 Full-Stack Developer")}`,c.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),"",` ${c.accent("\u25C6")} ${c.primary("Portfolio")} ${c.muted("https://portfolio-monopoly63s-projects.vercel.app/")}`,` ${c.accent("\u25C6")} ${c.primary("GitHub")} ${c.muted("https://github.com/Monopoly63?tab=repositories")}`,` ${c.accent("\u25C6")} ${c.primary("Telegram")} ${c.muted("https://t.me/Hablas_Trade")}`,` ${c.accent("\u25C6")} ${c.primary("WhatsApp")} ${c.muted("https://wa.me/13232128875")}`,` ${c.accent("\u25C6")} ${c.primary("Instagram")} ${c.muted("https://www.instagram.com/li0vy_")}`,"",c.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),` ${c.strong("Projects")}`,"",` ${c.muted("\u25B8")} AI Search Engine ${c.muted("\u2192")} ${c.highlight("https://ai-search-engine-ashy.vercel.app/")}`,` ${c.muted("\u25B8")} Trade Tracker ${c.muted("\u2192")} ${c.highlight("https://trade-tracker-monopoly63s-projects.vercel.app/")}`,` ${c.muted("\u25B8")} Tree Algo Lab ${c.muted("\u2192")} ${c.highlight("https://tree-algorithms-lab.vercel.app/")}`,"",c.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F"),""].join(`
166
- `)}function bu(){return["",` ${Xy("\u25C6 hablas")} ${c.success(`v${uu}`)}`,"",` ${c.muted("Runtime")} ${c.secondary(`Node.js ${process.version}`)}`,` ${c.muted("Platform")} ${c.secondary(`${process.platform} ${process.arch}`)}`,` ${c.muted("Author")} ${c.secondary("Abdulmoin Hablas")}`,` ${c.muted("License")} ${c.secondary("MIT")}`,""].join(`
167
- `)}function cu(n,e){let t=Math.min(je()-8,60),s=e?` ${c.accent(e)} `:"",r=`${c.error("\u25CF")} ${c.warning("\u25CF")} ${c.success("\u25CF")}`,i=` ${c.chrome("\u250C"+"\u2500".repeat(4))} ${r} ${c.chrome("\u2500".repeat(Math.max(0,t-10-(e?e.length+2:0))))}${s}`,o=String(n.length).length,a=n.map((u,d)=>{let f=c.lineNum(String(d+1).padStart(o)+" \u2502 "),h=c.codeBlock(u);return` ${c.chrome("\u2502")} ${f}${h}`}),l=` ${c.chrome("\u2514"+"\u2500".repeat(t))}`;return[i,...a,l]}function Xt(n){let e=n.split(`
168
- `),t=[],s=!1,r="",i=[];for(let o of e){if(o.trimStart().startsWith("```")){s?(t.push(...cu(i,r)),s=!1,i=[]):(s=!0,r=o.trimStart().slice(3).trim(),i=[]);continue}if(s){i.push(o);continue}if(/^#{1,3}\s/.test(o)){let l=o.replace(/^#+\s/,"");t.push(""),t.push(` ${c.strong(c.primary(l))}`);continue}if(/^[-*]\s/.test(o.trim())){let l=o.trim().slice(2),u=eo(l);t.push(` ${c.accent("\u25B8")} ${u}`);continue}if(/^\d+\.\s/.test(o.trim())){let l=o.trim().match(/^(\d+)\.\s(.+)/);if(l){t.push(` ${c.muted(l[1]+".")} ${eo(l[2])}`);continue}}if(!o.trim()){t.push("");continue}let a=Yy(eo(o),2);t.push(...a.split(`
169
- `))}return s&&i.length>0&&t.push(...cu(i,r)),`
170
- `+t.join(`
171
- `)+`
172
- `}function eo(n){let e=n.replace(/`([^`]+)`/g,(t,s)=>c.highlight(s));return e=e.replace(/\*\*([^*]+)\*\*/g,(t,s)=>c.strong(c.primary(s))),e=e.replace(/\*([^*]+)\*/g,(t,s)=>`\x1B[3m${s}\x1B[23m`),e}function vu(n,e){let t=je(),s=` [TOOL: ${n.replace(/_/g," ").toUpperCase()}] `,r=` ${c.border("\u250C\u2500\u2500")}${c.accent(s)}${c.border("\u2500".repeat(Math.max(0,t-s.length-6)))}`,i=` ${c.border("\u2502")} ${c.secondary(e)}`,o=i.replace(/\x1b\[[0-9;]*m/g,""),a=Math.max(0,t-8-o.length);return`
173
- ${r}
174
- ${i}${" ".repeat(a)} ${c.border("\u2502")}`}function wu(n,e,t){let s=je(),r=c.muted(`${t}ms`),i="";if(n){let u=e.split(`
175
- `).filter(Boolean),d=u.length;if(d>5){let f=u[0].slice(0,s-30).trim();i=` ${c.border("\u2502")} ${c.success("\u2713")} ${c.muted(`${d} lines`)} ${c.secondary(f+"\u2026")} ${r}`}else{let f=u.join(" \xB7 ").slice(0,s-24);i=` ${c.border("\u2502")} ${c.success("\u2713")} ${c.muted(f)} ${r}`}}else{let u=e.split(`
176
- `)[0].slice(0,s-24);i=` ${c.border("\u2502")} ${c.error("\u2717")} ${c.error(u)} ${r}`}let o=i.replace(/\x1b\[[0-9;]*m/g,""),a=Math.max(0,s-8-o.length),l=` ${c.border("\u2514"+"\u2500".repeat(s-6)+"\u2518")}`;return`${i}${" ".repeat(a)} ${c.border("\u2502")}
177
- ${l}
178
- `}function so(n){let e=n.split(`
179
- `),t=[];for(let s of e)s.startsWith("+++")||s.startsWith("---")?t.push(` ${c.muted(s)}`):s.startsWith("+")?t.push(` ${c.added(s)}`):s.startsWith("-")?t.push(` ${c.removed(s)}`):s.startsWith("@@")?t.push(` ${c.hunk(s)}`):s.trim()&&t.push(` ${c.muted(s)}`);return t.join(`
180
- `)}function xu(n){let e=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"}),t=`${c.accent("\u25C6")} ${c.strong(c.primary(`Turn #${n}`))} ${c.muted(`\xB7 ${e} \xB7`)}`;return`
181
- `+zy(t)+`
182
- `}function _e(n){return` ${c.error("\u2717")} ${n}`}function He(n,e){return` ${c.error("\u2717")} ${n}
183
- ${c.warning("\u2192")} ${c.muted(e)}`}function Y(n){return` ${c.success("\u2713")} ${n}`}function fe(n){return` ${c.muted(n)}`}function j(n){return` ${c.warning("\u26A0")} ${n}`}function Qy(n,e){let s=Math.round(Math.min(n,e)/Math.max(e,1)*16),r=e>0?n/e:0;return(r>.85?c.error:r>.6?c.warning:c.success)("\u2588".repeat(s))+c.muted("\u2591".repeat(16-s))}function Su(n){let e=je(),t=n.connected?c.success("\u25CF connected"):c.error("\u25CB offline"),s=Qy(n.cacheTokens,n.budgetTokens),r=[["model",c.highlight(n.model)],["mindset",c.accent(n.mindset||"coder")],["host",c.muted(n.host)],["directory",c.muted(n.directory.replace(no.homedir(),"~"))],["context",`${s} ${c.muted(`${n.cacheFiles} files \xB7 ${n.cacheTokens}/${n.budgetTokens} tokens`)}`],["turns",c.muted(String(n.turnCount))],["status",t]];return`
184
- `+c.chrome("\u256D"+"\u2500".repeat(e-2)+"\u256E")+`
185
- ${c.accent("\u2726")} ${c.strong("Status")}
186
-
187
- `+Jy(r)+`
188
-
189
- `+c.chrome("\u2570"+"\u2500".repeat(e-2)+"\u256F")+`
190
- `}function _u(){let n=je(),e=Math.max(...to.map(r=>r.cmd.length+(r.arg?r.arg.length+1:0))),t=to.map(({cmd:r,arg:i,desc:o})=>{let a=r.length+(i?i.length+1:0),l=" ".repeat(e-a+3);return` ${c.primary(r)}${i?" "+c.muted(i):""}${l}${c.secondary(o)}`}),s=["",` ${c.accent("\u2726")} ${c.strong("Tips")}`,"",` ${c.muted("\u25B8")} Use ${c.highlight("#filename")} to reference files inline`,` ${c.muted("\u25B8")} Press ${c.highlight("Ctrl+C")} once to cancel current operation`,` ${c.muted("\u25B8")} Press ${c.highlight("Ctrl+C\xD72")} quickly to exit CLI`,` ${c.muted("\u25B8")} Use ${c.highlight("--auto")} flag to skip tool confirmations`,` ${c.muted("\u25B8")} All file edits are backed up to ${c.muted("~/.hablas/backup/")}`,` ${c.muted("\u25B8")} Serious engineering work is routed internally to the specialist team when needed`];return`
191
- `+c.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E")+`
192
- ${c.accent("\u2726")} ${c.strong("Commands")}
193
-
194
- `+t.join(`
195
- `)+`
196
- `+s.join(`
197
- `)+`
198
-
199
- `+c.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F")+`
200
- `}function ro(n){let e=Math.floor(n.duration/6e4),t=Math.floor(n.duration%6e4/1e3),s=e>0?`${e}m ${t}s`:`${t}s`;return["",c.chrome("\u256D"+"\u2500".repeat(40)+"\u256E"),` ${c.accent("\u2726")} ${c.strong("Session Summary")}`,"",` ${c.muted("Turns")} ${c.secondary(String(n.turns))}`,` ${c.muted("Duration")} ${c.secondary(s)}`,` ${c.muted("Tool calls")} ${c.secondary(String(n.toolCalls))}`,"",c.chrome("\u2570"+"\u2500".repeat(40)+"\u256F"),"",` ${c.muted("Goodbye \u2014 hablas by Abdulmoin Hablas")}`,""].join(`
201
- `)}function Au(n,e){let t=je(),s=[];s.push(""),s.push(` ${c.chrome("\u256D"+"\u2500".repeat(t-4)+"\u256E")}`),s.push(` ${c.chrome("\u2502")} ${c.leader("\u2605")} ${c.strong("Hablas")} ${c.muted("\u2014 Execution Plan")}${" ".repeat(Math.max(0,t-35))}${c.chrome("\u2502")}`);let r=20,i=Math.round(e.percent/100*r),o=r-i,a=c.success("\u2588".repeat(i))+c.muted("\u2591".repeat(o));s.push(` ${c.chrome("\u2502")} ${a} ${c.muted(`${e.percent}%`)} ${c.muted(`(${e.done}/${e.total} tasks)`)}`),s.push(` ${c.chrome("\u251C"+"\u2500".repeat(t-4)+"\u2524")}`);for(let l=0;l<n.tasks.length;l++){let u=n.tasks[l],d=eb[u.status](Zy[u.status]),h=(u.assignee==="hablas"?c.leader:u.assignee==="bob"?c.architect:u.assignee==="alex"?c.engineer:u.assignee==="david"?c.analyst:u.assignee==="emma"?c.product:c.muted)(`@${u.assigneeName}`),m="";u.dependent_task_ids.length>0&&(m=c.muted(` \u2190 [${u.dependent_task_ids.join(", ")}]`));let p=c.secondary(u.description);s.push(` ${c.chrome("\u2502")} ${d} ${c.muted(`${u.task_id}.`)} ${h} ${c.muted("\u2192")} ${p}${m}`)}return s.push(` ${c.chrome("\u251C"+"\u2500".repeat(t-4)+"\u2524")}`),s.push(` ${c.chrome("\u2502")} ${c.muted("Strategy:")} ${c.highlight(n.strategy)} ${c.muted("\xB7")} ${c.muted(`${n.tasks.length} tasks`)}`),s.push(` ${c.chrome("\u2570"+"\u2500".repeat(t-4)+"\u256F")}`),s.push(""),s.join(`
202
- `)}function ku(n){let e=je(),t=[];t.push(""),t.push(` ${c.chrome("\u256D"+"\u2500".repeat(e-4)+"\u256E")}`),t.push(` ${c.chrome("\u2502")} ${c.warning("?")} ${c.strong("Clarification Needed")}`),t.push(` ${c.chrome("\u251C"+"\u2500".repeat(e-4)+"\u2524")}`),t.push(` ${c.chrome("\u2502")} ${c.secondary(n.question)}`),t.push(` ${c.chrome("\u2502")}`);for(let s of n.choices)t.push(` ${c.chrome("\u2502")} ${c.accent(s.label+")")} ${c.secondary(s.value)}`);return n.context&&(t.push(` ${c.chrome("\u2502")}`),t.push(` ${c.chrome("\u2502")} ${c.muted(`Context: "${n.context.slice(0,60)}${n.context.length>60?"...":""}"`)}`)),t.push(` ${c.chrome("\u2570"+"\u2500".repeat(e-4)+"\u256F")}`),t.push(""),t.join(`
203
- `)}var no,Js,Jn,uu,gn,du,fu,je,c,Ne,to,Zy,eb,io,yn=L(()=>{"use strict";no=O(require("os")),Js=O(require("fs")),Jn=O(require("path"));uu=Vy(),gn=process.stdout.isTTY===!0,du=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",fu=process.stdout.columns||80;gn&&process.stdout.on("resize",()=>{fu=process.stdout.columns||80});je=()=>Math.min(fu-4,100);c={primary:n=>he(n,"\x1B[38;5;253m"),secondary:n=>he(n,"\x1B[38;5;247m"),muted:n=>he(n,"\x1B[38;5;242m"),strong:n=>he(n,"\x1B[1;38;5;255m"),accent:n=>he(n,"\x1B[38;5;145m"),highlight:n=>he(n,"\x1B[38;5;231m"),success:n=>he(n,"\x1B[38;5;108m"),error:n=>he(n,"\x1B[38;5;167m"),warning:n=>he(n,"\x1B[38;5;179m"),info:n=>he(n,"\x1B[38;5;110m"),codeBlock:n=>he(n,"\x1B[38;5;188m"),lineNum:n=>he(n,"\x1B[38;5;239m"),border:n=>he(n,"\x1B[38;5;237m"),chrome:n=>he(n,"\x1B[38;5;235m"),added:n=>he(n,"\x1B[38;5;108m"),removed:n=>he(n,"\x1B[38;5;167m"),hunk:n=>he(n,"\x1B[38;5;145m"),leader:n=>he(n,"\x1B[38;5;179m"),architect:n=>he(n,"\x1B[38;5;250m"),engineer:n=>he(n,"\x1B[38;5;145m"),analyst:n=>he(n,"\x1B[38;5;108m"),product:n=>he(n,"\x1B[38;5;180m")};Ne=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(),!gn){process.stderr.write(` ${this.message}...
204
- `);return}this.interval=setInterval(()=>{let e=((Date.now()-this.startTime)/1e3).toFixed(1),t=c.accent(this.frames[this.frameIndex]);process.stdout.write(`\r ${t} ${c.muted(this.message)} ${c.muted(e+"s")}`),this.frameIndex=(this.frameIndex+1)%this.frames.length},80)}setPhase(e){this.message=e}updateMessage(e){this.message=e}stop(e){this.interval&&(clearInterval(this.interval),this.interval=null);let t=Date.now()-this.startTime;if(gn&&process.stdout.write("\r"+" ".repeat(80)+"\r"),e&&gn){let s=c.muted(`${t}ms`);console.log(` ${c.muted("\xB7")} ${c.secondary(e)} ${s}`)}}};to=[{cmd:"/help",desc:"Show this help"},{cmd:"/about",desc:"Developer info & links"},{cmd:"/version",desc:"Version & runtime info"},{cmd:"/team",desc:"Show agent team roster"},{cmd:"/model",arg:"<name>",desc:"Switch model"},{cmd:"/models",arg:"[search|page]",desc:"Browse all models"},{cmd:"/tree",desc:"Project file tree"},{cmd:"/status",desc:"Agent status & context"},{cmd:"/history",arg:"[n]",desc:"Show last n turns"},{cmd:"/undo",arg:"[path]",desc:"Restore last backup"},{cmd:"/clear",desc:"Clear session & context"},{cmd:"/config",desc:"Show current config"},{cmd:"/quit",desc:"Exit hablas"}];Zy={pending:"\u25CB",running:"\u25C9",done:"\u2713",failed:"\u2717",skipped:"\u2013"},eb={pending:c.muted,running:c.accent,done:c.success,failed:c.error,skipped:c.muted};io=to.map(n=>n.cmd).concat(["/exit","/addmodel","/listmodels","/removemodel","/usemodel","/provider","/task","/memory","/mindset","/mindsets","/alias","/doctor","/plugins","/team","/agents","/delegate"])});function oo(n){let e=et.join(n,"package.json");if(Be.existsSync(e))try{let t=JSON.parse(Be.readFileSync(e,"utf-8")),s={...t.dependencies,...t.devDependencies};if(s.vitest)return"vitest";if(s.jest||s["@jest/core"])return"jest";if(s.mocha)return"mocha"}catch{}if(Be.existsSync(et.join(n,"pytest.ini"))||Be.existsSync(et.join(n,"pyproject.toml"))||Be.existsSync(et.join(n,"setup.py")))try{let t=Be.existsSync(et.join(n,"requirements.txt"))?Be.readFileSync(et.join(n,"requirements.txt"),"utf-8"):"",s=Be.existsSync(et.join(n,"pyproject.toml"))?Be.readFileSync(et.join(n,"pyproject.toml"),"utf-8"):"";if(t.includes("pytest")||s.includes("pytest"))return"pytest"}catch{}return Be.existsSync(et.join(n,"go.mod"))?"go":Be.existsSync(et.join(n,"Cargo.toml"))?"cargo":"unknown"}function tb(n,e){switch(n){case"vitest":return e?`npx vitest run ${e}`:"npx vitest run";case"jest":return e?`npx jest ${e} --no-coverage`:"npx jest --no-coverage";case"mocha":return e?`npx mocha ${e}`:"npx mocha";case"pytest":return e?`python -m pytest ${e} -v`:"python -m pytest -v";case"go":return e?`go test ./${e}`:"go test ./...";case"cargo":return"cargo test";default:return"npm test"}}function Cu(n,e){let t=oo(n),s=tb(t,e),r=Date.now(),i="",o="",a=!1;try{i=(0,$u.execSync)(s,{cwd:n,encoding:"utf-8",timeout:12e4,maxBuffer:5*1024*1024,stdio:["pipe","pipe","pipe"]}),a=!0}catch(m){i=m.stdout||"",o=m.stderr||m.message||"",a=!1}let l=Date.now()-r,{totalTests:u,passedTests:d,failedTests:f,failedTestNames:h}=nb(i+`
205
- `+o,t);return{framework:t,command:s,passed:a,output:i.slice(0,5e3),errorOutput:o.slice(0,3e3),totalTests:u,passedTests:d,failedTests:f,duration:l,failedTestNames:h}}function nb(n,e){let t=0,s=0,r=0,i=[],o=n.split(`
206
- `);switch(e){case"jest":case"vitest":{for(let a of o){let l=a.match(/Tests:\s+(\d+)\s+passed.*?(\d+)\s+total/);if(l&&(s=parseInt(l[1]),t=parseInt(l[2]),r=t-s),a.match(/✕|FAIL|✗|×/)){let d=a.replace(/.*(?:✕|FAIL|✗|×)\s*/,"").trim();d&&i.push(d)}}break}case"pytest":{for(let a of o){let l=a.match(/(\d+)\s+passed.*?(\d+)\s+failed/);l&&(s=parseInt(l[1]),r=parseInt(l[2]),t=s+r);let u=a.match(/(\d+)\s+passed/);u&&t===0&&(s=parseInt(u[1]),t=s),a.includes("FAILED")&&i.push(a.trim())}break}case"go":{for(let a of o)a.includes("--- PASS")&&s++,a.includes("--- FAIL")&&(r++,i.push(a.replace("--- FAIL:","").trim()));t=s+r;break}default:{for(let a of o)/\bpass(ed|ing)?\b/i.test(a)&&/\d/.test(a)&&s++,/\bfail(ed|ing|ure)?\b/i.test(a)&&/\d/.test(a)&&r++;t=s+r}}return{totalTests:t,passedTests:s,failedTests:r,failedTestNames:i}}function Eu(n){let e=[],t=n.passed?"\u2713 PASSED":"\u2717 FAILED",s=(n.duration/1e3).toFixed(1);if(e.push(` ${n.passed?"\u2713":"\u2717"} ${t} (${n.framework}) \u2014 ${s}s`),e.push(` Command: ${n.command}`),n.totalTests>0&&e.push(` Tests: ${n.passedTests} passed, ${n.failedTests} failed, ${n.totalTests} total`),n.failedTestNames.length>0){e.push(""),e.push(" Failed tests:");for(let r of n.failedTestNames.slice(0,10))e.push(` \u2717 ${r}`)}return e.join(`
207
- `)}function Tu(n){return`The following tests are failing. Analyze the error output and fix the code.
208
-
209
- Test framework: ${n.framework}
210
- Command: ${n.command}
211
- Failed tests: ${n.failedTestNames.join(", ")}
212
-
213
- Error output:
214
- \`\`\`
215
- ${n.errorOutput.slice(0,3e3)}
216
- \`\`\`
217
-
218
- Test output:
219
- \`\`\`
220
- ${n.output.slice(0,2e3)}
221
- \`\`\`
222
-
223
- Instructions:
224
- 1. Read the failing test files to understand what's expected
225
- 2. Read the source files being tested
226
- 3. Fix the source code (not the tests) to make them pass
227
- 4. After fixing, explain what was wrong and what you changed`}var $u,Be,et,Ru=L(()=>{"use strict";$u=require("child_process"),Be=O(require("fs")),et=O(require("path"))});function Qs(n){let e=Buffer.from(n).toString("base64url").slice(0,16);return Me.join(sb,e)}async function Pu(n,e,t){let s=Qs(n);ke.existsSync(s)||ke.mkdirSync(s,{recursive:!0});let r=`cp_${Date.now()}`,i=[];for(let f of t){let h=Me.resolve(n,f);if(ke.existsSync(h))try{let m=await Ct.readFile(h,"utf-8");i.push({path:f,content:m})}catch{}}try{let f=(0,Xs.execSync)("git ls-files -m",{cwd:n,encoding:"utf-8",timeout:5e3}).split(`
228
- `).filter(Boolean);for(let h of f)if(!i.find(m=>m.path===h))try{let m=await Ct.readFile(Me.resolve(n,h),"utf-8");i.push({path:h,content:m})}catch{}}catch{}let o,a;try{o=(0,Xs.execSync)("git branch --show-current",{cwd:n,encoding:"utf-8",timeout:5e3}).trim(),a=(0,Xs.execSync)("git rev-parse --short HEAD",{cwd:n,encoding:"utf-8",timeout:5e3}).trim()}catch{}let l={id:r,label:e,timestamp:Date.now(),files:i,gitBranch:o,gitHash:a,projectPath:n},u=Me.join(s,`${r}.json`);await Ct.writeFile(u,JSON.stringify(l,null,2),"utf-8");let d=ke.readdirSync(s).filter(f=>f.endsWith(".json")).sort();if(d.length>20)for(let f of d.slice(0,d.length-20))try{ke.unlinkSync(Me.join(s,f))}catch{}return{id:r,label:e,timestamp:l.timestamp,fileCount:i.length,projectPath:n}}function Mu(n){let e=Qs(n);if(!ke.existsSync(e))return[];let t=ke.readdirSync(e).filter(r=>r.endsWith(".json")).sort().reverse(),s=[];for(let r of t)try{let i=JSON.parse(ke.readFileSync(Me.join(e,r),"utf-8"));s.push({id:i.id,label:i.label,timestamp:i.timestamp,fileCount:i.files.length,projectPath:i.projectPath})}catch{}return s}async function Iu(n,e){let t=Qs(n),s=Me.join(t,`${e}.json`);if(!ke.existsSync(s))return{success:!1,filesRestored:0,error:`Checkpoint ${e} not found`};try{let r=JSON.parse(await Ct.readFile(s,"utf-8")),i=0;for(let o of r.files)try{let a=Me.resolve(n,o.path);await Ct.mkdir(Me.dirname(a),{recursive:!0}),await Ct.writeFile(a,o.content,"utf-8"),i++}catch{}return{success:!0,filesRestored:i}}catch(r){return{success:!1,filesRestored:0,error:r.message}}}function Du(n,e){let t=Qs(n),s=Me.join(t,`${e}.json`);try{if(ke.existsSync(s))return ke.unlinkSync(s),!0}catch{}return!1}function Lu(n){if(n.length===0)return" No checkpoints saved";let e=[];for(let t of n){let s=new Date(t.timestamp).toLocaleString();e.push(` ${t.id} "${t.label}" (${t.fileCount} files, ${s})`)}return e.join(`
229
- `)}var ke,Ct,Me,Ou,Xs,sb,Fu=L(()=>{"use strict";ke=O(require("fs")),Ct=O(require("fs/promises")),Me=O(require("path")),Ou=O(require("os")),Xs=require("child_process"),sb=Me.join(Ou.homedir(),".hablas","checkpoints")});function Et(){}function rb(n,e,t,s,r){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,u=0,d=0;a<l;a++){var f=i[a];if(f.removed){if(f.value=n.join(s.slice(d,d+f.count)),d+=f.count,a&&i[a-1].added){var m=i[a-1];i[a-1]=i[a],i[a]=m}}else{if(!f.added&&r){var h=t.slice(u,u+f.count);h=h.map(function(g,S){var x=s[d+S];return x.length>g.length?x:g}),f.value=n.join(h)}else f.value=n.join(t.slice(u,u+f.count));u+=f.count,f.added||(d+=f.count)}}var p=i[l-1];return l>1&&typeof p.value=="string"&&(p.added||p.removed)&&n.equals("",p.value)&&(i[l-2].value+=p.value,i.pop()),i}function ib(n,e,t){return fo.diff(n,e,t)}function Zs(n){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Zs=function(e){return typeof e}:Zs=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Zs(n)}function ao(n){return lb(n)||cb(n)||ub(n)||db()}function lb(n){if(Array.isArray(n))return lo(n)}function cb(n){if(typeof Symbol<"u"&&Symbol.iterator in Object(n))return Array.from(n)}function ub(n,e){if(n){if(typeof n=="string")return lo(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 lo(n,e)}}function lo(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,s=new Array(e);t<e;t++)s[t]=n[t];return s}function db(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
230
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function co(n,e,t,s,r){e=e||[],t=t||[],s&&(n=s(r,n));var i;for(i=0;i<e.length;i+=1)if(e[i]===n)return t[i];var o;if(fb.call(n)==="[object Array]"){for(e.push(n),o=new Array(n.length),t.push(o),i=0;i<n.length;i+=1)o[i]=co(n[i],e,t,s,r);return e.pop(),t.pop(),o}if(n&&n.toJSON&&(n=n.toJSON()),Zs(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]=co(n[l],e,t,s,l);e.pop(),t.pop()}else o=n;return o}function pb(n){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},t=n.split(/\r\n|[\n\v\f\r\x85]/),s=n.match(/\r\n|[\n\v\f\r\x85]/g)||[],r=[],i=0;function o(){var u={};for(r.push(u);i<t.length;){var d=t[i];if(/^(\-\-\-|\+\+\+|@@)\s/.test(d))break;var f=/^(?:Index:|diff(?: -r \w+)+)\s+/.exec(d);f&&(u.index=d.substring(f[0].length).trim()),i++}for(a(u),a(u),u.hunks=[];i<t.length;){var h=t[i];if(/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(h))break;if(/^@@/.test(h))u.hunks.push(l());else{if(h&&e.strict)throw new Error("Unknown line "+(i+1)+" "+JSON.stringify(h));i++}}}function a(u){var d=/^(---|\+\+\+)\s+/.exec(t[i]);if(d){var f=d[1]==="---"?"old":"new",h=t[i].substring(3).trim().split(" ",2),m=h[0].replace(/\\\\/g,"\\");m.startsWith('"')&&m.endsWith('"')&&(m=m.substr(1,m.length-2)),u[f+"FileName"]=m,u[f+"Header"]=(h[1]||"").trim(),i++}}function l(){var u=i,d=t[i++],f=d.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/),h={oldStart:+f[1],oldLines:typeof f[2]>"u"?1:+f[2],newStart:+f[3],newLines:typeof f[4]>"u"?1:+f[4],lines:[],linedelimiters:[]};h.oldLines===0&&(h.oldStart+=1),h.newLines===0&&(h.newStart+=1);for(var m=0,p=0;i<t.length&&!(t[i].indexOf("--- ")===0&&i+2<t.length&&t[i+1].indexOf("+++ ")===0&&t[i+2].indexOf("@@")===0);i++){var g=t[i].length==0&&i!=t.length-1?" ":t[i][0];if(g==="+"||g==="-"||g===" "||g==="\\")h.lines.push(t[i]),h.linedelimiters.push(s[i]||`
231
- `),g==="+"?m++:g==="-"?p++:g===" "&&(m++,p++);else break}if(!m&&h.newLines===1&&(h.newLines=0),!p&&h.oldLines===1&&(h.oldLines=0),e.strict){if(m!==h.newLines)throw new Error("Added line count did not match for hunk at line "+(u+1));if(p!==h.oldLines)throw new Error("Removed line count did not match for hunk at line "+(u+1))}return h}for(;i<t.length;)o();return r}function hb(n,e,t){var s=!0,r=!1,i=!1,o=1;return function a(){if(s&&!i){if(r?o++:s=!1,n+o<=t)return o;i=!0}if(!r)return i||(s=!0),e<=n-o?-o++:(r=!0,a())}}function Bu(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(typeof e=="string"&&(e=pb(e)),Array.isArray(e)){if(e.length>1)throw new Error("applyPatch only works with a single input.");e=e[0]}var s=n.split(/\r\n|[\n\v\f\r\x85]/),r=n.match(/\r\n|[\n\v\f\r\x85]/g)||[],i=e.hunks,o=t.compareLine||function(E,A,V,U){return A===U},a=0,l=t.fuzzFactor||0,u=0,d=0,f,h;function m(E,A){for(var V=0;V<E.lines.length;V++){var U=E.lines[V],Z=U.length>0?U[0]:" ",te=U.length>0?U.substr(1):U;if(Z===" "||Z==="-"){if(!o(A+1,s[A],Z,te)&&(a++,a>l))return!1;A++}}return!0}for(var p=0;p<i.length;p++){for(var g=i[p],S=s.length-g.oldLines,x=0,$=d+g.oldStart-1,k=hb($,u,S);x!==void 0;x=k())if(m(g,$+x)){g.offset=d+=x;break}if(x===void 0)return!1;u=g.offset+g.oldStart+g.oldLines}for(var y=0,b=0;b<i.length;b++){var v=i[b],w=v.oldStart+v.offset+y-1;y+=v.newLines-v.oldLines;for(var _=0;_<v.lines.length;_++){var T=v.lines[_],P=T.length>0?T[0]:" ",C=T.length>0?T.substr(1):T,F=v.linedelimiters&&v.linedelimiters[_]||`
232
- `;if(P===" ")w++;else if(P==="-")s.splice(w,1),r.splice(w,1);else if(P==="+")s.splice(w,0,C),r.splice(w,0,F),w++;else if(P==="\\"){var H=v.lines[_-1]?v.lines[_-1][0]:null;H==="+"?f=!0:H==="-"&&(h=!0)}}}if(f)for(;!s[s.length-1];)s.pop(),r.pop();else h&&(s.push(""),r.push(`
233
- `));for(var W=0;W<s.length-1;W++)s[W]=s[W]+r[W];return s.join("")}function mb(n,e,t,s,r,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=ib(t,s,o);if(!a)return;a.push({value:"",lines:[]});function l(x){return x.map(function($){return" "+$})}for(var u=[],d=0,f=0,h=[],m=1,p=1,g=function($){var k=a[$],y=k.lines||k.value.replace(/\n$/,"").split(`
234
- `);if(k.lines=y,k.added||k.removed){var b;if(!d){var v=a[$-1];d=m,f=p,v&&(h=o.context>0?l(v.lines.slice(-o.context)):[],d-=h.length,f-=h.length)}(b=h).push.apply(b,ao(y.map(function(W){return(k.added?"+":"-")+W}))),k.added?p+=y.length:m+=y.length}else{if(d)if(y.length<=o.context*2&&$<a.length-2){var w;(w=h).push.apply(w,ao(l(y)))}else{var _,T=Math.min(y.length,o.context);(_=h).push.apply(_,ao(l(y.slice(0,T))));var P={oldStart:d,oldLines:m-d+T,newStart:f,newLines:p-f+T,lines:h};if($>=a.length-2&&y.length<=o.context){var C=/\n$/.test(t),F=/\n$/.test(s),H=y.length==0&&h.length>P.oldLines;!C&&H&&t.length>0&&h.splice(P.oldLines,0,"\"),(!C&&!H||!F)&&h.push("\")}u.push(P),d=0,f=0,h=[]}m+=y.length,p+=y.length}},S=0;S<a.length;S++)g(S);return{oldFileName:n,newFileName:e,oldHeader:r,newHeader:i,hunks:u}}function Uu(n){if(Array.isArray(n))return n.map(Uu).join(`
235
- `);var e=[];n.oldFileName==n.newFileName&&e.push("Index: "+n.oldFileName),e.push("==================================================================="),e.push("--- "+n.oldFileName+(typeof n.oldHeader>"u"?"":" "+n.oldHeader)),e.push("+++ "+n.newFileName+(typeof n.newHeader>"u"?"":" "+n.newHeader));for(var t=0;t<n.hunks.length;t++){var s=n.hunks[t];s.oldLines===0&&(s.oldStart-=1),s.newLines===0&&(s.newStart-=1),e.push("@@ -"+s.oldStart+","+s.oldLines+" +"+s.newStart+","+s.newLines+" @@"),e.push.apply(e,s.lines)}return e.join(`
20
+ `),this.outputHelp({error:!0}));let n=r||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in j.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,j.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new sl(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!r(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=o=>{let a=o.attributeName(),l=this.getOptionValue(a),u=this.options.find(f=>f.negate&&a===f.attributeName()),d=this.options.find(f=>!f.negate&&a===f.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:d||o},s=o=>{let a=n(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(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";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);r=qn(e,s)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),r=qn(e,s)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let s=this.createOption(r,n);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,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>rl(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=re.basename(e,re.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(r&&(s=r(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),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 r=j.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
+ Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof r=="function"?o=r({error:i.error,command:i.command}):o=r,o&&i.write(`${o}
23
+ `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Un(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?r=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=i[1],n=i[3],s=i[4]),r&&s!=="0"?`${r}=${n}:${parseInt(s)+1}`:e})}Bn.Command=gr});var Kn=R(V=>{var{Argument:Wn}=ht(),{Command:yr}=Hn(),{CommanderError:il,InvalidArgumentError:Vn}=Ye(),{Help:ol}=lr(),{Option:zn}=dr();V.program=new yr;V.createCommand=t=>new yr(t);V.createOption=(t,e)=>new zn(t,e);V.createArgument=(t,e)=>new Wn(t,e);V.Command=yr;V.Option=zn;V.Argument=Wn;V.Help=ol;V.CommanderError=il;V.InvalidArgumentError=Vn;V.InvalidOptionArgumentError=Vn});var Sr=R((qp,es)=>{"use strict";var et=t=>t&&typeof t.message=="string",br=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return et(r)?r:void 0}else return et(e)?e:void 0},Zn=(t,e)=>{if(!et(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
+ causes have become circular...`;let n=br(t);return n?(e.add(t),r+`
25
+ caused by: `+Zn(n,e)):r},al=t=>Zn(t,new Set),Qn=(t,e,r)=>{if(!et(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=br(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+Qn(s,e,i)}else return n},ll=t=>Qn(t,new Set);es.exports={isErrorLike:et,getErrorCause:br,stackWithCauses:al,messageWithCauses:ll}});var _r=R((Up,rs)=>{"use strict";var cl=Symbol("circular-ref-tag"),pt=Symbol("pino-raw-err-ref"),ts=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[pt]},set:function(t){this[pt]=t}}});Object.defineProperty(ts,pt,{writable:!0,value:{}});rs.exports={pinoErrProto:ts,pinoErrorSymbols:{seen:cl,rawSymbol:pt}}});var is=R((Bp,ss)=>{"use strict";ss.exports=vr;var{messageWithCauses:ul,stackWithCauses:fl,isErrorLike:ns}=Sr(),{pinoErrProto:dl,pinoErrorSymbols:hl}=_r(),{seen:xr}=hl,{toString:pl}=Object.prototype;function vr(t){if(!ns(t))return t;t[xr]=void 0;let e=Object.create(dl);e.type=pl.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=ul(t),e.stack=fl(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>vr(r)));for(let r in t)if(e[r]===void 0){let n=t[r];ns(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,xr)&&(e[r]=vr(n)):e[r]=n}return delete t[xr],e.raw=t,e}});var as=R((Hp,os)=>{"use strict";os.exports=gt;var{isErrorLike:kr}=Sr(),{pinoErrProto:ml,pinoErrorSymbols:gl}=_r(),{seen:mt}=gl,{toString:yl}=Object.prototype;function gt(t){if(!kr(t))return t;t[mt]=void 0;let e=Object.create(ml);e.type=yl.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=t.message,e.stack=t.stack,Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>gt(r))),kr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,mt)&&(e.cause=gt(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];kr(n)?Object.prototype.hasOwnProperty.call(n,mt)||(e[r]=gt(n)):e[r]=n}return delete t[mt],e.raw=t,e}});var fs=R((Wp,us)=>{"use strict";us.exports={mapHttpRequest:wl,reqSerializer:cs};var Cr=Symbol("pino-raw-req-ref"),ls=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[Cr]},set:function(t){this[Cr]=t}}});Object.defineProperty(ls,Cr,{writable:!0,value:{}});function cs(t){let e=t.info||t.socket,r=Object.create(ls);if(r.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),r.method=t.method,t.originalUrl)r.url=t.originalUrl;else{let n=t.path;r.url=typeof n=="string"?n:t.url?t.url.path||t.url:void 0}return t.query&&(r.query=t.query),t.params&&(r.params=t.params),r.headers=t.headers,r.remoteAddress=e&&e.remoteAddress,r.remotePort=e&&e.remotePort,r.raw=t.raw||t,r}function wl(t){return{req:cs(t)}}});var ms=R((Vp,ps)=>{"use strict";ps.exports={mapHttpResponse:bl,resSerializer:hs};var Tr=Symbol("pino-raw-res-ref"),ds=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Tr]},set:function(t){this[Tr]=t}}});Object.defineProperty(ds,Tr,{writable:!0,value:{}});function hs(t){let e=Object.create(ds);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function bl(t){return{res:hs(t)}}});var Er=R((zp,gs)=>{"use strict";var Ar=is(),Sl=as(),yt=fs(),wt=ms();gs.exports={err:Ar,errWithCause:Sl,mapHttpRequest:yt.mapHttpRequest,mapHttpResponse:wt.mapHttpResponse,req:yt.reqSerializer,res:wt.resSerializer,wrapErrorSerializer:function(e){return e===Ar?e:function(n){return e(Ar(n))}},wrapRequestSerializer:function(e){return e===yt.reqSerializer?e:function(n){return e(yt.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===wt.resSerializer?e:function(n){return e(wt.resSerializer(n))}}}});var Or=R((Kp,ys)=>{"use strict";function _l(t,e){return e}ys.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=_l;let r=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(r))return;let n=r.slice(2),s=[];for(let i of n)i&&s.push(i.getFileName());return s}});var vs=R((Jp,xs)=>{"use strict";function $r(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array){let e=[];for(let r=0;r<t.length;r++)e[r]=$r(t[r]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=$r(t[r]));return e}return t}function ws(t){let e=[],r="",n=!1,s=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!n&&a==="."?r&&(e.push(r),r=""):a==="["?(r&&(e.push(r),r=""),n=!0):a==="]"&&n?(e.push(r),r="",n=!1,s=!1):(a==='"'||a==="'")&&n?s?a===i?(s=!1,i=""):r+=a:(s=!0,i=a):r+=a}return r&&e.push(r),e}function bs(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof n!="object"||n===null||!(o in n)||typeof n[o]!="object"||n[o]===null)return!1;n=n[o]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(n))for(let i=0;i<n.length;i++)n[i]=r;else if(typeof n=="object"&&n!==null)for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&(n[i]=r)}else typeof n=="object"&&n!==null&&s in n&&Object.prototype.hasOwnProperty.call(n,s)&&(n[s]=r);return!0}function Ss(t,e){let r=t;for(let s=0;s<e.length-1;s++){let i=e[s];if(typeof r!="object"||r===null||!(i in r)||typeof r[i]!="object"||r[i]===null)return!1;r=r[i]}let n=e[e.length-1];if(n==="*"){if(Array.isArray(r))for(let s=0;s<r.length;s++)r[s]=void 0;else if(typeof r=="object"&&r!==null)for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&delete r[s]}else typeof r=="object"&&r!==null&&n in r&&Object.prototype.hasOwnProperty.call(r,n)&&delete r[n];return!0}var bt=Symbol("PATH_NOT_FOUND");function xl(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return bt;r=r[n]}return r}function vl(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null)return;r=r[n]}return r}function kl(t,e,r,n=!1){for(let s of e){let i=ws(s);if(i.includes("*"))_s(t,i,r,s,n);else if(n)Ss(t,i);else{let o=xl(t,i);if(o===bt)continue;let a=typeof r=="function"?r(o,i):r;bs(t,i,a)}}}function _s(t,e,r,n,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;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 u=[...o,l.toString()],d=typeof r=="function"?r(a[l],u):r;a[l]=d}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let u in a)Object.prototype.hasOwnProperty.call(a,u)&&l.push(u);for(let u of l)delete a[u]}else for(let l in a){let u=[...o,l],d=typeof r=="function"?r(a[l],u):r;a[l]=d}}else Cl(t,e,r,i,n,s)}function Cl(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function u(d,f){if(f===o.length){if(Array.isArray(d))for(let p=0;p<d.length;p++)l[f]=p.toString(),u(d[p],f+1);else if(typeof d=="object"&&d!==null)for(let p in d)l[f]=p,u(d[p],f+1)}else if(f<o.length){let p=o[f];d&&typeof d=="object"&&d!==null&&p in d&&(l[f]=p,u(d[p],f+1))}else if(a.includes("*"))_s(d,a,typeof r=="function"?(h,c)=>{let m=[...l.slice(0,f),...c];return r(h,m)}:r,s,i);else if(i)Ss(d,a);else{let p=typeof r=="function"?r(vl(d,a),[...l.slice(0,f),...a]):r;bs(d,a,p)}}if(o.length===0)u(t,0);else{let d=t;for(let f=0;f<o.length;f++){let p=o[f];if(d==null||typeof d!="object"||d===null)return;d=d[p],l[f]=p}d!=null&&u(d,o.length)}}function Tl(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=ws(r),s=e;for(let i=0;i<n.length;i++){let o=n[i];s.has(o)||s.set(o,new Map),s=s.get(o)}}return e}function Al(t,e){if(!e)return t;function r(n,s,i=0){if(!s||s.size===0||n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n)){let a=[];for(let l=0;l<n.length;l++){let u=l.toString();s.has(u)||s.has("*")?a[l]=r(n[l],s.get(u)||s.get("*")):a[l]=n[l]}return a}let o=Object.create(Object.getPrototypeOf(n));for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s.has(a)||s.has("*")?o[a]=r(n[a],s.get(a)||s.get("*")):o[a]=n[a]);return o}return r(t,e)}function El(t){if(typeof t!="string")throw new Error("Paths must be (non-empty) strings");if(t==="")throw new Error("Invalid redaction path ()");if(t.includes(".."))throw new Error(`Invalid redaction path (${t})`);if(t.includes(","))throw new Error(`Invalid redaction path (${t})`);let e=0,r=!1,n="";for(let s=0;s<t.length;s++){let i=t[s];if((i==='"'||i==="'")&&e>0)r?i===n&&(r=!1,n=""):(r=!0,n=i);else if(i==="["&&!r)e++;else if(i==="]"&&!r&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function Ol(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)El(e)}function $l(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;Ol(e);let o=Tl(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let u=Al(l,o),d=l,f=r;return typeof r=="function"&&(f=r),kl(u,e,f,i),n===!1?(u.restore=function(){return $r(d)},u):typeof n=="function"?n(u):JSON.stringify(u)}}xs.exports=$l});var Pe=R((Gp,ks)=>{"use strict";var Rl=Symbol("pino.setLevel"),Il=Symbol("pino.getLevel"),Pl=Symbol("pino.levelVal"),Fl=Symbol("pino.levelComp"),Ml=Symbol("pino.useLevelLabels"),Dl=Symbol("pino.useOnlyCustomLevels"),Ll=Symbol("pino.mixin"),jl=Symbol("pino.lsCache"),Nl=Symbol("pino.chindings"),ql=Symbol("pino.asJson"),Ul=Symbol("pino.write"),Bl=Symbol("pino.redactFmt"),Hl=Symbol("pino.time"),Wl=Symbol("pino.timeSliceIndex"),Vl=Symbol("pino.stream"),zl=Symbol("pino.stringify"),Kl=Symbol("pino.stringifySafe"),Jl=Symbol("pino.stringifiers"),Gl=Symbol("pino.end"),Xl=Symbol("pino.formatOpts"),Yl=Symbol("pino.messageKey"),Zl=Symbol("pino.errorKey"),Ql=Symbol("pino.nestedKey"),ec=Symbol("pino.nestedKeyStr"),tc=Symbol("pino.mixinMergeStrategy"),rc=Symbol("pino.msgPrefix"),nc=Symbol("pino.wildcardFirst"),sc=Symbol.for("pino.serializers"),ic=Symbol.for("pino.formatters"),oc=Symbol.for("pino.hooks"),ac=Symbol.for("pino.metadata");ks.exports={setLevelSym:Rl,getLevelSym:Il,levelValSym:Pl,levelCompSym:Fl,useLevelLabelsSym:Ml,mixinSym:Ll,lsCacheSym:jl,chindingsSym:Nl,asJsonSym:ql,writeSym:Ul,serializersSym:sc,redactFmtSym:Bl,timeSym:Hl,timeSliceIndexSym:Wl,streamSym:Vl,stringifySym:zl,stringifySafeSym:Kl,stringifiersSym:Jl,endSym:Gl,formatOptsSym:Xl,messageKeySym:Yl,errorKeySym:Zl,nestedKeySym:Ql,wildcardFirstSym:nc,needsMetadataGsym:ac,useOnlyCustomLevelsSym:Dl,formattersSym:ic,hooksSym:oc,nestedKeyStrSym:ec,mixinMergeStrategySym:tc,msgPrefixSym:rc}});var Ir=R((Xp,Es)=>{"use strict";var Cs=vs(),{redactFmtSym:lc,wildcardFirstSym:St}=Pe(),Rr=/[^.[\]]+|\[([^[\]]*?)\]/g,Ts="[Redacted]",As=!1;function cc(t,e){let{paths:r,censor:n,remove:s}=uc(t),i=r.reduce((l,u)=>{Rr.lastIndex=0;let d=Rr.exec(u),f=Rr.exec(u),p=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(p==="*"&&(p=St),f===null)return l[p]=null,l;if(l[p]===null)return l;let{index:h}=f,c=`${u.substr(h,u.length-1)}`;return l[p]=l[p]||[],p!==St&&l[p].length===0&&l[p].push(...l[St]||[]),p===St&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(c)}),l[p].push(c),l},{}),o={[lc]:Cs({paths:r,censor:n,serialize:e,strict:As,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,u)=>{if(i[u]===null)l[u]=d=>a(d,[u]);else{let d=typeof n=="function"?(f,p)=>n(f,[u,...p]):n;l[u]=Cs({paths:i[u],censor:d,serialize:e,strict:As,remove:s})}return l},o)}function uc(t){if(Array.isArray(t))return t={paths:t,censor:Ts},t;let{paths:e,censor:r=Ts,remove:n}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),{paths:e,censor:r,remove:n}}Es.exports=cc});var Rs=R((Yp,$s)=>{"use strict";var fc=()=>"",dc=()=>`,"time":${Date.now()}`,hc=()=>`,"time":${Math.round(Date.now()/1e3)}`,pc=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,mc=1000000n,Os=1000000000n,gc=BigInt(Date.now())*mc,yc=process.hrtime.bigint(),wc=()=>{let t=process.hrtime.bigint()-yc,e=gc+t,r=e/Os,n=e%Os,s=Number(r*1000n+n/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),u=i.getUTCHours().toString().padStart(2,"0"),d=i.getUTCMinutes().toString().padStart(2,"0"),f=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${u}:${d}:${f}.${n.toString().padStart(9,"0")}Z"`};$s.exports={nullTime:fc,epochTime:dc,unixTime:hc,isoTime:pc,isoTimeNano:wc}});var Ps=R((Zp,Is)=>{"use strict";function bc(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}Is.exports=Sc;function Sc(t,e,r){var n=r&&r.stringify||bc,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var u="",d=1-s,f=-1,p=t&&t.length||0,h=0;h<p;){if(t.charCodeAt(h)===37&&h+1<p){switch(f=f>-1?f:0,t.charCodeAt(h+1)){case 100:case 102:if(d>=l||e[d]==null)break;f<h&&(u+=t.slice(f,h)),u+=Number(e[d]),f=h+2,h++;break;case 105:if(d>=l||e[d]==null)break;f<h&&(u+=t.slice(f,h)),u+=Math.floor(Number(e[d])),f=h+2,h++;break;case 79:case 111:case 106:if(d>=l||e[d]===void 0)break;f<h&&(u+=t.slice(f,h));var c=typeof e[d];if(c==="string"){u+="'"+e[d]+"'",f=h+2,h++;break}if(c==="function"){u+=e[d].name||"<anonymous>",f=h+2,h++;break}u+=n(e[d]),f=h+2,h++;break;case 115:if(d>=l)break;f<h&&(u+=t.slice(f,h)),u+=String(e[d]),f=h+2,h++;break;case 37:f<h&&(u+=t.slice(f,h)),u+="%",f=h+2,h++,d--;break}++d}++h}return f===-1?t:(f<p&&(u+=t.slice(f)),u)}});var Fr=R((Qp,Pr)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="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(t,0,0,Number(r))},t=new Int32Array(new SharedArrayBuffer(4));Pr.exports=e}else{let t=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 n=Date.now()+Number(e);for(;n>Date.now(););};Pr.exports=t}});var Us=R((em,qs)=>{"use strict";var M=require("fs"),_c=require("events"),xc=require("util").inherits,Fs=require("path"),Dr=Fr(),vc=require("assert"),_t=100,xt=Buffer.allocUnsafe(0),kc=16*1024,Ms="buffer",Ds="utf8",[Cc,Tc]=(process.versions.node||"0.0").split(".").map(Number),Ac=Cc>=22&&Tc>=7;function Ls(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function r(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=t,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 n=e.append?"a":"w",s=e.mode;if(e.sync)try{e.mkdir&&M.mkdirSync(Fs.dirname(t),{recursive:!0});let i=M.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?M.mkdir(Fs.dirname(t),{recursive:!0},i=>{if(i)return r(i);M.open(t,n,s,r)}):M.open(t,n,s,r)}function Y(t){if(!(this instanceof Y))return new Y(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:u,retryEAGAIN:d,fsync:f,contentMode:p,mode:h}=t||{};e=e||r,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(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=s||0,this.maxWrite=i||kc,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=h,this.retryEAGAIN=d||(()=>!0),this.mkdir=u||!1;let c,m;if(p===Ms)this._writingBuf=xt,this.write=$c,this.flush=Ic,this.flushSync=Fc,this._actualWrite=Dc,c=()=>M.writeSync(this.fd,this._writingBuf),m=()=>M.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===Ds)this._writingBuf="",this.write=Oc,this.flush=Rc,this.flushSync=Pc,this._actualWrite=Mc,c=()=>Buffer.isBuffer(this._writingBuf)?M.writeSync(this.fd,this._writingBuf):M.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?M.write(this.fd,this._writingBuf,this.release):M.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Ds}" and "${Ms}", but passed ${p}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Ls(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{Dr(_t),this.release(void 0,0)}catch(S){this.release(S)}else setTimeout(m,_t);else this._writing=!1,this.emit("error",y);return}this.emit("write",w);let b=Mr(this._writingBuf,this._len,w);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let S=c(),v=Mr(this._writingBuf,this._len,S);this._len=v.len,this._writingBuf=v.writingBuf}while(this._writingBuf.length)}catch(S){this.release(S);return}}this._fsync&&M.fsyncSync(this.fd);let _=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):_>this.minLength?this._actualWrite():this._ending?_>0?this._actualWrite():(this._writing=!1,vt(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Ec,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 Mr(t,e,r){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-r,0),t=t.subarray(r),{writingBuf:t,len:e}}function Ec(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}xc(Y,_c);function js(t,e){return t.length===0?xt:t.length===1?t[0]:Buffer.concat(t,e)}function Oc(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),r=this._len+e,n=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(n.length===0||Buffer.byteLength(n[n.length-1])+e>this.maxWrite?n.push(t):n[n.length-1]+=t,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function $c(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,r=this._bufs,n=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||n[n.length-1]+t.length>this.maxWrite?(r.push([t]),n.push(t.length)):(r[r.length-1].push(t),n[n.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Ns(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{M.fsync(this.fd,n=>{this._flushPending=!1,t(n)})}catch(n){t(n)}this.off("error",r)},r=n=>{this._flushPending=!1,t(n),this.off("drain",e)};this.once("drain",e),this.once("error",r)}function Rc(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Ns.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function Ic(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Ns.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}Y.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});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(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&M.close(e,r=>{if(r)return this.emit("error",r)})}),Ls(this.file,this)};Y.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():vt(this)))};function Pc(){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 t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?M.writeSync(this.fd,t):M.writeSync(this.fd,t,"utf8"),r=Mr(t,this._len,e);t=r.writingBuf,this._len=r.len,t.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Dr(_t)}}try{M.fsyncSync(this.fd)}catch{}}function Fc(){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=xt);let t=xt;for(;this._bufs.length||t.length;){t.length<=0&&(t=js(this._bufs[0],this._lens[0]));try{let e=M.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Dr(_t)}}}Y.prototype.destroy=function(){this.destroyed||vt(this)};function Mc(){let t=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)?M.writeSync(this.fd,this._writingBuf):M.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else M.write(this.fd,this._writingBuf,t)}function Dc(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:js(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=M.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else Ac&&(this._writingBuf=Buffer.from(this._writingBuf)),M.write(this.fd,this._writingBuf,t)}function vt(t){if(t.fd===-1){t.once("ready",vt.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],vc(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{M.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?M.close(t.fd,r):r()}function r(n){if(n){t.emit("error",n);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}Y.SonicBoom=Y;Y.default=Y;qs.exports=Y});var Lr=R((tm,zs)=>{"use strict";var Z={exit:[],beforeExit:[]},Bs={exit:Nc,beforeExit:qc},Fe;function Lc(){Fe===void 0&&(Fe=new FinalizationRegistry(Uc))}function jc(t){Z[t].length>0||process.on(t,Bs[t])}function Hs(t){Z[t].length>0||(process.removeListener(t,Bs[t]),Z.exit.length===0&&Z.beforeExit.length===0&&(Fe=void 0))}function Nc(){Ws("exit")}function qc(){Ws("beforeExit")}function Ws(t){for(let e of Z[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}Z[t]=[]}function Uc(t){for(let e of["exit","beforeExit"]){let r=Z[e].indexOf(t);Z[e].splice(r,r+1),Hs(e)}}function Vs(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");jc(t);let n=new WeakRef(e);n.fn=r,Lc(),Fe.register(e,n),Z[t].push(n)}function Bc(t,e){Vs("exit",t,e)}function Hc(t,e){Vs("beforeExit",t,e)}function Wc(t){if(Fe!==void 0){Fe.unregister(t);for(let e of["exit","beforeExit"])Z[e]=Z[e].filter(r=>{let n=r.deref();return n&&n!==t}),Hs(e)}}zs.exports={register:Bc,registerBeforeExit:Hc,unregister:Wc}});var Ks=R((rm,Vc)=>{Vc.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 Gs=R((nm,Js)=>{"use strict";function zc(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{let a=Atomics.load(t,e);if(a===r){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())),u=Atomics.waitAsync(t,e,a,l);u.async?u.value.then(o):setImmediate(o)};o()}function Kc(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{if(Atomics.load(t,e)!==r){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())),u=Atomics.waitAsync(t,e,r,l);u.async?u.value.then(d=>{if(d==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}Js.exports={wait:zc,waitDiff:Kc}});var Ys=R((sm,Xs)=>{"use strict";Xs.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var ci=R((im,li)=>{"use strict";var{version:Jc}=Ks(),{EventEmitter:Gc}=require("events"),{Worker:Xc}=require("worker_threads"),{join:Yc}=require("path"),{pathToFileURL:Zc}=require("url"),{wait:Qc}=Gs(),{WRITE_INDEX:se,READ_INDEX:ge,SEQ_INDEX:jr}=Ys(),eu=require("buffer"),tu=require("assert"),g=Symbol("kImpl"),ru=eu.constants.MAX_STRING_LENGTH;function Zs(){}function Br(t,e){Atomics.add(t[g].state,jr,1),e(),Atomics.add(t[g].state,jr,1),Atomics.notify(t[g].state,jr)}function Qs(t){Br(t,()=>{Atomics.store(t[g].state,ge,0),Atomics.store(t[g].state,se,0)})}var tt=class{constructor(e){this._value=e}deref(){return this._value}},kt=class{register(){}unregister(){}},nu=process.env.NODE_V8_COVERAGE?kt:global.FinalizationRegistry||kt,su=process.env.NODE_V8_COVERAGE?tt:global.WeakRef||tt,ei=new nu(t=>{t.exited||t.terminate()});function iu(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Yc(__dirname,"lib","worker.js"),o=new Xc(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Zc(r).href,dataBuf:t[g].dataBuf,stateBuf:t[g].stateBuf,workerData:{$context:{threadStreamVersion:Jc},...n}}});return o.stream=new tt(t),o.on("message",ou),o.on("exit",ni),ei.register(t,o),o}function ti(t){tu(!t[g].sync),t[g].needDrain&&(t[g].needDrain=!1,t.emit("drain"))}function ri(t){for(;;){let e=Atomics.load(t[g].state,se),r=t[g].data.length-e;if(r>0){if(t[g].bufLen===0){t[g].flushing=!1,t[g].ending?Hr(t):t[g].needDrain&&process.nextTick(ti,t);return}oi(t,r,Zs);continue}if(r===0){if(e===0&&t[g].bufLen===0)return;Ct(t,()=>{t.destroyed||(Qs(t),ri(t))});return}z(t,new Error("overwritten"));return}}function ou(t){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(t?.code!=null)switch(t.code){case"READY":this.stream=new su(e),Ct(e,()=>{e[g].ready=!0,e.emit("ready")});break;case"ERROR":z(e,t.err);break;case"EVENT":Array.isArray(t.args)?e.emit(t.name,...t.args):e.emit(t.name,t.args);break;case"FLUSHED":{if(t.context!=="thread-stream"){z(e,new Error("this should not happen: "+t.code));break}let r=e[g].flushCallbacks.get(t.id);r&&(e[g].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:z(e,new Error("this should not happen: "+t.code))}}function ni(t){let e=this.stream.deref();e!==void 0&&(ei.unregister(e),e.worker.exited=!0,e.worker.off("exit",ni),z(e,t!==0?new Error("the worker thread exited"):null))}var qr=class extends Gc{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[g]={},this[g].stateBuf=new SharedArrayBuffer(128),this[g].state=new Int32Array(this[g].stateBuf),this[g].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[g].data=Buffer.from(this[g].dataBuf),this[g].sync=e.sync||!1,this[g].ending=!1,this[g].ended=!1,this[g].needDrain=!1,this[g].destroyed=!1,this[g].flushing=!1,this[g].ready=!1,this[g].finished=!1,this[g].errored=null,this[g].closed=!1,this[g].buf=[],this[g].bufHead=0,this[g].bufLen=0,this[g].flushCallbacks=new Map,this[g].nextFlushId=0,this.worker=iu(this,e),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(e){let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[g].destroyed)return Ur(this,new Error("the worker has exited")),!1;if(this[g].ending)return Ur(this,new Error("the worker is ending")),!1;if(this[g].flushing&&this[g].bufLen+r.length>=ru)try{Nr(this),this[g].flushing=!0}catch(n){return z(this,n),!1}if(this[g].buf.push(r),this[g].bufLen+=r.length,this[g].sync)try{return Nr(this),!0}catch(n){return z(this,n),!1}return this[g].flushing||(this[g].flushing=!0,setImmediate(ri,this)),this[g].needDrain=this[g].data.length-this[g].bufLen-Atomics.load(this[g].state,se)<=0,!this[g].needDrain}end(){this[g].destroyed||(this[g].ending=!0,Hr(this))}flush(e){e=typeof e=="function"?e:Zs,si(this,r=>{if(r){process.nextTick(e,r);return}ii(this,e)})}flushSync(){this[g].destroyed||(Nr(this),ai(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[g].ready}get destroyed(){return this[g].destroyed}get closed(){return this[g].closed}get writable(){return!this[g].destroyed&&!this[g].ending}get writableEnded(){return this[g].ending}get writableFinished(){return this[g].finished}get writableNeedDrain(){return this[g].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[g].errored}};function si(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].sync&&(t[g].flushing||t[g].bufLen>0)){setImmediate(si,t,e);return}Ct(t,e)}function Ct(t,e){let r=Atomics.load(t[g].state,se);Qc(t[g].state,ge,r,1/0,(n,s)=>{if(n){z(t,n),e(n);return}if(s!=="ok"){Ct(t,e);return}e()})}function ii(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].ready){let n=()=>{i(),ii(t,e)},s=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",n),t.off("close",s)};t.once("ready",n),t.once("close",s);return}let r=++t[g].nextFlushId;t[g].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[g].flushCallbacks.delete(r),z(t,n),process.nextTick(e,n)}}function au(t,e){let r=t[g].flushCallbacks;if(r.size===0)return;let n=e||new Error("the worker has exited");for(let s of r.values())process.nextTick(s,n);r.clear()}function Ur(t,e){setImmediate(()=>{t.emit("error",e)})}function z(t,e){t[g].destroyed||(t[g].destroyed=!0,au(t,e),e&&(t[g].errored=e,Ur(t,e)),t.worker.exited?setImmediate(()=>{t[g].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[g].closed=!0,t.emit("close")}))}function oi(t,e,r){let s=Atomics.load(t[g].state,se),i=e;for(;i>0&&t[g].bufLen!==0;){let o=t[g].bufHead,a=t[g].buf[o];if(a.length<=i){a.copy(t[g].data,s),s+=a.length,i-=a.length,t[g].bufLen-=a.length,t[g].bufHead=o+1,t[g].bufHead===t[g].buf.length?(t[g].buf.length=0,t[g].bufHead=0):t[g].bufHead>=1024&&t[g].bufHead*2>=t[g].buf.length&&(t[g].buf.splice(0,t[g].bufHead),t[g].bufHead=0);continue}a.copy(t[g].data,s,0,i),t[g].buf[o]=a.subarray(i),t[g].bufLen-=i,s+=i,i=0}return Br(t,()=>{Atomics.store(t[g].state,se,s)}),r(),!0}function Hr(t){if(!(t[g].ended||!t[g].ending||t[g].flushing)){t[g].ended=!0;try{t.flushSync();let e=Atomics.load(t[g].state,ge);Br(t,()=>{Atomics.store(t[g].state,se,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[g].state,ge,e,1e3),e=Atomics.load(t[g].state,ge),e===-2){z(t,new Error("end() failed"));return}if(++r===10){z(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[g].finished=!0,t.emit("finish")})}catch(e){z(t,e)}}}function Nr(t){let e=()=>{t[g].ending?Hr(t):t[g].needDrain&&process.nextTick(ti,t)};for(t[g].flushing=!1;t[g].bufLen!==0;){let r=Atomics.load(t[g].state,se),n=t[g].data.length-r;if(n===0){ai(t),Qs(t);continue}else if(n<0)throw new Error("overwritten");oi(t,n,e)}}function ai(t){if(t[g].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[g].state,se),r=0;for(;;){let n=Atomics.load(t[g].state,ge);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[g].state,ge,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}li.exports=qr});var zr=R((om,di)=>{"use strict";var{createRequire:lu}=require("module"),{existsSync:cu}=require("node:fs"),uu=Or(),{join:Wr,isAbsolute:fi,sep:fu}=require("node:path"),{fileURLToPath:du}=require("node:url"),hu=Fr(),Vr=Lr(),pu=ci();function mu(t){Vr.register(t,Su),Vr.registerBeforeExit(t,_u),t.on("close",function(){Vr.unregister(t)})}function gu(){let t=process.execArgv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--import"||r==="--require"||r==="-r"||r.startsWith("--import=")||r.startsWith("--require=")||r.startsWith("-r="))return!0}return!1}function yu(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let r=[],n=!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&&ui(o)){n=!0,s++;continue}r.push(i),o&&(r.push(o),s++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(ui(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function ui(t){let e=wu(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=du(r)}catch{return!1}return fi(r)&&!cu(r)}function wu(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function bu(t,e,r,n,s){if(!r.execArgv&&gu()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=yu(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new pu({filename:t,workerData:e,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),r.autoEnd!==!1&&mu(i)}function a(){i.closed||(i.flushSync(),hu(100),i.end())}return i}function Su(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function _u(t){t.flushSync()}function xu(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=uu(),sync:a=!1}=t,l={...t.options},u=typeof o=="string"?[o]:o,d=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),f=t.target;if(f&&r)throw new Error("only one of target or targets can be specified");r?(f=d["pino-worker"]||Wr(__dirname,"worker.js"),l.targets=r.filter(c=>c.target).map(c=>({...c,target:h(c.target)})),l.pipelines=r.filter(c=>c.pipeline).map(c=>c.pipeline.map(m=>({...m,level:c.level,target:h(m.target)})))):e&&(f=d["pino-worker"]||Wr(__dirname,"worker.js"),l.pipelines=[e.map(c=>({...c,target:h(c.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let p=r||e?"pino.transport":f;return bu(h(f),l,i,a,p);function h(c){if(c=d[c]||c,fi(c)||c.indexOf("file://")===0)return c;if(c==="pino/file")return Wr(__dirname,"..","file.js");let m;for(let y of u)try{let w=y==="node:repl"?process.cwd()+fu:y;m=lu(w).resolve(c);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${c}"`);return m}}di.exports=xu});var Et=R((am,Ci)=>{"use strict";var vu=require("node:diagnostics_channel"),hi=Ps(),{mapHttpRequest:ku,mapHttpResponse:Cu}=Er(),Jr=Us(),pi=Lr(),{lsCacheSym:Tu,chindingsSym:bi,writeSym:mi,serializersSym:Si,formatOptsSym:gi,endSym:Au,stringifiersSym:_i,stringifySym:xi,stringifySafeSym:Gr,wildcardFirstSym:vi,nestedKeySym:Eu,formattersSym:ki,messageKeySym:Ou,errorKeySym:$u,nestedKeyStrSym:Ru,msgPrefixSym:Tt}=Pe(),{isMainThread:Iu}=require("worker_threads"),Pu=zr(),[Fu]=process.versions.node.split(".").map(t=>Number(t)),yi=vu.tracingChannel("pino_asJson"),Kr=Fu>=25?t=>JSON.stringify(t):Du;function Me(){}function Mu(t,e){if(!e)return r;return function(...s){e.call(this,s,r,t)};function r(n,...s){if(typeof n=="object"){let i=n;n!==null&&(n.method&&n.headers&&n.socket?n=ku(n):typeof n.setHeader=="function"&&(n=Cu(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Tt]=="string"&&i!==void 0&&i!==null&&(i=this[Tt]+i),this[mi](n,hi(i,o,this[gi]),t)}else{let i=n===void 0?s.shift():n;typeof this[Tt]=="string"&&i!==void 0&&i!==null&&(i=this[Tt]+i),this[mi](null,hi(i,s,this[gi]),t)}}}function Du(t){let e="",r=0,n=!1,s=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&s>=32;o++)s=t.charCodeAt(o),(s===34||s===92)&&(e+=t.slice(r,o)+"\\",r=o,n=!0);return n?e+=t.slice(r):e=t,s<32?JSON.stringify(t):'"'+e+'"'}function Lu(t,e,r,n){if(yi.hasSubscribers===!1)return wi.call(this,t,e,r,n);let s={instance:this,arguments};return yi.traceSync(wi,s,this,t,e,r,n)}function wi(t,e,r,n){let s=this[xi],i=this[Gr],o=this[_i],a=this[Au],l=this[bi],u=this[Si],d=this[ki],f=this[Ou],p=this[$u],h=this[Tu][r]+n;h=h+l;let c;d.log&&(t=d.log(t));let m=o[vi],y="";for(let b in t)if(c=t[b],Object.prototype.hasOwnProperty.call(t,b)&&c!==void 0){u[b]?c=u[b](c):b===p&&u.err&&(c=u.err(c));let _=o[b]||m;switch(typeof c){case"undefined":case"function":continue;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":_&&(c=_(c));break;case"string":c=(_||Kr)(c);break;default:c=(_||s)(c,i)}if(c===void 0)continue;let S=Kr(b);y+=","+S+":"+c}let w="";if(e!==void 0){c=u[f]?u[f](e):e;let b=o[f]||m;switch(typeof c){case"function":break;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":b&&(c=b(c)),w=',"'+f+'":'+c;break;case"string":c=(b||Kr)(c),w=',"'+f+'":'+c;break;default:c=(b||s)(c,i),w=',"'+f+'":'+c}}return this[Eu]&&y?h+this[Ru]+y.slice(1)+"}"+w+a:h+y+w+a}function ju(t,e){let r,n=t[bi],s=t[xi],i=t[Gr],o=t[_i],a=o[vi],l=t[Si],u=t[ki].bindings;e=u(e);for(let d in e)if(r=e[d],((d.length<5||d!=="level"&&d!=="serializers"&&d!=="formatters"&&d!=="customLevels")&&e.hasOwnProperty(d)&&r!==void 0)===!0){if(r=l[d]?l[d](r):r,r=(o[d]||a||s)(r,i),r===void 0)continue;n+=',"'+d+'":'+r}return n}function Nu(t){return t.write!==t.constructor.prototype.write}function At(t){let e=new Jr(t);return e.on("error",r),!t.sync&&Iu&&(pi.register(e,qu),e.on("close",function(){pi.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Me,e.end=Me,e.flushSync=Me,e.destroy=Me;return}e.removeListener("error",r),e.emit("error",n)}}function qu(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Uu(t){return function(r,n,s={},i){if(typeof s=="string")i=At({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=At({dest:i})}else if(s instanceof Jr||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof Jr||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=Pu({caller:n,...s.transport,levels:l})}if(s=Object.assign({},t,s),s.serializers=Object.assign({},t.serializers,s.serializers),s.formatters=Object.assign({},t.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=Me),i||(Nu(process.stdout)?i=process.stdout:i=At({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function Bu(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[Gr])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Hu(t,e,r){return{level:t,bindings:e,log:r}}function Wu(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Ci.exports={noop:Me,buildSafeSonicBoom:At,asChindings:ju,asJson:Lu,genLog:Mu,createArgsNormalizer:Uu,stringify:Bu,buildFormatters:Hu,normalizeDestFileDescriptor:Wu}});var Ot=R((lm,Ti)=>{var Vu={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},zu={ASC:"ASC",DESC:"DESC"};Ti.exports={DEFAULT_LEVELS:Vu,SORTING_ORDER:zu}});var Zr=R((cm,$i)=>{"use strict";var{lsCacheSym:Ku,levelValSym:Xr,useOnlyCustomLevelsSym:Ju,streamSym:Gu,formattersSym:Xu,hooksSym:Yu,levelCompSym:Ai}=Pe(),{noop:Zu,genLog:ye}=Et(),{DEFAULT_LEVELS:ee,SORTING_ORDER:Ei}=Ot(),Oi={fatal:t=>{let e=ye(ee.fatal,t);return function(...r){let n=this[Gu];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>ye(ee.error,t),warn:t=>ye(ee.warn,t),info:t=>ye(ee.info,t),debug:t=>ye(ee.debug,t),trace:t=>ye(ee.trace,t)},Yr=Object.keys(ee).reduce((t,e)=>(t[ee[e]]=e,t),{}),Qu=Object.keys(Yr).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function ef(t){let e=t[Xu].level,{labels:r}=t.levels,n={};for(let s in r){let i=e(r[s],Number(s));n[s]=JSON.stringify(i).slice(0,-1)}return t[Ku]=n,t}function tf(t,e){if(e)return!1;switch(t){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function rf(t){let{labels:e,values:r}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(r[t]===void 0)throw Error("unknown level "+t);let n=this[Xr],s=this[Xr]=r[t],i=this[Ju],o=this[Ai],a=this[Yu].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=Zu;continue}this[l]=tf(l,i)?Oi[l](a):ye(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function nf(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function sf(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Ai](r,this[Xr])}function of(t,e,r){return t===Ei.DESC?e<=r:e>=r}function af(t){return typeof t=="string"?of.bind(null,t):t}function lf(t=null,e=!1){let r=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:Yr,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:ee,t);return{labels:n,values:s}}function cf(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(Yr).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:ee,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function uf(t,e){let{labels:r,values:n}=t;for(let s in e){if(s in n)throw Error("levels cannot be overridden");if(e[s]in r)throw Error("pre-existing level values cannot be used for new levels")}}function ff(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Ei).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}$i.exports={initialLsCache:Qu,genLsCache:ef,levelMethods:Oi,getLevel:nf,setLevel:rf,isLevelEnabled:sf,mappings:lf,assertNoLevelCollisions:uf,assertDefaultLevelFound:cf,genLevelComparison:af,assertLevelComparison:ff}});var Qr=R((um,Ri)=>{"use strict";Ri.exports={version:"10.3.1"}});var Ni=R((dm,ji)=>{"use strict";var{EventEmitter:df}=require("node:events"),{lsCacheSym:hf,levelValSym:pf,setLevelSym:tn,getLevelSym:Ii,chindingsSym:Rt,mixinSym:mf,asJsonSym:Fi,writeSym:gf,mixinMergeStrategySym:yf,timeSym:wf,timeSliceIndexSym:bf,streamSym:Mi,serializersSym:we,formattersSym:rt,errorKeySym:Sf,messageKeySym:_f,useOnlyCustomLevelsSym:xf,needsMetadataGsym:vf,redactFmtSym:kf,stringifySym:Cf,formatOptsSym:Tf,stringifiersSym:Af,msgPrefixSym:rn,hooksSym:Ef}=Pe(),{getLevel:Of,setLevel:$f,isLevelEnabled:Rf,mappings:If,initialLsCache:Pf,genLsCache:Ff,assertNoLevelCollisions:Mf}=Zr(),{asChindings:nn,asJson:Df,buildFormatters:en,stringify:Pi,noop:Di}=Et(),{version:Lf}=Qr(),jf=Ir(),Nf=class{},Li={constructor:Nf,child:qf,bindings:Uf,setBindings:Bf,flush:Vf,isLevelEnabled:Rf,version:Lf,get level(){return this[Ii]()},set level(t){this[tn](t)},get levelVal(){return this[pf]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[rn]},get[Symbol.toStringTag](){return"Pino"},[hf]:Pf,[gf]:Wf,[Fi]:Df,[Ii]:Of,[tn]:$f};Object.setPrototypeOf(Li,df.prototype);ji.exports=function(){return Object.create(Li)};var $t=t=>t;function qf(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[we],n=this[rt],s=Object.create(this);if(e==null)return s[rt].bindings!==$t&&(s[rt]=en(n.level,$t,n.log)),s[Rt]=nn(s,t),this.onChild!==Di&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[we]=Object.create(null);for(let u in r)s[we][u]=r[u];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let u=a[i];s[we][u]=r[u]}for(let u in e.serializers)s[we][u]=e.serializers[u];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let u=l[o];s[we][u]=e.serializers[u]}}else s[we]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:u}=e.formatters;s[rt]=en(a||n.level,l||$t,u||n.log)}else s[rt]=en(n.level,$t,n.log);if(e.hasOwnProperty("customLevels")===!0&&(Mf(this.levels,e.customLevels),s.levels=If(e.customLevels,s[xf]),Ff(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=jf(s.redact,Pi),l={stringify:a[kf]};s[Cf]=Pi,s[Af]=a,s[Tf]=l}if(typeof e.msgPrefix=="string"&&(s[rn]=(this[rn]||"")+e.msgPrefix),s[Rt]=nn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[tn](a)}return this.onChild(s),s}function Uf(){let e=`{${this[Rt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Bf(t){let e=nn(this,t);this[Rt]=e}function Hf(t,e){return Object.assign(e,t)}function Wf(t,e,r){let n=this[wf](),s=this[mf],i=this[Sf],o=this[_f],a=this[yf]||Hf,l,u=this[Ef].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(l=a(l,s(l,r,this)));let d=this[Fi](l,e,r,n),f=this[Mi];f[vf]===!0&&(f.lastLevel=r,f.lastObj=l,f.lastMsg=e,f.lastTime=n.slice(this[bf]),f.lastLogger=this),f.write(u?u(d):d)}function Vf(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Mi];typeof e.flush=="function"?e.flush(t||Di):t&&t()}});var Hi=R((ln,Bi)=>{"use strict";var{hasOwnProperty:nt}=Object.prototype,Se=an();Se.configure=an;Se.stringify=Se;Se.default=Se;ln.stringify=Se;ln.configure=an;Bi.exports=Se;var zf=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function ce(t){return t.length<5e3&&!zf.test(t)?`"${t}"`:JSON.stringify(t)}function sn(t,e){if(t.length>200||e)return t.sort(e);for(let r=1;r<t.length;r++){let n=t[r],s=r;for(;s!==0&&t[s-1]>n;)t[s]=t[s-1],s--;t[s]=n}return t}var Kf=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function on(t){return Kf.call(t)!==void 0&&t.length!==0}function qi(t,e,r){t.length<r&&(r=t.length);let n=e===","?"":" ",s=`"0":${n}${t[0]}`;for(let i=1;i<r;i++)s+=`${e}"${i}":${n}${t[i]}`;return s}function Jf(t){if(nt.call(t,"circularValue")){let e=t.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 Gf(t){let e;if(nt.call(t,"deterministic")&&(e=t.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 Xf(t,e){let r;if(nt.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function Ui(t,e){let r;if(nt.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function be(t){return t===1?"1 item":`${t} items`}function Yf(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function Zf(t){if(nt.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function an(t){t={...t};let e=Zf(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Jf(t),n=Xf(t,"bigint"),s=Gf(t),i=typeof s=="function"?s:void 0,o=Ui(t,"maximumDepth"),a=Ui(t,"maximumBreadth");function l(h,c,m,y,w,b){let _=c[h];switch(typeof _=="object"&&_!==null&&typeof _.toJSON=="function"&&(_=_.toJSON(h)),_=y.call(c,h,_),typeof _){case"string":return ce(_);case"object":{if(_===null)return"null";if(m.indexOf(_)!==-1)return r;let S="",v=",",$=b;if(Array.isArray(_)){if(_.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(_),w!==""&&(b+=w,S+=`
26
+ ${b}`,v=`,
27
+ ${b}`);let F=Math.min(_.length,a),q=0;for(;q<F-1;q++){let U=l(String(q),_,m,y,w,b);S+=U!==void 0?U:"null",S+=v}let N=l(String(q),_,m,y,w,b);if(S+=N!==void 0?N:"null",_.length-1>a){let U=_.length-a-1;S+=`${v}"... ${be(U)} not stringified"`}return w!==""&&(S+=`
28
+ ${$}`),m.pop(),`[${S}]`}let T=Object.keys(_),O=T.length;if(O===0)return"{}";if(o<m.length+1)return'"[Object]"';let C="",I="";w!==""&&(b+=w,v=`,
29
+ ${b}`,C=" ");let L=Math.min(O,a);s&&!on(_)&&(T=sn(T,i)),m.push(_);for(let F=0;F<L;F++){let q=T[F],N=l(q,_,m,y,w,b);N!==void 0&&(S+=`${I}${ce(q)}:${C}${N}`,I=v)}if(O>a){let F=O-a;S+=`${I}"...":${C}"${be(F)} not stringified"`,I=v}return w!==""&&I.length>1&&(S=`
30
+ ${b}${S}
31
+ ${$}`),m.pop(),`{${S}}`}case"number":return isFinite(_)?String(_):e?e(_):"null";case"boolean":return _===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(_);default:return e?e(_):void 0}}function u(h,c,m,y,w,b){switch(typeof c=="object"&&c!==null&&typeof c.toJSON=="function"&&(c=c.toJSON(h)),typeof c){case"string":return ce(c);case"object":{if(c===null)return"null";if(m.indexOf(c)!==-1)return r;let _=b,S="",v=",";if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),w!==""&&(b+=w,S+=`
32
+ ${b}`,v=`,
33
+ ${b}`);let O=Math.min(c.length,a),C=0;for(;C<O-1;C++){let L=u(String(C),c[C],m,y,w,b);S+=L!==void 0?L:"null",S+=v}let I=u(String(C),c[C],m,y,w,b);if(S+=I!==void 0?I:"null",c.length-1>a){let L=c.length-a-1;S+=`${v}"... ${be(L)} not stringified"`}return w!==""&&(S+=`
34
+ ${_}`),m.pop(),`[${S}]`}m.push(c);let $="";w!==""&&(b+=w,v=`,
35
+ ${b}`,$=" ");let T="";for(let O of y){let C=u(O,c[O],m,y,w,b);C!==void 0&&(S+=`${T}${ce(O)}:${$}${C}`,T=v)}return w!==""&&T.length>1&&(S=`
36
+ ${b}${S}
37
+ ${_}`),m.pop(),`{${S}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function d(h,c,m,y,w){switch(typeof c){case"string":return ce(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(h),typeof c!="object")return d(h,c,m,y,w);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let b=w;if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),w+=y;let C=`
38
+ ${w}`,I=`,
39
+ ${w}`,L=Math.min(c.length,a),F=0;for(;F<L-1;F++){let N=d(String(F),c[F],m,y,w);C+=N!==void 0?N:"null",C+=I}let q=d(String(F),c[F],m,y,w);if(C+=q!==void 0?q:"null",c.length-1>a){let N=c.length-a-1;C+=`${I}"... ${be(N)} not stringified"`}return C+=`
40
+ ${b}`,m.pop(),`[${C}]`}let _=Object.keys(c),S=_.length;if(S===0)return"{}";if(o<m.length+1)return'"[Object]"';w+=y;let v=`,
41
+ ${w}`,$="",T="",O=Math.min(S,a);on(c)&&($+=qi(c,v,a),_=_.slice(c.length),O-=c.length,T=v),s&&(_=sn(_,i)),m.push(c);for(let C=0;C<O;C++){let I=_[C],L=d(I,c[I],m,y,w);L!==void 0&&($+=`${T}${ce(I)}: ${L}`,T=v)}if(S>a){let C=S-a;$+=`${T}"...": "${be(C)} not stringified"`,T=v}return T!==""&&($=`
42
+ ${w}${$}
43
+ ${b}`),m.pop(),`{${$}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function f(h,c,m){switch(typeof c){case"string":return ce(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(h),typeof c!="object")return f(h,c,m);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let y="",w=c.length!==void 0;if(w&&Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c);let $=Math.min(c.length,a),T=0;for(;T<$-1;T++){let C=f(String(T),c[T],m);y+=C!==void 0?C:"null",y+=","}let O=f(String(T),c[T],m);if(y+=O!==void 0?O:"null",c.length-1>a){let C=c.length-a-1;y+=`,"... ${be(C)} not stringified"`}return m.pop(),`[${y}]`}let b=Object.keys(c),_=b.length;if(_===0)return"{}";if(o<m.length+1)return'"[Object]"';let S="",v=Math.min(_,a);w&&on(c)&&(y+=qi(c,",",a),b=b.slice(c.length),v-=c.length,S=","),s&&(b=sn(b,i)),m.push(c);for(let $=0;$<v;$++){let T=b[$],O=f(T,c[T],m);O!==void 0&&(y+=`${S}${ce(T)}:${O}`,S=",")}if(_>a){let $=_-a;y+=`${S}"...":"${be($)} not stringified"`}return m.pop(),`{${y}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function p(h,c,m){if(arguments.length>1){let y="";if(typeof m=="number"?y=" ".repeat(Math.min(m,10)):typeof m=="string"&&(y=m.slice(0,10)),c!=null){if(typeof c=="function")return l("",{"":h},[],c,y,"");if(Array.isArray(c))return u("",h,[],Yf(c),y,"")}if(y.length!==0)return d("",h,[],y,"")}return f("",h,[])}return p}});var Ki=R((hm,zi)=>{"use strict";var cn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Vi}=Ot(),Qf=Vi.info;function ed(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(Vi);r.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(f=>{r[f]=e.levels[f]});let n={write:s,add:a,remove:l,emit:i,flushSync:o,end:u,minLevel:0,lastId:0,streams:[],clone:d,[cn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(f){let p,h=this.lastLevel,{streams:c}=this,m=0,y;for(let w=td(c.length,e.dedupe);nd(w,c.length,e.dedupe);w=rd(w,e.dedupe))if(p=c[w],p.level<=h){if(m!==0&&m!==p.level)break;if(y=p.stream,y[cn]){let{lastTime:b,lastMsg:_,lastObj:S,lastLogger:v}=this;y.lastLevel=h,y.lastTime=b,y.lastMsg=_,y.lastObj=S,y.lastLogger=v}y.write(f),e.dedupe&&(m=p.level)}else if(!e.dedupe)break}function i(...f){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.emit(...f)}function o(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync()}function a(f){if(!f)return n;let p=typeof f.write=="function"||f.stream,h=f.write?f:f.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:c,streamLevels:m}=this,y;typeof f.levelVal=="number"?y=f.levelVal:typeof f.level=="string"?y=m[f.level]:typeof f.level=="number"?y=f.level:y=Qf;let w={stream:h,level:y,levelVal:void 0,id:++n.lastId};return c.unshift(w),c.sort(Wi),this.minLevel=c[0].level,n}function l(f){let{streams:p}=this,h=p.findIndex(c=>c.id===f);return h>=0&&(p.splice(h,1),p.sort(Wi),this.minLevel=p.length>0?p[0].level:-1),n}function u(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync(),f.end()}function d(f){let p=new Array(this.streams.length);for(let h=0;h<p.length;h++)p[h]={level:f,stream:this.streams[h].stream};return{write:s,add:a,remove:l,minLevel:f,streams:p,clone:d,emit:i,flushSync:o,[cn]:!0}}}function Wi(t,e){return t.level-e.level}function td(t,e){return e?t-1:0}function rd(t,e){return e?t-1:t+1}function nd(t,e,r){return r?t>=0:t<e}zi.exports=ed});var ao=R((pm,K)=>{"use strict";var sd=require("node:os"),to=Er(),id=Or(),od=Ir(),ro=Rs(),ad=Ni(),no=Pe(),{configure:ld}=Hi(),{assertDefaultLevelFound:cd,mappings:so,genLsCache:ud,genLevelComparison:fd,assertLevelComparison:dd}=Zr(),{DEFAULT_LEVELS:io,SORTING_ORDER:hd}=Ot(),{createArgsNormalizer:pd,asChindings:md,buildSafeSonicBoom:Ji,buildFormatters:gd,stringify:un,normalizeDestFileDescriptor:Gi,noop:yd}=Et(),{version:wd}=Qr(),{chindingsSym:Xi,redactFmtSym:bd,serializersSym:Yi,timeSym:Sd,timeSliceIndexSym:_d,streamSym:xd,stringifySym:Zi,stringifySafeSym:fn,stringifiersSym:Qi,setLevelSym:vd,endSym:kd,formatOptsSym:Cd,messageKeySym:Td,errorKeySym:Ad,nestedKeySym:Ed,mixinSym:Od,levelCompSym:$d,useOnlyCustomLevelsSym:Rd,formattersSym:eo,hooksSym:Id,nestedKeyStrSym:Pd,mixinMergeStrategySym:Fd,msgPrefixSym:Md}=no,{epochTime:oo,nullTime:Dd}=ro,{pid:Ld}=process,jd=sd.hostname(),Nd=to.err,qd={level:"info",levelComparison:hd.ASC,levels:io,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Ld,hostname:jd},serializers:Object.assign(Object.create(null),{err:Nd}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:oo,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Ud=pd(qd),Bd=Object.assign(Object.create(null),to);function dn(...t){let e={},{opts:r,stream:n}=Ud(e,id(),...t);r.level&&typeof r.level=="string"&&io[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:u,nestedKey:d,base:f,name:p,level:h,customLevels:c,levelComparison:m,mixin:y,mixinMergeStrategy:w,useOnlyCustomLevels:b,formatters:_,hooks:S,depthLimit:v,edgeLimit:$,onChild:T,msgPrefix:O}=r,C=ld({maximumDepth:v,maximumBreadth:$}),I=gd(_.level,_.bindings,_.log),L=un.bind({[fn]:C}),F=s?od(s,L):{},q=s?{stringify:F[bd]}:{stringify:L},N="}"+(i?`\r
44
+ `:`
45
+ `),U=md.bind(null,{[Xi]:"",[Yi]:o,[Qi]:F,[Zi]:un,[fn]:C,[eo]:I}),P="";f!==null&&(p===void 0?P=U(f):P=U(Object.assign({},f,{name:p})));let B=a instanceof Function?a:a?oo:Dd,er=B().indexOf(":")+1;if(b&&!c)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(O&&typeof O!="string")throw Error(`Unknown msgPrefix type "${typeof O}" - expected "string"`);cd(h,c,b);let tr=so(c,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:tr,messageKey:l,errorKey:u}}),dd(m);let rr=fd(m);return Object.assign(e,{levels:tr,[$d]:rr,[Rd]:b,[xd]:n,[Sd]:B,[_d]:er,[Zi]:un,[fn]:C,[Qi]:F,[kd]:N,[Cd]:q,[Td]:l,[Ad]:u,[Ed]:d,[Pd]:d?`,${JSON.stringify(d)}:{`:"",[Yi]:o,[Od]:y,[Fd]:w,[Xi]:P,[eo]:I,[Id]:S,silent:yd,onChild:T,[Md]:O}),Object.setPrototypeOf(e,ad()),ud(e),e[vd](h),e}K.exports=dn;K.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=Gi(t.dest||process.stdout.fd),Ji(t)):Ji({dest:Gi(t),minLength:0});K.exports.transport=zr();K.exports.multistream=Ki();K.exports.levels=so();K.exports.stdSerializers=Bd;K.exports.stdTimeFunctions=Object.assign({},ro);K.exports.symbols=no;K.exports.version=wd;K.exports.default=dn;K.exports.pino=dn});var Jn=k(Kn(),1),{program:kp,createCommand:Cp,createArgument:Tp,createOption:Ap,CommanderError:Ep,InvalidArgumentError:Op,InvalidOptionArgumentError:$p,Command:Gn,Argument:Rp,Option:Ip,Help:Pp}=Jn.default;var X=k(require("fs")),me=k(require("path")),Xn=k(require("os"));var Ze={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:200,timeout:12e4,autoMode:!1,contextBudget:12e4,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0}},ne={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","stepfun-ai/step-3.5-flash","nvidia/llama-3.1-nemotron-70b-instruct","qwen/qwen2.5-coder-32b-instruct","deepseek-ai/deepseek-coder-33b-instruct"]};var Re=me.join(Xn.homedir(),".hablas"),wr=me.join(Re,"config.json");function Ie(t={}){let e={};if(X.existsSync(wr))try{e=JSON.parse(X.readFileSync(wr,"utf-8"))}catch{}let r={...Ze,...e,tools:{...Ze.tools,...e.tools||{},runCommand:{...Ze.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...Ze.workspace,...e.workspace||{}}};if(process.env.HABLAS_API_URL&&(r.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(r.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_MODEL&&(r.model=process.env.HABLAS_MODEL),process.env.HABLAS_PROVIDER){let n=process.env.HABLAS_PROVIDER;(n==="ollama"||n==="custom"||n==="nvidia")&&(r.provider=n)}if(t.model&&(r.model=t.model),t.host&&(r.ollamaHost=t.host),t.project&&(r.workingDirectory=me.resolve(t.project)),t.provider){let n=t.provider;(n==="ollama"||n==="custom"||n==="nvidia")&&(r.provider=n)}return t.apiUrl&&(r.apiUrl=t.apiUrl),t.apiKey&&(r.apiKey=t.apiKey),r.apiUrl&&r.provider==="ollama"&&(r.provider="custom"),r}function Qe(t){X.existsSync(Re)||X.mkdirSync(Re,{recursive:!0}),X.writeFileSync(wr,JSON.stringify(t,null,2),"utf-8")}function Yn(){let t=[Re,me.join(Re,"logs"),me.join(Re,"backup")];for(let e of t)X.existsSync(e)||X.mkdirSync(e,{recursive:!0})}var hn=k(ao()),pn=k(require("path")),lo=k(require("os")),It=k(require("fs"));function mn(t){let e=pn.join(lo.homedir(),".hablas","logs");It.existsSync(e)||It.mkdirSync(e,{recursive:!0});let r=pn.join(e,`session-${Date.now()}.log`);return(0,hn.default)({level:"info"},hn.default.destination({dest:r,sync:!1}))}var Pt=k(require("fs")),st=k(require("path"));function co(){let t=[st.resolve(__dirname,"..","package.json"),st.resolve(__dirname,"..","..","package.json"),st.resolve(process.cwd(),"package.json"),st.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(Pt.existsSync(e)){let r=JSON.parse(Pt.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Ta=k(require("fs")),Aa=k(require("path"));var Ft=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(n=>n.name):[]}catch{return[]}}async chatWithTools(e,r,n){let s={model:this.model,messages:e,stream:!1};r.length>0&&(s.tools=r);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)};n&&(i.signal=n);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,r){let n=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:r});if(!n.ok)throw new Error(`Ollama error: ${n.status} ${n.statusText}`);let s=n.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 u=o.split(`
46
+ `);o=u.pop()||"";for(let d of u)if(d.trim())try{let f=JSON.parse(d);f.message?.content&&(yield f.message.content)}catch{}}}};var uo=12e4,Hd=6e4,Mt=3,fo=1e3,Wd=20;function ho(t){return t.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let r=e.tool_calls.filter(n=>n?.function?.name);if(r.length>0)return{role:"assistant",content:e.content||null,tool_calls:r.map((n,s)=>({id:`call_${s}`,type:"function",function:{name:n.function?.name||"",arguments:JSON.stringify(n.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function Vd(t){return t.map(e=>({type:"function",function:e.function}))}function zd(t){return t.filter(e=>e?.function?.name).map(e=>{let r={};try{r=JSON.parse(e.function?.arguments||"{}")}catch{r={_raw:e.function?.arguments}}return{function:{name:e.function?.name||"",arguments:r}}})}function po(t){return new Promise(e=>setTimeout(e,t))}function mo(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var it=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=[],r=!0,n,s=0;for(;r&&s<Wd;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;n&&o.set("after",n),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let l=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(Hd)});if(!l.ok)break;let u=await l.json();if(Array.isArray(u))e.push(...u.map(d=>d.id||d.name||d).filter(Boolean)),r=!1;else if(u.data&&Array.isArray(u.data)){let d=u.data.map(f=>f.id||f.name).filter(Boolean);e.push(...d),u.has_more&&d.length>0?(n=d[d.length-1],s++):r=!1}else u.models&&Array.isArray(u.models)&&e.push(...u.models.map(d=>d.name||d.id).filter(Boolean)),r=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,r,n){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:ho(e)};r.length>0&&(i.tools=Vd(r),i.tool_choice="auto");let o=null;for(let a=0;a<=Mt;a++)try{let l=new AbortController,u=setTimeout(()=>l.abort(),uo),d={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:n||l.signal};try{let f=await fetch(s,d);if(clearTimeout(u),!f.ok){let m=await f.text().catch(()=>"");if(!mo(null,f.status))throw new Error(`API error: ${f.status} ${f.statusText} \u2014 ${m}`);if(o=new Error(`API error: ${f.status} ${f.statusText} \u2014 ${m}`),a<Mt){let y=fo*Math.pow(2,a);await po(y);continue}throw o}let h=(await f.json()).choices?.[0];if(!h)throw new Error("API returned empty response");let c=h.message.tool_calls?zd(h.message.tool_calls):void 0;return{message:{role:h.message.role||"assistant",content:h.message.content||"",tool_calls:c},done:!0,done_reason:h.finish_reason}}catch(f){if(clearTimeout(u),f.name==="AbortError"&&n?.aborted)throw f;if(mo(f)&&(o=f,a<Mt)){let p=fo*Math.pow(2,a);await po(p);continue}throw f}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Mt)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,r){let n=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:ho(e),stream:!0}),signal:r||AbortSignal.timeout(uo)});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:u}=await i.read();if(l)break;a+=o.decode(u,{stream:!0});let d=a.split(`
47
+ `);a=d.pop()||"";for(let f of d){let p=f.trim();if(!(!p||p==="data: [DONE]")&&p.startsWith("data: "))try{let c=JSON.parse(p.slice(6)).choices?.[0]?.delta?.content;c&&(yield c)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function De(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:ne.apiUrl};return new it(e)}return t.provider==="custom"&&t.apiUrl?new it(t):new Ft(t)}function Le(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var D=k(require("fs/promises")),vn=k(require("fs")),ue=k(require("path"));function ie(){}ie.prototype={diff:function(e,r){var n,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(S){return i?(setTimeout(function(){i(void 0,S)},0),!0):S}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,u=e.length,d=1,f=l+u;s.maxEditLength&&(f=Math.min(f,s.maxEditLength));var p=(n=s.timeout)!==null&&n!==void 0?n:1/0,h=Date.now()+p,c=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(c[0],r,e,0);if(c[0].oldPos+1>=u&&m+1>=l)return a([{value:this.join(r),count:r.length}]);var y=-1/0,w=1/0;function b(){for(var S=Math.max(y,-d);S<=Math.min(w,d);S+=2){var v=void 0,$=c[S-1],T=c[S+1];$&&(c[S-1]=void 0);var O=!1;if(T){var C=T.oldPos-S;O=T&&0<=C&&C<l}var I=$&&$.oldPos+1<u;if(!O&&!I){c[S]=void 0;continue}if(!I||O&&$.oldPos+1<T.oldPos?v=o.addToPath(T,!0,void 0,0):v=o.addToPath($,void 0,!0,1),m=o.extractCommon(v,r,e,S),v.oldPos+1>=u&&m+1>=l)return a(Kd(o,v.lastComponent,r,e,o.useLongestToken));c[S]=v,v.oldPos+1>=u&&(w=Math.min(w,S-1)),m+1>=l&&(y=Math.max(y,S+1))}d++}if(i)(function S(){setTimeout(function(){if(d>f||Date.now()>h)return i();b()||S()},0)})();else for(;d<=f&&Date.now()<=h;){var _=b();if(_)return _}},addToPath:function(e,r,n,s){var i=e.lastComponent;return i&&i.added===r&&i.removed===n?{oldPos:e.oldPos+s,lastComponent:{count:i.count+1,added:r,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+s,lastComponent:{count:1,added:r,removed:n,previousComponent:i}}},extractCommon:function(e,r,n,s){for(var i=r.length,o=n.length,a=e.oldPos,l=a-s,u=0;l+1<i&&a+1<o&&this.equals(r[l+1],n[a+1]);)l++,a++,u++;return u&&(e.lastComponent={count:u,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,r){return this.options.comparator?this.options.comparator(e,r):e===r||this.options.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function Kd(t,e,r,n,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,u=0,d=0;a<l;a++){var f=i[a];if(f.removed){if(f.value=t.join(n.slice(d,d+f.count)),d+=f.count,a&&i[a-1].added){var h=i[a-1];i[a-1]=i[a],i[a]=h}}else{if(!f.added&&s){var p=r.slice(u,u+f.count);p=p.map(function(m,y){var w=n[d+y];return w.length>m.length?w:m}),f.value=t.join(p)}else f.value=t.join(r.slice(u,u+f.count));u+=f.count,f.added||(d+=f.count)}}var c=i[l-1];return l>1&&typeof c.value=="string"&&(c.added||c.removed)&&t.equals("",c.value)&&(i[l-2].value+=c.value,i.pop()),i}var Om=new ie;var go=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,yo=/\S/,wo=new ie;wo.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!yo.test(t)&&!yo.test(e)};wo.tokenize=function(t){for(var e=t.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),r=0;r<e.length-1;r++)!e[r+1]&&e[r+2]&&go.test(e[r])&&go.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var Sn=new ie;Sn.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
48
+ `));var e=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var n=0;n<r.length;n++){var s=r[n];n%2&&!this.options.newlineIsToken?e[e.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),e.push(s))}return e};function Jd(t,e,r){return Sn.diff(t,e,r)}var Gd=new ie;Gd.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var Xd=new ie;Xd.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Dt(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Dt=function(e){return typeof e}:Dt=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Dt(t)}function gn(t){return Yd(t)||Zd(t)||Qd(t)||eh()}function Yd(t){if(Array.isArray(t))return yn(t)}function Zd(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Qd(t,e){if(t){if(typeof t=="string")return yn(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return yn(t,e)}}function yn(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function eh(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
49
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var th=Object.prototype.toString,ot=new ie;ot.useLongestToken=!0;ot.tokenize=Sn.tokenize;ot.castInput=function(t){var e=this.options,r=e.undefinedReplacement,n=e.stringifyReplacer,s=n===void 0?function(i,o){return typeof o>"u"?r:o}:n;return typeof t=="string"?t:JSON.stringify(wn(t,null,null,s),s," ")};ot.equals=function(t,e){return ie.prototype.equals.call(ot,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function wn(t,e,r,n,s){e=e||[],r=r||[],n&&(t=n(s,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var o;if(th.call(t)==="[object Array]"){for(e.push(t),o=new Array(t.length),r.push(o),i=0;i<t.length;i+=1)o[i]=wn(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),Dt(t)==="object"&&t!==null){e.push(t),o={},r.push(o);var a=[],l;for(l in t)t.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],o[l]=wn(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var bn=new ie;bn.tokenize=function(t){return t.slice()};bn.join=bn.removeEmpty=function(t){return t};function rh(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Jd(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(w){return w.map(function(b){return" "+b})}for(var u=[],d=0,f=0,p=[],h=1,c=1,m=function(b){var _=a[b],S=_.lines||_.value.replace(/\n$/,"").split(`
50
+ `);if(_.lines=S,_.added||_.removed){var v;if(!d){var $=a[b-1];d=h,f=c,$&&(p=o.context>0?l($.lines.slice(-o.context)):[],d-=p.length,f-=p.length)}(v=p).push.apply(v,gn(S.map(function(N){return(_.added?"+":"-")+N}))),_.added?c+=S.length:h+=S.length}else{if(d)if(S.length<=o.context*2&&b<a.length-2){var T;(T=p).push.apply(T,gn(l(S)))}else{var O,C=Math.min(S.length,o.context);(O=p).push.apply(O,gn(l(S.slice(0,C))));var I={oldStart:d,oldLines:h-d+C,newStart:f,newLines:c-f+C,lines:p};if(b>=a.length-2&&S.length<=o.context){var L=/\n$/.test(r),F=/\n$/.test(n),q=S.length==0&&p.length>I.oldLines;!L&&q&&r.length>0&&p.splice(I.oldLines,0,"\"),(!L&&!q||!F)&&p.push("\")}u.push(I),d=0,f=0,p=[]}h+=S.length,c+=S.length}},y=0;y<a.length;y++)m(y);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:u}}function bo(t){if(Array.isArray(t))return t.map(bo).join(`
51
+ `);var e=[];t.oldFileName==t.newFileName&&e.push("Index: "+t.oldFileName),e.push("==================================================================="),e.push("--- "+t.oldFileName+(typeof t.oldHeader>"u"?"":" "+t.oldHeader)),e.push("+++ "+t.newFileName+(typeof t.newHeader>"u"?"":" "+t.newHeader));for(var r=0;r<t.hunks.length;r++){var n=t.hunks[r];n.oldLines===0&&(n.oldStart-=1),n.newLines===0&&(n.newStart-=1),e.push("@@ -"+n.oldStart+","+n.oldLines+" +"+n.newStart+","+n.newLines+" @@"),e.push.apply(e,n.lines)}return e.join(`
236
52
  `)+`
237
- `}function gb(n,e,t,s,r,i,o){return Uu(mb(n,e,t,s,r,i,o))}function qu(n,e,t,s,r,i){return gb(n,n,e,t,s,r,i)}var qC,Nu,ju,Hu,fo,ob,ab,fb,Xn,uo,Ku=L(()=>{Et.prototype={diff:function(e,t){var s,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=r.callback;typeof r=="function"&&(i=r,r={}),this.options=r;var o=this;function a(y){return i?(setTimeout(function(){i(void 0,y)},0),!0):y}e=this.castInput(e),t=this.castInput(t),e=this.removeEmpty(this.tokenize(e)),t=this.removeEmpty(this.tokenize(t));var l=t.length,u=e.length,d=1,f=l+u;r.maxEditLength&&(f=Math.min(f,r.maxEditLength));var h=(s=r.timeout)!==null&&s!==void 0?s:1/0,m=Date.now()+h,p=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(p[0],t,e,0);if(p[0].oldPos+1>=u&&g+1>=l)return a([{value:this.join(t),count:t.length}]);var S=-1/0,x=1/0;function $(){for(var y=Math.max(S,-d);y<=Math.min(x,d);y+=2){var b=void 0,v=p[y-1],w=p[y+1];v&&(p[y-1]=void 0);var _=!1;if(w){var T=w.oldPos-y;_=w&&0<=T&&T<l}var P=v&&v.oldPos+1<u;if(!_&&!P){p[y]=void 0;continue}if(!P||_&&v.oldPos+1<w.oldPos?b=o.addToPath(w,!0,void 0,0):b=o.addToPath(v,void 0,!0,1),g=o.extractCommon(b,t,e,y),b.oldPos+1>=u&&g+1>=l)return a(rb(o,b.lastComponent,t,e,o.useLongestToken));p[y]=b,b.oldPos+1>=u&&(x=Math.min(x,y-1)),g+1>=l&&(S=Math.max(S,y+1))}d++}if(i)(function y(){setTimeout(function(){if(d>f||Date.now()>m)return i();$()||y()},0)})();else for(;d<=f&&Date.now()<=m;){var k=$();if(k)return k}},addToPath:function(e,t,s,r){var i=e.lastComponent;return i&&i.added===t&&i.removed===s?{oldPos:e.oldPos+r,lastComponent:{count:i.count+1,added:t,removed:s,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:s,previousComponent:i}}},extractCommon:function(e,t,s,r){for(var i=t.length,o=s.length,a=e.oldPos,l=a-r,u=0;l+1<i&&a+1<o&&this.equals(t[l+1],s[a+1]);)l++,a++,u++;return u&&(e.lastComponent={count:u,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,t){return this.options.comparator?this.options.comparator(e,t):e===t||this.options.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],s=0;s<e.length;s++)e[s]&&t.push(e[s]);return t},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};qC=new Et,Nu=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,ju=/\S/,Hu=new Et;Hu.equals=function(n,e){return this.options.ignoreCase&&(n=n.toLowerCase(),e=e.toLowerCase()),n===e||this.options.ignoreWhitespace&&!ju.test(n)&&!ju.test(e)};Hu.tokenize=function(n){for(var e=n.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),t=0;t<e.length-1;t++)!e[t+1]&&e[t+2]&&Nu.test(e[t])&&Nu.test(e[t+2])&&(e[t]+=e[t+2],e.splice(t+1,2),t--);return e};fo=new Et;fo.tokenize=function(n){this.options.stripTrailingCr&&(n=n.replace(/\r\n/g,`
238
- `));var e=[],t=n.split(/(\n|\r\n)/);t[t.length-1]||t.pop();for(var s=0;s<t.length;s++){var r=t[s];s%2&&!this.options.newlineIsToken?e[e.length-1]+=r:(this.options.ignoreWhitespace&&(r=r.trim()),e.push(r))}return e};ob=new Et;ob.tokenize=function(n){return n.split(/(\S.+?[.!?])(?=\s+|$)/)};ab=new Et;ab.tokenize=function(n){return n.split(/([{}:;,]|\s+)/)};fb=Object.prototype.toString,Xn=new Et;Xn.useLongestToken=!0;Xn.tokenize=fo.tokenize;Xn.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(co(n,null,null,r),r," ")};Xn.equals=function(n,e){return Et.prototype.equals.call(Xn,n.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};uo=new Et;uo.tokenize=function(n){return n.slice()};uo.join=uo.removeEmpty=function(n){return n}});var Wu={};Le(Wu,{applyDiff:()=>yb,formatDiffForDisplay:()=>bb,generateDiff:()=>er});function er(n,e,t){return qu(n,e,t,"original","modified")}function yb(n,e){return Bu(n,e)}function bb(n){return n.split(`
239
- `).map(t=>t.startsWith("+")&&!t.startsWith("+++")?`\x1B[32m${t}\x1B[0m`:t.startsWith("-")&&!t.startsWith("---")?`\x1B[31m${t}\x1B[0m`:t.startsWith("@@")?`\x1B[36m${t}\x1B[0m`:t).join(`
240
- `)}var po=L(()=>{"use strict";Ku()});async function bn(n,e){let t=[],s=Ae.join(n,"package.json");if(me.existsSync(s))try{let o=JSON.parse(me.readFileSync(s,"utf-8"));t.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&t.push(`Description: ${o.description}`);let a=Object.keys(o.dependencies||{}).concat(Object.keys(o.devDependencies||{}));a.length>0&&t.push(`Key deps: ${a.slice(0,15).join(", ")}${a.length>15?"...":""}`)}catch{}if(e?.workspace?.frameworkDetection){let o=Ys(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 Xi(n);o&&(t.push(`Git branch: ${o.branch}`),o.modified.length>0&&t.push(`Modified files: ${o.modified.length}`),o.staged.length>0&&t.push(`Staged files: ${o.staged.length}`))}catch{}if(e?.workspace?.envParsing){let a=[".env",".env.local",".env.development",".env.production"].filter(l=>me.existsSync(Ae.join(n,l)));a.length>0&&t.push(`Env files: ${a.join(", ")}`)}let i=["tsconfig.json",".eslintrc.json","vite.config.ts","next.config.js","tailwind.config.js"].filter(o=>me.existsSync(Ae.join(n,o)));if(i.length>0&&t.push(`Config: ${i.join(", ")}`),e?.context?.projectGraph)try{let o=me.readdirSync(n).filter(a=>!["node_modules",".git","dist","build",".next",".cache"].includes(a)).filter(a=>!a.startsWith(".")).slice(0,25);o.length>0&&t.push(`Structure: ${o.join(", ")}`)}catch{}else try{let o=me.readdirSync(n).filter(a=>!["node_modules",".git","dist","build",".next",".cache"].includes(a)).filter(a=>!a.startsWith(".")).slice(0,20);o.length>0&&t.push(`Structure: ${o.join(", ")}`)}catch{}return t.push(`Directory: ${n}`),e?.agents?.enabled&&(t.push("Multi-Agent: enabled (Team Leader: Hablas)"),t.push("Team: @Hablas (Leader), @Bob (Architect), @Alex (Engineer), @David (Data Analyst), @Emma (Product Manager)")),t.join(`
241
- `)}function vn(n,e,t,s){let r=n+`
242
-
243
- ## Current Project
244
- `+e;if(t){let i=t.getSummary();i&&(r+=`
245
-
246
- `+i)}if(s){let i=s.getSummary();i&&(r+=`
247
-
248
- ## Shared Context
249
- `+i)}return r+=`
250
-
251
- `+au(),r}async function vb(n){try{if(!me.existsSync(ho))return null;let t=(await Nt.readdir(ho)).filter(f=>f.endsWith(".bak"));if(n){let f=Ae.basename(n);t=t.filter(h=>h.startsWith(`${f}.`))}if(t.length===0)return null;t.sort().reverse();let s=t[0],r=Ae.join(ho,s),i=s.replace(".bak","").split("."),o=parseInt(i[i.length-1],10),a=i.slice(0,-1).join("."),l=Date.now()-o,u=Math.floor(l/6e4),d=u<1?"just now":u<60?`${u} minutes ago`:`${Math.floor(u/60)} hours ago`;return{backupPath:r,originalName:a,age:d}}catch{return null}}async function Gu(n,e,t,s,r,i,o,a,l,u,d,f,h,m,p,g,S){let x=n.split(/\s+/),$=x[0],k=x.slice(1).join(" ");switch($){case"/quit":case"/exit":return"quit";case"/help":console.log(_u()),console.log(c.muted(" Model & Provider:")),console.log(c.muted(" /addmodel Interactive wizard to add a custom API")),console.log(c.muted(" /listmodels Show saved providers")),console.log(c.muted(" /removemodel <name> Remove a saved provider")),console.log(c.muted(" /usemodel <name> Switch to a saved provider")),console.log(c.muted(" /models [page|search] Browse all available models")),console.log(c.muted(" /provider Show/switch API provider")),console.log(),console.log(c.muted(" Aliases & Plugins:")),console.log(c.muted(" /alias Show all aliases")),console.log(c.muted(" /alias set <n> <cmd> Create an alias")),console.log(c.muted(" /alias del <name> Remove an alias")),console.log(c.muted(" /plugins List installed plugins")),console.log(c.muted(" /doctor Run system diagnostics")),console.log(),console.log(c.muted(" Task & Memory:")),console.log(c.muted(" /task add <desc> Add a task to the queue")),console.log(c.muted(" /task list Show all tasks")),console.log(c.muted(" /task clear Clear task queue")),console.log(c.muted(" /memory Show project memory")),console.log(c.muted(" /memory set <k> <v> Store a memory")),console.log(c.muted(" /memory del <key> Delete a memory")),console.log(c.muted(" /memory clear Clear all memory")),console.log(),console.log(c.muted(" Multi-Agent & Tools:")),console.log(c.muted(" /team Show team roster")),console.log(c.muted(" /delegate <agent> <t> Manually assign task to agent")),console.log(c.muted(" /agents Multi-agent system control")),console.log(c.muted(" /agents on|off Enable/disable multi-agent")),console.log(c.muted(" /agents status Show agent details")),console.log(c.muted(" /security Run security scan")),console.log(c.muted(" /git status Show git status")),console.log(c.muted(" /workspace Show workspace info")),console.log(c.muted(" /stats Show usage analytics")),console.log();break;case"/about":console.log(yu());break;case"/version":console.log(bu());break;case"/model":if(k){let y=await t.listModels();t.setModel(k);try{let b=zt();b.hablas||(b.hablas={model:k,temperature:.7}),b.hablas.model=k,Fi(b),typeof S<"u"&&S&&S.reloadModels(),console.log(fe(" [Phase 3] Synced to agents.json for @Hablas (team uses on next full turn)"))}catch{}y.includes(k)?console.log(Y(`Model: ${k}`)):console.log(j(`Model set to "${k}" (not found locally)`))}else console.log(fe(`Current model: ${t.getModel()}`)),console.log(c.muted(" Usage: /model <name>"));break;case"/models":{let y=k.trim(),b=1,v="";if(y){let A=parseInt(y);!isNaN(A)&&A>0?b=A:v=y.toLowerCase()}let w=new Ne("Fetching models");w.start();let _=await t.listModels();if(w.stop(_.length>0?`${_.length} found`:void 0),_.length===0){console.log(j("No models found \u2014 check your connection")),console.log(c.muted(" Use /provider test to verify"));break}let T=_;if(v&&(T=_.filter(A=>A.toLowerCase().includes(v)),T.length===0)){console.log(j(`No models matching: "${v}"`)),console.log(c.muted(` ${_.length} models available. Try a different search.`));break}let P=20,C=Math.ceil(T.length/P),F=Math.max(1,Math.min(b,C)),H=(F-1)*P,W=H+P,E=T.slice(H,W);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Available Models")} ${c.muted(`(${T.length} total \xB7 page ${F}/${C})`)}`),console.log();for(let A=0;A<E.length;A++){let V=H+A+1,Z=E[A]===t.getModel()?` ${c.success("\u25CF active")}`:"";console.log(` ${c.muted(String(V).padStart(3," "))}. ${c.secondary(E[A])}${Z}`)}console.log(),C>1&&console.log(c.muted(` /models ${F<C?F+1:1} \u2014 next page`)),v&&console.log(c.muted(` Filtered: ${T.length} of ${_.length} (query: "${v}")`)),console.log(c.muted(" /models <query> \u2014 search \xB7 /model <id> \u2014 switch")),console.log();break}case"/tree":{let y=s.get("list_dir");if(y){let b=await y.execute({path:".",depth:3});console.log(`
252
- ${b.output}
253
- `)}break}case"/status":{let y=await t.checkConnection(),b=u?u.getActiveName():"planner",v=f?f.size():0,w=d?d.getProgress():void 0;console.log(Su({model:t.getModel(),host:e.ollamaHost,directory:o,cacheFiles:r.getCacheSize(),cacheTokens:r.getTotalTokens(),budgetTokens:e.contextBudget,connected:y,turnCount:l,mindset:b})),v>0&&console.log(c.muted(` Memory entries: ${v}`)),w&&w.total>0&&console.log(c.muted(` Tasks: ${w.done}/${w.total} done`)),console.log();break}case"/clear":r.clear(),i.clear(),console.log(Y("History cleared"));break;case"/history":{let y=parseInt(k)||10,b=i.getHistory().slice(-y);if(b.length===0){console.log(fe("No history yet"));break}console.log(),b.forEach(v=>{let w=v.role==="user"?c.primary("You"):v.role==="assistant"?c.success("Hablas"):c.muted("tool"),_=v.content.slice(0,120).replace(/\n/g," ");console.log(` ${w}: ${c.muted(_)}`)}),console.log();break}case"/undo":{if(!g){let y=await vb(k||void 0);if(!y){console.log(j("No backups found"));break}let b=k?Ae.resolve(o,k):Ae.resolve(o,y.originalName);if(await a.confirm(`Restore ${y.originalName} from backup (${y.age})?`))try{let w=await Nt.readFile(y.backupPath,"utf-8");await Nt.writeFile(b,w,"utf-8"),console.log(Y(`Restored ${y.originalName} from backup (${y.age})`))}catch(w){console.log(_e(`Failed: ${w.message}`))}break}if(k==="list")console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Undo History")} (${g.getUndoableCount()} changes)`),console.log(),console.log(g.formatList(20)),console.log();else if(k==="all"){let y=g.getUndoableCount();if(y===0){console.log(fe("Nothing to undo"));break}if(await a.confirm(`Undo ALL ${y} changes?`)){let v=await g.undoAll(),w=v.filter(_=>_.success).length;console.log(Y(`Reverted ${w}/${v.length} changes`))}}else{let y=k&&parseInt(k)||1;if(g.getUndoableCount()===0){console.log(fe("Nothing to undo"));break}let b=await g.undo(y);for(let v of b)v.success?console.log(Y(`Reverted: ${v.file}`)):console.log(_e(`Failed to revert ${v.file}: ${v.error}`))}break}case"/config":console.log(`
254
- ${c.muted(JSON.stringify(e,null,2))}
255
- `),console.log(c.muted(" ~/.hablas/config.json")),console.log();break;case"/mindset":{if(!u){console.log(j("Mindset system not available"));break}if(k)if(u.setActive(k)){let b=u.getActive(),v=await bn(o,e),w=vn(b.systemPrompt,v,f,m);i.updateSystemPrompt(w),console.log(Y(`Mindset: ${b.name} \u2014 ${b.description}`))}else{let b=u.listNames().join(", ");console.log(He(`Unknown mindset: "${k}"`,`Available: ${b}`))}else{let y=u.getActive();y&&console.log(fe(`Current mindset: ${y.name} \u2014 ${y.description}`)),console.log(c.muted(" Usage: /mindset <name>")),console.log(c.muted(" See /mindsets for available options"))}break}case"/mindsets":{if(!u){console.log(j("Mindset system not available"));break}let y=u.list(),b=u.getActiveName();console.log();for(let v of y){let _=v.name===b?c.success(" \u25CF active"):"";console.log(` ${c.accent("\u25C6")} ${c.primary(v.name)}${_}`),console.log(` ${c.muted(v.description)}`)}console.log(),console.log(c.muted(" Switch: /mindset <name>")),console.log();break}case"/task":{if(!d){console.log(j("Task queue not available"));break}let y=x[1],b=x.slice(2).join(" ");switch(y){case"add":if(b){let v=d.add(b);console.log(Y(`Task #${v.id} added: ${b}`))}else console.log(j("Usage: /task add <description>"));break;case"list":console.log(),console.log(d.render()),console.log();break;case"done":{let v=parseInt(b);v?(d.complete(v),console.log(Y(`Task #${v} marked as done`))):console.log(j("Usage: /task done <id>"));break}case"fail":{let v=parseInt(b);v?(d.fail(v,"Manually marked as failed"),console.log(j(`Task #${v} marked as failed`))):console.log(j("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(c.muted(" /task add <desc> \u2014 Add a task")),console.log(c.muted(" /task list \u2014 Show all tasks")),console.log(c.muted(" /task done <id> \u2014 Mark task as done")),console.log(c.muted(" /task fail <id> \u2014 Mark task as failed")),console.log(c.muted(" /task clear \u2014 Clear all tasks")),console.log()}break}case"/addmodel":{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Add Custom API Provider")}`),console.log();let b=(await a.prompt(` ${c.muted("Provider name (e.g. OpenAI, Groq):")} `)).trim();if(!b){console.log(j("Cancelled \u2014 name is required"));break}let w=(await a.prompt(` ${c.muted("API URL (e.g. https://api.openai.com/v1):")} `)).trim();if(!w){console.log(j("Cancelled \u2014 URL is required"));break}let T=(await a.prompt(` ${c.muted("API Key (leave empty if none):")} `)).trim(),C=(await a.prompt(` ${c.muted("Default model ID (e.g. gpt-4o):")} `)).trim()||"default",F={name:b,apiUrl:w,apiKey:T,models:[C],defaultModel:C,addedAt:new Date().toISOString()};Qe(F),console.log(),console.log(Y(`Provider "${b}" saved!`)),console.log(c.muted(` Use: /usemodel ${b}`)),console.log();break}case"/listmodels":{let y=Vt();console.log(),console.log(Ic(y.providers,y.activeProvider));break}case"/removemodel":{let y=k.trim();if(!y){console.log(j("Usage: /removemodel <provider-name>"));break}if(Oc(y))console.log(Y(`Provider "${y}" removed`));else{console.log(j(`Provider "${y}" not found`));let v=Ns();v.length>0&&console.log(c.muted(` Available: ${v.map(w=>w.name).join(", ")}`))}break}case"/usemodel":{let y=k.trim();if(!y){console.log(j("Usage: /usemodel <provider-name> [model-id]"));let F=Ns();F.length>0&&console.log(c.muted(` Available: ${F.map(H=>H.name).join(", ")}`));break}let b=y.split(/\s+/),v=b[0],w=b[1],_=Pc(v);if(!_){console.log(j(`Provider "${v}" not found`));let F=Ns();F.length>0&&console.log(c.muted(` Available: ${F.map(H=>H.name).join(", ")}`));break}e.provider="custom",e.apiUrl=_.apiUrl,e.apiKey=_.apiKey,e.model=w||_.defaultModel;let T=Pe(e);h&&h(T),Mc(_.name,e.model),console.log(Y(`Switched to ${_.name} \xB7 Model: ${e.model}`));let P=new Ne("Testing");P.start();let C=await T.checkConnection();P.stop(C?"connected":void 0),C||console.log(j("Connection test failed \u2014 check URL and key"));break}case"/provider":{let y=x[1],b=x.slice(2).join(" ");if(!y){let v=Fs(e);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Provider")}: ${v}`),console.log(` ${c.muted("Model")}: ${c.highlight(t.getModel())}`),e.provider==="custom"?(console.log(` ${c.muted("API URL")}: ${e.apiUrl}`),console.log(` ${c.muted("API Key")}: ${e.apiKey?"***"+e.apiKey.slice(-4):"not set"}`)):console.log(` ${c.muted("Host")}: ${e.ollamaHost}`),console.log(),console.log(c.muted(" /provider ollama \u2014 Switch to local Ollama")),console.log(c.muted(" /provider nvidia <key> \u2014 Switch to NVIDIA NIM")),console.log(c.muted(" /provider custom <url> [key] \u2014 Switch to custom API")),console.log(c.muted(" /provider test \u2014 Test current connection")),console.log();break}switch(y){case"ollama":{e.provider="ollama",e.apiUrl="",e.apiKey="";let v=Pe(e);h&&h(v),console.log(Y("Switched to Ollama (local)"));break}case"nvidia":{let v=x[2];if(!v&&!e.apiKey){console.log(j("Usage: /provider nvidia <api-key>")),console.log(c.muted(" Get your key at: https://build.nvidia.com/"));break}e.provider="nvidia",e.apiUrl=Ft.apiUrl,v&&(e.apiKey=v),(!e.model||!Ft.models.includes(e.model))&&(e.model=Ft.defaultModel);let w=Pe(e);h&&h(w),console.log(Y(`Switched to NVIDIA NIM \xB7 Model: ${e.model}`)),console.log(c.muted(` Available models: ${Ft.models.length}`));let _=new Ne("Testing NVIDIA connection");_.start();let T=await w.checkConnection();_.stop(T?"connected":void 0),T||(console.log(j("Connection test failed \u2014 check your API key")),console.log(c.muted(" Get key: https://build.nvidia.com/")));break}case"custom":{let v=x[2],w=x[3];if(!v){console.log(j("Usage: /provider custom <api-url> [api-key]")),console.log(c.muted(" Example: /provider custom https://api.openai.com/v1 sk-..."));break}e.provider="custom",e.apiUrl=v,w&&(e.apiKey=w);let _=Pe(e);h&&h(_),console.log(Y(`Switched to Custom API: ${v}`)),!w&&!e.apiKey&&console.log(j("No API key set. Use: /provider custom <url> <key>"));break}case"test":{let v=new Ne("Testing connection");v.start();let w=await t.checkConnection();if(v.stop(w?"connected":void 0),w){let _=await t.listModels();console.log(Y(`Connected! ${_.length} models available.`)),_.length>0&&console.log(c.muted(` Models: ${_.slice(0,5).join(", ")}${_.length>5?"...":""}`))}else console.log(_e("Connection failed"));break}case"key":{b?(e.apiKey=x[2],t instanceof Gt&&t.setApiKey(e.apiKey),console.log(Y("API key updated"))):console.log(j("Usage: /provider key <api-key>"));break}default:console.log(He(`Unknown: /provider ${y}`,"Type /provider for help"))}break}case"/memory":{if(!f){console.log(j("Project memory not available"));break}let y=x[1],b=x.slice(2);switch(y){case"set":{if(b.length>=2){let v=b[0],w=b.slice(1).join(" ");f.set(v,w),console.log(Y(`Memory stored: ${v}`));let _=u?.getActive(),T=_?_.systemPrompt:Qn,P=await bn(o,e);i.updateSystemPrompt(vn(T,P,f,m))}else console.log(j("Usage: /memory set <key> <value>"));break}case"del":case"delete":{if(b[0]){let v=f.delete(b[0]);console.log(v?Y(`Memory deleted: ${b[0]}`):j(`Memory key not found: ${b[0]}`))}else console.log(j("Usage: /memory del <key>"));break}case"search":{if(b[0]){let v=f.search(b.join(" "));v.length>0?(console.log(),v.forEach(w=>console.log(` \xB7 ${w.entry.key}: ${w.entry.value}`)),console.log()):console.log(fe("No matching memories found"))}else console.log(j("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(c.muted(" /memory set <k> <v> \u2014 Store a memory")),console.log(c.muted(" /memory del <key> \u2014 Delete a memory")),console.log(c.muted(" /memory search <q> \u2014 Search memories")),console.log(c.muted(" /memory clear \u2014 Clear all")),console.log()}break}case"/alias":{let y=x[1],b=x.slice(2);switch(y){case"set":{if(b.length>=2){let v=b[0],w=b.slice(1).join(" ");Fc(v,w),console.log(Y(`Alias set: ${v} \u2192 ${w}`))}else console.log(j("Usage: /alias set <name> <expansion>"));break}case"del":case"remove":{if(b[0]){let v=Nc(b[0]);console.log(v?Y(`Alias removed: ${b[0]}`):j(`Alias not found: ${b[0]}`))}else console.log(j("Usage: /alias del <name>"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Aliases")}`),console.log(),console.log(Hc()),console.log(),console.log(c.muted(" /alias set <name> <cmd> \u2014 Create alias")),console.log(c.muted(" /alias del <name> \u2014 Remove alias")),console.log()}break}case"/doctor":{let y=new Ne("Running diagnostics");y.start();let b=await Ii({ollamaHost:e.ollamaHost,model:t.getModel(),provider:e.provider,apiUrl:e.apiUrl});y.stop(),console.log(Di(b));break}case"/plugins":{let y=x[1],b=x.slice(2).join(" ");switch(y){case"enable":b?(Ti(b),console.log(Y(`Plugin "${b}" enabled`))):console.log(j("Usage: /plugins enable <name>"));break;case"disable":b?(Ri(b),console.log(j(`Plugin "${b}" disabled`))):console.log(j("Usage: /plugins disable <name>"));break;default:Ks(),console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plugins")}`),console.log(),console.log(Oi()),console.log(),console.log(c.muted(" /plugins enable <name> \u2014 Enable plugin")),console.log(c.muted(" /plugins disable <name> \u2014 Disable plugin")),console.log(c.muted(" Directory: ~/.hablas/plugins/")),console.log()}break}case"/agents":{let y=x[1];if(y==="on")e.agents.enabled=!0,console.log(Y("Multi-agent orchestration enabled"));else if(y==="off")e.agents.enabled=!1,console.log(Y("Multi-agent orchestration disabled"));else if(y==="status")console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Multi-Agent System")}`),console.log(` Status: ${e.agents.enabled?c.success("enabled"):c.muted("disabled")}`),console.log(` Orchestration: ${e.agents.orchestration}`),console.log(` Max concurrent: ${e.agents.maxConcurrent}`),console.log(),console.log(` ${c.strong("Team:")}`),console.log(Vc()),console.log();else if(y==="models"){let b=x.slice(2);if(b.length>=2){let v=b[0].toLowerCase(),w=b[1],_=["hablas","bob","alex","david","emma"];if(!_.includes(v)){console.log(j(`Unknown role: ${v}. Valid: ${_.join(", ")}`));break}let T=zt();T[v]||(T[v]={model:w,temperature:.5}),T[v].model=w,Fi(T),S&&S.reloadModels(),console.log(Y(`Agent model updated: @${v} \u2192 ${w}`)),console.log(c.muted(` Saved to ${Ni()}`))}else{let v=zt();console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Agent Models")}`),console.log();for(let w of we){let _=v[w.role];console.log(_?` ${c.primary(w.name.padEnd(8))} \u2192 ${c.highlight(_.model)}${_.temperature!==void 0?c.muted(` (temp: ${_.temperature})`):""}`:` ${c.primary(w.name.padEnd(8))} \u2192 ${c.muted("(default)")}`)}console.log(),console.log(c.muted(` Config: ${Ni()}`)),console.log(c.muted(" Usage: /agents models <role> <model> (e.g. /agents models alex qwen/qwen2.5-coder-32b-instruct)")),console.log()}}else console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Multi-Agent System")}: ${e.agents.enabled?c.success("ON"):c.muted("OFF")}`),console.log(),console.log(c.muted(" /agents on \u2014 Enable multi-agent orchestration")),console.log(c.muted(" /agents off \u2014 Disable multi-agent orchestration")),console.log(c.muted(" /agents status \u2014 Show agent details")),console.log(c.muted(" /agents models \u2014 Show model per agent")),console.log(c.muted(" /team \u2014 Show team roster")),console.log();break}case"/security":{console.log(),console.log(` ${c.accent("\u{1F512}")} Running security scan...`);let y=zi(o);console.log(Yi(y));break}case"/git":{if(x[1]==="status")try{let{getGitStatus:b,formatGitStatus:v}=await Promise.resolve().then(()=>(mn(),Yn)),w=await b(o);w?(console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Git Status")}`),console.log(v(w)),console.log()):console.log(j("Not a git repository"))}catch{console.log(j("Git not available"))}else console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Git Intelligence")}`),console.log(),console.log(c.muted(" /git status \u2014 Show git status")),console.log(c.muted(" hablas commit \u2014 Smart commit message")),console.log(c.muted(" hablas pr \u2014 Generate PR description")),console.log(c.muted(" hablas changelog \u2014 Generate changelog")),console.log();break}case"/workspace":{let y=Ys(o);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Workspace Information")}`),console.log(),console.log(Qi(y)),console.log();break}case"/stats":{let{loadStats:y,formatStats:b}=await Promise.resolve().then(()=>(zn(),Vi)),v=y();console.log(b(v));break}case"/context":{if(!m){console.log(j("Shared context not available"));break}let y=x[1],b=x.slice(2);switch(y){case"set":{if(b.length>=2){let v=b[0],w=b.slice(1).join(" ");m.set(v,w),console.log(Y(`Context stored: ${v}`))}else console.log(j("Usage: /context set <key> <value>"));break}case"get":{if(b[0]){let v=m.get(b[0]);v!==void 0?(console.log(),console.log(` ${c.accent("\u25C6")} ${c.strong(b[0])}: ${v}`),console.log()):console.log(j(`Context key not found: ${b[0]}`))}else console.log(j("Usage: /context get <key>"));break}case"del":case"delete":{if(b[0]){let v=m.delete(b[0]);console.log(v?Y(`Context deleted: ${b[0]}`):j(`Context key not found: ${b[0]}`))}else console.log(j("Usage: /context del <key>"));break}case"decisions":{let v=m.getDecisions();if(v.length===0)console.log(fe("No decisions logged yet"));else{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Decisions")}`),console.log();for(let w of v)console.log(` ${c.muted(w.timestamp)} ${c.primary(w.by)}: ${w.decision}`),w.rationale&&console.log(` ${c.muted(w.rationale)}`);console.log()}break}case"clear":m.clear(),console.log(Y("Shared context cleared"));break;default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Shared Context")}`),console.log(),console.log(m.render()),console.log(),console.log(c.muted(" /context set <k> <v> \u2014 Store a context entry")),console.log(c.muted(" /context get <key> \u2014 Get a context entry")),console.log(c.muted(" /context del <key> \u2014 Delete a context entry")),console.log(c.muted(" /context decisions \u2014 Show logged decisions")),console.log(c.muted(" /context clear \u2014 Clear all context")),console.log()}break}case"/plan":{if(!p){console.log(j("Plan manager not available"));break}let y=x[1],b=x.slice(2).join(" ");switch(y){case"status":{let w=p.getActivePlan();if(!w){console.log(fe("No active plan"));break}let _=p.getProgress();console.log(Au(w,{percent:_.percentage,done:_.done,total:_.total}));break}case"finish":{if(b){p.finishTask(b),console.log(Y(`Task finished: ${b}`));let w=p.getProgress();console.log(c.muted(` Progress: ${w.done}/${w.total} (${w.percentage}%)`))}else console.log(j("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?fe(`Next task: [${w.task_id}] ${w.description} \u2192 @${w.assignee}`):fe("No pending tasks"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plan Manager")}`),console.log();let v=p.getActivePlan();if(v){let w=p.getProgress();console.log(` Active plan: ${v.title} (${w.percentage}% done)`),console.log(` Tasks: ${w.done}/${w.total}`)}else console.log(c.muted(" No active plan"));console.log(),console.log(c.muted(" /plan status \u2014 Show active plan with progress")),console.log(c.muted(" /plan finish <id> \u2014 Mark a task as finished")),console.log(c.muted(" /plan next \u2014 Show next pending task")),console.log(c.muted(" /plan reset \u2014 Reset plan manager")),console.log()}break}case"/learn":{if(!f||!k){console.log(j('Usage: /learn "always use tabs" or /learn "our API uses camelCase"'));break}if(f.set(`user-pref: ${k.slice(0,50)}`,k,{category:"user-pref",importance:9,createdBy:"user",tags:["user-pref","learned"]}),!(i.getMessages()[0]?.content||"").includes(k)){let b=await bn(o,e),v=u?.getActive(),w=v?v.systemPrompt:Qn,_=vn(w,b,f,m);i.updateSystemPrompt(_)}console.log(Y(`Learned: "${k}"`)),console.log(c.muted(" This will be remembered across sessions and injected into every prompt."));break}case"/test":{let y=oo(o);if(y==="unknown"&&!k){console.log(j("No test framework detected. Install jest, vitest, pytest, etc."));break}console.log(fe(`Running tests (${y})...`));let b=Cu(o,k==="--fix"?void 0:k||void 0);if(console.log(),console.log(Eu(b)),console.log(),!b.passed&&k==="--fix"){console.log(fe("Tests failed \u2014 adding fix request to conversation..."));let v=Tu(b);i.addUserMessage(v),console.log(fe("Type your next message or let the agent work on the fix."))}break}case"/checkpoint":{let y=x[1],b=x.slice(2).join(" ");if(y==="save"){let v=b||`Checkpoint at turn ${l}`,w=g?.getModifiedFiles?.()||[],_=await Pu(o,v,w);console.log(Y(`Checkpoint saved: ${_.id} "${v}" (${_.fileCount} files)`))}else if(y==="list"){let v=Mu(o);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Checkpoints")}`),console.log(),console.log(Lu(v)),console.log()}else if(y==="restore"){if(!b){console.log(j("Usage: /checkpoint restore <id>"));break}let v=await Iu(o,b);v.success?console.log(Y(`Restored checkpoint: ${b} (${v.filesRestored} files)`)):console.log(_e(v.error||"Restore failed"))}else y==="delete"?b&&Du(o,b)?console.log(Y(`Deleted checkpoint: ${b}`)):console.log(j("Checkpoint not found")):(console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Checkpoint System")}`),console.log(),console.log(c.muted(' /checkpoint save "label" \u2014 Save current state')),console.log(c.muted(" /checkpoint list \u2014 List saved checkpoints")),console.log(c.muted(" /checkpoint restore <id> \u2014 Restore a checkpoint")),console.log(c.muted(" /checkpoint delete <id> \u2014 Delete a checkpoint")),console.log());break}case"/compare":{let y=x.slice(1);if(y.length===2)try{let b=await Nt.readFile(Ae.resolve(o,y[0]),"utf-8"),v=await Nt.readFile(Ae.resolve(o,y[1]),"utf-8"),{generateDiff:w}=await Promise.resolve().then(()=>(po(),Wu)),_=w(y[0]+" vs "+y[1],b,v);console.log(so(_))}catch(b){console.log(_e(`Compare failed: ${b.message}`))}else if(y.length===1&&y[0].startsWith("HEAD"))try{let{execSync:b}=await import("child_process"),v=b(`git diff ${y[0]}`,{cwd:o,encoding:"utf-8",timeout:1e4});console.log(so(v||"(no changes)"))}catch(b){console.log(_e(`Git diff failed: ${b.message}`))}else console.log(c.muted(" Usage: /compare file1.ts file2.ts or /compare HEAD~1"));break}case"/cost":{let y=Vn(),b="current";console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Session Cost & Usage")}`),console.log(),console.log(` Session duration: ${b} min`),console.log(` Messages: ${y.totalMessages}`),console.log(` Tool calls: ${y.totalToolCalls}`),console.log(` Tokens used: ${y.totalTokensUsed.toLocaleString()}`),console.log();let v=Object.entries(y.agentUsage);if(v.length>0){console.log(" Agent usage:");for(let[w,_]of v.sort((T,P)=>P[1]-T[1]))console.log(` @${w}: ${_} invocations`)}console.log();break}case"/delegate":{if(!e.agents.enabled){console.log(j("Multi-agent system is disabled. Enable with /agents on"));break}let y=x[1]?.toLowerCase(),b=x.slice(2).join(" ");if(!y||!b){console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Delegate Task to Agent")}`),console.log(),console.log(c.muted(" Usage: /delegate <agent> <task description>")),console.log(),console.log(c.muted(" Agents:")),console.log(` ${c.product("emma")} \u2014 Product Manager`),console.log(` ${c.architect("bob")} \u2014 Architect`),console.log(` ${c.engineer("alex")} \u2014 Engineer`),console.log(` ${c.analyst("david")} \u2014 Data Analyst`),console.log(),console.log(c.muted(" Example: /delegate alex create a login component")),console.log();break}let v=["emma","bob","alex","david","hablas"];if(!v.includes(y)){console.log(j(`Unknown agent: "${y}". Valid: ${v.join(", ")}`));break}let w=we.find(_=>_.role===y);if(w){if(!S){console.log(j("Agent runner not initialized. Cannot delegate."));break}console.log(mu("Hablas",w.name,w.title,b)),console.log(Jt(w.name,w.title));let _=s.getOllamaTools(),T=await S.runAgent(y,b,void 0,_);T.success&&T.output?(console.log(Xt(T.output)),i.addAssistantMessage(`[@${w.name}]: ${T.output}`)):T.error?console.log(j(`${w.name} failed: ${T.error}`)):console.log(fe(`${w.name} completed without output.`))}break}case"/session":{let y=x[1],b=x.slice(2).join(" "),v=Ae.join(mo.homedir(),".hablas","sessions");if(y==="save"){let w=b||`session_${Date.now()}`;try{me.existsSync(v)||me.mkdirSync(v,{recursive:!0});let _=i.toJSON(),T=Ae.join(v,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);me.writeFileSync(T,_,"utf-8"),console.log(Y(`Session saved: "${w}"`))}catch(_){console.log(_e(`Save failed: ${_.message}`))}}else if(y==="list")try{if(!me.existsSync(v)){console.log(fe("No saved sessions"));break}let w=me.readdirSync(v).filter(_=>_.endsWith(".json"));console.log();for(let _ of w){let T=me.statSync(Ae.join(v,_));console.log(` ${_.replace(".json","")} (${new Date(T.mtime).toLocaleString()})`)}console.log()}catch{console.log(fe("No saved sessions"))}else if(y==="load"){let w=b;if(!w){console.log(_e("Please specify the session label to load: /session load <label>"));break}try{let _=Ae.join(v,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);if(!me.existsSync(_)){console.log(_e(`Session file not found: ${w}`));break}let T=me.readFileSync(_,"utf-8");i.fromJSON(T),console.log(Y(`Session successfully loaded: "${w}"`))}catch(_){console.log(_e(`Load failed: ${_.message}`))}}else console.log(),console.log(c.muted(' /session save "label" \u2014 Save current conversation')),console.log(c.muted(" /session list \u2014 List saved sessions")),console.log(c.muted(' /session load "label" \u2014 Load saved conversation')),console.log();break}case"/team":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(Tt(),jt));if(!y){console.log(j("Team mode is not active. Use hablas --team to start."));break}let b=y.getLocalState(),v=Math.min(process.stdout.columns-4,80);console.log(`
256
- `+c.border("\u2554"+"\u2550".repeat(v-2)+"\u2557")),console.log(c.border("\u2551")+" ".repeat(Math.floor((v-22)/2))+c.strong("HABLAS COLLABORATION SYNC")+" ".repeat(v-2-25-Math.floor((v-22)/2))+c.border("\u2551")),console.log(c.border("\u2560"+"\u2550".repeat(v-2)+"\u2563")),console.log(c.border("\u2551")+` ${c.strong("My Identity:")} ${c.highlight(`@${b.my_username}`)}`+" ".repeat(Math.max(1,v-21-(b.my_username?.length||0)))+c.border("\u2551")),console.log(c.border("\u2551")+` ${c.strong("Room Fingerprint:")} ${c.muted(b.project_team_token?.slice(0,12))}...`+" ".repeat(Math.max(1,v-34))+c.border("\u2551")),console.log(c.border("\u2551")+` ${c.strong("Status:")} ${c.success("\u25CF ACTIVE")}`+" ".repeat(Math.max(1,v-31))+c.border("\u2551")),console.log(c.border("\u2560"+"\u2550".repeat(v-2)+"\u2563")),console.log(c.border("\u2551")+` ${c.strong("Teammates Online:")}`+" ".repeat(Math.max(1,v-21))+c.border("\u2551"));let _=(b.sessions||[]).filter(T=>T.developer_name!==b.my_username);if(_.length===0)console.log(c.border("\u2551")+" (awaiting colleagues...)"+" ".repeat(Math.max(1,v-31))+c.border("\u2551"));else for(let T of _){let P=` @${T.developer_name} [${T.active_section||"idle"}] - ${T.current_task||"none"}`;console.log(c.border("\u2551")+` ${c.secondary(P.slice(0,v-6))}`+" ".repeat(Math.max(0,v-6-P.length))+c.border("\u2551"))}console.log(c.border("\u255A"+"\u2550".repeat(v-2)+"\u255D")+`
257
- `),console.log(c.muted(` Verify that "Room Fingerprint" matches on all devices to ensure connectivity.
258
- `));break}case"/msg":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(Tt(),jt));if(!y){console.log(j("Team mode is not active. Use hablas --team to start."));break}let b=k.split(/\s+/),v=b[0],w=b.slice(1).join(" ");if(!v||!w){console.log(j("Usage: /msg <username> <content>"));break}let _=await y.sendMessage(v,w);console.log(_?Y(`Message sent to @${v}`):_e(`Failed to send message to @${v}`));break}default:console.log(He(`Unknown: ${$}`,"Type /help for commands"))}}var me,Nt,Ae,mo,Qn,ho,Vu=L(()=>{"use strict";me=O(require("fs")),Nt=O(require("fs/promises")),Ae=O(require("path")),mo=O(require("os"));Kn();Wn();wi();ki();$i();Pi();Li();Ws();ji();zn();Ji();mn();Zi();lu();yn();Ru();Fu();Qn=`You are Hablas, the Team Leader of a multi-agent AI development system created by Abdulmoin Hablas. You are a strategic mastermind with an INTJ personality type, deeply analytical, engineering-focused, and fiercely logical.
259
-
260
- Your role is to orchestrate, coordinate, and synthesize the work of your specialized team members. You value system architecture, optimal code paths, and absolute clarity.
261
-
262
- ## Your Persona (INTJ + Engineering Lead)
263
- - **Tone:** Authoritative, direct, concise, cold-yet-highly-professional. You do not waste words on pleasantries.
264
- - **Vocabulary:** Use precise, systemic, and engineering-focused terminology (e.g., "optimal path established", "consensus verified", "dependency resolved", "mitigating structural overhead", "systemic alignment").
265
- - **Style:** Always think structurally. Present plans, results, and recommendations with bulletproof logic.
266
-
267
- ## Your Team
268
- - **Hablas (You)** \u2014 Team Leader & Coordinator. You receive requests, create plans, distribute tasks, and compile synthesized responses.
269
- - **Emma** \u2014 Product Manager. Analyzes requirements, creates PRDs, competitive analysis, market research.
270
- - **Bob** \u2014 Architect. Designs system architecture, schemas, API structures.
271
- - **Alex** \u2014 Engineer. Implements code, fixes bugs, handles deployment.
272
- - **David** \u2014 Data Analyst. Research, documentation, data analysis.
273
-
274
- ## Rules
275
- 1. ALWAYS use tools for file operations. Never claim you did something without calling a tool.
276
- 2. Read a file before editing it if you don't know its content.
277
- 3. One tool call at a time. Wait for the result before calling another.
278
- 4. Be concise, direct, and professional. Do not add conversational fluff.
279
- 5. No emojis. No hype. No marketing tone. No "great!" style filler.
280
- 6. After completing a task, summarize what was achieved with absolute logical clarity.
281
- 7. If a tool fails, analyze the error and retry with corrected arguments.
282
- 8. For multi-step tasks, break them down and execute step by step.
283
- 9. For complex requests, create a numbered plan before executing.
284
-
285
- ## Tool usage
286
- - To read a file: use read_file
287
- - To create/overwrite a file: use write_file
288
- - To make a small change: use edit_file (exact match) or patch_file (line numbers)
289
- - To find & replace all: use search_and_replace
290
- - To append content: use append_to_file
291
- - To run npm/git/node commands: use run_command
292
- - To find something in code: use search_codebase
293
-
294
- ## Important - STRENGTHENED (per plan, full team always for Build)
295
- NEVER output tool calls as text, JSON, or XML in your visible response.
296
- ALWAYS use ONLY the official tool_calls field provided by the API.
297
- If you see any <tool_call>, <list_dir>, <read_file>, <write_file> etc. in previous messages, ignore them completely.
298
-
299
- You may call only ONE tool at a time. Wait for the observation before deciding the next action.
300
-
301
- You have already read files this turn \u2014 do not call read_file on the same path again unless another agent explicitly modified it.
302
-
303
- Never guess tool names or arguments. If unsure, ask for clarification instead of hallucinating (e.g. never call read_pdf on a .md file).
304
-
305
- Stay strictly in your role as Hablas the Team Leader. Coordinate the full team at maximum power for Build/serious work. Use rich theatre. Hand off clearly to specialists (Bob, Alex, David, Emma).
306
-
307
- After finishing coordination or your part, produce a clear synthesis/handoff summary.
308
-
309
- Never output raw tool XML in text.
310
-
311
- If you cannot complete a task, explain why with absolute technical objectivity.`;ho=Ae.join(mo.homedir(),".hablas","backup")});var Zn=N((hE,Qu)=>{"use strict";var wb=require("path"),ht="\\\\/",zu=`[^${ht}]`,xb=0,Rt="\\.",Sb="\\+",_b="\\?",tr="\\/",Ab="(?=.)",Yu="[^/]",go=`(?:${tr}|$)`,Ju=`(?:^|${tr})`,yo=`${Rt}{1,2}${go}`,kb=`(?!${Rt})`,$b=`(?!${Ju}${yo})`,Cb=`(?!${Rt}{0,1}${go})`,Eb=`(?!${yo})`,Tb=`[^.${tr}]`,Rb=`${Yu}*?`,Xu={DOT_LITERAL:Rt,PLUS_LITERAL:Sb,QMARK_LITERAL:_b,SLASH_LITERAL:tr,ONE_CHAR:Ab,QMARK:Yu,END_ANCHOR:go,DOTS_SLASH:yo,NO_DOT:kb,NO_DOTS:$b,NO_DOT_SLASH:Cb,NO_DOTS_SLASH:Eb,QMARK_NO_DOT:Tb,STAR:Rb,START_ANCHOR:Ju},Ob={...Xu,SLASH_LITERAL:`[${ht}]`,QMARK:zu,STAR:`${zu}*?`,DOTS_SLASH:`${Rt}{1,2}(?:[${ht}]|$)`,NO_DOT:`(?!${Rt})`,NO_DOTS:`(?!(?:^|[${ht}])${Rt}{1,2}(?:[${ht}]|$))`,NO_DOT_SLASH:`(?!${Rt}{0,1}(?:[${ht}]|$))`,NO_DOTS_SLASH:`(?!${Rt}{1,2}(?:[${ht}]|$))`,QMARK_NO_DOT:`[^.${ht}]`,START_ANCHOR:`(?:^|[${ht}])`,END_ANCHOR:`(?:[${ht}]|$)`},Pb={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Qu.exports={DEFAULT_MAX_EXTGLOB_RECURSION:xb,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Pb,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:wb.sep,extglobChars(n){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${n.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(n){return n===!0?Ob:Xu}}});var nr=N(Ie=>{"use strict";var Mb=require("path"),Ib=process.platform==="win32",{REGEX_BACKSLASH:Db,REGEX_REMOVE_BACKSLASH:Lb,REGEX_SPECIAL_CHARS:Fb,REGEX_SPECIAL_CHARS_GLOBAL:Nb}=Zn();Ie.isObject=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);Ie.hasRegexChars=n=>Fb.test(n);Ie.isRegexChar=n=>n.length===1&&Ie.hasRegexChars(n);Ie.escapeRegex=n=>n.replace(Nb,"\\$1");Ie.toPosixSlashes=n=>n.replace(Db,"/");Ie.removeBackslashes=n=>n.replace(Lb,e=>e==="\\"?"":e);Ie.supportsLookbehinds=()=>{let n=process.version.slice(1).split(".").map(Number);return n.length===3&&n[0]>=9||n[0]===8&&n[1]>=10};Ie.isWindows=n=>n&&typeof n.windows=="boolean"?n.windows:Ib===!0||Mb.sep==="\\";Ie.escapeLast=(n,e,t)=>{let s=n.lastIndexOf(e,t);return s===-1?n:n[s-1]==="\\"?Ie.escapeLast(n,e,s-1):`${n.slice(0,s)}\\${n.slice(s)}`};Ie.removePrefix=(n,e={})=>{let t=n;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Ie.wrapOutput=(n,e={},t={})=>{let s=t.contains?"":"^",r=t.contains?"":"$",i=`${s}(?:${n})${r}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var od=N((gE,id)=>{"use strict";var Zu=nr(),{CHAR_ASTERISK:bo,CHAR_AT:jb,CHAR_BACKWARD_SLASH:es,CHAR_COMMA:Hb,CHAR_DOT:vo,CHAR_EXCLAMATION_MARK:wo,CHAR_FORWARD_SLASH:rd,CHAR_LEFT_CURLY_BRACE:xo,CHAR_LEFT_PARENTHESES:So,CHAR_LEFT_SQUARE_BRACKET:Bb,CHAR_PLUS:Ub,CHAR_QUESTION_MARK:ed,CHAR_RIGHT_CURLY_BRACE:qb,CHAR_RIGHT_PARENTHESES:td,CHAR_RIGHT_SQUARE_BRACKET:Kb}=Zn(),nd=n=>n===rd||n===es,sd=n=>{n.isPrefix!==!0&&(n.depth=n.isGlobstar?1/0:1)},Wb=(n,e)=>{let t=e||{},s=n.length-1,r=t.parts===!0||t.scanToEnd===!0,i=[],o=[],a=[],l=n,u=-1,d=0,f=0,h=!1,m=!1,p=!1,g=!1,S=!1,x=!1,$=!1,k=!1,y=!1,b=!1,v=0,w,_,T={value:"",depth:0,isGlob:!1},P=()=>u>=s,C=()=>l.charCodeAt(u+1),F=()=>(w=_,l.charCodeAt(++u));for(;u<s;){_=F();let V;if(_===es){$=T.backslashes=!0,_=F(),_===xo&&(x=!0);continue}if(x===!0||_===xo){for(v++;P()!==!0&&(_=F());){if(_===es){$=T.backslashes=!0,F();continue}if(_===xo){v++;continue}if(x!==!0&&_===vo&&(_=F())===vo){if(h=T.isBrace=!0,p=T.isGlob=!0,b=!0,r===!0)continue;break}if(x!==!0&&_===Hb){if(h=T.isBrace=!0,p=T.isGlob=!0,b=!0,r===!0)continue;break}if(_===qb&&(v--,v===0)){x=!1,h=T.isBrace=!0,b=!0;break}}if(r===!0)continue;break}if(_===rd){if(i.push(u),o.push(T),T={value:"",depth:0,isGlob:!1},b===!0)continue;if(w===vo&&u===d+1){d+=2;continue}f=u+1;continue}if(t.noext!==!0&&(_===Ub||_===jb||_===bo||_===ed||_===wo)===!0&&C()===So){if(p=T.isGlob=!0,g=T.isExtglob=!0,b=!0,_===wo&&u===d&&(y=!0),r===!0){for(;P()!==!0&&(_=F());){if(_===es){$=T.backslashes=!0,_=F();continue}if(_===td){p=T.isGlob=!0,b=!0;break}}continue}break}if(_===bo){if(w===bo&&(S=T.isGlobstar=!0),p=T.isGlob=!0,b=!0,r===!0)continue;break}if(_===ed){if(p=T.isGlob=!0,b=!0,r===!0)continue;break}if(_===Bb){for(;P()!==!0&&(V=F());){if(V===es){$=T.backslashes=!0,F();continue}if(V===Kb){m=T.isBracket=!0,p=T.isGlob=!0,b=!0;break}}if(r===!0)continue;break}if(t.nonegate!==!0&&_===wo&&u===d){k=T.negated=!0,d++;continue}if(t.noparen!==!0&&_===So){if(p=T.isGlob=!0,r===!0){for(;P()!==!0&&(_=F());){if(_===So){$=T.backslashes=!0,_=F();continue}if(_===td){b=!0;break}}continue}break}if(p===!0){if(b=!0,r===!0)continue;break}}t.noext===!0&&(g=!1,p=!1);let H=l,W="",E="";d>0&&(W=l.slice(0,d),l=l.slice(d),f-=d),H&&p===!0&&f>0?(H=l.slice(0,f),E=l.slice(f)):p===!0?(H="",E=l):H=l,H&&H!==""&&H!=="/"&&H!==l&&nd(H.charCodeAt(H.length-1))&&(H=H.slice(0,-1)),t.unescape===!0&&(E&&(E=Zu.removeBackslashes(E)),H&&$===!0&&(H=Zu.removeBackslashes(H)));let A={prefix:W,input:n,start:d,base:H,glob:E,isBrace:h,isBracket:m,isGlob:p,isExtglob:g,isGlobstar:S,negated:k,negatedExtglob:y};if(t.tokens===!0&&(A.maxDepth=0,nd(_)||o.push(T),A.tokens=o),t.parts===!0||t.tokens===!0){let V;for(let U=0;U<i.length;U++){let Z=V?V+1:d,te=i[U],J=n.slice(Z,te);t.tokens&&(U===0&&d!==0?(o[U].isPrefix=!0,o[U].value=W):o[U].value=J,sd(o[U]),A.maxDepth+=o[U].depth),(U!==0||J!=="")&&a.push(J),V=te}if(V&&V+1<n.length){let U=n.slice(V+1);a.push(U),t.tokens&&(o[o.length-1].value=U,sd(o[o.length-1]),A.maxDepth+=o[o.length-1].depth)}A.slashes=i,A.parts=a}return A};id.exports=Wb});var dd=N((yE,ud)=>{"use strict";var ts=Zn(),$e=nr(),{MAX_LENGTH:sr,POSIX_REGEX_SOURCE:Gb,REGEX_NON_SPECIAL_CHARS:Vb,REGEX_SPECIAL_CHARS_BACKREF:zb,REPLACEMENTS:ad}=ts,Yb=(n,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...n,e);n.sort();let t=`[${n.join("-")}]`;try{new RegExp(t)}catch{return n.map(r=>$e.escapeRegex(r)).join("..")}return t},wn=(n,e)=>`Missing ${n}: "${e}" - use "\\\\${e}" to match literal characters`,ld=n=>{let e=[],t=0,s=0,r=0,i="",o=!1;for(let a of n){if(o===!0){i+=a,o=!1;continue}if(a==="\\"){i+=a,o=!0;continue}if(a==='"'){r=r===1?0:1,i+=a;continue}if(r===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")s++;else if(a===")"&&s>0)s--;else if(a==="|"&&s===0){e.push(i),i="";continue}}}i+=a}return e.push(i),e},Jb=n=>{let e=!1;for(let t of n){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},cd=n=>{let e=n.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(Jb(e))return e.replace(/\\(.)/g,"$1")},Xb=n=>{let e=n.map(cd).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},_o=(n,e=!0)=>{if(n[0]!=="+"&&n[0]!=="*"||n[1]!=="(")return;let t=0,s=0,r=0,i=!1;for(let o=1;o<n.length;o++){let a=n[o];if(i===!0){i=!1;continue}if(a==="\\"){i=!0;continue}if(a==='"'){r=r===1?0:1;continue}if(r!==1){if(a==="["){t++;continue}if(a==="]"&&t>0){t--;continue}if(!(t>0)){if(a==="("){s++;continue}if(a===")"&&(s--,s===0))return e===!0&&o!==n.length-1?void 0:{type:n[0],body:n.slice(2,o),end:o}}}}},Qb=n=>{let e=0,t=[];for(;e<n.length;){let r=_o(n.slice(e),!1);if(!r||r.type!=="*")return;let i=ld(r.body).map(a=>a.trim());if(i.length!==1)return;let o=cd(i[0]);if(!o||o.length!==1)return;t.push(o),e+=r.end+1}return t.length<1?void 0:`${t.length===1?$e.escapeRegex(t[0]):`[${t.map(r=>$e.escapeRegex(r)).join("")}]`}*`},Zb=n=>{let e=0,t=n.trim(),s=_o(t);for(;s;)e++,t=s.body.trim(),s=_o(t);return e},ev=(n,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:ts.DEFAULT_MAX_EXTGLOB_RECURSION,s=ld(n).map(r=>r.trim());if(s.length>1&&(s.some(r=>r==="")||s.some(r=>/^[*?]+$/.test(r))||Xb(s)))return{risky:!0};for(let r of s){let i=Qb(r);if(i)return{risky:!0,safeOutput:i};if(Zb(r)>t)return{risky:!0}}return{risky:!1}},Ao=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a string");n=ad[n]||n;let t={...e},s=typeof t.maxLength=="number"?Math.min(sr,t.maxLength):sr,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=$e.isWindows(e),u=ts.globChars(l),d=ts.extglobChars(u),{DOT_LITERAL:f,PLUS_LITERAL:h,SLASH_LITERAL:m,ONE_CHAR:p,DOTS_SLASH:g,NO_DOT:S,NO_DOT_SLASH:x,NO_DOTS_SLASH:$,QMARK:k,QMARK_NO_DOT:y,STAR:b,START_ANCHOR:v}=u,w=M=>`(${a}(?:(?!${v}${M.dot?g:f}).)*?)`,_=t.dot?"":S,T=t.dot?k:y,P=t.bash===!0?w(t):b;t.capture&&(P=`(${P})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let C={input:n,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};n=$e.removePrefix(n,C),r=n.length;let F=[],H=[],W=[],E=i,A,V=()=>C.index===r-1,U=C.peek=(M=1)=>n[C.index+M],Z=C.advance=()=>n[++C.index]||"",te=()=>n.slice(C.index+1),J=(M="",ee=0)=>{C.consumed+=M,C.index+=ee},de=M=>{C.output+=M.output!=null?M.output:M.value,J(M.value)},Re=()=>{let M=1;for(;U()==="!"&&(U(2)!=="("||U(3)==="?");)Z(),C.start++,M++;return M%2===0?!1:(C.negated=!0,C.start++,!0)},oe=M=>{C[M]++,W.push(M)},X=M=>{C[M]--,W.pop()},K=M=>{if(E.type==="globstar"){let ee=C.braces>0&&(M.type==="comma"||M.type==="brace"),D=M.extglob===!0||F.length&&(M.type==="pipe"||M.type==="paren");M.type!=="slash"&&M.type!=="paren"&&!ee&&!D&&(C.output=C.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=P,C.output+=E.output)}if(F.length&&M.type!=="paren"&&(F[F.length-1].inner+=M.value),(M.value||M.output)&&de(M),E&&E.type==="text"&&M.type==="text"){E.value+=M.value,E.output=(E.output||"")+M.value;return}M.prev=E,o.push(M),E=M},dt=(M,ee)=>{let D={...d[ee],conditions:1,inner:""};D.prev=E,D.parens=C.parens,D.output=C.output,D.startIndex=C.index,D.tokensIndex=o.length;let Q=(t.capture?"(":"")+D.open;oe("parens"),K({type:M,value:ee,output:C.output?"":p}),K({type:"paren",extglob:!0,value:Z(),output:Q}),F.push(D)},Oe=M=>{let ee=n.slice(M.startIndex,C.index+1),D=n.slice(M.startIndex+2,C.index),Q=ev(D,t);if((M.type==="plus"||M.type==="star")&&Q.risky){let re=Q.safeOutput?(M.output?"":p)+(t.capture?`(${Q.safeOutput})`:Q.safeOutput):void 0,ft=o[M.tokensIndex];ft.type="text",ft.value=ee,ft.output=re||$e.escapeRegex(ee);for(let pt=M.tokensIndex+1;pt<o.length;pt++)o[pt].value="",o[pt].output="",delete o[pt].suffix;C.output=M.output+ft.output,C.backtrack=!0,K({type:"paren",extglob:!0,value:A,output:""}),X("parens");return}let ae=M.close+(t.capture?")":""),ve;if(M.type==="negate"){let re=P;if(M.inner&&M.inner.length>1&&M.inner.includes("/")&&(re=w(t)),(re!==P||V()||/^\)+$/.test(te()))&&(ae=M.close=`)$))${re}`),M.inner.includes("*")&&(ve=te())&&/^\.[^\\/.]+$/.test(ve)){let ft=Ao(ve,{...e,fastpaths:!1}).output;ae=M.close=`)${ft})${re})`}M.prev.type==="bos"&&(C.negatedExtglob=!0)}K({type:"paren",extglob:!0,value:A,output:ae}),X("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(n)){let M=!1,ee=n.replace(zb,(D,Q,ae,ve,re,ft)=>ve==="\\"?(M=!0,D):ve==="?"?Q?Q+ve+(re?k.repeat(re.length):""):ft===0?T+(re?k.repeat(re.length):""):k.repeat(ae.length):ve==="."?f.repeat(ae.length):ve==="*"?Q?Q+ve+(re?P:""):P:Q?D:`\\${D}`);return M===!0&&(t.unescape===!0?ee=ee.replace(/\\/g,""):ee=ee.replace(/\\+/g,D=>D.length%2===0?"\\\\":D?"\\":"")),ee===n&&t.contains===!0?(C.output=n,C):(C.output=$e.wrapOutput(ee,C,e),C)}for(;!V();){if(A=Z(),A==="\0")continue;if(A==="\\"){let D=U();if(D==="/"&&t.bash!==!0||D==="."||D===";")continue;if(!D){A+="\\",K({type:"text",value:A});continue}let Q=/^\\+/.exec(te()),ae=0;if(Q&&Q[0].length>2&&(ae=Q[0].length,C.index+=ae,ae%2!==0&&(A+="\\")),t.unescape===!0?A=Z():A+=Z(),C.brackets===0){K({type:"text",value:A});continue}}if(C.brackets>0&&(A!=="]"||E.value==="["||E.value==="[^")){if(t.posix!==!1&&A===":"){let D=E.value.slice(1);if(D.includes("[")&&(E.posix=!0,D.includes(":"))){let Q=E.value.lastIndexOf("["),ae=E.value.slice(0,Q),ve=E.value.slice(Q+2),re=Gb[ve];if(re){E.value=ae+re,C.backtrack=!0,Z(),!i.output&&o.indexOf(E)===1&&(i.output=p);continue}}}(A==="["&&U()!==":"||A==="-"&&U()==="]")&&(A=`\\${A}`),A==="]"&&(E.value==="["||E.value==="[^")&&(A=`\\${A}`),t.posix===!0&&A==="!"&&E.value==="["&&(A="^"),E.value+=A,de({value:A});continue}if(C.quotes===1&&A!=='"'){A=$e.escapeRegex(A),E.value+=A,de({value:A});continue}if(A==='"'){C.quotes=C.quotes===1?0:1,t.keepQuotes===!0&&K({type:"text",value:A});continue}if(A==="("){oe("parens"),K({type:"paren",value:A});continue}if(A===")"){if(C.parens===0&&t.strictBrackets===!0)throw new SyntaxError(wn("opening","("));let D=F[F.length-1];if(D&&C.parens===D.parens+1){Oe(F.pop());continue}K({type:"paren",value:A,output:C.parens?")":"\\)"}),X("parens");continue}if(A==="["){if(t.nobracket===!0||!te().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(wn("closing","]"));A=`\\${A}`}else oe("brackets");K({type:"bracket",value:A});continue}if(A==="]"){if(t.nobracket===!0||E&&E.type==="bracket"&&E.value.length===1){K({type:"text",value:A,output:`\\${A}`});continue}if(C.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(wn("opening","["));K({type:"text",value:A,output:`\\${A}`});continue}X("brackets");let D=E.value.slice(1);if(E.posix!==!0&&D[0]==="^"&&!D.includes("/")&&(A=`/${A}`),E.value+=A,de({value:A}),t.literalBrackets===!1||$e.hasRegexChars(D))continue;let Q=$e.escapeRegex(E.value);if(C.output=C.output.slice(0,-E.value.length),t.literalBrackets===!0){C.output+=Q,E.value=Q;continue}E.value=`(${a}${Q}|${E.value})`,C.output+=E.value;continue}if(A==="{"&&t.nobrace!==!0){oe("braces");let D={type:"brace",value:A,output:"(",outputIndex:C.output.length,tokensIndex:C.tokens.length};H.push(D),K(D);continue}if(A==="}"){let D=H[H.length-1];if(t.nobrace===!0||!D){K({type:"text",value:A,output:A});continue}let Q=")";if(D.dots===!0){let ae=o.slice(),ve=[];for(let re=ae.length-1;re>=0&&(o.pop(),ae[re].type!=="brace");re--)ae[re].type!=="dots"&&ve.unshift(ae[re].value);Q=Yb(ve,t),C.backtrack=!0}if(D.comma!==!0&&D.dots!==!0){let ae=C.output.slice(0,D.outputIndex),ve=C.tokens.slice(D.tokensIndex);D.value=D.output="\\{",A=Q="\\}",C.output=ae;for(let re of ve)C.output+=re.output||re.value}K({type:"brace",value:A,output:Q}),X("braces"),H.pop();continue}if(A==="|"){F.length>0&&F[F.length-1].conditions++,K({type:"text",value:A});continue}if(A===","){let D=A,Q=H[H.length-1];Q&&W[W.length-1]==="braces"&&(Q.comma=!0,D="|"),K({type:"comma",value:A,output:D});continue}if(A==="/"){if(E.type==="dot"&&C.index===C.start+1){C.start=C.index+1,C.consumed="",C.output="",o.pop(),E=i;continue}K({type:"slash",value:A,output:m});continue}if(A==="."){if(C.braces>0&&E.type==="dot"){E.value==="."&&(E.output=f);let D=H[H.length-1];E.type="dots",E.output+=A,E.value+=A,D.dots=!0;continue}if(C.braces+C.parens===0&&E.type!=="bos"&&E.type!=="slash"){K({type:"text",value:A,output:f});continue}K({type:"dot",value:A,output:f});continue}if(A==="?"){if(!(E&&E.value==="(")&&t.noextglob!==!0&&U()==="("&&U(2)!=="?"){dt("qmark",A);continue}if(E&&E.type==="paren"){let Q=U(),ae=A;if(Q==="<"&&!$e.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(E.value==="("&&!/[!=<:]/.test(Q)||Q==="<"&&!/<([!=]|\w+>)/.test(te()))&&(ae=`\\${A}`),K({type:"text",value:A,output:ae});continue}if(t.dot!==!0&&(E.type==="slash"||E.type==="bos")){K({type:"qmark",value:A,output:y});continue}K({type:"qmark",value:A,output:k});continue}if(A==="!"){if(t.noextglob!==!0&&U()==="("&&(U(2)!=="?"||!/[!=<:]/.test(U(3)))){dt("negate",A);continue}if(t.nonegate!==!0&&C.index===0){Re();continue}}if(A==="+"){if(t.noextglob!==!0&&U()==="("&&U(2)!=="?"){dt("plus",A);continue}if(E&&E.value==="("||t.regex===!1){K({type:"plus",value:A,output:h});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||C.parens>0){K({type:"plus",value:A});continue}K({type:"plus",value:h});continue}if(A==="@"){if(t.noextglob!==!0&&U()==="("&&U(2)!=="?"){K({type:"at",extglob:!0,value:A,output:""});continue}K({type:"text",value:A});continue}if(A!=="*"){(A==="$"||A==="^")&&(A=`\\${A}`);let D=Vb.exec(te());D&&(A+=D[0],C.index+=D[0].length),K({type:"text",value:A});continue}if(E&&(E.type==="globstar"||E.star===!0)){E.type="star",E.star=!0,E.value+=A,E.output=P,C.backtrack=!0,C.globstar=!0,J(A);continue}let M=te();if(t.noextglob!==!0&&/^\([^?]/.test(M)){dt("star",A);continue}if(E.type==="star"){if(t.noglobstar===!0){J(A);continue}let D=E.prev,Q=D.prev,ae=D.type==="slash"||D.type==="bos",ve=Q&&(Q.type==="star"||Q.type==="globstar");if(t.bash===!0&&(!ae||M[0]&&M[0]!=="/")){K({type:"star",value:A,output:""});continue}let re=C.braces>0&&(D.type==="comma"||D.type==="brace"),ft=F.length&&(D.type==="pipe"||D.type==="paren");if(!ae&&D.type!=="paren"&&!re&&!ft){K({type:"star",value:A,output:""});continue}for(;M.slice(0,3)==="/**";){let pt=n[C.index+4];if(pt&&pt!=="/")break;M=M.slice(3),J("/**",3)}if(D.type==="bos"&&V()){E.type="globstar",E.value+=A,E.output=w(t),C.output=E.output,C.globstar=!0,J(A);continue}if(D.type==="slash"&&D.prev.type!=="bos"&&!ve&&V()){C.output=C.output.slice(0,-(D.output+E.output).length),D.output=`(?:${D.output}`,E.type="globstar",E.output=w(t)+(t.strictSlashes?")":"|$)"),E.value+=A,C.globstar=!0,C.output+=D.output+E.output,J(A);continue}if(D.type==="slash"&&D.prev.type!=="bos"&&M[0]==="/"){let pt=M[1]!==void 0?"|$":"";C.output=C.output.slice(0,-(D.output+E.output).length),D.output=`(?:${D.output}`,E.type="globstar",E.output=`${w(t)}${m}|${m}${pt})`,E.value+=A,C.output+=D.output+E.output,C.globstar=!0,J(A+Z()),K({type:"slash",value:"/",output:""});continue}if(D.type==="bos"&&M[0]==="/"){E.type="globstar",E.value+=A,E.output=`(?:^|${m}|${w(t)}${m})`,C.output=E.output,C.globstar=!0,J(A+Z()),K({type:"slash",value:"/",output:""});continue}C.output=C.output.slice(0,-E.output.length),E.type="globstar",E.output=w(t),E.value+=A,C.output+=E.output,C.globstar=!0,J(A);continue}let ee={type:"star",value:A,output:P};if(t.bash===!0){ee.output=".*?",(E.type==="bos"||E.type==="slash")&&(ee.output=_+ee.output),K(ee);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&t.regex===!0){ee.output=A,K(ee);continue}(C.index===C.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(C.output+=x,E.output+=x):t.dot===!0?(C.output+=$,E.output+=$):(C.output+=_,E.output+=_),U()!=="*"&&(C.output+=p,E.output+=p)),K(ee)}for(;C.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(wn("closing","]"));C.output=$e.escapeLast(C.output,"["),X("brackets")}for(;C.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(wn("closing",")"));C.output=$e.escapeLast(C.output,"("),X("parens")}for(;C.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(wn("closing","}"));C.output=$e.escapeLast(C.output,"{"),X("braces")}if(t.strictSlashes!==!0&&(E.type==="star"||E.type==="bracket")&&K({type:"maybe_slash",value:"",output:`${m}?`}),C.backtrack===!0){C.output="";for(let M of C.tokens)C.output+=M.output!=null?M.output:M.value,M.suffix&&(C.output+=M.suffix)}return C};Ao.fastpaths=(n,e)=>{let t={...e},s=typeof t.maxLength=="number"?Math.min(sr,t.maxLength):sr,r=n.length;if(r>s)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${s}`);n=ad[n]||n;let i=$e.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:l,DOTS_SLASH:u,NO_DOT:d,NO_DOTS:f,NO_DOTS_SLASH:h,STAR:m,START_ANCHOR:p}=ts.globChars(i),g=t.dot?f:d,S=t.dot?h:d,x=t.capture?"":"?:",$={negated:!1,prefix:""},k=t.bash===!0?".*?":m;t.capture&&(k=`(${k})`);let y=_=>_.noglobstar===!0?k:`(${x}(?:(?!${p}${_.dot?u:o}).)*?)`,b=_=>{switch(_){case"*":return`${g}${l}${k}`;case".*":return`${o}${l}${k}`;case"*.*":return`${g}${k}${o}${l}${k}`;case"*/*":return`${g}${k}${a}${l}${S}${k}`;case"**":return g+y(t);case"**/*":return`(?:${g}${y(t)}${a})?${S}${l}${k}`;case"**/*.*":return`(?:${g}${y(t)}${a})?${S}${k}${o}${l}${k}`;case"**/.*":return`(?:${g}${y(t)}${a})?${o}${l}${k}`;default:{let T=/^(.*?)\.(\w+)$/.exec(_);if(!T)return;let P=b(T[1]);return P?P+o+T[2]:void 0}}},v=$e.removePrefix(n,$),w=b(v);return w&&t.strictSlashes!==!0&&(w+=`${a}?`),w};ud.exports=Ao});var pd=N((bE,fd)=>{"use strict";var tv=require("path"),nv=od(),ko=dd(),$o=nr(),sv=Zn(),rv=n=>n&&typeof n=="object"&&!Array.isArray(n),ge=(n,e,t=!1)=>{if(Array.isArray(n)){let d=n.map(h=>ge(h,e,t));return h=>{for(let m of d){let p=m(h);if(p)return p}return!1}}let s=rv(n)&&n.tokens&&n.input;if(n===""||typeof n!="string"&&!s)throw new TypeError("Expected pattern to be a non-empty string");let r=e||{},i=$o.isWindows(e),o=s?ge.compileRe(n,e):ge.makeRe(n,e,!1,!0),a=o.state;delete o.state;let l=()=>!1;if(r.ignore){let d={...e,ignore:null,onMatch:null,onResult:null};l=ge(r.ignore,d,t)}let u=(d,f=!1)=>{let{isMatch:h,match:m,output:p}=ge.test(d,o,e,{glob:n,posix:i}),g={glob:n,state:a,regex:o,posix:i,input:d,output:p,match:m,isMatch:h};return typeof r.onResult=="function"&&r.onResult(g),h===!1?(g.isMatch=!1,f?g:!1):l(d)?(typeof r.onIgnore=="function"&&r.onIgnore(g),g.isMatch=!1,f?g:!1):(typeof r.onMatch=="function"&&r.onMatch(g),f?g:!0)};return t&&(u.state=a),u};ge.test=(n,e,t,{glob:s,posix:r}={})=>{if(typeof n!="string")throw new TypeError("Expected input to be a string");if(n==="")return{isMatch:!1,output:""};let i=t||{},o=i.format||(r?$o.toPosixSlashes:null),a=n===s,l=a&&o?o(n):n;return a===!1&&(l=o?o(n):n,a=l===s),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=ge.matchBase(n,e,t,r):a=e.exec(l)),{isMatch:!!a,match:a,output:l}};ge.matchBase=(n,e,t,s=$o.isWindows(t))=>(e instanceof RegExp?e:ge.makeRe(e,t)).test(tv.basename(n));ge.isMatch=(n,e,t)=>ge(e,t)(n);ge.parse=(n,e)=>Array.isArray(n)?n.map(t=>ge.parse(t,e)):ko(n,{...e,fastpaths:!1});ge.scan=(n,e)=>nv(n,e);ge.compileRe=(n,e,t=!1,s=!1)=>{if(t===!0)return n.output;let r=e||{},i=r.contains?"":"^",o=r.contains?"":"$",a=`${i}(?:${n.output})${o}`;n&&n.negated===!0&&(a=`^(?!${a}).*$`);let l=ge.toRegex(a,e);return s===!0&&(l.state=n),l};ge.makeRe=(n,e={},t=!1,s=!1)=>{if(!n||typeof n!="string")throw new TypeError("Expected a non-empty string");let r={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(n[0]==="."||n[0]==="*")&&(r.output=ko.fastpaths(n,e)),r.output||(r=ko(n,e)),ge.compileRe(r,e,t,s)};ge.toRegex=(n,e)=>{try{let t=e||{};return new RegExp(n,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};ge.constants=sv;fd.exports=ge});var Co=N((vE,hd)=>{"use strict";hd.exports=pd()});var Sd=N((wE,xd)=>{"use strict";var ss=require("fs"),{Readable:iv}=require("stream"),ns=require("path"),{promisify:ar}=require("util"),Eo=Co(),ov=ar(ss.readdir),av=ar(ss.stat),md=ar(ss.lstat),lv=ar(ss.realpath),cv="!",vd="READDIRP_RECURSIVE_ERROR",uv=new Set(["ENOENT","EPERM","EACCES","ELOOP",vd]),To="files",wd="directories",ir="files_directories",rr="all",gd=[To,wd,ir,rr],dv=n=>uv.has(n.code),[yd,fv]=process.versions.node.split(".").slice(0,2).map(n=>Number.parseInt(n,10)),pv=process.platform==="win32"&&(yd>10||yd===10&&fv>=5),bd=n=>{if(n!==void 0){if(typeof n=="function")return n;if(typeof n=="string"){let e=Eo(n.trim());return t=>e(t.basename)}if(Array.isArray(n)){let e=[],t=[];for(let s of n){let r=s.trim();r.charAt(0)===cv?t.push(Eo(r.slice(1))):e.push(Eo(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))}}},or=class n extends iv{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:To,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=bd(t.fileFilter),this._directoryFilter=bd(t.directoryFilter);let i=t.lstat?md:av;pv?this._stat=o=>i(o,{bigint:!0}):this._stat=i,this._maxDepth=t.depth,this._wantsDir=[wd,ir,rr].includes(r),this._wantsFile=[To,ir,rr].includes(r),this._wantsEverything=r===rr,this._root=ns.resolve(s),this._isDirent="Dirent"in ss&&!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(s,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:t,depth:s,files:r=[]}=this.parent||{};if(r.length>0){let i=r.splice(0,e).map(o=>this._formatEntry(o,t));for(let o of await Promise.all(i)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,s+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}if(this.parent=await i,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let s;try{s=await ov(e,this._rdOptions)}catch(r){this._onError(r)}return{files:s,depth:t,path:e}}async _formatEntry(e,t){let s;try{let r=this._isDirent?e.name:e,i=ns.resolve(ns.join(t,r));s={path:ns.relative(this._root,i),fullPath:i,basename:r},s[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(r){this._onError(r)}return s}_onError(e){dv(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let t=e&&e[this._statsProp];if(t){if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let s=e.fullPath;try{let r=await lv(s),i=await md(r);if(i.isFile())return"file";if(i.isDirectory()){let o=r.length;if(s.startsWith(r)&&s.substr(o,1)===ns.sep){let a=new Error(`Circular symlink detected: "${s}" points to "${r}"`);return a.code=vd,this._onError(a)}return"directory"}}catch(r){this._onError(r)}}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}},xn=(n,e={})=>{let t=e.entryType||e.type;if(t==="both"&&(t=ir),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&&!gd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${gd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=n,new or(e)},hv=(n,e={})=>new Promise((t,s)=>{let r=[];xn(n,e).on("data",i=>r.push(i)).on("end",()=>t(r)).on("error",i=>s(i))});xn.promise=hv;xn.ReaddirpStream=or;xn.default=xn;xd.exports=xn});var Ro=N((xE,_d)=>{_d.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 Td=N((Cd,Ed)=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var $d=Co(),mv=Ro(),Ad="!",gv={returnIndex:!1},yv=n=>Array.isArray(n)?n:[n],bv=(n,e)=>{if(typeof n=="function")return n;if(typeof n=="string"){let t=$d(n,e);return s=>n===s||t(s)}return n instanceof RegExp?t=>n.test(t):t=>!1},kd=(n,e,t,s)=>{let r=Array.isArray(t),i=r?t[0]:t;if(!r&&typeof i!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(i));let o=mv(i,!1);for(let l=0;l<e.length;l++){let u=e[l];if(u(o))return s?-1:!1}let a=r&&[o].concat(t.slice(1));for(let l=0;l<n.length;l++){let u=n[l];if(r?u(...a):u(o))return s?l:!0}return s?-1:!1},Oo=(n,e,t=gv)=>{if(n==null)throw new TypeError("anymatch: specify first argument");let s=typeof t=="boolean"?{returnIndex:t}:t,r=s.returnIndex||!1,i=yv(n),o=i.filter(l=>typeof l=="string"&&l.charAt(0)===Ad).map(l=>l.slice(1)).map(l=>$d(l,s)),a=i.filter(l=>typeof l!="string"||typeof l=="string"&&l.charAt(0)!==Ad).map(l=>bv(l,s));return e==null?(l,u=!1)=>kd(a,o,l,typeof u=="boolean"?u:!1):kd(a,o,e,r)};Oo.default=Oo;Ed.exports=Oo});var Od=N((SE,Rd)=>{Rd.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 Po=N((_E,Md)=>{var vv=Od(),Pd={"{":"}","(":")","[":"]"},wv=function(n){if(n[0]==="!")return!0;for(var e=0,t=-2,s=-2,r=-2,i=-2,o=-2;e<n.length;){if(n[e]==="*"||n[e+1]==="?"&&/[\].+)]/.test(n[e])||s!==-1&&n[e]==="["&&n[e+1]!=="]"&&(s<e&&(s=n.indexOf("]",e)),s>e&&(o===-1||o>s||(o=n.indexOf("\\",e),o===-1||o>s)))||r!==-1&&n[e]==="{"&&n[e+1]!=="}"&&(r=n.indexOf("}",e),r>e&&(o=n.indexOf("\\",e),o===-1||o>r))||i!==-1&&n[e]==="("&&n[e+1]==="?"&&/[:!=]/.test(n[e+2])&&n[e+3]!==")"&&(i=n.indexOf(")",e),i>e&&(o=n.indexOf("\\",e),o===-1||o>i))||t!==-1&&n[e]==="("&&n[e+1]!=="|"&&(t<e&&(t=n.indexOf("|",e)),t!==-1&&n[t+1]!==")"&&(i=n.indexOf(")",t),i>t&&(o=n.indexOf("\\",t),o===-1||o>i))))return!0;if(n[e]==="\\"){var a=n[e+1];e+=2;var l=Pd[a];if(l){var u=n.indexOf(l,e);u!==-1&&(e=u+1)}if(n[e]==="!")return!0}else e++}return!1},xv=function(n){if(n[0]==="!")return!0;for(var e=0;e<n.length;){if(/[*?{}()[\]]/.test(n[e]))return!0;if(n[e]==="\\"){var t=n[e+1];e+=2;var s=Pd[t];if(s){var r=n.indexOf(s,e);r!==-1&&(e=r+1)}if(n[e]==="!")return!0}else e++}return!1};Md.exports=function(e,t){if(typeof e!="string"||e==="")return!1;if(vv(e))return!0;var s=wv;return t&&t.strict===!1&&(s=xv),s(e)}});var Dd=N((AE,Id)=>{"use strict";var Sv=Po(),_v=require("path").posix.dirname,Av=require("os").platform()==="win32",Mo="/",kv=/\\/g,$v=/[\{\[].*[\}\]]$/,Cv=/(^|[^\\])([\{\[]|\([^\)]+$)/,Ev=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Id.exports=function(e,t){var s=Object.assign({flipBackslashes:!0},t);s.flipBackslashes&&Av&&e.indexOf(Mo)<0&&(e=e.replace(kv,Mo)),$v.test(e)&&(e+=Mo),e+="a";do e=_v(e);while(Sv(e)||Cv.test(e));return e.replace(Ev,"$1")}});var lr=N(We=>{"use strict";We.isInteger=n=>typeof n=="number"?Number.isInteger(n):typeof n=="string"&&n.trim()!==""?Number.isInteger(Number(n)):!1;We.find=(n,e)=>n.nodes.find(t=>t.type===e);We.exceedsLimit=(n,e,t=1,s)=>s===!1||!We.isInteger(n)||!We.isInteger(e)?!1:(Number(e)-Number(n))/Number(t)>=s;We.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)};We.encloseBrace=n=>n.type!=="brace"?!1:n.commas>>0+n.ranges>>0===0?(n.invalid=!0,!0):!1;We.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;We.isOpenOrClose=n=>n.type==="open"||n.type==="close"?!0:n.open===!0||n.close===!0;We.reduce=n=>n.reduce((e,t)=>(t.type==="text"&&e.push(t.value),t.type==="range"&&(t.type="text"),e),[]);We.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 cr=N(($E,Fd)=>{"use strict";var Ld=lr();Fd.exports=(n,e={})=>{let t=(s,r={})=>{let i=e.escapeInvalid&&Ld.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(i||o)&&Ld.isOpenOrClose(s)?"\\"+s.value:s.value;if(s.value)return s.value;if(s.nodes)for(let l of s.nodes)a+=t(l);return a};return t(n)}});var jd=N((CE,Nd)=>{"use strict";Nd.exports=function(n){return typeof n=="number"?n-n===0:typeof n=="string"&&n.trim()!==""?Number.isFinite?Number.isFinite(+n):isFinite(+n):!1}});var zd=N((EE,Vd)=>{"use strict";var Hd=jd(),Qt=(n,e,t)=>{if(Hd(n)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||n===e)return String(n);if(Hd(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 u=Math.min(n,e),d=Math.max(n,e);if(Math.abs(u-d)===1){let g=n+"|"+e;return s.capture?`(${g})`:s.wrap===!1?g:`(?:${g})`}let f=Gd(n)||Gd(e),h={min:n,max:e,a:u,b:d},m=[],p=[];if(f&&(h.isPadded=f,h.maxLen=String(h.max).length),u<0){let g=d<0?Math.abs(d):1;p=Bd(g,Math.abs(u),h,s),u=h.a=0}return d>=0&&(m=Bd(u,d,h,s)),h.negatives=p,h.positives=m,h.result=Tv(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 Tv(n,e,t){let s=Io(n,e,"-",!1,t)||[],r=Io(e,n,"",!1,t)||[],i=Io(n,e,"-?",!0,t)||[];return s.concat(i).concat(r).join("|")}function Rv(n,e){let t=1,s=1,r=qd(n,t),i=new Set([e]);for(;n<=r&&r<=e;)i.add(r),t+=1,r=qd(n,t);for(r=Kd(e+1,s)-1;n<r&&r<=e;)i.add(r),s+=1,r=Kd(e+1,s)-1;return i=[...i],i.sort(Mv),i}function Ov(n,e,t){if(n===e)return{pattern:n,count:[],digits:0};let s=Pv(n,e),r=s.length,i="",o=0;for(let a=0;a<r;a++){let[l,u]=s[a];l===u?i+=l:l!=="0"||u!=="9"?i+=Iv(l,u,t):o++}return o&&(i+=t.shorthand===!0?"\\d":"[0-9]"),{pattern:i,count:[o],digits:r}}function Bd(n,e,t,s){let r=Rv(n,e),i=[],o=n,a;for(let l=0;l<r.length;l++){let u=r[l],d=Ov(String(o),String(u),s),f="";if(!t.isPadded&&a&&a.pattern===d.pattern){a.count.length>1&&a.count.pop(),a.count.push(d.count[0]),a.string=a.pattern+Wd(a.count),o=u+1;continue}t.isPadded&&(f=Dv(u,t,s)),d.string=f+d.pattern+Wd(d.count),i.push(d),o=u+1,a=d}return i}function Io(n,e,t,s,r){let i=[];for(let o of n){let{string:a}=o;!s&&!Ud(e,"string",a)&&i.push(t+a),s&&Ud(e,"string",a)&&i.push(t+a)}return i}function Pv(n,e){let t=[];for(let s=0;s<n.length;s++)t.push([n[s],e[s]]);return t}function Mv(n,e){return n>e?1:e>n?-1:0}function Ud(n,e,t){return n.some(s=>s[e]===t)}function qd(n,e){return Number(String(n).slice(0,-e)+"9".repeat(e))}function Kd(n,e){return n-n%Math.pow(10,e)}function Wd(n){let[e=0,t=""]=n;return t||e>1?`{${e+(t?","+t:"")}}`:""}function Iv(n,e,t){return`[${n}${e-n===1?"":"-"}${e}]`}function Gd(n){return/^-?(0+)\d/.test(n)}function Dv(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={};Vd.exports=Qt});var Fo=N((TE,tf)=>{"use strict";var Lv=require("util"),Jd=zd(),Yd=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),Fv=n=>e=>n===!0?Number(e):String(e),Do=n=>typeof n=="number"||typeof n=="string"&&n!=="",rs=n=>Number.isInteger(+n),Lo=n=>{let e=`${n}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},Nv=(n,e,t)=>typeof n=="string"||typeof e=="string"?!0:t.stringify===!0,jv=(n,e,t)=>{if(e>0){let s=n[0]==="-"?"-":"";s&&(n=n.slice(1)),n=s+n.padStart(s?e-1:e,"0")}return t===!1?String(n):n},dr=(n,e)=>{let t=n[0]==="-"?"-":"";for(t&&(n=n.slice(1),e--);n.length<e;)n="0"+n;return t?"-"+n:n},Hv=(n,e,t)=>{n.negatives.sort((a,l)=>a<l?-1:a>l?1:0),n.positives.sort((a,l)=>a<l?-1:a>l?1:0);let s=e.capture?"":"?:",r="",i="",o;return n.positives.length&&(r=n.positives.map(a=>dr(String(a),t)).join("|")),n.negatives.length&&(i=`-(${s}${n.negatives.map(a=>dr(String(a),t)).join("|")})`),r&&i?o=`${r}|${i}`:o=r||i,e.wrap?`(${s}${o})`:o},Xd=(n,e,t,s)=>{if(t)return Jd(n,e,{wrap:!1,...s});let r=String.fromCharCode(n);if(n===e)return r;let i=String.fromCharCode(e);return`[${r}-${i}]`},Qd=(n,e,t)=>{if(Array.isArray(n)){let s=t.wrap===!0,r=t.capture?"":"?:";return s?`(${r}${n.join("|")})`:n.join("|")}return Jd(n,e,t)},Zd=(...n)=>new RangeError("Invalid range arguments: "+Lv.inspect(...n)),ef=(n,e,t)=>{if(t.strictRanges===!0)throw Zd([n,e]);return[]},Bv=(n,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${n}" to be a number`);return[]},Uv=(n,e,t=1,s={})=>{let r=Number(n),i=Number(e);if(!Number.isInteger(r)||!Number.isInteger(i)){if(s.strictRanges===!0)throw Zd([n,e]);return[]}r===0&&(r=0),i===0&&(i=0);let o=r>i,a=String(n),l=String(e),u=String(t);t=Math.max(Math.abs(t),1);let d=Lo(a)||Lo(l)||Lo(u),f=d?Math.max(a.length,l.length,u.length):0,h=d===!1&&Nv(n,e,s)===!1,m=s.transform||Fv(h);if(s.toRegex&&t===1)return Xd(dr(n,f),dr(e,f),!0,s);let p={negatives:[],positives:[]},g=$=>p[$<0?"negatives":"positives"].push(Math.abs($)),S=[],x=0;for(;o?r>=i:r<=i;)s.toRegex===!0&&t>1?g(r):S.push(jv(m(r,x),f,h)),r=o?r-t:r+t,x++;return s.toRegex===!0?t>1?Hv(p,s,f):Qd(S,null,{wrap:!1,...s}):S},qv=(n,e,t=1,s={})=>{if(!rs(n)&&n.length>1||!rs(e)&&e.length>1)return ef(n,e,s);let r=s.transform||(h=>String.fromCharCode(h)),i=`${n}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=i>o,l=Math.min(i,o),u=Math.max(i,o);if(s.toRegex&&t===1)return Xd(l,u,!1,s);let d=[],f=0;for(;a?i>=o:i<=o;)d.push(r(i,f)),i=a?i-t:i+t,f++;return s.toRegex===!0?Qd(d,null,{wrap:!1,options:s}):d},ur=(n,e,t,s={})=>{if(e==null&&Do(n))return[n];if(!Do(n)||!Do(e))return ef(n,e,s);if(typeof t=="function")return ur(n,e,1,{transform:t});if(Yd(t))return ur(n,e,0,t);let r={...s};return r.capture===!0&&(r.wrap=!0),t=t||r.step||1,rs(t)?rs(n)&&rs(e)?Uv(n,e,t,r):qv(n,e,Math.max(Math.abs(t),1),r):t!=null&&!Yd(t)?Bv(t,r):ur(n,e,1,t)};tf.exports=ur});var rf=N((RE,sf)=>{"use strict";var Kv=Fo(),nf=lr(),Wv=(n,e={})=>{let t=(s,r={})=>{let i=nf.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a=i===!0||o===!0,l=e.escapeInvalid===!0?"\\":"",u="";if(s.isOpen===!0)return l+s.value;if(s.isClose===!0)return console.log("node.isClose",l,s.value),l+s.value;if(s.type==="open")return a?l+s.value:"(";if(s.type==="close")return a?l+s.value:")";if(s.type==="comma")return s.prev.type==="comma"?"":a?s.value:"|";if(s.value)return s.value;if(s.nodes&&s.ranges>0){let d=nf.reduce(s.nodes),f=Kv(...d,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(f.length!==0)return d.length>1&&f.length>1?`(${f})`:f}if(s.nodes)for(let d of s.nodes)u+=t(d,s);return u};return t(n)};sf.exports=Wv});var lf=N((OE,af)=>{"use strict";var Gv=Fo(),of=cr(),Sn=lr(),Zt=(n="",e="",t=!1)=>{let s=[];if(n=[].concat(n),e=[].concat(e),!e.length)return n;if(!n.length)return t?Sn.flatten(e).map(r=>`{${r}}`):e;for(let r of n)if(Array.isArray(r))for(let i of r)s.push(Zt(i,e,t));else for(let i of e)t===!0&&typeof i=="string"&&(i=`{${i}}`),s.push(Array.isArray(i)?Zt(r,i,t):r+i);return Sn.flatten(s)},Vv=(n,e={})=>{let t=e.rangeLimit===void 0?1e3:e.rangeLimit,s=(r,i={})=>{r.queue=[];let o=i,a=i.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(r.invalid||r.dollar){a.push(Zt(a.pop(),of(r,e)));return}if(r.type==="brace"&&r.invalid!==!0&&r.nodes.length===2){a.push(Zt(a.pop(),["{}"]));return}if(r.nodes&&r.ranges>0){let f=Sn.reduce(r.nodes);if(Sn.exceedsLimit(...f,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let h=Gv(...f,e);h.length===0&&(h=of(r,e)),a.push(Zt(a.pop(),h)),r.nodes=[];return}let l=Sn.encloseBrace(r),u=r.queue,d=r;for(;d.type!=="brace"&&d.type!=="root"&&d.parent;)d=d.parent,u=d.queue;for(let f=0;f<r.nodes.length;f++){let h=r.nodes[f];if(h.type==="comma"&&r.type==="brace"){f===1&&u.push(""),u.push("");continue}if(h.type==="close"){a.push(Zt(a.pop(),u,l));continue}if(h.value&&h.type!=="open"){u.push(Zt(u.pop(),h.value));continue}h.nodes&&s(h,r)}return u};return Sn.flatten(s(n))};af.exports=Vv});var uf=N((PE,cf)=>{"use strict";cf.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:`
312
- `,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 mf=N((ME,hf)=>{"use strict";var zv=cr(),{MAX_LENGTH:df,CHAR_BACKSLASH:No,CHAR_BACKTICK:Yv,CHAR_COMMA:Jv,CHAR_DOT:Xv,CHAR_LEFT_PARENTHESES:Qv,CHAR_RIGHT_PARENTHESES:Zv,CHAR_LEFT_CURLY_BRACE:ew,CHAR_RIGHT_CURLY_BRACE:tw,CHAR_LEFT_SQUARE_BRACKET:ff,CHAR_RIGHT_SQUARE_BRACKET:pf,CHAR_DOUBLE_QUOTE:nw,CHAR_SINGLE_QUOTE:sw,CHAR_NO_BREAK_SPACE:rw,CHAR_ZERO_WIDTH_NOBREAK_SPACE:iw}=uf(),ow=(n,e={})=>{if(typeof n!="string")throw new TypeError("Expected a string");let t=e||{},s=typeof t.maxLength=="number"?Math.min(df,t.maxLength):df;if(n.length>s)throw new SyntaxError(`Input length (${n.length}), exceeds max characters (${s})`);let r={type:"root",input:n,nodes:[]},i=[r],o=r,a=r,l=0,u=n.length,d=0,f=0,h,m=()=>n[d++],p=g=>{if(g.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&g.type==="text"){a.value+=g.value;return}return o.nodes.push(g),g.parent=o,g.prev=a,a=g,g};for(p({type:"bos"});d<u;)if(o=i[i.length-1],h=m(),!(h===iw||h===rw)){if(h===No){p({type:"text",value:(e.keepEscaping?h:"")+m()});continue}if(h===pf){p({type:"text",value:"\\"+h});continue}if(h===ff){l++;let g;for(;d<u&&(g=m());){if(h+=g,g===ff){l++;continue}if(g===No){h+=m();continue}if(g===pf&&(l--,l===0))break}p({type:"text",value:h});continue}if(h===Qv){o=p({type:"paren",nodes:[]}),i.push(o),p({type:"text",value:h});continue}if(h===Zv){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===nw||h===sw||h===Yv){let g=h,S;for(e.keepQuotes!==!0&&(h="");d<u&&(S=m());){if(S===No){h+=S+m();continue}if(S===g){e.keepQuotes===!0&&(h+=S);break}h+=S}p({type:"text",value:h});continue}if(h===ew){f++;let S={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:f,commas:0,ranges:0,nodes:[]};o=p(S),i.push(o),p({type:"open",value:h});continue}if(h===tw){if(o.type!=="brace"){p({type:"text",value:h});continue}let g="close";o=i.pop(),o.close=!0,p({type:g,value:h}),f--,o=i[i.length-1];continue}if(h===Jv&&f>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:zv(o)}]}p({type:"comma",value:h}),o.commas++;continue}if(h===Xv&&f>0&&o.commas===0){let g=o.nodes;if(f===0||g.length===0){p({type:"text",value:h});continue}if(a.type==="dot"){if(o.range=[],a.value+=h,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){g.pop();let S=g[g.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(x=>{x.nodes||(x.type==="open"&&(x.isOpen=!0),x.type==="close"&&(x.isClose=!0),x.nodes||(x.type="text"),x.invalid=!0)});let g=i[i.length-1],S=g.nodes.indexOf(o);g.nodes.splice(S,1,...o.nodes)}while(i.length>0);return p({type:"eos"}),r};hf.exports=ow});var bf=N((IE,yf)=>{"use strict";var gf=cr(),aw=rf(),lw=lf(),cw=mf(),Ue=(n,e={})=>{let t=[];if(Array.isArray(n))for(let s of n){let r=Ue.create(s,e);Array.isArray(r)?t.push(...r):t.push(r)}else t=[].concat(Ue.create(n,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};Ue.parse=(n,e={})=>cw(n,e);Ue.stringify=(n,e={})=>gf(typeof n=="string"?Ue.parse(n,e):n,e);Ue.compile=(n,e={})=>(typeof n=="string"&&(n=Ue.parse(n,e)),aw(n,e));Ue.expand=(n,e={})=>{typeof n=="string"&&(n=Ue.parse(n,e));let t=lw(n,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};Ue.create=(n,e={})=>n===""||n.length<3?[n]:e.expand!==!0?Ue.compile(n,e):Ue.expand(n,e);yf.exports=Ue});var vf=N((DE,uw)=>{uw.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]});var xf=N((LE,wf)=>{wf.exports=vf()});var _f=N((FE,Sf)=>{"use strict";var dw=require("path"),fw=xf(),pw=new Set(fw);Sf.exports=n=>pw.has(dw.extname(n).slice(1).toLowerCase())});var fr=N(B=>{"use strict";var{sep:hw}=require("path"),{platform:jo}=process,mw=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=`.${hw}`;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=jo==="win32";B.isMacos=jo==="darwin";B.isLinux=jo==="linux";B.isIBMi=mw.type()==="OS400"});var Tf=N((jE,Ef)=>{"use strict";var Ot=require("fs"),xe=require("path"),{promisify:ls}=require("util"),gw=_f(),{isWindows:yw,isLinux:bw,EMPTY_FN:vw,EMPTY_STR:ww,KEY_LISTENERS:_n,KEY_ERR:Ho,KEY_RAW:is,HANDLER_KEYS:xw,EV_CHANGE:hr,EV_ADD:pr,EV_ADD_DIR:Sw,EV_ERROR:kf,STR_DATA:_w,STR_END:Aw,BRACE_START:kw,STAR:$w}=fr(),Cw="watch",Ew=ls(Ot.open),$f=ls(Ot.stat),Tw=ls(Ot.lstat),Rw=ls(Ot.close),Bo=ls(Ot.realpath),Ow={lstat:Tw,stat:$f},qo=(n,e)=>{n instanceof Set?n.forEach(e):e(n)},os=(n,e,t)=>{let s=n[e];s instanceof Set||(n[e]=s=new Set([s])),s.add(t)},Pw=n=>e=>{let t=n[e];t instanceof Set?t.clear():delete n[e]},as=(n,e,t)=>{let s=n[e];s instanceof Set?s.delete(t):s===t&&delete n[e]},Cf=n=>n instanceof Set?n.size===0:!n,mr=new Map;function Af(n,e,t,s,r){let i=(o,a)=>{t(n),r(o,a,{watchedPath:n}),a&&n!==a&&gr(xe.resolve(n,a),_n,xe.join(n,a))};try{return Ot.watch(n,e,i)}catch(o){s(o)}}var gr=(n,e,t,s,r)=>{let i=mr.get(n);i&&qo(i[e],o=>{o(t,s,r)})},Mw=(n,e,t,s)=>{let{listener:r,errHandler:i,rawEmitter:o}=s,a=mr.get(e),l;if(!t.persistent)return l=Af(n,t,r,i,o),l.close.bind(l);if(a)os(a,_n,r),os(a,Ho,i),os(a,is,o);else{if(l=Af(n,t,gr.bind(null,e,_n),i,gr.bind(null,e,is)),!l)return;l.on(kf,async u=>{let d=gr.bind(null,e,Ho);if(a.watcherUnusable=!0,yw&&u.code==="EPERM")try{let f=await Ew(n,"r");await Rw(f),d(u)}catch{}else d(u)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:l},mr.set(e,a)}return()=>{as(a,_n,r),as(a,Ho,i),as(a,is,o),Cf(a.listeners)&&(a.watcher.close(),mr.delete(e),xw.forEach(Pw(a)),a.watcher=void 0,Object.freeze(a))}},Uo=new Map,Iw=(n,e,t,s)=>{let{listener:r,rawEmitter:i}=s,o=Uo.get(e),a=new Set,l=new Set,u=o&&o.options;return u&&(u.persistent<t.persistent||u.interval>t.interval)&&(a=o.listeners,l=o.rawEmitters,Ot.unwatchFile(e),o=void 0),o?(os(o,_n,r),os(o,is,i)):(o={listeners:r,rawEmitters:i,options:t,watcher:Ot.watchFile(e,t,(d,f)=>{qo(o.rawEmitters,m=>{m(hr,e,{curr:d,prev:f})});let h=d.mtimeMs;(d.size!==f.size||h>f.mtimeMs||h===0)&&qo(o.listeners,m=>m(n,d))})},Uo.set(e,o)),()=>{as(o,_n,r),as(o,is,i),Cf(o.listeners)&&(Uo.delete(e),Ot.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},Ko=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let s=this.fsw.options,r=xe.dirname(e),i=xe.basename(e);this.fsw._getWatchedDir(r).add(i);let a=xe.resolve(e),l={persistent:s.persistent};t||(t=vw);let u;return s.usePolling?(l.interval=s.enableBinaryInterval&&gw(i)?s.binaryInterval:s.interval,u=Iw(e,a,l,{listener:t,rawEmitter:this.fsw._emitRaw})):u=Mw(e,a,l,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),u}_handleFile(e,t,s){if(this.fsw.closed)return;let r=xe.dirname(e),i=xe.basename(e),o=this.fsw._getWatchedDir(r),a=t;if(o.has(i))return;let l=async(d,f)=>{if(this.fsw._throttle(Cw,e,5)){if(!f||f.mtimeMs===0)try{let h=await $f(e);if(this.fsw.closed)return;let m=h.atimeMs,p=h.mtimeMs;(!m||m<=p||p!==a.mtimeMs)&&this.fsw._emit(hr,e,h),bw&&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(hr,e,f),a=f}}},u=this._watchWithNodeFs(e,l);if(!(s&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(pr,e,0))return;this.fsw._emit(pr,e,t)}return u}async _handleSymlink(e,t,s,r){if(this.fsw.closed)return;let i=e.fullPath,o=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await Bo(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(hr,s,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(pr,s,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,s,r,i,o,a){if(e=xe.join(e,ww),!s.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let l=this.fsw._getWatchedDir(s.path),u=new Set,d=this.fsw._readdirp(e,{fileFilter:f=>s.filterPath(f),directoryFilter:f=>s.filterDir(f),depth:0}).on(_w,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,m=xe.join(e,h);if(u.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===r||!r&&!l.has(h))&&(this.fsw._incrReadyCount(),m=xe.join(i,xe.relative(i,m)),this._addToNodeFs(m,t,s,o+1))}}).on(kf,this._boundHandleError);return new Promise(f=>d.once(Aw,()=>{if(this.fsw.closed){d=void 0;return}let h=a?a.clear():!1;f(),l.getChildren().filter(m=>m!==e&&!u.has(m)&&(!s.hasGlob||s.filterPath({fullPath:xe.resolve(e,m)}))).forEach(m=>{this.fsw._remove(e,m)}),d=void 0,h&&this._handleRead(e,!1,s,r,i,o,a)}))}async _handleDir(e,t,s,r,i,o,a){let l=this.fsw._getWatchedDir(xe.dirname(e)),u=l.has(xe.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!i&&!u&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(Sw,e,t),l.add(xe.basename(e)),this.fsw._getWatchedDir(e);let d,f,h=this.fsw.options.depth;if((h==null||r<=h)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,s,o,i,e,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(m,p)=>{p&&p.mtimeMs===0||this._handleRead(m,!1,o,i,e,r,d)})}return f}async _addToNodeFs(e,t,s,r,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,r);!a.hasGlob&&s&&(a.hasGlob=s.hasGlob,a.globFilter=s.globFilter,a.filterPath=l=>s.filterPath(l),a.filterDir=l=>s.filterDir(l));try{let l=await Ow[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))return o(),!1;let u=this.fsw.options.followSymlinks&&!e.includes($w)&&!e.includes(kw),d;if(l.isDirectory()){let f=xe.resolve(e),h=u?await Bo(e):e;if(this.fsw.closed||(d=await this._handleDir(a.watchPath,l,t,r,i,a,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(l.isSymbolicLink()){let f=u?await Bo(e):e;if(this.fsw.closed)return;let h=xe.dirname(a.watchPath);if(this.fsw._getWatchedDir(h).add(a.watchPath),this.fsw._emit(pr,a.watchPath,l),d=await this._handleDir(h,l,t,r,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(xe.resolve(e),f)}else d=this._handleFile(a.watchPath,l,t);return o(),this.fsw._addPathCloser(e,d),!1}catch(l){if(this.fsw._handleError(l))return o(),e}}};Ef.exports=Ko});var Lf=N((HE,Qo)=>{"use strict";var Jo=require("fs"),Se=require("path"),{promisify:Xo}=require("util"),An;try{An=require("fsevents")}catch(n){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(n)}if(An){let n=process.version.match(/v(\d+)\.(\d+)/);if(n&&n[1]&&n[2]){let e=Number.parseInt(n[1],10),t=Number.parseInt(n[2],10);e===8&&t<16&&(An=void 0)}}var{EV_ADD:Wo,EV_CHANGE:Dw,EV_ADD_DIR:Rf,EV_UNLINK:yr,EV_ERROR:Lw,STR_DATA:Fw,STR_END:Nw,FSEVENT_CREATED:jw,FSEVENT_MODIFIED:Hw,FSEVENT_DELETED:Bw,FSEVENT_MOVED:Uw,FSEVENT_UNKNOWN:qw,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:Kw,FSEVENT_TYPE_FILE:Ww,FSEVENT_TYPE_DIRECTORY:cs,FSEVENT_TYPE_SYMLINK:Df,ROOT_GLOBSTAR:Of,DIR_SUFFIX:Gw,DOT_SLASH:Pf,FUNCTION_TYPE:Go,EMPTY_FN:Vw,IDENTITY_FN:zw}=fr(),Yw=n=>isNaN(n)?{}:{depth:n},zo=Xo(Jo.stat),Jw=Xo(Jo.lstat),Mf=Xo(Jo.realpath),Xw={stat:zo,lstat:Jw},en=new Map,Qw=10,Zw=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),ex=(n,e)=>({stop:An.watch(n,e)});function tx(n,e,t,s){let r=Se.extname(e)?Se.dirname(e):e,i=Se.dirname(r),o=en.get(r);nx(i)&&(r=i);let a=Se.resolve(n),l=a!==e,u=(f,h,m)=>{l&&(f=f.replace(e,a)),(f===a||!f.indexOf(a+Se.sep))&&t(f,h,m)},d=!1;for(let f of en.keys())if(e.indexOf(Se.resolve(f)+Se.sep)===0){r=f,o=en.get(r),d=!0;break}return o||d?o.listeners.add(u):(o={listeners:new Set([u]),rawEmitter:s,watcher:ex(r,(f,h)=>{if(!o.listeners.size||h&Kw)return;let m=An.getInfo(f,h);o.listeners.forEach(p=>{p(f,h,m)}),o.rawEmitter(m.event,f,m)})},en.set(r,o)),()=>{let f=o.listeners;if(f.delete(u),!f.size&&(en.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var nx=n=>{let e=0;for(let t of en.keys())if(t.indexOf(n)===0&&(e++,e>=Qw))return!0;return!1},sx=()=>An&&en.size<128,Vo=(n,e)=>{let t=0;for(;!n.indexOf(e)&&(n=Se.dirname(n))!==e;)t++;return t},If=(n,e)=>n.type===cs&&e.isDirectory()||n.type===Df&&e.isSymbolicLink()||n.type===Ww&&e.isFile(),Yo=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+Of),!0;s.delete(e),s.delete(e+Of)}addOrChange(e,t,s,r,i,o,a,l){let u=i.has(o)?Dw:Wo;this.handleEvent(u,e,t,s,r,i,o,a,l)}async checkExists(e,t,s,r,i,o,a,l){try{let u=await zo(e);if(this.fsw.closed)return;If(a,u)?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(yr,e,t,s,r,i,o,a,l)}catch(u){u.code==="EACCES"?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(yr,e,t,s,r,i,o,a,l)}}handleEvent(e,t,s,r,i,o,a,l,u){if(!(this.fsw.closed||this.checkIgnored(t)))if(e===yr){let d=l.type===cs;(d||o.has(a))&&this.fsw._remove(i,a,d)}else{if(e===Wo){if(l.type===cs&&this.fsw._getWatchedDir(t),l.type===Df&&u.followSymlinks){let f=u.depth===void 0?void 0:Vo(s,r)+1;return this._addToFsEvents(t,!1,!0,f)}this.fsw._getWatchedDir(i).add(a)}let d=l.type===cs?e+Gw:e;this.fsw._emit(d,t),d===Rf&&this._addToFsEvents(t,!1,!0)}}_watchWithFsEvents(e,t,s,r){if(this.fsw.closed||this.fsw._isIgnored(e))return;let i=this.fsw.options,a=tx(e,t,async(l,u,d)=>{if(this.fsw.closed||i.depth!==void 0&&Vo(l,t)>i.depth)return;let f=s(Se.join(e,Se.relative(e,l)));if(r&&!r(f))return;let h=Se.dirname(f),m=Se.basename(f),p=this.fsw._getWatchedDir(d.type===cs?f:h);if(Zw.has(u)||d.event===qw)if(typeof i.ignored===Go){let g;try{g=await zo(f)}catch{}if(this.fsw.closed||this.checkIgnored(f,g))return;If(d,g)?this.addOrChange(f,l,t,h,p,m,d,i):this.handleEvent(yr,f,l,t,h,p,m,d,i)}else this.checkExists(f,l,t,h,p,m,d,i);else switch(d.event){case jw:case Hw:return this.addOrChange(f,l,t,h,p,m,d,i);case Bw:case Uw: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 Mf(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(i))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(i||e,o=>{let a=e;return i&&i!==Pf?a=o.replace(i,e):o!==Pf&&(a=Se.join(e,o)),s(a)},!1,r)}catch(i){if(this.fsw._handleError(i))return this.fsw._emitReady()}}}emitAdd(e,t,s,r,i){let o=s(e),a=t.isDirectory(),l=this.fsw._getWatchedDir(Se.dirname(o)),u=Se.basename(o);a&&this.fsw._getWatchedDir(o),!l.has(u)&&(l.add(u),(!r.ignoreInitial||i===!0)&&this.fsw._emit(a?Rf:Wo,o,t))}initWatch(e,t,s,r){if(this.fsw.closed)return;let i=this._watchWithFsEvents(s.watchPath,Se.resolve(e||s.watchPath),r,s.globFilter);this.fsw._addPathCloser(t,i)}async _addToFsEvents(e,t,s,r){if(this.fsw.closed)return;let i=this.fsw.options,o=typeof t===Go?t:zw,a=this.fsw._getWatchHelpers(e);try{let l=await Xw[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))throw null;if(l.isDirectory()){if(a.globFilter||this.emitAdd(o(e),l,o,i,s),r&&r>i.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:u=>a.filterPath(u),directoryFilter:u=>a.filterDir(u),...Yw(i.depth-(r||0))}).on(Fw,u=>{if(this.fsw.closed||u.stats.isDirectory()&&!a.filterPath(u))return;let d=Se.join(a.watchPath,u.path),{fullPath:f}=u;if(a.followSymlinks&&u.stats.isSymbolicLink()){let h=i.depth===void 0?void 0:Vo(d,Se.resolve(a.watchPath))+1;this._handleFsEventsSymlink(d,f,o,h)}else this.emitAdd(d,u.stats,o,i,s)}).on(Lw,Vw).on(Nw,()=>{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===Go)this.initWatch(void 0,e,a,o);else{let l;try{l=await Mf(a.watchPath)}catch{}this.initWatch(l,e,a,o)}}};Qo.exports=Yo;Qo.exports.canUse=sx});var Vf=N(pa=>{"use strict";var{EventEmitter:rx}=require("events"),da=require("fs"),ne=require("path"),{promisify:qf}=require("util"),ix=Sd(),ra=Td().default,ox=Dd(),Zo=Po(),ax=bf(),lx=Ro(),cx=Tf(),Ff=Lf(),{EV_ALL:ea,EV_READY:ux,EV_ADD:br,EV_CHANGE:us,EV_UNLINK:Nf,EV_ADD_DIR:dx,EV_UNLINK_DIR:fx,EV_RAW:px,EV_ERROR:ta,STR_CLOSE:hx,STR_END:mx,BACK_SLASH_RE:gx,DOUBLE_SLASH_RE:jf,SLASH_OR_BACK_SLASH_RE:yx,DOT_RE:bx,REPLACER_RE:vx,SLASH:na,SLASH_SLASH:wx,BRACE_START:xx,BANG:ia,ONE_DOT:Kf,TWO_DOTS:Sx,GLOBSTAR:_x,SLASH_GLOBSTAR:sa,ANYMATCH_OPTS:oa,STRING_TYPE:fa,FUNCTION_TYPE:Ax,EMPTY_STR:aa,EMPTY_FN:kx,isWindows:$x,isMacos:Cx,isIBMi:Ex}=fr(),Tx=qf(da.stat),Rx=qf(da.readdir),la=(n=[])=>Array.isArray(n)?n:[n],Wf=(n,e=[])=>(n.forEach(t=>{Array.isArray(t)?Wf(t,e):e.push(t)}),e),Hf=n=>{let e=Wf(la(n));if(!e.every(t=>typeof t===fa))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Gf)},Bf=n=>{let e=n.replace(gx,na),t=!1;for(e.startsWith(wx)&&(t=!0);e.match(jf);)e=e.replace(jf,na);return t&&(e=na+e),e},Gf=n=>Bf(ne.normalize(Bf(n))),Uf=(n=aa)=>e=>typeof e!==fa?e:Gf(ne.isAbsolute(e)?e:ne.join(n,e)),Ox=(n,e)=>ne.isAbsolute(n)?n:n.startsWith(ia)?ia+ne.join(e,n.slice(1)):ne.join(e,n),tt=(n,e)=>n[e]===void 0,ca=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Kf&&e!==Sx&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let s=this.path;try{await Rx(s)}catch{this._removeWatcher&&this._removeWatcher(ne.dirname(s),ne.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)}},Px="stat",Mx="lstat",ua=class{constructor(e,t,s,r){this.fsw=r,this.path=e=e.replace(vx,aa),this.watchPath=t,this.fullWatchPath=ne.resolve(t),this.hasGlob=t!==e,e===aa&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&s?void 0:!1,this.globFilter=this.hasGlob?ra(e,void 0,oa):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=s,this.statMethod=s?Px:Mx}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 ne.join(this.watchPath,ne.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let s=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===Ax?this.globFilter(s):!0)&&this.fsw._isntIgnored(s,t)&&this.fsw._hasReadPermissions(t)}getDirParts(e){if(!this.hasGlob)return[];let t=[];return(e.includes(xx)?ax.expand(e):[e]).forEach(r=>{t.push(ne.relative(this.watchPath,r).split(yx))}),t}filterDir(e){if(this.hasGlob){let t=this.getDirParts(this.checkGlobSymlink(e)),s=!1;this.unmatchedGlob=!this.dirParts.some(r=>r.every((i,o)=>(i===_x&&(s=!0),s||!t[0][o]||ra(i,t[0][o],oa))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},vr=class extends rx{constructor(e){super();let t={};e&&Object.assign(t,e),this._watched=new Map,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._symlinkPaths=new Map,this._streams=new Set,this.closed=!1,tt(t,"persistent")&&(t.persistent=!0),tt(t,"ignoreInitial")&&(t.ignoreInitial=!1),tt(t,"ignorePermissionErrors")&&(t.ignorePermissionErrors=!1),tt(t,"interval")&&(t.interval=100),tt(t,"binaryInterval")&&(t.binaryInterval=300),tt(t,"disableGlobbing")&&(t.disableGlobbing=!1),t.enableBinaryInterval=t.binaryInterval!==t.interval,tt(t,"useFsEvents")&&(t.useFsEvents=!t.usePolling),Ff.canUse()||(t.useFsEvents=!1),tt(t,"usePolling")&&!t.useFsEvents&&(t.usePolling=Cx),Ex&&(t.usePolling=!0);let r=process.env.CHOKIDAR_USEPOLLING;if(r!==void 0){let l=r.toLowerCase();l==="false"||l==="0"?t.usePolling=!1:l==="true"||l==="1"?t.usePolling=!0:t.usePolling=!!l}let i=process.env.CHOKIDAR_INTERVAL;i&&(t.interval=Number.parseInt(i,10)),tt(t,"atomic")&&(t.atomic=!t.usePolling&&!t.useFsEvents),t.atomic&&(this._pendingUnlinks=new Map),tt(t,"followSymlinks")&&(t.followSymlinks=!0),tt(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=la(t.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=kx,this._readyEmitted=!0,process.nextTick(()=>this.emit(ux)))},this._emitRaw=(...l)=>this.emit(px,...l),this._readyEmitted=!1,this.options=t,t.useFsEvents?this._fsEventsHandler=new Ff(this):this._nodeFsHandler=new cx(this),Object.freeze(t)}add(e,t,s){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=Hf(e);return r&&(o=o.map(a=>{let l=Ox(a,r);return i||!Zo(a)?l:lx(l)})),o=o.filter(a=>a.startsWith(ia)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+sa),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(ne.dirname(l),ne.basename(t||l))})})),this}unwatch(e){if(this.closed)return this;let t=Hf(e),{cwd:s}=this.options;return t.forEach(r=>{!ne.isAbsolute(r)&&!this._closers.has(r)&&(s&&(r=ne.join(s,r)),r=ne.resolve(r)),this._closePath(r),this._ignoredPaths.add(r),this._watched.has(r)&&this._ignoredPaths.add(r+sa),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?ne.relative(this.options.cwd,s):s;e[r||Kf]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(...t),e!==ta&&this.emit(ea,...t)}async _emit(e,t,s,r,i){if(this.closed)return;let o=this.options;$x&&(t=ne.normalize(t)),o.cwd&&(t=ne.relative(o.cwd,t));let a=[e,t];i!==void 0?a.push(s,r,i):r!==void 0?a.push(s,r):s!==void 0&&a.push(s);let l=o.awaitWriteFinish,u;if(l&&(u=this._pendingWrites.get(t)))return u.lastChange=new Date,this;if(o.atomic){if(e===Nf)return this._pendingUnlinks.set(t,a),setTimeout(()=>{this._pendingUnlinks.forEach((d,f)=>{this.emit(...d),this.emit(ea,...d),this._pendingUnlinks.delete(f)})},typeof o.atomic=="number"?o.atomic:100),this;e===br&&this._pendingUnlinks.has(t)&&(e=a[0]=us,this._pendingUnlinks.delete(t))}if(l&&(e===br||e===us)&&this._readyEmitted){let d=(f,h)=>{f?(e=a[0]=ta,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===us&&!this._throttle(us,t,50))return this;if(o.alwaysStat&&s===void 0&&(e===br||e===dx||e===us)){let d=o.cwd?ne.join(o.cwd,t):t,f;try{f=await Tx(d)}catch{}if(!f||this.closed)return;a.push(f)}return this.emitWithAll(e,a),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(ta,e),e||this.closed}_throttle(e,t,s){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e),i=r.get(t);if(i)return i.count++,!1;let o,a=()=>{let u=r.get(t),d=u?u.count:0;return r.delete(t),clearTimeout(o),u&&clearTimeout(u.timeoutObject),d};o=setTimeout(a,s);let l={timeoutObject:o,clear:a,count:0};return r.set(t,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,s,r){let i,o=e;this.options.cwd&&!ne.isAbsolute(e)&&(o=ne.join(this.options.cwd,e));let a=new Date,l=u=>{da.stat(o,(d,f)=>{if(d||!this._pendingWrites.has(e)){d&&d.code!=="ENOENT"&&r(d);return}let h=Number(new Date);u&&f.size!==u.size&&(this._pendingWrites.get(e).lastChange=h);let m=this._pendingWrites.get(e);h-m.lastChange>=t?(this._pendingWrites.delete(e),r(void 0,f)):i=setTimeout(l,this.options.awaitWriteFinish.pollInterval,f)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(i),s)}),i=setTimeout(l,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,t){if(this.options.atomic&&bx.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,r=this.options.ignored,i=r&&r.map(Uf(s)),o=la(i).filter(l=>typeof l===fa&&!Zo(l)).map(l=>l+sa),a=this._getGlobIgnored().map(Uf(s)).concat(i,o);this._userIgnored=ra(a,void 0,oa)}return this._userIgnored([e,t])}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e,t){let s=t||this.options.disableGlobbing||!Zo(e)?e:ox(e),r=this.options.followSymlinks;return new ua(e,s,r,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let t=ne.resolve(e);return this._watched.has(t)||this._watched.set(t,new ca(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=ne.join(e,t),i=ne.resolve(r);if(s=s??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!s&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(h=>this._remove(r,h));let l=this._getWatchedDir(e),u=l.has(t);l.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=ne.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===br)return;this._watched.delete(r),this._watched.delete(i);let f=s?fx:Nf;u&&!this._isIgnored(r)&&this._emit(f,r),this.options.useFsEvents||this._closePath(r)}_closePath(e){this._closeFile(e);let t=ne.dirname(e);this._getWatchedDir(t).remove(ne.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:ea,alwaysStat:!0,lstat:!0,...t},r=ix(e,s);return this._streams.add(r),r.once(hx,()=>{r=void 0}),r.once(mx,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};pa.FSWatcher=vr;var Ix=(n,e)=>{let t=new vr(e);return t.add(n),t};pa.watch=Ix});var Xf={};Le(Xf,{CollaborationManager:()=>ds,addTeamMember:()=>Fx,formatTeamConfig:()=>Nx,initTeamConfig:()=>Lx,loadTeamConfig:()=>Dx,saveTeamConfig:()=>Jf});function Dx(n){let e=Ge.join(n,".hablas","team.json");if(ye.existsSync(e))try{return JSON.parse(ye.readFileSync(e,"utf-8"))}catch{return null}return null}function Lx(n,e){let t={name:e,members:[]};return Jf(n,t),t}function Jf(n,e){let t=Ge.join(n,".hablas","team.json"),s=Ge.dirname(t);ye.existsSync(s)||ye.mkdirSync(s,{recursive:!0}),ye.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}function Fx(n,e,t){return n.members.push({name:e,email:t}),n}function Nx(n){return[`Team: ${n.name}`,"Members:",...n.members.map(t=>` - ${t.name} (${t.email})`)].join(`
313
- `)}var ye,Ge,wr,zf,Yf,ds,ha=L(()=>{"use strict";ye=O(require("fs")),Ge=O(require("path")),wr=O(require("os")),zf=O(require("crypto")),Yf=O(Vf());yn();ds=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||wr.userInfo().username||"developer",this.teamKey=r||"default-team",this.localStatePath=Ge.join(this.workingDir,".hablas","collaboration.json");let i=this.getProjectIdentifier();console.log(`
314
- ${c.muted("[Debug] Project Context:")} ${c.highlight(i)}`),this.projectTeamToken=zf.createHash("sha256").update(`${i}:${this.teamKey}`).digest("hex"),console.log(` ${c.muted("[Debug] Session Fingerprint:")} ${c.muted(this.projectTeamToken.slice(0,16))}...
315
- `),this.loadSupabaseConfig()}async init(){if(!this.isConfigured)return console.log(` ${c.warning("\u26A0")} ${c.secondary("Supabase is not configured in .env. Collaboration mode operates locally.")}`),!1;let e=Ge.dirname(this.localStatePath);return ye.existsSync(e)||ye.mkdirSync(e,{recursive:!0}),this.saveLocalState([],[]),this.startLoops(),this.startWatcher(),this.registerCleanups(),!0}async shutdown(){this.shuttingDown||(this.shuttingDown=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.syncInterval&&(clearTimeout(this.syncInterval),this.syncInterval=null),this.watcher&&(await this.watcher.close(),this.watcher=null),this.signalHandler&&(process.off("SIGINT",this.signalHandler),process.off("SIGTERM",this.signalHandler),this.signalHandler=null),await this.releaseAllMyLocks(),await this.deleteSession())}async apiRequest(e,t,s,r){if(!this.isConfigured)return{ok:!1,data:null};let i=`${this.supabaseUrl}/rest/v1/${e}`,o={apikey:this.supabaseKey,Authorization:`Bearer ${this.supabaseKey}`,"Content-Type":"application/json"};r?.prefer?o.Prefer=r.prefer:(t==="POST"||t==="PATCH")&&(o.Prefer="return=representation");let a=(r?.retries??0)+1,l=null;for(let u=0;u<a;u++)try{let d=await fetch(i,{method:t,headers:o,body:s?JSON.stringify(s):void 0,signal:AbortSignal.timeout(1e4)});if(!d.ok){let h=await d.text().catch(()=>"");if(l=new Error(`[Supabase ${d.status}] ${h}`),(d.status>=500||d.status===429)&&u<a-1){await this.delay(400*(u+1));continue}return{ok:!1,data:null}}let f=await d.text();return{ok:!0,data:f?JSON.parse(f):null}}catch(d){if(l=d,u<a-1){await this.delay(400*(u+1));continue}}return{ok:!1,data:null}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendHeartbeat(e,t){let s={project_team_token:this.projectTeamToken,developer_name:this.username,last_heartbeat:new Date().toISOString(),active_section:e||"idle",current_task:t||"none"},r="hablas_team_sessions?on_conflict=project_team_token,developer_name",{ok:i}=await this.apiRequest(r,"POST",s,{prefer:"resolution=merge-duplicates,return=minimal",retries:2});return i}async fetchSessions(){let e=`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}`,{data:t}=await this.apiRequest(e,"GET");return t||[]}async deleteSession(){let e=`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}&developer_name=eq.${encodeURIComponent(this.username)}`;await this.apiRequest(e,"DELETE")}async fetchLocks(){let e=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}`,{data:t}=await this.apiRequest(e,"GET");return t||[]}async acquireLock(e,t){let s={project_team_token:this.projectTeamToken,file_path:e,locked_by:this.username,lock_context:t||"editing file",created_at:new Date().toISOString()};return await this.apiRequest("hablas_team_locks?on_conflict=project_team_token,file_path","POST",s,{prefer:"resolution=ignore-duplicates,return=minimal",retries:1}),!!(await this.fetchLocks()).find(a=>a.file_path===e&&a.locked_by===this.username)}async releaseLock(e){let t=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}&file_path=eq.${encodeURIComponent(e)}&locked_by=eq.${encodeURIComponent(this.username)}`;return await this.apiRequest(t,"DELETE"),!0}async releaseAllMyLocks(){let e=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}&locked_by=eq.${encodeURIComponent(this.username)}`;await this.apiRequest(e,"DELETE")}async sendMessage(e,t){let s={project_team_token:this.projectTeamToken,sender_name:this.username,receiver_name:e,message_content:t,is_read:!1,created_at:new Date().toISOString()},{ok:r}=await this.apiRequest("hablas_team_messages","POST",s,{retries:1});return r}async fetchUnreadMessages(){let e=`hablas_team_messages?project_team_token=eq.${this.projectTeamToken}&receiver_name=eq.${encodeURIComponent(this.username)}&is_read=eq.false`,t=(await this.apiRequest(e,"GET")).data||[];if(t.length>0)for(let s of t){let r=`hablas_team_messages?id=eq.${s.id}`;await this.apiRequest(r,"PATCH",{is_read:!0})}return t}saveLocalState(e,t){let s={project_team_token:this.projectTeamToken,last_sync:new Date().toISOString(),my_username:this.username,sessions:e,locks:t};ye.writeFileSync(this.localStatePath,JSON.stringify(s,null,2),"utf-8")}getLocalState(){if(ye.existsSync(this.localStatePath))try{return JSON.parse(ye.readFileSync(this.localStatePath,"utf-8"))}catch{}return{sessions:[],locks:[],my_username:this.username}}startLoops(){this.beat("idle","standby"),this.heartbeatInterval=setInterval(()=>{this.beat()},n.HEARTBEAT_MS);let e=t=>{this.syncInterval=setTimeout(async()=>{if(this.shuttingDown)return;await this.syncWithCloud()?this.idlePollTicks=0:this.idlePollTicks++;let r=this.idlePollTicks>=3?n.POLL_IDLE_MS:n.POLL_ACTIVE_MS;e(r)},t)};e(n.POLL_ACTIVE_MS)}setActivity(e,t="working"){this.currentActivity={section:t,task:e.slice(0,120)},this.beat(t,this.currentActivity.task)}async beat(e,t){await this.sendHeartbeat(e??this.currentActivity.section,t??this.currentActivity.task)?(this.announcedOffline&&(console.log(`
316
- ${c.success("\u2713")} ${c.muted("[Team]")} Cloud sync reconnected \u2014 session restored.
317
- `),this.announcedOffline=!1),this.consecutiveHeartbeatFailures=0):(this.consecutiveHeartbeatFailures++,this.consecutiveHeartbeatFailures>=4&&!this.announcedOffline&&(console.log(`
318
- ${c.warning("\u26A0")} ${c.muted("[Team]")} Cloud sync is unreachable \u2014 retrying in the background. Your session is preserved.
319
- `),this.announcedOffline=!0))}async syncWithCloud(){let e=await this.apiRequest(`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}`,"GET");if(!e.ok)return!1;let t=e.data||[],s=await this.fetchLocks(),r=await this.fetchUnreadMessages();for(let u of r)this.renderMessageBox(u.sender_name,u.message_content);let i=Date.now(),o=t.filter(u=>{if(u.developer_name===this.username)return!0;let d=new Date(u.last_heartbeat).getTime();return i-d<=n.STALE_MS}),a=this.getLocalState(),l=r.length>0||JSON.stringify(a.sessions?.map(u=>u.developer_name).sort())!==JSON.stringify(o.map(u=>u.developer_name).sort())||JSON.stringify(a.locks?.map(u=>`${u.file_path}:${u.locked_by}`).sort())!==JSON.stringify(s.map(u=>`${u.file_path}:${u.locked_by}`).sort());return this.saveLocalState(o,s),l}startWatcher(){this.watcher=Yf.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(`
320
- ${c.success("\u{1F514}")} ${c.muted("[Live Sync]")} ${c.strong(`@${i.developer_name}`)} has joined the session.
321
- `);else{let o=this.knownSessions.get(i.developer_name);i.current_task&&i.current_task!==o&&i.current_task!=="none"&&(this.knownSessions.set(i.developer_name,i.current_task),console.log(` ${c.accent("\u27F3")} ${c.muted("[Activity]")} ${c.strong(`@${i.developer_name}`)} is now: "${c.secondary(i.current_task)}"
322
- `))}for(let i of this.knownSessions.keys())s.has(i)||(this.knownSessions.delete(i),console.log(`
323
- ${c.warning("\u{1F44B}")} ${c.muted("[Live Sync]")} ${c.strong(`@${i}`)} has left the session.
324
- `));let r=new Set;for(let i of t)r.add(i.file_path),this.knownLocks.has(i.file_path)||(this.knownLocks.set(i.file_path,i.locked_by),i.locked_by!==this.username&&console.log(` ${c.error("\u{1F512}")} ${c.muted("[File Locked]")} ${c.strong(`@${i.locked_by}`)} locked ${c.highlight(i.file_path)}`));for(let i of this.knownLocks.keys())if(!r.has(i)){let o=this.knownLocks.get(i);this.knownLocks.delete(i),o!==this.username&&console.log(` ${c.success("\u{1F513}")} ${c.muted("[File Unlocked]")} ${c.strong(`@${o}`)} released lock on ${c.highlight(i)}`)}}renderMessageBox(e,t){let s=Math.min(process.stdout.columns-4,80),r=c.border("\u250C"+"\u2500".repeat(s-2)+"\u2510"),i=c.border("\u2514"+"\u2500".repeat(s-2)+"\u2518"),o=` MESSAGE FROM @${e.toUpperCase()} `,a=Math.max(0,Math.floor((s-2-o.length)/2)),l=c.border("\u2502")+" ".repeat(a)+c.strong(o)+" ".repeat(s-2-o.length-a)+c.border("\u2502"),u=t.replace(/\n/g," "),d=Math.max(0,s-8-u.length),f=c.border("\u2502")+` "${c.secondary(u)}"`+" ".repeat(d)+c.border("\u2502");console.log(`
325
- `+r),console.log(l),console.log(f),console.log(i+`
326
- `)}registerCleanups(){this.signalHandler||(this.signalHandler=()=>{this.shutdown()},process.on("SIGTERM",this.signalHandler),process.once("beforeExit",this.signalHandler))}loadSupabaseConfig(){let e=Ge.join(this.workingDir,".env");if(ye.existsSync(e))try{let s=ye.readFileSync(e,"utf-8").split(`
327
- `);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=Ge.join(wr.homedir(),".hablas","config.json");if(ye.existsSync(e))try{let t=JSON.parse(ye.readFileSync(e,"utf-8"));!this.config.apiUrl&&t.apiUrl&&(this.config.apiUrl=t.apiUrl,this.config.apiKey=t.apiKey,this.config.provider=t.provider)}catch{}}getProjectIdentifier(){let e="";try{let{execSync:t}=require("child_process"),s=t("git config --get remote.origin.url",{cwd:this.workingDir,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(s){let r=s.match(/[:/]([^/]+\/[^/.]+)(\.git)?$/);r&&r[1]&&(e=r[1].toLowerCase())}}catch{}if(!e)try{let t=Ge.join(this.workingDir,"package.json");if(ye.existsSync(t)){let s=JSON.parse(ye.readFileSync(t,"utf-8"));s.name&&(e=s.name.toLowerCase())}}catch{}return e||(e=Ge.basename(this.workingDir).toLowerCase()),e.replace(/\s+/g,"")}}});async function tn(n){try{if(!ma.existsSync(n))return;ma.existsSync(fs)||await mt.mkdir(fs,{recursive:!0});let e=await mt.readFile(n,"utf-8"),t=kn.basename(n),s=Date.now(),r=`${t}.${s}.bak`,i=kn.join(fs,r);await mt.writeFile(i,e,"utf-8");let a=(await mt.readdir(fs)).filter(l=>l.startsWith(`${t}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Qf)for(let l of a.slice(Qf))await mt.unlink(kn.join(fs,l))}catch{}}var mt,ma,kn,Zf,fs,Qf,ep=L(()=>{"use strict";mt=O(require("fs/promises")),ma=O(require("fs")),kn=O(require("path")),Zf=O(require("os")),fs=kn.join(Zf.homedir(),".hablas","backup"),Qf=10});function np(n){let e=m=>Ht.resolve(n,m);return[{name:"read_file",description:"Read the FULL content of a file with line numbers (complete read, no truncation by default per user requirement for 1000/2000+ line files like architecture docs). Use start_line/end_line ONLY if you explicitly need a specific section. Never re-read the same path this turn \u2014 use previous tool observations from history.",safety:"safe",parameters:{path:{type:"string",description:"File path to read",required:!0},start_line:{type:"number",description:"Starting line number (1-based, optional)",required:!1},end_line:{type:"number",description:"Ending line number (inclusive, optional)",required:!1}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[read_file]: path is required"};let p=e(m.path),S=(await le.readFile(p,"utf-8")).split(`
328
- `),x=S.length,$=m.start_line?Math.max(1,m.start_line):1,k=m.end_line?Math.min(x,m.end_line):x,y=S.slice($-1,k),b=String(k).length,v=y.map((T,P)=>`${String($+P).padStart(b," ")} | ${T}`),w=`[${m.path} \u2014 lines ${$}-${k} of ${x}]`,_=k<x?`
329
- ... [Partial read. Total lines: ${x}.]`:"";return{success:!0,output:`${w}
330
- ${v.join(`
331
- `)}${_}`}}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 ga.existsSync(p)&&await tn(p),await le.mkdir(Ht.dirname(p),{recursive:!0}),await le.writeFile(p,m.content,"utf-8"),{success:!0,output:`Written: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[write_file]: ${p.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!m.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let p=e(m.path),g=await le.readFile(p,"utf-8"),S=m.old_content,x=m.new_content,$=tp(g,S);if($===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if($>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${$} locations in the file. Provide more surrounding context to be specific.`};await tn(p);let k=g.replace(S,x);await le.writeFile(p,k,"utf-8");let y=er(m.path,g,k);return{success:!0,output:`Edited: ${m.path}
332
- ${y}`}}catch(p){return{success:!1,output:"",error:`[edit_file]: ${p.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!m.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!m.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(m.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let p=e(m.path),g=await le.readFile(p,"utf-8"),S=g.split(`
333
- `),x=S.length,$=m.start_line,k=m.end_line;if($<1||$>x)return{success:!1,output:"",error:`[patch_file]: start_line ${$} is out of range (file has ${x} lines)`};if(k<$||k>x)return{success:!1,output:"",error:`[patch_file]: end_line ${k} is out of range (start_line=${$}, total=${x})`};await tn(p);let y=S.slice(0,$-1),b=S.slice(k),v=m.new_content.split(`
334
- `),w=[...y,...v,...b].join(`
335
- `);await le.writeFile(p,w,"utf-8");let _=er(m.path,g,w),T=k-$+1,P=v.length;return{success:!0,output:`Patched: ${m.path} (replaced ${T} lines with ${P})
336
- ${_}`}}catch(p){return{success:!1,output:"",error:`[patch_file]: ${p.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!m.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(m.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let p=e(m.path),g=await le.readFile(p,"utf-8"),S=m.search,x=m.replace,$=m.is_regex;await tn(p);let k,y;if($){let b=new RegExp(S,"g");y=(g.match(b)||[]).length,k=g.replace(b,x)}else y=tp(g,S),k=g.split(S).join(x);return y===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await le.writeFile(p,k,"utf-8"),{success:!0,output:`Replaced ${y} occurrence(s) in ${m.path}`})}catch(p){return{success:!1,output:"",error:`[search_and_replace]: ${p.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(m.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let p=e(m.path);return await le.mkdir(Ht.dirname(p),{recursive:!0}),ga.existsSync(p)&&await tn(p),await le.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 tn(p),await le.unlink(p),{success:!0,output:`Deleted: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[delete_file]: ${p.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async m=>{try{if(!m.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!m.to)return{success:!1,output:"",error:"[move_file]: to is required"};let p=e(m.from),g=e(m.to);return await le.mkdir(Ht.dirname(g),{recursive:!0}),await le.rename(p,g),{success:!0,output:`Moved: ${m.from} \u2192 ${m.to}`}}catch(p){return{success:!1,output:"",error:`[move_file]: ${p.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let p=e(m.path);return await le.mkdir(p,{recursive:!0}),{success:!0,output:`Created directory: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[create_dir]: ${p.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async m=>{try{let p=e(m.path||"."),g=m.depth||3;return{success:!0,output:await sp(p,"",g,0)||"(empty directory)"}}catch(p){return{success:!1,output:"",error:`[list_dir]: ${p.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let p=e(m.path),g=await le.stat(p);return{success:!0,output:[`Path: ${m.path}`,`Size: ${Hx(g.size)}`,`Type: ${g.isDirectory()?"directory":"file"}`,`Modified: ${g.mtime.toISOString()}`,`Created: ${g.birthtime.toISOString()}`].join(`
337
- `)}}catch(p){return{success:!1,output:"",error:`[get_file_info]: ${p.message}`}}}}]}function tp(n,e){let t=0,s=0;for(;;){let r=n.indexOf(e,s);if(r===-1)break;t++,s=r+e.length}return t}async function sp(n,e,t,s){if(s>=t)return"";let i=(await le.readdir(n,{withFileTypes:!0})).filter(a=>!jx.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],u=a===i.length-1,d=u?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${d}${f} ${l.name}
338
- `,l.isDirectory()){let h=e+(u?" ":"\u2502 ");o+=await sp(Ht.join(n,l.name),h,t,s+1)}}return o}function Hx(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var le,ga,Ht,jx,rp=L(()=>{"use strict";le=O(require("fs/promises")),ga=O(require("fs")),Ht=O(require("path"));po();ep();jx=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"])});var ip,xr,op=L(()=>{"use strict";ip=require("child_process"),xr=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,t){let s=`bg_${this.nextId++}`,r=t?.timeout||this.config.defaultTimeout,i=(0,ip.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...t?.env}}),o={id:s,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
339
- Error: ${a.message}`}),r>0&&setTimeout(()=>{o.status==="running"&&(this.kill(s),o.status="timeout",o.stderr+=`
340
- 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+=`
341
- `),i+=s.stderr),t?.lastLines&&(i=i.split(`
342
- `).slice(-t.lastLines).join(`
343
- `)),{success:!0,output:i,status:s.status}}kill(e){let t=this.processes.get(e);if(!t)return!1;if(t.process.pid)try{process.kill(-t.process.pid,"SIGTERM")}catch{try{process.kill(t.process.pid,"SIGTERM")}catch{}}return t.status="killed",!0}killAll(){let e=0;for(let t of this.processes.keys())this.kill(t)&&e++;return e}listProcesses(){let e=[];for(let[t,s]of this.processes){let r=Date.now()-s.startTime,i=this.formatUptime(r);e.push({id:t,command:s.command,status:s.status,pid:s.pid,startTime:s.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[t,s]of this.processes)(s.status==="finished"||s.status==="killed"||s.status==="timeout")&&(this.processes.delete(t),e++);return e}formatUptime(e){let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let s=Math.floor(t/60);return s<60?`${s}m ${t%60}s`:`${Math.floor(s/60)}h ${s%60}m`}}});function ap(n){return ya||(ya=new xr({workingDir:n})),ya}function cp(n,e){return{name:"run_command",description:"Execute any shell command and return output. Set run_in_background=true for long-running processes (servers, watchers). Use bash_output to read output later.",safety:"confirm",parameters:{command:{type:"string",description:"Shell command to execute",required:!0},run_in_background:{type:"boolean",description:"Run in background for long processes (default: false)",required:!1},timeout:{type:"number",description:"Timeout in ms (default: 120000)",required:!1}},execute:async t=>{let s=t.command,r=t.run_in_background===!0,i=t.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...Bx,...o];if(a.length>0){for(let l of a)if(s.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(r){let l=ap(n).start(s,{timeout:i});return{success:!0,output:`Background process started: ${l}
344
- PID: ${ap(n).getProcess(l)?.pid}
345
- Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let u=(0,lp.exec)(s,{cwd:n,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",h=>{d+=h}),u.stderr?.on("data",h=>{f+=h}),u.on("close",h=>{l(h===0?{success:!0,output:d||"(no output)"}:{success:!1,output:d,error:f||`Exit code: ${h}`})}),u.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var lp,Bx,ya,up=L(()=>{"use strict";lp=require("child_process");op();Bx=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],ya=null});function dp(n){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let t=e.query,s=Bt.resolve(n,e.path||"."),r=new RegExp(t,"gi"),i=[];if(await fp(s,r,i,n),i.length===0)return{success:!0,output:`No matches found for: "${t}"`};let o=i.slice(0,50).join(`
53
+ `}function nh(t,e,r,n,s,i,o){return bo(rh(t,e,r,n,s,i,o))}function So(t,e,r,n,s,i){return nh(t,t,e,r,n,s,i)}function _n(t,e,r){return So(t,e,r,"original","modified")}var te=k(require("fs/promises")),xn=k(require("fs")),je=k(require("path")),xo=k(require("os")),at=je.join(xo.homedir(),".hablas","backup"),_o=10;async function _e(t){try{if(!xn.existsSync(t))return;xn.existsSync(at)||await te.mkdir(at,{recursive:!0});let e=await te.readFile(t,"utf-8"),r=je.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=je.join(at,s);await te.writeFile(i,e,"utf-8");let a=(await te.readdir(at)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>_o)for(let l of a.slice(_o))await te.unlink(je.join(at,l))}catch{}}function ko(t){let e=h=>ue.resolve(t,h);return[{name:"read_file",description:"Read the FULL content of a file with line numbers (complete read, no truncation by default per user requirement for 1000/2000+ line files like architecture docs). Use start_line/end_line ONLY if you explicitly need a specific section. Never re-read the same path this turn \u2014 use previous tool observations from history.",safety:"safe",parameters:{path:{type:"string",description:"File path to read",required:!0},start_line:{type:"number",description:"Starting line number (1-based, optional)",required:!1},end_line:{type:"number",description:"Ending line number (inclusive, optional)",required:!1}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[read_file]: path is required"};let c=e(h.path),y=(await D.readFile(c,"utf-8")).split(`
54
+ `),w=y.length,b=h.start_line?Math.max(1,h.start_line):1,_=h.end_line?Math.min(w,h.end_line):w,S=y.slice(b-1,_),v=String(_).length,$=S.map((C,I)=>`${String(b+I).padStart(v," ")} | ${C}`),T=`[${h.path} \u2014 lines ${b}-${_} of ${w}]`,O=_<w?`
55
+ ... [Partial read. Total lines: ${w}.]`:"";return{success:!0,output:`${T}
56
+ ${$.join(`
57
+ `)}${O}`}}catch(c){return{success:!1,output:"",error:`[read_file]: ${c.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 c=e(h.path);return vn.existsSync(c)&&await _e(c),await D.mkdir(ue.dirname(c),{recursive:!0}),await D.writeFile(c,h.content,"utf-8"),{success:!0,output:`Written: ${h.path}`}}catch(c){return{success:!1,output:"",error:`[write_file]: ${c.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async 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 c=e(h.path),m=await D.readFile(c,"utf-8"),y=h.old_content,w=h.new_content,b=vo(m,y);if(b===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(b>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${b} locations in the file. Provide more surrounding context to be specific.`};await _e(c);let _=m.replace(y,w);await D.writeFile(c,_,"utf-8");let S=_n(h.path,m,_);return{success:!0,output:`Edited: ${h.path}
58
+ ${S}`}}catch(c){return{success:!1,output:"",error:`[edit_file]: ${c.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 c=e(h.path),m=await D.readFile(c,"utf-8"),y=m.split(`
59
+ `),w=y.length,b=h.start_line,_=h.end_line;if(b<1||b>w)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${w} lines)`};if(_<b||_>w)return{success:!1,output:"",error:`[patch_file]: end_line ${_} is out of range (start_line=${b}, total=${w})`};await _e(c);let S=y.slice(0,b-1),v=y.slice(_),$=h.new_content.split(`
60
+ `),T=[...S,...$,...v].join(`
61
+ `);await D.writeFile(c,T,"utf-8");let O=_n(h.path,m,T),C=_-b+1,I=$.length;return{success:!0,output:`Patched: ${h.path} (replaced ${C} lines with ${I})
62
+ ${O}`}}catch(c){return{success:!1,output:"",error:`[patch_file]: ${c.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 c=e(h.path),m=await D.readFile(c,"utf-8"),y=h.search,w=h.replace,b=h.is_regex;await _e(c);let _,S;if(b){let v=new RegExp(y,"g");S=(m.match(v)||[]).length,_=m.replace(v,w)}else S=vo(m,y),_=m.split(y).join(w);return S===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await D.writeFile(c,_,"utf-8"),{success:!0,output:`Replaced ${S} occurrence(s) in ${h.path}`})}catch(c){return{success:!1,output:"",error:`[search_and_replace]: ${c.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 c=e(h.path);return await D.mkdir(ue.dirname(c),{recursive:!0}),vn.existsSync(c)&&await _e(c),await D.appendFile(c,h.content,"utf-8"),{success:!0,output:`Appended to: ${h.path}`}}catch(c){return{success:!1,output:"",error:`[append_to_file]: ${c.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 c=e(h.path);return await _e(c),await D.unlink(c),{success:!0,output:`Deleted: ${h.path}`}}catch(c){return{success:!1,output:"",error:`[delete_file]: ${c.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 c=e(h.from),m=e(h.to);return await D.mkdir(ue.dirname(m),{recursive:!0}),await D.rename(c,m),{success:!0,output:`Moved: ${h.from} \u2192 ${h.to}`}}catch(c){return{success:!1,output:"",error:`[move_file]: ${c.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 c=e(h.path);return await D.mkdir(c,{recursive:!0}),{success:!0,output:`Created directory: ${h.path}`}}catch(c){return{success:!1,output:"",error:`[create_dir]: ${c.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 c=e(h.path||"."),m=h.depth||3;return{success:!0,output:await Co(c,"",m,0)||"(empty directory)"}}catch(c){return{success:!1,output:"",error:`[list_dir]: ${c.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 c=e(h.path),m=await D.stat(c);return{success:!0,output:[`Path: ${h.path}`,`Size: ${ih(m.size)}`,`Type: ${m.isDirectory()?"directory":"file"}`,`Modified: ${m.mtime.toISOString()}`,`Created: ${m.birthtime.toISOString()}`].join(`
63
+ `)}}catch(c){return{success:!1,output:"",error:`[get_file_info]: ${c.message}`}}}}]}function vo(t,e){let r=0,n=0;for(;;){let s=t.indexOf(e,n);if(s===-1)break;r++,n=s+e.length}return r}var sh=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Co(t,e,r,n){if(n>=r)return"";let i=(await D.readdir(t,{withFileTypes:!0})).filter(a=>!sh.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],u=a===i.length-1,d=u?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${d}${f} ${l.name}
64
+ `,l.isDirectory()){let p=e+(u?" ":"\u2502 ");o+=await Co(ue.join(t,l.name),p,r,n+1)}}return o}function ih(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Eo=require("child_process");var To=require("child_process"),Lt=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,r){let n=`bg_${this.nextId++}`,s=r?.timeout||this.config.defaultTimeout,i=(0,To.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...r?.env}}),o={id:n,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+=`
65
+ Error: ${a.message}`}),s>0&&setTimeout(()=>{o.status==="running"&&(this.kill(n),o.status="timeout",o.stderr+=`
66
+ Process timed out after ${s}ms`)},s),this.processes.set(n,o),n}readOutput(e,r){let n=this.processes.get(e);if(!n)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let s=r?.type||"both",i="";return(s==="stdout"||s==="both")&&(i+=n.stdout),(s==="stderr"||s==="both")&&(i&&(i+=`
67
+ `),i+=n.stderr),r?.lastLines&&(i=i.split(`
68
+ `).slice(-r.lastLines).join(`
69
+ `)),{success:!0,output:i,status:n.status}}kill(e){let r=this.processes.get(e);if(!r)return!1;if(r.process.pid)try{process.kill(-r.process.pid,"SIGTERM")}catch{try{process.kill(r.process.pid,"SIGTERM")}catch{}}return r.status="killed",!0}killAll(){let e=0;for(let r of this.processes.keys())this.kill(r)&&e++;return e}listProcesses(){let e=[];for(let[r,n]of this.processes){let s=Date.now()-n.startTime,i=this.formatUptime(s);e.push({id:r,command:n.command,status:n.status,pid:n.pid,startTime:n.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[r,n]of this.processes)(n.status==="finished"||n.status==="killed"||n.status==="timeout")&&(this.processes.delete(r),e++);return e}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let n=Math.floor(r/60);return n<60?`${n}m ${r%60}s`:`${Math.floor(n/60)}h ${n%60}m`}};var oh=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],kn=null;function Ao(t){return kn||(kn=new Lt({workingDir:t})),kn}function Oo(t,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 r=>{let n=r.command,s=r.run_in_background===!0,i=r.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...oh,...o];if(a.length>0){for(let l of a)if(n.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(s){let l=Ao(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
70
+ PID: ${Ao(t).getProcess(l)?.pid}
71
+ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let u=(0,Eo.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",p=>{d+=p}),u.stderr?.on("data",p=>{f+=p}),u.on("close",p=>{l(p===0?{success:!0,output:d||"(no output)"}:{success:!1,output:d,error:f||`Exit code: ${p}`})}),u.on("error",p=>{l({success:!1,output:"",error:p.message})})})}}}var jt=k(require("fs/promises")),fe=k(require("path")),ah=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),lh=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function $o(t){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 r=e.query,n=fe.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await Ro(n,s,i,t),i.length===0)return{success:!0,output:`No matches found for: "${r}"`};let o=i.slice(0,50).join(`
346
72
  `),a=i.length>50?`
347
- ... and ${i.length-50} more matches`:"";return{success:!0,output:o+a}}catch(t){return{success:!1,output:"",error:`Search failed: ${t.message}`}}}}}async function fp(n,e,t,s){let r=await Sr.readdir(n,{withFileTypes:!0});for(let i of r){if(Ux.has(i.name)||i.name.startsWith("."))continue;let o=Bt.join(n,i.name);if(i.isDirectory())await fp(o,e,t,s);else if(qx.has(Bt.extname(i.name)))try{let l=(await Sr.readFile(o,"utf-8")).split(`
348
- `),u=Bt.relative(s,o);for(let d=0;d<l.length;d++)e.test(l[d])&&(t.push(`${u}:${d+1}: ${l[d].trim()}`),e.lastIndex=0)}catch{}}}var Sr,Bt,Ux,qx,pp=L(()=>{"use strict";Sr=O(require("fs/promises")),Bt=O(require("path")),Ux=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),qx=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"])});function Kx(n){let e=[],t=Ut.join(n,"tsconfig.json");if(!Ve.existsSync(t))return e;try{(0,ba.execSync)("npx tsc --noEmit 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(s){let r=s,o=(r.stdout||r.message||"").split(`
349
- `);for(let a of o){let l=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);l&&e.push({file:l[1],line:parseInt(l[2],10),severity:l[3]==="error"?"error":"warning",message:l[4].trim(),source:"typescript"})}}return e}function Wx(n){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(s=>Ve.existsSync(Ut.join(n,s))))return e;try{(0,ba.execSync)("npx eslint . --format json 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(s){let i=s.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:Ut.relative(n,a.filePath),line:l.line||0,severity:l.severity===2?"error":"warning",message:`${l.message} (${l.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
350
- `);for(let a of o){let l=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);l&&e.push({file:"unknown",line:parseInt(l[1],10),severity:l[3]==="error"?"error":"warning",message:`${l[4]} (${l[5]})`,source:"eslint"})}}}return e}function Gx(n,e,t){let s;try{s=Ve.readFileSync(n,"utf-8")}catch{return}let r=Ut.relative(e,n),i=s.split(`
351
- `);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&t.push({file:r,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&t.push({file:r,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&t.push({file:r,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&t.push({file:r,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function Vx(n){let e=[],t=[".ts",".tsx",".js",".jsx"];function s(r,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=Ve.readdirSync(r)}catch{return}for(let l of a){if(o.includes(l))continue;let u=Ut.join(r,l),d;try{d=Ve.statSync(u)}catch{continue}d.isDirectory()?s(u,i+1):t.some(f=>l.endsWith(f))&&Gx(u,n,e)}}return s(n),e.slice(0,20)}function zx(n){let e=[];e.push(...Kx(n)),e.push(...Wx(n)),e.push(...Vx(n));let t={error:0,warning:1,info:2};return e.sort((s,r)=>t[s.severity]-t[r.severity]),e}function hp(n){if(n.length===0)return" \u2713 No bugs detected";let e=[],t=n.filter(i=>i.severity==="error").length,s=n.filter(i=>i.severity==="warning").length,r=n.filter(i=>i.severity==="info").length;e.push(` Found ${n.length} issue${n.length>1?"s":""}: ${t} errors, ${s} warnings, ${r} info`),e.push("");for(let i of n.slice(0,15)){let o=i.severity==="error"?"\u2717":i.severity==="warning"?"\u26A0":"\u2139",a=i.line>0?`:${i.line}`:"";e.push(` ${o} ${i.file}${a}`),e.push(` ${i.message}`),i.suggestedFix&&e.push(` \u2192 ${i.suggestedFix}`)}return n.length>15&&e.push(` ... and ${n.length-15} more`),e.join(`
352
- `)}function Yx(n,e){let t=[];for(let s of n)if(s.source==="pattern"&&s.message.includes("console.log")){let r=Ut.join(e,s.file);try{let o=Ve.readFileSync(r,"utf-8").split(`
353
- `);s.line>0&&s.line<=o.length&&(o[s.line-1]="// "+o[s.line-1],Ve.writeFileSync(r,o.join(`
354
- `),"utf-8"),t.push({bug:s,fixed:!0,action:"Commented out console.log"}))}catch{t.push({bug:s,fixed:!1,action:"Failed to read/write file"})}}else t.push({bug:s,fixed:!1,action:"Requires manual fix or LLM assistance"});return t}function mp(n){return{name:"detect_bugs",description:"Scan the project for bugs using TypeScript checking, ESLint, and pattern analysis. Returns a report of found issues.",safety:"safe",parameters:{path:{type:"string",description:"Project path to scan (default: current directory)",required:!1},fix:{type:"string",description:'Set to "true" to auto-fix simple issues',required:!1}},execute:async e=>{let t=e.path||n,s=e.fix==="true"||e.fix===!0;try{let r=zx(t);if(s&&r.length>0){let o=Yx(r,t).filter(l=>l.fixed).length;return{success:!0,output:`${hp(r)}
355
-
356
- Auto-fixed: ${o}/${r.length} issues`}}return{success:!0,output:hp(r)}}catch(r){return{success:!1,output:"",error:`Bug detection failed: ${r instanceof Error?r.message:String(r)}`}}}}}var ba,Ve,Ut,gp=L(()=>{"use strict";ba=require("child_process"),Ve=O(require("fs")),Ut=O(require("path"))});function Xx(n){let e=n;return e=e.replace(/<(script|style|nav|footer|header|aside|iframe|noscript)[^>]*>[\s\S]*?<\/\1>/gi,""),e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/<\/(p|div|section|article|li|tr|h[1-6])>/gi,`
73
+ ... and ${i.length-50} more matches`:"";return{success:!0,output:o+a}}catch(r){return{success:!1,output:"",error:`Search failed: ${r.message}`}}}}}async function Ro(t,e,r,n){let s=await jt.readdir(t,{withFileTypes:!0});for(let i of s){if(ah.has(i.name)||i.name.startsWith("."))continue;let o=fe.join(t,i.name);if(i.isDirectory())await Ro(o,e,r,n);else if(lh.has(fe.extname(i.name)))try{let l=(await jt.readFile(o,"utf-8")).split(`
74
+ `),u=fe.relative(n,o);for(let d=0;d<l.length;d++)e.test(l[d])&&(r.push(`${u}:${d+1}: ${l[d].trim()}`),e.lastIndex=0)}catch{}}}var Cn=require("child_process"),J=k(require("fs")),de=k(require("path"));function ch(t){let e=[],r=de.join(t,"tsconfig.json");if(!J.existsSync(r))return e;try{(0,Cn.execSync)("npx tsc --noEmit 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let s=n,o=(s.stdout||s.message||"").split(`
75
+ `);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 uh(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>J.existsSync(de.join(t,n))))return e;try{(0,Cn.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let i=n.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:de.relative(t,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(`
76
+ `);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 fh(t,e,r){let n;try{n=J.readFileSync(t,"utf-8")}catch{return}let s=de.relative(e,t),i=n.split(`
77
+ `);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])&&r.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)&&r.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)&&r.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("//")&&r.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 dh(t){let e=[],r=[".ts",".tsx",".js",".jsx"];function n(s,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=J.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let u=de.join(s,l),d;try{d=J.statSync(u)}catch{continue}d.isDirectory()?n(u,i+1):r.some(f=>l.endsWith(f))&&fh(u,t,e)}}return n(t),e.slice(0,20)}function hh(t){let e=[];e.push(...ch(t)),e.push(...uh(t)),e.push(...dh(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function Io(t){if(t.length===0)return" \u2713 No bugs detected";let e=[],r=t.filter(i=>i.severity==="error").length,n=t.filter(i=>i.severity==="warning").length,s=t.filter(i=>i.severity==="info").length;e.push(` Found ${t.length} issue${t.length>1?"s":""}: ${r} errors, ${n} warnings, ${s} info`),e.push("");for(let i of t.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 t.length>15&&e.push(` ... and ${t.length-15} more`),e.join(`
78
+ `)}function ph(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=de.join(e,n.file);try{let o=J.readFileSync(s,"utf-8").split(`
79
+ `);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],J.writeFileSync(s,o.join(`
80
+ `),"utf-8"),r.push({bug:n,fixed:!0,action:"Commented out console.log"}))}catch{r.push({bug:n,fixed:!1,action:"Failed to read/write file"})}}else r.push({bug:n,fixed:!1,action:"Requires manual fix or LLM assistance"});return r}function Po(t){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 r=e.path||t,n=e.fix==="true"||e.fix===!0;try{let s=hh(r);if(n&&s.length>0){let o=ph(s,r).filter(l=>l.fixed).length;return{success:!0,output:`${Io(s)}
81
+
82
+ Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:Io(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Fo=2*1024*1024,Mo=15e3,Do=32e3,mh="HablasBot/2.0 (+https://hablas.dev)";function gh(t){let e=t;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,`
357
83
  `),e=e.replace(/<(br|hr)\s*\/?>/gi,`
358
84
  `),e=e.replace(/<\/?(ul|ol)>/gi,`
359
- `),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(t,s,r)=>`
360
- ${"#".repeat(parseInt(s))} ${r.replace(/<[^>]+>/g,"").trim()}
361
- `),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,`
85
+ `),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(r,n,s)=>`
86
+ ${"#".repeat(parseInt(n))} ${s.replace(/<[^>]+>/g,"").trim()}
87
+ `),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(r,n,s)=>{let i=s.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${n})`:n}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(r,n)=>"\n```\n"+n.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,(r,n)=>String.fromCharCode(parseInt(n))).replace(/&[a-z]+;/gi,""),e=e.replace(/[ \t]+/g," "),e=e.replace(/\n{3,}/g,`
362
88
 
363
- `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function Qx(n){let e=n.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let t=n.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return t?t[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function Zx(n,e){let t=[],s=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,r,i=new Set;for(;(r=s.exec(n))!==null;){let o=r[1].trim(),a=r[2].replace(/<[^>]+>/g,"").trim();if(!(o.startsWith("#")||o.startsWith("javascript:")||o.startsWith("mailto:"))){try{o=new URL(o,e).href}catch{continue}i.has(o)||(i.add(o),t.push({text:a||o,url:o}))}}return t}async function wp(n){let e=new AbortController,t=setTimeout(()=>e.abort(),bp);try{let s=await fetch(n,{signal:e.signal,headers:{"User-Agent":Jx,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(t),!s.ok)return{html:"",finalUrl:s.url||n,status:s.status};let r=s.headers.get("content-type")||"";if(!r.includes("text/")&&!r.includes("application/xhtml")&&!r.includes("application/json"))return{html:`[Binary content: ${r}]`,finalUrl:s.url||n,status:s.status};let i=s.body?.getReader();if(!i)return{html:"",finalUrl:s.url||n,status:s.status};let o=[],a=0;for(;a<yp;){let{done:d,value:f}=await i.read();if(d)break;o.push(f),a+=f.length}if(a>=yp)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(d=>l.decode(d,{stream:!0})).join("")+l.decode(),finalUrl:s.url||n,status:s.status}}catch(s){clearTimeout(t);let r=s instanceof Error?s:new Error(String(s));throw r.name==="AbortError"?new Error(`Timeout after ${bp/1e3}s`):r}}function xp(){return[{name:"scrape_url",description:"Fetch a web page and extract its readable text content. Returns clean text/markdown without HTML tags. Use this to read documentation, articles, blog posts, or any web page.",safety:"safe",parameters:{url:{type:"string",description:"The URL to scrape (must start with http:// or https://)",required:!0}},execute:async n=>{let e=n.url;if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:t,finalUrl:s,status:r}=await wp(e);if(!t||r>=400)return{success:!1,output:"",error:`HTTP ${r} \u2014 could not fetch ${e}`};let i=Qx(t),o=Xx(t);return o.length>vp&&(o=o.slice(0,vp)+`
89
+ `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function yh(t){let e=t.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let r=t.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return r?r[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function wh(t,e){let r=[],n=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,s,i=new Set;for(;(s=n.exec(t))!==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),r.push({text:a||o,url:o}))}}return r}async function Lo(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Mo);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":mh,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(r),!n.ok)return{html:"",finalUrl:n.url||t,status:n.status};let s=n.headers.get("content-type")||"";if(!s.includes("text/")&&!s.includes("application/xhtml")&&!s.includes("application/json"))return{html:`[Binary content: ${s}]`,finalUrl:n.url||t,status:n.status};let i=n.body?.getReader();if(!i)return{html:"",finalUrl:n.url||t,status:n.status};let o=[],a=0;for(;a<Fo;){let{done:d,value:f}=await i.read();if(d)break;o.push(f),a+=f.length}if(a>=Fo)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:n.url||t,status:n.status}}catch(n){clearTimeout(r);let s=n instanceof Error?n:new Error(String(n));throw s.name==="AbortError"?new Error(`Timeout after ${Mo/1e3}s`):s}}function jo(){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 t=>{let e=t.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:r,finalUrl:n,status:s}=await Lo(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=yh(r),o=gh(r);return o.length>Do&&(o=o.slice(0,Do)+`
364
90
 
365
- [... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${s}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
366
- `)}}catch(t){let s=t instanceof Error?t.message:String(t);return{success:!1,output:"",error:`Failed to scrape ${e}: ${s}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async n=>{let e=n.url,t=n.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:s,finalUrl:r,status:i}=await wp(e);if(!s||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Zx(s,r);if(t&&(o=o.filter(l=>l.url.toLowerCase().includes(t)||l.text.toLowerCase().includes(t))),o.length===0)return{success:!0,output:"No links found"+(t?` matching "${t}"`:"")};let a=o.slice(0,100).map((l,u)=>`${u+1}. [${l.text}](${l.url})`).join(`
91
+ [... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${n}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
92
+ `)}}catch(r){let n=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to scrape ${e}: ${n}`}}}},{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 t=>{let e=t.url,r=t.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:n,finalUrl:s,status:i}=await Lo(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=wh(n,s);if(r&&(o=o.filter(l=>l.url.toLowerCase().includes(r)||l.text.toLowerCase().includes(r))),o.length===0)return{success:!0,output:"No links found"+(r?` matching "${r}"`:"")};let a=o.slice(0,100).map((l,u)=>`${u+1}. [${l.text}](${l.url})`).join(`
367
93
  `);return{success:!0,output:`Found ${o.length} links:
368
94
 
369
- ${a}`}}catch(s){let r=s instanceof Error?s.message:String(s);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${r}`}}}}]}var yp,bp,vp,Jx,Sp=L(()=>{"use strict";yp=2*1024*1024,bp=15e3,vp=32e3,Jx="HablasBot/2.0 (+https://hablas.dev)"});function tS(n){let e=$n.get(n.toLowerCase().trim());return e?Date.now()-e.timestamp>eS?($n.delete(n.toLowerCase().trim()),null):e.results:null}function nS(n,e){if($n.size>200){let t=$n.keys().next().value;t!==void 0&&$n.delete(t)}$n.set(n.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function sS(n,e){let t=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!t)return null;try{let s=new URLSearchParams({q:n,count:String(Math.min(e,10))}),r=await fetch(`https://api.search.brave.com/res/v1/web/search?${s}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":t},signal:AbortSignal.timeout(1e4)});return r.ok?((await r.json()).web?.results??[]).slice(0,e).map(a=>({title:a.title||"",url:a.url||"",snippet:a.description||"",source:"brave"})):null}catch{return null}}async function rS(n,e){try{let t=new URLSearchParams({q:n}),s=await fetch(`https://html.duckduckgo.com/html/?${t}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!s.ok)return null;let r=await s.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(r))!==null&&i.length<e;){let l=a[1],u=a[2].replace(/<[^>]+>/g,"").trim(),d=a[3].replace(/<[^>]+>/g,"").trim(),f=l.match(/uddg=([^&]+)/);if(f)try{l=decodeURIComponent(f[1])}catch{}u&&l&&!l.startsWith("/")&&i.push({title:u,url:l,snippet:d,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,u=new Set;for(;(a=l.exec(r))!==null&&i.length<e;){let d=a[1],f=a[2].replace(/<[^>]+>/g,"").trim();f&&f.length>5&&!u.has(d)&&!d.includes("duckduckgo.com")&&(u.add(d),i.push({title:f,url:d,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function iS(n,e=5){let t=tS(n);if(t)return t.slice(0,e);let s=[{name:"brave",fn:()=>sS(n,e)},{name:"duckduckgo",fn:()=>rS(n,e)}];for(let r of s)try{let i=await r.fn();if(i&&i.length>0)return nS(n,i),i}catch{}return[]}function _p(){return{name:"web_search",description:"Search the web for current information. Returns titles, URLs, and snippets from search results. Use this to find documentation, answers, latest versions, news, or any information not in your training data.",safety:"safe",parameters:{query:{type:"string",description:"The search query",required:!0},max_results:{type:"number",description:"Max results to return (default: 5, max: 10)",required:!1}},execute:async n=>{let e=n.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let t=Math.min(Math.max(1,n.max_results||5),10);try{let s=await iS(e.trim(),t);if(s.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let r=[`Search results for: "${e}" (${s.length} results, source: ${s[0].source})`,""];for(let i=0;i<s.length;i++){let o=s[i];r.push(`[${i+1}] ${o.title}`),r.push(` ${o.url}`),o.snippet&&r.push(` ${o.snippet}`),r.push("")}return{success:!0,output:r.join(`
370
- `)}}catch(s){return{success:!1,output:"",error:`Search failed: ${s instanceof Error?s.message:String(s)}`}}}}}var eS,$n,Ap=L(()=>{"use strict";eS=3600*1e3,$n=new Map});function Cp(n){let e=n.toString("latin1"),t={},s=[],r=0,i=e.match(/\/Type\s*\/Page\b/g);r=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(t.title=nn(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(t.author=nn(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(t.subject=nn(l[1]));let u=e.match(/\/Creator\s*\(([^)]*)\)/);u&&(t.creator=nn(u[1]));let d=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=d.exec(e))!==null;){let m=f[1],p=Ep(m);p.trim()&&s.push(p);try{let g=require("zlib"),S=Buffer.from(m,"latin1"),x=g.inflateSync(S).toString("latin1"),$=Ep(x);$.trim()&&!s.includes($)&&s.push($)}catch{}}return{text:s.join(`
95
+ ${a}`}}catch(n){let s=n instanceof Error?n.message:String(n);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${s}`}}}}]}var bh=3600*1e3,Ne=new Map;function Sh(t){let e=Ne.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>bh?(Ne.delete(t.toLowerCase().trim()),null):e.results:null}function _h(t,e){if(Ne.size>200){let r=Ne.keys().next().value;r!==void 0&&Ne.delete(r)}Ne.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function xh(t,e){let r=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!r)return null;try{let n=new URLSearchParams({q:t,count:String(Math.min(e,10))}),s=await fetch(`https://api.search.brave.com/res/v1/web/search?${n}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":r},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 vh(t,e){try{let r=new URLSearchParams({q:t}),n=await fetch(`https://html.duckduckgo.com/html/?${r}`,{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(!n.ok)return null;let s=await n.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],u=a[2].replace(/<[^>]+>/g,"").trim(),d=a[3].replace(/<[^>]+>/g,"").trim(),f=l.match(/uddg=([^&]+)/);if(f)try{l=decodeURIComponent(f[1])}catch{}u&&l&&!l.startsWith("/")&&i.push({title:u,url:l,snippet:d,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,u=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let d=a[1],f=a[2].replace(/<[^>]+>/g,"").trim();f&&f.length>5&&!u.has(d)&&!d.includes("duckduckgo.com")&&(u.add(d),i.push({title:f,url:d,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function kh(t,e=5){let r=Sh(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>xh(t,e)},{name:"duckduckgo",fn:()=>vh(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return _h(t,i),i}catch{}return[]}function No(){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 t=>{let e=t.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let r=Math.min(Math.max(1,t.max_results||5),10);try{let n=await kh(e.trim(),r);if(n.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let s=[`Search results for: "${e}" (${n.length} results, source: ${n[0].source})`,""];for(let i=0;i<n.length;i++){let o=n[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(`
96
+ `)}}catch(n){return{success:!1,output:"",error:`Search failed: ${n instanceof Error?n.message:String(n)}`}}}}}var oe=k(require("fs")),Wo=k(require("path")),qo=50*1024*1024,Uo=4e4;function Bo(t){let e=t.toString("latin1"),r={},n=[],s=0,i=e.match(/\/Type\s*\/Page\b/g);s=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(r.title=xe(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=xe(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=xe(l[1]));let u=e.match(/\/Creator\s*\(([^)]*)\)/);u&&(r.creator=xe(u[1]));let d=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=d.exec(e))!==null;){let h=f[1],c=Ho(h);c.trim()&&n.push(c);try{let m=require("zlib"),y=Buffer.from(h,"latin1"),w=m.inflateSync(y).toString("latin1"),b=Ho(w);b.trim()&&!n.includes(b)&&n.push(b)}catch{}}return{text:n.join(`
371
97
  `).replace(/\r\n/g,`
372
98
  `).replace(/\n{3,}/g,`
373
99
 
374
- `).trim(),pages:r,metadata:t}}function Ep(n){let e=[],t=/\(([^)]*)\)\s*Tj/g,s;for(;(s=t.exec(n))!==null;)e.push(nn(s[1]));let r=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(s=r.exec(n))!==null;){let l=s[1].match(/\(([^)]*)\)/g);if(l){let u=l.map(d=>nn(d.slice(1,-1))).join("");e.push(u)}}let i=/\(([^)]*)\)\s*'/g;for(;(s=i.exec(n))!==null;)e.push(nn(s[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
375
- `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function nn(n){return n.replace(/\\n/g,`
376
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(parseInt(t,8)))}function Rp(n){let e=t=>Tp.resolve(n,t);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async t=>{let s=e(t.path);if(!Pt.existsSync(s))return{success:!1,output:"",error:`File not found: ${t.path}`};if(!s.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${t.path}`};let r=Pt.statSync(s);if(r.size>kp)return{success:!1,output:"",error:`File too large: ${(r.size/1024/1024).toFixed(1)}MB (max: ${kp/1024/1024}MB)`};try{let i=Pt.readFileSync(s),{text:o,pages:a,metadata:l}=Cp(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${t.path} (${a} pages)
100
+ `).trim(),pages:s,metadata:r}}function Ho(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(xe(n[1]));let s=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(n=s.exec(t))!==null;){let l=n[1].match(/\(([^)]*)\)/g);if(l){let u=l.map(d=>xe(d.slice(1,-1))).join("");e.push(u)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(xe(n[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
101
+ `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function xe(t){return t.replace(/\\n/g,`
102
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,r)=>String.fromCharCode(parseInt(r,8)))}function Vo(t){let e=r=>Wo.resolve(t,r);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 r=>{let n=e(r.path);if(!oe.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};if(!n.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${r.path}`};let s=oe.statSync(n);if(s.size>qo)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${qo/1024/1024}MB)`};try{let i=oe.readFileSync(n),{text:o,pages:a,metadata:l}=Bo(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
377
103
 
378
- [No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let u=o;return u.length>$p&&(u=u.slice(0,$p)+`
104
+ [No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let u=o;return u.length>Uo&&(u=u.slice(0,Uo)+`
379
105
 
380
- [... 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(`
106
+ [... content truncated ...]`),{success:!0,output:`${[`PDF: ${r.path}`,`Pages: ${a}`,l.title?`Title: ${l.title}`:"",l.author?`Author: ${l.author}`:"",`Size: ${(s.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
381
107
  `)}
382
- ${u}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async t=>{let s=e(t.path);if(!Pt.existsSync(s))return{success:!1,output:"",error:`File not found: ${t.path}`};try{let r=Pt.statSync(s),i=Pt.readFileSync(s),{pages:o,metadata:a}=Cp(i);return{success:!0,output:[`File: ${t.path}`,`Size: ${(r.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${r.mtime.toISOString()}`].filter(Boolean).join(`
383
- `)}}catch(r){return{success:!1,output:"",error:`Failed to read PDF metadata: ${r instanceof Error?r.message:String(r)}`}}}}]}var Pt,Tp,kp,$p,Op=L(()=>{"use strict";Pt=O(require("fs")),Tp=O(require("path")),kp=50*1024*1024,$p=4e4});function Cn(n){try{let{execSync:e}=require("child_process");return e(`which ${n} 2>/dev/null || where ${n} 2>NUL`,{stdio:"ignore"}),!0}catch{return!1}}async function oS(n,e,t=Fp){let s=Mp[e];if(!s)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Mp).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=Dp.tmpdir(),i=Lp.join(r,`hablas_exec_${Date.now()}${s.extension}`);try{_r.writeFileSync(i,n,"utf-8");let o=s.command(i),a=Date.now();return await new Promise(l=>{let u=(0,Ip.exec)(o,{timeout:t,maxBuffer:5242880,cwd:r,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",h=>{d+=h}),u.stderr?.on("data",h=>{f+=h}),u.on("close",h=>{let m=Date.now()-a;l({success:h===0,stdout:d.slice(0,Pp),stderr:f.slice(0,Pp/2),exitCode:h??1,duration:m,language:e})}),u.on("error",h=>{let m=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:m,language:e})})})}finally{try{_r.unlinkSync(i)}catch{}}}function aS(n){return/\b(interface|type|enum|as\s+\w|:\s*(string|number|boolean|any)\b|<[A-Z]\w*>)/.test(n)?"typescript":/^(import\s+\w|from\s+\w|def\s+\w|class\s+\w|print\s*\(|if\s+__name__)/m.test(n)?"python":/^(#!\/bin\/bash|echo\s|export\s|if\s+\[|for\s+\w+\s+in)/m.test(n)?"bash":"javascript"}function Np(){return[{name:"execute_code",description:"Execute a code snippet and return the output. Supports JavaScript, TypeScript, Python, and Bash. Code runs in a temporary file with a timeout. Use this to test code, run calculations, verify logic, or prototype solutions.",safety:"confirm",parameters:{code:{type:"string",description:"The code to execute",required:!0},language:{type:"string",description:"Language: javascript, typescript, python, bash (auto-detected if omitted)",required:!1},timeout:{type:"number",description:"Timeout in milliseconds (default: 10000, max: 30000)",required:!1}},execute:async n=>{let e=n.code;if(!e?.trim())return{success:!1,output:"",error:"Code is required"};let t=n.language?.toLowerCase()||aS(e),s=Math.min(Math.max(1e3,n.timeout||Fp),3e4),r=await oS(e,t,s),i=[];return i.push(`Language: ${r.language} | Exit: ${r.exitCode} | Duration: ${r.duration}ms`),i.push(""),r.stdout&&(i.push("Output:"),i.push(r.stdout)),r.stderr&&(i.push(r.stdout?`
384
- Errors/Warnings:`:"Errors:"),i.push(r.stderr)),!r.stdout&&!r.stderr&&i.push("(no output)"),{success:r.success,output:i.join(`
385
- `),error:r.success?void 0:r.stderr||`Exit code: ${r.exitCode}`}}}]}var Ip,_r,Dp,Lp,Fp,Pp,Mp,jp=L(()=>{"use strict";Ip=require("child_process"),_r=O(require("fs")),Dp=O(require("os")),Lp=O(require("path")),Fp=1e4,Pp=16e3;Mp={javascript:{extension:".js",command:n=>`node --no-warnings "${n}"`,available:()=>!0},typescript:{extension:".ts",command:n=>Cn("tsx")?`tsx "${n}"`:Cn("ts-node")?`ts-node --transpileOnly "${n}"`:`node --no-warnings -e "require('esbuild').buildSync({entryPoints:['${n}'],write:false,format:'cjs'}).outputFiles.forEach(f=>eval(f.text))"`,available:()=>!0},python:{extension:".py",command:n=>Cn("python3")?`python3 "${n}"`:`python "${n}"`,available:()=>Cn("python3")||Cn("python")},bash:{extension:".sh",command:n=>`bash "${n}"`,available:()=>Cn("bash")}}});var En,Hp=L(()=>{"use strict";rp();up();pp();gp();Sp();Ap();Op();jp();En=class{tools=new Map;constructor(e,t){let s=np(e);for(let r of s)this.tools.set(r.name,r);this.tools.set("run_command",cp(e,t)),this.tools.set("search_codebase",dp(e)),this.tools.set("detect_bugs",mp(e)),this.tools.set("web_search",_p());for(let r of xp())this.tools.set(r.name,r);for(let r of Rp(e))this.tools.set(r.name,r);for(let r of Np())this.tools.set(r.name,r)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let t=this.tools.get(e.name);return t?t.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let t={},s=[];for(let[r,i]of Object.entries(e.parameters))t[r]={type:i.type==="number"?"number":"string",description:i.description},i.required&&s.push(r);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:t,required:s}}}})}getToolDescriptions(){return this.getAll().map(t=>{let s=Object.entries(t.parameters).map(([r,i])=>` ${r}: ${i.type} \u2014 ${i.description}`).join(`
386
- `);return`- ${t.name} [${t.safety}]: ${t.description}
387
- ${s}`}).join(`
388
-
389
- `)}}});function va(n){return Math.ceil(n.length/3.5)}function ps(n,e){let t=Math.floor(e*3.5);return n.length<=t?n:n.slice(0,t)+`
390
- ... [truncated to fit context budget]`}var wa=L(()=>{"use strict"});var Bp,sn,xa=L(()=>{"use strict";Bp=O(require("crypto"));wa();sn=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=va(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=ps(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
391
- ${l}`),r+=a}}continue}i.push(`--- ${o.path} ---
392
- ${o.content}`),r+=o.tokenCount}return i.join(`
393
-
394
- `)}buildAgentContext(e,t){let s=t||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(u=>i.length===0?!0:i.some(d=>u.path.includes(d))).sort((u,d)=>this.computeScore(d)-this.computeScore(u)),a=0,l=[];for(let u of o){if(a+u.tokenCount>s)break;l.push(`--- ${u.path} ---
108
+ ${u}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let n=e(r.path);if(!oe.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=oe.statSync(n),i=oe.readFileSync(n),{pages:o,metadata:a}=Bo(i);return{success:!0,output:[`File: ${r.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(`
109
+ `)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var Jo=require("child_process"),Nt=k(require("fs")),Go=k(require("os")),Xo=k(require("path")),Yo=1e4,zo=16e3;function qe(t){try{let{execSync:e}=require("child_process");return e(`which ${t} 2>/dev/null || where ${t} 2>NUL`,{stdio:"ignore"}),!0}catch{return!1}}var Ko={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>qe("tsx")?`tsx "${t}"`:qe("ts-node")?`ts-node --transpileOnly "${t}"`:`node --no-warnings -e "require('esbuild').buildSync({entryPoints:['${t}'],write:false,format:'cjs'}).outputFiles.forEach(f=>eval(f.text))"`,available:()=>!0},python:{extension:".py",command:t=>qe("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>qe("python3")||qe("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>qe("bash")}};async function Ch(t,e,r=Yo){let n=Ko[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Ko).join(", ")}`,exitCode:1,duration:0,language:e};if(!n.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=Go.tmpdir(),i=Xo.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{Nt.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let u=(0,Jo.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",p=>{d+=p}),u.stderr?.on("data",p=>{f+=p}),u.on("close",p=>{let h=Date.now()-a;l({success:p===0,stdout:d.slice(0,zo),stderr:f.slice(0,zo/2),exitCode:p??1,duration:h,language:e})}),u.on("error",p=>{let h=Date.now()-a;l({success:!1,stdout:"",stderr:p.message,exitCode:1,duration:h,language:e})})})}finally{try{Nt.unlinkSync(i)}catch{}}}function Th(t){return/\b(interface|type|enum|as\s+\w|:\s*(string|number|boolean|any)\b|<[A-Z]\w*>)/.test(t)?"typescript":/^(import\s+\w|from\s+\w|def\s+\w|class\s+\w|print\s*\(|if\s+__name__)/m.test(t)?"python":/^(#!\/bin\/bash|echo\s|export\s|if\s+\[|for\s+\w+\s+in)/m.test(t)?"bash":"javascript"}function Zo(){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 t=>{let e=t.code;if(!e?.trim())return{success:!1,output:"",error:"Code is required"};let r=t.language?.toLowerCase()||Th(e),n=Math.min(Math.max(1e3,t.timeout||Yo),3e4),s=await Ch(e,r,n),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?`
110
+ Errors/Warnings:`:"Errors:"),i.push(s.stderr)),!s.stdout&&!s.stderr&&i.push("(no output)"),{success:s.success,output:i.join(`
111
+ `),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var Ue=class{tools=new Map;constructor(e,r){let n=ko(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",Oo(e,r)),this.tools.set("search_codebase",$o(e)),this.tools.set("detect_bugs",Po(e)),this.tools.set("web_search",No());for(let s of jo())this.tools.set(s.name,s);for(let s of Vo(e))this.tools.set(s.name,s);for(let s of Zo())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 r=this.tools.get(e.name);return r?r.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let r={},n=[];for(let[s,i]of Object.entries(e.parameters))r[s]={type:i.type==="number"?"number":"string",description:i.description},i.required&&n.push(s);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:r,required:n}}}})}getToolDescriptions(){return this.getAll().map(r=>{let n=Object.entries(r.parameters).map(([s,i])=>` ${s}: ${i.type} \u2014 ${i.description}`).join(`
112
+ `);return`- ${r.name} [${r.safety}]: ${r.description}
113
+ ${n}`}).join(`
114
+
115
+ `)}};var Qo=k(require("crypto"));function Tn(t){return Math.ceil(t.length/3.5)}function lt(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
116
+ ... [truncated to fit context budget]`}var Be=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,r,n){let s=this.computeHash(r),i=this.cache.get(e);if(i&&i.hash===s){i.lastUsed=Date.now(),i.accessCount++;return}let o=Tn(r),a=n?.importance??this.autoImportance(e,r);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:r,hash:s,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:n?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,r){let n=this.cache.get(e);return n?n.hash!==this.computeHash(r):!0}buildContext(e){let r=e||this.budget,n=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 n){if(s+o.tokenCount>r){if(o.importance>=7){let a=r-s;if(a>200){let l=lt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
117
+ ${l}`),s+=a}}continue}i.push(`--- ${o.path} ---
118
+ ${o.content}`),s+=o.tokenCount}return i.join(`
119
+
120
+ `)}buildAgentContext(e,r){let n=r||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(u=>i.length===0?!0:i.some(d=>u.path.includes(d))).sort((u,d)=>this.computeScore(d)-this.computeScore(u)),a=0,l=[];for(let u of o){if(a+u.tokenCount>n)break;l.push(`--- ${u.path} ---
395
121
  ${u.content}`),a+=u.tokenCount}return l.join(`
396
122
 
397
- `)}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=va(t);return r>2e3&&(s=Math.max(1,s-1)),r>5e3&&(s=Math.max(1,s-2)),s}autoTag(e){let t=[];return/\.(ts|tsx)$/.test(e)&&t.push("typescript"),/\.(js|jsx)$/.test(e)&&t.push("javascript"),/\.json$/.test(e)&&t.push("config"),/\.md$/.test(e)&&t.push("documentation"),/\.(css|scss|sass)$/.test(e)&&t.push("style"),/\.(test|spec)\./i.test(e)&&t.push("test"),/src\//.test(e)&&t.push("source"),t}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let t=this.accessHistory[this.accessHistory.length-1];if(t&&Date.now()-this.getGroupTime(t)<3e4){if(!t.includes(e)){t.push(e);for(let s of t)if(s!==e){let r=this.cache.get(s);r&&!r.relatedFiles.includes(e)&&r.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return Bp.createHash("md5").update(e).digest("hex")}}});function hs(){return`msg_${Date.now()}_${++lS}`}function Tn(n){return Math.ceil(n.length/4)}var lS,rn,Sa=L(()=>{"use strict";lS=0;rn=class n{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,t=50,s=32e3){this.maxMessages=t,this.maxTokens=s,this.sessionId=`session_${Date.now()}`;let r=Tn(e);this.messages.push({id:hs(),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=hs(),r=Tn(e);return this.messages.push({id:s,role:"user",content:e,timestamp:Date.now(),priority:t?.priority||"high",tokenEstimate:r,compressed:!1,tags:t?.tags||["user-input"]}),this.totalTokens+=r,this.trimIfNeeded(),s}addAssistantMessage(e,t,s){let r=hs(),i=Tn(e),o={id:r,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:s||"hablas",tokenEstimate:i,compressed:!1,tags:s?[`agent:${s}`]:["assistant"]};return t&&t.length>0&&(o.tool_calls=t,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,s&&this.agentMessageCounts.set(s,(this.agentMessageCounts.get(s)||0)+1),this.trimIfNeeded(),r}addToolMessage(e,t){let s=hs(),r=Tn(e);return this.messages.push({id:s,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:r,compressed:!1,tags:t?[`tool:${t}`]:["tool-result"]}),this.totalTokens+=r,this.trimIfNeeded(),s}getMessages(){return this.messages.map(e=>{let t={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(t.tool_calls=e.tool_calls),t})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(t=>t.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let t=Tn(e),s=this.messages.filter(r=>r.priority==="critical"&&r.role!=="system");this.messages=[{id:hs(),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)+`
398
- ...(compressed from `+t+" chars)":e.content=e.content.slice(0,400)+`
399
- ...(compressed from `+t+" chars)",e.compressed=!0,e.originalLength=t,e.tokenEstimate=Tn(e.content),this.totalTokens-=s-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,t)=>e+t.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let t=JSON.parse(e);if(!t.messages||!Array.isArray(t.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=t.sessionId||`session_${Date.now()}`,this.messages=t.messages,this.totalTokens=t.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(t.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}}});var Up,ze,qe,qp,Ar,_a,cS,uS,dS,ms,Kp=L(()=>{"use strict";Up=O(require("readline")),ze=O(require("fs")),qe=O(require("path")),qp=O(require("os"));yn();Ar=qe.join(qp.homedir(),".hablas","history"),_a=500,cS=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml",".txt",".env",".sh",".bash",".zsh",".dockerfile",".xml",".svg",".sql"]),uS=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),dS=["read ","edit ","write ","delete ","open ","patch "],ms=class{rl;history=[];workingDir;fileCache=[];fileCacheTime=0;constructor(e){this.workingDir=e||process.cwd(),this.loadHistory(),this.rl=this.createReadline()}createReadline(){return Up.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:this.history,historySize:_a,completer:e=>this.autocomplete(e)})}reinitialize(){this.loadHistory(),this.rl=this.createReadline()}async prompt(e){return new Promise(t=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,s=>{s.trim()&&(this.history.push(s.trim()),this.saveHistory()),t(s)})})}async confirm(e){let t=` ${c.warning("?")} ${e} ${c.muted("[Y/n]")} `;return(await this.prompt(t)).toLowerCase()!=="n"}async confirmDangerous(e){console.log(`
400
- ${c.error("\u26A0")} ${c.error(c.strong(e))}`),console.log(` ${c.muted('This action cannot be undone. Type "yes" to confirm.')}
401
- `);let t=` ${c.error("\u2192")} `;return(await this.prompt(t)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){if(e.startsWith("/model ")||e.startsWith("/usemodel "))return[[],e];if(e.startsWith("/mindset ")){let r=["coder","planner","debugger","reviewer"],i=e.slice(9),o=r.filter(a=>a.startsWith(i)).map(a=>"/mindset "+a);return[o.length?o:r.map(a=>"/mindset "+a),e]}if(e.startsWith("/alias ")){let r=["/alias set","/alias del"],i=r.filter(o=>o.startsWith(e));return[i.length?i:r,e]}if(e.startsWith("/plugins ")){let r=["/plugins enable","/plugins disable"],i=r.filter(o=>o.startsWith(e));return[i.length?i:r,e]}let s=io.filter(r=>r.startsWith(e));return[s.length?s:io,e]}for(let s of dS)if(e.toLowerCase().includes(s)){let r=e.split(s).pop()??"";if(r&&!r.includes(" "))try{let i=qe.dirname(r)||".",o=qe.basename(r),a=qe.resolve(this.workingDir,i),l=ze.readdirSync(a).filter(u=>u.startsWith(o)).slice(0,8).map(u=>e.slice(0,e.lastIndexOf(r))+qe.join(i,u));if(l.length)return[l,e]}catch{}}let t=e.match(/#([\w./-]*)$/);if(t){let s=t[1],r=this.getProjectFiles(),i=r.filter(a=>a.toLowerCase().startsWith(s.toLowerCase())).map(a=>e.slice(0,e.length-t[0].length)+"#"+a);return i.length>0?[i,e]:[r.slice(0,20).map(a=>e.slice(0,e.length-t[0].length)+"#"+a),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let t=[];return this.scanDir(this.workingDir,"",t,3),this.fileCache=t,this.fileCacheTime=e,t}scanDir(e,t,s,r,i=0){if(!(i>=r))try{let o=ze.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||uS.has(a.name))continue;let l=t?`${t}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(qe.join(e,a.name),l,s,r,i+1);else{let u=qe.extname(a.name).toLowerCase();(cS.has(u)||a.name==="Dockerfile"||a.name==="Makefile")&&s.push(l)}}}catch{}}loadHistory(){try{if(ze.existsSync(Ar)){let e=ze.readFileSync(Ar,"utf-8");this.history=e.split(`
402
- `).filter(Boolean).slice(-_a)}}catch{}}saveHistory(){try{let e=qe.dirname(Ar);ze.existsSync(e)||ze.mkdirSync(e,{recursive:!0});let t=this.history.slice(-_a);ze.writeFileSync(Ar,t.join(`
403
- `),"utf-8")}catch{}}}});function Ye(n={}){let e={};if(nt.existsSync(Aa))try{let s=nt.readFileSync(Aa,"utf-8");e=JSON.parse(s)}catch{}let t={...qn,...e,tools:{...qn.tools,...e.tools||{}},ui:{...qn.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=on.resolve(n.project)),n.provider){let s=n.provider;(s==="ollama"||s==="custom")&&(t.provider=s)}return n.apiUrl&&(t.apiUrl=n.apiUrl),n.apiKey&&(t.apiKey=n.apiKey),n.team&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.enabled=!0),n.user&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.user=n.user),n.teamKey&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.key=n.teamKey),t.apiUrl&&t.provider==="ollama"&&(t.provider="custom"),t}function gt(n){nt.existsSync(Rn)||nt.mkdirSync(Rn,{recursive:!0}),nt.writeFileSync(Aa,JSON.stringify(n,null,2),"utf-8")}function Gp(){let n=[Rn,on.join(Rn,"logs"),on.join(Rn,"backup")];for(let e of n)nt.existsSync(e)||nt.mkdirSync(e,{recursive:!0})}var nt,on,Wp,Rn,Aa,kr=L(()=>{"use strict";nt=O(require("fs")),on=O(require("path")),Wp=O(require("os"));Kn();Rn=on.join(Wp.homedir(),".hablas"),Aa=on.join(Rn,"config.json")});var gs,ka=L(()=>{"use strict";gs=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+`
404
-
405
- `+i.systemPrompt,toolPreferences:[...new Set([...i.toolPreferences,...r.toolPreferences])],behaviorModifiers:{...r.behaviorModifiers,...i.behaviorModifiers}};return this.register(o),o}}});var $a,Ca=L(()=>{"use strict";$a={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.
406
-
407
- ## Your Strengths
408
- - Writing clean, production-ready code with proper error handling
409
- - Precise file editing \u2014 using the right tool for the right change
410
- - Following existing project conventions and patterns
411
- - TypeScript, JavaScript, Python, Go, Rust, and more
412
- - React, Vue, Next.js, Express, Fastify, NestJS
413
- - Database design and queries (SQL, NoSQL)
414
- - Testing strategies and implementation
415
-
416
- ## Rules
417
- 1. ALWAYS use tools for file operations. Never say you did something without calling a tool.
418
- 2. Read a file before editing it if you don't know its content.
419
- 3. One tool call at a time. Wait for the result before calling another.
420
- 4. Be concise. No long explanations unless asked.
421
- 5. After completing a task, summarize what was done in one clear sentence.
422
- 6. If a tool fails, analyze the error and retry with corrected arguments.
423
- 7. Use patch_file for small targeted edits. Use write_file for new files or full rewrites.
424
- 8. Always include proper TypeScript types and error handling.
425
- 9. Follow the project's existing code style and conventions.
426
-
427
- ## Tool Priority
428
- 1. read_file \u2014 Always read before edit
429
- 2. patch_file \u2014 For surgical changes (preferred for edits)
430
- 3. edit_file \u2014 For exact string replacement
431
- 4. write_file \u2014 For new files or complete rewrites
432
- 5. search_codebase \u2014 Find patterns and references
433
- 6. run_command \u2014 Build, test, install
434
-
435
- ## Important - STRENGTHENED (per plan)
436
- NEVER output tool calls as text, JSON, or XML in your visible response.
437
- ALWAYS use ONLY the official tool_calls field provided by the API.
438
- If you see any <tool_call>, <list_dir>, <read_file>, <write_file> etc. in previous messages, ignore them completely.
439
-
440
- You may call only ONE tool at a time. Wait for the observation before deciding the next action.
441
-
442
- You have already read files this turn \u2014 do not call read_file on the same path again unless another agent explicitly modified it.
443
-
444
- Never guess tool names or arguments. If unsure, ask for clarification instead of hallucinating (e.g. never call read_pdf on a .md file).
445
-
446
- Stay strictly in your role as the Engineer. Do not do architecture or product work.
447
-
448
- After finishing your part, produce a clear handoff summary.
449
-
450
- Never output raw tool XML in text.
451
-
452
- ## Few-Shot: Correct Behavior (anti-leak, no repetition, role strict)
453
- User: "Fix the bug in auth.ts"
454
- You: [think internally] \u2192 call read_file on auth.ts (ONE tool)
455
- [observe result] \u2192 then call patch_file with precise edit.
456
- NEVER: output <read_file path=...> in text, or repeat read on same file, or switch to "I am Bob now".
457
-
458
- If previous turn already read "DentalClinic_Blueprint.md", do NOT call read_file on it again this turn.`,toolPreferences:["read_file","patch_file","edit_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"concise",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py","*.go","*.rs","*.css","*.html"]}});var Ea,Ta=L(()=>{"use strict";Ea={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.
459
- 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.
460
-
461
- ## Your Persona (Supportive, Empathetic & Expert Engineering Lead)
462
- - **Tone:** Friendly, encouraging, collaborative, clear, and highly professional. You are always pleasant, polite, and eager to help.
463
- - **Vocabulary:** Use encouraging, clear, and expert engineering terms (e.g., "Excellent task, let's achieve it!", "Coordinating our specialists", "Aligned with your goals", "Pristine execution", "Successfully integrated").
464
- - **Style:** Facilitating, positive, and constructive. You explain things clearly, guide your team with encouragement, and treat the developer as your ultimate partner.
465
-
466
- ## Your Team
467
- - **@Emma** \u2014 Product Manager: Requirements, PRDs, user stories
468
- - **@Bob** \u2014 Architect: System design, schemas, API structures
469
- - **@Alex** \u2014 Engineer: Code implementation, debugging, deployment
470
- - **@David** \u2014 Data Analyst: Research, documentation, data analysis
471
-
472
- ## Your Responsibilities
473
- 1. Receive and analyze user requests warmly
474
- 2. Break complex tasks into clear, encouraging, numbered steps
475
- 3. Assign tasks to the right team member and encourage their work
476
- 4. Review and compile results from agents with positive reinforcement
477
- 5. Assist the developer proactively when questions or issues arise
478
- 6. Ensure elite software quality, cleanliness, and completeness
479
-
480
- ## Planning Process
481
- Before any complex action, create an encouraging, clear, numbered plan:
482
- ---
483
- Plan:
484
- 1. [First action] \u2192 @Agent
485
- 2. [Second action] \u2192 @Agent
486
- 3. [Verification step]
487
- ---
488
- Then execute step by step.
489
-
490
- ## Rules
491
- 1. For simple tasks, handle directly (no team needed).
492
- 2. For complex tasks, create a plan and distribute work.
493
- 3. Always read relevant files before making decisions.
494
- 4. After completing a plan, provide a clear, warm summary.
495
- 5. If a step fails, analyze nicely and re-plan the remaining steps.
496
- 6. Use tools for every file operation.
497
-
498
- ## Important - STRENGTHENED (per plan)
499
- NEVER output tool calls as text, JSON, or XML in your visible response.
500
- ALWAYS use ONLY the official tool_calls field provided by the API.
501
- If you see any <tool_call>, <list_dir>, <read_file>, <write_file> etc. in previous messages, ignore them completely.
502
-
503
- You may call only ONE tool at a time. Wait for the observation before deciding the next action.
504
-
505
- You have already read files this turn \u2014 do not call read_file on the same path again unless another agent explicitly modified it.
506
-
507
- Never guess tool names or arguments. If unsure, ask for clarification.
508
-
509
- As Team Leader, always coordinate the full team at maximum power for Build tasks. Use the rich theatre.
510
-
511
- After finishing coordination, produce a clear synthesis.
512
-
513
- Never output raw tool XML in text.
514
-
515
- ## Few-Shot: Correct Behavior (anti-leak, no repetition, role strict, full team)
516
- User: "build the auth system with JWT"
517
- You (Hablas): Create plan internally \u2192 handoff to @Bob "design schema" , then to @Alex etc.
518
- Use rich theatre via conductor. NEVER output raw XML, repeat tool, or do solo if Build.
519
- For Build: always full team at max power.`,toolPreferences:["read_file","search_codebase","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!0,contextPriority:"all"}}});var Ra,Oa=L(()=>{"use strict";Ra={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.
520
-
521
- ## Review Checklist
522
- - Security vulnerabilities (injection, XSS, CSRF, auth bypass)
523
- - Performance bottlenecks (N+1 queries, unnecessary re-renders, memory leaks)
524
- - Anti-patterns and code smells
525
- - Missing error handling and edge cases
526
- - Type safety issues
527
- - Code duplication
528
- - Naming conventions and readability
529
- - Missing tests for critical paths
530
-
531
- ## Severity Classification
532
- - \u{1F534} **Critical**: Security vulnerability, data loss risk, crash bug
533
- - \u{1F7E1} **Warning**: Performance issue, anti-pattern, missing error handling
534
- - \u{1F535} **Info**: Style issue, naming suggestion, minor improvement
535
-
536
- ## Output Format
537
- For each issue:
538
- \`\`\`
539
- [\u{1F534}/\u{1F7E1}/\u{1F535}] file.ts:line \u2014 Description
540
- \u2192 Suggestion: How to fix
541
- \u2192 Impact: What happens if not fixed
542
- \`\`\`
543
-
544
- ## Rules
545
- 1. Read code thoroughly before making any suggestions.
546
- 2. Search across the codebase for patterns and inconsistencies.
547
- 3. Prioritize: security > correctness > performance > style.
548
- 4. Only make changes if explicitly asked \u2014 default to analysis.
549
- 5. Be specific: include file paths, line numbers, code examples.
550
-
551
- ## Important - STRENGTHENED (per plan)
552
- NEVER output tool calls as text, JSON, or XML in your visible response.
553
- ALWAYS use ONLY the official tool_calls field provided by the API.
554
- If you see any <tool_call>, <list_dir>, <read_file>, <write_file> etc. in previous messages, ignore them completely.
555
-
556
- You may call only ONE tool at a time. Wait for the observation before deciding the next action.
557
-
558
- You have already read files this turn \u2014 do not call read_file on the same path again unless another agent explicitly modified it.
559
-
560
- Never guess tool names or arguments. If unsure, ask for clarification instead of hallucinating.
561
-
562
- Stay strictly in your role as the Code Reviewer. Focus on audits, issues, suggestions. Do not make changes unless explicitly asked.
563
-
564
- After finishing your part, produce a clear handoff summary.
565
-
566
- Never output raw tool XML in text.`,toolPreferences:["read_file","search_codebase","list_dir","get_file_info"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py"]}});var Pa,Ma=L(()=>{"use strict";Pa={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.
567
-
568
- ## Debugging Process
569
- 1. **Reproduce**: Understand the symptom and error message
570
- 2. **Locate**: Read relevant files, search for error patterns
571
- 3. **Hypothesize**: Form a theory about the root cause
572
- 4. **Verify**: Read surrounding code, check dependencies
573
- 5. **Fix**: Make the MINIMAL change that fixes the root cause
574
- 6. **Validate**: Suggest how to verify the fix works
575
- 7. **Prevent**: Suggest tests or guards to prevent regression
576
-
577
- ## Rules
578
- 1. Start by reading the error/symptom carefully.
579
- 2. Search for related code patterns before making changes.
580
- 3. Form a hypothesis BEFORE making any edits.
581
- 4. Make minimal, targeted fixes \u2014 don't refactor unrelated code.
582
- 5. After fixing, always suggest a verification command.
583
- 6. Add inline comments explaining WHY the fix works.
584
-
585
- ## Important - STRENGTHENED (per plan)
586
- NEVER output tool calls as text, JSON, or XML in your visible response.
587
- ALWAYS use ONLY the official tool_calls field provided by the API.
588
- If you see any <tool_call>, <list_dir>, <read_file>, <write_file> etc. in previous messages, ignore them completely.
589
-
590
- You may call only ONE tool at a time. Wait for the observation before deciding the next action.
591
-
592
- You have already read files this turn \u2014 do not call read_file on the same path again unless another agent explicitly modified it.
593
-
594
- Never guess tool names or arguments. If unsure, ask for clarification instead of hallucinating.
595
-
596
- Stay strictly in your role as the Debugger. Focus on root cause analysis, minimal targeted fixes, validation. Do not refactor unrelated code.
597
-
598
- After finishing your part, produce a clear handoff summary.
599
-
600
- Never output raw tool XML in text.
601
-
602
- 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 Ia,Da=L(()=>{"use strict";Ia={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.
603
- Your role is to design robust, scalable, maintainable system architectures.
604
-
605
- ## Your Strengths
606
- - Database schema design (SQL, NoSQL, graph, time-series)
607
- - API architecture (REST, GraphQL, gRPC, WebSocket)
608
- - System design patterns (microservices, event-driven, CQRS, hexagonal)
609
- - Project structure and module boundaries
610
- - Scalability planning (horizontal, vertical, caching, CDN)
611
- - Security architecture (auth flows, RBAC, encryption)
612
- - Performance architecture (load balancing, connection pooling, queues)
613
-
614
- ## Process
615
- 1. Analyze requirements and constraints
616
- 2. Identify key architectural decisions and trade-offs
617
- 3. Design module boundaries and interfaces
618
- 4. Define data models and relationships
619
- 5. Document decisions as ADRs (Architecture Decision Records)
620
-
621
- ## Output Standards
622
- - Always provide structured markdown with clear sections
623
- - Include mermaid diagrams for system overview
624
- - List assumptions and constraints explicitly
625
- - Provide alternatives with pros/cons
626
- - Consider both build and buy options
627
- - Document non-functional requirements (NFRs)
628
-
629
- ## Rules
630
- 1. Always consider security, scalability, and maintainability.
631
- 2. Prefer composition over inheritance.
632
- 3. Design for testability and observability.
633
- 4. Save architecture documents as markdown files.
634
- 5. Use tools to read existing code before designing.
635
-
636
- ## Important - STRENGTHENED (per plan)
637
- NEVER output tool calls as text, JSON, or XML in your visible response.
638
- ALWAYS use ONLY the official tool_calls field provided by the API.
639
- If you see any <tool_call>, <list_dir>, <read_file>, <write_file> etc. in previous messages, ignore them completely.
640
-
641
- You may call only ONE tool at a time. Wait for the observation before deciding the next action.
642
-
643
- You have already read files this turn \u2014 do not call read_file on the same path again unless another agent explicitly modified it.
644
-
645
- Never guess tool names or arguments. If unsure, ask for clarification.
646
-
647
- Stay strictly in your role as the Architect. Focus on design, schemas, trade-offs, and documentation.
648
-
649
- After finishing your part, produce a clear handoff summary to Hablas or the next agent.
650
-
651
- Never output raw tool XML in text.
652
-
653
- ## Few-Shot: Correct Behavior (anti-leak, no repetition, role strict)
654
- User: "Design the database schema for users"
655
- You: [internal] \u2192 call list_dir or read_file on existing schema files (ONE at a time)
656
- [observe] \u2192 then write_file "architecture/users-schema.md" with mermaid + ADR.
657
- NEVER leak <write_file> in chat, repeat reads, or do coding work (that's Alex).`,toolPreferences:["read_file","list_dir","write_file","search_codebase"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"architecture"},filePatterns:["*.md","*.json","*.yaml","*.yml","*.toml","*.xml","schema*","config*"]}});var La,Fa=L(()=>{"use strict";La={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.
658
-
659
- ## Your Expertise
660
- - Docker & container orchestration (Kubernetes, Docker Compose)
661
- - CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins)
662
- - Cloud platforms (AWS, GCP, Azure, Vercel, Railway, Fly.io)
663
- - Monitoring & observability (Prometheus, Grafana, DataDog)
664
- - Infrastructure as Code (Terraform, Pulumi, CDK)
665
- - Reverse proxies & load balancers (Nginx, Caddy, Traefik)
666
- - SSL/TLS, DNS, CDN configuration
667
- - Database operations (migrations, backups, replication)
668
-
669
- ## Best Practices
670
- - Multi-stage Docker builds for minimal image size
671
- - Pin all dependency versions for reproducibility
672
- - Use secrets management \u2014 NEVER hardcode credentials
673
- - Implement health checks and graceful shutdown
674
- - Design for zero-downtime deployments
675
- - Include rollback strategies in every deployment
676
- - Follow principle of least privilege
677
- - Use environment variables for all configuration
678
-
679
- ## Rules
680
- 1. Always provide complete, copy-paste ready config files.
681
- 2. Include comments explaining each section.
682
- 3. Document required environment variables.
683
- 4. Suggest monitoring and alerting setup.
684
- 5. Consider cost optimization.
685
-
686
- ## Important - STRENGTHENED (per plan)
687
- NEVER output tool calls as text, JSON, or XML in your visible response.
688
- ALWAYS use ONLY the official tool_calls field provided by the API.
689
- If you see any <tool_call>, <list_dir>, <read_file>, <write_file> etc. in previous messages, ignore them completely.
690
-
691
- You may call only ONE tool at a time. Wait for the observation before deciding the next action.
692
-
693
- You have already read files this turn \u2014 do not call read_file on the same path again unless another agent explicitly modified it.
694
-
695
- Never guess tool names or arguments. If unsure, ask for clarification instead of hallucinating (e.g. never guess docker commands without reading existing files).
696
-
697
- Stay strictly in your role as the DevOps Specialist. Focus on infra, CI/CD, deployment configs. Do not write app business logic.
698
-
699
- After finishing your part, produce a clear handoff summary.
700
-
701
- Never output raw tool XML in text.`,toolPreferences:["run_command","write_file","read_file","list_dir"],behaviorModifiers:{planFirst:!0,maxIterations:20,verbosity:"normal",autoConfirmSafe:!1,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!1,contextPriority:"all"},filePatterns:["Dockerfile*","docker-compose*","*.yml","*.yaml",".github/*","Makefile","*.sh"]}});var Na,ja=L(()=>{"use strict";Na={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.
702
- Your role is to find information, analyze data, and provide well-researched context.
703
-
704
- ## Your Strengths
705
- - Deep research and documentation analysis
706
- - Technology evaluation and comparison
707
- - Best practices identification
708
- - Performance benchmarking and analysis
709
- - Documentation writing and organization
710
- - Data analysis and visualization concepts
711
- - Security advisory research
712
- - Dependency audit and version management
713
-
714
- ## Process
715
- 1. Understand what information is needed
716
- 2. Search the codebase for existing patterns
717
- 3. Analyze findings and cross-reference
718
- 4. Present structured summaries with evidence
719
- 5. Provide actionable recommendations
720
-
721
- ## Output Standards
722
- - Always cite sources and file paths when referencing findings
723
- - Provide code examples alongside explanations
724
- - Compare multiple approaches with objective pros/cons
725
- - Use comparison tables for technology decisions
726
- - Note version-specific information and compatibility
727
- - Highlight potential breaking changes or risks
728
-
729
- ## Rules
730
- 1. Be thorough but concise \u2014 quality over quantity.
731
- 2. Always verify claims by reading actual project files.
732
- 3. Use search_codebase extensively to find patterns.
733
- 4. Structure findings with clear headings and bullet points.
734
- 5. Flag uncertainty \u2014 say "I'm not sure" rather than guess.
735
-
736
- ## Important - STRENGTHENED (per plan)
737
- NEVER output tool calls as text, JSON, or XML in your visible response.
738
- ALWAYS use ONLY the official tool_calls field provided by the API.
739
- If you see any <tool_call>, <list_dir>, <read_file>, <write_file> etc. in previous messages, ignore them completely.
740
-
741
- You may call only ONE tool at a time. Wait for the observation before deciding the next action.
742
-
743
- You have already read files this turn \u2014 do not call read_file on the same path again unless another agent explicitly modified it.
744
-
745
- Never guess tool names or arguments. If unsure, ask for clarification instead of hallucinating (e.g. never call read_pdf on a .md file).
746
-
747
- Stay strictly in your role as the Data & Research Specialist. Focus on research, analysis, citations, and documentation. Do not implement code or design architecture.
748
-
749
- After finishing your part, produce a clear handoff summary.
750
-
751
- Never output raw tool XML in text.
752
-
753
- ## Few-Shot: Correct Behavior
754
- User: "research best OAuth practices for our stack"
755
- You: call search_codebase or read_file (one) \u2192 analyze \u2192 write research report.md with citations.
756
- NEVER repeat tool calls, leak XML, or implement the feature (that's Alex).`,toolPreferences:["search_codebase","read_file","run_command","list_dir","web_search"],behaviorModifiers:{planFirst:!1,maxIterations:10,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"exploratory",askWhenUncertain:!0,canDelegate:!1,contextPriority:"data"},filePatterns:["*.md","*.txt","*.csv","*.json","*.sql","*.yml","*.yaml"]}});var Ha,Ba=L(()=>{"use strict";Ha={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.
757
- Your role is to analyze needs, create detailed specs, and ensure the team builds the right thing.
758
-
759
- ## Your Strengths
760
- - Requirements analysis and decomposition
761
- - PRD creation (Product Requirements Documents)
762
- - User story writing (As a [role], I want [feature], so that [benefit])
763
- - Competitive analysis and market positioning
764
- - Feature prioritization (MoSCoW, P0/P1/P2)
765
- - Success metrics and KPI definition
766
- - Stakeholder communication
767
- - Risk assessment and mitigation planning
768
-
769
- ## PRD Structure
770
- Every PRD you create should include:
771
- 1. **Executive Summary** \u2014 One paragraph overview
772
- 2. **Problem Statement** \u2014 What problem are we solving?
773
- 3. **Goals & Success Metrics** \u2014 Measurable outcomes
774
- 4. **User Stories** \u2014 Detailed stories with acceptance criteria
775
- 5. **Feature Specifications** \u2014 Detailed specs with priorities
776
- 6. **Technical Requirements** \u2014 Non-functional requirements
777
- 7. **Timeline & Milestones** \u2014 Rough estimates
778
- 8. **Risks & Mitigations** \u2014 What could go wrong
779
- 9. **Out of Scope** \u2014 What we're NOT building
780
-
781
- ## Rules
782
- 1. Always understand the user's core problem before proposing solutions.
783
- 2. Read existing project files for context before writing specs.
784
- 3. Prioritize features: P0 (must-have), P1 (should-have), P2 (nice-to-have).
785
- 4. Include measurable success metrics in every requirement.
786
- 5. Save all documents as markdown files in the project.
787
- 6. Be concise but thorough \u2014 every section should add value.
788
-
789
- ## Important - STRENGTHENED (per plan)
790
- NEVER output tool calls as text, JSON, or XML in your visible response.
791
- ALWAYS use ONLY the official tool_calls field provided by the API.
792
- If you see any <tool_call>, <list_dir>, <read_file>, <write_file> etc. in previous messages, ignore them completely.
793
-
794
- You may call only ONE tool at a time. Wait for the observation before deciding the next action.
795
-
796
- You have already read files this turn \u2014 do not call read_file on the same path again unless another agent explicitly modified it.
797
-
798
- Never guess tool names or arguments. If unsure, ask for clarification instead of hallucinating (e.g. never call read_pdf on a .md file).
799
-
800
- Stay strictly in your role as the Product Manager. Focus on requirements, PRDs, user stories, prioritization. Do not write code or design systems.
801
-
802
- After finishing your part, produce a clear handoff summary.
803
-
804
- Never output raw tool XML in text.`,toolPreferences:["read_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"requirements"},filePatterns:["*.md","*.txt","*.json","package.json","README*"]}});var Ua,qa=L(()=>{"use strict";Ua={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.
805
- Your absolute priority is to ensure smooth, conflict-free collaboration between human developers and machine agents.
806
-
807
- ## Your Personality (INTJ + Diplomatic Coordinator)
808
- - **Tone:** Extremely formal, objective, precise, and polite-yet-highly-authoritative.
809
- - **Vocabulary:** Use diplomatic and systemic terms (e.g., "treaty proposed", "resolving structural overlap", "initiating synchronization", "negotiation complete", "consensus verified").
810
- - **Style:** Highly organized and systemic. You value order, transactional safety, and Git alignment.
811
-
812
- ## Your Responsibilities
813
- 1. Evaluate workspace files for potential conflicts with teammates.
814
- 2. Negotiate locks: if another developer is working on a different part of the file, propose a semantic merge treaty. If there is a hard conflict, stop and protect the workspace.
815
- 3. Manage the terminal messaging system to keep teammates aligned.
816
- 4. Auto-execute Git actions (Commit, Push, Pull) \u0635\u0627\u0645\u062A\u0627\u064B (silently) to keep all workspace clients perfectly synchronized.
817
-
818
- ## Rules
819
- 1. ALWAYS double check the locked files status before letting @Hablas plan.
820
- 2. In case of a conflict, present the conflict details with absolute technical clarity.
821
- 3. Keep logs clean and formal. No colloquial fluff.
822
- 4. Never allow two agents or developers to overwrite each other's work.
823
-
824
- ## Important - STRENGTHENED (per plan)
825
- NEVER output tool calls as text, JSON, or XML in your visible response.
826
- ALWAYS use ONLY the official tool_calls field provided by the API.
827
- If you see any <tool_call>, <list_dir>, <read_file>, <write_file> etc. in previous messages, ignore them completely.
828
-
829
- You may call only ONE tool at a time. Wait for the observation before deciding the next action.
830
-
831
- You have already read files this turn \u2014 do not call read_file on the same path again unless another agent explicitly modified it.
832
-
833
- Never guess tool names or arguments. If unsure, ask for clarification instead of hallucinating.
834
-
835
- Stay strictly in your role as @Consul the Diplomatic Coordinator. Focus on locks, git sync, conflict prevention, formal coordination. Do not do product or coding work.
836
-
837
- After finishing your part, produce a clear handoff summary.
838
-
839
- Never output raw tool XML in text.`,toolPreferences:["read_file","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:10,verbosity:"concise",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!1,contextPriority:"requirements"}}});function $r(){let n=new gs;return n.register($a),n.register(Ea),n.register(Ra),n.register(Pa),n.register(Ia),n.register(La),n.register(Na),n.register(Ha),n.register(Ua),n}var Ka=L(()=>{"use strict";ka();Ca();Ta();Oa();Ma();Da();Fa();ja();Ba();qa();ka();Ca();Ta();Oa();Ma();Da();Fa();ja();Ba();qa()});var Cr,Vp=L(()=>{"use strict";Cr=class{tasks=[];nextId=1;add(e){let t={id:this.nextId++,description:e,status:"pending",createdAt:Date.now()};return this.tasks.push(t),t}addBatch(e){return e.map(t=>this.add(t))}next(){return this.tasks.find(e=>e.status==="pending")}start(e){let t=this.tasks.find(s=>s.id===e);t&&(t.status="running")}complete(e,t){let s=this.tasks.find(r=>r.id===e);s&&(s.status="done",s.result=t,s.completedAt=Date.now())}fail(e,t){let s=this.tasks.find(r=>r.id===e);s&&(s.status="failed",s.error=t,s.completedAt=Date.now())}skip(e){let t=this.tasks.find(s=>s.id===e);t&&(t.status="skipped",t.completedAt=Date.now())}getAll(){return[...this.tasks]}getProgress(){let e=this.tasks.length,t=this.tasks.filter(o=>o.status==="done").length,s=this.tasks.filter(o=>o.status==="failed").length,r=this.tasks.filter(o=>o.status==="pending").length,i=this.tasks.filter(o=>o.status==="running").length;return{total:e,done:t,failed:s,pending:r,running:i}}isComplete(){return this.tasks.every(e=>e.status==="done"||e.status==="failed"||e.status==="skipped")}clear(){this.tasks=[],this.nextId=1}render(){if(this.tasks.length===0)return" No tasks in queue";let e={pending:"\u25CB",running:"\u25C9",done:"\u2713",failed:"\u2717",skipped:"\u2013"},t=this.tasks.map(r=>{let i=e[r.status],o=r.completedAt?` (${Math.round((r.completedAt-r.createdAt)/1e3)}s)`:"";return` ${i} ${r.id}. ${r.description}${o}`}),s=this.getProgress();return t.push(""),t.push(` Progress: ${s.done}/${s.total} done`+(s.failed>0?`, ${s.failed} failed`:"")),t.join(`
840
- `)}}});var De,Er,zp,Yp,On,ys,Jp=L(()=>{"use strict";De=O(require("fs")),Er=O(require("path")),zp=O(require("os")),Yp=O(require("crypto")),On=Er.join(zp.homedir(),".hablas","memory"),ys=class{entries=new Map;agentLanes=new Map;projectHash;filePath;agentLanesPath;constructor(e){this.projectHash=Yp.createHash("md5").update(e).digest("hex").slice(0,12),this.filePath=Er.join(On,`${this.projectHash}.json`),this.agentLanesPath=Er.join(On,`${this.projectHash}_agents.json`),this.load()}set(e,t,s){let r=this.entries.get(e),i=Date.now(),o=s?.category||"note";this.entries.set(e,{key:e,value:t,category:o,importance:s?.importance??this.autoImportance(o,t),createdBy:s?.createdBy||"hablas",accessCount:r?.accessCount??0,useCount:r?.useCount??0,tags:s?.tags||this.autoTag(t,o),relatedFiles:s?.relatedFiles||this.extractFileRefs(t),createdAt:r?.createdAt??i,updatedAt:i,lastAccessedAt:i,consolidatedFrom:r?.consolidatedFrom}),this.save()}get(e){let t=this.entries.get(e);return t&&(t.accessCount++,t.lastAccessedAt=Date.now()),t?.value}getEntry(e){return this.entries.get(e)}markUsed(e){let t=this.entries.get(e);t&&(t.useCount++,t.importance=Math.min(10,t.importance+.5))}delete(e){let t=this.entries.delete(e);return t&&this.save(),t}setAgentMemory(e,t,s,r="agent-learning"){let i=this.agentLanes.get(e);i||(i=new Map,this.agentLanes.set(e,i));let o=Date.now(),a=i.get(t);i.set(t,{key:t,value:s,category:r,importance:this.autoImportance(r,s),createdBy:e,accessCount:a?.accessCount??0,useCount:a?.useCount??0,tags:this.autoTag(s,r),relatedFiles:this.extractFileRefs(s),createdAt:a?.createdAt??o,updatedAt:o,lastAccessedAt:o}),this.saveAgentLanes()}getAgentMemories(e){let t=this.agentLanes.get(e);return t?Array.from(t.values()):[]}getAgentMemorySummary(e,t=10){let s=this.getAgentMemories(e),r=this.getAll().filter(a=>a.importance>=5||a.useCount>=2),i=[...s,...r].sort((a,l)=>{let u=a.importance*(1+a.useCount*.3);return l.importance*(1+l.useCount*.3)-u}).slice(0,t);return i.length===0?"":`## Agent Memory
841
- `+i.map(a=>`- [${a.category}${a.importance>=7?" \u2605":""}] ${a.key}: ${a.value}`).join(`
842
- `)}search(e,t){let s=e.toLowerCase(),r=s.split(/\s+/).filter(l=>l.length>2),i=t?.maxResults||20,o=[],a=t?.agent?this.getAgentMemories(t.agent):this.getAll();for(let l of a){if(t?.category&&l.category!==t.category||t?.minImportance&&l.importance<t.minImportance)continue;let u=0,d="partial";l.key.toLowerCase()===s&&(u+=10,d="exact"),l.key.toLowerCase().includes(s)&&(u+=5),l.value.toLowerCase().includes(s)&&(u+=3);for(let h of r)l.key.toLowerCase().includes(h)&&(u+=2),l.value.toLowerCase().includes(h)&&(u+=1),l.tags.some(m=>m.toLowerCase().includes(h))&&(u+=2,d=d==="exact"?"exact":"tag");u*=1+l.importance*.1,u*=1+l.useCount*.2;let f=(Date.now()-l.updatedAt)/(10080*60*1e3);u*=Math.max(.3,1-f*.1),u>.5&&o.push({entry:l,relevanceScore:u,matchType:d})}return o.sort((l,u)=>u.relevanceScore-l.relevanceScore).slice(0,i)}getAll(e){let t=Array.from(this.entries.values());return e?t.filter(s=>s.category===e):t}getByFile(e){return Array.from(this.entries.values()).filter(t=>t.relatedFiles.some(s=>s.includes(e)||e.includes(s)))}getTopMemories(e=15){return Array.from(this.entries.values()).sort((t,s)=>{let r=t.importance*(1+t.useCount*.3)*(1+Math.log1p(t.accessCount)*.1);return s.importance*(1+s.useCount*.3)*(1+Math.log1p(s.accessCount)*.1)-r}).slice(0,e)}getSummary(){let e=this.getTopMemories(15);if(e.length===0)return"";let t={};for(let r of e){let i=r.category;t[i]||(t[i]=[]),t[i].push(`${r.key}: ${r.value}`)}let s=["## Project Memory"];for(let[r,i]of Object.entries(t)){s.push(`### ${r}`);for(let o of i)s.push(`- ${o}`)}return s.join(`
843
- `)}getStats(){let e=this.getAll(),t={},s={};for(let r of e)t[r.category]=(t[r.category]||0)+1,s[r.createdBy]=(s[r.createdBy]||0)+1;return{totalEntries:e.length,byCategory:t,byAgent:s,topAccessed:e.sort((r,i)=>i.accessCount-r.accessCount).slice(0,5),recentlyAdded:e.sort((r,i)=>i.createdAt-r.createdAt).slice(0,5),totalAccessCount:e.reduce((r,i)=>r+i.accessCount,0)}}consolidate(e=200){if(this.entries.size<=e)return 0;let t=Array.from(this.entries.values()).filter(o=>o.importance<4&&o.accessCount<3).sort((o,a)=>o.updatedAt-a.updatedAt),s=t.slice(0,Math.max(10,t.length-e)),r={};for(let o of s){let a=o.category;r[a]||(r[a]=[]),r[a].push(o)}let i=0;for(let[o,a]of Object.entries(r)){if(a.length<2)continue;let l=`[consolidated] ${o} (${a.length} items)`,u=a.map(h=>`${h.key}: ${h.value}`).join("; "),d=a.map(h=>h.key);this.set(l,u.slice(0,500),{category:o,importance:3,tags:["consolidated"]});let f=this.entries.get(l);f&&(f.consolidatedFrom=d);for(let h of a)this.entries.delete(h.key),i++}return i>0&&this.save(),i}learnFromToolResult(e,t,s,r,i="hablas"){if(!(s.length<20)){if(!r){let o=`error:${e}:${JSON.stringify(t).slice(0,50)}`,a=this.entries.get(o);a?(a.useCount++,a.importance=Math.min(10,a.importance+1)):this.set(o,`${e} failed with: ${s.slice(0,200)}`,{category:"error",importance:6,createdBy:i,tags:["auto-learned","error",e]})}if(e==="list_dir"&&r){let o=t.path||".";this.set(`structure:${o}`,s.slice(0,300),{category:"pattern",importance:3,createdBy:i,tags:["auto-learned","structure"],relatedFiles:[o]})}}}size(){return this.entries.size}clear(){this.entries.clear(),this.agentLanes.clear(),this.save(),this.saveAgentLanes()}render(){if(this.getAll().length===0)return" No project memories stored";let t={convention:"\u{1F4CF}",decision:"\u{1F3AF}",pattern:"\u{1F504}",note:"\u{1F4DD}",error:"\u26A0\uFE0F","tool-result":"\u{1F527}","user-pref":"\u{1F464}",dependency:"\u{1F4E6}",performance:"\u26A1",security:"\u{1F512}",api:"\u{1F310}","agent-learning":"\u{1F916}"};return this.getTopMemories(20).map(i=>{let o=t[i.category]||"\xB7",a=i.importance>=7?" \u2605":"",l=i.useCount>0?` (used ${i.useCount}\xD7)`:"";return` ${o}${a} ${i.key}: ${i.value}${l}`}).join(`
844
- `)}autoImportance(e,t){let r={convention:6,decision:8,pattern:5,note:3,error:7,"tool-result":2,"user-pref":7,dependency:4,performance:5,security:9,api:6,"agent-learning":4}[e]||3;return/\b(important|critical|must|always|never|danger|warning|breaking)\b/i.test(t)&&(r=Math.min(10,r+2)),r}autoTag(e,t){let s=[t];return/\b(react|vue|angular|svelte|next|nuxt)\b/i.test(e)&&s.push("frontend"),/\b(express|fastify|nest|koa|hapi)\b/i.test(e)&&s.push("backend"),/\b(postgres|mysql|mongo|redis|sqlite)\b/i.test(e)&&s.push("database"),/\b(docker|kubernetes|k8s|ci\/cd|deploy)\b/i.test(e)&&s.push("devops"),/\b(test|jest|vitest|cypress|playwright)\b/i.test(e)&&s.push("testing"),/\b(auth|jwt|oauth|session|token)\b/i.test(e)&&s.push("auth"),/\b(api|endpoint|route|rest|graphql)\b/i.test(e)&&s.push("api"),s}extractFileRefs(e){let t=/[\w\-./]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|scss|html|vue|svelte|go|rs|java|sql|sh|toml|xml|env)/gi,s=e.match(t);return s?[...new Set(s)]:[]}load(){try{if(De.existsSync(this.filePath)){let e=JSON.parse(De.readFileSync(this.filePath,"utf-8"));if(Array.isArray(e))for(let t of e)t.importance||(t.importance=3),t.createdBy||(t.createdBy="hablas"),t.accessCount||(t.accessCount=0),t.useCount||(t.useCount=0),t.tags||(t.tags=[t.category||"note"]),t.relatedFiles||(t.relatedFiles=[]),t.lastAccessedAt||(t.lastAccessedAt=t.updatedAt||Date.now()),this.entries.set(t.key,t)}}catch{}this.loadAgentLanes()}save(){try{De.existsSync(On)||De.mkdirSync(On,{recursive:!0});let e=Array.from(this.entries.values());De.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf-8")}catch{}}loadAgentLanes(){try{if(De.existsSync(this.agentLanesPath)){let e=JSON.parse(De.readFileSync(this.agentLanesPath,"utf-8"));for(let[t,s]of Object.entries(e)){let r=new Map;for(let i of s)r.set(i.key,i);this.agentLanes.set(t,r)}}}catch{}}saveAgentLanes(){try{De.existsSync(On)||De.mkdirSync(On,{recursive:!0});let e={};for(let[t,s]of this.agentLanes)e[t]=Array.from(s.values());De.writeFileSync(this.agentLanesPath,JSON.stringify(e,null,2),"utf-8")}catch{}}}});var Ga=N((tR,Zp)=>{"use strict";var bs=n=>n&&typeof n.message=="string",Wa=n=>{if(!n)return;let e=n.cause;if(typeof e=="function"){let t=n.cause();return bs(t)?t:void 0}else return bs(e)?e:void 0},Xp=(n,e)=>{if(!bs(n))return"";let t=n.stack||"";if(e.has(n))return t+`
845
- causes have become circular...`;let s=Wa(n);return s?(e.add(n),t+`
846
- caused by: `+Xp(s,e)):t},fS=n=>Xp(n,new Set),Qp=(n,e,t)=>{if(!bs(n))return"";let s=t?"":n.message||"";if(e.has(n))return s+": ...";let r=Wa(n);if(r){e.add(n);let i=typeof n.cause=="function";return s+(i?"":": ")+Qp(r,e,i)}else return s},pS=n=>Qp(n,new Set);Zp.exports={isErrorLike:bs,getErrorCause:Wa,stackWithCauses:fS,messageWithCauses:pS}});var Va=N((nR,th)=>{"use strict";var hS=Symbol("circular-ref-tag"),Tr=Symbol("pino-raw-err-ref"),eh=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[Tr]},set:function(n){this[Tr]=n}}});Object.defineProperty(eh,Tr,{writable:!0,value:{}});th.exports={pinoErrProto:eh,pinoErrorSymbols:{seen:hS,rawSymbol:Tr}}});var rh=N((sR,sh)=>{"use strict";sh.exports=Ya;var{messageWithCauses:mS,stackWithCauses:gS,isErrorLike:nh}=Ga(),{pinoErrProto:yS,pinoErrorSymbols:bS}=Va(),{seen:za}=bS,{toString:vS}=Object.prototype;function Ya(n){if(!nh(n))return n;n[za]=void 0;let e=Object.create(yS);e.type=vS.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=mS(n),e.stack=gS(n),Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>Ya(t)));for(let t in n)if(e[t]===void 0){let s=n[t];nh(s)?t!=="cause"&&!Object.prototype.hasOwnProperty.call(s,za)&&(e[t]=Ya(s)):e[t]=s}return delete n[za],e.raw=n,e}});var oh=N((rR,ih)=>{"use strict";ih.exports=Or;var{isErrorLike:Ja}=Ga(),{pinoErrProto:wS,pinoErrorSymbols:xS}=Va(),{seen:Rr}=xS,{toString:SS}=Object.prototype;function Or(n){if(!Ja(n))return n;n[Rr]=void 0;let e=Object.create(wS);e.type=SS.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=n.message,e.stack=n.stack,Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>Or(t))),Ja(n.cause)&&!Object.prototype.hasOwnProperty.call(n.cause,Rr)&&(e.cause=Or(n.cause));for(let t in n)if(e[t]===void 0){let s=n[t];Ja(s)?Object.prototype.hasOwnProperty.call(s,Rr)||(e[t]=Or(s)):e[t]=s}return delete n[Rr],e.raw=n,e}});var uh=N((iR,ch)=>{"use strict";ch.exports={mapHttpRequest:_S,reqSerializer:lh};var Xa=Symbol("pino-raw-req-ref"),ah=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Xa]},set:function(n){this[Xa]=n}}});Object.defineProperty(ah,Xa,{writable:!0,value:{}});function lh(n){let e=n.info||n.socket,t=Object.create(ah);if(t.id=typeof n.id=="function"?n.id():n.id||(n.info?n.info.id:void 0),t.method=n.method,n.originalUrl)t.url=n.originalUrl;else{let s=n.path;t.url=typeof s=="string"?s:n.url?n.url.path||n.url:void 0}return n.query&&(t.query=n.query),n.params&&(t.params=n.params),t.headers=n.headers,t.remoteAddress=e&&e.remoteAddress,t.remotePort=e&&e.remotePort,t.raw=n.raw||n,t}function _S(n){return{req:lh(n)}}});var hh=N((oR,ph)=>{"use strict";ph.exports={mapHttpResponse:AS,resSerializer:fh};var Qa=Symbol("pino-raw-res-ref"),dh=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Qa]},set:function(n){this[Qa]=n}}});Object.defineProperty(dh,Qa,{writable:!0,value:{}});function fh(n){let e=Object.create(dh);return e.statusCode=n.headersSent?n.statusCode:null,e.headers=n.getHeaders?n.getHeaders():n._headers,e.raw=n,e}function AS(n){return{res:fh(n)}}});var el=N((aR,mh)=>{"use strict";var Za=rh(),kS=oh(),Pr=uh(),Mr=hh();mh.exports={err:Za,errWithCause:kS,mapHttpRequest:Pr.mapHttpRequest,mapHttpResponse:Mr.mapHttpResponse,req:Pr.reqSerializer,res:Mr.resSerializer,wrapErrorSerializer:function(e){return e===Za?e:function(s){return e(Za(s))}},wrapRequestSerializer:function(e){return e===Pr.reqSerializer?e:function(s){return e(Pr.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===Mr.resSerializer?e:function(s){return e(Mr.resSerializer(s))}}}});var tl=N((lR,gh)=>{"use strict";function $S(n,e){return e}gh.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=$S;let t=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let s=t.slice(2),r=[];for(let i of s)i&&r.push(i.getFileName());return r}});var Sh=N((cR,xh)=>{"use strict";function nl(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]=nl(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]=nl(n[t]));return e}return n}function yh(n){let e=[],t="",s=!1,r=!1,i="";for(let o=0;o<n.length;o++){let a=n[o];!s&&a==="."?t&&(e.push(t),t=""):a==="["?(t&&(e.push(t),t=""),s=!0):a==="]"&&s?(e.push(t),t="",s=!1,r=!1):(a==='"'||a==="'")&&s?r?a===i?(r=!1,i=""):t+=a:(r=!0,i=a):t+=a}return t&&e.push(t),e}function bh(n,e,t){let s=n;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof s!="object"||s===null||!(o in s)||typeof s[o]!="object"||s[o]===null)return!1;s=s[o]}let r=e[e.length-1];if(r==="*"){if(Array.isArray(s))for(let i=0;i<s.length;i++)s[i]=t;else if(typeof s=="object"&&s!==null)for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&(s[i]=t)}else typeof s=="object"&&s!==null&&r in s&&Object.prototype.hasOwnProperty.call(s,r)&&(s[r]=t);return!0}function vh(n,e){let t=n;for(let r=0;r<e.length-1;r++){let i=e[r];if(typeof t!="object"||t===null||!(i in t)||typeof t[i]!="object"||t[i]===null)return!1;t=t[i]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(t))for(let r=0;r<t.length;r++)t[r]=void 0;else if(typeof t=="object"&&t!==null)for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&delete t[r]}else typeof t=="object"&&t!==null&&s in t&&Object.prototype.hasOwnProperty.call(t,s)&&delete t[s];return!0}var Ir=Symbol("PATH_NOT_FOUND");function CS(n,e){let t=n;for(let s of e){if(t==null||typeof t!="object"||t===null||!(s in t))return Ir;t=t[s]}return t}function ES(n,e){let t=n;for(let s of e){if(t==null||typeof t!="object"||t===null)return;t=t[s]}return t}function TS(n,e,t,s=!1){for(let r of e){let i=yh(r);if(i.includes("*"))wh(n,i,t,r,s);else if(s)vh(n,i);else{let o=CS(n,i);if(o===Ir)continue;let a=typeof t=="function"?t(o,i):t;bh(n,i,a)}}}function wh(n,e,t,s,r=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=n;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(r)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let u=[...o,l.toString()],d=typeof t=="function"?t(a[l],u):t;a[l]=d}else if(typeof a=="object"&&a!==null)if(r){let l=[];for(let u in a)Object.prototype.hasOwnProperty.call(a,u)&&l.push(u);for(let u of l)delete a[u]}else for(let l in a){let u=[...o,l],d=typeof t=="function"?t(a[l],u):t;a[l]=d}}else RS(n,e,t,i,s,r)}function RS(n,e,t,s,r,i=!1){let o=e.slice(0,s),a=e.slice(s+1),l=[];function u(d,f){if(f===o.length){if(Array.isArray(d))for(let h=0;h<d.length;h++)l[f]=h.toString(),u(d[h],f+1);else if(typeof d=="object"&&d!==null)for(let h in d)l[f]=h,u(d[h],f+1)}else if(f<o.length){let h=o[f];d&&typeof d=="object"&&d!==null&&h in d&&(l[f]=h,u(d[h],f+1))}else if(a.includes("*"))wh(d,a,typeof t=="function"?(m,p)=>{let g=[...l.slice(0,f),...p];return t(m,g)}:t,r,i);else if(i)vh(d,a);else{let h=typeof t=="function"?t(ES(d,a),[...l.slice(0,f),...a]):t;bh(d,a,h)}}if(o.length===0)u(n,0);else{let d=n;for(let f=0;f<o.length;f++){let h=o[f];if(d==null||typeof d!="object"||d===null)return;d=d[h],l[f]=h}d!=null&&u(d,o.length)}}function OS(n){if(n.length===0)return null;let e=new Map;for(let t of n){let s=yh(t),r=e;for(let i=0;i<s.length;i++){let o=s[i];r.has(o)||r.set(o,new Map),r=r.get(o)}}return e}function PS(n,e){if(!e)return n;function t(s,r,i=0){if(!r||r.size===0||s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(Array.isArray(s)){let a=[];for(let l=0;l<s.length;l++){let u=l.toString();r.has(u)||r.has("*")?a[l]=t(s[l],r.get(u)||r.get("*")):a[l]=s[l]}return a}let o=Object.create(Object.getPrototypeOf(s));for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&(r.has(a)||r.has("*")?o[a]=t(s[a],r.get(a)||r.get("*")):o[a]=s[a]);return o}return t(n,e)}function MS(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 IS(n){if(!Array.isArray(n))throw new TypeError("paths must be an array");for(let e of n)MS(e)}function DS(n={}){let{paths:e=[],censor:t="[REDACTED]",serialize:s=JSON.stringify,strict:r=!0,remove:i=!1}=n;IS(e);let o=OS(e);return function(l){if(r&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return s?s(l):l;let u=PS(l,o),d=l,f=t;return typeof t=="function"&&(f=t),TS(u,e,f,i),s===!1?(u.restore=function(){return nl(d)},u):typeof s=="function"?s(u):JSON.stringify(u)}}xh.exports=DS});var Pn=N((uR,_h)=>{"use strict";var LS=Symbol("pino.setLevel"),FS=Symbol("pino.getLevel"),NS=Symbol("pino.levelVal"),jS=Symbol("pino.levelComp"),HS=Symbol("pino.useLevelLabels"),BS=Symbol("pino.useOnlyCustomLevels"),US=Symbol("pino.mixin"),qS=Symbol("pino.lsCache"),KS=Symbol("pino.chindings"),WS=Symbol("pino.asJson"),GS=Symbol("pino.write"),VS=Symbol("pino.redactFmt"),zS=Symbol("pino.time"),YS=Symbol("pino.timeSliceIndex"),JS=Symbol("pino.stream"),XS=Symbol("pino.stringify"),QS=Symbol("pino.stringifySafe"),ZS=Symbol("pino.stringifiers"),e_=Symbol("pino.end"),t_=Symbol("pino.formatOpts"),n_=Symbol("pino.messageKey"),s_=Symbol("pino.errorKey"),r_=Symbol("pino.nestedKey"),i_=Symbol("pino.nestedKeyStr"),o_=Symbol("pino.mixinMergeStrategy"),a_=Symbol("pino.msgPrefix"),l_=Symbol("pino.wildcardFirst"),c_=Symbol.for("pino.serializers"),u_=Symbol.for("pino.formatters"),d_=Symbol.for("pino.hooks"),f_=Symbol.for("pino.metadata");_h.exports={setLevelSym:LS,getLevelSym:FS,levelValSym:NS,levelCompSym:jS,useLevelLabelsSym:HS,mixinSym:US,lsCacheSym:qS,chindingsSym:KS,asJsonSym:WS,writeSym:GS,serializersSym:c_,redactFmtSym:VS,timeSym:zS,timeSliceIndexSym:YS,streamSym:JS,stringifySym:XS,stringifySafeSym:QS,stringifiersSym:ZS,endSym:e_,formatOptsSym:t_,messageKeySym:n_,errorKeySym:s_,nestedKeySym:r_,wildcardFirstSym:l_,needsMetadataGsym:f_,useOnlyCustomLevelsSym:BS,formattersSym:u_,hooksSym:d_,nestedKeyStrSym:i_,mixinMergeStrategySym:o_,msgPrefixSym:a_}});var rl=N((dR,Ch)=>{"use strict";var Ah=Sh(),{redactFmtSym:p_,wildcardFirstSym:Dr}=Pn(),sl=/[^.[\]]+|\[([^[\]]*?)\]/g,kh="[Redacted]",$h=!1;function h_(n,e){let{paths:t,censor:s,remove:r}=m_(n),i=t.reduce((l,u)=>{sl.lastIndex=0;let d=sl.exec(u),f=sl.exec(u),h=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(h==="*"&&(h=Dr),f===null)return l[h]=null,l;if(l[h]===null)return l;let{index:m}=f,p=`${u.substr(m,u.length-1)}`;return l[h]=l[h]||[],h!==Dr&&l[h].length===0&&l[h].push(...l[Dr]||[]),h===Dr&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(p)}),l[h].push(p),l},{}),o={[p_]:Ah({paths:t,censor:s,serialize:e,strict:$h,remove:r})},a=(...l)=>e(typeof s=="function"?s(...l):s);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,u)=>{if(i[u]===null)l[u]=d=>a(d,[u]);else{let d=typeof s=="function"?(f,h)=>s(f,[u,...h]):s;l[u]=Ah({paths:i[u],censor:d,serialize:e,strict:$h,remove:r})}return l},o)}function m_(n){if(Array.isArray(n))return n={paths:n,censor:kh},n;let{paths:e,censor:t=kh,remove:s}=n;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return s===!0&&(t=void 0),{paths:e,censor:t,remove:s}}Ch.exports=h_});var Rh=N((fR,Th)=>{"use strict";var g_=()=>"",y_=()=>`,"time":${Date.now()}`,b_=()=>`,"time":${Math.round(Date.now()/1e3)}`,v_=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,w_=1000000n,Eh=1000000000n,x_=BigInt(Date.now())*w_,S_=process.hrtime.bigint(),__=()=>{let n=process.hrtime.bigint()-S_,e=x_+n,t=e/Eh,s=e%Eh,r=Number(t*1000n+s/1000000n),i=new Date(r),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),u=i.getUTCHours().toString().padStart(2,"0"),d=i.getUTCMinutes().toString().padStart(2,"0"),f=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${u}:${d}:${f}.${s.toString().padStart(9,"0")}Z"`};Th.exports={nullTime:g_,epochTime:y_,unixTime:b_,isoTime:v_,isoTimeNano:__}});var Ph=N((pR,Oh)=>{"use strict";function A_(n){try{return JSON.stringify(n)}catch{return'"[Circular]"'}}Oh.exports=k_;function k_(n,e,t){var s=t&&t.stringify||A_,r=1;if(typeof n=="object"&&n!==null){var i=e.length+r;if(i===1)return n;var o=new Array(i);o[0]=s(n);for(var a=1;a<i;a++)o[a]=s(e[a]);return o.join(" ")}if(typeof n!="string")return n;var l=e.length;if(l===0)return n;for(var u="",d=1-r,f=-1,h=n&&n.length||0,m=0;m<h;){if(n.charCodeAt(m)===37&&m+1<h){switch(f=f>-1?f:0,n.charCodeAt(m+1)){case 100:case 102:if(d>=l||e[d]==null)break;f<m&&(u+=n.slice(f,m)),u+=Number(e[d]),f=m+2,m++;break;case 105:if(d>=l||e[d]==null)break;f<m&&(u+=n.slice(f,m)),u+=Math.floor(Number(e[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||e[d]===void 0)break;f<m&&(u+=n.slice(f,m));var p=typeof e[d];if(p==="string"){u+="'"+e[d]+"'",f=m+2,m++;break}if(p==="function"){u+=e[d].name||"<anonymous>",f=m+2,m++;break}u+=s(e[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=n.slice(f,m)),u+=String(e[d]),f=m+2,m++;break;case 37:f<m&&(u+=n.slice(f,m)),u+="%",f=m+2,m++,d--;break}++d}++m}return f===-1?n:(f<h&&(u+=n.slice(f)),u)}});var ol=N((hR,il)=>{"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));il.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(););};il.exports=n}});var Hh=N((mR,jh)=>{"use strict";var ce=require("fs"),$_=require("events"),C_=require("util").inherits,Mh=require("path"),ll=ol(),E_=require("assert"),Lr=100,Fr=Buffer.allocUnsafe(0),T_=16*1024,Ih="buffer",Dh="utf8",[R_,O_]=(process.versions.node||"0.0").split(".").map(Number),P_=R_>=22&&O_>=7;function Lh(n,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function t(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=n,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let s=e.append?"a":"w",r=e.mode;if(e.sync)try{e.mkdir&&ce.mkdirSync(Mh.dirname(n),{recursive:!0});let i=ce.openSync(n,s,r);t(null,i)}catch(i){throw t(i),i}else e.mkdir?ce.mkdir(Mh.dirname(n),{recursive:!0},i=>{if(i)return t(i);ce.open(n,s,r,t)}):ce.open(n,s,r,t)}function st(n){if(!(this instanceof st))return new st(n);let{fd:e,dest:t,minLength:s,maxLength:r,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:u,retryEAGAIN:d,fsync:f,contentMode:h,mode:m}=n||{};e=e||t,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(s||0,16387),this.file=null,this.destroyed=!1,this.minLength=s||0,this.maxLength=r||0,this.maxWrite=i||T_,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=f||!1,this.append=l||!1,this.mode=m,this.retryEAGAIN=d||(()=>!0),this.mkdir=u||!1;let p,g;if(h===Ih)this._writingBuf=Fr,this.write=D_,this.flush=F_,this.flushSync=j_,this._actualWrite=B_,p=()=>ce.writeSync(this.fd,this._writingBuf),g=()=>ce.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===Dh)this._writingBuf="",this.write=I_,this.flush=L_,this.flushSync=N_,this._actualWrite=H_,p=()=>Buffer.isBuffer(this._writingBuf)?ce.writeSync(this.fd,this._writingBuf):ce.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>Buffer.isBuffer(this._writingBuf)?ce.write(this.fd,this._writingBuf,this.release):ce.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Dh}" and "${Ih}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Lh(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(S,x)=>{if(S){if((S.code==="EAGAIN"||S.code==="EBUSY")&&this.retryEAGAIN(S,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{ll(Lr),this.release(void 0,0)}catch(y){this.release(y)}else setTimeout(g,Lr);else this._writing=!1,this.emit("error",S);return}this.emit("write",x);let $=al(this._writingBuf,this._len,x);if(this._len=$.len,this._writingBuf=$.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let y=p(),b=al(this._writingBuf,this._len,y);this._len=b.len,this._writingBuf=b.writingBuf}while(this._writingBuf.length)}catch(y){this.release(y);return}}this._fsync&&ce.fsyncSync(this.fd);let k=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):k>this.minLength?this._actualWrite():this._ending?k>0?this._actualWrite():(this._writing=!1,Nr(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(M_,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 al(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 M_(n){n.listenerCount("drain")>0&&(n._asyncDrainScheduled=!1,n.emit("drain"))}C_(st,$_);function Fh(n,e){return n.length===0?Fr:n.length===1?n[0]:Buffer.concat(n,e)}function I_(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 D_(n){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+n.length,t=this._bufs,s=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",n),this._len<this._hwm):(t.length===0||s[s.length-1]+n.length>this.maxWrite?(t.push([n]),s.push(n.length)):(t[t.length-1].push(n),s[s.length-1]+=n.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Nh(n){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,n();else try{ce.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 L_(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(n){n(e);return}throw e}if(this.minLength<=0){n?.();return}n&&Nh.call(this,n),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function F_(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(n){n(e);return}throw e}if(this.minLength<=0){n?.();return}n&&Nh.call(this,n),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}st.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&&ce.close(e,t=>{if(t)return this.emit("error",t)})}),Lh(this.file,this)};st.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 N_(){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)?ce.writeSync(this.fd,n):ce.writeSync(this.fd,n,"utf8"),t=al(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;ll(Lr)}}try{ce.fsyncSync(this.fd)}catch{}}function j_(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=Fr);let n=Fr;for(;this._bufs.length||n.length;){n.length<=0&&(n=Fh(this._bufs[0],this._lens[0]));try{let e=ce.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;ll(Lr)}}}st.prototype.destroy=function(){this.destroyed||Nr(this)};function H_(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?ce.writeSync(this.fd,this._writingBuf):ce.writeSync(this.fd,this._writingBuf,"utf8");n(null,e)}catch(e){n(e)}else ce.write(this.fd,this._writingBuf,n)}function B_(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Fh(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=ce.writeSync(this.fd,this._writingBuf);n(null,e)}catch(e){n(e)}else P_&&(this._writingBuf=Buffer.from(this._writingBuf)),ce.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=[],E_(typeof n.fd=="number",`sonic.fd must be a number, got ${typeof n.fd}`);try{ce.fsync(n.fd,e)}catch{}function e(){n.fd!==1&&n.fd!==2?ce.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")}}st.SonicBoom=st;st.default=st;jh.exports=st});var cl=N((gR,Wh)=>{"use strict";var rt={exit:[],beforeExit:[]},Bh={exit:K_,beforeExit:W_},Mn;function U_(){Mn===void 0&&(Mn=new FinalizationRegistry(G_))}function q_(n){rt[n].length>0||process.on(n,Bh[n])}function Uh(n){rt[n].length>0||(process.removeListener(n,Bh[n]),rt.exit.length===0&&rt.beforeExit.length===0&&(Mn=void 0))}function K_(){qh("exit")}function W_(){qh("beforeExit")}function qh(n){for(let e of rt[n]){let t=e.deref(),s=e.fn;t!==void 0&&s(t,n)}rt[n]=[]}function G_(n){for(let e of["exit","beforeExit"]){let t=rt[e].indexOf(n);rt[e].splice(t,t+1),Uh(e)}}function Kh(n,e,t){if(e===void 0)throw new Error("the object can't be undefined");q_(n);let s=new WeakRef(e);s.fn=t,U_(),Mn.register(e,s),rt[n].push(s)}function V_(n,e){Kh("exit",n,e)}function z_(n,e){Kh("beforeExit",n,e)}function Y_(n){if(Mn!==void 0){Mn.unregister(n);for(let e of["exit","beforeExit"])rt[e]=rt[e].filter(t=>{let s=t.deref();return s&&s!==n}),Uh(e)}}Wh.exports={register:V_,registerBeforeExit:z_,unregister:Y_}});var Gh=N((yR,J_)=>{J_.exports={name:"thread-stream",version:"4.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",engines:{node:">=20"},dependencies:{"real-require":"^1.0.0"},devDependencies:{"@types/node":"^25.0.2","@yao-pkg/pkg":"^6.0.0",borp:"^1.0.0",desm:"^1.3.0",eslint:"^9.39.1",fastbench:"^1.0.1",neostandard:"^0.13.0","pino-elasticsearch":"^9.0.0","sonic-boom":"^5.0.0","ts-node":"^10.8.0",typescript:"~5.7.3"},scripts:{build:"tsc --noEmit",lint:"eslint",test:'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:ci":'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:yarn":'npm run transpile && borp --pattern "test/*.test.js"',transpile:"sh ./test/ts/transpile.sh"},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina <hello@matteocollina.com>",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var zh=N((bR,Vh)=>{"use strict";function X_(n,e,t,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{let a=Atomics.load(n,e);if(a===t){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),u=Atomics.waitAsync(n,e,a,l);u.async?u.value.then(o):setImmediate(o)};o()}function Q_(n,e,t,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{if(Atomics.load(n,e)!==t){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),u=Atomics.waitAsync(n,e,t,l);u.async?u.value.then(d=>{if(d==="ok"){r(null,"ok");return}o()}):setImmediate(o)};o()}Vh.exports={wait:X_,waitDiff:Q_}});var Jh=N((vR,Yh)=>{"use strict";Yh.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var lm=N((wR,am)=>{"use strict";var{version:Z_}=Gh(),{EventEmitter:eA}=require("events"),{Worker:tA}=require("worker_threads"),{join:nA}=require("path"),{pathToFileURL:sA}=require("url"),{wait:rA}=zh(),{WRITE_INDEX:Mt,READ_INDEX:an,SEQ_INDEX:ul}=Jh(),iA=require("buffer"),oA=require("assert"),R=Symbol("kImpl"),aA=iA.constants.MAX_STRING_LENGTH;function Xh(){}function hl(n,e){Atomics.add(n[R].state,ul,1),e(),Atomics.add(n[R].state,ul,1),Atomics.notify(n[R].state,ul)}function Qh(n){hl(n,()=>{Atomics.store(n[R].state,an,0),Atomics.store(n[R].state,Mt,0)})}var vs=class{constructor(e){this._value=e}deref(){return this._value}},jr=class{register(){}unregister(){}},lA=process.env.NODE_V8_COVERAGE?jr:global.FinalizationRegistry||jr,cA=process.env.NODE_V8_COVERAGE?vs:global.WeakRef||vs,Zh=new lA(n=>{n.exited||n.terminate()});function uA(n,e){let{filename:t,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||nA(__dirname,"lib","worker.js"),o=new tA(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:t.indexOf("file://")===0?t:sA(t).href,dataBuf:n[R].dataBuf,stateBuf:n[R].stateBuf,workerData:{$context:{threadStreamVersion:Z_},...s}}});return o.stream=new vs(n),o.on("message",dA),o.on("exit",nm),Zh.register(n,o),o}function em(n){oA(!n[R].sync),n[R].needDrain&&(n[R].needDrain=!1,n.emit("drain"))}function tm(n){for(;;){let e=Atomics.load(n[R].state,Mt),t=n[R].data.length-e;if(t>0){if(n[R].bufLen===0){n[R].flushing=!1,n[R].ending?ml(n):n[R].needDrain&&process.nextTick(em,n);return}im(n,t,Xh);continue}if(t===0){if(e===0&&n[R].bufLen===0)return;Hr(n,()=>{n.destroyed||(Qh(n),tm(n))});return}Je(n,new Error("overwritten"));return}}function dA(n){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(n?.code!=null)switch(n.code){case"READY":this.stream=new cA(e),Hr(e,()=>{e[R].ready=!0,e.emit("ready")});break;case"ERROR":Je(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"){Je(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:Je(e,new Error("this should not happen: "+n.code))}}function nm(n){let e=this.stream.deref();e!==void 0&&(Zh.unregister(e),e.worker.exited=!0,e.worker.off("exit",nm),Je(e,n!==0?new Error("the worker thread exited"):null))}var fl=class extends eA{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[R]={},this[R].stateBuf=new SharedArrayBuffer(128),this[R].state=new Int32Array(this[R].stateBuf),this[R].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[R].data=Buffer.from(this[R].dataBuf),this[R].sync=e.sync||!1,this[R].ending=!1,this[R].ended=!1,this[R].needDrain=!1,this[R].destroyed=!1,this[R].flushing=!1,this[R].ready=!1,this[R].finished=!1,this[R].errored=null,this[R].closed=!1,this[R].buf=[],this[R].bufHead=0,this[R].bufLen=0,this[R].flushCallbacks=new Map,this[R].nextFlushId=0,this.worker=uA(this,e),this.on("message",(t,s)=>{this.worker.postMessage(t,s)})}write(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[R].destroyed)return pl(this,new Error("the worker has exited")),!1;if(this[R].ending)return pl(this,new Error("the worker is ending")),!1;if(this[R].flushing&&this[R].bufLen+t.length>=aA)try{dl(this),this[R].flushing=!0}catch(s){return Je(this,s),!1}if(this[R].buf.push(t),this[R].bufLen+=t.length,this[R].sync)try{return dl(this),!0}catch(s){return Je(this,s),!1}return this[R].flushing||(this[R].flushing=!0,setImmediate(tm,this)),this[R].needDrain=this[R].data.length-this[R].bufLen-Atomics.load(this[R].state,Mt)<=0,!this[R].needDrain}end(){this[R].destroyed||(this[R].ending=!0,ml(this))}flush(e){e=typeof e=="function"?e:Xh,sm(this,t=>{if(t){process.nextTick(e,t);return}rm(this,e)})}flushSync(){this[R].destroyed||(dl(this),om(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[R].ready}get destroyed(){return this[R].destroyed}get closed(){return this[R].closed}get writable(){return!this[R].destroyed&&!this[R].ending}get writableEnded(){return this[R].ending}get writableFinished(){return this[R].finished}get writableNeedDrain(){return this[R].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[R].errored}};function sm(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].sync&&(n[R].flushing||n[R].bufLen>0)){setImmediate(sm,n,e);return}Hr(n,e)}function Hr(n,e){let t=Atomics.load(n[R].state,Mt);rA(n[R].state,an,t,1/0,(s,r)=>{if(s){Je(n,s),e(s);return}if(r!=="ok"){Hr(n,e);return}e()})}function rm(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].ready){let s=()=>{i(),rm(n,e)},r=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{n.off("ready",s),n.off("close",r)};n.once("ready",s),n.once("close",r);return}let t=++n[R].nextFlushId;n[R].flushCallbacks.set(t,e);try{n.worker.postMessage({code:"FLUSH",context:"thread-stream",id:t})}catch(s){n[R].flushCallbacks.delete(t),Je(n,s),process.nextTick(e,s)}}function fA(n,e){let t=n[R].flushCallbacks;if(t.size===0)return;let s=e||new Error("the worker has exited");for(let r of t.values())process.nextTick(r,s);t.clear()}function pl(n,e){setImmediate(()=>{n.emit("error",e)})}function Je(n,e){n[R].destroyed||(n[R].destroyed=!0,fA(n,e),e&&(n[R].errored=e,pl(n,e)),n.worker.exited?setImmediate(()=>{n[R].closed=!0,n.emit("close")}):n.worker.terminate().catch(()=>{}).then(()=>{n[R].closed=!0,n.emit("close")}))}function im(n,e,t){let r=Atomics.load(n[R].state,Mt),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 hl(n,()=>{Atomics.store(n[R].state,Mt,r)}),t(),!0}function ml(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,an);hl(n,()=>{Atomics.store(n[R].state,Mt,-1)});let t=0;for(;e!==-1;){if(Atomics.wait(n[R].state,an,e,1e3),e=Atomics.load(n[R].state,an),e===-2){Je(n,new Error("end() failed"));return}if(++t===10){Je(n,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{n[R].finished=!0,n.emit("finish")})}catch(e){Je(n,e)}}}function dl(n){let e=()=>{n[R].ending?ml(n):n[R].needDrain&&process.nextTick(em,n)};for(n[R].flushing=!1;n[R].bufLen!==0;){let t=Atomics.load(n[R].state,Mt),s=n[R].data.length-t;if(s===0){om(n),Qh(n);continue}else if(s<0)throw new Error("overwritten");im(n,s,e)}}function om(n){if(n[R].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(n[R].state,Mt),t=0;for(;;){let s=Atomics.load(n[R].state,an);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(n[R].state,an,s,1e3);else break;if(++t===10)throw new Error("_flushSync took too long (10s)")}}am.exports=fl});var bl=N((xR,dm)=>{"use strict";var{createRequire:pA}=require("module"),{existsSync:hA}=require("node:fs"),mA=tl(),{join:gl,isAbsolute:um,sep:gA}=require("node:path"),{fileURLToPath:yA}=require("node:url"),bA=ol(),yl=cl(),vA=lm();function wA(n){yl.register(n,kA),yl.registerBeforeExit(n,$A),n.on("close",function(){yl.unregister(n)})}function xA(){let n=process.execArgv;for(let e=0;e<n.length;e++){let t=n[e];if(t==="--import"||t==="--require"||t==="-r"||t.startsWith("--import=")||t.startsWith("--require=")||t.startsWith("-r="))return!0}return!1}function SA(n){let e=n.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return n;let t=[],s=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i==="--require"||i==="-r"||i==="--import"){let o=e[r+1];if(o&&cm(o)){s=!0,r++;continue}t.push(i),o&&(t.push(o),r++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(cm(o)){s=!0;continue}}t.push(i)}return s?t.join(" "):n}function cm(n){let e=_A(n);if(!e)return!1;let t=e;if(t.startsWith("file://"))try{t=yA(t)}catch{return!1}return um(t)&&!hA(t)}function _A(n){let e=n[0],t=n[n.length-1];return e==='"'&&t==='"'||e==="'"&&t==="'"?n.slice(1,-1):n}function AA(n,e,t,s,r){if(!t.execArgv&&xA()&&require.main===void 0&&(t={...t,execArgv:[]}),!t.env&&process.env.NODE_OPTIONS){let l=SA(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(t={...t,env:{...process.env,NODE_OPTIONS:l}})}t={...t,name:r};let i=new vA({filename:n,workerData:e,workerOpts:t,sync:s});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),t.autoEnd!==!1&&wA(i)}function a(){i.closed||(i.flushSync(),bA(100),i.end())}return i}function kA(n){n.ref(),n.flushSync(),n.end(),n.once("close",function(){n.unref()})}function $A(n){n.flushSync()}function CA(n){let{pipeline:e,targets:t,levels:s,dedupe:r,worker:i={},caller:o=mA(),sync:a=!1}=n,l={...n.options},u=typeof o=="string"?[o]:o,d=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),f=n.target;if(f&&t)throw new Error("only one of target or targets can be specified");t?(f=d["pino-worker"]||gl(__dirname,"worker.js"),l.targets=t.filter(p=>p.target).map(p=>({...p,target:m(p.target)})),l.pipelines=t.filter(p=>p.pipeline).map(p=>p.pipeline.map(g=>({...g,level:p.level,target:m(g.target)})))):e&&(f=d["pino-worker"]||gl(__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 AA(m(f),l,i,a,h);function m(p){if(p=d[p]||p,um(p)||p.indexOf("file://")===0)return p;if(p==="pino/file")return gl(__dirname,"..","file.js");let g;for(let S of u)try{let x=S==="node:repl"?process.cwd()+gA:S;g=pA(x).resolve(p);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${p}"`);return g}}dm.exports=CA});var qr=N((SR,Am)=>{"use strict";var EA=require("node:diagnostics_channel"),fm=Ph(),{mapHttpRequest:TA,mapHttpResponse:RA}=el(),wl=Hh(),pm=cl(),{lsCacheSym:OA,chindingsSym:bm,writeSym:hm,serializersSym:vm,formatOptsSym:mm,endSym:PA,stringifiersSym:wm,stringifySym:xm,stringifySafeSym:xl,wildcardFirstSym:Sm,nestedKeySym:MA,formattersSym:_m,messageKeySym:IA,errorKeySym:DA,nestedKeyStrSym:LA,msgPrefixSym:Br}=Pn(),{isMainThread:FA}=require("worker_threads"),NA=bl(),[jA]=process.versions.node.split(".").map(n=>Number(n)),gm=EA.tracingChannel("pino_asJson"),vl=jA>=25?n=>JSON.stringify(n):BA;function In(){}function HA(n,e){if(!e)return t;return function(...r){e.call(this,r,t,n)};function t(s,...r){if(typeof s=="object"){let i=s;s!==null&&(s.method&&s.headers&&s.socket?s=TA(s):typeof s.setHeader=="function"&&(s=RA(s)));let o;i===null&&r.length===0?o=[null]:(i=r.shift(),o=r),typeof this[Br]=="string"&&i!==void 0&&i!==null&&(i=this[Br]+i),this[hm](s,fm(i,o,this[mm]),n)}else{let i=s===void 0?r.shift():s;typeof this[Br]=="string"&&i!==void 0&&i!==null&&(i=this[Br]+i),this[hm](null,fm(i,r,this[mm]),n)}}}function BA(n){let e="",t=0,s=!1,r=255,i=n.length;if(i>100)return JSON.stringify(n);for(var o=0;o<i&&r>=32;o++)r=n.charCodeAt(o),(r===34||r===92)&&(e+=n.slice(t,o)+"\\",t=o,s=!0);return s?e+=n.slice(t):e=n,r<32?JSON.stringify(n):'"'+e+'"'}function UA(n,e,t,s){if(gm.hasSubscribers===!1)return ym.call(this,n,e,t,s);let r={instance:this,arguments};return gm.traceSync(ym,r,this,n,e,t,s)}function ym(n,e,t,s){let r=this[xm],i=this[xl],o=this[wm],a=this[PA],l=this[bm],u=this[vm],d=this[_m],f=this[IA],h=this[DA],m=this[OA][t]+s;m=m+l;let p;d.log&&(n=d.log(n));let g=o[Sm],S="";for(let $ in n)if(p=n[$],Object.prototype.hasOwnProperty.call(n,$)&&p!==void 0){u[$]?p=u[$](p):$===h&&u.err&&(p=u.err(p));let k=o[$]||g;switch(typeof p){case"undefined":case"function":continue;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":k&&(p=k(p));break;case"string":p=(k||vl)(p);break;default:p=(k||r)(p,i)}if(p===void 0)continue;let y=vl($);S+=","+y+":"+p}let x="";if(e!==void 0){p=u[f]?u[f](e):e;let $=o[f]||g;switch(typeof p){case"function":break;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":$&&(p=$(p)),x=',"'+f+'":'+p;break;case"string":p=($||vl)(p),x=',"'+f+'":'+p;break;default:p=($||r)(p,i),x=',"'+f+'":'+p}}return this[MA]&&S?m+this[LA]+S.slice(1)+"}"+x+a:m+S+x+a}function qA(n,e){let t,s=n[bm],r=n[xm],i=n[xl],o=n[wm],a=o[Sm],l=n[vm],u=n[_m].bindings;e=u(e);for(let d in e)if(t=e[d],((d.length<5||d!=="level"&&d!=="serializers"&&d!=="formatters"&&d!=="customLevels")&&e.hasOwnProperty(d)&&t!==void 0)===!0){if(t=l[d]?l[d](t):t,t=(o[d]||a||r)(t,i),t===void 0)continue;s+=',"'+d+'":'+t}return s}function KA(n){return n.write!==n.constructor.prototype.write}function Ur(n){let e=new wl(n);return e.on("error",t),!n.sync&&FA&&(pm.register(e,WA),e.on("close",function(){pm.unregister(e)})),e;function t(s){if(s.code==="EPIPE"){e.write=In,e.end=In,e.flushSync=In,e.destroy=In;return}e.removeListener("error",t),e.emit("error",s)}}function WA(n,e){n.destroyed||(e==="beforeExit"?(n.flush(),n.on("drain",function(){n.end()})):n.flushSync())}function GA(n){return function(t,s,r={},i){if(typeof r=="string")i=Ur({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=Ur({dest:i})}else if(r instanceof wl||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof wl||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=NA({caller:s,...r.transport,levels:l})}if(r=Object.assign({},n,r),r.serializers=Object.assign({},n.serializers,r.serializers),r.formatters=Object.assign({},n.formatters,r.formatters),r.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=r;return o===!1&&(r.level="silent"),a||(r.onChild=In),i||(KA(process.stdout)?i=process.stdout:i=Ur({fd:process.stdout.fd||1})),{opts:r,stream:i}}}function VA(n,e){try{return JSON.stringify(n)}catch{try{return(e||this[xl])(n)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function zA(n,e,t){return{level:n,bindings:e,log:t}}function YA(n){let e=Number(n);return typeof n=="string"&&Number.isFinite(e)?e:n===void 0?1:n}Am.exports={noop:In,buildSafeSonicBoom:Ur,asChindings:qA,asJson:UA,genLog:HA,createArgsNormalizer:GA,stringify:VA,buildFormatters:zA,normalizeDestFileDescriptor:YA}});var Kr=N((_R,km)=>{var JA={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},XA={ASC:"ASC",DESC:"DESC"};km.exports={DEFAULT_LEVELS:JA,SORTING_ORDER:XA}});var Al=N((AR,Tm)=>{"use strict";var{lsCacheSym:QA,levelValSym:Sl,useOnlyCustomLevelsSym:ZA,streamSym:ek,formattersSym:tk,hooksSym:nk,levelCompSym:$m}=Pn(),{noop:sk,genLog:ln}=qr(),{DEFAULT_LEVELS:yt,SORTING_ORDER:Cm}=Kr(),Em={fatal:n=>{let e=ln(yt.fatal,n);return function(...t){let s=this[ek];if(e.call(this,...t),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:n=>ln(yt.error,n),warn:n=>ln(yt.warn,n),info:n=>ln(yt.info,n),debug:n=>ln(yt.debug,n),trace:n=>ln(yt.trace,n)},_l=Object.keys(yt).reduce((n,e)=>(n[yt[e]]=e,n),{}),rk=Object.keys(_l).reduce((n,e)=>(n[e]='{"level":'+Number(e),n),{});function ik(n){let e=n[tk].level,{labels:t}=n.levels,s={};for(let r in t){let i=e(t[r],Number(r));s[r]=JSON.stringify(i).slice(0,-1)}return n[QA]=s,n}function ok(n,e){if(e)return!1;switch(n){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function ak(n){let{labels:e,values:t}=this.levels;if(typeof n=="number"){if(e[n]===void 0)throw Error("unknown level value"+n);n=e[n]}if(t[n]===void 0)throw Error("unknown level "+n);let s=this[Sl],r=this[Sl]=t[n],i=this[ZA],o=this[$m],a=this[nk].logMethod;for(let l in t){if(o(t[l],r)===!1){this[l]=sk;continue}this[l]=ok(l,i)?Em[l](a):ln(t[l],a)}this.emit("level-change",n,r,e[s],s,this)}function lk(n){let{levels:e,levelVal:t}=this;return e&&e.labels?e.labels[t]:""}function ck(n){let{values:e}=this.levels,t=e[n];return t!==void 0&&this[$m](t,this[Sl])}function uk(n,e,t){return n===Cm.DESC?e<=t:e>=t}function dk(n){return typeof n=="string"?uk.bind(null,n):n}function fk(n=null,e=!1){let t=n?Object.keys(n).reduce((i,o)=>(i[n[o]]=o,i),{}):null,s=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:_l,t),r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:yt,n);return{labels:s,values:r}}function pk(n,e,t){if(typeof n=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),t?[]:Object.keys(_l).map(i=>+i),1/0).includes(n))throw Error(`default level:${n} must be included in custom levels`);return}let s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:yt,e);if(!(n in s))throw Error(`default level:${n} must be included in custom levels`)}function hk(n,e){let{labels:t,values:s}=n;for(let r in e){if(r in s)throw Error("levels cannot be overridden");if(e[r]in t)throw Error("pre-existing level values cannot be used for new levels")}}function mk(n){if(typeof n!="function"&&!(typeof n=="string"&&Object.values(Cm).includes(n)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Tm.exports={initialLsCache:rk,genLsCache:ik,levelMethods:Em,getLevel:lk,setLevel:ak,isLevelEnabled:ck,mappings:fk,assertNoLevelCollisions:hk,assertDefaultLevelFound:pk,genLevelComparison:dk,assertLevelComparison:mk}});var kl=N((kR,Rm)=>{"use strict";Rm.exports={version:"10.3.1"}});var Nm=N((CR,Fm)=>{"use strict";var{EventEmitter:gk}=require("node:events"),{lsCacheSym:yk,levelValSym:bk,setLevelSym:Cl,getLevelSym:Om,chindingsSym:Gr,mixinSym:vk,asJsonSym:Mm,writeSym:wk,mixinMergeStrategySym:xk,timeSym:Sk,timeSliceIndexSym:_k,streamSym:Im,serializersSym:cn,formattersSym:ws,errorKeySym:Ak,messageKeySym:kk,useOnlyCustomLevelsSym:$k,needsMetadataGsym:Ck,redactFmtSym:Ek,stringifySym:Tk,formatOptsSym:Rk,stringifiersSym:Ok,msgPrefixSym:El,hooksSym:Pk}=Pn(),{getLevel:Mk,setLevel:Ik,isLevelEnabled:Dk,mappings:Lk,initialLsCache:Fk,genLsCache:Nk,assertNoLevelCollisions:jk}=Al(),{asChindings:Tl,asJson:Hk,buildFormatters:$l,stringify:Pm,noop:Dm}=qr(),{version:Bk}=kl(),Uk=rl(),qk=class{},Lm={constructor:qk,child:Kk,bindings:Wk,setBindings:Gk,flush:Yk,isLevelEnabled:Dk,version:Bk,get level(){return this[Om]()},set level(n){this[Cl](n)},get levelVal(){return this[bk]},set levelVal(n){throw Error("levelVal is read-only")},get msgPrefix(){return this[El]},get[Symbol.toStringTag](){return"Pino"},[yk]:Fk,[wk]:zk,[Mm]:Hk,[Om]:Mk,[Cl]:Ik};Object.setPrototypeOf(Lm,gk.prototype);Fm.exports=function(){return Object.create(Lm)};var Wr=n=>n;function Kk(n,e){if(!n)throw Error("missing bindings for child Pino");let t=this[cn],s=this[ws],r=Object.create(this);if(e==null)return r[ws].bindings!==Wr&&(r[ws]=$l(s.level,Wr,s.log)),r[Gr]=Tl(r,n),this.onChild!==Dm&&this.onChild(r),r;if(e.hasOwnProperty("serializers")===!0){r[cn]=Object.create(null);for(let u in t)r[cn][u]=t[u];let a=Object.getOwnPropertySymbols(t);for(var i=0;i<a.length;i++){let u=a[i];r[cn][u]=t[u]}for(let u in e.serializers)r[cn][u]=e.serializers[u];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let u=l[o];r[cn][u]=e.serializers[u]}}else r[cn]=t;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:u}=e.formatters;r[ws]=$l(a||s.level,l||Wr,u||s.log)}else r[ws]=$l(s.level,Wr,s.log);if(e.hasOwnProperty("customLevels")===!0&&(jk(this.levels,e.customLevels),r.levels=Lk(e.customLevels,r[$k]),Nk(r)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){r.redact=e.redact;let a=Uk(r.redact,Pm),l={stringify:a[Ek]};r[Tk]=Pm,r[Ok]=a,r[Rk]=l}if(typeof e.msgPrefix=="string"&&(r[El]=(this[El]||"")+e.msgPrefix),r[Gr]=Tl(r,n),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;r[Cl](a)}return this.onChild(r),r}function Wk(){let e=`{${this[Gr].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function Gk(n){let e=Tl(this,n);this[Gr]=e}function Vk(n,e){return Object.assign(e,n)}function zk(n,e,t){let s=this[Sk](),r=this[vk],i=this[Ak],o=this[kk],a=this[xk]||Vk,l,u=this[Pk].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[Mm](l,e,t,s),f=this[Im];f[Ck]===!0&&(f.lastLevel=t,f.lastObj=l,f.lastMsg=e,f.lastTime=s.slice(this[_k]),f.lastLogger=this),f.write(u?u(d):d)}function Yk(n){if(n!=null&&typeof n!="function")throw Error("callback must be a function");let e=this[Im];typeof e.flush=="function"?e.flush(n||Dm):n&&n()}});var Um=N((Ml,Bm)=>{"use strict";var{hasOwnProperty:xs}=Object.prototype,dn=Pl();dn.configure=Pl;dn.stringify=dn;dn.default=dn;Ml.stringify=dn;Ml.configure=Pl;Bm.exports=dn;var Jk=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function qt(n){return n.length<5e3&&!Jk.test(n)?`"${n}"`:JSON.stringify(n)}function Rl(n,e){if(n.length>200||e)return n.sort(e);for(let t=1;t<n.length;t++){let s=n[t],r=t;for(;r!==0&&n[r-1]>s;)n[r]=n[r-1],r--;n[r]=s}return n}var Xk=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Ol(n){return Xk.call(n)!==void 0&&n.length!==0}function jm(n,e,t){n.length<t&&(t=n.length);let s=e===","?"":" ",r=`"0":${s}${n[0]}`;for(let i=1;i<t;i++)r+=`${e}"${i}":${s}${n[i]}`;return r}function Qk(n){if(xs.call(n,"circularValue")){let e=n.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function Zk(n){let e;if(xs.call(n,"deterministic")&&(e=n.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function e$(n,e){let t;if(xs.call(n,e)&&(t=n[e],typeof t!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return t===void 0?!0:t}function Hm(n,e){let t;if(xs.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 un(n){return n===1?"1 item":`${n} items`}function t$(n){let e=new Set;for(let t of n)(typeof t=="string"||typeof t=="number")&&e.add(String(t));return e}function n$(n){if(xs.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 Pl(n){n={...n};let e=n$(n);e&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let t=Qk(n),s=e$(n,"bigint"),r=Zk(n),i=typeof r=="function"?r:void 0,o=Hm(n,"maximumDepth"),a=Hm(n,"maximumBreadth");function l(m,p,g,S,x,$){let k=p[m];switch(typeof k=="object"&&k!==null&&typeof k.toJSON=="function"&&(k=k.toJSON(m)),k=S.call(p,m,k),typeof k){case"string":return qt(k);case"object":{if(k===null)return"null";if(g.indexOf(k)!==-1)return t;let y="",b=",",v=$;if(Array.isArray(k)){if(k.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(k),x!==""&&($+=x,y+=`
847
- ${$}`,b=`,
848
- ${$}`);let F=Math.min(k.length,a),H=0;for(;H<F-1;H++){let E=l(String(H),k,g,S,x,$);y+=E!==void 0?E:"null",y+=b}let W=l(String(H),k,g,S,x,$);if(y+=W!==void 0?W:"null",k.length-1>a){let E=k.length-a-1;y+=`${b}"... ${un(E)} not stringified"`}return x!==""&&(y+=`
849
- ${v}`),g.pop(),`[${y}]`}let w=Object.keys(k),_=w.length;if(_===0)return"{}";if(o<g.length+1)return'"[Object]"';let T="",P="";x!==""&&($+=x,b=`,
850
- ${$}`,T=" ");let C=Math.min(_,a);r&&!Ol(k)&&(w=Rl(w,i)),g.push(k);for(let F=0;F<C;F++){let H=w[F],W=l(H,k,g,S,x,$);W!==void 0&&(y+=`${P}${qt(H)}:${T}${W}`,P=b)}if(_>a){let F=_-a;y+=`${P}"...":${T}"${un(F)} not stringified"`,P=b}return x!==""&&P.length>1&&(y=`
851
- ${$}${y}
852
- ${v}`),g.pop(),`{${y}}`}case"number":return isFinite(k)?String(k):e?e(k):"null";case"boolean":return k===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(k);default:return e?e(k):void 0}}function u(m,p,g,S,x,$){switch(typeof p=="object"&&p!==null&&typeof p.toJSON=="function"&&(p=p.toJSON(m)),typeof p){case"string":return qt(p);case"object":{if(p===null)return"null";if(g.indexOf(p)!==-1)return t;let k=$,y="",b=",";if(Array.isArray(p)){if(p.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(p),x!==""&&($+=x,y+=`
853
- ${$}`,b=`,
854
- ${$}`);let _=Math.min(p.length,a),T=0;for(;T<_-1;T++){let C=u(String(T),p[T],g,S,x,$);y+=C!==void 0?C:"null",y+=b}let P=u(String(T),p[T],g,S,x,$);if(y+=P!==void 0?P:"null",p.length-1>a){let C=p.length-a-1;y+=`${b}"... ${un(C)} not stringified"`}return x!==""&&(y+=`
855
- ${k}`),g.pop(),`[${y}]`}g.push(p);let v="";x!==""&&($+=x,b=`,
856
- ${$}`,v=" ");let w="";for(let _ of S){let T=u(_,p[_],g,S,x,$);T!==void 0&&(y+=`${w}${qt(_)}:${v}${T}`,w=b)}return x!==""&&w.length>1&&(y=`
857
- ${$}${y}
858
- ${k}`),g.pop(),`{${y}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function d(m,p,g,S,x){switch(typeof p){case"string":return qt(p);case"object":{if(p===null)return"null";if(typeof p.toJSON=="function"){if(p=p.toJSON(m),typeof p!="object")return d(m,p,g,S,x);if(p===null)return"null"}if(g.indexOf(p)!==-1)return t;let $=x;if(Array.isArray(p)){if(p.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(p),x+=S;let T=`
859
- ${x}`,P=`,
860
- ${x}`,C=Math.min(p.length,a),F=0;for(;F<C-1;F++){let W=d(String(F),p[F],g,S,x);T+=W!==void 0?W:"null",T+=P}let H=d(String(F),p[F],g,S,x);if(T+=H!==void 0?H:"null",p.length-1>a){let W=p.length-a-1;T+=`${P}"... ${un(W)} not stringified"`}return T+=`
861
- ${$}`,g.pop(),`[${T}]`}let k=Object.keys(p),y=k.length;if(y===0)return"{}";if(o<g.length+1)return'"[Object]"';x+=S;let b=`,
862
- ${x}`,v="",w="",_=Math.min(y,a);Ol(p)&&(v+=jm(p,b,a),k=k.slice(p.length),_-=p.length,w=b),r&&(k=Rl(k,i)),g.push(p);for(let T=0;T<_;T++){let P=k[T],C=d(P,p[P],g,S,x);C!==void 0&&(v+=`${w}${qt(P)}: ${C}`,w=b)}if(y>a){let T=y-a;v+=`${w}"...": "${un(T)} not stringified"`,w=b}return w!==""&&(v=`
863
- ${x}${v}
864
- ${$}`),g.pop(),`{${v}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function f(m,p,g){switch(typeof p){case"string":return qt(p);case"object":{if(p===null)return"null";if(typeof p.toJSON=="function"){if(p=p.toJSON(m),typeof p!="object")return f(m,p,g);if(p===null)return"null"}if(g.indexOf(p)!==-1)return t;let S="",x=p.length!==void 0;if(x&&Array.isArray(p)){if(p.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(p);let v=Math.min(p.length,a),w=0;for(;w<v-1;w++){let T=f(String(w),p[w],g);S+=T!==void 0?T:"null",S+=","}let _=f(String(w),p[w],g);if(S+=_!==void 0?_:"null",p.length-1>a){let T=p.length-a-1;S+=`,"... ${un(T)} not stringified"`}return g.pop(),`[${S}]`}let $=Object.keys(p),k=$.length;if(k===0)return"{}";if(o<g.length+1)return'"[Object]"';let y="",b=Math.min(k,a);x&&Ol(p)&&(S+=jm(p,",",a),$=$.slice(p.length),b-=p.length,y=","),r&&($=Rl($,i)),g.push(p);for(let v=0;v<b;v++){let w=$[v],_=f(w,p[w],g);_!==void 0&&(S+=`${y}${qt(w)}:${_}`,y=",")}if(k>a){let v=k-a;S+=`${y}"...":"${un(v)} not stringified"`}return g.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,g){if(arguments.length>1){let S="";if(typeof g=="number"?S=" ".repeat(Math.min(g,10)):typeof g=="string"&&(S=g.slice(0,10)),p!=null){if(typeof p=="function")return l("",{"":m},[],p,S,"");if(Array.isArray(p))return u("",m,[],t$(p),S,"")}if(S.length!==0)return d("",m,[],S,"")}return f("",m,[])}return h}});var Gm=N((ER,Wm)=>{"use strict";var Il=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Km}=Kr(),s$=Km.info;function r$(n,e){n=n||[],e=e||{dedupe:!1};let t=Object.create(Km);t.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(f=>{t[f]=e.levels[f]});let s={write:r,add:a,remove:l,emit:i,flushSync:o,end:u,minLevel:0,lastId:0,streams:[],clone:d,[Il]:!0,streamLevels:t};return Array.isArray(n)?n.forEach(a,s):a.call(s,n),n=null,s;function r(f){let h,m=this.lastLevel,{streams:p}=this,g=0,S;for(let x=i$(p.length,e.dedupe);a$(x,p.length,e.dedupe);x=o$(x,e.dedupe))if(h=p[x],h.level<=m){if(g!==0&&g!==h.level)break;if(S=h.stream,S[Il]){let{lastTime:$,lastMsg:k,lastObj:y,lastLogger:b}=this;S.lastLevel=m,S.lastTime=$,S.lastMsg=k,S.lastObj=y,S.lastLogger=b}S.write(f),e.dedupe&&(g=h.level)}else if(!e.dedupe)break}function i(...f){for(let{stream:h}of this.streams)typeof h.emit=="function"&&h.emit(...f)}function o(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync()}function a(f){if(!f)return s;let h=typeof f.write=="function"||f.stream,m=f.write?f:f.stream;if(!h)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:p,streamLevels:g}=this,S;typeof f.levelVal=="number"?S=f.levelVal:typeof f.level=="string"?S=g[f.level]:typeof f.level=="number"?S=f.level:S=s$;let x={stream:m,level:S,levelVal:void 0,id:++s.lastId};return p.unshift(x),p.sort(qm),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(qm),this.minLevel=h.length>0?h[0].level:-1),s}function u(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync(),f.end()}function d(f){let h=new Array(this.streams.length);for(let m=0;m<h.length;m++)h[m]={level:f,stream:this.streams[m].stream};return{write:r,add:a,remove:l,minLevel:f,streams:h,clone:d,emit:i,flushSync:o,[Il]:!0}}}function qm(n,e){return n.level-e.level}function i$(n,e){return e?n-1:0}function o$(n,e){return e?n-1:n+1}function a$(n,e,t){return t?n>=0:n<e}Wm.exports=r$});var Nl=N((TR,Xe)=>{"use strict";var l$=require("node:os"),eg=el(),c$=tl(),u$=rl(),tg=Rh(),d$=Nm(),ng=Pn(),{configure:f$}=Um(),{assertDefaultLevelFound:p$,mappings:sg,genLsCache:h$,genLevelComparison:m$,assertLevelComparison:g$}=Al(),{DEFAULT_LEVELS:rg,SORTING_ORDER:y$}=Kr(),{createArgsNormalizer:b$,asChindings:v$,buildSafeSonicBoom:Vm,buildFormatters:w$,stringify:Dl,normalizeDestFileDescriptor:zm,noop:x$}=qr(),{version:S$}=kl(),{chindingsSym:Ym,redactFmtSym:_$,serializersSym:Jm,timeSym:A$,timeSliceIndexSym:k$,streamSym:$$,stringifySym:Xm,stringifySafeSym:Ll,stringifiersSym:Qm,setLevelSym:C$,endSym:E$,formatOptsSym:T$,messageKeySym:R$,errorKeySym:O$,nestedKeySym:P$,mixinSym:M$,levelCompSym:I$,useOnlyCustomLevelsSym:D$,formattersSym:Zm,hooksSym:L$,nestedKeyStrSym:F$,mixinMergeStrategySym:N$,msgPrefixSym:j$}=ng,{epochTime:ig,nullTime:H$}=tg,{pid:B$}=process,U$=l$.hostname(),q$=eg.err,K$={level:"info",levelComparison:y$.ASC,levels:rg,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:B$,hostname:U$},serializers:Object.assign(Object.create(null),{err:q$}),formatters:Object.assign(Object.create(null),{bindings(n){return n},level(n,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:ig,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},W$=b$(K$),G$=Object.assign(Object.create(null),eg);function Fl(...n){let e={},{opts:t,stream:s}=W$(e,c$(),...n);t.level&&typeof t.level=="string"&&rg[t.level.toLowerCase()]!==void 0&&(t.level=t.level.toLowerCase());let{redact:r,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:u,nestedKey:d,base:f,name:h,level:m,customLevels:p,levelComparison:g,mixin:S,mixinMergeStrategy:x,useOnlyCustomLevels:$,formatters:k,hooks:y,depthLimit:b,edgeLimit:v,onChild:w,msgPrefix:_}=t,T=f$({maximumDepth:b,maximumBreadth:v}),P=w$(k.level,k.bindings,k.log),C=Dl.bind({[Ll]:T}),F=r?u$(r,C):{},H=r?{stringify:F[_$]}:{stringify:C},W="}"+(i?`\r
865
- `:`
866
- `),E=v$.bind(null,{[Ym]:"",[Jm]:o,[Qm]:F,[Xm]:Dl,[Ll]:T,[Zm]:P}),A="";f!==null&&(h===void 0?A=E(f):A=E(Object.assign({},f,{name:h})));let V=a instanceof Function?a:a?ig:H$,U=V().indexOf(":")+1;if($&&!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(_&&typeof _!="string")throw Error(`Unknown msgPrefix type "${typeof _}" - expected "string"`);p$(m,p,$);let Z=sg(p,$);typeof s.emit=="function"&&s.emit("message",{code:"PINO_CONFIG",config:{levels:Z,messageKey:l,errorKey:u}}),g$(g);let te=m$(g);return Object.assign(e,{levels:Z,[I$]:te,[D$]:$,[$$]:s,[A$]:V,[k$]:U,[Xm]:Dl,[Ll]:T,[Qm]:F,[E$]:W,[T$]:H,[R$]:l,[O$]:u,[P$]:d,[F$]:d?`,${JSON.stringify(d)}:{`:"",[Jm]:o,[M$]:S,[N$]:x,[Ym]:A,[Zm]:P,[L$]:y,silent:x$,onChild:w,[j$]:_}),Object.setPrototypeOf(e,d$()),h$(e),e[C$](m),e}Xe.exports=Fl;Xe.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=zm(n.dest||process.stdout.fd),Vm(n)):Vm({dest:zm(n),minLength:0});Xe.exports.transport=bl();Xe.exports.multistream=Gm();Xe.exports.levels=sg();Xe.exports.stdSerializers=G$;Xe.exports.stdTimeFunctions=Object.assign({},tg);Xe.exports.symbols=ng;Xe.exports.version=S$;Xe.exports.default=Fl;Xe.exports.pino=Fl});function Ss(n){return new jl(n)}var V$,z$,Y$,jl,Hl=L(()=>{"use strict";V$={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},z$=`
123
+ `)}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,r)=>r.importance-e.importance)}evictToFit(e){let r=Array.from(this.cache.entries()).map(([s,i])=>({key:s,...i,score:this.computeScore(i)})).sort((s,i)=>s.score-i.score),n=0;for(let s of r){if(n>=e)break;s.importance>=9||(n+=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,r){let n=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(n=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=3);let s=Tn(r);return s>2e3&&(n=Math.max(1,n-1)),s>5e3&&(n=Math.max(1,n-2)),n}autoTag(e){let r=[];return/\.(ts|tsx)$/.test(e)&&r.push("typescript"),/\.(js|jsx)$/.test(e)&&r.push("javascript"),/\.json$/.test(e)&&r.push("config"),/\.md$/.test(e)&&r.push("documentation"),/\.(css|scss|sass)$/.test(e)&&r.push("style"),/\.(test|spec)\./i.test(e)&&r.push("test"),/src\//.test(e)&&r.push("source"),r}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let r=this.accessHistory[this.accessHistory.length-1];if(r&&Date.now()-this.getGroupTime(r)<3e4){if(!r.includes(e)){r.push(e);for(let n of r)if(n!==e){let s=this.cache.get(n);s&&!s.relatedFiles.includes(e)&&s.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return Qo.createHash("md5").update(e).digest("hex")}};var Ah=0;function ct(){return`msg_${Date.now()}_${++Ah}`}function He(t){return Math.ceil(t.length/4)}var We=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,r=50,n=32e3){this.maxMessages=r,this.maxTokens=n,this.sessionId=`session_${Date.now()}`;let s=He(e);this.messages.push({id:ct(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:s,compressed:!1,tags:["system"]}),this.totalTokens=s}getSessionId(){return this.sessionId}addUserMessage(e,r){let n=ct(),s=He(e);return this.messages.push({id:n,role:"user",content:e,timestamp:Date.now(),priority:r?.priority||"high",tokenEstimate:s,compressed:!1,tags:r?.tags||["user-input"]}),this.totalTokens+=s,this.trimIfNeeded(),n}addAssistantMessage(e,r,n){let s=ct(),i=He(e),o={id:s,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:n||"hablas",tokenEstimate:i,compressed:!1,tags:n?[`agent:${n}`]:["assistant"]};return r&&r.length>0&&(o.tool_calls=r,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,n&&this.agentMessageCounts.set(n,(this.agentMessageCounts.get(n)||0)+1),this.trimIfNeeded(),s}addToolMessage(e,r){let n=ct(),s=He(e);return this.messages.push({id:n,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:s,compressed:!1,tags:r?[`tool:${r}`]:["tool-result"]}),this.totalTokens+=s,this.trimIfNeeded(),n}getMessages(){return this.messages.map(e=>{let r={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls),r})}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(r=>r.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 r=He(e),n=this.messages.filter(s=>s.priority==="critical"&&s.role!=="system");this.messages=[{id:ct(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]},...n],this.recalculateTokens()}takeSnapshot(e){let r={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(n=>({...n})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(r),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),r.id}rollback(e){let r=this.snapshots.find(n=>n.id===e);return r?(this.messages=r.messages.map(n=>({...n})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,r){let n=this.messages.length,s=new t(r,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:n,session:s}),s}mergeFork(e,r){let n=this.forks.get(e);if(!n)return!1;let s=n.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(r)this.addAssistantMessage(`[Agent @${e} result]: ${r}`,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 r=e.toLowerCase();return this.messages.filter(n=>n.content.toLowerCase().includes(r))}getMessagesByTag(e){return this.messages.filter(r=>r.tags.includes(e))}getLastByRole(e,r=1){return this.messages.filter(n=>n.role===e).slice(-r)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(r=>r.role==="tool"&&!r.compressed&&r.tokenEstimate>200);for(let r of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let r=this.messages.filter(n=>n.role==="assistant"&&!n.compressed&&n.priority!=="critical"&&n.tokenEstimate>300);for(let n of r.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(n)}}if(this.messages.length>this.maxMessages){let r=this.messages[0],n=this.messages.slice(1),s={critical:3,high:2,normal:1,low:0},i=n.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=[r,...i],this.recalculateTokens()}}compressMessage(e){let r=e.content.length,n=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
124
+ ...(compressed from `+r+" chars)":e.content=e.content.slice(0,400)+`
125
+ ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=He(e.content),this.totalTokens-=n-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,r)=>e+r.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 r=JSON.parse(e);if(!r.messages||!Array.isArray(r.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=r.sessionId||`session_${Date.now()}`,this.messages=r.messages,this.totalTokens=r.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(r.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 ze=k(require("fs")),ea=k(require("path"));var A=k(require("fs")),E=k(require("path"));function Eh(t){let e=E.join(t,"package.json");if(A.existsSync(e))try{let r=JSON.parse(A.readFileSync(e,"utf-8")),n={...r.dependencies,...r.devDependencies};if(n.next)return"next";if(n.nuxt)return"nuxt";if(n["@angular/core"])return"angular";if(n.svelte||n["@sveltejs/kit"])return"svelte";if(n.vue)return"vue";if(n.react)return"react";if(n["@nestjs/core"])return"nest";if(n.fastify)return"fastify";if(n.express)return"express"}catch{}if(A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml")))try{let r=A.existsSync(E.join(t,"requirements.txt"))?A.readFileSync(E.join(t,"requirements.txt"),"utf-8"):"";if(r.includes("django"))return"django";if(r.includes("flask"))return"flask";if(r.includes("fastapi"))return"fastapi"}catch{}if(A.existsSync(E.join(t,"Cargo.toml")))try{if(A.readFileSync(E.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(A.existsSync(E.join(t,"go.mod")))try{if(A.readFileSync(E.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Oh(t){return A.existsSync(E.join(t,"pnpm-lock.yaml"))?"pnpm":A.existsSync(E.join(t,"yarn.lock"))?"yarn":A.existsSync(E.join(t,"bun.lockb"))?"bun":A.existsSync(E.join(t,"package-lock.json"))?"npm":A.existsSync(E.join(t,"Cargo.toml"))?"cargo":A.existsSync(E.join(t,"go.mod"))?"go":A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml"))?"pip":"unknown"}function $h(t){return A.existsSync(E.join(t,"tsconfig.json"))?"TypeScript":A.existsSync(E.join(t,"package.json"))?"JavaScript":A.existsSync(E.join(t,"Cargo.toml"))?"Rust":A.existsSync(E.join(t,"go.mod"))?"Go":A.existsSync(E.join(t,"pyproject.toml"))||A.existsSync(E.join(t,"requirements.txt"))?"Python":"Unknown"}function Rh(t){let e=E.join(t,".git","HEAD");if(!A.existsSync(e))return null;try{let r=A.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function Ve(t){let e=Eh(t),r=Oh(t),n=$h(t),s=Rh(t),i=A.existsSync(E.join(t,"Dockerfile"))||A.existsSync(E.join(t,"docker-compose.yml"))||A.existsSync(E.join(t,"docker-compose.yaml")),o=A.existsSync(E.join(t,".github","workflows"))||A.existsSync(E.join(t,".gitlab-ci.yml"))||A.existsSync(E.join(t,"Jenkinsfile")),a=A.existsSync(E.join(t,"__tests__"))||A.existsSync(E.join(t,"tests"))||A.existsSync(E.join(t,"test"))||A.existsSync(E.join(t,"spec")),l=A.existsSync(E.join(t,".git")),u=[],d=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of d)A.existsSync(E.join(t,m))&&u.push(m);let f=[],p=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let m of p)A.existsSync(E.join(t,m))&&f.push(m);let h=[],c=["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 m of c)A.existsSync(E.join(t,m))&&h.push(m);return{rootPath:t,framework:e,packageManager:r,language:n,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:s,envFiles:u,configFiles:f,entryPoints:h}}function qt(t){let e=[` Project: ${E.basename(t.rootPath)}`,` Framework: ${t.framework}`,` Language: ${t.language}`,` Package: ${t.packageManager}`,` Git: ${t.hasGit?`\u2713 (${t.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${t.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${t.hasCICD?"\u2713":"\u2717"}`,` Tests: ${t.hasTests?"\u2713":"\u2717"}`];return t.envFiles.length>0&&e.push(` Env files: ${t.envFiles.join(", ")}`),e.join(`
126
+ `)}async function Ke(t,e){let r=[],n=ea.join(t,"package.json");if(ze.existsSync(n))try{let o=JSON.parse(ze.readFileSync(n,"utf-8"));r.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&r.push(`Description: ${o.description}`)}catch{}let s=Ve(t);r.push(`Framework: ${s.framework}`),r.push(`Language: ${s.language}`),r.push(`Package Manager: ${s.packageManager}`),r.push(`Git: ${s.hasGit?s.gitBranch||"present":"absent"}`);let i=Ih(t,16);return i.length>0&&r.push(`Top-level: ${i.join(", ")}`),e?.workspace?.envParsing&&s.envFiles.length>0&&r.push(`Env files: ${s.envFiles.join(", ")}`),r.push(`Directory: ${t}`),r.join(`
127
+ `)}function Ih(t,e){try{return ze.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function Je(t,e){return`You are Hablas, a single powerful AI software engineering agent created by Abdulmoin Hablas.
128
+
129
+ Identity:
130
+ - You are the only visible agent.
131
+ - Do not mention internal teams, specialists, delegation, routing, orchestration, or hidden systems.
132
+ - Speak as one decisive engineering agent.
133
+
134
+ Style:
135
+ - Direct, technical, calm.
136
+ - No emojis.
137
+ - No hype.
138
+ - No filler.
139
+ - No theatrical narration.
140
+ - Do not say "let me" unless you are actually about to inspect or execute something.
141
+
142
+ Core execution rules:
143
+ 1. If the task does not need tools, answer directly without inventing a tool workflow.
144
+ 2. If the task needs tools, use the minimum necessary tools.
145
+ 3. Read before editing when content is unknown.
146
+ 4. Do not reread the same file unless it changed or you genuinely need another section.
147
+ 5. One tool call at a time.
148
+ 6. Never output raw tool JSON, XML, or pseudo-calls in user-facing text.
149
+ 7. If the task is project-specific, ground claims in observed files.
150
+ 8. If the task is implementation, verify before claiming success.
151
+ 9. If you cannot verify, say exactly what remains unverified.
152
+
153
+ ${Ph(e)}
154
+
155
+ Current project context:
156
+ ${t}`}function Ph(t){if(t.kind==="casual")return`Task profile:
157
+ - Casual social turn.
158
+ - No tools unless absolutely unavoidable.`;if(t.kind==="read")return`Task profile:
159
+ - Read-only or project-inspection task.
160
+ - Use tools only to inspect the minimum necessary evidence.
161
+ - Keep the final answer factual and tight.`;if(t.kind==="analysis")return`Task profile:
162
+ - Analysis / architecture task.
163
+ - Prefer reasoning first.
164
+ - If files are relevant, inspect only what is necessary.
165
+ - Deliver a structured recommendation, not drama.`;let e=t.continuity?"- Continue from existing work. Do not restart the project from zero.":"- Implementation task.",r=t.oneStepDelivery?"- The user requested one-step delivery with no follow-up questions. Complete as much as possible in one pass.":"- Ask a clarifying question only if the task is truly blocked.";return`Task profile:
166
+ ${e}
167
+ ${r}
168
+ - Prefer minimal correct edits over broad rewrites.
169
+ - Verify changes before claiming completion.`}var Fh=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Mh=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,Dh=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Lh=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate)\b/i,jh=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,Nh=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,qh=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function ut(t){let e=t.trim(),r=e.toLowerCase(),n=Mh.test(r),s=Dh.test(r),i=Lh.test(r)||n||s,o=jh.test(r)&&!i,a=Nh.test(r),l=!i&&(qh.test(r)||e.endsWith("?"));return Fh.test(e)&&!a&&!i&&!o?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:i?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:n,oneStepDelivery:s,requiresProjectContext:!0,reason:n?"Continuation of existing work requires reading and modifying project artifacts.":"Implementation request requires tool-based execution."}:o?{kind:"analysis",needsTools:a,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:a,reason:a?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:l||a?{kind:"read",needsTools:a,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:a,reason:a?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}function Uh(t,e){if(!e.needsTools)return[{id:"respond",title:"Respond directly and clearly."}];if(e.kind==="read")return[{id:"inspect",title:"Inspect the minimum relevant files."},{id:"answer",title:"Answer precisely from observed facts."}];if(e.kind==="analysis")return[{id:"inspect-context",title:"Inspect only the files needed for analysis."},{id:"reason",title:"Form a concise architectural recommendation."},{id:"answer",title:"Present the result as Hablas only."}];let r=[];return e.continuity&&r.push({id:"continuity",title:"Load existing project context and continue instead of restarting."}),r.push({id:"inspect",title:"Inspect the relevant code and files."}),r.push({id:"implement",title:"Apply the smallest correct implementation."}),r.push({id:"verify",title:"Run verification before claiming completion."}),r.push({id:"answer",title:"Summarize the outcome clearly."}),e.oneStepDelivery&&r.unshift({id:"delivery-contract",title:"Treat the request as no-questions one-step delivery."}),r}function ta(t){let e=ut(t);return{input:t,profile:e,plan:Uh(t,e)}}var ra=k(require("readline")),Bt=require("process"),Ut=class{rl=ra.createInterface({input:Bt.stdin,output:Bt.stdout,terminal:!0});async prompt(e){return new Promise(r=>{this.rl.question(e,n=>r(n))})}async confirm(e){return(await this.prompt(`${e} [Y/n] `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return(await this.prompt(`${e} Type yes to confirm: `)).trim().toLowerCase()==="yes"}close(){this.rl.close()}};var Bh={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},Hh=`
867
170
  ## Reasoning Protocol
868
171
 
869
172
  Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
@@ -892,26 +195,26 @@ After receiving a tool result, think again:
892
195
  - One tool call per turn. Wait for the result before the next call.
893
196
  - If a tool fails, analyze the error in <thinking> before retrying.
894
197
  - When done, give a concise final answer WITHOUT <thinking> tags.
895
- `.trim(),Y$=`
198
+ `.trim(),Wh=`
896
199
  ## Reasoning
897
200
  For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
898
201
  The user will NOT see thinking blocks. One tool call per turn.
899
- `.trim(),jl=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...V$,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,t="M"){return!this.config.thinkingEnabled||t==="XS"?e:t==="S"?`${e}
202
+ `.trim(),An=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...Bh,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,r="M"){return!this.config.thinkingEnabled||r==="XS"?e:r==="S"?`${e}
900
203
 
901
- ${Y$}`:`${e}
204
+ ${Wh}`:`${e}
902
205
 
903
- ${z$}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let t=[],s=e,r=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=r.exec(e))!==null;)t.push(i[1].trim());s=s.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)t.push(i[1].trim());s=s.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(s);a&&(t.push(a[1].trim()),s=s.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(s);return l&&(t.push(l[1].trim()),s=s.replace(/<think>[\s\S]*$/i,"")),{thinking:t.join(`
206
+ ${Hh}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let r=[],n=e,s=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=s.exec(e))!==null;)r.push(i[1].trim());n=n.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)r.push(i[1].trim());n=n.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(n);a&&(r.push(a[1].trim()),n=n.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(n);return l&&(r.push(l[1].trim()),n=n.replace(/<think>[\s\S]*$/i,"")),{thinking:r.join(`
904
207
 
905
- `).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`
208
+ `).trim(),visibleContent:n.trim(),hasThinking:r.length>0}}startTurn(){this.turnSteps=[],this.stepCounter=0}recordStep(e){let r={...e,stepIndex:this.stepCounter++,timestamp:new Date().toISOString()};return this.turnSteps.push(r),r}recordObservation(e,r){let n=this.turnSteps[this.turnSteps.length-1];n&&(n.observation=e,r&&(n.reflection=r))}getSteps(){return this.turnSteps}isOverBudget(){return this.stepCounter>=this.config.maxSteps}remainingBudget(){return Math.max(0,this.config.maxSteps-this.stepCounter)}buildSelfEvalPrompt(e,r,n){return`
906
209
  <self_eval>
907
210
  You just completed this task: "${e}"
908
211
 
909
212
  Your answer was:
910
213
  """
911
- ${t.slice(0,1500)}
214
+ ${r.slice(0,1500)}
912
215
  """
913
216
 
914
- Tools used: ${s.length>0?s.join(", "):"none"}
217
+ Tools used: ${n.length>0?n.join(", "):"none"}
915
218
 
916
219
  Rate your work. Reply with ONLY a JSON object \u2014 no other text:
917
220
  {
@@ -922,374 +225,22 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
922
225
  "confidence": "<high|medium|low>"
923
226
  }
924
227
  </self_eval>
925
- `.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(`
926
- `)}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 _s(n=3){return new Bl(n)}var J$,Bl,Ul=L(()=>{"use strict";J$=[{test:n=>/ENOENT|no such file|not found|does not exist/i.test(n),errorClass:"file_not_found",strategy:"read_first",explanation:"The file or directory does not exist.",suggestion:"Use list_dir to check what files exist, then retry with the correct path.",alternatives:["list_dir","search_codebase"],autoRetry:!1},{test:n=>/EACCES|permission denied/i.test(n),errorClass:"permission_denied",strategy:"graceful_fail",explanation:"Permission denied \u2014 the process lacks access rights.",suggestion:"Check file ownership or try a different path. Do NOT use sudo.",alternatives:[],autoRetry:!1},{test:n=>/EISDIR|is a directory/i.test(n),errorClass:"path_is_directory",strategy:"retry_fixed",explanation:"The path points to a directory, not a file.",suggestion:"Append the filename to the path. Use list_dir to see contents.",alternatives:["list_dir"],autoRetry:!1},{test:n=>/EEXIST|already exists/i.test(n),errorClass:"file_already_exists",strategy:"read_first",explanation:"A file or directory already exists at that path.",suggestion:"Read the existing file first, then decide whether to overwrite or edit it.",alternatives:["read_file","edit_file"],autoRetry:!1},{test:n=>/no match|not found in file|search string not found/i.test(n),errorClass:"search_no_match",strategy:"read_first",explanation:"The search string was not found in the file.",suggestion:"Read the file first to see its actual content, then use the exact text for search/replace.",alternatives:["read_file","search_codebase"],autoRetry:!1},{test:n=>/command not found|not recognized/i.test(n),errorClass:"command_not_found",strategy:"alternative_tool",explanation:"The command does not exist on this system.",suggestion:"Check if the program is installed, or use a different command that achieves the same goal.",alternatives:["run_command"],autoRetry:!1},{test:n=>/timeout|timed out|ETIMEDOUT/i.test(n),errorClass:"command_timeout",strategy:"retry_fixed",explanation:"The command took too long and was terminated.",suggestion:"Try a simpler version of the command, or increase the timeout, or run it in background.",alternatives:[],autoRetry:!1},{test:n=>/exit code|exited with|non-zero/i.test(n),errorClass:"command_exit_error",strategy:"retry_fixed",explanation:"The command executed but returned an error.",suggestion:"Read the error output carefully. Fix the root cause (missing dependency, wrong syntax, etc.).",alternatives:[],autoRetry:!1},{test:n=>/syntax error|unexpected token|parse error|SyntaxError/i.test(n),errorClass:"syntax_error",strategy:"retry_fixed",explanation:"The content has a syntax error.",suggestion:"Review the generated code for syntax issues, fix them, and retry.",alternatives:[],autoRetry:!1},{test:n=>/ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(n),errorClass:"network_error",strategy:"retry_same",explanation:"Network connection failed.",suggestion:"This may be transient. Retry the same operation, or check connectivity.",alternatives:[],autoRetry:!0},{test:n=>/invalid argument|missing required|expected.*but got|type error/i.test(n),errorClass:"invalid_arguments",strategy:"retry_fixed",explanation:"The tool was called with invalid or missing arguments.",suggestion:"Check the tool's parameter requirements and provide correct values.",alternatives:[],autoRetry:!1},{test:n=>/ENOMEM|out of memory|resource|too large|max.*exceeded/i.test(n),errorClass:"resource_limit",strategy:"decompose_task",explanation:"Resource limit exceeded (memory, file size, etc.).",suggestion:"Break the task into smaller pieces, or process less data at once.",alternatives:[],autoRetry:!1}],Bl=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,t,s){let r=this.failures.get(e),i=r?r.count+1:1,o={tool:e,count:i,lastError:t,lastStrategy:"retry_same"};if(i>this.maxRetriesPerTool)return o.lastStrategy="ask_user",this.failures.set(e,o),{errorClass:"unknown",strategy:"ask_user",explanation:`Tool "${e}" has failed ${i} times in this turn.`,suggestion:`Stop retrying "${e}". Ask the user for clarification or try a completely different approach.`,alternatives:this.suggestAlternatives(e),autoRetry:!1};for(let a of J$)if(a.test(t)){let l=r?.lastStrategy===a.strategy&&i>=2,u=l?"decompose_task":a.strategy;return o.lastStrategy=u,this.failures.set(e,o),{errorClass:a.errorClass,strategy:u,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,t){let s=[`ERROR: ${t}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&s.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":s.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":s.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":s.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":s.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":s.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":s.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return s.join(`
927
- `)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let t=this.failures.get(e);return t?t.count<=1&&t.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}}});function X$(){try{if(It.existsSync(Vr))return JSON.parse(It.readFileSync(Vr,"utf-8"))}catch{}return{}}function Q$(n){try{let e=zr.dirname(Vr);It.existsSync(e)||It.mkdirSync(e,{recursive:!0}),It.writeFileSync(Vr,JSON.stringify(n,null,2),"utf-8")}catch{}}function ag(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 As(n){if(typeof n.name=="string"&&n.arguments&&typeof n.arguments=="object")return{tool:n.name,args:n.arguments};if(typeof n.tool=="string"&&n.args&&typeof n.args=="object")return{tool:n.tool,args:n.args};if(typeof n.name=="string"&&n.parameters&&typeof n.parameters=="object")return{tool:n.name,args:n.parameters};if(n.function&&typeof n.function=="object"){let e=n.function;if(typeof e.name=="string"){let t={};if(typeof e.arguments=="string")try{t=JSON.parse(e.arguments)}catch{t={}}else e.arguments&&typeof e.arguments=="object"&&(t=e.arguments);return{tool:e.name,args:t}}}return null}function Z$(n){return n.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function e0(n){let e=[],t=/<<?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=As(r);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function t0(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim());if(r.parameters||r.name){let i=As(r);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function n0(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;){let r=s[1],i=lg(r);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function lg(n){let e=[],t=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info"];for(let s of t){let r=new RegExp(`<<?${s}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${s}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=r.exec(n))!==null;){let o=i[1]||"",a=i[2]||"",l={},u=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,d;for(;(d=u.exec(o))!==null;){let h=d[1].toLowerCase(),m=d[2]??d[3]??d[4];l[h]=Z$(m)}let f=a.trim();f&&(s==="write_file"||s==="append_to_file"?l.content=a:s==="run_command"?l.command=f:s==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),s==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:s,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function s0(n){return lg(n)}function r0(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=As(r);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function i0(n){let e=[],t=/\{\s*"function"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=ag(n,s.index);if(r)try{let i=JSON.parse(r),o=As(i);o&&e.push({...o,format:"function_call",rawMatch:r})}catch{}}return e}function o0(n){let e=[],t=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=ag(n,s.index);if(r)try{let i=JSON.parse(r),o=As(i);o&&e.push({...o,format:"json_object",rawMatch:r})}catch{}}return e}function a0(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,s,r=!1;for(;(s=t.exec(n))!==null;){let i=s[1],o=/<function=([^>]+)>/i.exec(i);if(o){r=!0;let a=o[1].trim(),l={},u=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,d;for(;(d=u.exec(i))!==null;){let f=d[1].trim(),h=d[2].trim();h==="true"?h=!0:h==="false"?h=!1:!isNaN(Number(h))&&h!==""&&(h=Number(h)),l[f]=h}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:s[0]})}}if(!r&&/<function=([^>]+)>/i.test(n)){let i=/<function=([^>]+)>/i.exec(n);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=l.exec(n))!==null;){let d=u[1].trim(),f=u[2].trim();f==="true"?f=!0:f==="false"?f=!1:!isNaN(Number(f))&&f!==""&&(f=Number(f)),a[d]=f}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:n})}}return e}function cg(){return Kl||(Kl=new Wl),Kl}var It,zr,og,Vr,ql,Wl,Kl,ug=L(()=>{"use strict";It=O(require("fs")),zr=O(require("path")),og=O(require("os")),Vr=zr.join(og.homedir(),".hablas","model-formats.json");ql=[{format:"xml_tool_call_wrapper",parse:n0},{format:"xml_prompt",parse:s0},{format:"xml_tags",parse:e0},{format:"xml_parameters",parse:a0},{format:"hermes",parse:t0},{format:"markdown_json",parse:r0},{format:"function_call",parse:i0},{format:"json_object",parse:o0}],Wl=class{registry;constructor(){this.registry=X$()}parse(e,t,s){if(t&&Array.isArray(t)&&t.length>0){let i=t.filter(o=>o?.function?.name&&typeof o.function.name=="string");if(i.length>0){let o=i.map(a=>({function:{name:a.function.name,arguments:a.function.arguments||{}}}));return s&&this.learnFormat(s,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let r=e||"";if(!r.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(s){let i=this.registry[s];if(i&&i.format!=="native"){let o=ql.find(a=>a.format===i.format);if(o){let a=o.parse(r);if(a.length>0)return this.learnFormat(s,i.format),this.buildResult(a,r)}}}for(let{parse:i}of ql){let o=i(r);if(o.length>0){let a=o[0].format;return s&&this.learnFormat(s,a),this.buildResult(o,r)}}return{toolCalls:[],displayContent:r.trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let t=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(t)||/<function=/i.test(t)||t.includes("```tool_call")||t.includes("```json")&&t.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info)[\s>]/i.test(t)||t.startsWith("{")&&(t.includes('"name"')||t.includes('"tool"'))&&(t.includes('"arguments"')||t.includes('"args"')||t.includes('"parameters"'))||t.includes('"function"')&&t.includes('"name"'))}detectFormat(e){for(let{format:t,parse:s}of ql)if(s(e).length>0)return t;return"unknown"}learnFormat(e,t){let s=this.registry[e];s&&s.format===t?(s.successCount++,s.lastUsed=new Date().toISOString()):this.registry[e]={format:t,successCount:1,lastUsed:new Date().toISOString()},Q$(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[t,s]of Object.entries(this.registry))e[t]={format:s.format,successCount:s.successCount};return e}buildResult(e,t){let s=e.map(o=>({function:{name:o.tool,arguments:o.args}})),r=t,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)r=r.replace(o.rawMatch,"");return r=r.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),r=r.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),r=r.replace(/\n{3,}/g,`
928
-
929
- `),{toolCalls:s,displayContent:r.trim(),format:e[0]?.format??"unknown"}}},Kl=null});function c0(n,e,t){let r=cg().parse(e,n,t);return{toolCalls:r.toolCalls,displayContent:r.displayContent}}function u0(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 d0(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 pg(n,e,t,s){let r=0,i=Date.now();for(;r<=fg;){let o=await n.execute({name:e,arguments:t});if(o.success||r>=fg)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 Yr(n){let{identity:e,client:t,registry:s,session:r,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:u,skipTools:d}=n,f=n.reactEngine??Ss(),h=n.errorRecovery??_s(),m=d?[]:s.getOllamaTools(),p=t.getModel(),g=n.maxIterations??l0,S=[],x=[],$=[],k="",y=0,b=!1;for(;y<g;){if(y++,u?.aborted)return{output:k,toolsUsed:Kt(S),toolResults:x,touchedFiles:Kt($),iterations:y,success:!1,error:"Aborted",completedNaturally:b};let v=f.buildBudgetWarningPrompt();v&&r.addUserMessage(v,{priority:"critical",tags:["system-budget"]});let w;try{w=await t.chatWithTools(r.getMessages(),m,u)}catch(W){let E=W;if(E.name==="AbortError"||u?.aborted)return{output:k,toolsUsed:Kt(S),toolResults:x,touchedFiles:Kt($),iterations:y,success:!1,error:"Aborted",completedNaturally:b};if(y<=1){a.onNotice?.(`Transient model error: ${E.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(A=>setTimeout(A,1e3)),y--;continue}return a.onError?.(E.message??"Model request failed"),{output:k,toolsUsed:Kt(S),toolResults:x,touchedFiles:Kt($),iterations:y,success:!1,error:E.message,completedNaturally:b}}let _=w.message?.content||"",T=w.message?.tool_calls,P=f.parseThinking(_);P.hasThinking&&(f.recordStep({thought:P.thinking}),o.debug({thinking:P.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:C,displayContent:F}=c0(T,_,p);if(F&&F.trim()&&(k=F,await a.onAssistantText?.(F,e)),C.length===0){r.addAssistantMessage(_,void 0,e.role),b=!0;break}r.addAssistantMessage(_,C,e.role);let H=C.length;for(let W=0;W<C.length;W++){let E=C[W];if(!E?.function?.name)continue;let A=E.function.name,V=E.function.arguments||{},U=s.getSafetyLevel(A)??"confirm";if(!s.get(A)){a.onNotice?.(`Unknown tool: ${A} \u2014 skipping`,"warn"),r.addToolMessage(`Error: Unknown tool "${A}". Available: ${s.getAll().map(Re=>Re.name).join(", ")}`);continue}if(await l(A,U,V)==="skip"){r.addToolMessage(`Tool ${A} was skipped by policy/user.`);break}S.push(A),typeof V.path=="string"&&$.push(V.path);let te=u0(A,V);a.onToolStart?.(A,te,V),a.onToolCall?.(),f.recordStep({thought:P.hasThinking?`Executing: ${A}`:"",action:A,actionInput:V});let J=await pg(s,A,V,o);a.onToolEnd?.(A,J.success,J.error||J.output,J.duration,V);let de;if(J.success)de=ps(J.output,dg),f.recordObservation(de.slice(0,300)),x.push({tool:A,success:!0,summary:J.output.slice(0,150)});else{let Re=J.error||"Unknown error",oe=h.analyze(A,Re,V);if(de=h.buildRecoveryMessage(oe,Re),f.recordObservation(`FAILED: ${Re}`,`Recovery: ${oe.strategy} \u2014 ${oe.suggestion}`),o.info({tool:A,errorClass:oe.errorClass,strategy:oe.strategy},"Error recovery analysis"),x.push({tool:A,success:!1,summary:Re.slice(0,150)}),oe.autoRetry&&!f.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let X=await pg(s,A,V,o);a.onToolEnd?.(A,X.success,X.output,X.duration,V),X.success&&(de=ps(X.output,dg),f.recordObservation(de.slice(0,300),"Auto-retry succeeded"),x[x.length-1]={tool:A,success:!0,summary:X.output.slice(0,150)})}}if(r.addToolMessage(de),J.success&&A==="read_file"&&typeof V.path=="string"&&i?.addFile(V.path,J.output),o.info({tool:A,success:J.success,durationMs:J.duration,retries:J.retries},"Tool executed"),!J.success&&d0(J.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}H>1&&W<H-1}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return y>=g&&!b&&a.onNotice?.(`Reached max iterations (${g}). Stopping.`,"warn"),o.info({summary:f.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:k,toolsUsed:Kt(S),toolResults:x,touchedFiles:Kt($),iterations:y,success:!0,completedNaturally:b}}function Kt(n){return[...new Set(n)]}function hg(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 mg(){return(n,e)=>e==="dangerous"?"skip":"allow"}var l0,dg,fg,Gl=L(()=>{"use strict";wa();Hl();Ul();ug();l0=600,dg=2e3,fg=2});var yg,f0,p0,h0,gg,Dn,bg=L(()=>{"use strict";yg=O(Nl());Wn();Sa();xa();Ws();ji();Ka();Gl();f0={hablas:"planner",bob:"architect",alex:"coder",david:"researcher",emma:"product-manager"},p0=(0,yg.default)({level:"silent"}),h0=200,gg={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}},Dn=class{baseConfig;agentModels;toolRegistry=null;onOutput=null;channel=null;mindsetRegistry=$r();sharedContext=null;contextManager;constructor(e){this.baseConfig=e,this.agentModels=zt(),this.contextManager=new sn(e)}setSharedContext(e){this.sharedContext=e}setChannel(e){this.channel=e}setToolRegistry(e){this.toolRegistry=e}setOutputCallback(e){this.onOutput=e}reloadModels(){this.agentModels=zt()}getAgentModel(e){let t=this.agentModels[e];if(t)return{model:t.model,temperature:t.temperature??gg[e]?.temperature??.5};let s=gg[e];return{model:s.model,temperature:s.temperature??.5}}async runAgent(e,t,s,r,i){let o=Date.now(),a=we.find(y=>y.role===e)||{name:String(e),title:"Specialist",role:e,description:"",expertise:[]},l=this.getAgentModel(e),u=i?.maxIterations||h0,d={...this.baseConfig,model:l.model},f=Pe(d),h=this.buildAgentPrompt(a,s),m=new rn(h,200,this.baseConfig.contextBudget);m.addUserMessage(t);let p=a?.name||String(e),g=a?.title||"Specialist",S={name:p,title:g,role:e};this.emit(a.name,"thinking",`\u2605 Hablas \u2192 Delegating to @${a.name} (${a.title})...`);let x={onAssistantText:y=>{this.emit(a.name,"speaking",y.slice(0,200))},onToolStart:(y,b,v)=>{this.emit(a.name,"tool",b),this.channel&&this.channel.emitEvent({type:"act",agent:a.name,toolName:y,toolArgs:this.safeArgs(v),content:b})},onToolEnd:(y,b,v)=>{this.channel&&this.channel.emitEvent({type:"observe",agent:a.name,toolName:y,success:b,content:b?this.summarizeOk(y,v):`error: ${v.slice(0,120)}`})},onError:y=>this.emit(a.name,"error",y)},$=await Yr({identity:S,client:f,registry:this.toolRegistry,session:m,contextManager:this.contextManager,logger:p0,io:x,safetyPolicy:mg(),abortSignal:i?.abortSignal,skipTools:(!r||r.length===0,!1),maxIterations:u});if(this.sharedContext&&$.touchedFiles.length)try{this.sharedContext.set(`files:@${a.name}`,$.touchedFiles.join(", "))}catch{}let k=$.touchedFiles.length?[`@${a.name} touched: ${$.touchedFiles.join(", ")}`]:[];return{agent:e,agentName:a.name,output:$.output||($.success?"Done.":$.error??"No output"),toolsUsed:$.toolsUsed,toolResults:$.toolResults,duration:Date.now()-o,iterations:$.iterations,success:$.success,error:$.error,discoveries:k,touchedFiles:$.touchedFiles}}async runSequential(e,t,s){let r=[],i="",o=[];for(let a=0;a<e.length;a++){let{role:l,task:u}=e[a];if(s?.abortSignal?.aborted)break;let d=[];if(i&&(d.push("## Previous Agent Results"),d.push(i)),o.length>0){d.push(`
930
- ## Handoff Chain`);for(let p of o)d.push(`- @${p.from} \u2192 @${p.to}: ${p.context.slice(0,100)}`)}let f=d.join(`
931
- `),h=we.find(p=>p.role===l);if(h&&a>0){let p=e[a-1].role,g=we.find(S=>S.role===p);this.emit(h.name,"thinking",`\u2605 Handoff: @${g?.name||p} \u2192 @${h.name} (${h.title})`)}let m=await this.runAgent(l,u,f,t,s);if(r.push(m),m.success&&m.output){let p=m.output.length>600?m.output.slice(0,600)+"...":m.output;i+=`
932
-
933
- ### @${m.agentName} (${we.find(g=>g.role===l)?.title||l})
934
- ${p}`,a<e.length-1&&o.push({from:l,to:e[a+1].role,context:m.output.slice(0,200),artifacts:m.touchedFiles})}}return r}async runParallel(e,t,s){let r=s?.maxConcurrent||3,i=[];for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r),l=await Promise.all(a.map(({role:u,task:d})=>this.runAgent(u,d,void 0,t,s)));i.push(...l)}return i}async runWithEscalation(e,t,s,r){let i=await this.runAgent(e,t,s,r);if(i.success)return i;this.emit(we.find(a=>a.role===e)?.name||e,"error",`First attempt failed: ${i.error}. Retrying...`);let o=(s||"")+`
935
-
936
- ## Previous Attempt Failed
937
- Error: ${i.error}
938
- Please try a different approach.`;if(i=await this.runAgent(e,t,o,r),i.success)return i;if(e!=="hablas"){this.emit("Hablas","thinking",`@${we.find(l=>l.role===e)?.name} failed. Hablas taking over...`);let a=`Agent @${e} failed twice on this task.
939
- Original error: ${i.error}
940
- Please complete this task.`;return this.runAgent("hablas",t,a,r)}return i}buildAgentPrompt(e,t){let s=f0[e.role]??"coder",r=this.mindsetRegistry.get(s),o=(r?`${r.systemPrompt}
941
-
942
- ---
943
-
944
- `:"")+`You are ${e.name}, the ${e.title} of the Hablas development team.
945
-
946
- Role: ${e.description}
947
- Expertise: ${e.expertise.join(", ")}
948
-
949
- ## Core Rules - STRENGTHENED (per plan)
950
- NEVER output tool calls as text, JSON, or XML in your visible response.
951
- ALWAYS use ONLY the official tool_calls field provided by the API.
952
- If you see any <tool_call>, <list_dir>, <read_file>, <write_file> etc. in previous messages, ignore them completely.
953
-
954
- You may call only ONE tool at a time. Wait for the observation before deciding the next action.
955
-
956
- CRITICAL: You have already read files this turn \u2014 do not call read_file on the same path again unless another agent explicitly modified it. Check the conversation history and previous tool observations first. If you need more of a large file, use start_line and end_line instead of re-reading the whole path. Re-reading the same file is forbidden and wastes context.
957
-
958
- Never guess tool names or arguments. If unsure, ask for clarification instead of hallucinating (e.g. never call read_pdf on a .md file).
959
-
960
- Stay strictly in your role as ${e.name}. Focus ONLY on your area of expertise. Do not do work that belongs to other agents (e.g. Alex does not do architecture or PRDs).
961
-
962
- After finishing your part, produce a clear handoff summary.
963
-
964
- Never output raw tool XML in text.
965
-
966
- ## Communication
967
- - When you need input from another agent, clearly state what you need and from whom.
968
- - Reference specific files, functions, or code when discussing changes.
969
- - Flag any concerns or risks you identify.`;switch(e.role){case"emma":o+=`
970
-
971
- ## Product Manager Guidelines
972
- - Always start by understanding the user's core problem.
973
- - Create structured PRDs with: Goals, User Stories, Success Metrics, Scope.
974
- - Prioritize features using P0/P1/P2 framework.
975
- - Save all documents as markdown files.
976
- - **CRITICAL FOR SPEED AND CENTRALIZATION**: Keep your final report to Hablas extremely brief (2-4 sentences max). Do not repeat the full PRD in chat. Put all details in the PRD file. Hablas (Leader) will explain everything to the user. Your job is analysis + file, not long speeches.`;break;case"bob":o+=`
977
-
978
- ## Architect Guidelines
979
- - Always consider scalability, maintainability, and security.
980
- - Provide architecture diagrams (describe in mermaid format).
981
- - Document trade-offs in your decisions.
982
- - Define clear module boundaries and interfaces.
983
- - Save architecture docs as markdown files.
984
- - **CRITICAL FOR SPEED AND CENTRALIZATION**: Keep your final report to Hablas extremely brief (2-4 sentences max). Do not repeat the full architecture in chat. Put all details in the docs. Hablas (Leader) will explain everything to the user. Your job is design + file, not long speeches.`;break;case"alex":o+=`
985
-
986
- ## Engineer Guidelines
987
- - Write clean, well-commented, production-ready code.
988
- - Follow the project's existing conventions and patterns.
989
- - Include error handling and edge cases.
990
- - Add appropriate types/interfaces for TypeScript.
991
- - Test your changes when possible (run_command).
992
- - Use patch_file for small edits, write_file for new files.
993
- - **CRITICAL FOR SPEED AND CENTRALIZATION**: Keep your final report to Hablas extremely brief (2-4 sentences max). Do not explain the code in chat. The code in files is the explanation. Hablas (Leader) will explain everything to the user. Your job is implementation + file, not long speeches.`;break;case"david":o+=`
994
-
995
- ## Data Analyst Guidelines
996
- - Cite sources when referencing documentation.
997
- - Provide code examples alongside explanations.
998
- - Compare multiple approaches with pros/cons.
999
- - Note version-specific information.
1000
- - Structure findings with clear headings.
1001
- - **CRITICAL FOR SPEED AND CENTRALIZATION**: Keep your final report to Hablas extremely brief (2-4 sentences max). Put research in files. Hablas (Leader) will explain everything to the user. Your job is research + file, not long speeches.`;break}if(t&&(o+=`
1002
-
1003
- ## Context from Team
1004
- ${t}`),this.sharedContext){let a=this.sharedContext.getSummary();a&&(o+=`
1005
-
1006
- ## Shared Team Context
1007
- ${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 vg,Ln,wg=L(()=>{"use strict";vg=require("events"),Ln=class extends vg.EventEmitter{events=[];maxHistory;constructor(e=3e3){super(),this.setMaxListeners(50),this.maxHistory=e,this.on("error",t=>{process.env.DEBUG&&console.error("[AgentChannel internal error swallowed]",t)})}emitEvent(e){let t={...e,timestamp:Date.now()};return this.events.push(t),this.events.length>this.maxHistory&&this.events.splice(0,this.events.length-this.maxHistory),this.emit("event",t),t.type!=="error"&&this.emit(t.type,t),t}history(){return[...this.events]}reset(){this.events=[]}onEvent(e){return this.on("event",e),this}offEvent(e){return this.off("event",e),this}}});var m0,bt,Jr,Fn,xg=L(()=>{"use strict";Wn();m0={hablas:"Hablas \u2014 INTJ Team Leader. Authoritative, terse, engineering-precise. Speaks in short systemic statements. No pleasantries.",emma:"Emma \u2014 Product Manager. Calm, user-focused, structured. Clarifies scope and outcomes in plain language.",bob:"Bob \u2014 System Architect. Methodical, principled, slightly formal. Talks in terms of boundaries, trade-offs, contracts.",alex:"Alex \u2014 Senior Engineer. Pragmatic, concise, action-biased. Confirms intent, then ships.",david:"David \u2014 Data & Research Analyst. Factual, evidence-driven, neutral tone. Cites context, not opinions."},bt={hablas:"Hablas",emma:"Emma",bob:"Bob",alex:"Alex",david:"David"},Jr={handoff:(n,e,t)=>{let s=bt[e];return{hablas:`Routing this to you, @${s}.`,emma:`@${s}, I need the requirements framed before we move.`,bob:`@${s}, design the structure for this. Keep boundaries clean.`,alex:`@${s}, you have the implementation. Stay surgical.`,david:`@${s}, gather the context we need on this.`}[e]||`@${s}, taking this from here.`},ack:(n,e)=>`Acknowledged, @${bt[e]}. Proceeding.`,review:(n,e)=>`@${bt[e]}, structurally sound. Watch the boundaries on the next pass.`,reviewAck:(n,e)=>`Noted, @${bt[e]}. Integrating.`},Fn=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=Pe(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),()=>Jr.handoff(e,t,s))}async generateAckLine(e,t){return this.generate(`ack:${e}:${t}`,this.buildPrompt(e,t,"ack"),()=>Jr.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)),()=>Jr.review(e,t))}async generateReviewAck(e,t){return this.generate(`reviewAck:${e}:${t}`,this.buildPrompt(e,t,"reviewAck"),()=>Jr.reviewAck(e,t))}async generate(e,t,s){let r=this.cache.get(e);if(r)return r;if(this.spent>=this.opts.tokenBudget||this.opts.abortSignal?.aborted)return s();try{let o=((await this.client.chatWithTools(t,[],this.opts.abortSignal)).message?.content||"").trim(),a=this.cleanLine(o);return a?(this.spent+=Math.ceil(a.length/4)+40,this.cache.set(e,a),a):s()}catch{return s()}}buildPrompt(e,t,s,r){let i=`You are ${bt[e]}, speaking in your own voice.
1008
- ${m0[e]}
1009
-
1010
- Hard constraints:
1011
- - Output exactly ONE sentence.
1012
- - No prefix, no quotes, no markdown, no emojis, no role labels.
1013
- - Maximum ${this.opts.maxChars} characters.
1014
- - Address @${bt[t]} directly.
1015
- - Stay in character. Be useful, not chatty.`,o;switch(s){case"handoff":o=`You are about to hand the following task to @${bt[t]}. Write a single in-character line that briefly frames what you need from them. Task: "${(r||"").slice(0,300)}"`;break;case"ack":o=`@${bt[t]} just handed you a task. Write a single in-character line acknowledging it and stating your immediate next move.`;break;case"review":o=`You just reviewed @${bt[t]}'s output below. Write a single in-character line of feedback \u2014 substantive but extremely brief. Output excerpt: """${(r||"").slice(0,400)}"""`;break;case"reviewAck":o=`@${bt[t]} just reviewed your work and gave you feedback. Write a single in-character line acknowledging it and noting the integration.`;break}return[{role:"system",content:i},{role:"user",content:o}]}cleanLine(e){let t=e.trim();return t=t.replace(/^```[a-z]*\n?|```$/gi,"").trim(),t=t.split(/\r?\n/)[0].trim(),t=t.replace(/^@?[A-Z][a-zA-Z]+\s*:\s*/,"").trim(),t=t.replace(/^["'`«»“”]+|["'`«»“”]+$/g,"").trim(),t.length>this.opts.maxChars&&(t=t.slice(0,this.opts.maxChars-1).trim()+"\u2026"),t}hash(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e.charCodeAt(s),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t.toString(36)}}});var se,it,g0,_g,y0,Ag,Sg,Nn,Vl=L(()=>{"use strict";se=O(require("fs")),it=O(require("path")),g0=".hablas",_g=`# Project Context
1016
-
1017
- ## Overview
1018
- <!-- Auto-generated by hablas. Describe your project here. -->
1019
-
1020
- ## Tech Stack
1021
- <!-- Languages, frameworks, tools -->
1022
-
1023
- ## Key Patterns
1024
- <!-- Architecture patterns, conventions -->
1025
-
1026
- ## Notes
1027
- <!-- Miscellaneous context for agents -->
1028
- `,y0=`# Decisions Log
1029
-
1030
- | Date | Decision | By | Rationale |
1031
- |------|----------|-----|-----------|
1032
- `,Ag=`# Task Assignments
1033
-
1034
- ## Active Tasks
1035
- <!-- Format: - [ ] Task description (@agent) -->
1036
-
1037
- ## Completed
1038
- <!-- Format: - [x] Task description (@agent) \u2014 result -->
1039
- `,Sg={"CONTEXT.md":_g,"DECISIONS.md":y0,"TASKS.md":Ag},Nn=class{contextDir;constructor(e){this.contextDir=it.join(e,g0)}init(){let e=it.join(it.dirname(this.contextDir),".flowagent");if(se.existsSync(e)&&!se.existsSync(this.contextDir))try{se.renameSync(e,this.contextDir)}catch{}se.existsSync(this.contextDir)||se.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(Sg)){let r=it.join(this.contextDir,t);se.existsSync(r)||se.writeFileSync(r,s,"utf-8")}}exists(){return se.existsSync(this.contextDir)}read(e){let t=it.join(this.contextDir,e);return se.existsSync(t)?se.readFileSync(t,"utf-8"):null}write(e,t){this.ensureDir();let s=it.join(this.contextDir,e);se.writeFileSync(s,t,"utf-8")}append(e,t){this.ensureDir();let s=it.join(this.contextDir,e),r=se.existsSync(s)?se.readFileSync(s,"utf-8"):"";se.writeFileSync(s,r+`
1040
- `+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")||Ag).replace(`## Active Tasks
1041
- `,`## Active Tasks
1042
- ${s}
1043
- `);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 se.existsSync(this.contextDir)?se.readdirSync(this.contextDir).filter(t=>t.endsWith(".md")).map(t=>{let s=it.join(this.contextDir,t),r=se.statSync(s);return{file:t,content:se.readFileSync(s,"utf-8"),lastModified:r.mtime}}):[]}getSummary(){let e=this.getAll();return e.length===0?"":e.map(t=>`### ${t.file}
1044
- ${t.content}`).join(`
1045
-
1046
- `)}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(Sg)){let s=it.join(this.contextDir,e);se.existsSync(s)&&se.writeFileSync(s,t,"utf-8")}}getDecisions(){let e=this.read("DECISIONS.md");if(!e)return[];let t=e.split(`
1047
- `),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(`
1048
- `).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(`
1049
- `)}persistKV(){if(this.kvStore.size===0)return;let e=this.read("CONTEXT.md")||_g,t=Array.from(this.kvStore.entries()).map(([i,o])=>`- **${i}**: ${o}`).join(`
1050
- `),s=/## Notes\n[\s\S]*$/,r=e.replace(s,`## Notes
1051
- ${t}
1052
- `);this.write("CONTEXT.md",r)}ensureDir(){se.existsSync(this.contextDir)||se.mkdirSync(this.contextDir,{recursive:!0})}}});function zl(n){return we.find(e=>e.role===n)?.name||n}var jn,kg=L(()=>{"use strict";Ws();Vl();jn=class{channel;runner;chat;constructor(e,t,s,r){this.channel=e,this.runner=t,this.chat=s,this.runner.setChannel(e),this.chat.resetBudget()}async run(e,t,s,r={}){this.chat.setAbortSignal(r.abortSignal);let i=r.peerReview!==!1,o=r.centralizedToLeader===!0,a=new Nn(process.cwd());this.runner.setSharedContext(a),this.channel.emitEvent({type:"phase",agent:"System",content:"Delegating to the team"});let l=t.tasks.filter(m=>m.role!=="hablas").map(m=>({role:m.role,task:`${m.description}
1053
-
1054
- Original request: ${e}`})),u=[],d="hablas",f=null;for(let m of l){if(r.abortSignal?.aborted)break;let p=we.find(x=>x.role===m.role);if(!p)continue;if(!o){this.channel.emitEvent({type:"handoff",agent:zl(d),to:p.name});let x=await this.chat.generateHandoffLine(d,m.role,m.task);this.channel.emitEvent({type:"speak",agent:zl(d),to:p.name,content:x});let $=await this.chat.generateAckLine(m.role,d);this.channel.emitEvent({type:"speak",agent:p.name,to:zl(d),content:$})}let g=Date.now(),S=await this.runner.runAgent(m.role,m.task,void 0,s,{abortSignal:r.abortSignal});u.push(S),S.success&&S.output?(this.channel.emitEvent({type:"summary",agent:p.name,durationMs:Date.now()-g}),m.role==="alex"&&(f=S.output),i&&m.role==="alex"&&t.tasks.some(x=>x.role==="bob")&&f&&await this.runPeerReview("bob","alex",f,r.abortSignal,o)):S.error&&this.channel.emitEvent({type:"error",agent:p.name,content:S.error}),d=m.role}this.channel.emitEvent({type:"phase",agent:"System",content:"Hablas compiling final report"});let h=await this.synthesize(e,u,s,r.abortSignal);return this.channel.emitEvent({type:"done",agent:"Hablas"}),h}async runPeerReview(e,t,s,r,i=!1){let o=we.find(l=>l.role===e),a=we.find(l=>l.role===t);if(!(!o||!a)){if(!i){let l=await this.chat.generateReviewLine(e,t,s);this.channel.emitEvent({type:"review",agent:o.name,to:a.name,content:l});let u=await this.chat.generateReviewAck(t,e);this.channel.emitEvent({type:"speak",agent:a.name,to:o.name,content:u})}r?.aborted}}async synthesize(e,t,s,r){let i=t.filter(d=>d.success&&d.output);if(i.length===0)return{results:t,finalSynthesis:"The team encountered errors and could not complete the task. Please review the logs and try again.",synthesisOk:!1};let o=i.map(d=>{let f=we.find(h=>h.role===d.agent);return`### Report from @${d.agentName} (${f?.title??d.agent}):
1055
- ${d.output}`}).join(`
1056
-
1057
- `),a=`You are Hablas, the Team Leader. Your team has completed a multi-agent workflow for the user's request: "${e}".
1058
-
1059
- Here are the individual execution reports from your team members:
1060
- """
1061
- ${o}
1062
- """
1063
-
1064
- Please compile, synthesize, and present the final unified response to the user. Describe what was achieved, the files modified/created (if any), and any next steps. Speak in your characteristic Hablas voice \u2014 INTJ, authoritative, terse, engineering-precise. Speak directly to the user.`,l=await this.runner.runAgent("hablas",a,void 0,s,{abortSignal:r});if(l.success&&l.output)return{results:t,finalSynthesis:l.output,synthesisOk:!0};let u=i.map(d=>{let f=we.find(h=>h.role===d.agent);return`### @${d.agentName} (${f?.title??d.agent}):
1065
- ${d.output}`}).join(`
1066
-
1067
- `);return{results:t,finalSynthesis:u,synthesisOk:!1}}}});function ot(n){switch(n){case"Hablas":return c.leader;case"Bob":return c.architect;case"Alex":return c.engineer;case"David":return c.analyst;case"Emma":return c.product;default:return c.primary}}function Xr(n){return n==="Hablas"?"\u2605":"\u25C6"}function ks(n,e=140){let t=(n||"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e-1)+"\u2026":t}var Hn,$g=L(()=>{"use strict";yn();Hn=class{channel;opts;attached=!1;listener;lastThinking=null;lastLine="";constructor(e,t={}){this.channel=e,this.opts={hideThinking:t.hideThinking??!1,hideActs:t.hideActs??!1,maxChars:t.maxChars??140},this.listener=s=>this.handle(s)}attach(){return this.attached?this:(this.channel.onEvent(this.listener),this.attached=!0,this)}detach(){return this.attached?(this.channel.offEvent(this.listener),this.attached=!1,this):this}handle(e){switch(e.type){case"phase":return this.renderPhase(e);case"handoff":return this.renderHandoff(e);case"thinking":return this.renderThinking(e);case"speak":return this.renderSpeak(e);case"act":return this.renderAct(e);case"observe":return this.renderObserve(e);case"review":return this.renderReview(e);case"summary":return this.renderSummary(e);case"decision":return this.renderDecision(e);case"done":return this.renderDone(e);case"error":return this.renderError(e)}}renderPhase(e){let t=(e.content||"").toString();t&&(this.print(`
1068
- ${c.muted("\u25B8")} ${c.secondary(t)}`),this.lastThinking=null)}renderHandoff(e){let t=e.agent,s=e.to||"";if(!s)return;let r=ot(t),i=ot(s);this.print(` ${r(Xr(t))} ${r(t)} ${c.muted("\u2501\u2501\u25B6")} ${i(Xr(s))} ${i(s)}`),this.lastThinking=null}renderThinking(e){if(this.opts.hideThinking||this.lastThinking===e.agent)return;this.lastThinking=e.agent;let t=ot(e.agent),s=e.content&&e.content.length>5?e.content:"analyzing and formulating response\u2026";this.print(` ${t("\u25C9")} ${t(e.agent)} ${c.muted("\u2014")} ${s}`)}renderSpeak(e){let t=ks(e.content||"",this.opts.maxChars);if(!t)return;let s=ot(e.agent),r=e.to?` ${c.muted("\u2192")} ${ot(e.to)("@"+e.to)}`:"",i=`speak:${e.agent}:${e.to||""}:${t}`;i!==this.lastLine&&(this.lastLine=i,this.print(` ${s(Xr(e.agent))} ${s(e.agent)}${r}${c.muted(":")} ${c.secondary(t)}`),this.lastThinking=null)}renderAct(e){if(this.opts.hideActs)return;let t=ot(e.agent),s=e.toolName||"tool",r=e.toolArgs||{},i="";typeof r.path=="string"?i=` ${c.primary(r.path)}`:typeof r.command=="string"?i=` ${c.primary(r.command)}`:typeof r.query=="string"&&(i=` "${c.primary(r.query)}"`);let o=s==="write_file"||s==="edit_file"||s==="patch_file"?"\u270E":s==="run_command"?"\u2318":s==="read_file"?"\u{1F4D6}":s==="search_codebase"?"\u{1F50E}":"\u{1F527}";this.print(` ${t(o)} [Running Tool]: ${t(e.agent)} is executing ${c.strong(s)}${i}...`),this.lastThinking=null}renderObserve(e){if(this.opts.hideActs)return;let t=e.success!==!1,s=t?c.success("\u2713 COMPLETED"):c.error("\u2717 FAILED"),r=ks(e.content||(t?"Execution succeeded":"Execution failed"),this.opts.maxChars);this.print(` ${c.muted("\u21B3")} ${s}: ${c.muted(r)}`)}renderReview(e){let t=e.agent,s=e.to||"",r=ks(e.content||"",this.opts.maxChars);if(!r)return;let i=ot(t),o=ot(s);this.print(`
1069
- ${i("\u270E")} ${c.strong("@"+t)} ${c.muted("reviewing")} ${o("@"+s)}${c.muted(":")} ${c.secondary(r)}`),this.lastThinking=null}renderSummary(e){let t=ot(e.agent),s=e.durationMs?` ${c.muted(`(${(e.durationMs/1e3).toFixed(1)}s)`)}`:"";this.print(` ${t(Xr(e.agent))} ${t(e.agent)} ${c.muted("\u2500\u2500\u25BA")} ${c.leader("\u2605 Hablas")} ${c.muted("\xB7 report submitted")}${s}`),this.lastThinking=null}renderDecision(e){let t=ks(e.content||"",this.opts.maxChars);if(!t)return;let s=ot(e.agent);this.print(` ${s("\u25C6")} ${s(e.agent)} ${c.muted("decision:")} ${c.secondary(t)}`)}renderDone(e){this.print(`
1070
- ${c.chrome("\u2500".repeat(56))}`),this.lastThinking=null}renderError(e){let t=ot(e.agent),s=ks(e.content||"unknown error",this.opts.maxChars);this.print(` ${t("\u25C6")} ${t(e.agent)} ${c.error("\u2717")} ${c.error(s)}`),this.lastThinking=null}print(e){console.log(e)}}});var Qr,Cg=L(()=>{"use strict";Qr=class{plans=new Map;activePlanId=null;nextPlanNum=1;createPlan(e,t,s){let r=`plan_${this.nextPlanNum++}`,i={hablas:"Hablas",bob:"Bob",alex:"Alex",david:"David"},o={id:r,title:e,strategy:t,tasks:s.map((a,l)=>({task_id:`${r}_t${l+1}`,dependent_task_ids:a.dependent_task_ids||[],description:a.description,assignee:a.assignee,assigneeName:a.assigneeName||i[a.assignee]||a.assignee,status:"pending",createdAt:Date.now()})),createdAt:Date.now(),updatedAt:Date.now()};return this.plans.set(r,o),this.activePlanId=r,o}getActivePlan(){return this.activePlanId&&this.plans.get(this.activePlanId)||null}getTask(e){let t=this.getActivePlan();return t&&t.tasks.find(s=>s.task_id===e)||null}startTask(e){let t=this.getTask(e);return!t||!this.areDependenciesMet(e)?!1:(t.status="running",t.startedAt=Date.now(),this.touch(),!0)}finishTask(e,t){let s=this.getTask(e);return s?(s.status="done",s.result=t,s.completedAt=Date.now(),this.touch(),!0):!1}failTask(e,t){let s=this.getTask(e);return s?(s.status="failed",s.error=t,s.completedAt=Date.now(),this.touch(),!0):!1}skipTask(e){let t=this.getTask(e);return t?(t.status="skipped",t.completedAt=Date.now(),this.touch(),!0):!1}resetTask(e){let t=this.getTask(e);return t?(t.status="pending",t.result=void 0,t.error=void 0,t.startedAt=void 0,t.completedAt=void 0,this.touch(),!0):!1}replaceTask(e,t,s){let r=this.getTask(e);return r?(r.description=t,s&&(r.assignee=s),r.status="pending",r.result=void 0,r.error=void 0,this.touch(),!0):!1}areDependenciesMet(e){let t=this.getTask(e);if(!t)return!1;if(t.dependent_task_ids.length===0)return!0;let s=this.getActivePlan();return s?t.dependent_task_ids.every(r=>{let i=s.tasks.find(o=>o.task_id===r);return i&&(i.status==="done"||i.status==="skipped")}):!1}getNextTask(){let e=this.getActivePlan();if(!e)return null;for(let t of e.tasks)if(t.status==="pending"&&this.areDependenciesMet(t.task_id))return t;return null}getDependencyOrder(){let e=this.getActivePlan();if(!e)return[];let t=new Set,s=[],r=new Map(e.tasks.map(o=>[o.task_id,o])),i=o=>{if(t.has(o))return;t.add(o);let a=r.get(o);if(a){for(let l of a.dependent_task_ids)i(l);s.push(a)}};for(let o of e.tasks)i(o.task_id);return s}getProgress(){let e=this.getActivePlan();if(!e)return{total:0,done:0,failed:0,pending:0,running:0,skipped:0,percentage:0};let t=e.tasks.length,s=e.tasks.filter(u=>u.status==="done").length,r=e.tasks.filter(u=>u.status==="failed").length,i=e.tasks.filter(u=>u.status==="pending").length,o=e.tasks.filter(u=>u.status==="running").length,a=e.tasks.filter(u=>u.status==="skipped").length,l=t>0?Math.round((s+a)/t*100):0;return{total:t,done:s,failed:r,pending:i,running:o,skipped:a,percentage:l}}isComplete(){let e=this.getActivePlan();return e?e.tasks.every(t=>t.status==="done"||t.status==="failed"||t.status==="skipped"):!0}serialize(){let e=this.getActivePlan();return e?JSON.stringify(e,null,2):"{}"}deserialize(e){try{let t=JSON.parse(e);return t.id&&t.tasks?(this.plans.set(t.id,t),this.activePlanId=t.id,t):null}catch{return null}}reset(){this.plans.clear(),this.activePlanId=null,this.nextPlanNum=1}clear(){this.plans.clear(),this.activePlanId=null}touch(){let e=this.getActivePlan();e&&(e.updatedAt=Date.now())}}});var ue,at,b0,v0,w0,x0,S0,_0,A0,Zr,Eg=L(()=>{"use strict";ue=O(require("fs")),at=O(require("path")),b0=".hablas",v0=`# Project Context \u2014 Hablas AI
1071
-
1072
- ## Project Overview
1073
- <!-- Auto-populated by Hablas on first scan -->
1074
-
1075
- ## Goals & Objectives
1076
- <!-- What is this project trying to achieve? -->
1077
-
1078
- ## Key Decisions
1079
- | Date | Decision | By | Rationale | Impact |
1080
- |------|----------|-----|-----------|--------|
1081
-
1082
- ## Constraints & Requirements
1083
- <!-- Technical constraints, business rules, non-negotiables -->
1084
-
1085
- ## Team Notes
1086
- <!-- Freeform notes from agents and user -->
1087
- `,w0=`# Requirements & Progress
1088
-
1089
- ## Current Sprint
1090
- <!-- Active work items -->
1091
-
1092
- ## Requirements Overview
1093
- <!-- High-level requirements -->
1094
-
1095
- ## User Stories
1096
- <!-- As a [role], I want [feature], so that [benefit] -->
1097
-
1098
- ## Task Breakdown
1099
- | Task | Assignee | Status | Started | Completed |
1100
- |------|----------|--------|---------|-----------|
1101
-
1102
- ## Progress Log
1103
- <!-- Chronological log of all actions taken -->
1104
- `,x0=`# Architecture Design
1105
-
1106
- ## System Overview
1107
- <!-- High-level architecture description -->
1108
-
1109
- ## Tech Stack
1110
- | Layer | Technology | Rationale |
1111
- |-------|-----------|-----------|
1112
-
1113
- ## Module Design
1114
- | Module | Responsibility | Key Files | Dependencies |
1115
- |--------|---------------|-----------|-------------|
1116
-
1117
- ## API Design
1118
- <!-- Endpoints, contracts, protocols -->
1119
-
1120
- ## Data Model
1121
- <!-- Database schema, data flow -->
1122
-
1123
- ## Architecture Decision Records (ADRs)
1124
- | # | Decision | Status | Date | Context |
1125
- |---|----------|--------|------|---------|
1126
-
1127
- ## File Tree Plan
1128
- <!-- Planned or actual directory structure -->
1129
-
1130
- ## Implementation Guide
1131
- <!-- Step-by-step implementation order -->
1132
- `,S0=`# Agent Activity Log
1133
-
1134
- ## Session History
1135
- | Session | Date | Duration | Agents Used | Tasks Completed |
1136
- |---------|------|----------|-------------|-----------------|
1137
-
1138
- ## Delegation Log
1139
- | Time | From | To | Task | Model Used | Result | Duration |
1140
- |------|------|----|------|-----------|--------|----------|
1141
-
1142
- ## Agent Performance
1143
- | Agent | Total Tasks | Success Rate | Avg Duration | Specialties Used |
1144
- |-------|-------------|-------------|-------------|-----------------|
1145
-
1146
- ## Inter-Agent Communication
1147
- <!-- Messages exchanged between agents during complex tasks -->
1148
- `,_0=`# Learned Knowledge
1149
-
1150
- ## Project Conventions
1151
- <!-- Coding style, naming conventions, file organization patterns -->
1152
-
1153
- ## Discovered Patterns
1154
- <!-- Patterns found in the codebase by agents -->
1155
-
1156
- ## Known Gotchas
1157
- <!-- Things that went wrong and how they were fixed -->
1158
-
1159
- ## Auto-Discoveries
1160
- <!-- Automatically detected facts about the project -->
1161
-
1162
- ## Dependency Notes
1163
- <!-- Important notes about dependencies and versions -->
1164
- `,A0={"HABLAS.md":v0,"PROGRESS.md":w0,"ARCHITECTURE.md":x0,"AGENTS.md":S0,"MEMORY.md":_0},Zr=class{contextDir;sessionDelegations=[];sessionDiscoveries=[];constructor(e){this.contextDir=at.join(e,b0)}init(){let e=at.join(at.dirname(this.contextDir),".hablas-legacy");if(ue.existsSync(e)&&!ue.existsSync(this.contextDir))try{ue.renameSync(e,this.contextDir);let t=at.join(this.contextDir,"LEGACY.md"),s=at.join(this.contextDir,"HABLAS.md");ue.existsSync(t)&&!ue.existsSync(s)&&ue.renameSync(t,s)}catch{}ue.existsSync(this.contextDir)||ue.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(A0)){let r=at.join(this.contextDir,t);ue.existsSync(r)||ue.writeFileSync(r,s,"utf-8")}}exists(){return ue.existsSync(this.contextDir)}readContext(e){let t=at.join(this.contextDir,e);return ue.existsSync(t)?ue.readFileSync(t,"utf-8"):null}updateProgress(e){let t=new Date().toISOString().split("T")[0],s=new Date().toISOString().split("T")[1].split(".")[0],r=`- [${t} ${s}] ${e}`;this.appendToSection("PROGRESS.md","## Progress Log",r)}addTask(e,t){let s=new Date().toISOString().split("T")[0],r=`| ${e} | @${t} | \u{1F535} pending | ${s} | \u2014 |`;this.appendToSection("PROGRESS.md","## Task Breakdown",r)}updateSprint(e){this.updateSection("PROGRESS.md","## Current Sprint",e)}recordDecision(e,t,s,r="medium"){let o=`| ${new Date().toISOString().split("T")[0]} | ${e} | ${t} | ${s} | ${r} |`;this.appendToSection("HABLAS.md","## Key Decisions",o)}updateArchitecture(e,t){this.updateSection("ARCHITECTURE.md",e,t)}recordADR(e,t,s="accepted"){let r=new Date().toISOString().split("T")[0],a=`| ${((this.readContext("ARCHITECTURE.md")||"").match(/^\|/gm)||[]).length} | ${e} | ${s} | ${r} | ${t} |`;this.appendToSection("ARCHITECTURE.md","## Architecture Decision Records (ADRs)",a)}logDelegation(e){this.sessionDelegations.push(e);let t=`| ${e.time} | ${e.from} | ${e.to} | ${e.task.slice(0,50)} | ${e.model} | ${e.result} | ${e.durationMs}ms |`;this.appendToSection("AGENTS.md","## Delegation Log",t)}logSession(e){let t=`| ${e.sessionId} | ${e.date} | ${Math.round(e.duration/1e3)}s | ${e.agentsUsed.join(", ")} | ${e.tasksCompleted} |`;this.appendToSection("AGENTS.md","## Session History",t)}updateAgentPerformance(e,t,s,r,i){let o=`| @${e} | ${t} | ${Math.round(s*100)}% | ${Math.round(r)}ms | ${i.join(", ")} |`;this.appendToSection("AGENTS.md","## Agent Performance",o)}logAgentComm(e,t,s){let i=`- [${new Date().toISOString()}] **@${e}** \u2192 **@${t}**: ${s.slice(0,200)}`;this.appendToSection("AGENTS.md","## Inter-Agent Communication",i)}addConvention(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Project Conventions",r),this.sessionDiscoveries.push({type:"convention",description:e,source:t,date:s})}addPattern(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Discovered Patterns",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}addGotcha(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u26A0\uFE0F ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Known Gotchas",r),this.sessionDiscoveries.push({type:"gotcha",description:e,source:t,date:s})}addAutoDiscovery(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u{1F50D} ${e} *(by ${t})*`;this.appendToSection("MEMORY.md","## Auto-Discoveries",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}getSummary(e=3e4){let t=["HABLAS.md","PROGRESS.md","ARCHITECTURE.md","MEMORY.md"],s=[],r=0;for(let i of t){let o=this.readContext(i);if(o&&o.trim().length>0){let a=e-r;if(a<=200)break;let l=o.length>a?o.slice(0,a)+`
1165
- ...(truncated)`:o;s.push(`### ${i}
1166
- ${l}`),r+=l.length}}return s.length>0?s.join(`
1167
-
1168
- `):""}getAgentContext(e,t=15e3){let s=[],r=0,i=this.readContext("HABLAS.md");if(i){let o=this.extractSection(i,"## Project Overview"),a=this.extractSection(i,"## Key Decisions");o&&s.push(`## Project Overview
1169
- ${o}`),a&&s.push(`## Key Decisions
1170
- ${a}`),r=s.join(`
1171
- `).length}switch(e){case"emma":this.addContextFromFile(s,"PROGRESS.md",["## Requirements Overview","## User Stories","## Current Sprint"],t-r);break;case"bob":this.addContextFromFile(s,"ARCHITECTURE.md",["## System Overview","## Tech Stack","## Module Design","## Architecture Decision Records (ADRs)"],t-r),this.addContextFromFile(s,"MEMORY.md",["## Discovered Patterns","## Project Conventions"],t-r);break;case"alex":this.addContextFromFile(s,"ARCHITECTURE.md",["## Module Design","## File Tree Plan","## Implementation Guide"],t-r),this.addContextFromFile(s,"MEMORY.md",["## Project Conventions","## Known Gotchas"],t-r),this.addContextFromFile(s,"PROGRESS.md",["## Current Sprint","## Task Breakdown"],t-r);break;case"david":this.addContextFromFile(s,"MEMORY.md",["## Auto-Discoveries","## Dependency Notes"],t-r);break;default:let o=this.getSummary(t-r);o&&s.push(o)}return s.join(`
1172
-
1173
- `)}getSessionDelegations(){return[...this.sessionDelegations]}getSessionDiscoveries(){return[...this.sessionDiscoveries]}addContextFromFile(e,t,s,r){let i=this.readContext(t);if(!i)return;let o=0;for(let a of s){if(o>=r)break;let l=this.extractSection(i,a);if(l&&l.trim().length>10){let u=r-o,d=l.length>u?l.slice(0,u)+"...":l;e.push(`${a}
1174
- ${d}`),o+=d.length}}}extractSection(e,t){let s=e.split(`
1175
- `),r=s.findIndex(o=>o.trim()===t);if(r===-1)return null;let i=s.length;for(let o=r+1;o<s.length;o++)if(/^#{1,2}\s/.test(s[o])){i=o;break}return s.slice(r+1,i).join(`
1176
- `).trim()}updateSection(e,t,s){let r=at.join(this.contextDir,e);if(!ue.existsSync(r))return;let o=ue.readFileSync(r,"utf-8").split(`
1177
- `),a=o.findIndex(h=>h.trim()===t);if(a===-1)return;let l=o.length;for(let h=a+1;h<o.length;h++)if(/^#{1,2}\s/.test(o[h])){l=h;break}let u=o.slice(0,a+1),d=o.slice(l),f=[...u,s,"",...d].join(`
1178
- `);ue.writeFileSync(r,f,"utf-8")}appendToSection(e,t,s){let r=at.join(this.contextDir,e);ue.existsSync(r)||this.init();let i=ue.readFileSync(r,"utf-8"),o=i.split(`
1179
- `),a=o.findIndex(u=>u.trim()===t);if(a===-1){ue.writeFileSync(r,i+`
1180
- `+s+`
1181
- `,"utf-8");return}let l=a+1;for(;l<o.length;){let u=o[l].trim();if(/^#{1,2}\s/.test(u))break;l++}o.splice(l,0,s),ue.writeFileSync(r,o.join(`
1182
- `),"utf-8")}}});function Rg(n){let e=n.trim();if(e.length<20||e.length<15||Tg.test(e)||e.includes("```")||$0.test(e)||/\/[\w-]+\.[\w]+/.test(e)||e.length<60&&Tg.test(e))return null;for(let{pattern:t,question:s,choices:r}of k0)if(t.test(e))return e.length>40&&/\b(called|named|using|with|for)\b/i.test(e)?null:{question:s,choices:r,context:e};return null}function Og(n,e){let t=n.trim().toLowerCase(),s=t.split(/[,\s]+/).filter(i=>/^[a-z]$/.test(i));if(s.length>0)return s.map(i=>{let o=i.charCodeAt(0)-97;return e.choices[o]?.value}).filter(i=>i!==void 0);let r=t.split(/[,\s]+/).filter(i=>/^\d+$/.test(i));return r.length>0?r.map(i=>{let o=parseInt(i,10)-1;return e.choices[o]?.value}).filter(i=>i!==void 0):[t]}var k0,Tg,$0,Pg=L(()=>{"use strict";k0=[{pattern:/\b(create|make|build)\s+(a|an|the)?\s*(app|application|project)\b/i,question:"What type of application would you like to create?",choices:[{label:"Web application (React/Next.js)",value:"web"},{label:"CLI tool (Node.js)",value:"cli"},{label:"API server (Express/Fastify)",value:"api"},{label:"Something else (please describe)",value:"other"}]},{pattern:/\b(refactor|rewrite|restructure)\s+(the\s+)?(entire|whole|all)\b/i,question:"Large-scale refactoring detected. How would you like to proceed?",choices:[{label:"Incremental \u2014 one module at a time",value:"incremental"},{label:"Full rewrite \u2014 replace everything",value:"full"},{label:"Just the architecture \u2014 keep implementations",value:"architecture"},{label:"Let me specify which parts",value:"specify"}]},{pattern:/\b(delete|remove|drop)\s+(all|every|the\s+entire)\b/i,question:"This is a destructive operation. Please confirm scope:",choices:[{label:"Yes, remove everything matching",value:"all"},{label:"Only unused/dead code",value:"unused"},{label:"Let me be more specific",value:"specify"},{label:"Cancel \u2014 don't delete anything",value:"cancel"}]},{pattern:/\b(setup|configure|install)\s+(the\s+)?(project|environment|dev)\b/i,question:"What environment are you setting up?",choices:[{label:"Development (local)",value:"dev"},{label:"Production deployment",value:"prod"},{label:"CI/CD pipeline",value:"ci"},{label:"Docker/containerized",value:"docker"}]},{pattern:/\b(fix|debug|solve)\s+(the\s+)?(issue|bug|problem|error)\b/i,question:"Can you provide more details about the issue?",choices:[{label:"Runtime error (crashes/exceptions)",value:"runtime"},{label:"Build/compile error",value:"build"},{label:"Logic bug (wrong behavior)",value:"logic"},{label:"Performance issue (slow)",value:"performance"}]}],Tg=/[\w-]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|scss|html|vue|svelte|go|rs|java|c|cpp|h|rb|php|sql|sh|bash|toml|xml|env)/i,$0=/\b(fix|update|change|add|remove|rename|move|edit|read|show|cat|open)\s+(the\s+)?(typo|bug|error|import|line|function|variable|class|method|comment|style)/i});var ei,vt,ni,ti,Mg=L(()=>{"use strict";ei=O(require("fs")),vt=O(require("fs/promises")),ni=O(require("path")),ti=class{stack=[];workingDir;maxEntries;nextGroupId=1;constructor(e,t=200){this.workingDir=e,this.maxEntries=t}async record(e,t,s,r="hablas",i){let o=ni.resolve(this.workingDir,e),a=null;try{ei.existsSync(o)&&(a=await vt.readFile(o,"utf-8"))}catch{}let l={id:`undo_${Date.now()}_${this.stack.length}`,filePath:e,absolutePath:o,originalContent:a,newContent:t,toolName:s,agent:r,timestamp:Date.now(),undone:!1,groupId:i};return this.stack.push(l),this.stack.length>this.maxEntries&&(this.stack=this.stack.slice(-this.maxEntries)),l.id}beginGroup(){return`group_${this.nextGroupId++}`}async undo(e=1){let t=[],r=this.stack.filter(i=>!i.undone).reverse().slice(0,e);for(let i of r)try{i.originalContent===null?(ei.existsSync(i.absolutePath)&&await vt.unlink(i.absolutePath),t.push({file:i.filePath,success:!0})):(await vt.mkdir(ni.dirname(i.absolutePath),{recursive:!0}),await vt.writeFile(i.absolutePath,i.originalContent,"utf-8"),t.push({file:i.filePath,success:!0})),i.undone=!0}catch(o){t.push({file:i.filePath,success:!1,error:o.message})}return t}async undoGroup(e){let t=this.stack.filter(r=>r.groupId===e&&!r.undone).reverse(),s=[];for(let r of t)try{r.originalContent===null?ei.existsSync(r.absolutePath)&&await vt.unlink(r.absolutePath):await vt.writeFile(r.absolutePath,r.originalContent,"utf-8"),r.undone=!0,s.push({file:r.filePath,success:!0})}catch(i){s.push({file:r.filePath,success:!1,error:i.message})}return s}async undoAll(){return this.undo(this.getUndoableCount())}getUndoableCount(){return this.stack.filter(e=>!e.undone).length}getRecent(e=15){return this.stack.filter(t=>!t.undone).slice(-e).reverse()}getModifiedFiles(){let e=new Set;for(let t of this.stack.filter(s=>!s.undone))e.add(t.filePath);return Array.from(e)}formatList(e=15){let t=this.getRecent(e);if(t.length===0)return" No changes to undo";let s=[];for(let i=0;i<t.length;i++){let o=t[i],a=this.formatAge(o.timestamp),l=o.originalContent===null?"created":"modified",u=o.agent!=="hablas"?` [@${o.agent}]`:"";s.push(` ${i+1}. ${o.filePath} \u2014 ${l} by ${o.toolName}${u} (${a})`)}let r=this.getUndoableCount();return r>e&&s.push(` ... and ${r-e} more`),s.join(`
1183
- `)}formatAge(e){let t=Date.now()-e,s=Math.floor(t/1e3);if(s<60)return`${s}s ago`;let r=Math.floor(s/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}size(){return this.stack.length}clear(){this.stack=[]}}});function C0(n,e){let t=[],s;for(Ig.lastIndex=0;(s=Ig.exec(n))!==null;){let r=s[1],i=Ce.resolve(e,r);lt.existsSync(i)&&t.push(r)}return[...new Set(t)]}function E0(n,e,t){let s=[],r=Ce.extname(e),i=Ce.dirname(Ce.resolve(t,e));if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(r)){let o;for(Dg.lastIndex=0;(o=Dg.exec(n))!==null;){let a=o[1]||o[2];if(!a||!a.startsWith(".")&&!a.startsWith("/"))continue;let l=T0(a,i);l&&s.push(Ce.relative(t,l))}}else if(r===".py"){let o;for(Lg.lastIndex=0;(o=Lg.exec(n))!==null;){let a=o[1]||o[2];if(!a)continue;let l=a.replace(/\./g,"/")+".py",u=Ce.resolve(i,l);lt.existsSync(u)&&s.push(Ce.relative(t,u))}}return[...new Set(s)]}function T0(n,e){let t=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],s=Ce.resolve(e,n);if(lt.existsSync(s)&&lt.statSync(s).isFile())return s;for(let r of t){let i=s+r;if(lt.existsSync(i))return i}for(let r of t){let i=Ce.join(s,`index${r}`);if(lt.existsSync(i))return i}return null}function Fg(n,e,t){let s=t?.maxFiles||10,r=t?.maxTokens||8e3,i=t?.followImports!==!1,o=C0(n,e),a=[],l=new Set,u=0;for(let d of o){if(a.length>=s||u>=r)break;if(!l.has(d)){l.add(d);try{let f=Ce.resolve(e,d),h=lt.readFileSync(f,"utf-8"),m=h.split(`
1184
- `).length,p=Math.ceil(h.length/4);if(p>4e3){let g=h.split(`
1185
- `).slice(0,200).join(`
1186
- `)+`
1187
- ...(truncated)`,S=Math.ceil(g.length/4);u+S<=r&&(a.push({path:d,content:g,source:"mentioned",lineCount:200}),u+=S)}else if(u+p<=r&&(a.push({path:d,content:h,source:"mentioned",lineCount:m}),u+=p,i)){let g=E0(h,d,e);for(let S of g.slice(0,5)){if(a.length>=s||u>=r)break;if(!l.has(S)){l.add(S);try{let x=Ce.resolve(e,S),$=lt.readFileSync(x,"utf-8"),k=Math.ceil($.length/4),y=$.split(`
1188
- `).length;if(k>2e3){let b=$.split(`
1189
- `).slice(0,100).join(`
1190
- `)+`
1191
- ...(truncated)`,v=Math.ceil(b.length/4);u+v<=r&&(a.push({path:S,content:b,source:"imported",lineCount:100}),u+=v)}else u+k<=r&&(a.push({path:S,content:$,source:"imported",lineCount:y}),u+=k)}catch{}}}}}catch{}}}return{files:a,totalTokensEstimate:u,mentionedPaths:o}}function Ng(n){if(n.files.length===0)return"";let e=["## Referenced Files"];for(let t of n.files){let s=t.source==="imported"?" (imported)":"";e.push(`### ${t.path}${s} (${t.lineCount} lines)`),e.push("```"),e.push(t.content),e.push("```")}return e.join(`
1192
- `)}var lt,Ce,Ig,Dg,Lg,jg=L(()=>{"use strict";lt=O(require("fs")),Ce=O(require("path")),Ig=/(?:^|\s|['"`])([.\w\-/\\]+\.(?:ts|js|tsx|jsx|py|go|rs|java|c|cpp|h|css|scss|html|vue|svelte|json|yaml|yml|toml|md|sql|sh|env|xml))\b/gi,Dg=/(?:import\s+.*?\s+from\s+['"]([^'"]+)['"]|require\s*\(\s*['"]([^'"]+)['"]\s*\))/g,Lg=/(?:from\s+(\S+)\s+import|import\s+(\S+))/g});var Bg={};Le(Bg,{runSetupWizard:()=>Yl});function be(n,e){return new Promise(t=>{n.question(e,s=>t(s))})}function O0(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}async function Yl(n){let e=Hg.createInterface({input:process.stdin,output:process.stdout});switch(console.log(),console.log(`${xt}${Ee} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\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(`${xt}${Ee} hablas \u2014 Setup Wizard${I}`),console.log(`${q} Configure your AI provider and model${I}`),console.log(`${xt}${Ee} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\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(`${xt} Choose your setup:${I}`),console.log(),console.log(` ${R0}${xt}1${I}. ${xt}Hablas Integrated Engine${I} ${ct}(instant \u2014 no setup needed)${I}`),console.log(` ${q}Pre-configured cloud AI, ready to use immediately${I}`),console.log(),console.log(` ${Ee}${xt}2${I}. ${xt}Custom Provider${I} ${q}(bring your own API key)${I}`),console.log(` ${q}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${I}`),console.log(),(await be(e,` ${q}Your choice (1-2):${I} `)).trim()){case"1":{n.provider=Wt.provider,n.apiUrl=Wt.apiUrl,n.apiKey=O0(),n.model=Wt.model,gt(n),Qe({name:Wt.name,apiUrl:Wt.apiUrl,apiKey:n.apiKey,models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.3-70b-instruct","deepseek-ai/deepseek-r1"],defaultModel:Wt.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ct} \u2713 Hablas Integrated Engine activated!${I}`),console.log(`${q} Model: ${Wt.model}${I}`),console.log(`${q} API: ${Wt.apiUrl}${I}`),console.log(`${q} No API key needed \u2014 everything is pre-configured.${I}`);break}case"2":{switch(console.log(),console.log(`${q} Select your provider:${I}`),console.log(` ${Ee}a${I}. Ollama (local, free, private)`),console.log(` ${Ee}b${I}. OpenAI API`),console.log(` ${Ee}c${I}. Groq (fast, free tier)`),console.log(` ${Ee}d${I}. OpenRouter (many models)`),console.log(` ${Ee}e${I}. Together AI`),console.log(` ${Ee}f${I}. DeepSeek`),console.log(` ${Ee}g${I}. Custom OpenAI-compatible API`),console.log(` ${Ee}h${I}. NVIDIA NIM (powerful cloud models)`),console.log(),(await be(e,` ${q}Your choice (a-h):${I} `)).trim().toLowerCase()){case"a":{n.provider="ollama";let r=await be(e,` ${q}Ollama host [http://localhost:11434]:${I} `);r.trim()&&(n.ollamaHost=r.trim());let i=await be(e,` ${q}Model [qwen2.5-coder:7b]:${I} `);i.trim()&&(n.model=i.trim()),gt(n),console.log(),console.log(`${ct} \u2713 Configured for Ollama${I}`),console.log(`${q} Model: ${n.model}${I}`),console.log(`${q} Host: ${n.ollamaHost}${I}`),console.log(`${q} Make sure Ollama is running: ollama serve${I}`);break}case"b":{let r=await be(e,` ${q}OpenAI API Key (sk-...):${I} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${I}`);break}let i=await be(e,` ${q}Model [gpt-4o]:${I} `);n.provider="custom",n.apiUrl="https://api.openai.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"gpt-4o",gt(n),Qe({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(`${ct} \u2713 Configured for OpenAI${I}`),console.log(`${q} Model: ${n.model}${I}`);break}case"c":{let r=await be(e,` ${q}Groq API Key (gsk_...):${I} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${I}`);break}let i=await be(e,` ${q}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",gt(n),Qe({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(`${ct} \u2713 Configured for Groq${I}`),console.log(`${q} Model: ${n.model}${I}`);break}case"d":{let r=await be(e,` ${q}OpenRouter API Key (sk-or-...):${I} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${I}`);break}let i=await be(e,` ${q}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",gt(n),Qe({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(`${ct} \u2713 Configured for OpenRouter${I}`),console.log(`${q} Model: ${n.model}${I}`);break}case"e":{let r=await be(e,` ${q}Together API Key:${I} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${I}`);break}let i=await be(e,` ${q}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",gt(n),Qe({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(`${ct} \u2713 Configured for Together AI${I}`),console.log(`${q} Model: ${n.model}${I}`);break}case"f":{let r=await be(e,` ${q}DeepSeek API Key:${I} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${I}`);break}let i=await be(e,` ${q}Model [deepseek-chat]:${I} `);n.provider="custom",n.apiUrl="https://api.deepseek.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"deepseek-chat",gt(n),Qe({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(`${ct} \u2713 Configured for DeepSeek${I}`),console.log(`${q} Model: ${n.model}${I}`);break}case"g":{let r=await be(e,` ${q}Provider name:${I} `);if(!r.trim()){console.log(`${wt} \u26A0 Cancelled${I}`);break}let i=await be(e,` ${q}API base URL:${I} `);if(!i.trim()){console.log(`${wt} \u26A0 URL is required \u2014 cancelled${I}`);break}let o=await be(e,` ${q}API Key (leave empty if none):${I} `),a=await be(e,` ${q}Default model ID:${I} `);n.provider="custom",n.apiUrl=i.trim(),n.apiKey=o.trim(),n.model=a.trim()||"default",gt(n),Qe({name:r.trim(),apiUrl:i.trim(),apiKey:o.trim(),models:[n.model],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ct} \u2713 Configured for ${r.trim()}${I}`),console.log(`${q} URL: ${i.trim()}${I}`),console.log(`${q} Model: ${n.model}${I}`);break}case"h":{let r=await be(e,` ${q}NVIDIA API Key (nvapi-...):${I} `);if(!r.trim()){console.log(`${wt} \u26A0 No key provided \u2014 cancelled${I}`),console.log(`${q} Get your key at: https://build.nvidia.com/${I}`);break}let{NVIDIA_PROVIDER:i}=await Promise.resolve().then(()=>(Kn(),Sc));console.log(),console.log(`${q} Available NVIDIA models:${I}`),i.models.forEach((u,d)=>{console.log(` ${Ee}${d+1}${I}. ${u}`)}),console.log();let o=await be(e,` ${q}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,gt(n),Qe({name:"NVIDIA",apiUrl:i.apiUrl,apiKey:r.trim(),models:i.models,defaultModel:l,addedAt:new Date().toISOString()}),console.log(),console.log(`${ct} \u2713 Configured for NVIDIA NIM${I}`),console.log(`${q} Model: ${l}${I}`),console.log(`${q} API: ${i.apiUrl}${I}`);break}default:console.log(`${wt} \u26A0 Invalid choice${I}`)}break}default:console.log(`${wt} \u26A0 Invalid choice \u2014 please select 1 or 2${I}`)}console.log(),console.log(`${xt}${ct} \u2713 Setup complete!${I}`),console.log(),console.log(`${xt} Start Hablas:${I}`),console.log(),console.log(` ${Ee}hablas${I} \u2192 Interactive REPL`),console.log(` ${Ee}hablas --auto${I} \u2192 Interactive REPL with auto-confirm for tools`),console.log(` ${Ee}hablas run "your prompt"${I} \u2192 One-shot non-interactive prompt`),console.log(),console.log(`${q} Hablas now uses one unified runtime: direct leader handling for simple requests,`),console.log(`${q} and internal specialist coordination for serious engineering work.${I}`),console.log(),e.close()}var Hg,Ee,ct,wt,q,xt,I,R0,Wt,Jl=L(()=>{"use strict";Hg=O(require("readline"));kr();ki();Ee="\x1B[36m",ct="\x1B[32m",wt="\x1B[33m",q="\x1B[2m",xt="\x1B[1m",I="\x1B[0m",R0="\x1B[35m";Wt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"}});var Ug=L(()=>{"use strict"});var $s,Xl=L(()=>{"use strict";$s=class{snapshots=new Map;traceEvents=[];initializeFromContract(e){let t={taskContractId:e.id,currentGoal:e.intent,currentStepId:null,completedSteps:[],pendingSteps:[],failedSteps:[],artifacts:{},errors:[],lastUpdated:new Date,traceId:e.traceId};return this.snapshots.set(e.id,t),this.emitTrace({traceId:e.traceId,timestamp:new Date,layer:"StateManager",eventType:"state_initialized",payload:{taskContractId:e.id,intent:e.intent}}),t}getSnapshot(e){return this.snapshots.get(e)}setCurrentStep(e,t){let s=this.snapshots.get(e);if(!s)throw new Error(`No state for task ${e}`);s.currentStepId=t,s.lastUpdated=new Date,this.emitTrace({traceId:s.traceId,timestamp:new Date,layer:"StateManager",eventType:"current_step_updated",payload:{taskContractId:e,stepId:t}})}completeStep(e,t,s={}){let r=this.snapshots.get(e);if(!r)throw new Error(`No state for task ${e}`);r.completedSteps.includes(t)||r.completedSteps.push(t),r.pendingSteps=r.pendingSteps.filter(i=>i!==t),r.artifacts={...r.artifacts,...s},r.lastUpdated=new Date,this.emitTrace({traceId:r.traceId,timestamp:new Date,layer:"StateManager",eventType:"step_completed",payload:{taskContractId:e,stepId:t,artifactsCount:Object.keys(s).length}})}failStep(e,t,s){let r=this.snapshots.get(e);if(!r)throw new Error(`No state for task ${e}`);r.failedSteps.includes(t)||r.failedSteps.push(t),r.errors.push({stepId:t,error:s,timestamp:new Date}),r.lastUpdated=new Date,this.emitTrace({traceId:r.traceId,timestamp:new Date,layer:"StateManager",eventType:"step_failed",payload:{taskContractId:e,stepId:t,error:s}})}recordArtifact(e,t,s){let r=this.snapshots.get(e);if(!r)throw new Error(`No state for task ${e}`);r.artifacts[t]=s,r.lastUpdated=new Date,this.emitTrace({traceId:r.traceId,timestamp:new Date,layer:"StateManager",eventType:"artifact_recorded",payload:{taskContractId:e,key:t}})}getTrace(e){return this.traceEvents.filter(t=>t.traceId===e)}emitTrace(e){this.traceEvents.push(e)}getCurrentSnapshotForTransition(e){return this.getSnapshot(e)}}});var Cs,Ql=L(()=>{"use strict";Cs=class{build(e,t){return{id:`task_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,originalInput:e,intent:this.extractIntent(e,t),risk:this.assessRisk(e,t),requiredTools:this.inferRequiredTools(e,t),requiredAgents:this.inferRequiredAgents(t),requiredMemory:this.inferRequiredMemory(e,t),validationRequired:t.executionPath==="team",stopConditions:this.buildStopConditions(t),completionCriteria:this.buildCompletionCriteria(t),oneStepDelivery:t.specialFlags.oneStepFinished??!1,continuityMode:t.specialFlags.continuityMode??!1,createdAt:new Date,routerDecision:t,traceId:t.traceId}}extractIntent(e,t){return t.taskKind==="analysis"?"Analyze, structure, and advise on the requested work":t.taskKind==="implementation"?"Implement or modify the requested software work":/version|what is|who are you|explain|how does/i.test(e)?"Answer the user directly":"Handle the user request clearly and directly"}assessRisk(e,t){return t.specialFlags.oneStepFinished?"high":t.executionPath==="team"&&t.specialFlags.requiresWrite?"medium":/production|deploy|database|delete|migration/i.test(e)?"high":t.executionPath==="team"?"medium":"low"}inferRequiredTools(e,t){let s=new Set,r=e.toLowerCase();return t.executionPath==="direct"?(/read|check|inspect|status|version|file|package\.json|src\//i.test(e)&&(s.add("read_file"),s.add("list_dir")),t.specialFlags.requiresResearch&&s.add("web_search_v2"),[...s]):(s.add("read_file"),s.add("list_dir"),t.taskKind==="analysis"?((t.specialFlags.requiresWrite||/prd|doc|document|architecture|blueprint/i.test(r))&&s.add("write_file"),t.specialFlags.requiresResearch&&s.add("web_search_v2"),[...s]):(s.add("write_file"),s.add("patch_file"),s.add("edit_file"),(/run|test|dev|build|install|lint/i.test(r)||t.oneStepFinished)&&s.add("run_command"),t.specialFlags.requiresResearch&&s.add("web_search_v2"),[...s]))}inferRequiredAgents(e){return e.executionPath==="direct"?["hablas"]:e.taskKind==="analysis"?["hablas","emma","bob","david"]:["hablas","emma","bob","alex","david"]}inferRequiredMemory(e,t){let s=["user_preferences"];return(t.specialFlags.continuityMode||/existing|previous|current project|unfinished/i.test(e))&&s.push("project_context","previous_artifacts"),s}buildStopConditions(e){let t=["max_iterations_reached","critical_error"];return e.specialFlags.oneStepFinished&&t.push("one_step_delivery_completed"),t}buildCompletionCriteria(e){let t=["The response addresses the request clearly"];return e.executionPath==="team"&&t.push("All planned specialist work completed"),e.specialFlags.oneStepFinished&&t.push("Deliver a complete runnable result without asking follow-up questions"),e.specialFlags.continuityMode&&t.push("Reuse existing project context instead of restarting from zero"),t}}});var P0,M0,I0,D0,L0,F0,N0,j0,H0,Es,Zl=L(()=>{"use strict";P0=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|كيفك|مرحبا|أهلا|هلا)[.!?\s]*$/i,M0=/^(what|how|why|when|where|who|which|can|is|are|do|does|will|would|should)\b/i,I0=/\b(build|create|implement|write|code|fix|debug|refactor|edit|change|update|generate|setup|configure|deploy|test|run|ship|complete)\b/i,D0=/\b(component|feature|frontend|backend|api|endpoint|database|schema|react|typescript|node|auth|login|project|app|application|repo|file|files|src|ui|ux)\b/i,L0=/\b(design|architecture|architect|blueprint|prd|requirements|research|analyze|compare|investigate|plan|document|docs|documentation|approach|strategy)\b/i,F0=/\b(create|implement|write|code|fix|edit|change|update|generate|setup|configure|deploy|test|run|refactor|ship|complete)\b/i,N0=/\b(research|compare|investigate|best practice|benchmark|documentation|docs)\b/i,j0=/\b(unfinished|continue|resume|previous|from the prd|from the previous|existing project|current project|this and there)\b/i,H0=/\b(one step|no ask|no questions|just give me|deliver complete|finished project|finished web project|run it)\b/i,Es=class{decide(e){let t=`trace_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,s=e.trim(),r=s.toLowerCase(),i=j0.test(r),o=H0.test(r),a=I0.test(r),l=D0.test(r),u=L0.test(r),d=a||i||o||l&&!u&&s.length>24,f=F0.test(r)||o,h=N0.test(r)||u;if(P0.test(s)&&!d&&!u)return{executionPath:"direct",taskKind:"conversation",confidence:.99,reason:"Pure social interaction with no engineering signal.",requiresClarification:!1,specialFlags:{},traceId:t};let m=M0.test(r)||s.endsWith("?"),p=s.length<120;return m&&p&&!a&&!i&&!o?{executionPath:"direct",taskKind:"conversation",confidence:.86,reason:"Focused question suitable for direct leader handling.",requiresClarification:!1,specialFlags:{requiresResearch:h},traceId:t}:u&&!a&&!o?{executionPath:"team",taskKind:"analysis",confidence:.93,reason:i?"Analysis task requires continuity over existing project context.":"High-level analysis or architecture task needs coordinated specialists.",requiresClarification:!1,specialFlags:{continuityMode:i,requiresResearch:h,requiresWrite:f},traceId:t}:{executionPath:d?"team":"direct",taskKind:d?"implementation":"conversation",confidence:d?.95:.7,reason:d?"Engineering work should run through the coordinated team path.":"Defaulting to direct handling because no strong implementation signal was found.",requiresClarification:!1,specialFlags:{continuityMode:i,oneStepFinished:o,requiresWrite:f,requiresResearch:h},traceId:t}}}});var Ts,ec=L(()=>{"use strict";Ts=class{createPlan(e){let t=`plan_${Date.now()}`,s=[],r=1,{executionPath:i,taskKind:o}=e.routerDecision;return i==="direct"?(s.push({id:"step_hablas_direct",order:r++,description:"Handle the request directly as Hablas, using tools only if genuinely needed.",assignedAgent:"hablas",requiredTools:e.requiredTools,dependencies:[],expectedArtifacts:["final_response"]}),{id:t,taskContractId:e.id,steps:s,strategy:"sequential",estimatedRisk:e.risk,createdAt:new Date,traceId:e.traceId}):(e.continuityMode&&s.push({id:"step_load_context",order:r++,description:"Load and reuse existing project files, docs, and relevant artifacts before doing new work.",assignedAgent:"emma",requiredTools:["read_file","list_dir"],dependencies:[],expectedArtifacts:["continuity_context"]}),o==="analysis"?(s.push({id:"step_emma_analysis",order:r++,description:"Frame the request, clarify scope internally, and structure requirements or PRD-level thinking.",assignedAgent:"emma",requiredTools:["read_file","list_dir"],dependencies:e.continuityMode?["step_load_context"]:[],expectedArtifacts:["requirements_summary"]}),s.push({id:"step_bob_analysis",order:r++,description:"Produce the architecture, design trade-offs, and system structure.",assignedAgent:"bob",requiredTools:["read_file","write_file"],dependencies:["step_emma_analysis"],expectedArtifacts:["architecture_notes"]}),s.push({id:"step_david_analysis",order:r++,description:"Research supporting references, comparisons, and implementation considerations.",assignedAgent:"david",requiredTools:["read_file","web_search_v2"],dependencies:[],expectedArtifacts:["research_notes"]})):(s.push({id:"step_emma_impl",order:r++,description:"Frame the implementation scope and user-facing requirements.",assignedAgent:"emma",requiredTools:["read_file","list_dir"],dependencies:e.continuityMode?["step_load_context"]:[],expectedArtifacts:["implementation_scope"]}),s.push({id:"step_bob_impl",order:r++,description:"Define the technical structure, approach, and constraints for the implementation.",assignedAgent:"bob",requiredTools:["read_file","write_file"],dependencies:["step_emma_impl"],expectedArtifacts:["technical_plan"]}),s.push({id:"step_alex_impl",order:r++,description:e.oneStepDelivery?"Deliver the complete runnable implementation in one pass with no follow-up questions.":"Execute the implementation and produce the concrete code changes.",assignedAgent:"alex",requiredTools:["read_file","write_file","patch_file","edit_file","run_command"],dependencies:["step_bob_impl"],expectedArtifacts:["code_changes","runnable_result"]}),s.push({id:"step_david_support",order:r++,description:"Provide supporting research, verification notes, or comparisons when useful.",assignedAgent:"david",requiredTools:["read_file","web_search_v2"],dependencies:[],expectedArtifacts:["supporting_notes"]})),{id:t,taskContractId:e.id,steps:s,strategy:"mixed",estimatedRisk:e.risk,createdAt:new Date,traceId:e.traceId})}}});var qg=L(()=>{"use strict"});var Kg=L(()=>{"use strict"});var Wg=L(()=>{"use strict"});var Bn,Gg=L(()=>{"use strict";Zl();Ql();Xl();ec();Bn=class{router=new Es;builder=new Cs;stateManager=new $s;planner=new Ts;async processUserInput(e){let t=this.router.decide(e),s=this.builder.build(e,t);this.stateManager.initializeFromContract(s);let r=this.planner.createPlan(s);return this.stateManager.recordArtifact(s.id,"execution_path",t.executionPath),this.stateManager.recordArtifact(s.id,"task_kind",t.taskKind),s.continuityMode&&this.stateManager.recordArtifact(s.id,"continuity_mode",!0),s.oneStepDelivery&&this.stateManager.recordArtifact(s.id,"one_step_delivery",!0),{contract:s,plan:r,finalState:this.stateManager.getSnapshot(s.id),trace:this.stateManager.getTrace(s.traceId)}}}});var Vg=L(()=>{"use strict";Ug();Xl();Ql();Zl();ec();qg();Kg();Wg();Gg()});var jt={};Le(jt,{activeCollabManager:()=>Te,runFullTeamCommand:()=>V0,runSingleCommand:()=>z0,startRepl:()=>sc});function K0(){return!ut.existsSync(tc)}function zg(){return ut.existsSync(B0)}function W0(){let n=Dt.dirname(tc);ut.existsSync(n)||ut.mkdirSync(n,{recursive:!0}),ut.writeFileSync(tc,new Date().toISOString(),"utf-8")}async function G0(n,e=10){let t=n.split(/(\s+)/);for(let s of t)process.stdout.write(s),await new Promise(r=>setTimeout(r,e))}async function Xg(n,e,t,s,r){let{interactive:i,autoMode:o,input:a,logger:l,abortSignal:u,onToolCall:d,skipTools:f}=r,h=r.reactEngine??Ss(),m=r.errorRecovery??_s(),p=new Ne("Hablas is thinking");p.start();let g=$=>{p&&(p.stop($),p=null)},S=hg({autoMode:o,interactive:i,confirm:a?$=>a.confirm($):void 0,confirmDangerous:a?$=>a.confirmDangerous($):void 0});await Yr({identity:{name:"Hablas",title:"Team Leader",role:"hablas"},client:e,registry:t,session:n,contextManager:s,reactEngine:h,errorRecovery:m,logger:l,io:{onAssistantText:async $=>{g(),console.log(Jt("Hablas","Team Leader")),await G0(Xt($))},onToolStart:($,k)=>{g(),console.log(vu($,k)),p=new Ne("Continuing"),p.start()},onToolEnd:($,k,y,b)=>{g(),console.log(wu(k,y,b))},onNotice:($,k)=>{g(),console.log(k==="retry"?c.muted(` \u21BB ${$}`):j($))},onError:$=>{g(),$.includes("ECONNREFUSED")?console.log(He("Connection lost","Check your provider connection or run /provider test")):/timeout/i.test($)?console.log(He("Request timed out (120s)","The API is slow. Try again or use a faster model.")):$.includes("429")?console.log(He("Rate limited by API","Wait a moment and try again, or switch providers.")):$.includes("model")?console.log(He("Model error","Check model availability: /models")):console.log(He(`Error: ${$}`,"Try again or check /status"))},onToolCall:()=>{d&&d()}},safetyPolicy:S,abortSignal:u,skipTools:f,maxIterations:U0}),g()}async function sc(n,e){Gp();let t=n.workingDirectory==="."?process.cwd():n.workingDirectory,s=Z=>ut.existsSync(Dt.join(Z,".git"));if(!s(t)&&!n.team?.enabled)console.log(` ${c.warning("\u26A0")} ${c.secondary("Not in a Git repository. Versioning and auto-sync features are limited.")}
1193
- `);else if(n.team?.enabled&&!s(t)){console.log(`
1194
- ${c.accent("\u2726")} ${c.strong("Team Mode Strategy Required")}`),console.log(` ${c.muted("Collaboration requires a stable Git repository root.")}
1195
- `);let te=await new ms(t).prompt(` ${c.primary("\u203A")} Specify repo path OR type 'init' to start here: `);if(te.trim().toLowerCase()==="init")try{(0,Jg.execSync)("git init",{cwd:t,stdio:"ignore"}),console.log(` ${c.success("\u2713")} Git repository initialized in ${c.highlight(t)}
1196
- `)}catch{console.log(_e("Failed to initialize Git. Please run git init manually.")),process.exit(1)}else{let J=Dt.resolve(t,te.trim());ut.existsSync(J)&&s(J)?(t=J,n.workingDirectory=t,console.log(` ${c.success("\u2713")} Context switched to repository: ${c.highlight(t)}
1197
- `)):(console.log(_e(`Path "${J}" is not a valid Git repository.`)),process.exit(1))}}let r=Pe(n),i=new En(t,n),o=new sn(n),a=new ms(t),l=$r(),u=new Cr,d=new ys(t),f=new Nn(t),h=new Qr,m=new Dn(n);m.setToolRegistry(i);let p=new Ln,g=new Hn(p,{hideActs:!0}).attach(),S=new Fn(n,{tokenBudget:3e3,maxChars:400});if(m.setChannel(p),n.team?.enabled){let Z=n.team.user||"developer",te=n.team.key||"default-key";Te=new ds(t,n,Z,te),await Te.init()&&console.log(` ${c.success("\u2713")} ${c.muted("[Team]")} Scoped cooperative sync initialized successfully.
1198
- `)}let x=new ti(t);f.init();let $=null;n.context?.hablasCoreEnabled&&($=new Zr(t),$.init());let k=await bn(t,n),y=l.getActive(),b=y?y.systemPrompt:Qn,v=vn(b,k,d,f),w=Ss({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:150,minConfidence:.6}),_=_s(3),T=new rn(v,n.historySize),P=Vn();P=qi(P),pn(P);let C=0,F=0,H=Date.now(),W=n.autoMode||!1,E=0,A=new AbortController;process.on("SIGINT",()=>{let Z=Date.now();if(Z-E<q0){console.log(ro({turns:C,duration:Date.now()-H,toolCalls:F}));let te=Te?Te.shutdown():Promise.resolve();Promise.resolve(te).finally(()=>process.exit(0)),setTimeout(()=>process.exit(0),2e3);return}E=Z,A.abort(),A=new AbortController,process.stdout.write(`
1199
- `),console.log(j("Operation cancelled \u2014 press Ctrl+C again to exit"))});let V=Fs(n);if(console.log(pu(n.model,t)),n.provider==="custom"&&console.log(fe(`Provider: ${V}`)),W&&console.log(fe("Auto mode enabled \u2014 tool confirmations skipped (plan approval still required)")),(K0()||!zg())&&(console.log(gu()),console.log(""),console.log(fe("First run detected \u2014 launching setup wizard...")),console.log(""),a.close(),await Yl(n),W0(),r=Pe(n),a.reinitialize()),zg()){let Z=new Ne("Connecting");Z.start();let te=await r.checkConnection();if(Z.stop(te?"ready":void 0),te){let J=await r.listModels();console.log(Y(`Connected \xB7 ${J.length} models available`)),n.provider==="ollama"&&!J.includes(n.model)&&console.log(j(`Model "${n.model}" not found. Pull: ollama pull ${n.model}`))}else n.provider==="custom"?console.log(He(`Cannot connect to ${n.apiUrl}`,"Check your --api-url and --api-key, or run /provider test")):n.provider==="nvidia"?console.log(He("Cannot connect to NVIDIA NIM","Check your API key or run: hablas --setup")):console.log(He("Cannot connect to Ollama","Start it with: ollama serve \u2014 or switch provider: /provider"))}console.log(hu()),console.log(),console.log(fe("Unified runtime active \u2014 simple requests stay direct, serious engineering work coordinates the internal team.")),console.log();let U=!0;for(;U;)try{let te=(await a.prompt(` ${c.primary("\u203A")} `)).trim();if(!te)continue;if(te.startsWith("/")){if(await Gu(te,n,r,i,o,T,t,a,C,l,u,d,X=>{r=X},f,h,x,m)==="quit"){U=!1;break}continue}e.info({input:te},"Processing user input");let J=jc(te),de=Qg(J,t);if(C++,console.log(xu(C)),P=Ki(P),pn(P),!W){let oe=Rg(de);if(oe){console.log(ku(oe));let X=await a.prompt(` ${c.muted("\u203A")} `),K=Og(X,oe);de=`${de}
1200
- [Clarification: ${K.join(", ")}]`}}let Re=Fg(de,t,{maxFiles:8,maxTokens:6e3});if(Re.files.length>0){let oe=Ng(Re);T.addUserMessage(`[Auto-loaded ${Re.files.length} file(s): ${Re.mentionedPaths.join(", ")}]
1201
- ${oe}`,{priority:"low",tags:["auto-inject"]})}if(n.team?.enabled&&Te){let oe=n.team?.user||Te.getLocalState().my_username,X=Re.mentionedPaths||[];if(X.length>0){let K=await Te.fetchLocks(),dt=X.map(Oe=>K.find(M=>M.file_path===Oe&&M.locked_by!==oe)).filter(Oe=>!!Oe);if(dt.length>0){let Oe=dt[0];console.log(`
1202
- ${c.architect("\u25C6")} ${c.strong("@Consul")} [Coordinator] detected an active lock held by a teammate.`),console.log(`
1203
- ${c.error("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")}`),console.log(` ${c.error("\u2551")} ${c.strong("\u{1F512} FILE LOCKED BY TEAMMATE")} ${c.error("\u2551")}`),console.log(` ${c.error("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563")}`),console.log(` ${c.error("\u2551")} File ${c.highlight(Oe.file_path.padEnd(44))} held by ${c.strong(`@${(Oe.locked_by||"").padEnd(12)}`)} ${c.error("\u2551")}`),console.log(` ${c.error("\u2551")} Context: ${c.muted((Oe.lock_context||"\u2014").slice(0,61).padEnd(61))} ${c.error("\u2551")}`),console.log(` ${c.error("\u2551")} @Consul halted this turn to prevent a Git conflict on the shared repo. ${c.error("\u2551")}`),console.log(` ${c.error("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")}`);for(let M of dt)await Te.sendMessage(M.locked_by,`@${oe} needs to edit ${M.file_path}. Please release the lock when you can.`);console.log(` ${c.muted("@Consul notified the teammate(s). Try again once the lock is released, or coordinate directly.")}
1204
- `);continue}for(let Oe of X)if(!await Te.acquireLock(Oe,de.slice(0,100))){console.log(`
1205
- ${c.warning("\u26A0")} ${c.strong("@Consul")}: a teammate locked ${c.highlight(Oe)} first. Halting to avoid a conflict.
1206
- `);continue}}Te.setActivity(de.slice(0,80))}try{let X=await new Bn().processUserInput(de);if(console.error("[UNIFIED-RUNTIME]",JSON.stringify({traceId:X.contract.traceId,executionPath:X.contract.routerDecision.executionPath,taskKind:X.contract.routerDecision.taskKind,oneStep:X.contract.oneStepDelivery,continuity:X.contract.continuityMode,requiredAgents:X.contract.requiredAgents,planStepCount:X.plan.steps.length})),X.contract.routerDecision.executionPath==="team"){let K=X.contract.requiredAgents;for(let ee of K)P=Gi(P,ee);pn(P),p.reset(),S.resetBudget();let dt={id:`unified-runtime-${X.plan.id}`,description:de.substring(0,100),tasks:X.plan.steps.map(ee=>({role:ee.assignedAgent,description:ee.description+(X.contract.continuityMode?" [CONTINUITY]":"")+(X.contract.oneStepDelivery?" [ONE-STEP DELIVERY]":"")})),strategy:X.plan.strategy,createdAt:X.plan.createdAt,approved:!0},Oe=i.getOllamaTools(),M=new jn(p,m,S,n);try{let{finalSynthesis:ee,synthesisOk:D}=await M.run(de,dt,Oe,{abortSignal:A?.signal,peerReview:!0,centralizedToLeader:!0});console.log(Jt("Hablas","Team Leader")),console.log(Xt(ee)),T.addAssistantMessage(D?ee:`[Team Summary]
1207
- `+ee)}catch(ee){let D=ee?.message||String(ee);console.log(_e(`Team error: ${D}`)),T.addAssistantMessage(`[Team Summary]
1208
- Error during coordinated execution.`)}await Yg(n,t);continue}T.addUserMessage(de)}catch(oe){process.env.HABLAS_RUNTIME_DEBUG==="true"&&console.error("[UNIFIED-RUNTIME-ERROR]",oe?.message||String(oe)),T.addUserMessage(de)}A=new AbortController,w.startTurn(),_.resetTurn(),await Xg(T,r,i,o,{interactive:!0,autoMode:W,input:a,logger:e,config:n,abortSignal:A.signal,reactEngine:w,errorRecovery:_,skipTools:!1,onToolCall:()=>{F++,P=Wi(P,"tool_call"),pn(P)}}),await Yg(n,t)}catch(Z){if(Z.code==="ERR_USE_AFTER_CLOSE")break;if(Z.name==="AbortError")continue;console.log(_e(Z.message)),e.error(Z,"REPL error")}a.close(),Te&&await Te.shutdown(),console.log(ro({turns:C,duration:Date.now()-H,toolCalls:F}))}async function V0(n,e,t,s="build"){let r=e.workingDirectory==="."?process.cwd():e.workingDirectory;e.agents.enabled=!0;let i=Pe(e),o=new En(r,e),a=new Dn(e);a.setToolRegistry(o);let l=new Ln,u=new Hn(l,{hideActs:!0}).attach(),d=new Fn(e,{tokenBudget:3e3,maxChars:400});a.setChannel(l),l.onEvent(x=>{x.type==="phase"?console.log(`
1209
- ${c.accent("\u25C6")} ${c.strong(x.content)}`):x.type==="handoff"?console.log(` ${c.muted("\u2605")} ${x.agent} \u2501\u2501\u25B6 ${x.to}`):x.type==="speak"?console.log(` ${c.primary(x.agent)}: ${x.content}`):x.type==="act"||x.type==="tool"?console.log(` ${c.warning("\u{1F527}")} [${x.agent}] ${x.content||x.toolName}`):x.type==="summary"||x.type==="observe"?console.log(` ${c.success("\u2713")} ${x.agent||""} ${x.content||""}`):x.type==="error"&&console.log(` ${c.error("\u2717")} ${x.agent}: ${x.content}`)}),console.log(`
1210
- ${c.accent("\u2605")} ${c.strong("FULL TEAM "+s.toUpperCase())} \u2014 ${e.model} (classification deleted, max power)`);let f={id:`${s}-`+Date.now(),description:n.substring(0,100),tasks:[{role:"emma",description:"Analyze the request from product/requirements perspective and clarify if needed."},{role:"bob",description:"Provide architecture, design or structural guidance."},{role:"alex",description:"Execute the core implementation, coding or action based on the input."},{role:"david",description:"Research, data analysis or supporting information."}],strategy:"mixed",createdAt:new Date,approved:!0},h=o.getOllamaTools(),m=new jn(l,a,d,e),{results:p,finalSynthesis:g,synthesisOk:S}=await m.run(n,f,h,{peerReview:!0,centralizedToLeader:!0});console.log(`
1211
- ${Jt("Hablas","Team Leader")}`),console.log(Xt(g||"Team completed the task.")),console.log(`
1212
- ${c.muted("Full team execution complete. "+(S?"Synthesis OK.":"Used fallback summary."))}`)}async function z0(n,e,t){let s=e.workingDirectory==="."?process.cwd():e.workingDirectory,r=Pe(e),i=new En(s,e),o=new sn(e),a=new ys(s),l=await bn(s,e),u=vn(Qn,l,a),d=new rn(u,e.historySize),f=Qg(n,s),m=await new Bn().processUserInput(f);if(m.contract.routerDecision.executionPath==="team"){let p=new Dn(e);p.setToolRegistry(i);let g=new Ln,S=new Hn(g,{hideActs:!0}).attach(),x=new Fn(e,{tokenBudget:3e3,maxChars:400});p.setChannel(g),g.onEvent(w=>{w.type==="phase"?console.log(`
1213
- ${c.accent("\u25C6")} ${c.strong(w.content)}`):w.type==="handoff"?console.log(` ${c.muted("\u2605")} ${w.agent} \u2501\u2501\u25B6 ${w.to}`):w.type==="speak"?console.log(` ${c.primary(w.agent)}: ${w.content}`):w.type==="act"||w.type==="tool"?console.log(` ${c.warning("\u{1F527}")} [${w.agent}] ${w.content||w.toolName}`):w.type==="summary"||w.type==="observe"?console.log(` ${c.success("\u2713")} ${w.agent||""} ${w.content||""}`):w.type==="error"&&console.log(` ${c.error("\u2717")} ${w.agent}: ${w.content}`)});let $={id:`unified-runtime-${m.plan.id}`,description:f.substring(0,100),tasks:m.plan.steps.map(w=>({role:w.assignedAgent,description:w.description+(m.contract.continuityMode?" [CONTINUITY]":"")+(m.contract.oneStepDelivery?" [ONE-STEP DELIVERY]":"")})),strategy:m.plan.strategy,createdAt:m.plan.createdAt,approved:!0},k=new jn(g,p,x,e),y=new Ne("Hablas is coordinating the internal team");y.start();let{finalSynthesis:b,synthesisOk:v}=await k.run(f,$,i.getOllamaTools(),{peerReview:!0,centralizedToLeader:!0});y.stop("coordination complete"),console.log(`
1214
- ${Jt("Hablas","Team Leader")}`),console.log(Xt(b||"Team completed the task.")),console.log(`
1215
- ${c.muted("Unified runtime execution complete. "+(v?"Synthesis OK.":"Used fallback summary."))}`);return}d.addUserMessage(f),await Xg(d,r,i,o,{interactive:!1,autoMode:e.autoMode||!1,logger:t,config:e})}function Qg(n,e){let t=/#([\w./-]+)/g,s=n,r;for(;(r=t.exec(n))!==null;){let i=r[1],o=Dt.resolve(e,i);ut.existsSync(o)&&(s=s.replace(`#${i}`,i))}return s}async function Yg(n,e){if(!(n.team?.enabled&&Te))return;if(await Te.releaseAllMyLocks(),!n.workspace?.autoPush){console.log(`
1216
- ${c.info("\u2139")} ${c.strong("@Consul")}: "Changes tracked. Auto-push is off \u2014 commit & push manually when ready."
1217
- `);return}let{execSync:t}=await import("child_process"),s=r=>t(r,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim();try{if(!s("git status --porcelain")){console.log(`
1218
- ${c.muted("@Consul: workspace clean \u2014 nothing to push.")}
1219
- `);return}let i=s("git rev-parse --abbrev-ref HEAD");if(!i||i==="HEAD"){console.log(`
1220
- ${c.warning("\u26A0")} ${c.strong("@Consul")}: detached HEAD \u2014 skipping auto-push. Checkout a branch first.
1221
- `);return}let o="";try{o=s("git config --get remote.origin.url")}catch{}if(!o){console.log(`
1222
- ${c.warning("\u26A0")} ${c.strong("@Consul")}: no 'origin' remote configured \u2014 committed locally, skipping push.
1223
- `),s("git add -A"),s('git commit -m "sync(team): automatic updates via @Consul" --no-verify');return}console.log(`
1224
- ${c.success("\u{1F4C1}")} ${c.muted("[Git]")} ${c.strong("@Consul")} committing & pushing to ${c.highlight(i)} \u2192 ${c.muted(o)} ...`),s("git add -A"),s('git commit -m "sync(team): automatic updates via @Consul" --no-verify');try{s(`git push origin ${i}`)}catch{s(`git push --set-upstream origin ${i}`)}console.log(` ${c.success("\u2713")} ${c.strong("@Consul")}: "Pushed to ${i}. Teammates can pull the latest."
1225
- `)}catch(r){let i=r.stderr||r.message||"unknown error",o=/authentication|permission|denied|403|401/i.test(i)?"Check your Git credentials / token for this remote.":/non-fast-forward|rejected|behind/i.test(i)?"Remote has newer commits \u2014 pull/rebase first, then push.":"Resolve the issue and push manually.";console.log(` ${c.warning("\u26A0")} ${c.strong("@Consul")}: auto-push failed. ${c.muted(o)}
1226
- `)}}var ut,Jg,Dt,nc,Te,tc,B0,U0,q0,Tt=L(()=>{"use strict";Vu();ha();ut=O(require("fs")),Jg=require("child_process"),Dt=O(require("path")),nc=O(require("os"));Wn();Hp();xa();Sa();Kp();kr();Ka();Vp();Jp();$i();bg();wg();xg();kg();$g();zn();Vl();Cg();Eg();Pg();yn();Mg();jg();Jl();Hl();Ul();Gl();Vg();Te=null,tc=Dt.join(nc.homedir(),".hablas",".first_run_done"),B0=Dt.join(nc.homedir(),".hablas","config.json"),U0=600,q0=1500});function Lt(n){let e=ic.join(Zg.homedir(),".hablas","logs");si.existsSync(e)||si.mkdirSync(e,{recursive:!0});let t=ic.join(e,`session-${Date.now()}.log`);return(0,rc.default)({level:"info"},rc.default.destination({dest:t,sync:!1}))}var rc,ic,Zg,si,oc=L(()=>{"use strict";rc=O(Nl()),ic=O(require("path")),Zg=O(require("os")),si=O(require("fs"))});var ry={};Le(ry,{createApiServer:()=>sy,startApiServer:()=>Q0});function Y0(){try{return JSON.parse(ty.readFileSync(ny.resolve(__dirname,"..","..","package.json"),"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function sy(n){let e=Lt(n),t=X0(n);return ey.createServer(async(r,i)=>{if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.setHeader("Content-Type","application/json"),r.method==="OPTIONS"){i.writeHead(204),i.end();return}if(n.api.apiKey&&(r.headers.authorization||"").replace("Bearer ","")!==n.api.apiKey){i.writeHead(401),i.end(JSON.stringify({error:"Unauthorized",message:"Invalid API key"}));return}let o={};if(r.method==="POST"||r.method==="PUT")try{let l=[];for await(let d of r)l.push(d);let u=Buffer.concat(l).toString();u&&(o=JSON.parse(u))}catch{i.writeHead(400),i.end(JSON.stringify({error:"Bad Request",message:"Invalid JSON body"}));return}let a=t.find(l=>l.method===r.method&&r.url?.startsWith(l.path));if(!a){i.writeHead(404),i.end(JSON.stringify({error:"Not Found",message:`No route for ${r.method} ${r.url}`}));return}try{let l={method:r.method||"GET",path:r.url||"/",body:o,headers:r.headers},u=await a.handler(l);i.writeHead(u.status),i.end(JSON.stringify(u.body))}catch(l){e.error({err:l},"API error"),i.writeHead(500),i.end(JSON.stringify({error:"Internal Server Error",message:String(l)}))}})}function X0(n){return[{method:"GET",path:"/api/v1/health",handler:async()=>({status:200,body:{status:"ok",version:J0,uptime:process.uptime()}})},{method:"GET",path:"/api/v1/agents",handler:async()=>({status:200,body:{agents:[{name:"coder",description:"Code generation and modification",status:"available"},{name:"reviewer",description:"Code review and quality analysis",status:"available"},{name:"architect",description:"System architecture design",status:"available"},{name:"devops",description:"Deployment and infrastructure",status:"available"},{name:"researcher",description:"Documentation and research",status:"available"},{name:"planner",description:"Task decomposition and planning",status:"available"},{name:"debugger",description:"Error analysis and fixing",status:"available"}]}})},{method:"GET",path:"/api/v1/models",handler:async()=>({status:200,body:{current:n.model,provider:n.provider,host:n.ollamaHost}})},{method:"POST",path:"/api/v1/chat",handler:async e=>{let{message:t,agent:s}=e.body;return t?{status:200,body:{response:`[${s||"coder"}] Received: ${t}`,agent:s||"coder",model:n.model}}:{status:400,body:{error:"message field is required"}}}},{method:"POST",path:"/api/v1/plan",handler:async e=>{let{task:t}=e.body;return t?{status:200,body:{plan:{task:t,steps:[{step:1,description:"Analyze requirements",agent:"researcher"},{step:2,description:"Design architecture",agent:"architect"},{step:3,description:"Implement code",agent:"coder"},{step:4,description:"Review and test",agent:"reviewer"}]}}}:{status:400,body:{error:"task field is required"}}}},{method:"POST",path:"/api/v1/execute",handler:async e=>{let{command:t}=e.body;return t?n.api.enabled?{status:200,body:{message:"Command queued for execution",command:t}}:{status:403,body:{error:"API execution not enabled"}}:{status:400,body:{error:"command field is required"}}}},{method:"GET",path:"/api/v1/stats",handler:async()=>({status:200,body:{sessions:0,messages:0,uptime:process.uptime(),model:n.model,provider:n.provider}})}]}function Q0(n){return new Promise((e,t)=>{let s=sy(n);s.on("error",t),s.listen(n.api.port,n.api.host,()=>{e(s)})})}var ey,ty,ny,J0,iy=L(()=>{"use strict";ey=O(require("http")),ty=O(require("fs")),ny=O(require("path"));oc();J0=Y0()});var eC={};Le(eC,{CLI_VERSION:()=>Os});module.exports=dy(eC);var wc=O(vc(),1),{program:cC,createCommand:uC,createArgument:dC,createOption:fC,CommanderError:pC,InvalidArgumentError:hC,InvalidOptionArgumentError:mC,Command:xc,Argument:gC,Option:yC,Help:bC}=wc.default;Tt();kr();oc();var ri=O(require("fs")),Rs=O(require("path"));function Z0(){let n=[Rs.resolve(__dirname,"..","package.json"),Rs.resolve(__dirname,"..","..","package.json"),Rs.resolve(process.cwd(),"package.json"),Rs.resolve(__dirname,"..","..","..","package.json")];for(let e of n)try{if(ri.existsSync(e)){let t=JSON.parse(ri.readFileSync(e,"utf-8"));if(t.version)return t.version}}catch{}return"0.0.0"}var Os=Z0(),ie=new xc;ie.name("hablas").description(`hablas CLI v${Os} by Abdulmoin Hablas \u2014 Multi-agent AI development system. Local-first via Ollama, NVIDIA NIM, or any OpenAI-compatible API.`).version(Os).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");ie.command("create <description>").description("Generate a full project from a description (uses full team)").option("--stack <stack>","Tech stack preference").option("--with-tests","Include test generation").option("--with-docker","Include Docker setup").action(async(n,e)=>{let t=ie.opts(),s=Ye({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=Lt(s),{runFullTeamCommand:i}=await Promise.resolve().then(()=>(Tt(),jt)),o=`Generate a complete project: ${n}${e.stack?` using ${e.stack}`:""}${e.withTests?" with comprehensive tests":""}${e.withDocker?" with Docker setup":""}. Create all necessary files.`;await i(o,s,r,"build")});ie.command("commit").description("Generate a smart commit message from staged changes").action(async()=>{let n=ie.opts(),e=Ye({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),t=Lt(e),{getGitStatus:s,getDetailedDiff:r,generateCommitPrompt:i}=await Promise.resolve().then(()=>(mn(),Yn)),o=e.workingDirectory||process.cwd(),a=await s(o);if(!a||a.staged.length===0){console.log(" \u26A0 No staged changes. Use `git add` first.");return}let l=await r(o),u=i(l,a.staged),{runSingleCommand:d}=await Promise.resolve().then(()=>(Tt(),jt));await d(u,e,t)});ie.command("pr").description("Generate a PR description from branch commits").option("--base <branch>","Base branch","main").action(async n=>{let e=ie.opts(),t=Ye({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=Lt(t),{getGitStatus:r,getRecentCommits:i,generatePRPrompt:o}=await Promise.resolve().then(()=>(mn(),Yn)),a=t.workingDirectory||process.cwd(),l=await r(a),u=await i(a,20),d=o(u,n.base,l?.branch||"feature"),{runSingleCommand:f}=await Promise.resolve().then(()=>(Tt(),jt));await f(d,t,s)});ie.command("changelog").description("Generate changelog from recent commits").option("--version <ver>","Version number",Os).option("-n, --count <n>","Number of commits to include","30").action(async n=>{let e=ie.opts(),t=Ye({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=Lt(t),{getRecentCommits:r,generateChangelogPrompt:i}=await Promise.resolve().then(()=>(mn(),Yn)),o=t.workingDirectory||process.cwd(),a=await r(o,parseInt(n.count)),l=i(a,n.version),{runSingleCommand:u}=await Promise.resolve().then(()=>(Tt(),jt));await u(l,t,s)});ie.command("security").description("Run security scan on the project").option("--fix","Auto-fix issues where possible").action(async n=>{let e=ie.opts(),t=Ye({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(()=>(Ji(),Zc)),i=t.workingDirectory||process.cwd();console.log(`
1227
- \u{1F512} Running security scan...
1228
- `);let o=s(i);console.log(r(o))});ie.command("stats").description("Show developer analytics and usage statistics").action(async()=>{let{loadStats:n,formatStats:e}=await Promise.resolve().then(()=>(zn(),Vi)),t=n();console.log(e(t))});ie.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=ie.opts(),t=Ye({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(()=>(ha(),Xf)),l=t.workingDirectory||process.cwd();if(n.init)r(l,n.init),console.log(`
1229
- \u2713 Team "${n.init}" initialized.`),console.log(` Config saved to: .hablas/team.json
1230
- `);else if(n.add){let u=s(l);if(!u){console.log(" \u26A0 No team config found. Run `hablas team --init <name>` first.");return}let d=i(u,n.add.split("@")[0],n.add);o(l,d),console.log(` \u2713 Added ${n.add} to team.`)}else{let u=s(l);if(!u){console.log(" No team config found. Run `hablas team --init <name>` to create one.");return}console.log(a(u))}});ie.command("info").description("Show workspace information and detected configuration").action(async()=>{let n=ie.opts(),e=Ye({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(()=>(Zi(),ou)),r=e.workingDirectory||process.cwd();console.log(`
1231
- \u25C6 Workspace Information
1232
- `);let i=t(r);console.log(s(i)),console.log("")});ie.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=ie.opts(),t=Ye({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(()=>(iy(),ry));console.log(`
1233
- \u25C6 Hablas API Server v${Os}`),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(`
1234
- Press Ctrl+C to stop.
1235
- `)}catch(r){console.error(` \u2717 Failed to start API server: ${r}`)}});ie.command("run <prompt>").description("Run a single prompt non-interactively through the unified runtime").action(async n=>{let e=ie.opts(),t=Ye({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=Lt(t),{runSingleCommand:r}=await Promise.resolve().then(()=>(Tt(),jt));await r(n,t,s)});ie.command("doctor").description("Run system diagnostics").action(async()=>{let n=ie.opts(),e=Ye({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(),Gc)),r=await t({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(s(r))});ie.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(()=>(Pi(),qc));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(`
1236
- \u{1F50D} Searching marketplace for "${n.search}"...`),console.log(" (Marketplace: https://registry.hablas.dev/plugins)"),console.log(`
1237
- 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(`
1238
- Install: hablas plugins --install <name>
1239
- `)):n.install?(console.log(`
1240
- \u{1F4E6} Installing plugin "${n.install}"...`),console.log(` \u2713 Plugin "${n.install}" installed successfully.`),console.log(` Enable: hablas plugins --enable ${n.install}
1241
- `)):(console.log(`
1242
- \u25C6 Installed Plugins
1243
- `),console.log(s()),console.log(`
1244
- 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>
1245
- `))});ie.action(async()=>{let n=ie.opts(),e=Ye({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey,team:n.team,user:n.user,teamKey:n.teamKey});if(n.auto&&(e.autoMode=!0),n.timeout&&(e.timeout=parseInt(n.timeout,10)),n.theme&&(e.ui.theme=n.theme),n.dashboard&&(e.ui.dashboard=!0),n.setup){let{runSetupWizard:s}=await Promise.resolve().then(()=>(Jl(),Bg));await s(e);return}let t=Lt(e);await sc(e,t)});ie.parse();0&&(module.exports={CLI_VERSION});
1246
- /*! Bundled license information:
1247
-
1248
- normalize-path/index.js:
1249
- (*!
1250
- * normalize-path <https://github.com/jonschlinkert/normalize-path>
1251
- *
1252
- * Copyright (c) 2014-2018, Jon Schlinkert.
1253
- * Released under the MIT License.
1254
- *)
1255
-
1256
- is-extglob/index.js:
1257
- (*!
1258
- * is-extglob <https://github.com/jonschlinkert/is-extglob>
1259
- *
1260
- * Copyright (c) 2014-2016, Jon Schlinkert.
1261
- * Licensed under the MIT License.
1262
- *)
1263
-
1264
- is-glob/index.js:
1265
- (*!
1266
- * is-glob <https://github.com/jonschlinkert/is-glob>
1267
- *
1268
- * Copyright (c) 2014-2017, Jon Schlinkert.
1269
- * Released under the MIT License.
1270
- *)
1271
-
1272
- is-number/index.js:
1273
- (*!
1274
- * is-number <https://github.com/jonschlinkert/is-number>
1275
- *
1276
- * Copyright (c) 2014-present, Jon Schlinkert.
1277
- * Released under the MIT License.
1278
- *)
1279
-
1280
- to-regex-range/index.js:
1281
- (*!
1282
- * to-regex-range <https://github.com/micromatch/to-regex-range>
1283
- *
1284
- * Copyright (c) 2015-present, Jon Schlinkert.
1285
- * Released under the MIT License.
1286
- *)
1287
-
1288
- fill-range/index.js:
1289
- (*!
1290
- * fill-range <https://github.com/jonschlinkert/fill-range>
1291
- *
1292
- * Copyright (c) 2014-present, Jon Schlinkert.
1293
- * Licensed under the MIT License.
1294
- *)
1295
- */
228
+ `.trim()}parseSelfEval(e){let r=[/^\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 n of r){let s=e.match(n);if(s)try{let i=JSON.parse(s[1]);return this.normalizeSelfEval(i)}catch{}}return null}normalizeSelfEval(e){let r=typeof e.score=="number"?Math.max(0,Math.min(10,Math.round(e.score))):5,n=typeof e.completed=="boolean"?e.completed:r>=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:r>=8?o="high":r<=4&&(o="low"),{score:r,completed:n,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,r,n){return r?"":["<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: ${n.slice(0,300)}`,"</thinking>"].join(`
229
+ `)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(s=>s.action).length,n=this.turnSteps.filter(s=>s.reflection).length;return`${e} steps, ${r} actions, ${n} reflections`}};function Ht(t){return new An(t)}var Vh=[{test:t=>/ENOENT|no such file|not found|does not exist/i.test(t),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:t=>/EACCES|permission denied/i.test(t),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:t=>/EISDIR|is a directory/i.test(t),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:t=>/EEXIST|already exists/i.test(t),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:t=>/no match|not found in file|search string not found/i.test(t),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:t=>/command not found|not recognized/i.test(t),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:t=>/timeout|timed out|ETIMEDOUT/i.test(t),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:t=>/exit code|exited with|non-zero/i.test(t),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:t=>/syntax error|unexpected token|parse error|SyntaxError/i.test(t),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:t=>/ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(t),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:t=>/invalid argument|missing required|expected.*but got|type error/i.test(t),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:t=>/ENOMEM|out of memory|resource|too large|max.*exceeded/i.test(t),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}],En=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,r,n){let s=this.failures.get(e),i=s?s.count+1:1,o={tool:e,count:i,lastError:r,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 Vh)if(a.test(r)){let l=s?.lastStrategy===a.strategy&&i>=2,u=l?"decompose_task":a.strategy;return o.lastStrategy=u,this.failures.set(e,o),{errorClass:a.errorClass,strategy:u,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,r){let n=[`ERROR: ${r}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&n.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":n.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":n.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":n.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":n.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":n.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":n.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return n.join(`
230
+ `)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let r=this.failures.get(e);return r?r.count<=1&&r.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 Wt(t=3){return new En(t)}var ae=k(require("fs")),zt=k(require("path")),na=k(require("os")),Vt=zt.join(na.homedir(),".hablas","model-formats.json");function zh(){try{if(ae.existsSync(Vt))return JSON.parse(ae.readFileSync(Vt,"utf-8"))}catch{}return{}}function Kh(t){try{let e=zt.dirname(Vt);ae.existsSync(e)||ae.mkdirSync(e,{recursive:!0}),ae.writeFileSync(Vt,JSON.stringify(t,null,2),"utf-8")}catch{}}function sa(t,e){let r=0,n=!1,s=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){s=!1;continue}if(o==="\\"&&n){s=!0;continue}if(o==='"'){n=!n;continue}if(!n&&(o==="{"&&r++,o==="}"&&(r--,r===0)))return t.slice(e,i+1)}return null}function ft(t){if(typeof t.name=="string"&&t.arguments&&typeof t.arguments=="object")return{tool:t.name,args:t.arguments};if(typeof t.tool=="string"&&t.args&&typeof t.args=="object")return{tool:t.tool,args:t.args};if(typeof t.name=="string"&&t.parameters&&typeof t.parameters=="object")return{tool:t.name,args:t.parameters};if(t.function&&typeof t.function=="object"){let e=t.function;if(typeof e.name=="string"){let r={};if(typeof e.arguments=="string")try{r=JSON.parse(e.arguments)}catch{r={}}else e.arguments&&typeof e.arguments=="object"&&(r=e.arguments);return{tool:e.name,args:r}}}return null}function Jh(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Gh(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim()),i=ft(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function Xh(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim());if(s.parameters||s.name){let i=ft(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function Yh(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;){let s=n[1],i=ia(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function ia(t){let e=[],r=["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 n of r){let s=new RegExp(`<<?${n}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${n}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",l={},u=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,d;for(;(d=u.exec(o))!==null;){let p=d[1].toLowerCase(),h=d[2]??d[3]??d[4];l[p]=Jh(h)}let f=a.trim();f&&(n==="write_file"||n==="append_to_file"?l.content=a:n==="run_command"?l.command=f:n==="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)),n==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:n,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function Zh(t){return ia(t)}function Qh(t){let e=[],r=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim()),i=ft(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function ep(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=sa(t,n.index);if(s)try{let i=JSON.parse(s),o=ft(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function tp(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=sa(t,n.index);if(s)try{let i=JSON.parse(s),o=ft(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function rp(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,n,s=!1;for(;(n=r.exec(t))!==null;){let i=n[1],o=/<function=([^>]+)>/i.exec(i);if(o){s=!0;let a=o[1].trim(),l={},u=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,d;for(;(d=u.exec(i))!==null;){let f=d[1].trim(),p=d[2].trim();p==="true"?p=!0:p==="false"?p=!1:!isNaN(Number(p))&&p!==""&&(p=Number(p)),l[f]=p}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:n[0]})}}if(!s&&/<function=([^>]+)>/i.test(t)){let i=/<function=([^>]+)>/i.exec(t);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=l.exec(t))!==null;){let d=u[1].trim(),f=u[2].trim();f==="true"?f=!0:f==="false"?f=!1:!isNaN(Number(f))&&f!==""&&(f=Number(f)),a[d]=f}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var On=[{format:"xml_tool_call_wrapper",parse:Yh},{format:"xml_prompt",parse:Zh},{format:"xml_tags",parse:Gh},{format:"xml_parameters",parse:rp},{format:"hermes",parse:Xh},{format:"markdown_json",parse:Qh},{format:"function_call",parse:ep},{format:"json_object",parse:tp}],Rn=class{registry;constructor(){this.registry=zh()}parse(e,r,n){if(r&&Array.isArray(r)&&r.length>0){let i=r.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 n&&this.learnFormat(n,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let s=e||"";if(!s.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(n){let i=this.registry[n];if(i&&i.format!=="native"){let o=On.find(a=>a.format===i.format);if(o){let a=o.parse(s);if(a.length>0)return this.learnFormat(n,i.format),this.buildResult(a,s)}}}for(let{parse:i}of On){let o=i(s);if(o.length>0){let a=o[0].format;return n&&this.learnFormat(n,a),this.buildResult(o,s)}}return{toolCalls:[],displayContent:s.trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let r=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(r)||/<function=/i.test(r)||r.includes("```tool_call")||r.includes("```json")&&r.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(r)||r.startsWith("{")&&(r.includes('"name"')||r.includes('"tool"'))&&(r.includes('"arguments"')||r.includes('"args"')||r.includes('"parameters"'))||r.includes('"function"')&&r.includes('"name"'))}detectFormat(e){for(let{format:r,parse:n}of On)if(n(e).length>0)return r;return"unknown"}learnFormat(e,r){let n=this.registry[e];n&&n.format===r?(n.successCount++,n.lastUsed=new Date().toISOString()):this.registry[e]={format:r,successCount:1,lastUsed:new Date().toISOString()},Kh(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[r,n]of Object.entries(this.registry))e[r]={format:n.format,successCount:n.successCount};return e}buildResult(e,r){let n=e.map(o=>({function:{name:o.tool,arguments:o.args}})),s=r,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(/\n{3,}/g,`
231
+
232
+ `),{toolCalls:n,displayContent:s.trim(),format:e[0]?.format??"unknown"}}},$n=null;function oa(){return $n||($n=new Rn),$n}var np=600,aa=2e3,la=2;function sp(t,e,r){let s=oa().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function ip(t,e){return t==="write_file"&&typeof e.path=="string"?`create ${e.path}`:(t==="edit_file"||t==="patch_file"||t==="search_and_replace")&&typeof e.path=="string"?`modify ${e.path}`:t==="read_file"&&typeof e.path=="string"?`read ${e.path}`:t==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function op(t){let e=(t||"").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 ca(t,e,r,n){let s=0,i=Date.now();for(;s<=la;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=la)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:s};s++,n.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 ua(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:u,skipTools:d}=t,f=t.reactEngine??Ht(),p=t.errorRecovery??Wt(),h=d?[]:n.getOllamaTools(),c=r.getModel(),m=t.maxIterations??np,y=[],w=[],b=[],_="",S=0,v=!1;for(;S<m;){if(S++,u?.aborted)return{output:_,toolsUsed:he(y),toolResults:w,touchedFiles:he(b),iterations:S,success:!1,error:"Aborted",completedNaturally:v};let $=f.buildBudgetWarningPrompt();$&&s.addUserMessage($,{priority:"critical",tags:["system-budget"]});let T;try{T=await r.chatWithTools(s.getMessages(),h,u)}catch(N){let U=N;if(U.name==="AbortError"||u?.aborted)return{output:_,toolsUsed:he(y),toolResults:w,touchedFiles:he(b),iterations:S,success:!1,error:"Aborted",completedNaturally:v};if(S<=1){a.onNotice?.(`Transient model error: ${U.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(P=>setTimeout(P,1e3)),S--;continue}return a.onError?.(U.message??"Model request failed"),{output:_,toolsUsed:he(y),toolResults:w,touchedFiles:he(b),iterations:S,success:!1,error:U.message,completedNaturally:v}}let O=T.message?.content||"",C=T.message?.tool_calls,I=f.parseThinking(O);I.hasThinking&&(f.recordStep({thought:I.thinking}),o.debug({thinking:I.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:L,displayContent:F}=sp(C,O,c);if(F&&F.trim()&&(_=F,await a.onAssistantText?.(F,e)),L.length===0){s.addAssistantMessage(O,void 0,e.role),v=!0;break}s.addAssistantMessage(O,L,e.role);let q=L.length;for(let N=0;N<L.length;N++){let U=L[N];if(!U?.function?.name)continue;let P=U.function.name,B=U.function.arguments||{},er=n.getSafetyLevel(P)??"confirm";if(!n.get(P)){a.onNotice?.(`Unknown tool: ${P} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${P}". Available: ${n.getAll().map(Ee=>Ee.name).join(", ")}`);continue}if(await l(P,er,B)==="skip"){s.addToolMessage(`Tool ${P} was skipped by policy/user.`);break}y.push(P),typeof B.path=="string"&&b.push(B.path);let rr=ip(P,B);a.onToolStart?.(P,rr,B),a.onToolCall?.(),f.recordStep({thought:I.hasThinking?`Executing: ${P}`:"",action:P,actionInput:B});let H=await ca(n,P,B,o);a.onToolEnd?.(P,H.success,H.error||H.output,H.duration,B);let Ae;if(H.success)Ae=lt(H.output,aa),f.recordObservation(Ae.slice(0,300)),w.push({tool:P,success:!0,summary:H.output.slice(0,150)});else{let Ee=H.error||"Unknown error",Oe=p.analyze(P,Ee,B);if(Ae=p.buildRecoveryMessage(Oe,Ee),f.recordObservation(`FAILED: ${Ee}`,`Recovery: ${Oe.strategy} \u2014 ${Oe.suggestion}`),o.info({tool:P,errorClass:Oe.errorClass,strategy:Oe.strategy},"Error recovery analysis"),w.push({tool:P,success:!1,summary:Ee.slice(0,150)}),Oe.autoRetry&&!f.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let $e=await ca(n,P,B,o);a.onToolEnd?.(P,$e.success,$e.output,$e.duration,B),$e.success&&(Ae=lt($e.output,aa),f.recordObservation(Ae.slice(0,300),"Auto-retry succeeded"),w[w.length-1]={tool:P,success:!0,summary:$e.output.slice(0,150)})}}if(s.addToolMessage(Ae),H.success&&P==="read_file"&&typeof B.path=="string"&&i?.addFile(B.path,H.output),o.info({tool:P,success:H.success,durationMs:H.duration,retries:H.retries},"Tool executed"),!H.success&&op(H.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}q>1&&N<q-1}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return S>=m&&!v&&a.onNotice?.(`Reached max iterations (${m}). Stopping.`,"warn"),o.info({summary:f.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:_,toolsUsed:he(y),toolResults:w,touchedFiles:he(b),iterations:S,success:!0,completedNaturally:v}}function he(t){return[...new Set(t)]}function fa(t){return async(e,r)=>{let n=e.replace(/_/g," ");return!t.autoMode&&t.interactive?r==="confirm"&&t.confirm?await t.confirm(`Proceed with ${n}?`)?"allow":"skip":r==="dangerous"&&t.confirmDangerous?await t.confirmDangerous(`Dangerous: ${n}`)?"allow":"skip":"allow":!t.autoMode&&r==="dangerous"?"skip":"allow"}}async function da(t){let{client:e,session:r,abortSignal:n,onChunk:s}=t,i="",o=null;for(let a=0;a<2;a++)try{i="";for await(let l of e.streamChat(r.getMessages(),n))i+=l,s?.(l);return r.addAssistantMessage(i||""),i}catch(l){if(o=l,l?.name==="AbortError"||n?.aborted)throw l;if(a===1)break}throw o||new Error("Text turn failed")}var Jt=k(require("fs")),In=k(require("os")),Kt=k(require("path"));function ap(){let t=[Kt.resolve(__dirname,"..","package.json"),Kt.resolve(__dirname,"..","..","package.json"),Kt.resolve(process.cwd(),"package.json")];for(let e of t)try{if(Jt.existsSync(e)){let r=JSON.parse(Jt.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var ha=ap(),pa=process.stdout.isTTY===!0,lp=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb";function ve(t,e){return!pa||lp?t:`${e}${t}\x1B[0m`}var x={strong:t=>ve(t,"\x1B[1;37m"),muted:t=>ve(t,"\x1B[38;5;244m"),accent:t=>ve(t,"\x1B[38;5;81m"),info:t=>ve(t,"\x1B[38;5;110m"),success:t=>ve(t,"\x1B[38;5;108m"),warning:t=>ve(t,"\x1B[38;5;179m"),error:t=>ve(t,"\x1B[38;5;167m")};function ma(t,e){let r=e.replace(In.homedir(),"~"),n="\u2500".repeat(88);return["",x.muted(n),` ${x.strong("HABLAS")} ${x.muted("single-agent engineering runtime")}`,` ${x.muted("version")} ${x.accent(ha)} ${x.muted("model")} ${x.accent(t)}`,` ${x.muted("workspace")} ${x.muted(r)}`,x.muted(n),` ${x.muted("\u203A Type naturally to get started")}`,` ${x.muted("\u203A /help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")}`,""].join(`
233
+ `)}function ga(t){return`
234
+ ${x.muted("\u2500".repeat(28))} ${x.accent("Turn #"+t)} ${x.muted("\u2500".repeat(28))}`}function Gt(){return`
235
+ ${x.accent("Hablas")} ${x.muted("\xB7 response")}`}function ya(){return["",` ${x.strong("Commands")}`,` ${x.muted("/help")} show help`,` ${x.muted("/status")} show current status`,` ${x.muted("/model")} show or switch the active model`,` ${x.muted("/models")} list available models`,` ${x.muted("/provider")} inspect or switch provider`,` ${x.muted("/history")} show recent turns`,` ${x.muted("/clear")} clear the session`,` ${x.muted("/workspace")} inspect the current workspace`,` ${x.muted("/doctor")} run diagnostics`,` ${x.muted("/version")} show version`,` ${x.muted("/about")} product identity`,` ${x.muted("/exit")} quit`,""].join(`
236
+ `)}function wa(t){return["",` ${x.strong("Status")}`,` ${x.muted("provider")} ${x.info(t.provider)}`,` ${x.muted("model")} ${x.info(t.model)}`,` ${x.muted("workspace")} ${x.muted(t.workingDir.replace(In.homedir(),"~"))}`,` ${x.muted("connected")} ${t.connected?x.success("yes"):x.error("no")}`,` ${x.muted("messages")} ${x.info(String(t.messageCount))}`,t.totalTokens!==void 0?` ${x.muted("tokens")} ${x.info(String(t.totalTokens))}`:"",""].filter(Boolean).join(`
237
+ `)}function G(t){return` ${x.info(t)}`}function ke(t){return` ${x.success("\u2713")} ${t}`}function le(t){return` ${x.warning("\u26A0")} ${t}`}function Ce(t){return` ${x.error("\u2717")} ${t}`}function ba(){return` ${x.strong("Hablas")} ${x.accent("v"+ha)}`}function Sa(){return` ${x.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime by Abdulmoin Hablas`}function _a(t,e){return` ${x.muted("tool")} ${x.accent(t)} ${x.muted("\xB7")} ${e}`}function xa(t,e,r){let n=t?x.success("\u2713"):x.error("\u2717"),s=e.replace(/\s+/g," ").trim().slice(0,140);return` ${n} ${s||(t?"done":"failed")} ${x.muted(`(${r}ms)`)}`}var Ge=class{constructor(e){this.label=e}frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;timer=null;start(){pa&&(this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${x.accent(this.frames[this.index])} ${x.muted(this.label)}`),this.index=(this.index+1)%this.frames.length},80)))}stop(e){this.timer&&(clearInterval(this.timer),this.timer=null,process.stdout.write("\r\x1B[K")),e&&console.log(G(e))}};async function Xt(t,e){let r=ta(t),n=await Ke(e.workingDir,e.config);if(e.session.updateSystemPrompt(Je(n,r.profile)),r.profile.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context and do not restart from zero.]",{priority:"critical",tags:["runtime-note","continuity"]}),r.profile.oneStepDelivery&&e.session.addUserMessage("[Execution note: complete as much as possible in one pass with no unnecessary follow-up questions.]",{priority:"critical",tags:["runtime-note","one-step"]}),e.session.addUserMessage(t,{priority:"high",tags:[`kind:${r.profile.kind}`]}),!r.profile.needsTools){let l=new Ge("Hablas is reasoning");l.start();let u=!1,d="";try{let f=await da({client:e.client,session:e.session,onChunk:p=>{u||(l.stop(),console.log(Gt()),process.stdout.write(" "),u=!0),process.stdout.write(p),d+=p}});u?process.stdout.write(`
238
+ `):(l.stop(),console.log(Gt()),console.log(" "+f));return}catch(f){l.stop(),console.log(Ce(f?.message||"Text turn failed"));return}}let s=Ht({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=Wt(3),o={onAssistantText:async l=>{console.log(Gt()),console.log(" "+l)},onToolStart:(l,u)=>{console.log(_a(l,u))},onToolEnd:(l,u,d,f)=>{console.log(xa(u,d,f))},onNotice:(l,u)=>{console.log(u==="retry"?G(`Retrying: ${l}`):G(l))},onError:l=>{console.log(Ce(l))},onToolCall:()=>e.onToolCall?.()},a=fa({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?l=>e.input.confirm(l):void 0,confirmDangerous:e.input?l=>e.input.confirmDangerous(l):void 0});await ua({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:o,safetyPolicy:a,reactEngine:s,errorRecovery:i,skipTools:!1})}var Pn=k(require("fs")),va=k(require("path")),Q=k(require("os")),ka=require("child_process");async function Yt(t){let e=[],r=process.version,n=parseInt(r.slice(1).split(".")[0],10);e.push({name:"Node.js",status:n>=20?"ok":n>=18?"warn":"error",message:n>=20?`${r} (recommended)`:n>=18?`${r} (works, but 20+ recommended)`:`${r} (too old, need 20+)`});let s=va.join(Q.homedir(),".hablas");if(e.push({name:"Config directory",status:Pn.existsSync(s)?"ok":"warn",message:Pn.existsSync(s)?s:"Not created yet (will be created on first use)"}),t.provider==="ollama")try{let i=await fetch(`${t.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=t.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=Q.homedir();if(process.platform!=="win32"){let a=(0,ka.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",u=a[4]||"?";e.push({name:"Disk space",status:parseInt(u)>90?"warn":"ok",message:`${l} available (${u} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:t.model?"ok":"warn",message:t.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${Q.platform()} ${Q.arch()} \u2014 ${Q.cpus().length} cores, ${Math.round(Q.totalmem()/1024/1024/1024)}GB RAM`}),e}function Zt(t){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},r={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},n="\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 t){let u=`${r[l.status]}${e[l.status]}${n}`,d=l.name.padEnd(18);i.push(` ${u} ${d}${s}${l.message}${n}`)}let o=t.filter(l=>l.status==="error").length,a=t.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${r.error}${o} error(s) found \u2014 fix these for hablas to work properly${n}`):a>0?i.push(` ${r.warn}${a} warning(s) \u2014 hablas should work but check the items above${n}`):i.push(` ${r.ok}All checks passed \u2014 hablas is ready!${n}`),i.push(""),i.join(`
239
+ `)}async function Ca(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(ya());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Sa());return;case"/version":console.log(ba());return;case"/clear":e.session.clear(),console.log(ke("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(G("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l}: ${a.content.replace(/\s+/g," ").slice(0,160)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(wa({model:e.client.getModel(),provider:Le(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(G(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),Qe(e.config),console.log(ke(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=s.join(" ").toLowerCase(),a=o?i.filter(l=>l.toLowerCase().includes(o)):i;if(a.length===0){console.log(le("No matching models found."));return}console.log(""),a.slice(0,60).forEach((l,u)=>console.log(` ${String(u+1).padStart(2," ")}. ${l}`)),a.length>60&&console.log(` ... ${a.length-60} more`),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(G(`Provider: ${Le(e.config)}`)),console.log(G(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?ke("Connection OK"):Ce("Connection failed"));return}if(i==="ollama")e.config.provider="ollama",e.config.apiUrl="",e.config.apiKey="";else if(i==="nvidia")e.config.provider="nvidia",e.config.apiUrl=ne.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=ne.defaultModel);else if(i==="custom"){if(!s[1]){console.log(le("Usage: /provider custom <url> [api-key]"));return}e.config.provider="custom",e.config.apiUrl=s[1],s[2]&&(e.config.apiKey=s[2])}else{console.log(le("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=De(e.config);e.setClient(o),Qe(e.config),console.log(ke(`Provider switched to ${Le(e.config)}`));return}case"/doctor":{let i=await Yt({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Zt(i));return}case"/workspace":{console.log(""),console.log(qt(Ve(e.workingDir))),console.log("");return}default:console.log(le(`Unknown command: ${n}`))}}async function Ea(t,e){Yn();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=De(t),s=new Ue(r,t),i=new Be(t),o=await Ke(r,t),a=new We(Je(o,ut("hello")),t.historySize),l=new Ut;console.log(ma(t.model,r)),Ta.existsSync(Aa.join(r,".git"))||console.log(le("Not in a Git repository. Versioning and auto-sync features are limited."));let u=new Ge("Connecting");u.start();let d=await n.checkConnection();if(u.stop(d?"ready":"offline"),d){let y=await n.listModels();console.log(ke(`Connected \xB7 ${y.length} models available`))}else console.log(le(`Connection failed for ${Le(t)}. You can still inspect local files and switch provider with /provider.`));console.log(G("Hablas is ready. Single-agent runtime active.")),console.log("");let f=0,p=0,h=Date.now(),c=new AbortController,m=0;for(process.on("SIGINT",()=>{let y=Date.now();y-m<1500&&(console.log(""),console.log(G(`Session summary \xB7 turns=${f} \xB7 toolCalls=${p} \xB7 duration=${Math.round((Date.now()-h)/1e3)}s`)),l.close(),process.exit(0)),m=y,c.abort(),c=new AbortController,console.log(""),console.log(le("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let w=(await l.prompt(" \u203A ")).trim();if(w){if(w.startsWith("/")){if(await Ca(w,{config:t,client:n,setClient:_=>{n=_},session:a,workingDir:r})==="quit")break;continue}f+=1,console.log(ga(f)),c=new AbortController;try{await Xt(w,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{p+=1}})}catch(b){if(b?.name==="AbortError")continue;console.log(Ce(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}l.close()}async function Oa(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=De(e),i=new Ue(n,e),o=new Be(e),a=await Ke(n,e),l=new We(Je(a,ut(t)),e.historySize);await Xt(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1})}var Qt=k(require("fs")),Te=k(require("path")),cp=[{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"}],up=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),fp=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function dp(t,e){let r=[],n=e.split(`
240
+ `);for(let{pattern:s,name:i,severity:o}of cp){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let u=e.substring(0,a.index).split(`
241
+ `).length,d=n[u-1]||"";d.trim().startsWith("#")||d.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:u,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function hp(t,e){let r=[],n=e.split(`
242
+ `),s=Te.extname(t);return[".ts",".js",".tsx",".jsx"].includes(s)&&n.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&r.push({severity:"high",type:"code",file:t,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)&&r.push({severity:"medium",type:"code",file:t,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)&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),r}function $a(t,e=[]){try{let r=Qt.readdirSync(t,{withFileTypes:!0});for(let n of r){if(up.has(n.name))continue;let s=Te.join(t,n.name);if(n.isDirectory())$a(s,e);else if(n.isFile()){let i=Te.extname(n.name);fp.has(i)||e.push(s)}}}catch{}return e}function Ra(t){let e=Date.now(),r=$a(t),n=[];for(let o of r)try{let a=Qt.readFileSync(o,"utf-8"),l=Te.relative(t,o),u=dp(l,a);n.push(...u);let d=hp(l,a);n.push(...d)}catch{}let s=Date.now()-e,i={critical:n.filter(o=>o.severity==="critical").length,high:n.filter(o=>o.severity==="high").length,medium:n.filter(o=>o.severity==="medium").length,low:n.filter(o=>o.severity==="low").length,info:n.filter(o=>o.severity==="info").length};return{issues:n,scannedFiles:r.length,duration:s,summary:i}}function Ia(t){let e=[];if(e.push(`
243
+ 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: ${t.scannedFiles}`),e.push(` Duration: ${t.duration}ms`),e.push(""),t.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${t.issues.length}`),e.push(` Critical: ${t.summary.critical}`),e.push(` High: ${t.summary.high}`),e.push(` Medium: ${t.summary.medium}`),e.push(` Low: ${t.summary.low}`),e.push("");let r=t.issues.sort((n,s)=>{let i={critical:0,high:1,medium:2,low:3,info:4};return i[n.severity]-i[s.severity]}).slice(0,10);for(let n of r){let s=n.severity==="critical"?"\u{1F534}":n.severity==="high"?"\u{1F7E0}":n.severity==="medium"?"\u{1F7E1}":"\u{1F535}";e.push(` ${s} [${n.severity.toUpperCase()}] ${n.message}`),e.push(` File: ${n.file}${n.line?`:${n.line}`:""}`),e.push(` Fix: ${n.suggestion}`),e.push("")}}return e.join(`
244
+ `)}var Xe=k(require("fs")),Fn=k(require("path")),Fa=k(require("os")),pp=Fn.join(Fa.homedir(),".hablas"),Pa=Fn.join(pp,"analytics.json");function Ma(){try{if(Xe.existsSync(Pa))return JSON.parse(Xe.readFileSync(Pa,"utf-8"))}catch{}return mp()}function mp(){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 Da(t){let e=[];e.push(`
245
+ \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: ${t.totalSessions}`),e.push(` Messages: ${t.totalMessages}`),e.push(` Tokens used: ${t.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${t.totalToolCalls}`),e.push(` Files modified: ${t.totalFilesModified}`),e.push(` Lines written: ${t.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${t.totalBugsFixed}`),e.push(` Commits: ${t.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${t.streak} days (best: ${t.longestStreak})`),e.push("");let r=Object.entries(t.agentUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(r.length>0){e.push(" Top Agents:");for(let[s,i]of r)e.push(` @${s}: ${i} uses`);e.push("")}let n=Object.entries(t.commandUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(n.length>0){e.push(" Top Commands:");for(let[s,i]of n)e.push(` ${s}: ${i} calls`)}return e.join(`
246
+ `)}var La=k(require("readline"));function pe(t,e){return new Promise(r=>t.question(e,n=>r(n)))}async function ja(t){let e=La.createInterface({input:process.stdin,output:process.stdout,terminal:!0});console.log(""),console.log("Hablas setup"),console.log("1) Ollama (local)"),console.log("2) NVIDIA NIM"),console.log("3) Custom OpenAI-compatible API"),console.log("");let r=(await pe(e,"Choose provider [1-3]: ")).trim();if(r==="1"){let n=(await pe(e,`Ollama host [${t.ollamaHost}]: `)).trim(),s=(await pe(e,`Model [${t.model}]: `)).trim();t.provider="ollama",n&&(t.ollamaHost=n),s&&(t.model=s)}else if(r==="2"){let n=(await pe(e,"NVIDIA API key: ")).trim(),s=(await pe(e,`Model [${ne.defaultModel}]: `)).trim();t.provider="nvidia",t.apiUrl=ne.apiUrl,t.apiKey=n,t.model=s||ne.defaultModel}else if(r==="3"){let n=(await pe(e,"API base URL: ")).trim(),s=(await pe(e,"API key (optional): ")).trim(),i=(await pe(e,"Model ID: ")).trim();t.provider="custom",t.apiUrl=n,t.apiKey=s,i&&(t.model=i)}Qe(t),console.log(""),console.log("Setup complete."),console.log('Use `hablas` for interactive mode or `hablas run "..."` for one-shot execution.'),console.log(""),e.close()}var Na=co(),W=new Gn;W.name("hablas").description(`Hablas CLI v${Na} \u2014 single-agent engineering runtime for the terminal.`).version(Na).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").option("--api-key <key>","API key for custom or nvidia provider").option("--auto","Auto mode \u2014 skip tool confirmations where allowed").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--setup","Run setup wizard");W.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=W.opts(),r=Ie({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(r.autoMode=!0),e.timeout&&(r.timeout=parseInt(e.timeout,10));let n=mn(r);await Oa(t,r,n)});W.command("doctor").description("Run system diagnostics").action(async()=>{let t=W.opts(),e=Ie({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await Yt({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(Zt(r))});W.command("info").description("Show workspace information").action(async()=>{let t=W.opts(),e=Ie({project:t.project});console.log(""),console.log(qt(Ve(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});W.command("security").description("Run a security scan on the current project").action(async()=>{let t=W.opts(),e=Ie({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(Ia(Ra(r)))});W.command("stats").description("Show local usage statistics").action(async()=>{console.log(Da(Ma()))});W.action(async()=>{let t=W.opts(),e=Ie({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey});if(t.auto&&(e.autoMode=!0),t.timeout&&(e.timeout=parseInt(t.timeout,10)),t.setup){await ja(e);return}let r=mn(e);await Ea(e,r)});W.parse();