hablas-ai 2.1.2 → 2.2.1

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.
package/dist/index.js CHANGED
@@ -1,133 +1,133 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var cl=Object.create;var es=Object.defineProperty;var ul=Object.getOwnPropertyDescriptor;var fl=Object.getOwnPropertyNames;var dl=Object.getPrototypeOf,pl=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var hl=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fl(e))!pl.call(t,s)&&s!==r&&es(t,s,{get:()=>e[s],enumerable:!(n=ul(e,s))||n.enumerable});return t};var C=(t,e,r)=>(r=t!=null?cl(dl(t)):{},hl(e||!t||!t.__esModule?es(r,"default",{value:t,enumerable:!0}):r,t));var ct=I(br=>{var At=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}},wr=class extends At{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};br.CommanderError=At;br.InvalidArgumentError=wr});var Et=I(_r=>{var{InvalidArgumentError:ml}=ct(),Sr=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 ml(`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 gl(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}_r.Argument=Sr;_r.humanReadableArgName=gl});var vr=I(ts=>{var{humanReadableArgName:yl}=Et(),xr=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=>yl(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(`
2
+ "use strict";var ml=Object.create;var is=Object.defineProperty;var gl=Object.getOwnPropertyDescriptor;var yl=Object.getOwnPropertyNames;var wl=Object.getPrototypeOf,bl=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Sl=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of yl(e))!bl.call(t,s)&&s!==r&&is(t,s,{get:()=>e[s],enumerable:!(n=gl(e,s))||n.enumerable});return t};var k=(t,e,r)=>(r=t!=null?ml(wl(t)):{},Sl(e||!t||!t.__esModule?is(r,"default",{value:t,enumerable:!0}):r,t));var ft=I(xr=>{var Rt=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}},_r=class extends Rt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};xr.CommanderError=Rt;xr.InvalidArgumentError=_r});var It=I(kr=>{var{InvalidArgumentError:_l}=ft(),vr=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 _l(`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 xl(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}kr.Argument=vr;kr.humanReadableArgName=xl});var $r=I(os=>{var{humanReadableArgName:vl}=It(),Cr=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=>vl(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
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 h=r.visibleOptions(e).map(c=>a(r.optionTerm(c),r.optionDescription(c)));if(h.length>0&&(u=u.concat(["Options:",l(h),""])),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 p=r.visibleCommands(e).map(c=>a(r.subcommandTerm(c),r.subcommandDescription(c)));return p.length>0&&(u=u.concat(["Commands:",l(p),""])),u.join(`
4
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
6
  `),d=" ".repeat(n),h="\\s\u200B",p=new RegExp(`
7
7
  |.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),c=u.match(p)||[];return l+c.map((m,y)=>m===`
8
8
  `?"":(y>0?d:"")+m.trimEnd()).join(`
9
- `)}};ts.Help=xr});var Tr=I($r=>{var{InvalidArgumentError:wl}=ct(),kr=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=Sl(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 wl(`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 bl(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Cr=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 bl(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Sl(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}}$r.Option=kr;$r.DualOptions=Cr});var ns=I(rs=>{function _l(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 xl(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=_l(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?`
9
+ `)}};os.Help=Cr});var Or=I(Er=>{var{InvalidArgumentError:kl}=ft(),Tr=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=$l(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 kl(`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 Cl(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ar=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 Cl(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function $l(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}}Er.Option=Tr;Er.DualOptions=Ar});var ls=I(as=>{function Tl(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 Al(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=Tl(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
10
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
11
- (Did you mean ${n[0]}?)`:""}rs.suggestSimilar=xl});var ls=I(as=>{var vl=require("node:events").EventEmitter,Ar=require("node:child_process"),pe=require("node:path"),Er=require("node:fs"),U=require("node:process"),{Argument:kl,humanReadableArgName:Cl}=Et(),{CommanderError:Or}=ct(),{Help:$l}=vr(),{Option:ss,DualOptions:Tl}=Tr(),{suggestSimilar:is}=ns(),Rr=class t extends vl{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=>U.stdout.write(r),writeErr:r=>U.stderr.write(r),getOutHelpWidth:()=>U.stdout.isTTY?U.stdout.columns:void 0,getErrHelpWidth:()=>U.stderr.isTTY?U.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 $l,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 kl(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 Or(e,r,n)),U.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 ss(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 ss)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){U.versions?.electron&&(r.from="electron");let s=U.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(r.from="eval")}e===void 0&&(e=U.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":U.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 h=pe.resolve(d,f);if(Er.existsSync(h))return h;if(s.includes(pe.extname(f)))return;let p=s.find(c=>Er.existsSync(`${h}${c}`));if(p)return`${h}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=Er.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=pe.resolve(pe.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=pe.basename(this._scriptPath,pe.extname(this._scriptPath));f!==this._name&&(d=i(a,`${f}-${e._name}`))}o=d||o}n=s.includes(pe.extname(o));let l;U.platform!=="win32"?n?(r.unshift(o),r=os(U.execArgv).concat(r),l=Ar.spawn(U.argv[0],r,{stdio:"inherit"})):l=Ar.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=os(U.execArgv).concat(r),l=Ar.spawn(U.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{U.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 Or(d,"commander.executeSubCommandAsync","(close)")):U.exit(d)}),l.on("error",d=>{if(d.code==="ENOENT"){let f=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
11
+ (Did you mean ${n[0]}?)`:""}as.suggestSimilar=Al});var ps=I(ds=>{var El=require("node:events").EventEmitter,Rr=require("node:child_process"),pe=require("node:path"),Ir=require("node:fs"),U=require("node:process"),{Argument:Ol,humanReadableArgName:Rl}=It(),{CommanderError:Pr}=ft(),{Help:Il}=$r(),{Option:cs,DualOptions:Pl}=Or(),{suggestSimilar:us}=ls(),Mr=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=>U.stdout.write(r),writeErr:r=>U.stderr.write(r),getOutHelpWidth:()=>U.stdout.isTTY?U.stdout.columns:void 0,getErrHelpWidth:()=>U.stderr.isTTY?U.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 Il,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 Ol(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 Pr(e,r,n)),U.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 cs(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 cs)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){U.versions?.electron&&(r.from="electron");let s=U.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(r.from="eval")}e===void 0&&(e=U.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":U.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 h=pe.resolve(d,f);if(Ir.existsSync(h))return h;if(s.includes(pe.extname(f)))return;let p=s.find(c=>Ir.existsSync(`${h}${c}`));if(p)return`${h}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=Ir.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=pe.resolve(pe.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=pe.basename(this._scriptPath,pe.extname(this._scriptPath));f!==this._name&&(d=i(a,`${f}-${e._name}`))}o=d||o}n=s.includes(pe.extname(o));let l;U.platform!=="win32"?n?(r.unshift(o),r=fs(U.execArgv).concat(r),l=Rr.spawn(U.argv[0],r,{stdio:"inherit"})):l=Rr.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=fs(U.execArgv).concat(r),l=Rr.spawn(U.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{U.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 Pr(d,"commander.executeSubCommandAsync","(close)")):U.exit(d)}),l.on("error",d=>{if(d.code==="ENOENT"){let f=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
15
15
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${f}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)U.exit(1);else{let f=new Or(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}
17
+ - ${f}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)U.exit(1);else{let f=new Pr(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 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 U.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()}`,U.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Tl(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=is(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=is(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=>Cl(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=pe.basename(e,pe.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=U.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.
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 U.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()}`,U.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Pl(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=us(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=us(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=pe.basename(e,pe.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=U.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
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 os(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})}as.Command=Rr});var ds=I(Y=>{var{Argument:cs}=Et(),{Command:Ir}=ls(),{CommanderError:Al,InvalidArgumentError:us}=ct(),{Help:El}=vr(),{Option:fs}=Tr();Y.program=new Ir;Y.createCommand=t=>new Ir(t);Y.createOption=(t,e)=>new fs(t,e);Y.createArgument=(t,e)=>new cs(t,e);Y.Command=Ir;Y.Option=fs;Y.Argument=cs;Y.Help=El;Y.CommanderError=Al;Y.InvalidArgumentError=us;Y.InvalidOptionArgumentError=us});var Dr=I((bm,bs)=>{"use strict";var ft=t=>t&&typeof t.message=="string",Pr=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return ft(r)?r:void 0}else return ft(e)?e:void 0},ys=(t,e)=>{if(!ft(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
- causes have become circular...`;let n=Pr(t);return n?(e.add(t),r+`
25
- caused by: `+ys(n,e)):r},Ol=t=>ys(t,new Set),ws=(t,e,r)=>{if(!ft(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=Pr(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+ws(s,e,i)}else return n},Rl=t=>ws(t,new Set);bs.exports={isErrorLike:ft,getErrorCause:Pr,stackWithCauses:Ol,messageWithCauses:Rl}});var Fr=I((Sm,_s)=>{"use strict";var Il=Symbol("circular-ref-tag"),Ot=Symbol("pino-raw-err-ref"),Ss=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[Ot]},set:function(t){this[Ot]=t}}});Object.defineProperty(Ss,Ot,{writable:!0,value:{}});_s.exports={pinoErrProto:Ss,pinoErrorSymbols:{seen:Il,rawSymbol:Ot}}});var ks=I((_m,vs)=>{"use strict";vs.exports=jr;var{messageWithCauses:Ml,stackWithCauses:Pl,isErrorLike:xs}=Dr(),{pinoErrProto:Dl,pinoErrorSymbols:Fl}=Fr(),{seen:Lr}=Fl,{toString:Ll}=Object.prototype;function jr(t){if(!xs(t))return t;t[Lr]=void 0;let e=Object.create(Dl);e.type=Ll.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=Ml(t),e.stack=Pl(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>jr(r)));for(let r in t)if(e[r]===void 0){let n=t[r];xs(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Lr)&&(e[r]=jr(n)):e[r]=n}return delete t[Lr],e.raw=t,e}});var $s=I((xm,Cs)=>{"use strict";Cs.exports=It;var{isErrorLike:Nr}=Dr(),{pinoErrProto:jl,pinoErrorSymbols:Nl}=Fr(),{seen:Rt}=Nl,{toString:ql}=Object.prototype;function It(t){if(!Nr(t))return t;t[Rt]=void 0;let e=Object.create(jl);e.type=ql.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=>It(r))),Nr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,Rt)&&(e.cause=It(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];Nr(n)?Object.prototype.hasOwnProperty.call(n,Rt)||(e[r]=It(n)):e[r]=n}return delete t[Rt],e.raw=t,e}});var Os=I((vm,Es)=>{"use strict";Es.exports={mapHttpRequest:Ul,reqSerializer:As};var qr=Symbol("pino-raw-req-ref"),Ts=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[qr]},set:function(t){this[qr]=t}}});Object.defineProperty(Ts,qr,{writable:!0,value:{}});function As(t){let e=t.info||t.socket,r=Object.create(Ts);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 Ul(t){return{req:As(t)}}});var Ps=I((km,Ms)=>{"use strict";Ms.exports={mapHttpResponse:Bl,resSerializer:Is};var Ur=Symbol("pino-raw-res-ref"),Rs=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Ur]},set:function(t){this[Ur]=t}}});Object.defineProperty(Rs,Ur,{writable:!0,value:{}});function Is(t){let e=Object.create(Rs);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:Is(t)}}});var Hr=I((Cm,Ds)=>{"use strict";var Br=ks(),Hl=$s(),Mt=Os(),Pt=Ps();Ds.exports={err:Br,errWithCause:Hl,mapHttpRequest:Mt.mapHttpRequest,mapHttpResponse:Pt.mapHttpResponse,req:Mt.reqSerializer,res:Pt.resSerializer,wrapErrorSerializer:function(e){return e===Br?e:function(n){return e(Br(n))}},wrapRequestSerializer:function(e){return e===Mt.reqSerializer?e:function(n){return e(Mt.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Pt.resSerializer?e:function(n){return e(Pt.resSerializer(n))}}}});var Wr=I(($m,Fs)=>{"use strict";function Wl(t,e){return e}Fs.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=Wl;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 Bs=I((Tm,Us)=>{"use strict";function Vr(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]=Vr(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]=Vr(t[r]));return e}return t}function Ls(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 js(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 Ns(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 Dt=Symbol("PATH_NOT_FOUND");function Vl(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return Dt;r=r[n]}return r}function zl(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=Ls(s);if(i.includes("*"))qs(t,i,r,s,n);else if(n)Ns(t,i);else{let o=Vl(t,i);if(o===Dt)continue;let a=typeof r=="function"?r(o,i):r;js(t,i,a)}}}function qs(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 Gl(t,e,r,i,n,s)}function Gl(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 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("*"))qs(d,a,typeof r=="function"?(p,c)=>{let m=[...l.slice(0,f),...c];return r(p,m)}:r,s,i);else if(i)Ns(d,a);else{let h=typeof r=="function"?r(zl(d,a),[...l.slice(0,f),...a]):r;js(d,a,h)}}if(o.length===0)u(t,0);else{let d=t;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 Jl(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=Ls(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 Xl(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 Yl(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 Zl(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)Yl(e)}function Ql(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;Zl(e);let o=Jl(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let u=Xl(l,o),d=l,f=r;return typeof r=="function"&&(f=r),Kl(u,e,f,i),n===!1?(u.restore=function(){return Vr(d)},u):typeof n=="function"?n(u):JSON.stringify(u)}}Us.exports=Ql});var Ve=I((Am,Hs)=>{"use strict";var ec=Symbol("pino.setLevel"),tc=Symbol("pino.getLevel"),rc=Symbol("pino.levelVal"),nc=Symbol("pino.levelComp"),sc=Symbol("pino.useLevelLabels"),ic=Symbol("pino.useOnlyCustomLevels"),oc=Symbol("pino.mixin"),ac=Symbol("pino.lsCache"),lc=Symbol("pino.chindings"),cc=Symbol("pino.asJson"),uc=Symbol("pino.write"),fc=Symbol("pino.redactFmt"),dc=Symbol("pino.time"),pc=Symbol("pino.timeSliceIndex"),hc=Symbol("pino.stream"),mc=Symbol("pino.stringify"),gc=Symbol("pino.stringifySafe"),yc=Symbol("pino.stringifiers"),wc=Symbol("pino.end"),bc=Symbol("pino.formatOpts"),Sc=Symbol("pino.messageKey"),_c=Symbol("pino.errorKey"),xc=Symbol("pino.nestedKey"),vc=Symbol("pino.nestedKeyStr"),kc=Symbol("pino.mixinMergeStrategy"),Cc=Symbol("pino.msgPrefix"),$c=Symbol("pino.wildcardFirst"),Tc=Symbol.for("pino.serializers"),Ac=Symbol.for("pino.formatters"),Ec=Symbol.for("pino.hooks"),Oc=Symbol.for("pino.metadata");Hs.exports={setLevelSym:ec,getLevelSym:tc,levelValSym:rc,levelCompSym:nc,useLevelLabelsSym:sc,mixinSym:oc,lsCacheSym:ac,chindingsSym:lc,asJsonSym:cc,writeSym:uc,serializersSym:Tc,redactFmtSym:fc,timeSym:dc,timeSliceIndexSym:pc,streamSym:hc,stringifySym:mc,stringifySafeSym:gc,stringifiersSym:yc,endSym:wc,formatOptsSym:bc,messageKeySym:Sc,errorKeySym:_c,nestedKeySym:xc,wildcardFirstSym:$c,needsMetadataGsym:Oc,useOnlyCustomLevelsSym:ic,formattersSym:Ac,hooksSym:Ec,nestedKeyStrSym:vc,mixinMergeStrategySym:kc,msgPrefixSym:Cc}});var Kr=I((Em,Ks)=>{"use strict";var Ws=Bs(),{redactFmtSym:Rc,wildcardFirstSym:Ft}=Ve(),zr=/[^.[\]]+|\[([^[\]]*?)\]/g,Vs="[Redacted]",zs=!1;function Ic(t,e){let{paths:r,censor:n,remove:s}=Mc(t),i=r.reduce((l,u)=>{zr.lastIndex=0;let d=zr.exec(u),f=zr.exec(u),h=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(h==="*"&&(h=Ft),f===null)return l[h]=null,l;if(l[h]===null)return l;let{index:p}=f,c=`${u.substr(p,u.length-1)}`;return l[h]=l[h]||[],h!==Ft&&l[h].length===0&&l[h].push(...l[Ft]||[]),h===Ft&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(c)}),l[h].push(c),l},{}),o={[Rc]:Ws({paths:r,censor:n,serialize:e,strict:zs,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,h)=>n(f,[u,...h]):n;l[u]=Ws({paths:i[u],censor:d,serialize:e,strict:zs,remove:s})}return l},o)}function Mc(t){if(Array.isArray(t))return t={paths:t,censor:Vs},t;let{paths:e,censor:r=Vs,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}}Ks.exports=Ic});var Xs=I((Om,Js)=>{"use strict";var Pc=()=>"",Dc=()=>`,"time":${Date.now()}`,Fc=()=>`,"time":${Math.round(Date.now()/1e3)}`,Lc=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,jc=1000000n,Gs=1000000000n,Nc=BigInt(Date.now())*jc,qc=process.hrtime.bigint(),Uc=()=>{let t=process.hrtime.bigint()-qc,e=Nc+t,r=e/Gs,n=e%Gs,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"`};Js.exports={nullTime:Pc,epochTime:Dc,unixTime:Fc,isoTime:Lc,isoTimeNano:Uc}});var Zs=I((Rm,Ys)=>{"use strict";function Bc(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}Ys.exports=Hc;function Hc(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,h=t&&t.length||0,p=0;p<h;){if(t.charCodeAt(p)===37&&p+1<h){switch(f=f>-1?f:0,t.charCodeAt(p+1)){case 100:case 102:if(d>=l||e[d]==null)break;f<p&&(u+=t.slice(f,p)),u+=Number(e[d]),f=p+2,p++;break;case 105:if(d>=l||e[d]==null)break;f<p&&(u+=t.slice(f,p)),u+=Math.floor(Number(e[d])),f=p+2,p++;break;case 79:case 111:case 106:if(d>=l||e[d]===void 0)break;f<p&&(u+=t.slice(f,p));var c=typeof e[d];if(c==="string"){u+="'"+e[d]+"'",f=p+2,p++;break}if(c==="function"){u+=e[d].name||"<anonymous>",f=p+2,p++;break}u+=n(e[d]),f=p+2,p++;break;case 115:if(d>=l)break;f<p&&(u+=t.slice(f,p)),u+=String(e[d]),f=p+2,p++;break;case 37:f<p&&(u+=t.slice(f,p)),u+="%",f=p+2,p++,d--;break}++d}++p}return f===-1?t:(f<h&&(u+=t.slice(f)),u)}});var Jr=I((Im,Gr)=>{"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));Gr.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(););};Gr.exports=t}});var oi=I((Mm,ii)=>{"use strict";var L=require("fs"),Wc=require("events"),Vc=require("util").inherits,Qs=require("path"),Yr=Jr(),zc=require("assert"),Lt=100,jt=Buffer.allocUnsafe(0),Kc=16*1024,ei="buffer",ti="utf8",[Gc,Jc]=(process.versions.node||"0.0").split(".").map(Number),Xc=Gc>=22&&Jc>=7;function ri(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&&L.mkdirSync(Qs.dirname(t),{recursive:!0});let i=L.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?L.mkdir(Qs.dirname(t),{recursive:!0},i=>{if(i)return r(i);L.open(t,n,s,r)}):L.open(t,n,s,r)}function ie(t){if(!(this instanceof ie))return new ie(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:h,mode:p}=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=p,this.retryEAGAIN=d||(()=>!0),this.mkdir=u||!1;let c,m;if(h===ei)this._writingBuf=jt,this.write=Qc,this.flush=tu,this.flushSync=nu,this._actualWrite=iu,c=()=>L.writeSync(this.fd,this._writingBuf),m=()=>L.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===ti)this._writingBuf="",this.write=Zc,this.flush=eu,this.flushSync=ru,this._actualWrite=su,c=()=>Buffer.isBuffer(this._writingBuf)?L.writeSync(this.fd,this._writingBuf):L.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?L.write(this.fd,this._writingBuf,this.release):L.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${ti}" and "${ei}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")ri(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,S)=>{if(y){if((y.code==="EAGAIN"||y.code==="EBUSY")&&this.retryEAGAIN(y,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Yr(Lt),this.release(void 0,0)}catch(_){this.release(_)}else setTimeout(m,Lt);else this._writing=!1,this.emit("error",y);return}this.emit("write",S);let b=Xr(this._writingBuf,this._len,S);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let _=c(),k=Xr(this._writingBuf,this._len,_);this._len=k.len,this._writingBuf=k.writingBuf}while(this._writingBuf.length)}catch(_){this.release(_);return}}this._fsync&&L.fsyncSync(this.fd);let x=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):x>this.minLength?this._actualWrite():this._ending?x>0?this._actualWrite():(this._writing=!1,Nt(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Yc,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 Xr(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 Yc(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Vc(ie,Wc);function ni(t,e){return t.length===0?jt:t.length===1?t[0]:Buffer.concat(t,e)}function Zc(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 Qc(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 si(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{L.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 eu(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&&si.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function tu(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&&si.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}ie.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&&L.close(e,r=>{if(r)return this.emit("error",r)})}),ri(this.file,this)};ie.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():Nt(this)))};function ru(){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)?L.writeSync(this.fd,t):L.writeSync(this.fd,t,"utf8"),r=Xr(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;Yr(Lt)}}try{L.fsyncSync(this.fd)}catch{}}function nu(){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=jt);let t=jt;for(;this._bufs.length||t.length;){t.length<=0&&(t=ni(this._bufs[0],this._lens[0]));try{let e=L.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;Yr(Lt)}}}ie.prototype.destroy=function(){this.destroyed||Nt(this)};function su(){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)?L.writeSync(this.fd,this._writingBuf):L.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else L.write(this.fd,this._writingBuf,t)}function iu(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:ni(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=L.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else Xc&&(this._writingBuf=Buffer.from(this._writingBuf)),L.write(this.fd,this._writingBuf,t)}function Nt(t){if(t.fd===-1){t.once("ready",Nt.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],zc(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{L.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?L.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")}}ie.SonicBoom=ie;ie.default=ie;ii.exports=ie});var Zr=I((Pm,fi)=>{"use strict";var oe={exit:[],beforeExit:[]},ai={exit:lu,beforeExit:cu},ze;function ou(){ze===void 0&&(ze=new FinalizationRegistry(uu))}function au(t){oe[t].length>0||process.on(t,ai[t])}function li(t){oe[t].length>0||(process.removeListener(t,ai[t]),oe.exit.length===0&&oe.beforeExit.length===0&&(ze=void 0))}function lu(){ci("exit")}function cu(){ci("beforeExit")}function ci(t){for(let e of oe[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}oe[t]=[]}function uu(t){for(let e of["exit","beforeExit"]){let r=oe[e].indexOf(t);oe[e].splice(r,r+1),li(e)}}function ui(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");au(t);let n=new WeakRef(e);n.fn=r,ou(),ze.register(e,n),oe[t].push(n)}function fu(t,e){ui("exit",t,e)}function du(t,e){ui("beforeExit",t,e)}function pu(t){if(ze!==void 0){ze.unregister(t);for(let e of["exit","beforeExit"])oe[e]=oe[e].filter(r=>{let n=r.deref();return n&&n!==t}),li(e)}}fi.exports={register:fu,registerBeforeExit:du,unregister:pu}});var di=I((Dm,hu)=>{hu.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 hi=I((Fm,pi)=>{"use strict";function mu(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 gu(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()}pi.exports={wait:mu,waitDiff:gu}});var gi=I((Lm,mi)=>{"use strict";mi.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Ai=I((jm,Ti)=>{"use strict";var{version:yu}=di(),{EventEmitter:wu}=require("events"),{Worker:bu}=require("worker_threads"),{join:Su}=require("path"),{pathToFileURL:_u}=require("url"),{wait:xu}=hi(),{WRITE_INDEX:he,READ_INDEX:Ae,SEQ_INDEX:Qr}=gi(),vu=require("buffer"),ku=require("assert"),g=Symbol("kImpl"),Cu=vu.constants.MAX_STRING_LENGTH;function yi(){}function nn(t,e){Atomics.add(t[g].state,Qr,1),e(),Atomics.add(t[g].state,Qr,1),Atomics.notify(t[g].state,Qr)}function wi(t){nn(t,()=>{Atomics.store(t[g].state,Ae,0),Atomics.store(t[g].state,he,0)})}var dt=class{constructor(e){this._value=e}deref(){return this._value}},qt=class{register(){}unregister(){}},$u=process.env.NODE_V8_COVERAGE?qt:global.FinalizationRegistry||qt,Tu=process.env.NODE_V8_COVERAGE?dt:global.WeakRef||dt,bi=new $u(t=>{t.exited||t.terminate()});function Au(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Su(__dirname,"lib","worker.js"),o=new bu(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:_u(r).href,dataBuf:t[g].dataBuf,stateBuf:t[g].stateBuf,workerData:{$context:{threadStreamVersion:yu},...n}}});return o.stream=new dt(t),o.on("message",Eu),o.on("exit",xi),bi.register(t,o),o}function Si(t){ku(!t[g].sync),t[g].needDrain&&(t[g].needDrain=!1,t.emit("drain"))}function _i(t){for(;;){let e=Atomics.load(t[g].state,he),r=t[g].data.length-e;if(r>0){if(t[g].bufLen===0){t[g].flushing=!1,t[g].ending?sn(t):t[g].needDrain&&process.nextTick(Si,t);return}Ci(t,r,yi);continue}if(r===0){if(e===0&&t[g].bufLen===0)return;Ut(t,()=>{t.destroyed||(wi(t),_i(t))});return}Z(t,new Error("overwritten"));return}}function Eu(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 Tu(e),Ut(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 xi(t){let e=this.stream.deref();e!==void 0&&(bi.unregister(e),e.worker.exited=!0,e.worker.off("exit",xi),Z(e,t!==0?new Error("the worker thread exited"):null))}var tn=class extends wu{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=Au(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 rn(this,new Error("the worker has exited")),!1;if(this[g].ending)return rn(this,new Error("the worker is ending")),!1;if(this[g].flushing&&this[g].bufLen+r.length>=Cu)try{en(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 en(this),!0}catch(n){return Z(this,n),!1}return this[g].flushing||(this[g].flushing=!0,setImmediate(_i,this)),this[g].needDrain=this[g].data.length-this[g].bufLen-Atomics.load(this[g].state,he)<=0,!this[g].needDrain}end(){this[g].destroyed||(this[g].ending=!0,sn(this))}flush(e){e=typeof e=="function"?e:yi,vi(this,r=>{if(r){process.nextTick(e,r);return}ki(this,e)})}flushSync(){this[g].destroyed||(en(this),$i(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 vi(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(vi,t,e);return}Ut(t,e)}function Ut(t,e){let r=Atomics.load(t[g].state,he);xu(t[g].state,Ae,r,1/0,(n,s)=>{if(n){Z(t,n),e(n);return}if(s!=="ok"){Ut(t,e);return}e()})}function ki(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].ready){let n=()=>{i(),ki(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 Ou(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 rn(t,e){setImmediate(()=>{t.emit("error",e)})}function Z(t,e){t[g].destroyed||(t[g].destroyed=!0,Ou(t,e),e&&(t[g].errored=e,rn(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 Ci(t,e,r){let s=Atomics.load(t[g].state,he),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 nn(t,()=>{Atomics.store(t[g].state,he,s)}),r(),!0}function sn(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,Ae);nn(t,()=>{Atomics.store(t[g].state,he,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[g].state,Ae,e,1e3),e=Atomics.load(t[g].state,Ae),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 en(t){let e=()=>{t[g].ending?sn(t):t[g].needDrain&&process.nextTick(Si,t)};for(t[g].flushing=!1;t[g].bufLen!==0;){let r=Atomics.load(t[g].state,he),n=t[g].data.length-r;if(n===0){$i(t),wi(t);continue}else if(n<0)throw new Error("overwritten");Ci(t,n,e)}}function $i(t){if(t[g].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[g].state,he),r=0;for(;;){let n=Atomics.load(t[g].state,Ae);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[g].state,Ae,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}Ti.exports=tn});var ln=I((Nm,Ri)=>{"use strict";var{createRequire:Ru}=require("module"),{existsSync:Iu}=require("node:fs"),Mu=Wr(),{join:on,isAbsolute:Oi,sep:Pu}=require("node:path"),{fileURLToPath:Du}=require("node:url"),Fu=Jr(),an=Zr(),Lu=Ai();function ju(t){an.register(t,Hu),an.registerBeforeExit(t,Wu),t.on("close",function(){an.unregister(t)})}function Nu(){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 qu(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&&Ei(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(Ei(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function Ei(t){let e=Uu(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=Du(r)}catch{return!1}return Oi(r)&&!Iu(r)}function Uu(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&&Nu()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=qu(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new Lu({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&&ju(i)}function a(){i.closed||(i.flushSync(),Fu(100),i.end())}return i}function Hu(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Wu(t){t.flushSync()}function Vu(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=Mu(),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"]||on(__dirname,"worker.js"),l.targets=r.filter(c=>c.target).map(c=>({...c,target:p(c.target)})),l.pipelines=r.filter(c=>c.pipeline).map(c=>c.pipeline.map(m=>({...m,level:c.level,target:p(m.target)})))):e&&(f=d["pino-worker"]||on(__dirname,"worker.js"),l.pipelines=[e.map(c=>({...c,target:p(c.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let h=r||e?"pino.transport":f;return Bu(p(f),l,i,a,h);function p(c){if(c=d[c]||c,Oi(c)||c.indexOf("file://")===0)return c;if(c==="pino/file")return on(__dirname,"..","file.js");let m;for(let y of u)try{let S=y==="node:repl"?process.cwd()+Pu:y;m=Ru(S).resolve(c);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${c}"`);return m}}Ri.exports=Vu});var Wt=I((qm,Wi)=>{"use strict";var zu=require("node:diagnostics_channel"),Ii=Zs(),{mapHttpRequest:Ku,mapHttpResponse:Gu}=Hr(),un=oi(),Mi=Zr(),{lsCacheSym:Ju,chindingsSym:ji,writeSym:Pi,serializersSym:Ni,formatOptsSym:Di,endSym:Xu,stringifiersSym:qi,stringifySym:Ui,stringifySafeSym:fn,wildcardFirstSym:Bi,nestedKeySym:Yu,formattersSym:Hi,messageKeySym:Zu,errorKeySym:Qu,nestedKeyStrSym:ef,msgPrefixSym:Bt}=Ve(),{isMainThread:tf}=require("worker_threads"),rf=ln(),[nf]=process.versions.node.split(".").map(t=>Number(t)),Fi=zu.tracingChannel("pino_asJson"),cn=nf>=25?t=>JSON.stringify(t):of;function Ke(){}function sf(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=Gu(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Bt]=="string"&&i!==void 0&&i!==null&&(i=this[Bt]+i),this[Pi](n,Ii(i,o,this[Di]),t)}else{let i=n===void 0?s.shift():n;typeof this[Bt]=="string"&&i!==void 0&&i!==null&&(i=this[Bt]+i),this[Pi](null,Ii(i,s,this[Di]),t)}}}function of(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 af(t,e,r,n){if(Fi.hasSubscribers===!1)return Li.call(this,t,e,r,n);let s={instance:this,arguments};return Fi.traceSync(Li,s,this,t,e,r,n)}function Li(t,e,r,n){let s=this[Ui],i=this[fn],o=this[qi],a=this[Xu],l=this[ji],u=this[Ni],d=this[Hi],f=this[Zu],h=this[Qu],p=this[Ju][r]+n;p=p+l;let c;d.log&&(t=d.log(t));let m=o[Bi],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===h&&u.err&&(c=u.err(c));let x=o[b]||m;switch(typeof c){case"undefined":case"function":continue;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":x&&(c=x(c));break;case"string":c=(x||cn)(c);break;default:c=(x||s)(c,i)}if(c===void 0)continue;let _=cn(b);y+=","+_+":"+c}let S="";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)),S=',"'+f+'":'+c;break;case"string":c=(b||cn)(c),S=',"'+f+'":'+c;break;default:c=(b||s)(c,i),S=',"'+f+'":'+c}}return this[Yu]&&y?p+this[ef]+y.slice(1)+"}"+S+a:p+y+S+a}function lf(t,e){let r,n=t[ji],s=t[Ui],i=t[fn],o=t[qi],a=o[Bi],l=t[Ni],u=t[Hi].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 cf(t){return t.write!==t.constructor.prototype.write}function Ht(t){let e=new un(t);return e.on("error",r),!t.sync&&tf&&(Mi.register(e,uf),e.on("close",function(){Mi.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Ke,e.end=Ke,e.flushSync=Ke,e.destroy=Ke;return}e.removeListener("error",r),e.emit("error",n)}}function uf(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function ff(t){return function(r,n,s={},i){if(typeof s=="string")i=Ht({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=Ht({dest:i})}else if(s instanceof un||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof un||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=rf({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=Ke),i||(cf(process.stdout)?i=process.stdout:i=Ht({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function df(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[fn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function pf(t,e,r){return{level:t,bindings:e,log:r}}function hf(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Wi.exports={noop:Ke,buildSafeSonicBoom:Ht,asChindings:lf,asJson:af,genLog:sf,createArgsNormalizer:ff,stringify:df,buildFormatters:pf,normalizeDestFileDescriptor:hf}});var Vt=I((Um,Vi)=>{var mf={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},gf={ASC:"ASC",DESC:"DESC"};Vi.exports={DEFAULT_LEVELS:mf,SORTING_ORDER:gf}});var hn=I((Bm,Ji)=>{"use strict";var{lsCacheSym:yf,levelValSym:dn,useOnlyCustomLevelsSym:wf,streamSym:bf,formattersSym:Sf,hooksSym:_f,levelCompSym:zi}=Ve(),{noop:xf,genLog:Ee}=Wt(),{DEFAULT_LEVELS:ue,SORTING_ORDER:Ki}=Vt(),Gi={fatal:t=>{let e=Ee(ue.fatal,t);return function(...r){let n=this[bf];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>Ee(ue.error,t),warn:t=>Ee(ue.warn,t),info:t=>Ee(ue.info,t),debug:t=>Ee(ue.debug,t),trace:t=>Ee(ue.trace,t)},pn=Object.keys(ue).reduce((t,e)=>(t[ue[e]]=e,t),{}),vf=Object.keys(pn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function kf(t){let e=t[Sf].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[yf]=n,t}function Cf(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 $f(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[dn],s=this[dn]=r[t],i=this[wf],o=this[zi],a=this[_f].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=xf;continue}this[l]=Cf(l,i)?Gi[l](a):Ee(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function Tf(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Af(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[zi](r,this[dn])}function Ef(t,e,r){return t===Ki.DESC?e<=r:e>=r}function Of(t){return typeof t=="string"?Ef.bind(null,t):t}function Rf(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:pn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:ue,t);return{labels:n,values:s}}function If(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(pn).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:ue,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function Mf(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 Pf(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Ki).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Ji.exports={initialLsCache:vf,genLsCache:kf,levelMethods:Gi,getLevel:Tf,setLevel:$f,isLevelEnabled:Af,mappings:Rf,assertNoLevelCollisions:Mf,assertDefaultLevelFound:If,genLevelComparison:Of,assertLevelComparison:Pf}});var mn=I((Hm,Xi)=>{"use strict";Xi.exports={version:"10.3.1"}});var so=I((Vm,no)=>{"use strict";var{EventEmitter:Df}=require("node:events"),{lsCacheSym:Ff,levelValSym:Lf,setLevelSym:yn,getLevelSym:Yi,chindingsSym:Kt,mixinSym:jf,asJsonSym:Qi,writeSym:Nf,mixinMergeStrategySym:qf,timeSym:Uf,timeSliceIndexSym:Bf,streamSym:eo,serializersSym:Oe,formattersSym:pt,errorKeySym:Hf,messageKeySym:Wf,useOnlyCustomLevelsSym:Vf,needsMetadataGsym:zf,redactFmtSym:Kf,stringifySym:Gf,formatOptsSym:Jf,stringifiersSym:Xf,msgPrefixSym:wn,hooksSym:Yf}=Ve(),{getLevel:Zf,setLevel:Qf,isLevelEnabled:ed,mappings:td,initialLsCache:rd,genLsCache:nd,assertNoLevelCollisions:sd}=hn(),{asChindings:bn,asJson:id,buildFormatters:gn,stringify:Zi,noop:to}=Wt(),{version:od}=mn(),ad=Kr(),ld=class{},ro={constructor:ld,child:cd,bindings:ud,setBindings:fd,flush:hd,isLevelEnabled:ed,version:od,get level(){return this[Yi]()},set level(t){this[yn](t)},get levelVal(){return this[Lf]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[wn]},get[Symbol.toStringTag](){return"Pino"},[Ff]:rd,[Nf]:pd,[Qi]:id,[Yi]:Zf,[yn]:Qf};Object.setPrototypeOf(ro,Df.prototype);no.exports=function(){return Object.create(ro)};var zt=t=>t;function cd(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[Oe],n=this[pt],s=Object.create(this);if(e==null)return s[pt].bindings!==zt&&(s[pt]=gn(n.level,zt,n.log)),s[Kt]=bn(s,t),this.onChild!==to&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[Oe]=Object.create(null);for(let u in r)s[Oe][u]=r[u];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let u=a[i];s[Oe][u]=r[u]}for(let u in e.serializers)s[Oe][u]=e.serializers[u];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let u=l[o];s[Oe][u]=e.serializers[u]}}else s[Oe]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:u}=e.formatters;s[pt]=gn(a||n.level,l||zt,u||n.log)}else s[pt]=gn(n.level,zt,n.log);if(e.hasOwnProperty("customLevels")===!0&&(sd(this.levels,e.customLevels),s.levels=td(e.customLevels,s[Vf]),nd(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=ad(s.redact,Zi),l={stringify:a[Kf]};s[Gf]=Zi,s[Xf]=a,s[Jf]=l}if(typeof e.msgPrefix=="string"&&(s[wn]=(this[wn]||"")+e.msgPrefix),s[Kt]=bn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[yn](a)}return this.onChild(s),s}function ud(){let e=`{${this[Kt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function fd(t){let e=bn(this,t);this[Kt]=e}function dd(t,e){return Object.assign(e,t)}function pd(t,e,r){let n=this[Uf](),s=this[jf],i=this[Hf],o=this[Wf],a=this[qf]||dd,l,u=this[Yf].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[Qi](l,e,r,n),f=this[eo];f[zf]===!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 hd(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[eo];typeof e.flush=="function"?e.flush(t||to):t&&t()}});var lo=I((vn,ao)=>{"use strict";var{hasOwnProperty:ht}=Object.prototype,Ie=xn();Ie.configure=xn;Ie.stringify=Ie;Ie.default=Ie;vn.stringify=Ie;vn.configure=xn;ao.exports=Ie;var md=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function _e(t){return t.length<5e3&&!md.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 gd=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function _n(t){return gd.call(t)!==void 0&&t.length!==0}function io(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 yd(t){if(ht.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 wd(t){let e;if(ht.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 bd(t,e){let r;if(ht.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 oo(t,e){let r;if(ht.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 Re(t){return t===1?"1 item":`${t} items`}function Sd(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function _d(t){if(ht.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 xn(t){t={...t};let e=_d(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=yd(t),n=bd(t,"bigint"),s=wd(t),i=typeof s=="function"?s:void 0,o=oo(t,"maximumDepth"),a=oo(t,"maximumBreadth");function l(p,c,m,y,S,b){let x=c[p];switch(typeof x=="object"&&x!==null&&typeof x.toJSON=="function"&&(x=x.toJSON(p)),x=y.call(c,p,x),typeof x){case"string":return _e(x);case"object":{if(x===null)return"null";if(m.indexOf(x)!==-1)return r;let _="",k=",",A=b;if(Array.isArray(x)){if(x.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(x),S!==""&&(b+=S,_+=`
26
- ${b}`,k=`,
27
- ${b}`);let F=Math.min(x.length,a),B=0;for(;B<F-1;B++){let K=l(String(B),x,m,y,S,b);_+=K!==void 0?K:"null",_+=k}let W=l(String(B),x,m,y,S,b);if(_+=W!==void 0?W:"null",x.length-1>a){let K=x.length-a-1;_+=`${k}"... ${Re(K)} not stringified"`}return S!==""&&(_+=`
28
- ${A}`),m.pop(),`[${_}]`}let T=Object.keys(x),R=T.length;if(R===0)return"{}";if(o<m.length+1)return'"[Object]"';let $="",P="";S!==""&&(b+=S,k=`,
29
- ${b}`,$=" ");let N=Math.min(R,a);s&&!_n(x)&&(T=Sn(T,i)),m.push(x);for(let F=0;F<N;F++){let B=T[F],W=l(B,x,m,y,S,b);W!==void 0&&(_+=`${P}${_e(B)}:${$}${W}`,P=k)}if(R>a){let F=R-a;_+=`${P}"...":${$}"${Re(F)} not stringified"`,P=k}return S!==""&&P.length>1&&(_=`
30
- ${b}${_}
31
- ${A}`),m.pop(),`{${_}}`}case"number":return isFinite(x)?String(x):e?e(x):"null";case"boolean":return x===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(x);default:return e?e(x):void 0}}function u(p,c,m,y,S,b){switch(typeof c=="object"&&c!==null&&typeof c.toJSON=="function"&&(c=c.toJSON(p)),typeof c){case"string":return _e(c);case"object":{if(c===null)return"null";if(m.indexOf(c)!==-1)return r;let x=b,_="",k=",";if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),S!==""&&(b+=S,_+=`
32
- ${b}`,k=`,
33
- ${b}`);let R=Math.min(c.length,a),$=0;for(;$<R-1;$++){let N=u(String($),c[$],m,y,S,b);_+=N!==void 0?N:"null",_+=k}let P=u(String($),c[$],m,y,S,b);if(_+=P!==void 0?P:"null",c.length-1>a){let N=c.length-a-1;_+=`${k}"... ${Re(N)} not stringified"`}return S!==""&&(_+=`
34
- ${x}`),m.pop(),`[${_}]`}m.push(c);let A="";S!==""&&(b+=S,k=`,
35
- ${b}`,A=" ");let T="";for(let R of y){let $=u(R,c[R],m,y,S,b);$!==void 0&&(_+=`${T}${_e(R)}:${A}${$}`,T=k)}return S!==""&&T.length>1&&(_=`
36
- ${b}${_}
37
- ${x}`),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 d(p,c,m,y,S){switch(typeof c){case"string":return _e(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(p),typeof c!="object")return d(p,c,m,y,S);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let b=S;if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),S+=y;let $=`
38
- ${S}`,P=`,
39
- ${S}`,N=Math.min(c.length,a),F=0;for(;F<N-1;F++){let W=d(String(F),c[F],m,y,S);$+=W!==void 0?W:"null",$+=P}let B=d(String(F),c[F],m,y,S);if($+=B!==void 0?B:"null",c.length-1>a){let W=c.length-a-1;$+=`${P}"... ${Re(W)} not stringified"`}return $+=`
40
- ${b}`,m.pop(),`[${$}]`}let x=Object.keys(c),_=x.length;if(_===0)return"{}";if(o<m.length+1)return'"[Object]"';S+=y;let k=`,
41
- ${S}`,A="",T="",R=Math.min(_,a);_n(c)&&(A+=io(c,k,a),x=x.slice(c.length),R-=c.length,T=k),s&&(x=Sn(x,i)),m.push(c);for(let $=0;$<R;$++){let P=x[$],N=d(P,c[P],m,y,S);N!==void 0&&(A+=`${T}${_e(P)}: ${N}`,T=k)}if(_>a){let $=_-a;A+=`${T}"...": "${Re($)} not stringified"`,T=k}return T!==""&&(A=`
23
+ `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function fs(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})}ds.Command=Mr});var ys=I(Z=>{var{Argument:hs}=It(),{Command:Dr}=ps(),{CommanderError:Ml,InvalidArgumentError:ms}=ft(),{Help:Dl}=$r(),{Option:gs}=Or();Z.program=new Dr;Z.createCommand=t=>new Dr(t);Z.createOption=(t,e)=>new gs(t,e);Z.createArgument=(t,e)=>new hs(t,e);Z.Command=Dr;Z.Option=gs;Z.Argument=hs;Z.Help=Dl;Z.CommanderError=Ml;Z.InvalidArgumentError=ms;Z.InvalidOptionArgumentError=ms});var Lr=I(($m,ks)=>{"use strict";var pt=t=>t&&typeof t.message=="string",Fr=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return pt(r)?r:void 0}else return pt(e)?e:void 0},xs=(t,e)=>{if(!pt(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
+ causes have become circular...`;let n=Fr(t);return n?(e.add(t),r+`
25
+ caused by: `+xs(n,e)):r},jl=t=>xs(t,new Set),vs=(t,e,r)=>{if(!pt(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=Fr(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+vs(s,e,i)}else return n},Fl=t=>vs(t,new Set);ks.exports={isErrorLike:pt,getErrorCause:Fr,stackWithCauses:jl,messageWithCauses:Fl}});var Nr=I((Tm,$s)=>{"use strict";var Ll=Symbol("circular-ref-tag"),Pt=Symbol("pino-raw-err-ref"),Cs=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(Cs,Pt,{writable:!0,value:{}});$s.exports={pinoErrProto:Cs,pinoErrorSymbols:{seen:Ll,rawSymbol:Pt}}});var Es=I((Am,As)=>{"use strict";As.exports=Ur;var{messageWithCauses:Nl,stackWithCauses:ql,isErrorLike:Ts}=Lr(),{pinoErrProto:Ul,pinoErrorSymbols:Bl}=Nr(),{seen:qr}=Bl,{toString:Hl}=Object.prototype;function Ur(t){if(!Ts(t))return t;t[qr]=void 0;let e=Object.create(Ul);e.type=Hl.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=Nl(t),e.stack=ql(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Ur(r)));for(let r in t)if(e[r]===void 0){let n=t[r];Ts(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,qr)&&(e[r]=Ur(n)):e[r]=n}return delete t[qr],e.raw=t,e}});var Rs=I((Em,Os)=>{"use strict";Os.exports=Dt;var{isErrorLike:Br}=Lr(),{pinoErrProto:Wl,pinoErrorSymbols:Vl}=Nr(),{seen:Mt}=Vl,{toString:zl}=Object.prototype;function Dt(t){if(!Br(t))return t;t[Mt]=void 0;let e=Object.create(Wl);e.type=zl.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=>Dt(r))),Br(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,Mt)&&(e.cause=Dt(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];Br(n)?Object.prototype.hasOwnProperty.call(n,Mt)||(e[r]=Dt(n)):e[r]=n}return delete t[Mt],e.raw=t,e}});var Ds=I((Om,Ms)=>{"use strict";Ms.exports={mapHttpRequest:Kl,reqSerializer:Ps};var Hr=Symbol("pino-raw-req-ref"),Is=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[Hr]},set:function(t){this[Hr]=t}}});Object.defineProperty(Is,Hr,{writable:!0,value:{}});function Ps(t){let e=t.info||t.socket,r=Object.create(Is);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 Kl(t){return{req:Ps(t)}}});var Ns=I((Rm,Ls)=>{"use strict";Ls.exports={mapHttpResponse:Gl,resSerializer:Fs};var Wr=Symbol("pino-raw-res-ref"),js=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Wr]},set:function(t){this[Wr]=t}}});Object.defineProperty(js,Wr,{writable:!0,value:{}});function Fs(t){let e=Object.create(js);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function Gl(t){return{res:Fs(t)}}});var zr=I((Im,qs)=>{"use strict";var Vr=Es(),Jl=Rs(),jt=Ds(),Ft=Ns();qs.exports={err:Vr,errWithCause:Jl,mapHttpRequest:jt.mapHttpRequest,mapHttpResponse:Ft.mapHttpResponse,req:jt.reqSerializer,res:Ft.resSerializer,wrapErrorSerializer:function(e){return e===Vr?e:function(n){return e(Vr(n))}},wrapRequestSerializer:function(e){return e===jt.reqSerializer?e:function(n){return e(jt.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Ft.resSerializer?e:function(n){return e(Ft.resSerializer(n))}}}});var Kr=I((Pm,Us)=>{"use strict";function Xl(t,e){return e}Us.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=Xl;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 Ks=I((Mm,zs)=>{"use strict";function Gr(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]=Gr(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]=Gr(t[r]));return e}return t}function Bs(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 Hs(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 Ws(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 Lt=Symbol("PATH_NOT_FOUND");function Yl(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return Lt;r=r[n]}return r}function Zl(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 Ql(t,e,r,n=!1){for(let s of e){let i=Bs(s);if(i.includes("*"))Vs(t,i,r,s,n);else if(n)Ws(t,i);else{let o=Yl(t,i);if(o===Lt)continue;let a=typeof r=="function"?r(o,i):r;Hs(t,i,a)}}}function Vs(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 ec(t,e,r,i,n,s)}function ec(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 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("*"))Vs(d,a,typeof r=="function"?(p,c)=>{let m=[...l.slice(0,f),...c];return r(p,m)}:r,s,i);else if(i)Ws(d,a);else{let h=typeof r=="function"?r(Zl(d,a),[...l.slice(0,f),...a]):r;Hs(d,a,h)}}if(o.length===0)u(t,0);else{let d=t;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 tc(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=Bs(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 rc(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 nc(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 sc(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)nc(e)}function ic(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;sc(e);let o=tc(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let u=rc(l,o),d=l,f=r;return typeof r=="function"&&(f=r),Ql(u,e,f,i),n===!1?(u.restore=function(){return Gr(d)},u):typeof n=="function"?n(u):JSON.stringify(u)}}zs.exports=ic});var ze=I((Dm,Gs)=>{"use strict";var oc=Symbol("pino.setLevel"),ac=Symbol("pino.getLevel"),lc=Symbol("pino.levelVal"),cc=Symbol("pino.levelComp"),uc=Symbol("pino.useLevelLabels"),fc=Symbol("pino.useOnlyCustomLevels"),dc=Symbol("pino.mixin"),pc=Symbol("pino.lsCache"),hc=Symbol("pino.chindings"),mc=Symbol("pino.asJson"),gc=Symbol("pino.write"),yc=Symbol("pino.redactFmt"),wc=Symbol("pino.time"),bc=Symbol("pino.timeSliceIndex"),Sc=Symbol("pino.stream"),_c=Symbol("pino.stringify"),xc=Symbol("pino.stringifySafe"),vc=Symbol("pino.stringifiers"),kc=Symbol("pino.end"),Cc=Symbol("pino.formatOpts"),$c=Symbol("pino.messageKey"),Tc=Symbol("pino.errorKey"),Ac=Symbol("pino.nestedKey"),Ec=Symbol("pino.nestedKeyStr"),Oc=Symbol("pino.mixinMergeStrategy"),Rc=Symbol("pino.msgPrefix"),Ic=Symbol("pino.wildcardFirst"),Pc=Symbol.for("pino.serializers"),Mc=Symbol.for("pino.formatters"),Dc=Symbol.for("pino.hooks"),jc=Symbol.for("pino.metadata");Gs.exports={setLevelSym:oc,getLevelSym:ac,levelValSym:lc,levelCompSym:cc,useLevelLabelsSym:uc,mixinSym:dc,lsCacheSym:pc,chindingsSym:hc,asJsonSym:mc,writeSym:gc,serializersSym:Pc,redactFmtSym:yc,timeSym:wc,timeSliceIndexSym:bc,streamSym:Sc,stringifySym:_c,stringifySafeSym:xc,stringifiersSym:vc,endSym:kc,formatOptsSym:Cc,messageKeySym:$c,errorKeySym:Tc,nestedKeySym:Ac,wildcardFirstSym:Ic,needsMetadataGsym:jc,useOnlyCustomLevelsSym:fc,formattersSym:Mc,hooksSym:Dc,nestedKeyStrSym:Ec,mixinMergeStrategySym:Oc,msgPrefixSym:Rc}});var Xr=I((jm,Zs)=>{"use strict";var Js=Ks(),{redactFmtSym:Fc,wildcardFirstSym:Nt}=ze(),Jr=/[^.[\]]+|\[([^[\]]*?)\]/g,Xs="[Redacted]",Ys=!1;function Lc(t,e){let{paths:r,censor:n,remove:s}=Nc(t),i=r.reduce((l,u)=>{Jr.lastIndex=0;let d=Jr.exec(u),f=Jr.exec(u),h=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(h==="*"&&(h=Nt),f===null)return l[h]=null,l;if(l[h]===null)return l;let{index:p}=f,c=`${u.substr(p,u.length-1)}`;return l[h]=l[h]||[],h!==Nt&&l[h].length===0&&l[h].push(...l[Nt]||[]),h===Nt&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(c)}),l[h].push(c),l},{}),o={[Fc]:Js({paths:r,censor:n,serialize:e,strict:Ys,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,h)=>n(f,[u,...h]):n;l[u]=Js({paths:i[u],censor:d,serialize:e,strict:Ys,remove:s})}return l},o)}function Nc(t){if(Array.isArray(t))return t={paths:t,censor:Xs},t;let{paths:e,censor:r=Xs,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}}Zs.exports=Lc});var ti=I((Fm,ei)=>{"use strict";var qc=()=>"",Uc=()=>`,"time":${Date.now()}`,Bc=()=>`,"time":${Math.round(Date.now()/1e3)}`,Hc=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,Wc=1000000n,Qs=1000000000n,Vc=BigInt(Date.now())*Wc,zc=process.hrtime.bigint(),Kc=()=>{let t=process.hrtime.bigint()-zc,e=Vc+t,r=e/Qs,n=e%Qs,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"`};ei.exports={nullTime:qc,epochTime:Uc,unixTime:Bc,isoTime:Hc,isoTimeNano:Kc}});var ni=I((Lm,ri)=>{"use strict";function Gc(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}ri.exports=Jc;function Jc(t,e,r){var n=r&&r.stringify||Gc,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,h=t&&t.length||0,p=0;p<h;){if(t.charCodeAt(p)===37&&p+1<h){switch(f=f>-1?f:0,t.charCodeAt(p+1)){case 100:case 102:if(d>=l||e[d]==null)break;f<p&&(u+=t.slice(f,p)),u+=Number(e[d]),f=p+2,p++;break;case 105:if(d>=l||e[d]==null)break;f<p&&(u+=t.slice(f,p)),u+=Math.floor(Number(e[d])),f=p+2,p++;break;case 79:case 111:case 106:if(d>=l||e[d]===void 0)break;f<p&&(u+=t.slice(f,p));var c=typeof e[d];if(c==="string"){u+="'"+e[d]+"'",f=p+2,p++;break}if(c==="function"){u+=e[d].name||"<anonymous>",f=p+2,p++;break}u+=n(e[d]),f=p+2,p++;break;case 115:if(d>=l)break;f<p&&(u+=t.slice(f,p)),u+=String(e[d]),f=p+2,p++;break;case 37:f<p&&(u+=t.slice(f,p)),u+="%",f=p+2,p++,d--;break}++d}++p}return f===-1?t:(f<h&&(u+=t.slice(f)),u)}});var Zr=I((Nm,Yr)=>{"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));Yr.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(););};Yr.exports=t}});var fi=I((qm,ui)=>{"use strict";var L=require("fs"),Xc=require("events"),Yc=require("util").inherits,si=require("path"),en=Zr(),Zc=require("assert"),qt=100,Ut=Buffer.allocUnsafe(0),Qc=16*1024,ii="buffer",oi="utf8",[eu,tu]=(process.versions.node||"0.0").split(".").map(Number),ru=eu>=22&&tu>=7;function ai(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&&L.mkdirSync(si.dirname(t),{recursive:!0});let i=L.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?L.mkdir(si.dirname(t),{recursive:!0},i=>{if(i)return r(i);L.open(t,n,s,r)}):L.open(t,n,s,r)}function oe(t){if(!(this instanceof oe))return new oe(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:h,mode:p}=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||Qc,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=p,this.retryEAGAIN=d||(()=>!0),this.mkdir=u||!1;let c,m;if(h===ii)this._writingBuf=Ut,this.write=iu,this.flush=au,this.flushSync=cu,this._actualWrite=fu,c=()=>L.writeSync(this.fd,this._writingBuf),m=()=>L.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===oi)this._writingBuf="",this.write=su,this.flush=ou,this.flushSync=lu,this._actualWrite=uu,c=()=>Buffer.isBuffer(this._writingBuf)?L.writeSync(this.fd,this._writingBuf):L.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?L.write(this.fd,this._writingBuf,this.release):L.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${oi}" and "${ii}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")ai(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,S)=>{if(y){if((y.code==="EAGAIN"||y.code==="EBUSY")&&this.retryEAGAIN(y,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{en(qt),this.release(void 0,0)}catch(x){this.release(x)}else setTimeout(m,qt);else this._writing=!1,this.emit("error",y);return}this.emit("write",S);let b=Qr(this._writingBuf,this._len,S);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let x=c(),C=Qr(this._writingBuf,this._len,x);this._len=C.len,this._writingBuf=C.writingBuf}while(this._writingBuf.length)}catch(x){this.release(x);return}}this._fsync&&L.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,Bt(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(nu,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 Qr(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 nu(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Yc(oe,Xc);function li(t,e){return t.length===0?Ut:t.length===1?t[0]:Buffer.concat(t,e)}function su(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 iu(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 ci(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{L.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 ou(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&&ci.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function au(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&&ci.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}oe.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&&L.close(e,r=>{if(r)return this.emit("error",r)})}),ai(this.file,this)};oe.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():Bt(this)))};function lu(){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)?L.writeSync(this.fd,t):L.writeSync(this.fd,t,"utf8"),r=Qr(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;en(qt)}}try{L.fsyncSync(this.fd)}catch{}}function cu(){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=Ut);let t=Ut;for(;this._bufs.length||t.length;){t.length<=0&&(t=li(this._bufs[0],this._lens[0]));try{let e=L.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;en(qt)}}}oe.prototype.destroy=function(){this.destroyed||Bt(this)};function uu(){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)?L.writeSync(this.fd,this._writingBuf):L.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else L.write(this.fd,this._writingBuf,t)}function fu(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:li(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=L.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else ru&&(this._writingBuf=Buffer.from(this._writingBuf)),L.write(this.fd,this._writingBuf,t)}function Bt(t){if(t.fd===-1){t.once("ready",Bt.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Zc(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{L.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?L.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")}}oe.SonicBoom=oe;oe.default=oe;ui.exports=oe});var tn=I((Um,gi)=>{"use strict";var ae={exit:[],beforeExit:[]},di={exit:hu,beforeExit:mu},Ke;function du(){Ke===void 0&&(Ke=new FinalizationRegistry(gu))}function pu(t){ae[t].length>0||process.on(t,di[t])}function pi(t){ae[t].length>0||(process.removeListener(t,di[t]),ae.exit.length===0&&ae.beforeExit.length===0&&(Ke=void 0))}function hu(){hi("exit")}function mu(){hi("beforeExit")}function hi(t){for(let e of ae[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}ae[t]=[]}function gu(t){for(let e of["exit","beforeExit"]){let r=ae[e].indexOf(t);ae[e].splice(r,r+1),pi(e)}}function mi(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");pu(t);let n=new WeakRef(e);n.fn=r,du(),Ke.register(e,n),ae[t].push(n)}function yu(t,e){mi("exit",t,e)}function wu(t,e){mi("beforeExit",t,e)}function bu(t){if(Ke!==void 0){Ke.unregister(t);for(let e of["exit","beforeExit"])ae[e]=ae[e].filter(r=>{let n=r.deref();return n&&n!==t}),pi(e)}}gi.exports={register:yu,registerBeforeExit:wu,unregister:bu}});var yi=I((Bm,Su)=>{Su.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 bi=I((Hm,wi)=>{"use strict";function _u(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 xu(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()}wi.exports={wait:_u,waitDiff:xu}});var _i=I((Wm,Si)=>{"use strict";Si.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Pi=I((Vm,Ii)=>{"use strict";var{version:vu}=yi(),{EventEmitter:ku}=require("events"),{Worker:Cu}=require("worker_threads"),{join:$u}=require("path"),{pathToFileURL:Tu}=require("url"),{wait:Au}=bi(),{WRITE_INDEX:he,READ_INDEX:Oe,SEQ_INDEX:rn}=_i(),Eu=require("buffer"),Ou=require("assert"),g=Symbol("kImpl"),Ru=Eu.constants.MAX_STRING_LENGTH;function xi(){}function an(t,e){Atomics.add(t[g].state,rn,1),e(),Atomics.add(t[g].state,rn,1),Atomics.notify(t[g].state,rn)}function vi(t){an(t,()=>{Atomics.store(t[g].state,Oe,0),Atomics.store(t[g].state,he,0)})}var ht=class{constructor(e){this._value=e}deref(){return this._value}},Ht=class{register(){}unregister(){}},Iu=process.env.NODE_V8_COVERAGE?Ht:global.FinalizationRegistry||Ht,Pu=process.env.NODE_V8_COVERAGE?ht:global.WeakRef||ht,ki=new Iu(t=>{t.exited||t.terminate()});function Mu(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||$u(__dirname,"lib","worker.js"),o=new Cu(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Tu(r).href,dataBuf:t[g].dataBuf,stateBuf:t[g].stateBuf,workerData:{$context:{threadStreamVersion:vu},...n}}});return o.stream=new ht(t),o.on("message",Du),o.on("exit",Ti),ki.register(t,o),o}function Ci(t){Ou(!t[g].sync),t[g].needDrain&&(t[g].needDrain=!1,t.emit("drain"))}function $i(t){for(;;){let e=Atomics.load(t[g].state,he),r=t[g].data.length-e;if(r>0){if(t[g].bufLen===0){t[g].flushing=!1,t[g].ending?ln(t):t[g].needDrain&&process.nextTick(Ci,t);return}Oi(t,r,xi);continue}if(r===0){if(e===0&&t[g].bufLen===0)return;Wt(t,()=>{t.destroyed||(vi(t),$i(t))});return}Q(t,new Error("overwritten"));return}}function Du(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 Pu(e),Wt(e,()=>{e[g].ready=!0,e.emit("ready")});break;case"ERROR":Q(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"){Q(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:Q(e,new Error("this should not happen: "+t.code))}}function Ti(t){let e=this.stream.deref();e!==void 0&&(ki.unregister(e),e.worker.exited=!0,e.worker.off("exit",Ti),Q(e,t!==0?new Error("the worker thread exited"):null))}var sn=class extends ku{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=Mu(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 on(this,new Error("the worker has exited")),!1;if(this[g].ending)return on(this,new Error("the worker is ending")),!1;if(this[g].flushing&&this[g].bufLen+r.length>=Ru)try{nn(this),this[g].flushing=!0}catch(n){return Q(this,n),!1}if(this[g].buf.push(r),this[g].bufLen+=r.length,this[g].sync)try{return nn(this),!0}catch(n){return Q(this,n),!1}return this[g].flushing||(this[g].flushing=!0,setImmediate($i,this)),this[g].needDrain=this[g].data.length-this[g].bufLen-Atomics.load(this[g].state,he)<=0,!this[g].needDrain}end(){this[g].destroyed||(this[g].ending=!0,ln(this))}flush(e){e=typeof e=="function"?e:xi,Ai(this,r=>{if(r){process.nextTick(e,r);return}Ei(this,e)})}flushSync(){this[g].destroyed||(nn(this),Ri(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 Ai(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(Ai,t,e);return}Wt(t,e)}function Wt(t,e){let r=Atomics.load(t[g].state,he);Au(t[g].state,Oe,r,1/0,(n,s)=>{if(n){Q(t,n),e(n);return}if(s!=="ok"){Wt(t,e);return}e()})}function Ei(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].ready){let n=()=>{i(),Ei(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),Q(t,n),process.nextTick(e,n)}}function ju(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 on(t,e){setImmediate(()=>{t.emit("error",e)})}function Q(t,e){t[g].destroyed||(t[g].destroyed=!0,ju(t,e),e&&(t[g].errored=e,on(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,he),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 an(t,()=>{Atomics.store(t[g].state,he,s)}),r(),!0}function ln(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,Oe);an(t,()=>{Atomics.store(t[g].state,he,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[g].state,Oe,e,1e3),e=Atomics.load(t[g].state,Oe),e===-2){Q(t,new Error("end() failed"));return}if(++r===10){Q(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[g].finished=!0,t.emit("finish")})}catch(e){Q(t,e)}}}function nn(t){let e=()=>{t[g].ending?ln(t):t[g].needDrain&&process.nextTick(Ci,t)};for(t[g].flushing=!1;t[g].bufLen!==0;){let r=Atomics.load(t[g].state,he),n=t[g].data.length-r;if(n===0){Ri(t),vi(t);continue}else if(n<0)throw new Error("overwritten");Oi(t,n,e)}}function Ri(t){if(t[g].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[g].state,he),r=0;for(;;){let n=Atomics.load(t[g].state,Oe);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[g].state,Oe,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}Ii.exports=sn});var fn=I((zm,ji)=>{"use strict";var{createRequire:Fu}=require("module"),{existsSync:Lu}=require("node:fs"),Nu=Kr(),{join:cn,isAbsolute:Di,sep:qu}=require("node:path"),{fileURLToPath:Uu}=require("node:url"),Bu=Zr(),un=tn(),Hu=Pi();function Wu(t){un.register(t,Ju),un.registerBeforeExit(t,Xu),t.on("close",function(){un.unregister(t)})}function Vu(){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 zu(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&&Mi(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(Mi(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function Mi(t){let e=Ku(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=Uu(r)}catch{return!1}return Di(r)&&!Lu(r)}function Ku(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function Gu(t,e,r,n,s){if(!r.execArgv&&Vu()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=zu(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new Hu({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&&Wu(i)}function a(){i.closed||(i.flushSync(),Bu(100),i.end())}return i}function Ju(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Xu(t){t.flushSync()}function Yu(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=Nu(),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"]||cn(__dirname,"worker.js"),l.targets=r.filter(c=>c.target).map(c=>({...c,target:p(c.target)})),l.pipelines=r.filter(c=>c.pipeline).map(c=>c.pipeline.map(m=>({...m,level:c.level,target:p(m.target)})))):e&&(f=d["pino-worker"]||cn(__dirname,"worker.js"),l.pipelines=[e.map(c=>({...c,target:p(c.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let h=r||e?"pino.transport":f;return Gu(p(f),l,i,a,h);function p(c){if(c=d[c]||c,Di(c)||c.indexOf("file://")===0)return c;if(c==="pino/file")return cn(__dirname,"..","file.js");let m;for(let y of u)try{let S=y==="node:repl"?process.cwd()+qu:y;m=Fu(S).resolve(c);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${c}"`);return m}}ji.exports=Yu});var Kt=I((Km,Ji)=>{"use strict";var Zu=require("node:diagnostics_channel"),Fi=ni(),{mapHttpRequest:Qu,mapHttpResponse:ef}=zr(),pn=fi(),Li=tn(),{lsCacheSym:tf,chindingsSym:Hi,writeSym:Ni,serializersSym:Wi,formatOptsSym:qi,endSym:rf,stringifiersSym:Vi,stringifySym:zi,stringifySafeSym:hn,wildcardFirstSym:Ki,nestedKeySym:nf,formattersSym:Gi,messageKeySym:sf,errorKeySym:of,nestedKeyStrSym:af,msgPrefixSym:Vt}=ze(),{isMainThread:lf}=require("worker_threads"),cf=fn(),[uf]=process.versions.node.split(".").map(t=>Number(t)),Ui=Zu.tracingChannel("pino_asJson"),dn=uf>=25?t=>JSON.stringify(t):df;function Ge(){}function ff(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=Qu(n):typeof n.setHeader=="function"&&(n=ef(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Vt]=="string"&&i!==void 0&&i!==null&&(i=this[Vt]+i),this[Ni](n,Fi(i,o,this[qi]),t)}else{let i=n===void 0?s.shift():n;typeof this[Vt]=="string"&&i!==void 0&&i!==null&&(i=this[Vt]+i),this[Ni](null,Fi(i,s,this[qi]),t)}}}function df(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 pf(t,e,r,n){if(Ui.hasSubscribers===!1)return Bi.call(this,t,e,r,n);let s={instance:this,arguments};return Ui.traceSync(Bi,s,this,t,e,r,n)}function Bi(t,e,r,n){let s=this[zi],i=this[hn],o=this[Vi],a=this[rf],l=this[Hi],u=this[Wi],d=this[Gi],f=this[sf],h=this[of],p=this[tf][r]+n;p=p+l;let c;d.log&&(t=d.log(t));let m=o[Ki],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===h&&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=(_||dn)(c);break;default:c=(_||s)(c,i)}if(c===void 0)continue;let x=dn(b);y+=","+x+":"+c}let S="";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)),S=',"'+f+'":'+c;break;case"string":c=(b||dn)(c),S=',"'+f+'":'+c;break;default:c=(b||s)(c,i),S=',"'+f+'":'+c}}return this[nf]&&y?p+this[af]+y.slice(1)+"}"+S+a:p+y+S+a}function hf(t,e){let r,n=t[Hi],s=t[zi],i=t[hn],o=t[Vi],a=o[Ki],l=t[Wi],u=t[Gi].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 mf(t){return t.write!==t.constructor.prototype.write}function zt(t){let e=new pn(t);return e.on("error",r),!t.sync&&lf&&(Li.register(e,gf),e.on("close",function(){Li.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Ge,e.end=Ge,e.flushSync=Ge,e.destroy=Ge;return}e.removeListener("error",r),e.emit("error",n)}}function gf(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function yf(t){return function(r,n,s={},i){if(typeof s=="string")i=zt({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=zt({dest:i})}else if(s instanceof pn||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof pn||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=cf({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=Ge),i||(mf(process.stdout)?i=process.stdout:i=zt({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function wf(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[hn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function bf(t,e,r){return{level:t,bindings:e,log:r}}function Sf(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Ji.exports={noop:Ge,buildSafeSonicBoom:zt,asChindings:hf,asJson:pf,genLog:ff,createArgsNormalizer:yf,stringify:wf,buildFormatters:bf,normalizeDestFileDescriptor:Sf}});var Gt=I((Gm,Xi)=>{var _f={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},xf={ASC:"ASC",DESC:"DESC"};Xi.exports={DEFAULT_LEVELS:_f,SORTING_ORDER:xf}});var yn=I((Jm,eo)=>{"use strict";var{lsCacheSym:vf,levelValSym:mn,useOnlyCustomLevelsSym:kf,streamSym:Cf,formattersSym:$f,hooksSym:Tf,levelCompSym:Yi}=ze(),{noop:Af,genLog:Re}=Kt(),{DEFAULT_LEVELS:fe,SORTING_ORDER:Zi}=Gt(),Qi={fatal:t=>{let e=Re(fe.fatal,t);return function(...r){let n=this[Cf];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>Re(fe.error,t),warn:t=>Re(fe.warn,t),info:t=>Re(fe.info,t),debug:t=>Re(fe.debug,t),trace:t=>Re(fe.trace,t)},gn=Object.keys(fe).reduce((t,e)=>(t[fe[e]]=e,t),{}),Ef=Object.keys(gn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Of(t){let e=t[$f].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[vf]=n,t}function Rf(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 If(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[mn],s=this[mn]=r[t],i=this[kf],o=this[Yi],a=this[Tf].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=Af;continue}this[l]=Rf(l,i)?Qi[l](a):Re(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function Pf(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Mf(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Yi](r,this[mn])}function Df(t,e,r){return t===Zi.DESC?e<=r:e>=r}function jf(t){return typeof t=="string"?Df.bind(null,t):t}function Ff(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:gn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:fe,t);return{labels:n,values:s}}function Lf(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(gn).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:fe,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function Nf(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 qf(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Zi).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}eo.exports={initialLsCache:Ef,genLsCache:Of,levelMethods:Qi,getLevel:Pf,setLevel:If,isLevelEnabled:Mf,mappings:Ff,assertNoLevelCollisions:Nf,assertDefaultLevelFound:Lf,genLevelComparison:jf,assertLevelComparison:qf}});var wn=I((Xm,to)=>{"use strict";to.exports={version:"10.3.1"}});var co=I((Zm,lo)=>{"use strict";var{EventEmitter:Uf}=require("node:events"),{lsCacheSym:Bf,levelValSym:Hf,setLevelSym:Sn,getLevelSym:ro,chindingsSym:Xt,mixinSym:Wf,asJsonSym:so,writeSym:Vf,mixinMergeStrategySym:zf,timeSym:Kf,timeSliceIndexSym:Gf,streamSym:io,serializersSym:Ie,formattersSym:mt,errorKeySym:Jf,messageKeySym:Xf,useOnlyCustomLevelsSym:Yf,needsMetadataGsym:Zf,redactFmtSym:Qf,stringifySym:ed,formatOptsSym:td,stringifiersSym:rd,msgPrefixSym:_n,hooksSym:nd}=ze(),{getLevel:sd,setLevel:id,isLevelEnabled:od,mappings:ad,initialLsCache:ld,genLsCache:cd,assertNoLevelCollisions:ud}=yn(),{asChindings:xn,asJson:fd,buildFormatters:bn,stringify:no,noop:oo}=Kt(),{version:dd}=wn(),pd=Xr(),hd=class{},ao={constructor:hd,child:md,bindings:gd,setBindings:yd,flush:Sd,isLevelEnabled:od,version:dd,get level(){return this[ro]()},set level(t){this[Sn](t)},get levelVal(){return this[Hf]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[_n]},get[Symbol.toStringTag](){return"Pino"},[Bf]:ld,[Vf]:bd,[so]:fd,[ro]:sd,[Sn]:id};Object.setPrototypeOf(ao,Uf.prototype);lo.exports=function(){return Object.create(ao)};var Jt=t=>t;function md(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[Ie],n=this[mt],s=Object.create(this);if(e==null)return s[mt].bindings!==Jt&&(s[mt]=bn(n.level,Jt,n.log)),s[Xt]=xn(s,t),this.onChild!==oo&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[Ie]=Object.create(null);for(let u in r)s[Ie][u]=r[u];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let u=a[i];s[Ie][u]=r[u]}for(let u in e.serializers)s[Ie][u]=e.serializers[u];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let u=l[o];s[Ie][u]=e.serializers[u]}}else s[Ie]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:u}=e.formatters;s[mt]=bn(a||n.level,l||Jt,u||n.log)}else s[mt]=bn(n.level,Jt,n.log);if(e.hasOwnProperty("customLevels")===!0&&(ud(this.levels,e.customLevels),s.levels=ad(e.customLevels,s[Yf]),cd(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=pd(s.redact,no),l={stringify:a[Qf]};s[ed]=no,s[rd]=a,s[td]=l}if(typeof e.msgPrefix=="string"&&(s[_n]=(this[_n]||"")+e.msgPrefix),s[Xt]=xn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[Sn](a)}return this.onChild(s),s}function gd(){let e=`{${this[Xt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function yd(t){let e=xn(this,t);this[Xt]=e}function wd(t,e){return Object.assign(e,t)}function bd(t,e,r){let n=this[Kf](),s=this[Wf],i=this[Jf],o=this[Xf],a=this[zf]||wd,l,u=this[nd].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[so](l,e,r,n),f=this[io];f[Zf]===!0&&(f.lastLevel=r,f.lastObj=l,f.lastMsg=e,f.lastTime=n.slice(this[Gf]),f.lastLogger=this),f.write(u?u(d):d)}function Sd(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[io];typeof e.flush=="function"?e.flush(t||oo):t&&t()}});var ho=I(($n,po)=>{"use strict";var{hasOwnProperty:gt}=Object.prototype,Me=Cn();Me.configure=Cn;Me.stringify=Me;Me.default=Me;$n.stringify=Me;$n.configure=Cn;po.exports=Me;var _d=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function xe(t){return t.length<5e3&&!_d.test(t)?`"${t}"`:JSON.stringify(t)}function vn(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 xd=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function kn(t){return xd.call(t)!==void 0&&t.length!==0}function uo(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 vd(t){if(gt.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 kd(t){let e;if(gt.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 Cd(t,e){let r;if(gt.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 fo(t,e){let r;if(gt.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 Pe(t){return t===1?"1 item":`${t} items`}function $d(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function Td(t){if(gt.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 Cn(t){t={...t};let e=Td(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=vd(t),n=Cd(t,"bigint"),s=kd(t),i=typeof s=="function"?s:void 0,o=fo(t,"maximumDepth"),a=fo(t,"maximumBreadth");function l(p,c,m,y,S,b){let _=c[p];switch(typeof _=="object"&&_!==null&&typeof _.toJSON=="function"&&(_=_.toJSON(p)),_=y.call(c,p,_),typeof _){case"string":return xe(_);case"object":{if(_===null)return"null";if(m.indexOf(_)!==-1)return r;let x="",C=",",A=b;if(Array.isArray(_)){if(_.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(_),S!==""&&(b+=S,x+=`
26
+ ${b}`,C=`,
27
+ ${b}`);let F=Math.min(_.length,a),B=0;for(;B<F-1;B++){let G=l(String(B),_,m,y,S,b);x+=G!==void 0?G:"null",x+=C}let W=l(String(B),_,m,y,S,b);if(x+=W!==void 0?W:"null",_.length-1>a){let G=_.length-a-1;x+=`${C}"... ${Pe(G)} not stringified"`}return S!==""&&(x+=`
28
+ ${A}`),m.pop(),`[${x}]`}let T=Object.keys(_),R=T.length;if(R===0)return"{}";if(o<m.length+1)return'"[Object]"';let $="",D="";S!==""&&(b+=S,C=`,
29
+ ${b}`,$=" ");let q=Math.min(R,a);s&&!kn(_)&&(T=vn(T,i)),m.push(_);for(let F=0;F<q;F++){let B=T[F],W=l(B,_,m,y,S,b);W!==void 0&&(x+=`${D}${xe(B)}:${$}${W}`,D=C)}if(R>a){let F=R-a;x+=`${D}"...":${$}"${Pe(F)} not stringified"`,D=C}return S!==""&&D.length>1&&(x=`
30
+ ${b}${x}
31
+ ${A}`),m.pop(),`{${x}}`}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(p,c,m,y,S,b){switch(typeof c=="object"&&c!==null&&typeof c.toJSON=="function"&&(c=c.toJSON(p)),typeof c){case"string":return xe(c);case"object":{if(c===null)return"null";if(m.indexOf(c)!==-1)return r;let _=b,x="",C=",";if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),S!==""&&(b+=S,x+=`
32
+ ${b}`,C=`,
33
+ ${b}`);let R=Math.min(c.length,a),$=0;for(;$<R-1;$++){let q=u(String($),c[$],m,y,S,b);x+=q!==void 0?q:"null",x+=C}let D=u(String($),c[$],m,y,S,b);if(x+=D!==void 0?D:"null",c.length-1>a){let q=c.length-a-1;x+=`${C}"... ${Pe(q)} not stringified"`}return S!==""&&(x+=`
34
+ ${_}`),m.pop(),`[${x}]`}m.push(c);let A="";S!==""&&(b+=S,C=`,
35
+ ${b}`,A=" ");let T="";for(let R of y){let $=u(R,c[R],m,y,S,b);$!==void 0&&(x+=`${T}${xe(R)}:${A}${$}`,T=C)}return S!==""&&T.length>1&&(x=`
36
+ ${b}${x}
37
+ ${_}`),m.pop(),`{${x}}`}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(p,c,m,y,S){switch(typeof c){case"string":return xe(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(p),typeof c!="object")return d(p,c,m,y,S);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let b=S;if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),S+=y;let $=`
38
+ ${S}`,D=`,
39
+ ${S}`,q=Math.min(c.length,a),F=0;for(;F<q-1;F++){let W=d(String(F),c[F],m,y,S);$+=W!==void 0?W:"null",$+=D}let B=d(String(F),c[F],m,y,S);if($+=B!==void 0?B:"null",c.length-1>a){let W=c.length-a-1;$+=`${D}"... ${Pe(W)} not stringified"`}return $+=`
40
+ ${b}`,m.pop(),`[${$}]`}let _=Object.keys(c),x=_.length;if(x===0)return"{}";if(o<m.length+1)return'"[Object]"';S+=y;let C=`,
41
+ ${S}`,A="",T="",R=Math.min(x,a);kn(c)&&(A+=uo(c,C,a),_=_.slice(c.length),R-=c.length,T=C),s&&(_=vn(_,i)),m.push(c);for(let $=0;$<R;$++){let D=_[$],q=d(D,c[D],m,y,S);q!==void 0&&(A+=`${T}${xe(D)}: ${q}`,T=C)}if(x>a){let $=x-a;A+=`${T}"...": "${Pe($)} not stringified"`,T=C}return T!==""&&(A=`
42
42
  ${S}${A}
43
- ${b}`),m.pop(),`{${A}}`}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(p,c,m){switch(typeof c){case"string":return _e(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(p),typeof c!="object")return f(p,c,m);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let y="",S=c.length!==void 0;if(S&&Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c);let A=Math.min(c.length,a),T=0;for(;T<A-1;T++){let $=f(String(T),c[T],m);y+=$!==void 0?$:"null",y+=","}let R=f(String(T),c[T],m);if(y+=R!==void 0?R:"null",c.length-1>a){let $=c.length-a-1;y+=`,"... ${Re($)} not stringified"`}return m.pop(),`[${y}]`}let b=Object.keys(c),x=b.length;if(x===0)return"{}";if(o<m.length+1)return'"[Object]"';let _="",k=Math.min(x,a);S&&_n(c)&&(y+=io(c,",",a),b=b.slice(c.length),k-=c.length,_=","),s&&(b=Sn(b,i)),m.push(c);for(let A=0;A<k;A++){let T=b[A],R=f(T,c[T],m);R!==void 0&&(y+=`${_}${_e(T)}:${R}`,_=",")}if(x>a){let A=x-a;y+=`${_}"...":"${Re(A)} 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 h(p,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("",{"":p},[],c,y,"");if(Array.isArray(c))return u("",p,[],Sd(c),y,"")}if(y.length!==0)return d("",p,[],y,"")}return f("",p,[])}return h}});var po=I((zm,fo)=>{"use strict";var kn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:uo}=Vt(),xd=uo.info;function vd(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(uo);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,[kn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(f){let h,p=this.lastLevel,{streams:c}=this,m=0,y;for(let S=kd(c.length,e.dedupe);$d(S,c.length,e.dedupe);S=Cd(S,e.dedupe))if(h=c[S],h.level<=p){if(m!==0&&m!==h.level)break;if(y=h.stream,y[kn]){let{lastTime:b,lastMsg:x,lastObj:_,lastLogger:k}=this;y.lastLevel=p,y.lastTime=b,y.lastMsg=x,y.lastObj=_,y.lastLogger=k}y.write(f),e.dedupe&&(m=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 n;let h=typeof f.write=="function"||f.stream,p=f.write?f:f.stream;if(!h)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=xd;let S={stream:p,level:y,levelVal:void 0,id:++n.lastId};return c.unshift(S),c.sort(co),this.minLevel=c[0].level,n}function l(f){let{streams:h}=this,p=h.findIndex(c=>c.id===f);return p>=0&&(h.splice(p,1),h.sort(co),this.minLevel=h.length>0?h[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 h=new Array(this.streams.length);for(let p=0;p<h.length;p++)h[p]={level:f,stream:this.streams[p].stream};return{write:s,add:a,remove:l,minLevel:f,streams:h,clone:d,emit:i,flushSync:o,[kn]:!0}}}function co(t,e){return t.level-e.level}function kd(t,e){return e?t-1:0}function Cd(t,e){return e?t-1:t+1}function $d(t,e,r){return r?t>=0:t<e}fo.exports=vd});var To=I((Km,Q)=>{"use strict";var Td=require("node:os"),_o=Hr(),Ad=Wr(),Ed=Kr(),xo=Xs(),Od=so(),vo=Ve(),{configure:Rd}=lo(),{assertDefaultLevelFound:Id,mappings:ko,genLsCache:Md,genLevelComparison:Pd,assertLevelComparison:Dd}=hn(),{DEFAULT_LEVELS:Co,SORTING_ORDER:Fd}=Vt(),{createArgsNormalizer:Ld,asChindings:jd,buildSafeSonicBoom:ho,buildFormatters:Nd,stringify:Cn,normalizeDestFileDescriptor:mo,noop:qd}=Wt(),{version:Ud}=mn(),{chindingsSym:go,redactFmtSym:Bd,serializersSym:yo,timeSym:Hd,timeSliceIndexSym:Wd,streamSym:Vd,stringifySym:wo,stringifySafeSym:$n,stringifiersSym:bo,setLevelSym:zd,endSym:Kd,formatOptsSym:Gd,messageKeySym:Jd,errorKeySym:Xd,nestedKeySym:Yd,mixinSym:Zd,levelCompSym:Qd,useOnlyCustomLevelsSym:ep,formattersSym:So,hooksSym:tp,nestedKeyStrSym:rp,mixinMergeStrategySym:np,msgPrefixSym:sp}=vo,{epochTime:$o,nullTime:ip}=xo,{pid:op}=process,ap=Td.hostname(),lp=_o.err,cp={level:"info",levelComparison:Fd.ASC,levels:Co,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:op,hostname:ap},serializers:Object.assign(Object.create(null),{err:lp}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:$o,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},up=Ld(cp),fp=Object.assign(Object.create(null),_o);function Tn(...t){let e={},{opts:r,stream:n}=up(e,Ad(),...t);r.level&&typeof r.level=="string"&&Co[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:h,level:p,customLevels:c,levelComparison:m,mixin:y,mixinMergeStrategy:S,useOnlyCustomLevels:b,formatters:x,hooks:_,depthLimit:k,edgeLimit:A,onChild:T,msgPrefix:R}=r,$=Rd({maximumDepth:k,maximumBreadth:A}),P=Nd(x.level,x.bindings,x.log),N=Cn.bind({[$n]:$}),F=s?Ed(s,N):{},B=s?{stringify:F[Bd]}:{stringify:N},W="}"+(i?`\r
43
+ ${b}`),m.pop(),`{${A}}`}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(p,c,m){switch(typeof c){case"string":return xe(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(p),typeof c!="object")return f(p,c,m);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let y="",S=c.length!==void 0;if(S&&Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c);let A=Math.min(c.length,a),T=0;for(;T<A-1;T++){let $=f(String(T),c[T],m);y+=$!==void 0?$:"null",y+=","}let R=f(String(T),c[T],m);if(y+=R!==void 0?R:"null",c.length-1>a){let $=c.length-a-1;y+=`,"... ${Pe($)} not stringified"`}return m.pop(),`[${y}]`}let b=Object.keys(c),_=b.length;if(_===0)return"{}";if(o<m.length+1)return'"[Object]"';let x="",C=Math.min(_,a);S&&kn(c)&&(y+=uo(c,",",a),b=b.slice(c.length),C-=c.length,x=","),s&&(b=vn(b,i)),m.push(c);for(let A=0;A<C;A++){let T=b[A],R=f(T,c[T],m);R!==void 0&&(y+=`${x}${xe(T)}:${R}`,x=",")}if(_>a){let A=_-a;y+=`${x}"...":"${Pe(A)} 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 h(p,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("",{"":p},[],c,y,"");if(Array.isArray(c))return u("",p,[],$d(c),y,"")}if(y.length!==0)return d("",p,[],y,"")}return f("",p,[])}return h}});var wo=I((Qm,yo)=>{"use strict";var Tn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:go}=Gt(),Ad=go.info;function Ed(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(go);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,[Tn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(f){let h,p=this.lastLevel,{streams:c}=this,m=0,y;for(let S=Od(c.length,e.dedupe);Id(S,c.length,e.dedupe);S=Rd(S,e.dedupe))if(h=c[S],h.level<=p){if(m!==0&&m!==h.level)break;if(y=h.stream,y[Tn]){let{lastTime:b,lastMsg:_,lastObj:x,lastLogger:C}=this;y.lastLevel=p,y.lastTime=b,y.lastMsg=_,y.lastObj=x,y.lastLogger=C}y.write(f),e.dedupe&&(m=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 n;let h=typeof f.write=="function"||f.stream,p=f.write?f:f.stream;if(!h)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=Ad;let S={stream:p,level:y,levelVal:void 0,id:++n.lastId};return c.unshift(S),c.sort(mo),this.minLevel=c[0].level,n}function l(f){let{streams:h}=this,p=h.findIndex(c=>c.id===f);return p>=0&&(h.splice(p,1),h.sort(mo),this.minLevel=h.length>0?h[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 h=new Array(this.streams.length);for(let p=0;p<h.length;p++)h[p]={level:f,stream:this.streams[p].stream};return{write:s,add:a,remove:l,minLevel:f,streams:h,clone:d,emit:i,flushSync:o,[Tn]:!0}}}function mo(t,e){return t.level-e.level}function Od(t,e){return e?t-1:0}function Rd(t,e){return e?t-1:t+1}function Id(t,e,r){return r?t>=0:t<e}yo.exports=Ed});var Io=I((eg,ee)=>{"use strict";var Pd=require("node:os"),$o=zr(),Md=Kr(),Dd=Xr(),To=ti(),jd=co(),Ao=ze(),{configure:Fd}=ho(),{assertDefaultLevelFound:Ld,mappings:Eo,genLsCache:Nd,genLevelComparison:qd,assertLevelComparison:Ud}=yn(),{DEFAULT_LEVELS:Oo,SORTING_ORDER:Bd}=Gt(),{createArgsNormalizer:Hd,asChindings:Wd,buildSafeSonicBoom:bo,buildFormatters:Vd,stringify:An,normalizeDestFileDescriptor:So,noop:zd}=Kt(),{version:Kd}=wn(),{chindingsSym:_o,redactFmtSym:Gd,serializersSym:xo,timeSym:Jd,timeSliceIndexSym:Xd,streamSym:Yd,stringifySym:vo,stringifySafeSym:En,stringifiersSym:ko,setLevelSym:Zd,endSym:Qd,formatOptsSym:ep,messageKeySym:tp,errorKeySym:rp,nestedKeySym:np,mixinSym:sp,levelCompSym:ip,useOnlyCustomLevelsSym:op,formattersSym:Co,hooksSym:ap,nestedKeyStrSym:lp,mixinMergeStrategySym:cp,msgPrefixSym:up}=Ao,{epochTime:Ro,nullTime:fp}=To,{pid:dp}=process,pp=Pd.hostname(),hp=$o.err,mp={level:"info",levelComparison:Bd.ASC,levels:Oo,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:dp,hostname:pp},serializers:Object.assign(Object.create(null),{err:hp}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Ro,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},gp=Hd(mp),yp=Object.assign(Object.create(null),$o);function On(...t){let e={},{opts:r,stream:n}=gp(e,Md(),...t);r.level&&typeof r.level=="string"&&Oo[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:h,level:p,customLevels:c,levelComparison:m,mixin:y,mixinMergeStrategy:S,useOnlyCustomLevels:b,formatters:_,hooks:x,depthLimit:C,edgeLimit:A,onChild:T,msgPrefix:R}=r,$=Fd({maximumDepth:C,maximumBreadth:A}),D=Vd(_.level,_.bindings,_.log),q=An.bind({[En]:$}),F=s?Dd(s,q):{},B=s?{stringify:F[Gd]}:{stringify:q},W="}"+(i?`\r
44
44
  `:`
45
- `),K=jd.bind(null,{[go]:"",[yo]:o,[bo]:F,[wo]:Cn,[$n]:$,[So]:P}),X="";f!==null&&(h===void 0?X=K(f):X=K(Object.assign({},f,{name:h})));let D=a instanceof Function?a:a?$o:ip,q=D().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(R&&typeof R!="string")throw Error(`Unknown msgPrefix type "${typeof R}" - expected "string"`);Id(p,c,b);let Tt=ko(c,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:Tt,messageKey:l,errorKey:u}}),Dd(m);let Qn=Pd(m);return Object.assign(e,{levels:Tt,[Qd]:Qn,[ep]:b,[Vd]:n,[Hd]:D,[Wd]:q,[wo]:Cn,[$n]:$,[bo]:F,[Kd]:W,[Gd]:B,[Jd]:l,[Xd]:u,[Yd]:d,[rp]:d?`,${JSON.stringify(d)}:{`:"",[yo]:o,[Zd]:y,[np]:S,[go]:X,[So]:P,[tp]:_,silent:qd,onChild:T,[sp]:R}),Object.setPrototypeOf(e,Od()),Md(e),e[zd](p),e}Q.exports=Tn;Q.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=mo(t.dest||process.stdout.fd),ho(t)):ho({dest:mo(t),minLength:0});Q.exports.transport=ln();Q.exports.multistream=po();Q.exports.levels=ko();Q.exports.stdSerializers=fp;Q.exports.stdTimeFunctions=Object.assign({},xo);Q.exports.symbols=vo;Q.exports.version=Ud;Q.exports.default=Tn;Q.exports.pino=Tn});var ps=C(ds(),1),{program:nm,createCommand:sm,createArgument:im,createOption:om,CommanderError:am,InvalidArgumentError:lm,InvalidOptionArgumentError:cm,Command:hs,Argument:um,Option:fm,Help:dm}=ps.default;var se=C(require("fs")),Te=C(require("path")),ms=C(require("os"));var ut={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}},ce={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 Be=Te.join(ms.homedir(),".hablas"),Mr=Te.join(Be,"config.json");function He(t={}){let e={};if(se.existsSync(Mr))try{e=JSON.parse(se.readFileSync(Mr,"utf-8"))}catch{}let r={...ut,...e,tools:{...ut.tools,...e.tools||{},runCommand:{...ut.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...ut.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=Te.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 We(t){se.existsSync(Be)||se.mkdirSync(Be,{recursive:!0}),se.writeFileSync(Mr,JSON.stringify(t,null,2),"utf-8")}function gs(){let t=[Be,Te.join(Be,"logs"),Te.join(Be,"backup")];for(let e of t)se.existsSync(e)||se.mkdirSync(e,{recursive:!0})}var An=C(To()),En=C(require("path")),Ao=C(require("os")),Gt=C(require("fs"));function On(t){let e=En.join(Ao.homedir(),".hablas","logs");Gt.existsSync(e)||Gt.mkdirSync(e,{recursive:!0});let r=En.join(e,`session-${Date.now()}.log`);return(0,An.default)({level:"info"},An.default.destination({dest:r,sync:!1}))}var Jt=C(require("fs")),mt=C(require("path"));function Eo(){let t=[mt.resolve(__dirname,"..","package.json"),mt.resolve(__dirname,"..","..","package.json"),mt.resolve(process.cwd(),"package.json"),mt.resolve(__dirname,"..","..","..","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 Ga=C(require("fs")),Ja=C(require("path"));var Xt=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 Oo=12e4,dp=6e4,Yt=3,Ro=1e3,pp=20;function Io(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 hp(t){return t.map(e=>({type:"function",function:e.function}))}function mp(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 Mo(t){return new Promise(e=>setTimeout(e,t))}function Po(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var 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=[],r=!0,n,s=0;for(;r&&s<pp;){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(dp)});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:Io(e)};r.length>0&&(i.tools=hp(r),i.tool_choice="auto");let o=null;for(let a=0;a<=Yt;a++)try{let l=new AbortController,u=setTimeout(()=>l.abort(),Oo),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(!Po(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<Yt){let y=Ro*Math.pow(2,a);await Mo(y);continue}throw o}let p=(await f.json()).choices?.[0];if(!p)throw new Error("API returned empty response");let c=p.message.tool_calls?mp(p.message.tool_calls):void 0;return{message:{role:p.message.role||"assistant",content:p.message.content||"",tool_calls:c},done:!0,done_reason:p.finish_reason}}catch(f){if(clearTimeout(u),f.name==="AbortError"&&n?.aborted)throw f;if(Po(f)&&(o=f,a<Yt)){let h=Ro*Math.pow(2,a);await Mo(h);continue}throw f}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Yt)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:Io(e),stream:!0}),signal:r||AbortSignal.timeout(Oo)});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 h=f.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let c=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;c&&(yield c)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function Ge(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:ce.apiUrl};return new gt(e)}return t.provider==="custom"&&t.apiUrl?new gt(t):new Xt(t)}function Je(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 j=C(require("fs/promises")),jn=C(require("fs")),xe=C(require("path"));function me(){}me.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(_){return i?(setTimeout(function(){i(void 0,_)},0),!0):_}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 h=(n=s.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+h,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,S=1/0;function b(){for(var _=Math.max(y,-d);_<=Math.min(S,d);_+=2){var k=void 0,A=c[_-1],T=c[_+1];A&&(c[_-1]=void 0);var R=!1;if(T){var $=T.oldPos-_;R=T&&0<=$&&$<l}var P=A&&A.oldPos+1<u;if(!R&&!P){c[_]=void 0;continue}if(!P||R&&A.oldPos+1<T.oldPos?k=o.addToPath(T,!0,void 0,0):k=o.addToPath(A,void 0,!0,1),m=o.extractCommon(k,r,e,_),k.oldPos+1>=u&&m+1>=l)return a(gp(o,k.lastComponent,r,e,o.useLongestToken));c[_]=k,k.oldPos+1>=u&&(S=Math.min(S,_-1)),m+1>=l&&(y=Math.max(y,_+1))}d++}if(i)(function _(){setTimeout(function(){if(d>f||Date.now()>p)return i();b()||_()},0)})();else for(;d<=f&&Date.now()<=p;){var x=b();if(x)return x}},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 gp(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 p=i[a-1];i[a-1]=i[a],i[a]=p}}else{if(!f.added&&s){var h=r.slice(u,u+f.count);h=h.map(function(m,y){var S=n[d+y];return S.length>m.length?S:m}),f.value=t.join(h)}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 lg=new me;var Do=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Fo=/\S/,Lo=new me;Lo.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!Fo.test(t)&&!Fo.test(e)};Lo.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]&&Do.test(e[r])&&Do.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var Dn=new me;Dn.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 yp(t,e,r){return Dn.diff(t,e,r)}var wp=new me;wp.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var bp=new me;bp.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Zt(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Zt=function(e){return typeof e}:Zt=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Zt(t)}function Rn(t){return Sp(t)||_p(t)||xp(t)||vp()}function Sp(t){if(Array.isArray(t))return In(t)}function _p(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function xp(t,e){if(t){if(typeof t=="string")return In(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 In(t,e)}}function In(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 vp(){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 kp=Object.prototype.toString,yt=new me;yt.useLongestToken=!0;yt.tokenize=Dn.tokenize;yt.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(Mn(t,null,null,s),s," ")};yt.equals=function(t,e){return me.prototype.equals.call(yt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function Mn(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(kp.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]=Mn(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),Zt(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]=Mn(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var Pn=new me;Pn.tokenize=function(t){return t.slice()};Pn.join=Pn.removeEmpty=function(t){return t};function Cp(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=yp(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(S){return S.map(function(b){return" "+b})}for(var u=[],d=0,f=0,h=[],p=1,c=1,m=function(b){var x=a[b],_=x.lines||x.value.replace(/\n$/,"").split(`
50
- `);if(x.lines=_,x.added||x.removed){var k;if(!d){var A=a[b-1];d=p,f=c,A&&(h=o.context>0?l(A.lines.slice(-o.context)):[],d-=h.length,f-=h.length)}(k=h).push.apply(k,Rn(_.map(function(W){return(x.added?"+":"-")+W}))),x.added?c+=_.length:p+=_.length}else{if(d)if(_.length<=o.context*2&&b<a.length-2){var T;(T=h).push.apply(T,Rn(l(_)))}else{var R,$=Math.min(_.length,o.context);(R=h).push.apply(R,Rn(l(_.slice(0,$))));var P={oldStart:d,oldLines:p-d+$,newStart:f,newLines:c-f+$,lines:h};if(b>=a.length-2&&_.length<=o.context){var N=/\n$/.test(r),F=/\n$/.test(n),B=_.length==0&&h.length>P.oldLines;!N&&B&&r.length>0&&h.splice(P.oldLines,0,"\"),(!N&&!B||!F)&&h.push("\")}u.push(P),d=0,f=0,h=[]}p+=_.length,c+=_.length}},y=0;y<a.length;y++)m(y);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:u}}function jo(t){if(Array.isArray(t))return t.map(jo).join(`
45
+ `),G=Wd.bind(null,{[_o]:"",[xo]:o,[ko]:F,[vo]:An,[En]:$,[Co]:D}),Y="";f!==null&&(h===void 0?Y=G(f):Y=G(Object.assign({},f,{name:h})));let M=a instanceof Function?a:a?Ro:fp,j=M().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(R&&typeof R!="string")throw Error(`Unknown msgPrefix type "${typeof R}" - expected "string"`);Ld(p,c,b);let Ot=Eo(c,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:Ot,messageKey:l,errorKey:u}}),Ud(m);let ss=qd(m);return Object.assign(e,{levels:Ot,[ip]:ss,[op]:b,[Yd]:n,[Jd]:M,[Xd]:j,[vo]:An,[En]:$,[ko]:F,[Qd]:W,[ep]:B,[tp]:l,[rp]:u,[np]:d,[lp]:d?`,${JSON.stringify(d)}:{`:"",[xo]:o,[sp]:y,[cp]:S,[_o]:Y,[Co]:D,[ap]:x,silent:zd,onChild:T,[up]:R}),Object.setPrototypeOf(e,jd()),Nd(e),e[Zd](p),e}ee.exports=On;ee.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=So(t.dest||process.stdout.fd),bo(t)):bo({dest:So(t),minLength:0});ee.exports.transport=fn();ee.exports.multistream=wo();ee.exports.levels=Eo();ee.exports.stdSerializers=yp;ee.exports.stdTimeFunctions=Object.assign({},To);ee.exports.symbols=Ao;ee.exports.version=Kd;ee.exports.default=On;ee.exports.pino=On});var ws=k(ys(),1),{program:um,createCommand:fm,createArgument:dm,createOption:pm,CommanderError:hm,InvalidArgumentError:mm,InvalidOptionArgumentError:gm,Command:bs,Argument:ym,Option:wm,Help:bm}=ws.default;var ie=k(require("fs")),Ee=k(require("path")),Ss=k(require("os"));var dt={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:5e3,timeout:12e4,autoMode:!1,contextBudget:2e6,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0}},ue={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 He=Ee.join(Ss.homedir(),".hablas"),jr=Ee.join(He,"config.json");function We(t={}){let e={};if(ie.existsSync(jr))try{e=JSON.parse(ie.readFileSync(jr,"utf-8"))}catch{}let r={...dt,...e,tools:{...dt.tools,...e.tools||{},runCommand:{...dt.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...dt.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=Ee.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 Ve(t){ie.existsSync(He)||ie.mkdirSync(He,{recursive:!0}),ie.writeFileSync(jr,JSON.stringify(t,null,2),"utf-8")}function _s(){let t=[He,Ee.join(He,"logs"),Ee.join(He,"backup")];for(let e of t)ie.existsSync(e)||ie.mkdirSync(e,{recursive:!0})}var Rn=k(Io()),In=k(require("path")),Po=k(require("os")),Yt=k(require("fs"));function Pn(t){let e=In.join(Po.homedir(),".hablas","logs");Yt.existsSync(e)||Yt.mkdirSync(e,{recursive:!0});let r=In.join(e,`session-${Date.now()}.log`);return(0,Rn.default)({level:"info"},Rn.default.destination({dest:r,sync:!1}))}var Zt=k(require("fs")),yt=k(require("path"));function Mo(){let t=[yt.resolve(__dirname,"..","package.json"),yt.resolve(__dirname,"..","..","package.json"),yt.resolve(process.cwd(),"package.json"),yt.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(Zt.existsSync(e)){let r=JSON.parse(Zt.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var el=k(require("fs")),tl=k(require("path"));var Qt=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 Do=12e4,wp=6e4,er=3,jo=1e3,bp=20;function Fo(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 Sp(t){return t.map(e=>({type:"function",function:e.function}))}function _p(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 Lo(t){return new Promise(e=>setTimeout(e,t))}function No(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var wt=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<bp;){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(wp)});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:Fo(e)};r.length>0&&(i.tools=Sp(r),i.tool_choice="auto");let o=null;for(let a=0;a<=er;a++)try{let l=new AbortController,u=setTimeout(()=>l.abort(),Do),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(!No(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<er){let y=jo*Math.pow(2,a);await Lo(y);continue}throw o}let p=(await f.json()).choices?.[0];if(!p)throw new Error("API returned empty response");let c=p.message.tool_calls?_p(p.message.tool_calls):void 0;return{message:{role:p.message.role||"assistant",content:p.message.content||"",tool_calls:c},done:!0,done_reason:p.finish_reason}}catch(f){if(clearTimeout(u),f.name==="AbortError"&&n?.aborted)throw f;if(No(f)&&(o=f,a<er)){let h=jo*Math.pow(2,a);await Lo(h);continue}throw f}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=er)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:Fo(e),stream:!0}),signal:r||AbortSignal.timeout(Do)});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 h=f.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let c=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;c&&(yield c)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function Je(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:ue.apiUrl};return new wt(e)}return t.provider==="custom"&&t.apiUrl?new wt(t):new Qt(t)}function Xe(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 N=k(require("fs/promises")),Un=k(require("fs")),ve=k(require("path"));function me(){}me.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(x){return i?(setTimeout(function(){i(void 0,x)},0),!0):x}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 h=(n=s.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+h,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,S=1/0;function b(){for(var x=Math.max(y,-d);x<=Math.min(S,d);x+=2){var C=void 0,A=c[x-1],T=c[x+1];A&&(c[x-1]=void 0);var R=!1;if(T){var $=T.oldPos-x;R=T&&0<=$&&$<l}var D=A&&A.oldPos+1<u;if(!R&&!D){c[x]=void 0;continue}if(!D||R&&A.oldPos+1<T.oldPos?C=o.addToPath(T,!0,void 0,0):C=o.addToPath(A,void 0,!0,1),m=o.extractCommon(C,r,e,x),C.oldPos+1>=u&&m+1>=l)return a(xp(o,C.lastComponent,r,e,o.useLongestToken));c[x]=C,C.oldPos+1>=u&&(S=Math.min(S,x-1)),m+1>=l&&(y=Math.max(y,x+1))}d++}if(i)(function x(){setTimeout(function(){if(d>f||Date.now()>p)return i();b()||x()},0)})();else for(;d<=f&&Date.now()<=p;){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 xp(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 p=i[a-1];i[a-1]=i[a],i[a]=p}}else{if(!f.added&&s){var h=r.slice(u,u+f.count);h=h.map(function(m,y){var S=n[d+y];return S.length>m.length?S:m}),f.value=t.join(h)}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 mg=new me;var qo=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Uo=/\S/,Bo=new me;Bo.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!Uo.test(t)&&!Uo.test(e)};Bo.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]&&qo.test(e[r])&&qo.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var Ln=new me;Ln.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 vp(t,e,r){return Ln.diff(t,e,r)}var kp=new me;kp.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var Cp=new me;Cp.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function tr(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?tr=function(e){return typeof e}:tr=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},tr(t)}function Mn(t){return $p(t)||Tp(t)||Ap(t)||Ep()}function $p(t){if(Array.isArray(t))return Dn(t)}function Tp(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Ap(t,e){if(t){if(typeof t=="string")return Dn(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 Dn(t,e)}}function Dn(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 Ep(){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 Op=Object.prototype.toString,bt=new me;bt.useLongestToken=!0;bt.tokenize=Ln.tokenize;bt.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(jn(t,null,null,s),s," ")};bt.equals=function(t,e){return me.prototype.equals.call(bt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function jn(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(Op.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]=jn(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),tr(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]=jn(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var Fn=new me;Fn.tokenize=function(t){return t.slice()};Fn.join=Fn.removeEmpty=function(t){return t};function Rp(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=vp(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(S){return S.map(function(b){return" "+b})}for(var u=[],d=0,f=0,h=[],p=1,c=1,m=function(b){var _=a[b],x=_.lines||_.value.replace(/\n$/,"").split(`
50
+ `);if(_.lines=x,_.added||_.removed){var C;if(!d){var A=a[b-1];d=p,f=c,A&&(h=o.context>0?l(A.lines.slice(-o.context)):[],d-=h.length,f-=h.length)}(C=h).push.apply(C,Mn(x.map(function(W){return(_.added?"+":"-")+W}))),_.added?c+=x.length:p+=x.length}else{if(d)if(x.length<=o.context*2&&b<a.length-2){var T;(T=h).push.apply(T,Mn(l(x)))}else{var R,$=Math.min(x.length,o.context);(R=h).push.apply(R,Mn(l(x.slice(0,$))));var D={oldStart:d,oldLines:p-d+$,newStart:f,newLines:c-f+$,lines:h};if(b>=a.length-2&&x.length<=o.context){var q=/\n$/.test(r),F=/\n$/.test(n),B=x.length==0&&h.length>D.oldLines;!q&&B&&r.length>0&&h.splice(D.oldLines,0,"\"),(!q&&!B||!F)&&h.push("\")}u.push(D),d=0,f=0,h=[]}p+=x.length,c+=x.length}},y=0;y<a.length;y++)m(y);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:u}}function Ho(t){if(Array.isArray(t))return t.map(Ho).join(`
51
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(`
52
52
  `)+`
53
- `}function $p(t,e,r,n,s,i,o){return jo(Cp(t,e,r,n,s,i,o))}function No(t,e,r,n,s,i){return $p(t,t,e,r,n,s,i)}function Fn(t,e,r){return No(t,e,r,"original","modified")}var fe=C(require("fs/promises")),Ln=C(require("fs")),Xe=C(require("path")),Uo=C(require("os")),wt=Xe.join(Uo.homedir(),".hablas","backup"),qo=10;async function Me(t){try{if(!Ln.existsSync(t))return;Ln.existsSync(wt)||await fe.mkdir(wt,{recursive:!0});let e=await fe.readFile(t,"utf-8"),r=Xe.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=Xe.join(wt,s);await fe.writeFile(i,e,"utf-8");let a=(await fe.readdir(wt)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>qo)for(let l of a.slice(qo))await fe.unlink(Xe.join(wt,l))}catch{}}function Ho(t){let e=p=>xe.resolve(t,p);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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[read_file]: path is required"};let c=e(p.path),y=(await j.readFile(c,"utf-8")).split(`
54
- `),S=y.length,b=p.start_line?Math.max(1,p.start_line):1,x=p.end_line?Math.min(S,p.end_line):S,_=y.slice(b-1,x),k=String(x).length,A=_.map(($,P)=>`${String(b+P).padStart(k," ")} | ${$}`),T=`[${p.path} \u2014 lines ${b}-${x} of ${S}]`,R=x<S?`
53
+ `}function Ip(t,e,r,n,s,i,o){return Ho(Rp(t,e,r,n,s,i,o))}function Wo(t,e,r,n,s,i){return Ip(t,t,e,r,n,s,i)}function Nn(t,e,r){return Wo(t,e,r,"original","modified")}var de=k(require("fs/promises")),qn=k(require("fs")),Ye=k(require("path")),zo=k(require("os")),St=Ye.join(zo.homedir(),".hablas","backup"),Vo=10;async function De(t){try{if(!qn.existsSync(t))return;qn.existsSync(St)||await de.mkdir(St,{recursive:!0});let e=await de.readFile(t,"utf-8"),r=Ye.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=Ye.join(St,s);await de.writeFile(i,e,"utf-8");let a=(await de.readdir(St)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Vo)for(let l of a.slice(Vo))await de.unlink(Ye.join(St,l))}catch{}}function Go(t){let e=p=>ve.resolve(t,p);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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[read_file]: path is required"};let c=e(p.path),y=(await N.readFile(c,"utf-8")).split(`
54
+ `),S=y.length,b=p.start_line?Math.max(1,p.start_line):1,_=p.end_line?Math.min(S,p.end_line):S,x=y.slice(b-1,_),C=String(_).length,A=x.map(($,D)=>`${String(b+D).padStart(C," ")} | ${$}`),T=`[${p.path} \u2014 lines ${b}-${_} of ${S}]`,R=_<S?`
55
55
  ... [Partial read. Total lines: ${S}.]`:"";return{success:!0,output:`${T}
56
56
  ${A.join(`
57
- `)}${R}`}}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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let c=e(p.path);return jn.existsSync(c)&&await Me(c),await j.mkdir(xe.dirname(c),{recursive:!0}),await j.writeFile(c,p.content,"utf-8"),{success:!0,output:`Written: ${p.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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!p.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=p.old_content,S=p.new_content,b=Bo(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 Me(c);let x=m.replace(y,S);await j.writeFile(c,x,"utf-8");let _=Fn(p.path,m,x);return{success:!0,output:`Edited: ${p.path}
58
- ${_}`}}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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!p.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!p.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(p.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=m.split(`
59
- `),S=y.length,b=p.start_line,x=p.end_line;if(b<1||b>S)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${S} lines)`};if(x<b||x>S)return{success:!1,output:"",error:`[patch_file]: end_line ${x} is out of range (start_line=${b}, total=${S})`};await Me(c);let _=y.slice(0,b-1),k=y.slice(x),A=p.new_content.split(`
60
- `),T=[..._,...A,...k].join(`
61
- `);await j.writeFile(c,T,"utf-8");let R=Fn(p.path,m,T),$=x-b+1,P=A.length;return{success:!0,output:`Patched: ${p.path} (replaced ${$} lines with ${P})
62
- ${R}`}}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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!p.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(p.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=p.search,S=p.replace,b=p.is_regex;await Me(c);let x,_;if(b){let k=new RegExp(y,"g");_=(m.match(k)||[]).length,x=m.replace(k,S)}else _=Bo(m,y),x=m.split(y).join(S);return _===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await j.writeFile(c,x,"utf-8"),{success:!0,output:`Replaced ${_} occurrence(s) in ${p.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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let c=e(p.path);return await j.mkdir(xe.dirname(c),{recursive:!0}),jn.existsSync(c)&&await Me(c),await j.appendFile(c,p.content,"utf-8"),{success:!0,output:`Appended to: ${p.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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let c=e(p.path);return await Me(c),await j.unlink(c),{success:!0,output:`Deleted: ${p.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 p=>{try{if(!p.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!p.to)return{success:!1,output:"",error:"[move_file]: to is required"};let c=e(p.from),m=e(p.to);return await j.mkdir(xe.dirname(m),{recursive:!0}),await j.rename(c,m),{success:!0,output:`Moved: ${p.from} \u2192 ${p.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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let c=e(p.path);return await j.mkdir(c,{recursive:!0}),{success:!0,output:`Created directory: ${p.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 p=>{try{let c=e(p.path||"."),m=p.depth||3;return{success:!0,output:await Wo(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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let c=e(p.path),m=await j.stat(c);return{success:!0,output:[`Path: ${p.path}`,`Size: ${Ap(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 Bo(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 Tp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Wo(t,e,r,n){if(n>=r)return"";let i=(await j.readdir(t,{withFileTypes:!0})).filter(a=>!Tp.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 h=e+(u?" ":"\u2502 ");o+=await Wo(xe.join(t,l.name),h,r,n+1)}}return o}function Ap(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Ko=require("child_process");var Vo=require("child_process"),Qt=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,Vo.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+=`
57
+ `)}${R}`}}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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let c=e(p.path);return Un.existsSync(c)&&await De(c),await N.mkdir(ve.dirname(c),{recursive:!0}),await N.writeFile(c,p.content,"utf-8"),{success:!0,output:`Written: ${p.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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!p.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let c=e(p.path),m=await N.readFile(c,"utf-8"),y=p.old_content,S=p.new_content,b=Ko(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 De(c);let _=m.replace(y,S);await N.writeFile(c,_,"utf-8");let x=Nn(p.path,m,_);return{success:!0,output:`Edited: ${p.path}
58
+ ${x}`}}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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!p.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!p.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(p.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let c=e(p.path),m=await N.readFile(c,"utf-8"),y=m.split(`
59
+ `),S=y.length,b=p.start_line,_=p.end_line;if(b<1||b>S)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${S} lines)`};if(_<b||_>S)return{success:!1,output:"",error:`[patch_file]: end_line ${_} is out of range (start_line=${b}, total=${S})`};await De(c);let x=y.slice(0,b-1),C=y.slice(_),A=p.new_content.split(`
60
+ `),T=[...x,...A,...C].join(`
61
+ `);await N.writeFile(c,T,"utf-8");let R=Nn(p.path,m,T),$=_-b+1,D=A.length;return{success:!0,output:`Patched: ${p.path} (replaced ${$} lines with ${D})
62
+ ${R}`}}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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!p.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(p.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let c=e(p.path),m=await N.readFile(c,"utf-8"),y=p.search,S=p.replace,b=p.is_regex;await De(c);let _,x;if(b){let C=new RegExp(y,"g");x=(m.match(C)||[]).length,_=m.replace(C,S)}else x=Ko(m,y),_=m.split(y).join(S);return x===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await N.writeFile(c,_,"utf-8"),{success:!0,output:`Replaced ${x} occurrence(s) in ${p.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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let c=e(p.path);return await N.mkdir(ve.dirname(c),{recursive:!0}),Un.existsSync(c)&&await De(c),await N.appendFile(c,p.content,"utf-8"),{success:!0,output:`Appended to: ${p.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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let c=e(p.path);return await De(c),await N.unlink(c),{success:!0,output:`Deleted: ${p.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 p=>{try{if(!p.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!p.to)return{success:!1,output:"",error:"[move_file]: to is required"};let c=e(p.from),m=e(p.to);return await N.mkdir(ve.dirname(m),{recursive:!0}),await N.rename(c,m),{success:!0,output:`Moved: ${p.from} \u2192 ${p.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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let c=e(p.path);return await N.mkdir(c,{recursive:!0}),{success:!0,output:`Created directory: ${p.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 p=>{try{let c=e(p.path||"."),m=p.depth||3;return{success:!0,output:await Jo(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 p=>{try{if(!p.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let c=e(p.path),m=await N.stat(c);return{success:!0,output:[`Path: ${p.path}`,`Size: ${Mp(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 Ko(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 Pp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Jo(t,e,r,n){if(n>=r)return"";let i=(await N.readdir(t,{withFileTypes:!0})).filter(a=>!Pp.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 h=e+(u?" ":"\u2502 ");o+=await Jo(ve.join(t,l.name),h,r,n+1)}}return o}function Mp(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Zo=require("child_process");var Xo=require("child_process"),rr=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,Xo.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
65
  Error: ${a.message}`}),s>0&&setTimeout(()=>{o.status==="running"&&(this.kill(n),o.status="timeout",o.stderr+=`
66
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
67
  `),i+=n.stderr),r?.lastLines&&(i=i.split(`
68
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 Ep=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],Nn=null;function zo(t){return Nn||(Nn=new Qt({workingDir:t})),Nn}function Go(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=[...Ep,...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=zo(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
70
- PID: ${zo(t).getProcess(l)?.pid}
71
- Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let u=(0,Ko.exec)(n,{cwd:t,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 er=C(require("fs/promises")),ve=C(require("path")),Op=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Rp=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function Jo(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=ve.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await Xo(n,s,i,t),i.length===0)return{success:!0,output:`No matches found for: "${r}"`};let o=i.slice(0,50).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 Dp=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],Bn=null;function Yo(t){return Bn||(Bn=new rr({workingDir:t})),Bn}function Qo(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=[...Dp,...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=Yo(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
70
+ PID: ${Yo(t).getProcess(l)?.pid}
71
+ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let u=(0,Zo.exec)(n,{cwd:t,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 nr=k(require("fs/promises")),ke=k(require("path")),jp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Fp=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function ea(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=ke.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await ta(n,s,i,t),i.length===0)return{success:!0,output:`No matches found for: "${r}"`};let o=i.slice(0,50).join(`
72
72
  `),a=i.length>50?`
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 Xo(t,e,r,n){let s=await er.readdir(t,{withFileTypes:!0});for(let i of s){if(Op.has(i.name)||i.name.startsWith("."))continue;let o=ve.join(t,i.name);if(i.isDirectory())await Xo(o,e,r,n);else if(Rp.has(ve.extname(i.name)))try{let l=(await er.readFile(o,"utf-8")).split(`
74
- `),u=ve.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 qn=require("child_process"),ee=C(require("fs")),ke=C(require("path"));function Ip(t){let e=[],r=ke.join(t,"tsconfig.json");if(!ee.existsSync(r))return e;try{(0,qn.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 Mp(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>ee.existsSync(ke.join(t,n))))return e;try{(0,qn.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:ke.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 Pp(t,e,r){let n;try{n=ee.readFileSync(t,"utf-8")}catch{return}let s=ke.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 Dp(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=ee.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let u=ke.join(s,l),d;try{d=ee.statSync(u)}catch{continue}d.isDirectory()?n(u,i+1):r.some(f=>l.endsWith(f))&&Pp(u,t,e)}}return n(t),e.slice(0,20)}function Fp(t){let e=[];e.push(...Ip(t)),e.push(...Mp(t)),e.push(...Dp(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function Yo(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 Lp(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=ke.join(e,n.file);try{let o=ee.readFileSync(s,"utf-8").split(`
79
- `);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],ee.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 Zo(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=Fp(r);if(n&&s.length>0){let o=Lp(s,r).filter(l=>l.fixed).length;return{success:!0,output:`${Yo(s)}
81
-
82
- Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:Yo(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Qo=2*1024*1024,ea=15e3,ta=32e3,jp="HablasBot/2.0 (+https://hablas.dev)";function Np(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,`
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 ta(t,e,r,n){let s=await nr.readdir(t,{withFileTypes:!0});for(let i of s){if(jp.has(i.name)||i.name.startsWith("."))continue;let o=ke.join(t,i.name);if(i.isDirectory())await ta(o,e,r,n);else if(Fp.has(ke.extname(i.name)))try{let l=(await nr.readFile(o,"utf-8")).split(`
74
+ `),u=ke.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 Hn=require("child_process"),te=k(require("fs")),Ce=k(require("path"));function Lp(t){let e=[],r=Ce.join(t,"tsconfig.json");if(!te.existsSync(r))return e;try{(0,Hn.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 Np(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>te.existsSync(Ce.join(t,n))))return e;try{(0,Hn.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:Ce.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 qp(t,e,r){let n;try{n=te.readFileSync(t,"utf-8")}catch{return}let s=Ce.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 Up(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=te.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let u=Ce.join(s,l),d;try{d=te.statSync(u)}catch{continue}d.isDirectory()?n(u,i+1):r.some(f=>l.endsWith(f))&&qp(u,t,e)}}return n(t),e.slice(0,20)}function Bp(t){let e=[];e.push(...Lp(t)),e.push(...Np(t)),e.push(...Up(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function ra(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 Hp(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=Ce.join(e,n.file);try{let o=te.readFileSync(s,"utf-8").split(`
79
+ `);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],te.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 na(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=Bp(r);if(n&&s.length>0){let o=Hp(s,r).filter(l=>l.fixed).length;return{success:!0,output:`${ra(s)}
81
+
82
+ Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:ra(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var sa=2*1024*1024,ia=15e3,oa=32e3,Wp="HablasBot/2.0 (+https://hablas.dev)";function Vp(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,`
83
83
  `),e=e.replace(/<(br|hr)\s*\/?>/gi,`
84
84
  `),e=e.replace(/<\/?(ul|ol)>/gi,`
85
85
  `),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(r,n,s)=>`
86
86
  ${"#".repeat(parseInt(n))} ${s.replace(/<[^>]+>/g,"").trim()}
87
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,`
88
88
 
89
- `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function qp(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 Up(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 ra(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ea);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":jp,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<Qo;){let{done:d,value:f}=await i.read();if(d)break;o.push(f),a+=f.length}if(a>=Qo)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 ${ea/1e3}s`):s}}function na(){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 ra(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=qp(r),o=Np(r);return o.length>ta&&(o=o.slice(0,ta)+`
89
+ `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function zp(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 Kp(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 aa(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ia);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":Wp,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<sa;){let{done:d,value:f}=await i.read();if(d)break;o.push(f),a+=f.length}if(a>=sa)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 ${ia/1e3}s`):s}}function la(){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 aa(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=zp(r),o=Vp(r);return o.length>oa&&(o=o.slice(0,oa)+`
90
90
 
91
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 ra(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Up(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(`
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 aa(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Kp(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(`
93
93
  `);return{success:!0,output:`Found ${o.length} links:
94
94
 
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 Bp=3600*1e3,Ye=new Map;function Hp(t){let e=Ye.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>Bp?(Ye.delete(t.toLowerCase().trim()),null):e.results:null}function Wp(t,e){if(Ye.size>200){let r=Ye.keys().next().value;r!==void 0&&Ye.delete(r)}Ye.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Vp(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 zp(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 Kp(t,e=5){let r=Hp(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>Vp(t,e)},{name:"duckduckgo",fn:()=>zp(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return Wp(t,i),i}catch{}return[]}function sa(){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 Kp(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 ge=C(require("fs")),ca=C(require("path")),ia=50*1024*1024,oa=4e4;function aa(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=Pe(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=Pe(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=Pe(l[1]));let u=e.match(/\/Creator\s*\(([^)]*)\)/);u&&(r.creator=Pe(u[1]));let d=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=d.exec(e))!==null;){let p=f[1],c=la(p);c.trim()&&n.push(c);try{let m=require("zlib"),y=Buffer.from(p,"latin1"),S=m.inflateSync(y).toString("latin1"),b=la(S);b.trim()&&!n.includes(b)&&n.push(b)}catch{}}return{text:n.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 Gp=3600*1e3,Ze=new Map;function Jp(t){let e=Ze.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>Gp?(Ze.delete(t.toLowerCase().trim()),null):e.results:null}function Xp(t,e){if(Ze.size>200){let r=Ze.keys().next().value;r!==void 0&&Ze.delete(r)}Ze.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Yp(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 Zp(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 Qp(t,e=5){let r=Jp(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>Yp(t,e)},{name:"duckduckgo",fn:()=>Zp(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return Xp(t,i),i}catch{}return[]}function ca(){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 Qp(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 ge=k(require("fs")),ha=k(require("path")),ua=50*1024*1024,fa=4e4;function da(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=je(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=je(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=je(l[1]));let u=e.match(/\/Creator\s*\(([^)]*)\)/);u&&(r.creator=je(u[1]));let d=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=d.exec(e))!==null;){let p=f[1],c=pa(p);c.trim()&&n.push(c);try{let m=require("zlib"),y=Buffer.from(p,"latin1"),S=m.inflateSync(y).toString("latin1"),b=pa(S);b.trim()&&!n.includes(b)&&n.push(b)}catch{}}return{text:n.join(`
97
97
  `).replace(/\r\n/g,`
98
98
  `).replace(/\n{3,}/g,`
99
99
 
100
- `).trim(),pages:s,metadata:r}}function la(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(Pe(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=>Pe(d.slice(1,-1))).join("");e.push(u)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(Pe(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 Pe(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 ua(t){let e=r=>ca.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(!ge.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=ge.statSync(n);if(s.size>ia)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${ia/1024/1024}MB)`};try{let i=ge.readFileSync(n),{text:o,pages:a,metadata:l}=aa(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
100
+ `).trim(),pages:s,metadata:r}}function pa(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(je(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=>je(d.slice(1,-1))).join("");e.push(u)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(je(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 je(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 ma(t){let e=r=>ha.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(!ge.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=ge.statSync(n);if(s.size>ua)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${ua/1024/1024}MB)`};try{let i=ge.readFileSync(n),{text:o,pages:a,metadata:l}=da(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
103
103
 
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>oa&&(u=u.slice(0,oa)+`
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>fa&&(u=u.slice(0,fa)+`
105
105
 
106
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(`
107
107
  `)}
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(!ge.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=ge.statSync(n),i=ge.readFileSync(n),{pages:o,metadata:a}=aa(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 pa=require("child_process"),tr=C(require("fs")),ha=C(require("os")),ma=C(require("path")),ga=1e4,fa=16e3;function Ze(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 da={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>Ze("tsx")?`tsx "${t}"`:Ze("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=>Ze("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>Ze("python3")||Ze("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>Ze("bash")}};async function Gp(t,e,r=ga){let n=da[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(da).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=ha.tmpdir(),i=ma.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{tr.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let u=(0,pa.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,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 p=Date.now()-a;l({success:h===0,stdout:d.slice(0,fa),stderr:f.slice(0,fa/2),exitCode:h??1,duration:p,language:e})}),u.on("error",h=>{let p=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:p,language:e})})})}finally{try{tr.unlinkSync(i)}catch{}}}function Jp(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 ya(){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()||Jp(e),n=Math.min(Math.max(1e3,t.timeout||ga),3e4),s=await Gp(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?`
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(!ge.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=ge.statSync(n),i=ge.readFileSync(n),{pages:o,metadata:a}=da(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 wa=require("child_process"),sr=k(require("fs")),ba=k(require("os")),Sa=k(require("path")),_a=1e4,ga=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 ya={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 eh(t,e,r=_a){let n=ya[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(ya).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=ba.tmpdir(),i=Sa.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{sr.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let u=(0,wa.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,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 p=Date.now()-a;l({success:h===0,stdout:d.slice(0,ga),stderr:f.slice(0,ga/2),exitCode:h??1,duration:p,language:e})}),u.on("error",h=>{let p=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:p,language:e})})})}finally{try{sr.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 xa(){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||_a),3e4),s=await eh(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
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 rr=C(require("fs")),ae=C(require("path")),Xp=15*1024*1024;function Yp(t,e){return/image\/png/i.test(t)?".png":/image\/jpe?g/i.test(t)?".jpg":/image\/webp/i.test(t)?".webp":/image\/gif/i.test(t)?".gif":/image\/svg\+xml/i.test(t)?".svg":ae.extname(new URL(e).pathname)||".bin"}function wa(t){return{name:"download_asset",description:"Download an external asset such as an image or file from a URL and save it inside the project. Use this when the user wants real local assets, wallpaper images, hero images, icons, or downloadable files inside the generated project.",safety:"confirm",parameters:{url:{type:"string",description:"Public URL of the asset to download",required:!0},path:{type:"string",description:"Target project-relative path, e.g. public/hero.jpg or assets/bg.webp",required:!0}},execute:async e=>{let r=String(e.url||""),n=String(e.path||"");if(!r)return{success:!1,output:"",error:"url is required"};if(!n)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(r))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let s=await fetch(r,{signal:AbortSignal.timeout(15e3)});if(!s.ok)return{success:!1,output:"",error:`HTTP ${s.status} while downloading asset`};let i=s.headers.get("content-type")||"",o=await s.arrayBuffer(),a=Buffer.from(o);if(a.length>Xp)return{success:!1,output:"",error:`asset too large: ${Math.round(a.length/1024/1024)}MB`};let l=ae.resolve(t,n),d=ae.extname(l)?l:l+Yp(i,r);return rr.mkdirSync(ae.dirname(d),{recursive:!0}),rr.writeFileSync(d,a),{success:!0,output:`Downloaded asset: ${ae.relative(t,d)||ae.basename(d)}
111
+ `),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var ir=k(require("fs")),le=k(require("path")),rh=15*1024*1024;function nh(t,e){return/image\/png/i.test(t)?".png":/image\/jpe?g/i.test(t)?".jpg":/image\/webp/i.test(t)?".webp":/image\/gif/i.test(t)?".gif":/image\/svg\+xml/i.test(t)?".svg":le.extname(new URL(e).pathname)||".bin"}function va(t){return{name:"download_asset",description:"Download an external asset such as an image or file from a URL and save it inside the project. Use this when the user wants real local assets, wallpaper images, hero images, icons, or downloadable files inside the generated project.",safety:"confirm",parameters:{url:{type:"string",description:"Public URL of the asset to download",required:!0},path:{type:"string",description:"Target project-relative path, e.g. public/hero.jpg or assets/bg.webp",required:!0}},execute:async e=>{let r=String(e.url||""),n=String(e.path||"");if(!r)return{success:!1,output:"",error:"url is required"};if(!n)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(r))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let s=await fetch(r,{signal:AbortSignal.timeout(15e3)});if(!s.ok)return{success:!1,output:"",error:`HTTP ${s.status} while downloading asset`};let i=s.headers.get("content-type")||"",o=await s.arrayBuffer(),a=Buffer.from(o);if(a.length>rh)return{success:!1,output:"",error:`asset too large: ${Math.round(a.length/1024/1024)}MB`};let l=le.resolve(t,n),d=le.extname(l)?l:l+nh(i,r);return ir.mkdirSync(le.dirname(d),{recursive:!0}),ir.writeFileSync(d,a),{success:!0,output:`Downloaded asset: ${le.relative(t,d)||le.basename(d)}
112
112
  Source: ${r}
113
113
  Type: ${i||"unknown"}
114
- Size: ${a.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${s?.message||String(s)}`}}}}}var Qe=class{tools=new Map;constructor(e,r){let n=Ho(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",Go(e,r)),this.tools.set("search_codebase",Jo(e)),this.tools.set("detect_bugs",Zo(e)),this.tools.set("web_search",sa());for(let s of na())this.tools.set(s.name,s);for(let s of ua(e))this.tools.set(s.name,s);for(let s of ya())this.tools.set(s.name,s);this.tools.set("download_asset",wa(e))}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(`
114
+ Size: ${a.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${s?.message||String(s)}`}}}}}var et=class{tools=new Map;constructor(e,r){let n=Go(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",Qo(e,r)),this.tools.set("search_codebase",ea(e)),this.tools.set("detect_bugs",na(e)),this.tools.set("web_search",ca());for(let s of la())this.tools.set(s.name,s);for(let s of ma(e))this.tools.set(s.name,s);for(let s of xa())this.tools.set(s.name,s);this.tools.set("download_asset",va(e))}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(`
115
115
  `);return`- ${r.name} [${r.safety}]: ${r.description}
116
116
  ${n}`}).join(`
117
117
 
118
- `)}};var ba=C(require("crypto"));function Un(t){return Math.ceil(t.length/3.5)}function bt(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
119
- ... [truncated to fit context budget]`}var et=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=Un(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=bt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
118
+ `)}};var ka=k(require("crypto"));function Wn(t){return Math.ceil(t.length/3.5)}function _t(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
119
+ ... [truncated to fit context budget]`}var tt=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=Wn(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=_t(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
120
120
  ${l}`),s+=a}}continue}i.push(`--- ${o.path} ---
121
121
  ${o.content}`),s+=o.tokenCount}return i.join(`
122
122
 
123
123
  `)}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} ---
124
124
  ${u.content}`),a+=u.tokenCount}return l.join(`
125
125
 
126
- `)}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=Un(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 ba.createHash("md5").update(e).digest("hex")}};var Zp=0;function St(){return`msg_${Date.now()}_${++Zp}`}function tt(t){return Math.ceil(t.length/4)}var rt=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=tt(e);this.messages.push({id:St(),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=St(),s=tt(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=St(),i=tt(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=St(),s=tt(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=tt(e),n=this.messages.filter(s=>s.priority==="critical"&&s.role!=="system");this.messages=[{id:St(),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)+`
126
+ `)}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=Wn(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 ka.createHash("md5").update(e).digest("hex")}};var sh=0;function xt(){return`msg_${Date.now()}_${++sh}`}function rt(t){return Math.ceil(t.length/4)}var nt=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=rt(e);this.messages.push({id:xt(),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=xt(),s=rt(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=xt(),i=rt(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=xt(),s=rt(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=rt(e),n=this.messages.filter(s=>s.priority==="critical"&&s.role!=="system");this.messages=[{id:xt(),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)+`
127
127
  ...(compressed from `+r+" chars)":e.content=e.content.slice(0,400)+`
128
- ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=tt(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 st=C(require("fs")),Sa=C(require("path"));var E=C(require("fs")),O=C(require("path"));function Qp(t){let e=O.join(t,"package.json");if(E.existsSync(e))try{let r=JSON.parse(E.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(E.existsSync(O.join(t,"requirements.txt"))||E.existsSync(O.join(t,"pyproject.toml")))try{let r=E.existsSync(O.join(t,"requirements.txt"))?E.readFileSync(O.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(E.existsSync(O.join(t,"Cargo.toml")))try{if(E.readFileSync(O.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(E.existsSync(O.join(t,"go.mod")))try{if(E.readFileSync(O.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function eh(t){return E.existsSync(O.join(t,"pnpm-lock.yaml"))?"pnpm":E.existsSync(O.join(t,"yarn.lock"))?"yarn":E.existsSync(O.join(t,"bun.lockb"))?"bun":E.existsSync(O.join(t,"package-lock.json"))?"npm":E.existsSync(O.join(t,"Cargo.toml"))?"cargo":E.existsSync(O.join(t,"go.mod"))?"go":E.existsSync(O.join(t,"requirements.txt"))||E.existsSync(O.join(t,"pyproject.toml"))?"pip":"unknown"}function th(t){return E.existsSync(O.join(t,"tsconfig.json"))?"TypeScript":E.existsSync(O.join(t,"package.json"))?"JavaScript":E.existsSync(O.join(t,"Cargo.toml"))?"Rust":E.existsSync(O.join(t,"go.mod"))?"Go":E.existsSync(O.join(t,"pyproject.toml"))||E.existsSync(O.join(t,"requirements.txt"))?"Python":"Unknown"}function rh(t){let e=O.join(t,".git","HEAD");if(!E.existsSync(e))return null;try{let r=E.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function nt(t){let e=Qp(t),r=eh(t),n=th(t),s=rh(t),i=E.existsSync(O.join(t,"Dockerfile"))||E.existsSync(O.join(t,"docker-compose.yml"))||E.existsSync(O.join(t,"docker-compose.yaml")),o=E.existsSync(O.join(t,".github","workflows"))||E.existsSync(O.join(t,".gitlab-ci.yml"))||E.existsSync(O.join(t,"Jenkinsfile")),a=E.existsSync(O.join(t,"__tests__"))||E.existsSync(O.join(t,"tests"))||E.existsSync(O.join(t,"test"))||E.existsSync(O.join(t,"spec")),l=E.existsSync(O.join(t,".git")),u=[],d=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of d)E.existsSync(O.join(t,m))&&u.push(m);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 m of h)E.existsSync(O.join(t,m))&&f.push(m);let p=[],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)E.existsSync(O.join(t,m))&&p.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:p}}function nr(t){let e=[` Project: ${O.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(`
129
- `)}async function it(t,e){let r=[],n=Sa.join(t,"package.json");if(st.existsSync(n))try{let o=JSON.parse(st.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=nt(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=nh(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(`
130
- `)}function nh(t,e){try{return st.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function ot(t,e){return`You are Hablas, a single powerful AI software engineering agent created by Abdulmoin Hablas.
128
+ ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=rt(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 it=k(require("fs")),Ca=k(require("path"));var E=k(require("fs")),O=k(require("path"));function ih(t){let e=O.join(t,"package.json");if(E.existsSync(e))try{let r=JSON.parse(E.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(E.existsSync(O.join(t,"requirements.txt"))||E.existsSync(O.join(t,"pyproject.toml")))try{let r=E.existsSync(O.join(t,"requirements.txt"))?E.readFileSync(O.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(E.existsSync(O.join(t,"Cargo.toml")))try{if(E.readFileSync(O.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(E.existsSync(O.join(t,"go.mod")))try{if(E.readFileSync(O.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function oh(t){return E.existsSync(O.join(t,"pnpm-lock.yaml"))?"pnpm":E.existsSync(O.join(t,"yarn.lock"))?"yarn":E.existsSync(O.join(t,"bun.lockb"))?"bun":E.existsSync(O.join(t,"package-lock.json"))?"npm":E.existsSync(O.join(t,"Cargo.toml"))?"cargo":E.existsSync(O.join(t,"go.mod"))?"go":E.existsSync(O.join(t,"requirements.txt"))||E.existsSync(O.join(t,"pyproject.toml"))?"pip":"unknown"}function ah(t){return E.existsSync(O.join(t,"tsconfig.json"))?"TypeScript":E.existsSync(O.join(t,"package.json"))?"JavaScript":E.existsSync(O.join(t,"Cargo.toml"))?"Rust":E.existsSync(O.join(t,"go.mod"))?"Go":E.existsSync(O.join(t,"pyproject.toml"))||E.existsSync(O.join(t,"requirements.txt"))?"Python":"Unknown"}function lh(t){let e=O.join(t,".git","HEAD");if(!E.existsSync(e))return null;try{let r=E.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function st(t){let e=ih(t),r=oh(t),n=ah(t),s=lh(t),i=E.existsSync(O.join(t,"Dockerfile"))||E.existsSync(O.join(t,"docker-compose.yml"))||E.existsSync(O.join(t,"docker-compose.yaml")),o=E.existsSync(O.join(t,".github","workflows"))||E.existsSync(O.join(t,".gitlab-ci.yml"))||E.existsSync(O.join(t,"Jenkinsfile")),a=E.existsSync(O.join(t,"__tests__"))||E.existsSync(O.join(t,"tests"))||E.existsSync(O.join(t,"test"))||E.existsSync(O.join(t,"spec")),l=E.existsSync(O.join(t,".git")),u=[],d=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of d)E.existsSync(O.join(t,m))&&u.push(m);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 m of h)E.existsSync(O.join(t,m))&&f.push(m);let p=[],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)E.existsSync(O.join(t,m))&&p.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:p}}function or(t){let e=[` Project: ${O.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(`
129
+ `)}async function ot(t,e){let r=[],n=Ca.join(t,"package.json");if(it.existsSync(n))try{let o=JSON.parse(it.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=st(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=ch(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(`
130
+ `)}function ch(t,e){try{return it.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function at(t,e){return`You are Hablas, a single powerful AI software engineering agent created by Abdulmoin Hablas.
131
131
 
132
132
  Identity contract:
133
133
  - You are the only visible agent.
@@ -230,30 +230,30 @@ Few-shot behavior rules:
230
230
  -> do real work through tools, complete as much as possible, verify before claiming done.
231
231
 
232
232
  Task profile:
233
- ${sh(e)}
233
+ ${uh(e)}
234
234
 
235
235
  Current project context:
236
- ${t}`}function sh(t){return t.kind==="casual"?["- Casual social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short and natural."].join(`
236
+ ${t}`}function uh(t){return t.kind==="casual"?["- Casual social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short and natural."].join(`
237
237
  `):t.kind==="read"?["- Read-only or project-inspection task.","- Use tools only to inspect the minimum necessary evidence.","- Keep the final answer factual, grounded, and tight."].join(`
238
238
  `):t.kind==="analysis"?["- Analysis / architecture task.","- Prefer reasoning first.","- If files are relevant, inspect only what is necessary.","- Deliver a structured recommendation with trade-offs and assumptions."].join(`
239
239
  `):[t.continuity?"- Continue from existing work. Do not restart the project from zero.":"- Implementation task.",t.oneStepDelivery?"- The user requested one-step delivery with no unnecessary follow-up questions.":"- Ask a clarifying question only if the task is truly blocked.","- Real workspace tool usage is mandatory.","- Do not answer with inline code only if files can be created or modified directly.","- The task is not complete unless the relevant files were inspected and then changed or created when needed.","- Verify changes before claiming completion."].join(`
240
- `)}var ih=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,oh=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,ah=/\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|craft|make)\b/i,ch=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,uh=/\b(frontend|backend|store|shop|website|web app|landing page|page|component|ui|ux|auth|login|dashboard|api|endpoint|schema|database|project|application|app|image|images|photo|photos|wallpaper|background|hero)\b/i,fh=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,dh=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,_a=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function _t(t){let e=t.trim(),r=e.toLowerCase(),n=oh.test(r),s=ah.test(r),i=lh.test(r)||ch.test(r),o=uh.test(r),a=fh.test(r),l=i||n||s||o&&e.length>18&&!_a.test(r)&&!a,u=a&&!i&&!n&&!s,d=dh.test(r)||o,f=!l&&!u&&(_a.test(r)||e.endsWith("?"));return ih.test(e)&&!d&&!l&&!u?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:l?{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."}:u?{kind:"analysis",needsTools:d,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:d,reason:d?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:f||d?{kind:"read",needsTools:d,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:d,reason:d?"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 ph(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 xa(t){let e=_t(t);return{input:t,profile:e,plan:ph(t,e)}}var Pa=C(require("readline")),ne=C(require("fs")),G=C(require("path")),Da=C(require("os"));var Bn=C(require("os")),or=C(require("fs")),ir=C(require("path"));function hh(){let t=[ir.resolve(__dirname,"..","package.json"),ir.resolve(__dirname,"..","..","package.json"),ir.resolve(process.cwd(),"package.json")];for(let e of t)try{if(or.existsSync(e)){let r=JSON.parse(or.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var va=hh(),Hn=process.stdout.isTTY===!0,mh=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",ka=process.stdout.columns||100;Hn&&process.stdout.on("resize",()=>{ka=process.stdout.columns||100});var De=()=>Math.min(Math.max(ka-4,60),100);function te(t,e){return!Hn||mh?t:`${e}${t}\x1B[0m`}var w={strong:t=>te(t,"\x1B[1;38;5;255m"),muted:t=>te(t,"\x1B[38;5;242m"),accent:t=>te(t,"\x1B[38;5;145m"),info:t=>te(t,"\x1B[38;5;110m"),success:t=>te(t,"\x1B[38;5;108m"),warning:t=>te(t,"\x1B[38;5;179m"),error:t=>te(t,"\x1B[38;5;167m"),primary:t=>te(t,"\x1B[38;5;253m"),secondary:t=>te(t,"\x1B[38;5;247m"),border:t=>te(t,"\x1B[38;5;237m"),code:t=>te(t,"\x1B[38;5;188m"),line:t=>te(t,"\x1B[38;5;239m")};function Wn(t,e=2){let r=De()-e,n=t.split(" "),s=[],i="";for(let o of n)(i+" "+o).trim().length>r&&i?(s.push(" ".repeat(e)+i.trim()),i=o):i+=(i?" ":"")+o;return i&&s.push(" ".repeat(e)+i.trim()),s}function gh(t){let e=De();if(!t)return w.border("\u2500".repeat(e));let r=t.replace(/\x1b\[[0-9;]*m/g,""),n=Math.max(0,e-r.length-2),s=Math.floor(n/2),i=n-s;return w.border("\u2500".repeat(s))+" "+t+" "+w.border("\u2500".repeat(i))}function Ca(t,e){let r=De(),n=e.replace(Bn.homedir(),"~"),s=w.border("\u2554"+"\u2550".repeat(r-2)+"\u2557"),i=w.border("\u2560"+"\u2550".repeat(r-2)+"\u2563"),o=w.border("\u255A"+"\u2550".repeat(r-2)+"\u255D"),a="H A B L A S",l="APPLE-SLATE TERMINAL RUNTIME",u=Math.max(0,Math.floor((r-2-a.length)/2)),d=Math.max(0,Math.floor((r-2-l.length)/2));return["",s,w.border("\u2551")+" ".repeat(u)+w.strong(a)+" ".repeat(r-2-a.length-u)+w.border("\u2551"),w.border("\u2551")+" ".repeat(d)+w.secondary(l)+" ".repeat(r-2-l.length-d)+w.border("\u2551"),i,` ${w.muted("\u25B8")} ${w.muted(`VERSION: v${va}`)}`,` ${w.muted("\u25B8")} ${w.muted(`MODEL: ${t}`)}`,` ${w.muted("\u25B8")} ${w.muted(`WORKSPACE: ${n}`)}`,` ${w.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")}`,` ${w.muted(" \u203A")} ${w.secondary("Type naturally to get started")}`,` ${w.muted(" \u203A")} ${w.secondary("/help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")}`,o,""].join(`
241
- `)}function $a(t){return`
242
- `+gh(`${w.accent("\u25C6")} ${w.strong("Turn #"+t)}`)}function at(){return`
243
- ${w.accent("\u25C6")} ${w.strong("Hablas")} ${w.muted("[response]")}`}function sr(t){return t.replace(/`([^`]+)`/g,(e,r)=>w.primary(r)).replace(/\*\*([^*]+)\*\*/g,(e,r)=>w.strong(r))}function xt(t){let e=t.split(`
244
- `),r=[],n=!1,s="",i=[],o=()=>{if(!i.length)return;let a=String(i.length).length;r.push(` ${w.border("\u250C"+"\u2500".repeat(Math.max(24,De()-6)))} ${s?w.accent(s):""}`.trimEnd()),i.forEach((l,u)=>{r.push(` ${w.border("\u2502")} ${w.line(String(u+1).padStart(a)+" \u2502")} ${w.code(l)}`)}),r.push(` ${w.border("\u2514"+"\u2500".repeat(Math.max(24,De()-6)))}`),i=[]};for(let a of e){if(a.trimStart().startsWith("```")){n?(o(),n=!1,s=""):(n=!0,s=a.trimStart().slice(3).trim());continue}if(n){i.push(a);continue}if(!a.trim()){r.push("");continue}if(/^#{1,3}\s/.test(a)){r.push(` ${w.strong(sr(a.replace(/^#{1,3}\s/,"")))}`);continue}if(/^[-*]\s/.test(a.trim())){r.push(` ${w.accent("\u25B8")} ${sr(a.trim().slice(2))}`);continue}if(/^\d+\.\s/.test(a.trim())){r.push(` ${sr(a.trim())}`);continue}r.push(...Wn(sr(a),2))}return n&&o(),`
240
+ `)}var fh=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,dh=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,ph=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,hh=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,mh=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,gh=/\b(frontend|backend|store|shop|website|web app|landing page|page|component|ui|ux|auth|login|dashboard|api|endpoint|schema|database|project|application|app|image|images|photo|photos|wallpaper|background|hero)\b/i,yh=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,wh=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,$a=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function vt(t){let e=t.trim(),r=e.toLowerCase(),n=dh.test(r),s=ph.test(r),i=hh.test(r)||mh.test(r),o=gh.test(r),a=yh.test(r),l=i||n||s||o&&e.length>18&&!$a.test(r)&&!a,u=a&&!i&&!n&&!s,d=wh.test(r)||o,f=!l&&!u&&($a.test(r)||e.endsWith("?"));return fh.test(e)&&!d&&!l&&!u?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:l?{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."}:u?{kind:"analysis",needsTools:d,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:d,reason:d?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:f||d?{kind:"read",needsTools:d,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:d,reason:d?"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 bh(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=vt(t);return{input:t,profile:e,plan:bh(t,e)}}var Na=k(require("readline")),se=k(require("fs")),J=k(require("path")),qa=k(require("os"));var Vn=k(require("os")),cr=k(require("fs")),lr=k(require("path"));function Sh(){let t=[lr.resolve(__dirname,"..","package.json"),lr.resolve(__dirname,"..","..","package.json"),lr.resolve(process.cwd(),"package.json")];for(let e of t)try{if(cr.existsSync(e)){let r=JSON.parse(cr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Aa=Sh(),zn=process.stdout.isTTY===!0,_h=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",Ea=process.stdout.columns||100;zn&&process.stdout.on("resize",()=>{Ea=process.stdout.columns||100});var Fe=()=>Math.min(Math.max(Ea-4,60),100);function re(t,e){return!zn||_h?t:`${e}${t}\x1B[0m`}var w={strong:t=>re(t,"\x1B[1;38;5;255m"),muted:t=>re(t,"\x1B[38;5;242m"),accent:t=>re(t,"\x1B[38;5;145m"),info:t=>re(t,"\x1B[38;5;110m"),success:t=>re(t,"\x1B[38;5;108m"),warning:t=>re(t,"\x1B[38;5;179m"),error:t=>re(t,"\x1B[38;5;167m"),primary:t=>re(t,"\x1B[38;5;253m"),secondary:t=>re(t,"\x1B[38;5;247m"),border:t=>re(t,"\x1B[38;5;237m"),code:t=>re(t,"\x1B[38;5;188m"),line:t=>re(t,"\x1B[38;5;239m")};function Kn(t,e=2){let r=Fe()-e,n=t.split(" "),s=[],i="";for(let o of n)(i+" "+o).trim().length>r&&i?(s.push(" ".repeat(e)+i.trim()),i=o):i+=(i?" ":"")+o;return i&&s.push(" ".repeat(e)+i.trim()),s}function xh(t){let e=Fe();if(!t)return w.border("\u2500".repeat(e));let r=t.replace(/\x1b\[[0-9;]*m/g,""),n=Math.max(0,e-r.length-2),s=Math.floor(n/2),i=n-s;return w.border("\u2500".repeat(s))+" "+t+" "+w.border("\u2500".repeat(i))}function Oa(t,e){let r=Fe(),n=e.replace(Vn.homedir(),"~"),s=w.border("\u2554"+"\u2550".repeat(r-2)+"\u2557"),i=w.border("\u2560"+"\u2550".repeat(r-2)+"\u2563"),o=w.border("\u255A"+"\u2550".repeat(r-2)+"\u255D"),a="H A B L A S",l="APPLE-SLATE TERMINAL RUNTIME",u=Math.max(0,Math.floor((r-2-a.length)/2)),d=Math.max(0,Math.floor((r-2-l.length)/2));return["",s,w.border("\u2551")+" ".repeat(u)+w.strong(a)+" ".repeat(r-2-a.length-u)+w.border("\u2551"),w.border("\u2551")+" ".repeat(d)+w.secondary(l)+" ".repeat(r-2-l.length-d)+w.border("\u2551"),i,` ${w.muted("\u25B8")} ${w.muted(`VERSION: v${Aa}`)}`,` ${w.muted("\u25B8")} ${w.muted(`MODEL: ${t}`)}`,` ${w.muted("\u25B8")} ${w.muted(`WORKSPACE: ${n}`)}`,` ${w.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")}`,` ${w.muted(" \u203A")} ${w.secondary("Type naturally to get started")}`,` ${w.muted(" \u203A")} ${w.secondary("/help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")}`,o,""].join(`
241
+ `)}function Ra(t){return`
242
+ `+xh(`${w.accent("\u25C6")} ${w.strong("Turn #"+t)}`)}function lt(){return`
243
+ ${w.accent("\u25C6")} ${w.strong("Hablas")} ${w.muted("[response]")}`}function ar(t){return t.replace(/`([^`]+)`/g,(e,r)=>w.primary(r)).replace(/\*\*([^*]+)\*\*/g,(e,r)=>w.strong(r))}function kt(t){let e=t.split(`
244
+ `),r=[],n=!1,s="",i=[],o=()=>{if(!i.length)return;let a=String(i.length).length;r.push(` ${w.border("\u250C"+"\u2500".repeat(Math.max(24,Fe()-6)))} ${s?w.accent(s):""}`.trimEnd()),i.forEach((l,u)=>{r.push(` ${w.border("\u2502")} ${w.line(String(u+1).padStart(a)+" \u2502")} ${w.code(l)}`)}),r.push(` ${w.border("\u2514"+"\u2500".repeat(Math.max(24,Fe()-6)))}`),i=[]};for(let a of e){if(a.trimStart().startsWith("```")){n?(o(),n=!1,s=""):(n=!0,s=a.trimStart().slice(3).trim());continue}if(n){i.push(a);continue}if(!a.trim()){r.push("");continue}if(/^#{1,3}\s/.test(a)){r.push(` ${w.strong(ar(a.replace(/^#{1,3}\s/,"")))}`);continue}if(/^[-*]\s/.test(a.trim())){r.push(` ${w.accent("\u25B8")} ${ar(a.trim().slice(2))}`);continue}if(/^\d+\.\s/.test(a.trim())){r.push(` ${ar(a.trim())}`);continue}r.push(...Kn(ar(a),2))}return n&&o(),`
245
245
  `+r.join(`
246
246
  `)+`
247
- `}function Ta(){return["",` ${w.strong("Hablas commands")}`,"",` ${w.primary("/help")} ${w.muted("show help")}`,` ${w.primary("/status")} ${w.muted("show current runtime status")}`,` ${w.primary("/model")} ${w.muted("show or switch active model")}`,` ${w.primary("/models")} ${w.muted("list available models (supports search)")}`,` ${w.primary("/provider")} ${w.muted("inspect or switch provider")}`,` ${w.primary("/history")} ${w.muted("show recent turns")}`,` ${w.primary("/clear")} ${w.muted("clear the session")}`,` ${w.primary("/workspace")} ${w.muted("inspect workspace info")}`,` ${w.primary("/doctor")} ${w.muted("run diagnostics")}`,` ${w.primary("/version")} ${w.muted("show version")}`,` ${w.primary("/about")} ${w.muted("show product identity")}`,` ${w.primary("/exit")} ${w.muted("quit")}`,"",` ${w.accent("Tips")}`,` ${w.muted("\u2022 Tab completes commands and common file paths.")}`,` ${w.muted("\u2022 Use #filename to reference files quickly.")}`,` ${w.muted("\u2022 Ctrl+C cancels current work. Ctrl+C twice exits.")}`,""].join(`
248
- `)}function Aa(t){let e=[` ${w.muted("provider")} ${w.info(t.provider)}`,` ${w.muted("model")} ${w.info(t.model)}`,` ${w.muted("workspace")} ${w.muted(t.workingDir.replace(Bn.homedir(),"~"))}`,` ${w.muted("connected")} ${t.connected?w.success("yes"):w.error("no")}`,` ${w.muted("messages")} ${w.info(String(t.messageCount))}`,t.totalTokens!==void 0?` ${w.muted("tokens")} ${w.info(String(t.totalTokens))}`:""].filter(Boolean);return[""," "+w.strong("Status"),""].concat(e).concat([""]).join(`
249
- `)}function re(t){return` ${w.info(t)}`}function Le(t){return` ${w.success("\u2713")} ${t}`}function ye(t){return` ${w.warning("\u26A0")} ${t}`}function Ce(t){return` ${w.error("\u2717")} ${t}`}function Ea(){return` ${w.strong("Hablas")} ${w.accent("v"+va)}`}function Oa(){return` ${w.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime by Abdulmoin Hablas`}function Ra(t,e){let r=Math.max(44,De()-8),n=`${t} \xB7 ${e}`,s=Wn(n,0),i=[];i.push(` ${w.border("\u250C"+"\u2500".repeat(r+2)+"\u2510")}`);for(let o of s){let a=o.trim(),l=Math.max(0,r-a.replace(/\x1b\[[0-9;]*m/g,"").length);i.push(` ${w.border("\u2502")} ${w.accent(a)}${" ".repeat(l)} ${w.border("\u2502")}`)}return i.join(`
250
- `)}function Ia(t,e,r){let n=Math.max(44,De()-8),s=t?w.success("\u2713"):w.error("\u2717"),o=e.split(`
251
- `)[0]?.trim()||""||e.replace(/\s+/g," ").trim()||(t?"done":"failed"),a=`${s} ${o} ${w.muted(`(${r}ms)`)}`,l=Wn(a,0),u=[];for(let d of l){let f=d.trim(),h=Math.max(0,n-f.replace(/\x1b\[[0-9;]*m/g,"").length);u.push(` ${w.border("\u2502")} ${f}${" ".repeat(h)} ${w.border("\u2502")}`)}return u.push(` ${w.border("\u2514"+"\u2500".repeat(n+2)+"\u2518")}`),u.join(`
252
- `)}var Fe=class{constructor(e){this.label=e}frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;timer=null;setLabel(e){this.label=e}start(){!Hn||this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${w.accent(this.frames[this.index])} ${w.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(re(e))}};var ar=G.join(Da.homedir(),".hablas","history"),lr=500,yh=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),wh=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],bh=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",".svg",".sql",".png",".jpg",".jpeg",".webp"]),Ma=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],cr=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return Pa.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:lr,completer:e=>this.autocomplete(e)})}async prompt(e){return new Promise(r=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,n=>{let s=n.trim();s&&(this.history.push(s),this.history=this.history.slice(-lr),this.saveHistory()),r(n)})})}async confirm(e){return(await this.prompt(` ${w.warning("?")} ${e} ${w.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
247
+ `}function Ia(){return["",` ${w.strong("Hablas commands")}`,"",` ${w.primary("/help")} ${w.muted("show help")}`,` ${w.primary("/status")} ${w.muted("show current runtime status")}`,` ${w.primary("/model")} ${w.muted("show or switch active model")}`,` ${w.primary("/models")} ${w.muted("list available models (supports search)")}`,` ${w.primary("/provider")} ${w.muted("inspect or switch provider")}`,` ${w.primary("/history")} ${w.muted("show recent turns")}`,` ${w.primary("/clear")} ${w.muted("clear the session")}`,` ${w.primary("/workspace")} ${w.muted("inspect workspace info")}`,` ${w.primary("/doctor")} ${w.muted("run diagnostics")}`,` ${w.primary("/version")} ${w.muted("show version")}`,` ${w.primary("/about")} ${w.muted("show product identity")}`,` ${w.primary("/exit")} ${w.muted("quit")}`,"",` ${w.accent("Tips")}`,` ${w.muted("\u2022 Tab completes commands and common file paths.")}`,` ${w.muted("\u2022 Use #filename to reference files quickly.")}`,` ${w.muted("\u2022 Ctrl+C cancels current work. Ctrl+C twice exits.")}`,""].join(`
248
+ `)}function Pa(t){let e=[` ${w.muted("provider")} ${w.info(t.provider)}`,` ${w.muted("model")} ${w.info(t.model)}`,` ${w.muted("workspace")} ${w.muted(t.workingDir.replace(Vn.homedir(),"~"))}`,` ${w.muted("connected")} ${t.connected?w.success("yes"):w.error("no")}`,` ${w.muted("messages")} ${w.info(String(t.messageCount))}`,t.totalTokens!==void 0?` ${w.muted("tokens")} ${w.info(String(t.totalTokens))}`:""].filter(Boolean);return[""," "+w.strong("Status"),""].concat(e).concat([""]).join(`
249
+ `)}function ne(t){return` ${w.info(t)}`}function Ne(t){return` ${w.success("\u2713")} ${t}`}function ye(t){return` ${w.warning("\u26A0")} ${t}`}function $e(t){return` ${w.error("\u2717")} ${t}`}function Ma(){return` ${w.strong("Hablas")} ${w.accent("v"+Aa)}`}function Da(){return` ${w.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime by Abdulmoin Hablas`}function ja(t,e){let r=Math.max(44,Fe()-8),n=`${t} \xB7 ${e}`,s=Kn(n,0),i=[];i.push(` ${w.border("\u250C"+"\u2500".repeat(r+2)+"\u2510")}`);for(let o of s){let a=o.trim(),l=Math.max(0,r-a.replace(/\x1b\[[0-9;]*m/g,"").length);i.push(` ${w.border("\u2502")} ${w.accent(a)}${" ".repeat(l)} ${w.border("\u2502")}`)}return i.join(`
250
+ `)}function Fa(t,e,r){let n=Math.max(44,Fe()-8),s=t?w.success("\u2713"):w.error("\u2717"),o=e.split(`
251
+ `)[0]?.trim()||""||e.replace(/\s+/g," ").trim()||(t?"done":"failed"),a=`${s} ${o} ${w.muted(`(${r}ms)`)}`,l=Kn(a,0),u=[];for(let d of l){let f=d.trim(),h=Math.max(0,n-f.replace(/\x1b\[[0-9;]*m/g,"").length);u.push(` ${w.border("\u2502")} ${f}${" ".repeat(h)} ${w.border("\u2502")}`)}return u.push(` ${w.border("\u2514"+"\u2500".repeat(n+2)+"\u2518")}`),u.join(`
252
+ `)}var Le=class{constructor(e){this.label=e}frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;timer=null;setLabel(e){this.label=e}start(){!zn||this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${w.accent(this.frames[this.index])} ${w.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(ne(e))}};var ur=J.join(qa.homedir(),".hablas","history"),fr=500,vh=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),kh=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],Ch=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",".svg",".sql",".png",".jpg",".jpeg",".webp"]),La=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],dr=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return Na.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:fr,completer:e=>this.autocomplete(e)})}async prompt(e){return new Promise(r=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,n=>{let s=n.trim();s&&(this.history.push(s),this.history=this.history.slice(-fr),this.saveHistory()),r(n)})})}async confirm(e){return(await this.prompt(` ${w.warning("?")} ${e} ${w.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
253
253
  ${w.error("\u26A0")} ${e}`),console.log(` ${w.muted("Type yes to confirm this dangerous action.")}
254
- `),(await this.prompt(` ${w.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let n=Ma.filter(s=>s.startsWith(e));return[n.length?n:Ma,e]}for(let n of wh)if(e.toLowerCase().includes(n)){let s=e.split(n).pop()??"";if(s&&!s.includes(" "))try{let i=G.dirname(s)||".",o=G.basename(s),a=G.resolve(this.workingDir,i),l=ne.readdirSync(a).filter(u=>u.startsWith(o)).slice(0,8).map(u=>e.slice(0,e.lastIndexOf(s))+G.join(i,u));if(l.length)return[l,e]}catch{}}let r=e.match(/#([\w./-]*)$/);if(r){let n=r[1],s=this.getProjectFiles(),i=s.filter(o=>o.toLowerCase().startsWith(n.toLowerCase())).map(o=>e.slice(0,e.length-r[0].length)+"#"+o);return[i.length?i:s.slice(0,20).map(o=>e.slice(0,e.length-r[0].length)+"#"+o),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let r=[];return this.scanDir(this.workingDir,"",r,3),this.fileCache=r,this.fileCacheTime=e,r}scanDir(e,r,n,s,i=0){if(!(i>=s))try{let o=ne.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||yh.has(a.name))continue;let l=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(G.join(e,a.name),l,n,s,i+1);else{let u=G.extname(a.name).toLowerCase();(bh.has(u)||a.name==="Dockerfile"||a.name==="Makefile")&&n.push(l)}}}catch{}}loadHistory(){try{ne.existsSync(ar)&&(this.history=ne.readFileSync(ar,"utf-8").split(`
255
- `).filter(Boolean).slice(-lr))}catch{}}saveHistory(){try{let e=G.dirname(ar);ne.existsSync(e)||ne.mkdirSync(e,{recursive:!0}),ne.writeFileSync(ar,this.history.slice(-lr).join(`
256
- `),"utf-8")}catch{}}};var Sh={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},_h=`
254
+ `),(await this.prompt(` ${w.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let n=La.filter(s=>s.startsWith(e));return[n.length?n:La,e]}for(let n of kh)if(e.toLowerCase().includes(n)){let s=e.split(n).pop()??"";if(s&&!s.includes(" "))try{let i=J.dirname(s)||".",o=J.basename(s),a=J.resolve(this.workingDir,i),l=se.readdirSync(a).filter(u=>u.startsWith(o)).slice(0,8).map(u=>e.slice(0,e.lastIndexOf(s))+J.join(i,u));if(l.length)return[l,e]}catch{}}let r=e.match(/#([\w./-]*)$/);if(r){let n=r[1],s=this.getProjectFiles(),i=s.filter(o=>o.toLowerCase().startsWith(n.toLowerCase())).map(o=>e.slice(0,e.length-r[0].length)+"#"+o);return[i.length?i:s.slice(0,20).map(o=>e.slice(0,e.length-r[0].length)+"#"+o),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let r=[];return this.scanDir(this.workingDir,"",r,3),this.fileCache=r,this.fileCacheTime=e,r}scanDir(e,r,n,s,i=0){if(!(i>=s))try{let o=se.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||vh.has(a.name))continue;let l=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(J.join(e,a.name),l,n,s,i+1);else{let u=J.extname(a.name).toLowerCase();(Ch.has(u)||a.name==="Dockerfile"||a.name==="Makefile")&&n.push(l)}}}catch{}}loadHistory(){try{se.existsSync(ur)&&(this.history=se.readFileSync(ur,"utf-8").split(`
255
+ `).filter(Boolean).slice(-fr))}catch{}}saveHistory(){try{let e=J.dirname(ur);se.existsSync(e)||se.mkdirSync(e,{recursive:!0}),se.writeFileSync(ur,this.history.slice(-fr).join(`
256
+ `),"utf-8")}catch{}}};var $h={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},Th=`
257
257
  ## Reasoning Protocol
258
258
 
259
259
  Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
@@ -282,15 +282,15 @@ After receiving a tool result, think again:
282
282
  - One tool call per turn. Wait for the result before the next call.
283
283
  - If a tool fails, analyze the error in <thinking> before retrying.
284
284
  - When done, give a concise final answer WITHOUT <thinking> tags.
285
- `.trim(),xh=`
285
+ `.trim(),Ah=`
286
286
  ## Reasoning
287
287
  For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
288
288
  The user will NOT see thinking blocks. One tool call per turn.
289
- `.trim(),Vn=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...Sh,...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}
289
+ `.trim(),Gn=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...$h,...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}
290
290
 
291
- ${xh}`:`${e}
291
+ ${Ah}`:`${e}
292
292
 
293
- ${_h}`}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(`
293
+ ${Th}`}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(`
294
294
 
295
295
  `).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`
296
296
  <self_eval>
@@ -313,18 +313,18 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
313
313
  }
314
314
  </self_eval>
315
315
  `.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(`
316
- `)}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 vt(t){return new Vn(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}],zn=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(`
317
- `)}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 kt(t=3){return new zn(t)}var we=C(require("fs")),fr=C(require("path")),Fa=C(require("os")),ur=fr.join(Fa.homedir(),".hablas","model-formats.json");function kh(){try{if(we.existsSync(ur))return JSON.parse(we.readFileSync(ur,"utf-8"))}catch{}return{}}function Ch(t){try{let e=fr.dirname(ur);we.existsSync(e)||we.mkdirSync(e,{recursive:!0}),we.writeFileSync(ur,JSON.stringify(t,null,2),"utf-8")}catch{}}function La(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 Ct(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 $h(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Th(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=Ct(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function Ah(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=Ct(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function Eh(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=ja(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function ja(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","web_search","scrape_url","extract_links","read_pdf","pdf_metadata","execute_code","detect_bugs","download_asset"];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 h=d[1].toLowerCase(),p=d[2]??d[3]??d[4];l[h]=$h(p)}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 Oh(t){return ja(t)}function Rh(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=Ct(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function Ih(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=La(t,n.index);if(s)try{let i=JSON.parse(s),o=Ct(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function Mh(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=La(t,n.index);if(s)try{let i=JSON.parse(s),o=Ct(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function Ph(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(),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: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 Kn=[{format:"xml_tool_call_wrapper",parse:Eh},{format:"xml_prompt",parse:Oh},{format:"xml_tags",parse:Th},{format:"xml_parameters",parse:Ph},{format:"hermes",parse:Ah},{format:"markdown_json",parse:Rh},{format:"function_call",parse:Ih},{format:"json_object",parse:Mh}],Jn=class{registry;constructor(){this.registry=kh()}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=Kn.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 Kn){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:this.sanitizeResidualToolMarkup(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|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset)[\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 Kn)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()},Ch(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=this.sanitizeResidualToolMarkup(s),s=s.replace(/\n{3,}/g,`
316
+ `)}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 Ct(t){return new Gn(t)}var Eh=[{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}],Jn=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 Eh)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(`
317
+ `)}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 $t(t=3){return new Jn(t)}var we=k(require("fs")),hr=k(require("path")),Ua=k(require("os")),pr=hr.join(Ua.homedir(),".hablas","model-formats.json");function Oh(){try{if(we.existsSync(pr))return JSON.parse(we.readFileSync(pr,"utf-8"))}catch{}return{}}function Rh(t){try{let e=hr.dirname(pr);we.existsSync(e)||we.mkdirSync(e,{recursive:!0}),we.writeFileSync(pr,JSON.stringify(t,null,2),"utf-8")}catch{}}function Ba(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 Tt(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 Ih(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Ph(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=Tt(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function Mh(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=Tt(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function Dh(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=Ha(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function Ha(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","web_search","scrape_url","extract_links","read_pdf","pdf_metadata","execute_code","detect_bugs","download_asset"];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 h=d[1].toLowerCase(),p=d[2]??d[3]??d[4];l[h]=Ih(p)}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 jh(t){return Ha(t)}function Fh(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=Tt(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function Lh(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=Ba(t,n.index);if(s)try{let i=JSON.parse(s),o=Tt(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function Nh(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=Ba(t,n.index);if(s)try{let i=JSON.parse(s),o=Tt(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function qh(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(),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: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 Xn=[{format:"xml_tool_call_wrapper",parse:Dh},{format:"xml_prompt",parse:jh},{format:"xml_tags",parse:Ph},{format:"xml_parameters",parse:qh},{format:"hermes",parse:Mh},{format:"markdown_json",parse:Fh},{format:"function_call",parse:Lh},{format:"json_object",parse:Nh}],Zn=class{registry;constructor(){this.registry=Oh()}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=Xn.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 Xn){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:this.sanitizeResidualToolMarkup(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|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset)[\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 Xn)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()},Rh(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=this.sanitizeResidualToolMarkup(s),s=s.replace(/\n{3,}/g,`
318
318
 
319
319
  `),{toolCalls:n,displayContent:s.trim(),format:e[0]?.format??"unknown"}}sanitizeResidualToolMarkup(e){return e.replace(/<<?tool[-_]call[\s\S]*?<<?\/tool[-_]call\s*>>?/gi,"").replace(/<function=[^>]+>/gi,"").replace(/<parameter=[^>]+>/gi,"").replace(/<\/parameter>/gi,"").replace(/```tool_call[\s\S]*?```/gi,"").replace(/<<?(?: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|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset)[\s\S]*?(?:<<?\/[a-z_]+>>?|\/>)/gi,"").replace(/\n{3,}/g,`
320
320
 
321
- `)}},Gn=null;function Na(){return Gn||(Gn=new Jn),Gn}var Dh=600,Fh=2e3,qa=2;function Lh(t,e,r){let s=Na().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function jh(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 Nh(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 Ua(t,e,r,n){let s=0,i=Date.now();for(;s<=qa;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=qa)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 Xn(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??vt(),h=t.errorRecovery??kt(),p=d?[]:n.getOllamaTools(),c=r.getModel(),m=t.maxIterations??Dh,y=[],S=[],b=[],x=new Map,_="",k=0,A=!1;for(;k<m;){if(k++,u?.aborted)return{output:_,toolsUsed:$e(y),toolResults:S,touchedFiles:$e(b),iterations:k,success:!1,error:"Aborted",completedNaturally:A};let T=f.buildBudgetWarningPrompt();T&&s.addUserMessage(T,{priority:"critical",tags:["system-budget"]});let R;try{R=await r.chatWithTools(s.getMessages(),p,u)}catch(K){let X=K;if(X.name==="AbortError"||u?.aborted)return{output:_,toolsUsed:$e(y),toolResults:S,touchedFiles:$e(b),iterations:k,success:!1,error:"Aborted",completedNaturally:A};if(k<=1){a.onNotice?.(`Transient model error: ${X.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(D=>setTimeout(D,1e3)),k--;continue}return a.onError?.(X.message??"Model request failed"),{output:_,toolsUsed:$e(y),toolResults:S,touchedFiles:$e(b),iterations:k,success:!1,error:X.message,completedNaturally:A}}let $=R.message?.content||"",P=R.message?.tool_calls,N=f.parseThinking($);N.hasThinking&&(f.recordStep({thought:N.thinking}),o.debug({thinking:N.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:F,displayContent:B}=Lh(P,$,c);if(B&&B.trim()&&(_=B,await a.onAssistantText?.(B,e)),F.length===0){s.addAssistantMessage($,void 0,e.role),A=!0;break}s.addAssistantMessage($,F,e.role);let W=F.length;for(let K=0;K<F.length;K++){let X=F[K];if(!X?.function?.name)continue;let D=X.function.name,q=X.function.arguments||{},Tt=n.getSafetyLevel(D)??"confirm";if(!n.get(D)){a.onNotice?.(`Unknown tool: ${D} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${D}". Available: ${n.getAll().map(de=>de.name).join(", ")}`);continue}if(await l(D,Tt,q)==="skip"){s.addToolMessage(`Tool ${D} was skipped by policy/user.`);break}let ll=jh(D,q),yr=D==="read_file"?JSON.stringify({path:q.path||"",start:q.start_line||"",end:q.end_line||""}):"";if(D==="read_file"&&yr&&x.has(yr)){let de=x.get(yr)||"";s.addToolMessage(de),f.recordObservation(de.slice(0,300),"Reused cached file read");continue}y.push(D),typeof q.path=="string"&&b.push(q.path),typeof q.from=="string"&&b.push(q.from),typeof q.to=="string"&&b.push(q.to),a.onToolStart?.(D,ll,q),a.onToolCall?.(),f.recordStep({thought:N.hasThinking?`Executing: ${D}`:"",action:D,actionInput:q});let V=await Ua(n,D,q,o);a.onToolEnd?.(D,V.success,V.error||V.output,V.duration,q);let Ne;if(V.success)Ne=Ba(D,V.output),f.recordObservation(Ne.slice(0,300)),S.push({tool:D,success:!0,summary:V.output.slice(0,150)});else{let de=V.error||"Unknown error",qe=h.analyze(D,de,q);if(Ne=h.buildRecoveryMessage(qe,de),f.recordObservation(`FAILED: ${de}`,`Recovery: ${qe.strategy} \u2014 ${qe.suggestion}`),o.info({tool:D,errorClass:qe.errorClass,strategy:qe.strategy},"Error recovery analysis"),S.push({tool:D,success:!1,summary:de.slice(0,150)}),qe.autoRetry&&!f.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let Ue=await Ua(n,D,q,o);a.onToolEnd?.(D,Ue.success,Ue.output,Ue.duration,q),Ue.success&&(Ne=Ba(D,Ue.output),f.recordObservation(Ne.slice(0,300),"Auto-retry succeeded"),S[S.length-1]={tool:D,success:!0,summary:Ue.output.slice(0,150)})}}if(s.addToolMessage(Ne),V.success&&D==="read_file"&&typeof q.path=="string"&&i?.addFile(q.path,V.output),o.info({tool:D,success:V.success,durationMs:V.duration,retries:V.retries},"Tool executed"),!V.success&&Nh(V.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}W>1&&K<W-1}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return k>=m&&!A&&a.onNotice?.(`Reached max iterations (${m}). Stopping.`,"warn"),o.info({summary:f.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:_,toolsUsed:$e(y),toolResults:S,touchedFiles:$e(b),iterations:k,success:!0,completedNaturally:A}}function $e(t){return[...new Set(t)]}function Ba(t,e){return t==="read_file"?e:t==="web_search"||t==="scrape_url"||t==="extract_links"||t==="read_pdf"?bt(e,LARGE_WEB_RESULT_TOKENS):bt(e,Fh)}function Ha(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 Wa(t){let{client:e,session:r,abortSignal:n,onStart:s,onChunk:i,onComplete:o}=t,a="",l=null;for(let u=0;u<2;u++)try{a="";for await(let d of e.streamChat(r.getMessages(),n))a+=d,i?.(d);return r.addAssistantMessage(a||""),a}catch(d){if(l=d,d?.name==="AbortError"||n?.aborted)throw d;if(u===1)break}throw l||new Error("Text turn failed")}async function dr(t,e){let r=xa(t),n=await it(e.workingDir,e.config);if(e.session.updateSystemPrompt(ot(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 f=new Fe("Hablas is thinking"),h=!1;f.start();try{let p=await Wa({client:e.client,session:e.session,onStart:()=>{f.start()},onChunk:c=>{h||(f.stop(),console.log(at()),process.stdout.write(" "),h=!0),process.stdout.write(c)},onComplete:()=>{h&&process.stdout.write(`
322
- `)}});h||(f.stop(),console.log(at()),console.log(xt(p)));return}catch(p){f.stop(),console.log(Ce(p?.message||"Text turn failed"));return}}let s=vt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=kt(3),o=[],a=new Fe("Hablas is thinking"),l={onModelStart:f=>{a.stop(),a.setLabel(f),a.start()},onModelStop:()=>{a.stop()},onAssistantText:async f=>{o.push(f),r.profile.kind!=="implementation"&&(console.log(at()),console.log(xt(f)))},onToolStart:(f,h)=>{a.stop(),console.log(Ra(f,h))},onToolEnd:(f,h,p,c)=>{console.log(Ia(h,p,c))},onNotice:(f,h)=>{console.log(h==="retry"?re(`Retrying: ${f}`):re(f))},onError:f=>{console.log(Ce(f))},onToolCall:()=>e.onToolCall?.()},u=Ha({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?f=>e.input.confirm(f):void 0,confirmDangerous:e.input?f=>e.input.confirmDangerous(f):void 0}),d=await Xn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:l,safetyPolicy:u,reactEngine:s,errorRecovery:i,skipTools:!1});if(r.profile.kind==="implementation"&&d.toolsUsed.length>0&&o.length>0&&(console.log(at()),console.log(xt(o[o.length-1]))),r.profile.kind==="implementation"&&d.toolsUsed.length===0){e.session.addUserMessage("SYSTEM CORRECTION: This was an implementation request. You must use workspace tools, inspect files, and create or modify actual files instead of only replying with inline code. Retry now using tools.",{priority:"critical",tags:["system-correction","force-tools"]});let f=[];(await Xn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...l,onAssistantText:async p=>{f.push(p)}},safetyPolicy:u,reactEngine:vt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:kt(3),skipTools:!1})).toolsUsed.length===0?console.log(Ce("Implementation request failed to enter a real tool-execution path. Refusing to present inline-code-only output as a completed result.")):f.length>0&&(console.log(at()),console.log(xt(f[f.length-1])))}}var Yn=C(require("fs")),Va=C(require("path")),le=C(require("os")),za=require("child_process");async function pr(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(le.homedir(),".hablas");if(e.push({name:"Config directory",status:Yn.existsSync(s)?"ok":"warn",message:Yn.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=le.homedir();if(process.platform!=="win32"){let a=(0,za.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:`${le.platform()} ${le.arch()} \u2014 ${le.cpus().length} cores, ${Math.round(le.totalmem()/1024/1024/1024)}GB RAM`}),e}function hr(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(`
323
- `)}async function Ka(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Ta());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Oa());return;case"/version":console.log(Ea());return;case"/clear":e.session.clear(),console.log(Le("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(re("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(Aa({model:e.client.getModel(),provider:Je(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(re(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),We(e.config),console.log(Le(`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(ye("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(re(`Provider: ${Je(e.config)}`)),console.log(re(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Le("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=ce.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=ce.defaultModel);else if(i==="custom"){if(!s[1]){console.log(ye("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(ye("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=Ge(e.config);e.setClient(o),We(e.config),console.log(Le(`Provider switched to ${Je(e.config)}`));return}case"/doctor":{let i=await pr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(hr(i));return}case"/workspace":{console.log(""),console.log(nr(nt(e.workingDir))),console.log("");return}default:console.log(ye(`Unknown command: ${n}`))}}async function Xa(t,e){gs();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=Ge(t),s=new Qe(r,t),i=new et(t),o=await it(r,t),a=new rt(ot(o,_t("hello")),t.historySize),l=new cr(r);console.log(Ca(t.model,r)),Ga.existsSync(Ja.join(r,".git"))||console.log(ye("Not in a Git repository. Versioning and auto-sync features are limited."));let u=new Fe("Connecting");u.start();let d=await n.checkConnection();if(u.stop(d?"ready":"offline"),d){let y=await n.listModels();console.log(Le(`Connected \xB7 ${y.length} models available`))}else console.log(ye(`Connection failed for ${Je(t)}. You can still inspect local files and switch provider with /provider.`));console.log(re("Hablas is ready. Single-agent runtime active.")),console.log("");let f=0,h=0,p=Date.now(),c=new AbortController,m=0;for(process.on("SIGINT",()=>{let y=Date.now();y-m<1500&&(console.log(""),console.log(re(`Session summary \xB7 turns=${f} \xB7 toolCalls=${h} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),m=y,c.abort(),c=new AbortController,console.log(""),console.log(ye("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let S=(await l.prompt(" \u203A ")).trim();if(S){if(S.startsWith("/")){if(await Ka(S,{config:t,client:n,setClient:x=>{n=x},session:a,workingDir:r})==="quit")break;continue}f+=1,console.log($a(f)),c=new AbortController;try{await dr(S,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{h+=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 Ya(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=Ge(e),i=new Qe(n,e),o=new et(e),a=await it(n,e),l=new rt(ot(a,_t(t)),e.historySize);await dr(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1})}var mr=C(require("fs")),je=C(require("path")),qh=[{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"}],Uh=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Bh=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function Hh(t,e){let r=[],n=e.split(`
324
- `);for(let{pattern:s,name:i,severity:o}of qh){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let u=e.substring(0,a.index).split(`
325
- `).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 Wh(t,e){let r=[],n=e.split(`
326
- `),s=je.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 Za(t,e=[]){try{let r=mr.readdirSync(t,{withFileTypes:!0});for(let n of r){if(Uh.has(n.name))continue;let s=je.join(t,n.name);if(n.isDirectory())Za(s,e);else if(n.isFile()){let i=je.extname(n.name);Bh.has(i)||e.push(s)}}}catch{}return e}function Qa(t){let e=Date.now(),r=Za(t),n=[];for(let o of r)try{let a=mr.readFileSync(o,"utf-8"),l=je.relative(t,o),u=Hh(l,a);n.push(...u);let d=Wh(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 el(t){let e=[];if(e.push(`
321
+ `)}},Yn=null;function Wa(){return Yn||(Yn=new Zn),Yn}var Uh=600,Bh=2e3,Hh=12e3,Va=2;function Wh(t,e,r){let s=Wa().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function Vh(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 zh(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 za(t,e,r,n){let s=0,i=Date.now();for(;s<=Va;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=Va)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 Qn(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??Ct(),h=t.errorRecovery??$t(),p=d?[]:n.getOllamaTools(),c=r.getModel(),m=t.maxIterations??Uh,y=[],S=[],b=[],_=new Map,x="",C=0,A=!1;for(;C<m;){if(C++,u?.aborted)return{output:x,toolsUsed:Te(y),toolResults:S,touchedFiles:Te(b),iterations:C,success:!1,error:"Aborted",completedNaturally:A};let T=f.buildBudgetWarningPrompt();T&&s.addUserMessage(T,{priority:"critical",tags:["system-budget"]});let R;try{a.onModelStart?.(S.length>0?"Hablas is deciding the next step":"Hablas is thinking",e),R=await r.chatWithTools(s.getMessages(),p,u),a.onModelStop?.()}catch(G){a.onModelStop?.();let Y=G;if(Y.name==="AbortError"||u?.aborted)return{output:x,toolsUsed:Te(y),toolResults:S,touchedFiles:Te(b),iterations:C,success:!1,error:"Aborted",completedNaturally:A};if(C<=1){a.onNotice?.(`Transient model error: ${Y.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(M=>setTimeout(M,1e3)),C--;continue}return a.onError?.(Y.message??"Model request failed"),{output:x,toolsUsed:Te(y),toolResults:S,touchedFiles:Te(b),iterations:C,success:!1,error:Y.message,completedNaturally:A}}let $=R.message?.content||"",D=R.message?.tool_calls,q=f.parseThinking($);q.hasThinking&&(f.recordStep({thought:q.thinking}),o.debug({thinking:q.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:F,displayContent:B}=Wh(D,$,c);if(B&&B.trim()&&(x=B,await a.onAssistantText?.(B,e)),F.length===0){s.addAssistantMessage($,void 0,e.role),A=!0;break}s.addAssistantMessage($,F,e.role);let W=F.length;for(let G=0;G<F.length;G++){let Y=F[G];if(!Y?.function?.name)continue;let M=Y.function.name,j=Y.function.arguments||{},Ot=n.getSafetyLevel(M)??"confirm";if(!n.get(M)){a.onNotice?.(`Unknown tool: ${M} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${M}". Available: ${n.getAll().map(z=>z.name).join(", ")}`);continue}if(await l(M,Ot,j)==="skip"){s.addToolMessage(`Tool ${M} was skipped by policy/user.`);break}let hl=Vh(M,j),ut=M==="read_file"?JSON.stringify({path:j.path||"",start:j.start_line||"",end:j.end_line||""}):"";if(M==="read_file"&&ut&&_.has(ut)){let z=_.get(ut)||"";s.addToolMessage(z),f.recordObservation(z.slice(0,300),"Reused cached file read");continue}y.push(M),typeof j.path=="string"&&b.push(j.path),typeof j.from=="string"&&b.push(j.from),typeof j.to=="string"&&b.push(j.to),a.onToolStart?.(M,hl,j),a.onToolCall?.(),f.recordStep({thought:q.hasThinking?`Executing: ${M}`:"",action:M,actionInput:j});let V=await za(n,M,j,o);a.onToolEnd?.(M,V.success,V.error||V.output,V.duration,j);let Ae;if(V.success)Ae=Ka(M,V.output),f.recordObservation(Ae.slice(0,300)),S.push({tool:M,success:!0,summary:V.output.slice(0,150)});else{let z=V.error||"Unknown error",Ue=h.analyze(M,z,j);if(Ae=h.buildRecoveryMessage(Ue,z),f.recordObservation(`FAILED: ${z}`,`Recovery: ${Ue.strategy} \u2014 ${Ue.suggestion}`),o.info({tool:M,errorClass:Ue.errorClass,strategy:Ue.strategy},"Error recovery analysis"),S.push({tool:M,success:!1,summary:z.slice(0,150)}),Ue.autoRetry&&!f.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let Be=await za(n,M,j,o);a.onToolEnd?.(M,Be.success,Be.output,Be.duration,j),Be.success&&(Ae=Ka(M,Be.output),f.recordObservation(Ae.slice(0,300),"Auto-retry succeeded"),S[S.length-1]={tool:M,success:!0,summary:Be.output.slice(0,150)})}}if(s.addToolMessage(Ae),V.success&&M==="read_file"&&typeof j.path=="string"&&(i?.addFile(j.path,V.output),ut&&_.set(ut,Ae)),V.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(M)&&typeof j.path=="string")for(let z of[..._.keys()])z.includes(`"path":"${String(j.path).replace(/\"/g,'\\"')}"`)&&_.delete(z);if(V.success&&M==="move_file")for(let z of[..._.keys()])(j.from&&z.includes(`"path":"${String(j.from).replace(/\"/g,'\\"')}"`)||j.to&&z.includes(`"path":"${String(j.to).replace(/\"/g,'\\"')}"`))&&_.delete(z);if(o.info({tool:M,success:V.success,durationMs:V.duration,retries:V.retries},"Tool executed"),!V.success&&zh(V.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}W>1&&G<W-1}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return C>=m&&!A&&a.onNotice?.(`Reached max iterations (${m}). Stopping.`,"warn"),o.info({summary:f.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:x,toolsUsed:Te(y),toolResults:S,touchedFiles:Te(b),iterations:C,success:!0,completedNaturally:A}}function Te(t){return[...new Set(t)]}function Ka(t,e){return t==="read_file"?e:t==="web_search"||t==="scrape_url"||t==="extract_links"||t==="read_pdf"?_t(e,Hh):_t(e,Bh)}function Ga(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 Ja(t){let{client:e,session:r,abortSignal:n,onStart:s,onChunk:i,onComplete:o}=t,a="",l=null;for(let u=0;u<2;u++)try{a="";for await(let d of e.streamChat(r.getMessages(),n))a+=d,i?.(d);return r.addAssistantMessage(a||""),a}catch(d){if(l=d,d?.name==="AbortError"||n?.aborted)throw d;if(u===1)break}throw l||new Error("Text turn failed")}async function mr(t,e){let r=Ta(t),n=await ot(e.workingDir,e.config);if(e.session.updateSystemPrompt(at(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 f=new Le("Hablas is thinking"),h=!1;f.start();try{let p=await Ja({client:e.client,session:e.session,onStart:()=>{f.start()},onChunk:c=>{h||(f.stop(),console.log(lt()),process.stdout.write(" "),h=!0),process.stdout.write(c)},onComplete:()=>{h&&process.stdout.write(`
322
+ `)}});h||(f.stop(),console.log(lt()),console.log(kt(p)));return}catch(p){f.stop(),console.log($e(p?.message||"Text turn failed"));return}}let s=Ct({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=$t(3),o=[],a=new Le("Hablas is thinking"),l={onModelStart:f=>{a.stop(),a.setLabel(f),a.start()},onModelStop:()=>{a.stop()},onAssistantText:async f=>{o.push(f),r.profile.kind!=="implementation"&&(console.log(lt()),console.log(kt(f)))},onToolStart:(f,h)=>{a.stop(),console.log(ja(f,h))},onToolEnd:(f,h,p,c)=>{console.log(Fa(h,p,c))},onNotice:(f,h)=>{console.log(h==="retry"?ne(`Retrying: ${f}`):ne(f))},onError:f=>{console.log($e(f))},onToolCall:()=>e.onToolCall?.()},u=Ga({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?f=>e.input.confirm(f):void 0,confirmDangerous:e.input?f=>e.input.confirmDangerous(f):void 0}),d=await Qn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:l,safetyPolicy:u,reactEngine:s,errorRecovery:i,skipTools:!1});if(r.profile.kind==="implementation"&&d.toolsUsed.length>0&&o.length>0&&(console.log(lt()),console.log(kt(o[o.length-1]))),r.profile.kind==="implementation"&&d.toolsUsed.length===0){e.session.addUserMessage("SYSTEM CORRECTION: This was an implementation request. You must use workspace tools, inspect files, and create or modify actual files instead of only replying with inline code. Retry now using tools.",{priority:"critical",tags:["system-correction","force-tools"]});let f=[];(await Qn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...l,onAssistantText:async p=>{f.push(p)}},safetyPolicy:u,reactEngine:Ct({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:$t(3),skipTools:!1})).toolsUsed.length===0?console.log($e("Implementation request failed to enter a real tool-execution path. Refusing to present inline-code-only output as a completed result.")):f.length>0&&(console.log(lt()),console.log(kt(f[f.length-1])))}}var es=k(require("fs")),Xa=k(require("path")),ce=k(require("os")),Ya=require("child_process");async function gr(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=Xa.join(ce.homedir(),".hablas");if(e.push({name:"Config directory",status:es.existsSync(s)?"ok":"warn",message:es.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=ce.homedir();if(process.platform!=="win32"){let a=(0,Ya.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:`${ce.platform()} ${ce.arch()} \u2014 ${ce.cpus().length} cores, ${Math.round(ce.totalmem()/1024/1024/1024)}GB RAM`}),e}function yr(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(`
323
+ `)}async function Za(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Ia());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Da());return;case"/version":console.log(Ma());return;case"/clear":e.session.clear(),console.log(Ne("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(ne("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(Pa({model:e.client.getModel(),provider:Xe(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(ne(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),Ve(e.config),console.log(Ne(`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(ye("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(ne(`Provider: ${Xe(e.config)}`)),console.log(ne(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Ne("Connection OK"):$e("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=ue.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=ue.defaultModel);else if(i==="custom"){if(!s[1]){console.log(ye("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(ye("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=Je(e.config);e.setClient(o),Ve(e.config),console.log(Ne(`Provider switched to ${Xe(e.config)}`));return}case"/doctor":{let i=await gr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(yr(i));return}case"/workspace":{console.log(""),console.log(or(st(e.workingDir))),console.log("");return}default:console.log(ye(`Unknown command: ${n}`))}}var be=k(require("fs")),ts=k(require("path"));function rs(t){let e=ts.join(t,".hablas");return be.existsSync(e)||be.mkdirSync(e,{recursive:!0}),e}function Qa(t){return ts.join(rs(t),"session.json")}function wr(t,e){let r=Qa(t);try{return be.existsSync(r)?(e.fromJSON(be.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function At(t,e){let r=Qa(t);try{be.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}async function rl(t,e){_s();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=Je(t);rs(r);let s=new et(r,t),i=new tt(t),o=await ot(r,t),a=new nt(at(o,vt("hello")),t.historySize,t.contextBudget);wr(r,a);let l=new dr(r);console.log(Oa(t.model,r)),el.existsSync(tl.join(r,".git"))||console.log(ye("Not in a Git repository. Versioning and auto-sync features are limited."));let u=new Le("Connecting");u.start();let d=await n.checkConnection();if(u.stop(d?"ready":"offline"),d){let y=await n.listModels();console.log(Ne(`Connected \xB7 ${y.length} models available`))}else console.log(ye(`Connection failed for ${Xe(t)}. You can still inspect local files and switch provider with /provider.`));console.log(ne("Hablas is ready. Single-agent runtime active.")),console.log("");let f=0,h=0,p=Date.now(),c=new AbortController,m=0;for(process.on("SIGINT",()=>{let y=Date.now();y-m<1500&&(console.log(""),console.log(ne(`Session summary \xB7 turns=${f} \xB7 toolCalls=${h} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),m=y,c.abort(),c=new AbortController,console.log(""),console.log(ye("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let S=(await l.prompt(" \u203A ")).trim();if(S){if(S.startsWith("/")){let b=await Za(S,{config:t,client:n,setClient:_=>{n=_},session:a,workingDir:r});if(At(r,a),b==="quit")break;continue}f+=1,console.log(Ra(f)),c=new AbortController;try{await mr(S,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{h+=1}}),At(r,a)}catch(b){if(b?.name==="AbortError")continue;console.log($e(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}l.close()}async function nl(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=Je(e),i=new et(n,e),o=new tt(e),a=await ot(n,e),l=new nt(at(a,vt(t)),e.historySize,e.contextBudget);wr(n,l),await mr(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1}),At(n,l)}var br=k(require("fs")),qe=k(require("path")),Kh=[{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"}],Gh=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Jh=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function Xh(t,e){let r=[],n=e.split(`
324
+ `);for(let{pattern:s,name:i,severity:o}of Kh){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let u=e.substring(0,a.index).split(`
325
+ `).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 Yh(t,e){let r=[],n=e.split(`
326
+ `),s=qe.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 sl(t,e=[]){try{let r=br.readdirSync(t,{withFileTypes:!0});for(let n of r){if(Gh.has(n.name))continue;let s=qe.join(t,n.name);if(n.isDirectory())sl(s,e);else if(n.isFile()){let i=qe.extname(n.name);Jh.has(i)||e.push(s)}}}catch{}return e}function il(t){let e=Date.now(),r=sl(t),n=[];for(let o of r)try{let a=br.readFileSync(o,"utf-8"),l=qe.relative(t,o),u=Xh(l,a);n.push(...u);let d=Yh(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 ol(t){let e=[];if(e.push(`
327
327
  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(`
328
- `)}var lt=C(require("fs")),Zn=C(require("path")),rl=C(require("os")),Vh=Zn.join(rl.homedir(),".hablas"),tl=Zn.join(Vh,"analytics.json");function nl(){try{if(lt.existsSync(tl))return JSON.parse(lt.readFileSync(tl,"utf-8"))}catch{}return zh()}function zh(){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 sl(t){let e=[];e.push(`
328
+ `)}var ct=k(require("fs")),ns=k(require("path")),ll=k(require("os")),Zh=ns.join(ll.homedir(),".hablas"),al=ns.join(Zh,"analytics.json");function cl(){try{if(ct.existsSync(al))return JSON.parse(ct.readFileSync(al,"utf-8"))}catch{}return Qh()}function Qh(){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 ul(t){let e=[];e.push(`
329
329
  \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(`
330
- `)}var il=C(require("readline"));var z="\x1B[36m",gr="\x1B[32m",be="\x1B[33m",M="\x1B[2m",Se="\x1B[1m",v="\x1B[0m",Kh="\x1B[35m";function H(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function Gh(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var $t={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function ol(t){let e=il.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${Se}${z} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${v}`),console.log(`${Se}${z} hablas \u2014 Setup Wizard${v}`),console.log(`${M} Configure your AI provider and model${v}`),console.log(`${Se}${z} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${v}`),console.log(),console.log(`${Se} Choose your setup:${v}`),console.log(),console.log(` ${Kh}${Se}1${v}. ${Se}Hablas Integrated Engine${v} ${gr}(instant \u2014 no setup needed)${v}`),console.log(` ${M}Pre-configured cloud AI, ready to use immediately${v}`),console.log(),console.log(` ${z}${Se}2${v}. ${Se}Custom Provider${v} ${M}(bring your own API key)${v}`),console.log(` ${M}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${v}`),console.log(),(await H(e,` ${M}Your choice (1-2):${v} `)).trim()){case"1":{t.provider=$t.provider,t.apiUrl=$t.apiUrl,t.apiKey=Gh(),t.model=$t.model,We(t),console.log(),console.log(`${gr} \u2713 Hablas Integrated Engine activated!${v}`),console.log(`${M} Model: ${$t.model}${v}`),console.log(`${M} API: ${$t.apiUrl}${v}`),console.log(`${M} No API key needed \u2014 everything is pre-configured.${v}`);break}case"2":{switch(console.log(),console.log(`${M} Select your provider:${v}`),console.log(` ${z}a${v}. Ollama (local, free, private)`),console.log(` ${z}b${v}. OpenAI API`),console.log(` ${z}c${v}. Groq (fast, free tier)`),console.log(` ${z}d${v}. OpenRouter (many models)`),console.log(` ${z}e${v}. Together AI`),console.log(` ${z}f${v}. DeepSeek`),console.log(` ${z}g${v}. Custom OpenAI-compatible API`),console.log(` ${z}h${v}. NVIDIA NIM (powerful cloud models)`),console.log(),(await H(e,` ${M}Your choice (a-h):${v} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await H(e,` ${M}Ollama host [http://localhost:11434]:${v} `)).trim(),i=(await H(e,` ${M}Model [qwen2.5-coder:7b]:${v} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await H(e,` ${M}OpenAI API Key (sk-...):${v} `)).trim(),i=(await H(e,` ${M}Model [gpt-4o]:${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.openai.com/v1",t.apiKey=s,t.model=i||"gpt-4o";break}case"c":{let s=(await H(e,` ${M}Groq API Key (gsk_...):${v} `)).trim(),i=(await H(e,` ${M}Model [llama-3.3-70b-versatile]:${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.groq.com/openai/v1",t.apiKey=s,t.model=i||"llama-3.3-70b-versatile";break}case"d":{let s=(await H(e,` ${M}OpenRouter API Key (sk-or-...):${v} `)).trim(),i=(await H(e,` ${M}Model [anthropic/claude-3.5-sonnet]:${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://openrouter.ai/api/v1",t.apiKey=s,t.model=i||"anthropic/claude-3.5-sonnet";break}case"e":{let s=(await H(e,` ${M}Together API Key:${v} `)).trim(),i=(await H(e,` ${M}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.together.xyz/v1",t.apiKey=s,t.model=i||"meta-llama/Llama-3.3-70B-Instruct-Turbo";break}case"f":{let s=(await H(e,` ${M}DeepSeek API Key:${v} `)).trim(),i=(await H(e,` ${M}Model [deepseek-chat]:${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.deepseek.com/v1",t.apiKey=s,t.model=i||"deepseek-chat";break}case"g":{let s=(await H(e,` ${M}API base URL:${v} `)).trim(),i=(await H(e,` ${M}API key (optional):${v} `)).trim(),o=(await H(e,` ${M}Model ID:${v} `)).trim();if(!s){console.log(`${be} \u26A0 URL is required \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await H(e,` ${M}NVIDIA API Key (nvapi-...):${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),console.log(`${M} Get your key at: https://build.nvidia.com/${v}`),e.close();return}console.log(),console.log(`${M} Available NVIDIA models:${v}`),ce.models.forEach((a,l)=>{console.log(` ${z}${l+1}${v}. ${a}`)}),console.log();let i=(await H(e,` ${M}Model number [1]:${v} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=ce.apiUrl,t.apiKey=s,t.model=ce.models[o]||ce.defaultModel;break}default:console.log(`${be} \u26A0 Invalid choice${v}`),e.close();return}We(t),console.log(),console.log(`${gr} \u2713 Custom provider configured successfully${v}`),console.log(`${M} Provider: ${t.provider}${v}`),console.log(`${M} Model: ${t.model}${v}`);break}default:console.log(`${be} \u26A0 Invalid choice \u2014 please select 1 or 2${v}`),e.close();return}console.log(),console.log(`${Se}${gr} \u2713 Setup complete!${v}`),console.log(`${M} Use ${z}hablas${v}${M} for interactive mode or ${z}hablas run "..."${v}${M} for one-shot execution.${v}`),console.log(),e.close()}var al=Eo(),J=new hs;J.name("hablas").description(`Hablas CLI v${al} \u2014 single-agent engineering runtime for the terminal.`).version(al).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");J.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=J.opts(),r=He({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=On(r);await Ya(t,r,n)});J.command("doctor").description("Run system diagnostics").action(async()=>{let t=J.opts(),e=He({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await pr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(hr(r))});J.command("info").description("Show workspace information").action(async()=>{let t=J.opts(),e=He({project:t.project});console.log(""),console.log(nr(nt(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});J.command("security").description("Run a security scan on the current project").action(async()=>{let t=J.opts(),e=He({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(el(Qa(r)))});J.command("stats").description("Show local usage statistics").action(async()=>{console.log(sl(nl()))});J.action(async()=>{let t=J.opts(),e=He({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 ol(e);return}let r=On(e);await Xa(e,r)});J.parse();
330
+ `)}var fl=k(require("readline"));var K="\x1B[36m",Sr="\x1B[32m",Se="\x1B[33m",P="\x1B[2m",_e="\x1B[1m",v="\x1B[0m",em="\x1B[35m";function H(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function tm(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var Et={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function dl(t){let e=fl.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${_e}${K} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${v}`),console.log(`${_e}${K} hablas \u2014 Setup Wizard${v}`),console.log(`${P} Configure your AI provider and model${v}`),console.log(`${_e}${K} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${v}`),console.log(),console.log(`${_e} Choose your setup:${v}`),console.log(),console.log(` ${em}${_e}1${v}. ${_e}Hablas Integrated Engine${v} ${Sr}(instant \u2014 no setup needed)${v}`),console.log(` ${P}Pre-configured cloud AI, ready to use immediately${v}`),console.log(),console.log(` ${K}${_e}2${v}. ${_e}Custom Provider${v} ${P}(bring your own API key)${v}`),console.log(` ${P}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${v}`),console.log(),(await H(e,` ${P}Your choice (1-2):${v} `)).trim()){case"1":{t.provider=Et.provider,t.apiUrl=Et.apiUrl,t.apiKey=tm(),t.model=Et.model,Ve(t),console.log(),console.log(`${Sr} \u2713 Hablas Integrated Engine activated!${v}`),console.log(`${P} Model: ${Et.model}${v}`),console.log(`${P} API: ${Et.apiUrl}${v}`),console.log(`${P} No API key needed \u2014 everything is pre-configured.${v}`);break}case"2":{switch(console.log(),console.log(`${P} Select your provider:${v}`),console.log(` ${K}a${v}. Ollama (local, free, private)`),console.log(` ${K}b${v}. OpenAI API`),console.log(` ${K}c${v}. Groq (fast, free tier)`),console.log(` ${K}d${v}. OpenRouter (many models)`),console.log(` ${K}e${v}. Together AI`),console.log(` ${K}f${v}. DeepSeek`),console.log(` ${K}g${v}. Custom OpenAI-compatible API`),console.log(` ${K}h${v}. NVIDIA NIM (powerful cloud models)`),console.log(),(await H(e,` ${P}Your choice (a-h):${v} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await H(e,` ${P}Ollama host [http://localhost:11434]:${v} `)).trim(),i=(await H(e,` ${P}Model [qwen2.5-coder:7b]:${v} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await H(e,` ${P}OpenAI API Key (sk-...):${v} `)).trim(),i=(await H(e,` ${P}Model [gpt-4o]:${v} `)).trim();if(!s){console.log(`${Se} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.openai.com/v1",t.apiKey=s,t.model=i||"gpt-4o";break}case"c":{let s=(await H(e,` ${P}Groq API Key (gsk_...):${v} `)).trim(),i=(await H(e,` ${P}Model [llama-3.3-70b-versatile]:${v} `)).trim();if(!s){console.log(`${Se} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.groq.com/openai/v1",t.apiKey=s,t.model=i||"llama-3.3-70b-versatile";break}case"d":{let s=(await H(e,` ${P}OpenRouter API Key (sk-or-...):${v} `)).trim(),i=(await H(e,` ${P}Model [anthropic/claude-3.5-sonnet]:${v} `)).trim();if(!s){console.log(`${Se} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://openrouter.ai/api/v1",t.apiKey=s,t.model=i||"anthropic/claude-3.5-sonnet";break}case"e":{let s=(await H(e,` ${P}Together API Key:${v} `)).trim(),i=(await H(e,` ${P}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${v} `)).trim();if(!s){console.log(`${Se} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.together.xyz/v1",t.apiKey=s,t.model=i||"meta-llama/Llama-3.3-70B-Instruct-Turbo";break}case"f":{let s=(await H(e,` ${P}DeepSeek API Key:${v} `)).trim(),i=(await H(e,` ${P}Model [deepseek-chat]:${v} `)).trim();if(!s){console.log(`${Se} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.deepseek.com/v1",t.apiKey=s,t.model=i||"deepseek-chat";break}case"g":{let s=(await H(e,` ${P}API base URL:${v} `)).trim(),i=(await H(e,` ${P}API key (optional):${v} `)).trim(),o=(await H(e,` ${P}Model ID:${v} `)).trim();if(!s){console.log(`${Se} \u26A0 URL is required \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await H(e,` ${P}NVIDIA API Key (nvapi-...):${v} `)).trim();if(!s){console.log(`${Se} \u26A0 No key provided \u2014 cancelled${v}`),console.log(`${P} Get your key at: https://build.nvidia.com/${v}`),e.close();return}console.log(),console.log(`${P} Available NVIDIA models:${v}`),ue.models.forEach((a,l)=>{console.log(` ${K}${l+1}${v}. ${a}`)}),console.log();let i=(await H(e,` ${P}Model number [1]:${v} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=ue.apiUrl,t.apiKey=s,t.model=ue.models[o]||ue.defaultModel;break}default:console.log(`${Se} \u26A0 Invalid choice${v}`),e.close();return}Ve(t),console.log(),console.log(`${Sr} \u2713 Custom provider configured successfully${v}`),console.log(`${P} Provider: ${t.provider}${v}`),console.log(`${P} Model: ${t.model}${v}`);break}default:console.log(`${Se} \u26A0 Invalid choice \u2014 please select 1 or 2${v}`),e.close();return}console.log(),console.log(`${_e}${Sr} \u2713 Setup complete!${v}`),console.log(`${P} Use ${K}hablas${v}${P} for interactive mode or ${K}hablas run "..."${v}${P} for one-shot execution.${v}`),console.log(),e.close()}var pl=Mo(),X=new bs;X.name("hablas").description(`Hablas CLI v${pl} \u2014 single-agent engineering runtime for the terminal.`).version(pl).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");X.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=X.opts(),r=We({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=Pn(r);await nl(t,r,n)});X.command("doctor").description("Run system diagnostics").action(async()=>{let t=X.opts(),e=We({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await gr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(yr(r))});X.command("info").description("Show workspace information").action(async()=>{let t=X.opts(),e=We({project:t.project});console.log(""),console.log(or(st(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});X.command("security").description("Run a security scan on the current project").action(async()=>{let t=X.opts(),e=We({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(ol(il(r)))});X.command("stats").description("Show local usage statistics").action(async()=>{console.log(ul(cl()))});X.action(async()=>{let t=X.opts(),e=We({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 dl(e);return}let r=Pn(e);await rl(e,r)});X.parse();