hablas-ai 2.0.0 → 2.0.2

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,130 +1,130 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var qa=Object.create;var Mn=Object.defineProperty;var Ua=Object.getOwnPropertyDescriptor;var Ba=Object.getOwnPropertyNames;var Ha=Object.getPrototypeOf,Wa=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Va=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ba(e))!Wa.call(t,s)&&s!==r&&Mn(t,s,{get:()=>e[s],enumerable:!(n=Ua(e,s))||n.enumerable});return t};var k=(t,e,r)=>(r=t!=null?qa(Ha(t)):{},Va(e||!t||!t.__esModule?Mn(r,"default",{value:t,enumerable:!0}):r,t));var Ye=R(sr=>{var dt=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},nr=class extends dt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};sr.CommanderError=dt;sr.InvalidArgumentError=nr});var ht=R(or=>{var{InvalidArgumentError:za}=Ye(),ir=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new za(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Ka(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}or.Argument=ir;or.humanReadableArgName=Ka});var lr=R(Dn=>{var{humanReadableArgName:Ja}=ht(),ar=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,i)=>s.name().localeCompare(i.name())),r}compareOptions(e,r){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?r.push(n):n.long&&!i?r.push(e.createOption(n.long,n.description)):n.short&&!s&&r.push(e.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>Ja(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,s)=>Math.max(n,r.subcommandTerm(s).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,s)=>Math.max(n,r.argumentTerm(s).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),s=r.helpWidth||80,i=2,o=2;function a(c,m){if(m){let y=`${c.padEnd(n+o)}${m}`;return r.wrap(y,s-i,n+o)}return c}function l(c){return c.join(`
3
- `).replace(/^/gm," ".repeat(i))}let u=[`Usage: ${r.commandUsage(e)}`,""],d=r.commandDescription(e);d.length>0&&(u=u.concat([r.wrap(d,s,0),""]));let f=r.visibleArguments(e).map(c=>a(r.argumentTerm(c),r.argumentDescription(c)));f.length>0&&(u=u.concat(["Arguments:",l(f),""]));let p=r.visibleOptions(e).map(c=>a(r.optionTerm(c),r.optionDescription(c)));if(p.length>0&&(u=u.concat(["Options:",l(p),""])),this.showGlobalOptions){let c=r.visibleGlobalOptions(e).map(m=>a(r.optionTerm(m),r.optionDescription(m)));c.length>0&&(u=u.concat(["Global Options:",l(c),""]))}let h=r.visibleCommands(e).map(c=>a(r.subcommandTerm(c),r.subcommandDescription(c)));return h.length>0&&(u=u.concat(["Commands:",l(h),""])),u.join(`
4
- `)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=r-n;if(a<s)return e;let l=e.slice(0,n),u=e.slice(n).replace(`\r
2
+ "use strict";var Ga=Object.create;var Hn=Object.defineProperty;var Ja=Object.getOwnPropertyDescriptor;var Xa=Object.getOwnPropertyNames;var Ya=Object.getPrototypeOf,Za=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Qa=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xa(e))!Za.call(t,s)&&s!==r&&Hn(t,s,{get:()=>e[s],enumerable:!(n=Ja(e,s))||n.enumerable});return t};var C=(t,e,r)=>(r=t!=null?Ga(Ya(t)):{},Qa(e||!t||!t.__esModule?Hn(r,"default",{value:t,enumerable:!0}):r,t));var st=I(fr=>{var _t=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}},ur=class extends _t{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};fr.CommanderError=_t;fr.InvalidArgumentError=ur});var xt=I(pr=>{var{InvalidArgumentError:el}=st(),dr=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 el(`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 tl(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}pr.Argument=dr;pr.humanReadableArgName=tl});var mr=I(Wn=>{var{humanReadableArgName:rl}=xt(),hr=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=>rl(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,s)=>Math.max(n,r.subcommandTerm(s).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,s)=>Math.max(n,r.argumentTerm(s).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),s=r.helpWidth||80,i=2,o=2;function a(c,m){if(m){let y=`${c.padEnd(n+o)}${m}`;return r.wrap(y,s-i,n+o)}return c}function l(c){return c.join(`
3
+ `).replace(/^/gm," ".repeat(i))}let f=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(f=f.concat([r.wrap(u,s,0),""]));let d=r.visibleArguments(e).map(c=>a(r.argumentTerm(c),r.argumentDescription(c)));d.length>0&&(f=f.concat(["Arguments:",l(d),""]));let h=r.visibleOptions(e).map(c=>a(r.optionTerm(c),r.optionDescription(c)));if(h.length>0&&(f=f.concat(["Options:",l(h),""])),this.showGlobalOptions){let c=r.visibleGlobalOptions(e).map(m=>a(r.optionTerm(m),r.optionDescription(m)));c.length>0&&(f=f.concat(["Global Options:",l(c),""]))}let p=r.visibleCommands(e).map(c=>a(r.subcommandTerm(c),r.subcommandDescription(c)));return p.length>0&&(f=f.concat(["Commands:",l(p),""])),f.join(`
4
+ `)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=r-n;if(a<s)return e;let l=e.slice(0,n),f=e.slice(n).replace(`\r
5
5
  `,`
6
- `),d=" ".repeat(n),p="\\s\u200B",h=new RegExp(`
7
- |.{1,${a-1}}([${p}]|$)|[^${p}]+?([${p}]|$)`,"g"),c=u.match(h)||[];return l+c.map((m,y)=>m===`
8
- `?"":(y>0?d:"")+m.trimEnd()).join(`
9
- `)}};Dn.Help=ar});var dr=R(fr=>{var{InvalidArgumentError:Ga}=Ye(),cr=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Ya(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new Ga(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Xa(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ur=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return r.negate===(i===e)}};function Xa(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Ya(t){let e,r,n=t.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),r=n.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}fr.Option=cr;fr.DualOptions=ur});var jn=R(Ln=>{function Za(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=t.length;s++){let i=1;t[s-1]===e[n-1]?i=0:i=1,r[s][n]=Math.min(r[s-1][n]+1,r[s][n-1]+1,r[s-1][n-1]+i),s>1&&n>1&&t[s-1]===e[n-2]&&t[s-2]===e[n-1]&&(r[s][n]=Math.min(r[s][n],r[s-2][n-2]+1))}return r[t.length][e.length]}function Qa(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Za(t,o),l=Math.max(t.length,o.length);(l-a)/l>i&&(a<s?(s=a,n=[o]):a===s&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),r&&(n=n.map(o=>`--${o}`)),n.length>1?`
6
+ `),u=" ".repeat(n),h="\\s\u200B",p=new RegExp(`
7
+ |.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),c=f.match(p)||[];return l+c.map((m,y)=>m===`
8
+ `?"":(y>0?u:"")+m.trimEnd()).join(`
9
+ `)}};Wn.Help=hr});var br=I(wr=>{var{InvalidArgumentError:nl}=st(),gr=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=il(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 nl(`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 sl(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},yr=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 sl(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function il(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}}wr.Option=gr;wr.DualOptions=yr});var zn=I(Vn=>{function ol(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=ol(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]}?)`:""}Ln.suggestSimilar=Qa});var Hn=R(Bn=>{var el=require("node:events").EventEmitter,hr=require("node:child_process"),re=require("node:path"),pr=require("node:fs"),j=require("node:process"),{Argument:tl,humanReadableArgName:rl}=ht(),{CommanderError:mr}=Ye(),{Help:nl}=lr(),{Option:Nn,DualOptions:sl}=dr(),{suggestSimilar:qn}=jn(),gr=class t extends el{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>j.stdout.write(r),writeErr:r=>j.stderr.write(r),getOutHelpWidth:()=>j.stdout.isTTY?j.stdout.columns:void 0,getErrHelpWidth:()=>j.stderr.isTTY?j.stderr.columns:void 0,outputError:(r,n)=>n(r)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let s=r,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return s&&(l.description(s),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),s?this:l}createCommand(e){return new t(e)}createHelp(){return Object.assign(new nl,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
- - specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new tl(e,r)}argument(e,r,n,s){let i=this.createArgument(e,r);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=r??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
- Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new mr(e,r,n)),j.exit(e)}action(e){let r=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=r,this}createOption(e,r){return new Nn(e,r)}_callParseArg(e,r,n,s){try{return e.parseArg(r,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
14
- - already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=s=>[s.name()].concat(s.aliases()),n=r(e).find(s=>this._findCommand(s));if(n){let s=r(this._findCommand(n)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,a)};return this.on("option:"+r,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,r,n,s,i){if(typeof r=="object"&&r instanceof Nn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(r,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(l,u)=>{let d=a.exec(l);return d?d[0]:u},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,r,n,s){return this._optionEx({},e,r,n,s)}requiredOption(e,r,n,s){return this._optionEx({mandatory:!0},e,r,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){j.versions?.electron&&(r.from="electron");let s=j.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(r.from="eval")}e===void 0&&(e=j.argv),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":j.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,f){let p=re.resolve(d,f);if(pr.existsSync(p))return p;if(s.includes(re.extname(f)))return;let h=s.find(c=>pr.existsSync(`${p}${c}`));if(h)return`${p}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=pr.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=re.resolve(re.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=re.basename(this._scriptPath,re.extname(this._scriptPath));f!==this._name&&(d=i(a,`${f}-${e._name}`))}o=d||o}n=s.includes(re.extname(o));let l;j.platform!=="win32"?n?(r.unshift(o),r=Un(j.execArgv).concat(r),l=hr.spawn(j.argv[0],r,{stdio:"inherit"})):l=hr.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=Un(j.execArgv).concat(r),l=hr.spawn(j.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{j.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let u=this._exitCallback;l.on("close",d=>{d=d??1,u?u(new mr(d,"commander.executeSubCommandAsync","(close)")):j.exit(d)}),l.on("error",d=>{if(d.code==="ENOENT"){let f=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",p=`'${o}' does not exist
11
+ (Did you mean ${n[0]}?)`:""}Vn.suggestSimilar=al});var Yn=I(Xn=>{var ll=require("node:events").EventEmitter,Sr=require("node:child_process"),ae=require("node:path"),_r=require("node:fs"),q=require("node:process"),{Argument:cl,humanReadableArgName:ul}=xt(),{CommanderError:xr}=st(),{Help:fl}=mr(),{Option:Kn,DualOptions:dl}=br(),{suggestSimilar:Gn}=zn(),vr=class t extends ll{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=>q.stdout.write(r),writeErr:r=>q.stderr.write(r),getOutHelpWidth:()=>q.stdout.isTTY?q.stdout.columns:void 0,getErrHelpWidth:()=>q.stderr.isTTY?q.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 fl,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 cl(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 xr(e,r,n)),q.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 Kn(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 Kn)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,f)=>{let u=a.exec(l);return u?u[0]:f},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){q.versions?.electron&&(r.from="electron");let s=q.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(r.from="eval")}e===void 0&&(e=q.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":q.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(u,d){let h=ae.resolve(u,d);if(_r.existsSync(h))return h;if(s.includes(ae.extname(d)))return;let p=s.find(c=>_r.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 u;try{u=_r.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=ae.resolve(ae.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=ae.basename(this._scriptPath,ae.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}n=s.includes(ae.extname(o));let l;q.platform!=="win32"?n?(r.unshift(o),r=Jn(q.execArgv).concat(r),l=Sr.spawn(q.argv[0],r,{stdio:"inherit"})):l=Sr.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=Jn(q.execArgv).concat(r),l=Sr.spawn(q.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{q.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let f=this._exitCallback;l.on("close",u=>{u=u??1,f?f(new xr(u,"commander.executeSubCommandAsync","(close)")):q.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",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(p)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)j.exit(1);else{let f=new mr(1,"commander.executeSubCommandAsync","(error)");f.nestedError=d,u(f)}}),this.runningCommand=l}_dispatchSubcommand(e,r,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,r.concat(n));else return s._parseCommand(r,n)}),i}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,a)=>e(n,a,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),r[s]=i}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[r]!==void 0).forEach(i=>{i._lifeCycleHooks[r].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),r==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,r))}),s}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],s=r,i=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){s===n&&s.push(l),s.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let u=this._findOption(l);if(u){if(u.required){let d=i.shift();d===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,d)}else if(u.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${u.name()}`,d)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),d=this._findOption(l.slice(0,u));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,l.slice(u+1));continue}}if(o(l)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(l)){r.push(l),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){r.push(l),i.length>0&&r.push(...i);break}else if(this._defaultCommandName){n.push(l),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(l),i.length>0&&s.push(...i);break}s.push(l)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
17
+ - ${d}`;throw new Error(h)}else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!f)q.exit(1);else{let d=new xr(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,f(d)}}),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 f=this._findOption(l);if(f){if(f.required){let u=i.shift();u===void 0&&this.optionMissingArgument(f),this.emit(`option:${f.name()}`,u)}else if(f.optional){let u=null;i.length>0&&!o(i[0])&&(u=i.shift()),this.emit(`option:${f.name()}`,u)}else this.emit(`option:${f.name()}`);a=f.variadic?f:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let f=this._findOption(`-${l[1]}`);if(f){f.required||f.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${f.name()}`,l.slice(2)):(this.emit(`option:${f.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let f=l.indexOf("="),u=this._findOption(l.slice(0,f));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,l.slice(f+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 j.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,j.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new sl(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!r(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=o=>{let a=o.attributeName(),l=this.getOptionValue(a),u=this.options.find(f=>f.negate&&a===f.attributeName()),d=this.options.find(f=>!f.negate&&a===f.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:d||o},s=o=>{let a=n(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);r=qn(e,s)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),r=qn(e,s)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let s=this.createOption(r,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
- `),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>rl(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=re.basename(e,re.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(r&&(s=r(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let r=j.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
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 q.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()}`,q.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new dl(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),f=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return f&&(f.presetArg===void 0&&l===!1||f.presetArg!==void 0&&l===f.presetArg)?f:u||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=Gn(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=Gn(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=>ul(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=ae.basename(e,ae.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=q.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 Un(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?r=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=i[1],n=i[3],s=i[4]),r&&s!=="0"?`${r}=${n}:${parseInt(s)+1}`:e})}Bn.Command=gr});var Kn=R(V=>{var{Argument:Wn}=ht(),{Command:yr}=Hn(),{CommanderError:il,InvalidArgumentError:Vn}=Ye(),{Help:ol}=lr(),{Option:zn}=dr();V.program=new yr;V.createCommand=t=>new yr(t);V.createOption=(t,e)=>new zn(t,e);V.createArgument=(t,e)=>new Wn(t,e);V.Command=yr;V.Option=zn;V.Argument=Wn;V.Help=ol;V.CommanderError=il;V.InvalidArgumentError=Vn;V.InvalidOptionArgumentError=Vn});var Sr=R((qp,es)=>{"use strict";var et=t=>t&&typeof t.message=="string",br=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return et(r)?r:void 0}else return et(e)?e:void 0},Zn=(t,e)=>{if(!et(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
- causes have become circular...`;let n=br(t);return n?(e.add(t),r+`
25
- caused by: `+Zn(n,e)):r},al=t=>Zn(t,new Set),Qn=(t,e,r)=>{if(!et(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=br(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+Qn(s,e,i)}else return n},ll=t=>Qn(t,new Set);es.exports={isErrorLike:et,getErrorCause:br,stackWithCauses:al,messageWithCauses:ll}});var _r=R((Up,rs)=>{"use strict";var cl=Symbol("circular-ref-tag"),pt=Symbol("pino-raw-err-ref"),ts=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[pt]},set:function(t){this[pt]=t}}});Object.defineProperty(ts,pt,{writable:!0,value:{}});rs.exports={pinoErrProto:ts,pinoErrorSymbols:{seen:cl,rawSymbol:pt}}});var is=R((Bp,ss)=>{"use strict";ss.exports=vr;var{messageWithCauses:ul,stackWithCauses:fl,isErrorLike:ns}=Sr(),{pinoErrProto:dl,pinoErrorSymbols:hl}=_r(),{seen:xr}=hl,{toString:pl}=Object.prototype;function vr(t){if(!ns(t))return t;t[xr]=void 0;let e=Object.create(dl);e.type=pl.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=ul(t),e.stack=fl(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>vr(r)));for(let r in t)if(e[r]===void 0){let n=t[r];ns(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,xr)&&(e[r]=vr(n)):e[r]=n}return delete t[xr],e.raw=t,e}});var as=R((Hp,os)=>{"use strict";os.exports=gt;var{isErrorLike:kr}=Sr(),{pinoErrProto:ml,pinoErrorSymbols:gl}=_r(),{seen:mt}=gl,{toString:yl}=Object.prototype;function gt(t){if(!kr(t))return t;t[mt]=void 0;let e=Object.create(ml);e.type=yl.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=t.message,e.stack=t.stack,Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>gt(r))),kr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,mt)&&(e.cause=gt(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];kr(n)?Object.prototype.hasOwnProperty.call(n,mt)||(e[r]=gt(n)):e[r]=n}return delete t[mt],e.raw=t,e}});var fs=R((Wp,us)=>{"use strict";us.exports={mapHttpRequest:wl,reqSerializer:cs};var Cr=Symbol("pino-raw-req-ref"),ls=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Cr]},set:function(t){this[Cr]=t}}});Object.defineProperty(ls,Cr,{writable:!0,value:{}});function cs(t){let e=t.info||t.socket,r=Object.create(ls);if(r.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),r.method=t.method,t.originalUrl)r.url=t.originalUrl;else{let n=t.path;r.url=typeof n=="string"?n:t.url?t.url.path||t.url:void 0}return t.query&&(r.query=t.query),t.params&&(r.params=t.params),r.headers=t.headers,r.remoteAddress=e&&e.remoteAddress,r.remotePort=e&&e.remotePort,r.raw=t.raw||t,r}function wl(t){return{req:cs(t)}}});var ms=R((Vp,ps)=>{"use strict";ps.exports={mapHttpResponse:bl,resSerializer:hs};var Tr=Symbol("pino-raw-res-ref"),ds=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Tr]},set:function(t){this[Tr]=t}}});Object.defineProperty(ds,Tr,{writable:!0,value:{}});function hs(t){let e=Object.create(ds);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function bl(t){return{res:hs(t)}}});var Er=R((zp,gs)=>{"use strict";var Ar=is(),Sl=as(),yt=fs(),wt=ms();gs.exports={err:Ar,errWithCause:Sl,mapHttpRequest:yt.mapHttpRequest,mapHttpResponse:wt.mapHttpResponse,req:yt.reqSerializer,res:wt.resSerializer,wrapErrorSerializer:function(e){return e===Ar?e:function(n){return e(Ar(n))}},wrapRequestSerializer:function(e){return e===yt.reqSerializer?e:function(n){return e(yt.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===wt.resSerializer?e:function(n){return e(wt.resSerializer(n))}}}});var Or=R((Kp,ys)=>{"use strict";function _l(t,e){return e}ys.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=_l;let r=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(r))return;let n=r.slice(2),s=[];for(let i of n)i&&s.push(i.getFileName());return s}});var vs=R((Jp,xs)=>{"use strict";function $r(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array){let e=[];for(let r=0;r<t.length;r++)e[r]=$r(t[r]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=$r(t[r]));return e}return t}function ws(t){let e=[],r="",n=!1,s=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!n&&a==="."?r&&(e.push(r),r=""):a==="["?(r&&(e.push(r),r=""),n=!0):a==="]"&&n?(e.push(r),r="",n=!1,s=!1):(a==='"'||a==="'")&&n?s?a===i?(s=!1,i=""):r+=a:(s=!0,i=a):r+=a}return r&&e.push(r),e}function bs(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof n!="object"||n===null||!(o in n)||typeof n[o]!="object"||n[o]===null)return!1;n=n[o]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(n))for(let i=0;i<n.length;i++)n[i]=r;else if(typeof n=="object"&&n!==null)for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&(n[i]=r)}else typeof n=="object"&&n!==null&&s in n&&Object.prototype.hasOwnProperty.call(n,s)&&(n[s]=r);return!0}function Ss(t,e){let r=t;for(let s=0;s<e.length-1;s++){let i=e[s];if(typeof r!="object"||r===null||!(i in r)||typeof r[i]!="object"||r[i]===null)return!1;r=r[i]}let n=e[e.length-1];if(n==="*"){if(Array.isArray(r))for(let s=0;s<r.length;s++)r[s]=void 0;else if(typeof r=="object"&&r!==null)for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&delete r[s]}else typeof r=="object"&&r!==null&&n in r&&Object.prototype.hasOwnProperty.call(r,n)&&delete r[n];return!0}var bt=Symbol("PATH_NOT_FOUND");function xl(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return bt;r=r[n]}return r}function vl(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null)return;r=r[n]}return r}function kl(t,e,r,n=!1){for(let s of e){let i=ws(s);if(i.includes("*"))_s(t,i,r,s,n);else if(n)Ss(t,i);else{let o=xl(t,i);if(o===bt)continue;let a=typeof r=="function"?r(o,i):r;bs(t,i,a)}}}function _s(t,e,r,n,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(s)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let u=[...o,l.toString()],d=typeof r=="function"?r(a[l],u):r;a[l]=d}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let u in a)Object.prototype.hasOwnProperty.call(a,u)&&l.push(u);for(let u of l)delete a[u]}else for(let l in a){let u=[...o,l],d=typeof r=="function"?r(a[l],u):r;a[l]=d}}else Cl(t,e,r,i,n,s)}function Cl(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function u(d,f){if(f===o.length){if(Array.isArray(d))for(let p=0;p<d.length;p++)l[f]=p.toString(),u(d[p],f+1);else if(typeof d=="object"&&d!==null)for(let p in d)l[f]=p,u(d[p],f+1)}else if(f<o.length){let p=o[f];d&&typeof d=="object"&&d!==null&&p in d&&(l[f]=p,u(d[p],f+1))}else if(a.includes("*"))_s(d,a,typeof r=="function"?(h,c)=>{let m=[...l.slice(0,f),...c];return r(h,m)}:r,s,i);else if(i)Ss(d,a);else{let p=typeof r=="function"?r(vl(d,a),[...l.slice(0,f),...a]):r;bs(d,a,p)}}if(o.length===0)u(t,0);else{let d=t;for(let f=0;f<o.length;f++){let p=o[f];if(d==null||typeof d!="object"||d===null)return;d=d[p],l[f]=p}d!=null&&u(d,o.length)}}function Tl(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=ws(r),s=e;for(let i=0;i<n.length;i++){let o=n[i];s.has(o)||s.set(o,new Map),s=s.get(o)}}return e}function Al(t,e){if(!e)return t;function r(n,s,i=0){if(!s||s.size===0||n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n)){let a=[];for(let l=0;l<n.length;l++){let u=l.toString();s.has(u)||s.has("*")?a[l]=r(n[l],s.get(u)||s.get("*")):a[l]=n[l]}return a}let o=Object.create(Object.getPrototypeOf(n));for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s.has(a)||s.has("*")?o[a]=r(n[a],s.get(a)||s.get("*")):o[a]=n[a]);return o}return r(t,e)}function El(t){if(typeof t!="string")throw new Error("Paths must be (non-empty) strings");if(t==="")throw new Error("Invalid redaction path ()");if(t.includes(".."))throw new Error(`Invalid redaction path (${t})`);if(t.includes(","))throw new Error(`Invalid redaction path (${t})`);let e=0,r=!1,n="";for(let s=0;s<t.length;s++){let i=t[s];if((i==='"'||i==="'")&&e>0)r?i===n&&(r=!1,n=""):(r=!0,n=i);else if(i==="["&&!r)e++;else if(i==="]"&&!r&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function Ol(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)El(e)}function $l(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;Ol(e);let o=Tl(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let u=Al(l,o),d=l,f=r;return typeof r=="function"&&(f=r),kl(u,e,f,i),n===!1?(u.restore=function(){return $r(d)},u):typeof n=="function"?n(u):JSON.stringify(u)}}xs.exports=$l});var Pe=R((Gp,ks)=>{"use strict";var Rl=Symbol("pino.setLevel"),Il=Symbol("pino.getLevel"),Pl=Symbol("pino.levelVal"),Fl=Symbol("pino.levelComp"),Ml=Symbol("pino.useLevelLabels"),Dl=Symbol("pino.useOnlyCustomLevels"),Ll=Symbol("pino.mixin"),jl=Symbol("pino.lsCache"),Nl=Symbol("pino.chindings"),ql=Symbol("pino.asJson"),Ul=Symbol("pino.write"),Bl=Symbol("pino.redactFmt"),Hl=Symbol("pino.time"),Wl=Symbol("pino.timeSliceIndex"),Vl=Symbol("pino.stream"),zl=Symbol("pino.stringify"),Kl=Symbol("pino.stringifySafe"),Jl=Symbol("pino.stringifiers"),Gl=Symbol("pino.end"),Xl=Symbol("pino.formatOpts"),Yl=Symbol("pino.messageKey"),Zl=Symbol("pino.errorKey"),Ql=Symbol("pino.nestedKey"),ec=Symbol("pino.nestedKeyStr"),tc=Symbol("pino.mixinMergeStrategy"),rc=Symbol("pino.msgPrefix"),nc=Symbol("pino.wildcardFirst"),sc=Symbol.for("pino.serializers"),ic=Symbol.for("pino.formatters"),oc=Symbol.for("pino.hooks"),ac=Symbol.for("pino.metadata");ks.exports={setLevelSym:Rl,getLevelSym:Il,levelValSym:Pl,levelCompSym:Fl,useLevelLabelsSym:Ml,mixinSym:Ll,lsCacheSym:jl,chindingsSym:Nl,asJsonSym:ql,writeSym:Ul,serializersSym:sc,redactFmtSym:Bl,timeSym:Hl,timeSliceIndexSym:Wl,streamSym:Vl,stringifySym:zl,stringifySafeSym:Kl,stringifiersSym:Jl,endSym:Gl,formatOptsSym:Xl,messageKeySym:Yl,errorKeySym:Zl,nestedKeySym:Ql,wildcardFirstSym:nc,needsMetadataGsym:ac,useOnlyCustomLevelsSym:Dl,formattersSym:ic,hooksSym:oc,nestedKeyStrSym:ec,mixinMergeStrategySym:tc,msgPrefixSym:rc}});var Ir=R((Xp,Es)=>{"use strict";var Cs=vs(),{redactFmtSym:lc,wildcardFirstSym:St}=Pe(),Rr=/[^.[\]]+|\[([^[\]]*?)\]/g,Ts="[Redacted]",As=!1;function cc(t,e){let{paths:r,censor:n,remove:s}=uc(t),i=r.reduce((l,u)=>{Rr.lastIndex=0;let d=Rr.exec(u),f=Rr.exec(u),p=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(p==="*"&&(p=St),f===null)return l[p]=null,l;if(l[p]===null)return l;let{index:h}=f,c=`${u.substr(h,u.length-1)}`;return l[p]=l[p]||[],p!==St&&l[p].length===0&&l[p].push(...l[St]||[]),p===St&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(c)}),l[p].push(c),l},{}),o={[lc]:Cs({paths:r,censor:n,serialize:e,strict:As,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,u)=>{if(i[u]===null)l[u]=d=>a(d,[u]);else{let d=typeof n=="function"?(f,p)=>n(f,[u,...p]):n;l[u]=Cs({paths:i[u],censor:d,serialize:e,strict:As,remove:s})}return l},o)}function uc(t){if(Array.isArray(t))return t={paths:t,censor:Ts},t;let{paths:e,censor:r=Ts,remove:n}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),{paths:e,censor:r,remove:n}}Es.exports=cc});var Rs=R((Yp,$s)=>{"use strict";var fc=()=>"",dc=()=>`,"time":${Date.now()}`,hc=()=>`,"time":${Math.round(Date.now()/1e3)}`,pc=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,mc=1000000n,Os=1000000000n,gc=BigInt(Date.now())*mc,yc=process.hrtime.bigint(),wc=()=>{let t=process.hrtime.bigint()-yc,e=gc+t,r=e/Os,n=e%Os,s=Number(r*1000n+n/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),u=i.getUTCHours().toString().padStart(2,"0"),d=i.getUTCMinutes().toString().padStart(2,"0"),f=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${u}:${d}:${f}.${n.toString().padStart(9,"0")}Z"`};$s.exports={nullTime:fc,epochTime:dc,unixTime:hc,isoTime:pc,isoTimeNano:wc}});var Ps=R((Zp,Is)=>{"use strict";function bc(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}Is.exports=Sc;function Sc(t,e,r){var n=r&&r.stringify||bc,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var u="",d=1-s,f=-1,p=t&&t.length||0,h=0;h<p;){if(t.charCodeAt(h)===37&&h+1<p){switch(f=f>-1?f:0,t.charCodeAt(h+1)){case 100:case 102:if(d>=l||e[d]==null)break;f<h&&(u+=t.slice(f,h)),u+=Number(e[d]),f=h+2,h++;break;case 105:if(d>=l||e[d]==null)break;f<h&&(u+=t.slice(f,h)),u+=Math.floor(Number(e[d])),f=h+2,h++;break;case 79:case 111:case 106:if(d>=l||e[d]===void 0)break;f<h&&(u+=t.slice(f,h));var c=typeof e[d];if(c==="string"){u+="'"+e[d]+"'",f=h+2,h++;break}if(c==="function"){u+=e[d].name||"<anonymous>",f=h+2,h++;break}u+=n(e[d]),f=h+2,h++;break;case 115:if(d>=l)break;f<h&&(u+=t.slice(f,h)),u+=String(e[d]),f=h+2,h++;break;case 37:f<h&&(u+=t.slice(f,h)),u+="%",f=h+2,h++,d--;break}++d}++h}return f===-1?t:(f<p&&(u+=t.slice(f)),u)}});var Fr=R((Qp,Pr)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(t,0,0,Number(r))},t=new Int32Array(new SharedArrayBuffer(4));Pr.exports=e}else{let t=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(e);for(;n>Date.now(););};Pr.exports=t}});var Us=R((em,qs)=>{"use strict";var M=require("fs"),_c=require("events"),xc=require("util").inherits,Fs=require("path"),Dr=Fr(),vc=require("assert"),_t=100,xt=Buffer.allocUnsafe(0),kc=16*1024,Ms="buffer",Ds="utf8",[Cc,Tc]=(process.versions.node||"0.0").split(".").map(Number),Ac=Cc>=22&&Tc>=7;function Ls(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function r(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=t,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let n=e.append?"a":"w",s=e.mode;if(e.sync)try{e.mkdir&&M.mkdirSync(Fs.dirname(t),{recursive:!0});let i=M.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?M.mkdir(Fs.dirname(t),{recursive:!0},i=>{if(i)return r(i);M.open(t,n,s,r)}):M.open(t,n,s,r)}function Y(t){if(!(this instanceof Y))return new Y(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:u,retryEAGAIN:d,fsync:f,contentMode:p,mode:h}=t||{};e=e||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=s||0,this.maxWrite=i||kc,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=f||!1,this.append=l||!1,this.mode=h,this.retryEAGAIN=d||(()=>!0),this.mkdir=u||!1;let c,m;if(p===Ms)this._writingBuf=xt,this.write=$c,this.flush=Ic,this.flushSync=Fc,this._actualWrite=Dc,c=()=>M.writeSync(this.fd,this._writingBuf),m=()=>M.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===Ds)this._writingBuf="",this.write=Oc,this.flush=Rc,this.flushSync=Pc,this._actualWrite=Mc,c=()=>Buffer.isBuffer(this._writingBuf)?M.writeSync(this.fd,this._writingBuf):M.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?M.write(this.fd,this._writingBuf,this.release):M.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Ds}" and "${Ms}", but passed ${p}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Ls(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(y,w)=>{if(y){if((y.code==="EAGAIN"||y.code==="EBUSY")&&this.retryEAGAIN(y,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Dr(_t),this.release(void 0,0)}catch(S){this.release(S)}else setTimeout(m,_t);else this._writing=!1,this.emit("error",y);return}this.emit("write",w);let b=Mr(this._writingBuf,this._len,w);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let S=c(),v=Mr(this._writingBuf,this._len,S);this._len=v.len,this._writingBuf=v.writingBuf}while(this._writingBuf.length)}catch(S){this.release(S);return}}this._fsync&&M.fsyncSync(this.fd);let _=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):_>this.minLength?this._actualWrite():this._ending?_>0?this._actualWrite():(this._writing=!1,vt(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Ec,this)):this.emit("drain"))},this.on("newListener",function(y){y==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Mr(t,e,r){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-r,0),t=t.subarray(r),{writingBuf:t,len:e}}function Ec(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}xc(Y,_c);function js(t,e){return t.length===0?xt:t.length===1?t[0]:Buffer.concat(t,e)}function Oc(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),r=this._len+e,n=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(n.length===0||Buffer.byteLength(n[n.length-1])+e>this.maxWrite?n.push(t):n[n.length-1]+=t,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function $c(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,r=this._bufs,n=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||n[n.length-1]+t.length>this.maxWrite?(r.push([t]),n.push(t.length)):(r[r.length-1].push(t),n[n.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Ns(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{M.fsync(this.fd,n=>{this._flushPending=!1,t(n)})}catch(n){t(n)}this.off("error",r)},r=n=>{this._flushPending=!1,t(n),this.off("drain",e)};this.once("drain",e),this.once("error",r)}function Rc(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Ns.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function Ic(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Ns.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}Y.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&M.close(e,r=>{if(r)return this.emit("error",r)})}),Ls(this.file,this)};Y.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():vt(this)))};function Pc(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?M.writeSync(this.fd,t):M.writeSync(this.fd,t,"utf8"),r=Mr(t,this._len,e);t=r.writingBuf,this._len=r.len,t.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Dr(_t)}}try{M.fsyncSync(this.fd)}catch{}}function Fc(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=xt);let t=xt;for(;this._bufs.length||t.length;){t.length<=0&&(t=js(this._bufs[0],this._lens[0]));try{let e=M.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Dr(_t)}}}Y.prototype.destroy=function(){this.destroyed||vt(this)};function Mc(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?M.writeSync(this.fd,this._writingBuf):M.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else M.write(this.fd,this._writingBuf,t)}function Dc(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:js(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=M.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else Ac&&(this._writingBuf=Buffer.from(this._writingBuf)),M.write(this.fd,this._writingBuf,t)}function vt(t){if(t.fd===-1){t.once("ready",vt.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],vc(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{M.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?M.close(t.fd,r):r()}function r(n){if(n){t.emit("error",n);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}Y.SonicBoom=Y;Y.default=Y;qs.exports=Y});var Lr=R((tm,zs)=>{"use strict";var Z={exit:[],beforeExit:[]},Bs={exit:Nc,beforeExit:qc},Fe;function Lc(){Fe===void 0&&(Fe=new FinalizationRegistry(Uc))}function jc(t){Z[t].length>0||process.on(t,Bs[t])}function Hs(t){Z[t].length>0||(process.removeListener(t,Bs[t]),Z.exit.length===0&&Z.beforeExit.length===0&&(Fe=void 0))}function Nc(){Ws("exit")}function qc(){Ws("beforeExit")}function Ws(t){for(let e of Z[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}Z[t]=[]}function Uc(t){for(let e of["exit","beforeExit"]){let r=Z[e].indexOf(t);Z[e].splice(r,r+1),Hs(e)}}function Vs(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");jc(t);let n=new WeakRef(e);n.fn=r,Lc(),Fe.register(e,n),Z[t].push(n)}function Bc(t,e){Vs("exit",t,e)}function Hc(t,e){Vs("beforeExit",t,e)}function Wc(t){if(Fe!==void 0){Fe.unregister(t);for(let e of["exit","beforeExit"])Z[e]=Z[e].filter(r=>{let n=r.deref();return n&&n!==t}),Hs(e)}}zs.exports={register:Bc,registerBeforeExit:Hc,unregister:Wc}});var Ks=R((rm,Vc)=>{Vc.exports={name:"thread-stream",version:"4.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",engines:{node:">=20"},dependencies:{"real-require":"^1.0.0"},devDependencies:{"@types/node":"^25.0.2","@yao-pkg/pkg":"^6.0.0",borp:"^1.0.0",desm:"^1.3.0",eslint:"^9.39.1",fastbench:"^1.0.1",neostandard:"^0.13.0","pino-elasticsearch":"^9.0.0","sonic-boom":"^5.0.0","ts-node":"^10.8.0",typescript:"~5.7.3"},scripts:{build:"tsc --noEmit",lint:"eslint",test:'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:ci":'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:yarn":'npm run transpile && borp --pattern "test/*.test.js"',transpile:"sh ./test/ts/transpile.sh"},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina <hello@matteocollina.com>",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var Gs=R((nm,Js)=>{"use strict";function zc(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{let a=Atomics.load(t,e);if(a===r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),u=Atomics.waitAsync(t,e,a,l);u.async?u.value.then(o):setImmediate(o)};o()}function Kc(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{if(Atomics.load(t,e)!==r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),u=Atomics.waitAsync(t,e,r,l);u.async?u.value.then(d=>{if(d==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}Js.exports={wait:zc,waitDiff:Kc}});var Ys=R((sm,Xs)=>{"use strict";Xs.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var ci=R((im,li)=>{"use strict";var{version:Jc}=Ks(),{EventEmitter:Gc}=require("events"),{Worker:Xc}=require("worker_threads"),{join:Yc}=require("path"),{pathToFileURL:Zc}=require("url"),{wait:Qc}=Gs(),{WRITE_INDEX:se,READ_INDEX:ge,SEQ_INDEX:jr}=Ys(),eu=require("buffer"),tu=require("assert"),g=Symbol("kImpl"),ru=eu.constants.MAX_STRING_LENGTH;function Zs(){}function Br(t,e){Atomics.add(t[g].state,jr,1),e(),Atomics.add(t[g].state,jr,1),Atomics.notify(t[g].state,jr)}function Qs(t){Br(t,()=>{Atomics.store(t[g].state,ge,0),Atomics.store(t[g].state,se,0)})}var tt=class{constructor(e){this._value=e}deref(){return this._value}},kt=class{register(){}unregister(){}},nu=process.env.NODE_V8_COVERAGE?kt:global.FinalizationRegistry||kt,su=process.env.NODE_V8_COVERAGE?tt:global.WeakRef||tt,ei=new nu(t=>{t.exited||t.terminate()});function iu(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Yc(__dirname,"lib","worker.js"),o=new Xc(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Zc(r).href,dataBuf:t[g].dataBuf,stateBuf:t[g].stateBuf,workerData:{$context:{threadStreamVersion:Jc},...n}}});return o.stream=new tt(t),o.on("message",ou),o.on("exit",ni),ei.register(t,o),o}function ti(t){tu(!t[g].sync),t[g].needDrain&&(t[g].needDrain=!1,t.emit("drain"))}function ri(t){for(;;){let e=Atomics.load(t[g].state,se),r=t[g].data.length-e;if(r>0){if(t[g].bufLen===0){t[g].flushing=!1,t[g].ending?Hr(t):t[g].needDrain&&process.nextTick(ti,t);return}oi(t,r,Zs);continue}if(r===0){if(e===0&&t[g].bufLen===0)return;Ct(t,()=>{t.destroyed||(Qs(t),ri(t))});return}z(t,new Error("overwritten"));return}}function ou(t){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(t?.code!=null)switch(t.code){case"READY":this.stream=new su(e),Ct(e,()=>{e[g].ready=!0,e.emit("ready")});break;case"ERROR":z(e,t.err);break;case"EVENT":Array.isArray(t.args)?e.emit(t.name,...t.args):e.emit(t.name,t.args);break;case"FLUSHED":{if(t.context!=="thread-stream"){z(e,new Error("this should not happen: "+t.code));break}let r=e[g].flushCallbacks.get(t.id);r&&(e[g].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:z(e,new Error("this should not happen: "+t.code))}}function ni(t){let e=this.stream.deref();e!==void 0&&(ei.unregister(e),e.worker.exited=!0,e.worker.off("exit",ni),z(e,t!==0?new Error("the worker thread exited"):null))}var qr=class extends Gc{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[g]={},this[g].stateBuf=new SharedArrayBuffer(128),this[g].state=new Int32Array(this[g].stateBuf),this[g].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[g].data=Buffer.from(this[g].dataBuf),this[g].sync=e.sync||!1,this[g].ending=!1,this[g].ended=!1,this[g].needDrain=!1,this[g].destroyed=!1,this[g].flushing=!1,this[g].ready=!1,this[g].finished=!1,this[g].errored=null,this[g].closed=!1,this[g].buf=[],this[g].bufHead=0,this[g].bufLen=0,this[g].flushCallbacks=new Map,this[g].nextFlushId=0,this.worker=iu(this,e),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(e){let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[g].destroyed)return Ur(this,new Error("the worker has exited")),!1;if(this[g].ending)return Ur(this,new Error("the worker is ending")),!1;if(this[g].flushing&&this[g].bufLen+r.length>=ru)try{Nr(this),this[g].flushing=!0}catch(n){return z(this,n),!1}if(this[g].buf.push(r),this[g].bufLen+=r.length,this[g].sync)try{return Nr(this),!0}catch(n){return z(this,n),!1}return this[g].flushing||(this[g].flushing=!0,setImmediate(ri,this)),this[g].needDrain=this[g].data.length-this[g].bufLen-Atomics.load(this[g].state,se)<=0,!this[g].needDrain}end(){this[g].destroyed||(this[g].ending=!0,Hr(this))}flush(e){e=typeof e=="function"?e:Zs,si(this,r=>{if(r){process.nextTick(e,r);return}ii(this,e)})}flushSync(){this[g].destroyed||(Nr(this),ai(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[g].ready}get destroyed(){return this[g].destroyed}get closed(){return this[g].closed}get writable(){return!this[g].destroyed&&!this[g].ending}get writableEnded(){return this[g].ending}get writableFinished(){return this[g].finished}get writableNeedDrain(){return this[g].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[g].errored}};function si(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].sync&&(t[g].flushing||t[g].bufLen>0)){setImmediate(si,t,e);return}Ct(t,e)}function Ct(t,e){let r=Atomics.load(t[g].state,se);Qc(t[g].state,ge,r,1/0,(n,s)=>{if(n){z(t,n),e(n);return}if(s!=="ok"){Ct(t,e);return}e()})}function ii(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].ready){let n=()=>{i(),ii(t,e)},s=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",n),t.off("close",s)};t.once("ready",n),t.once("close",s);return}let r=++t[g].nextFlushId;t[g].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[g].flushCallbacks.delete(r),z(t,n),process.nextTick(e,n)}}function au(t,e){let r=t[g].flushCallbacks;if(r.size===0)return;let n=e||new Error("the worker has exited");for(let s of r.values())process.nextTick(s,n);r.clear()}function Ur(t,e){setImmediate(()=>{t.emit("error",e)})}function z(t,e){t[g].destroyed||(t[g].destroyed=!0,au(t,e),e&&(t[g].errored=e,Ur(t,e)),t.worker.exited?setImmediate(()=>{t[g].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[g].closed=!0,t.emit("close")}))}function oi(t,e,r){let s=Atomics.load(t[g].state,se),i=e;for(;i>0&&t[g].bufLen!==0;){let o=t[g].bufHead,a=t[g].buf[o];if(a.length<=i){a.copy(t[g].data,s),s+=a.length,i-=a.length,t[g].bufLen-=a.length,t[g].bufHead=o+1,t[g].bufHead===t[g].buf.length?(t[g].buf.length=0,t[g].bufHead=0):t[g].bufHead>=1024&&t[g].bufHead*2>=t[g].buf.length&&(t[g].buf.splice(0,t[g].bufHead),t[g].bufHead=0);continue}a.copy(t[g].data,s,0,i),t[g].buf[o]=a.subarray(i),t[g].bufLen-=i,s+=i,i=0}return Br(t,()=>{Atomics.store(t[g].state,se,s)}),r(),!0}function Hr(t){if(!(t[g].ended||!t[g].ending||t[g].flushing)){t[g].ended=!0;try{t.flushSync();let e=Atomics.load(t[g].state,ge);Br(t,()=>{Atomics.store(t[g].state,se,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[g].state,ge,e,1e3),e=Atomics.load(t[g].state,ge),e===-2){z(t,new Error("end() failed"));return}if(++r===10){z(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[g].finished=!0,t.emit("finish")})}catch(e){z(t,e)}}}function Nr(t){let e=()=>{t[g].ending?Hr(t):t[g].needDrain&&process.nextTick(ti,t)};for(t[g].flushing=!1;t[g].bufLen!==0;){let r=Atomics.load(t[g].state,se),n=t[g].data.length-r;if(n===0){ai(t),Qs(t);continue}else if(n<0)throw new Error("overwritten");oi(t,n,e)}}function ai(t){if(t[g].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[g].state,se),r=0;for(;;){let n=Atomics.load(t[g].state,ge);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[g].state,ge,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}li.exports=qr});var zr=R((om,di)=>{"use strict";var{createRequire:lu}=require("module"),{existsSync:cu}=require("node:fs"),uu=Or(),{join:Wr,isAbsolute:fi,sep:fu}=require("node:path"),{fileURLToPath:du}=require("node:url"),hu=Fr(),Vr=Lr(),pu=ci();function mu(t){Vr.register(t,Su),Vr.registerBeforeExit(t,_u),t.on("close",function(){Vr.unregister(t)})}function gu(){let t=process.execArgv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--import"||r==="--require"||r==="-r"||r.startsWith("--import=")||r.startsWith("--require=")||r.startsWith("-r="))return!0}return!1}function yu(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let r=[],n=!1;for(let s=0;s<e.length;s++){let i=e[s];if(i==="--require"||i==="-r"||i==="--import"){let o=e[s+1];if(o&&ui(o)){n=!0,s++;continue}r.push(i),o&&(r.push(o),s++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(ui(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function ui(t){let e=wu(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=du(r)}catch{return!1}return fi(r)&&!cu(r)}function wu(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function bu(t,e,r,n,s){if(!r.execArgv&&gu()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=yu(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new pu({filename:t,workerData:e,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),r.autoEnd!==!1&&mu(i)}function a(){i.closed||(i.flushSync(),hu(100),i.end())}return i}function Su(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function _u(t){t.flushSync()}function xu(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=uu(),sync:a=!1}=t,l={...t.options},u=typeof o=="string"?[o]:o,d=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),f=t.target;if(f&&r)throw new Error("only one of target or targets can be specified");r?(f=d["pino-worker"]||Wr(__dirname,"worker.js"),l.targets=r.filter(c=>c.target).map(c=>({...c,target:h(c.target)})),l.pipelines=r.filter(c=>c.pipeline).map(c=>c.pipeline.map(m=>({...m,level:c.level,target:h(m.target)})))):e&&(f=d["pino-worker"]||Wr(__dirname,"worker.js"),l.pipelines=[e.map(c=>({...c,target:h(c.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let p=r||e?"pino.transport":f;return bu(h(f),l,i,a,p);function h(c){if(c=d[c]||c,fi(c)||c.indexOf("file://")===0)return c;if(c==="pino/file")return Wr(__dirname,"..","file.js");let m;for(let y of u)try{let w=y==="node:repl"?process.cwd()+fu:y;m=lu(w).resolve(c);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${c}"`);return m}}di.exports=xu});var Et=R((am,Ci)=>{"use strict";var vu=require("node:diagnostics_channel"),hi=Ps(),{mapHttpRequest:ku,mapHttpResponse:Cu}=Er(),Jr=Us(),pi=Lr(),{lsCacheSym:Tu,chindingsSym:bi,writeSym:mi,serializersSym:Si,formatOptsSym:gi,endSym:Au,stringifiersSym:_i,stringifySym:xi,stringifySafeSym:Gr,wildcardFirstSym:vi,nestedKeySym:Eu,formattersSym:ki,messageKeySym:Ou,errorKeySym:$u,nestedKeyStrSym:Ru,msgPrefixSym:Tt}=Pe(),{isMainThread:Iu}=require("worker_threads"),Pu=zr(),[Fu]=process.versions.node.split(".").map(t=>Number(t)),yi=vu.tracingChannel("pino_asJson"),Kr=Fu>=25?t=>JSON.stringify(t):Du;function Me(){}function Mu(t,e){if(!e)return r;return function(...s){e.call(this,s,r,t)};function r(n,...s){if(typeof n=="object"){let i=n;n!==null&&(n.method&&n.headers&&n.socket?n=ku(n):typeof n.setHeader=="function"&&(n=Cu(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Tt]=="string"&&i!==void 0&&i!==null&&(i=this[Tt]+i),this[mi](n,hi(i,o,this[gi]),t)}else{let i=n===void 0?s.shift():n;typeof this[Tt]=="string"&&i!==void 0&&i!==null&&(i=this[Tt]+i),this[mi](null,hi(i,s,this[gi]),t)}}}function Du(t){let e="",r=0,n=!1,s=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&s>=32;o++)s=t.charCodeAt(o),(s===34||s===92)&&(e+=t.slice(r,o)+"\\",r=o,n=!0);return n?e+=t.slice(r):e=t,s<32?JSON.stringify(t):'"'+e+'"'}function Lu(t,e,r,n){if(yi.hasSubscribers===!1)return wi.call(this,t,e,r,n);let s={instance:this,arguments};return yi.traceSync(wi,s,this,t,e,r,n)}function wi(t,e,r,n){let s=this[xi],i=this[Gr],o=this[_i],a=this[Au],l=this[bi],u=this[Si],d=this[ki],f=this[Ou],p=this[$u],h=this[Tu][r]+n;h=h+l;let c;d.log&&(t=d.log(t));let m=o[vi],y="";for(let b in t)if(c=t[b],Object.prototype.hasOwnProperty.call(t,b)&&c!==void 0){u[b]?c=u[b](c):b===p&&u.err&&(c=u.err(c));let _=o[b]||m;switch(typeof c){case"undefined":case"function":continue;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":_&&(c=_(c));break;case"string":c=(_||Kr)(c);break;default:c=(_||s)(c,i)}if(c===void 0)continue;let S=Kr(b);y+=","+S+":"+c}let w="";if(e!==void 0){c=u[f]?u[f](e):e;let b=o[f]||m;switch(typeof c){case"function":break;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":b&&(c=b(c)),w=',"'+f+'":'+c;break;case"string":c=(b||Kr)(c),w=',"'+f+'":'+c;break;default:c=(b||s)(c,i),w=',"'+f+'":'+c}}return this[Eu]&&y?h+this[Ru]+y.slice(1)+"}"+w+a:h+y+w+a}function ju(t,e){let r,n=t[bi],s=t[xi],i=t[Gr],o=t[_i],a=o[vi],l=t[Si],u=t[ki].bindings;e=u(e);for(let d in e)if(r=e[d],((d.length<5||d!=="level"&&d!=="serializers"&&d!=="formatters"&&d!=="customLevels")&&e.hasOwnProperty(d)&&r!==void 0)===!0){if(r=l[d]?l[d](r):r,r=(o[d]||a||s)(r,i),r===void 0)continue;n+=',"'+d+'":'+r}return n}function Nu(t){return t.write!==t.constructor.prototype.write}function At(t){let e=new Jr(t);return e.on("error",r),!t.sync&&Iu&&(pi.register(e,qu),e.on("close",function(){pi.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Me,e.end=Me,e.flushSync=Me,e.destroy=Me;return}e.removeListener("error",r),e.emit("error",n)}}function qu(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Uu(t){return function(r,n,s={},i){if(typeof s=="string")i=At({dest:s}),s={};else if(typeof i=="string"){if(s&&s.transport)throw Error("only one of option.transport or stream can be specified");i=At({dest:i})}else if(s instanceof Jr||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof Jr||s.transport.writable||s.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(s.transport.targets&&s.transport.targets.length&&s.formatters&&typeof s.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;s.customLevels&&(l=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=Pu({caller:n,...s.transport,levels:l})}if(s=Object.assign({},t,s),s.serializers=Object.assign({},t.serializers,s.serializers),s.formatters=Object.assign({},t.formatters,s.formatters),s.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=s;return o===!1&&(s.level="silent"),a||(s.onChild=Me),i||(Nu(process.stdout)?i=process.stdout:i=At({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function Bu(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[Gr])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Hu(t,e,r){return{level:t,bindings:e,log:r}}function Wu(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Ci.exports={noop:Me,buildSafeSonicBoom:At,asChindings:ju,asJson:Lu,genLog:Mu,createArgsNormalizer:Uu,stringify:Bu,buildFormatters:Hu,normalizeDestFileDescriptor:Wu}});var Ot=R((lm,Ti)=>{var Vu={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},zu={ASC:"ASC",DESC:"DESC"};Ti.exports={DEFAULT_LEVELS:Vu,SORTING_ORDER:zu}});var Zr=R((cm,$i)=>{"use strict";var{lsCacheSym:Ku,levelValSym:Xr,useOnlyCustomLevelsSym:Ju,streamSym:Gu,formattersSym:Xu,hooksSym:Yu,levelCompSym:Ai}=Pe(),{noop:Zu,genLog:ye}=Et(),{DEFAULT_LEVELS:ee,SORTING_ORDER:Ei}=Ot(),Oi={fatal:t=>{let e=ye(ee.fatal,t);return function(...r){let n=this[Gu];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>ye(ee.error,t),warn:t=>ye(ee.warn,t),info:t=>ye(ee.info,t),debug:t=>ye(ee.debug,t),trace:t=>ye(ee.trace,t)},Yr=Object.keys(ee).reduce((t,e)=>(t[ee[e]]=e,t),{}),Qu=Object.keys(Yr).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function ef(t){let e=t[Xu].level,{labels:r}=t.levels,n={};for(let s in r){let i=e(r[s],Number(s));n[s]=JSON.stringify(i).slice(0,-1)}return t[Ku]=n,t}function tf(t,e){if(e)return!1;switch(t){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function rf(t){let{labels:e,values:r}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(r[t]===void 0)throw Error("unknown level "+t);let n=this[Xr],s=this[Xr]=r[t],i=this[Ju],o=this[Ai],a=this[Yu].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=Zu;continue}this[l]=tf(l,i)?Oi[l](a):ye(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function nf(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function sf(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Ai](r,this[Xr])}function of(t,e,r){return t===Ei.DESC?e<=r:e>=r}function af(t){return typeof t=="string"?of.bind(null,t):t}function lf(t=null,e=!1){let r=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:Yr,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:ee,t);return{labels:n,values:s}}function cf(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(Yr).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:ee,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function uf(t,e){let{labels:r,values:n}=t;for(let s in e){if(s in n)throw Error("levels cannot be overridden");if(e[s]in r)throw Error("pre-existing level values cannot be used for new levels")}}function ff(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Ei).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}$i.exports={initialLsCache:Qu,genLsCache:ef,levelMethods:Oi,getLevel:nf,setLevel:rf,isLevelEnabled:sf,mappings:lf,assertNoLevelCollisions:uf,assertDefaultLevelFound:cf,genLevelComparison:af,assertLevelComparison:ff}});var Qr=R((um,Ri)=>{"use strict";Ri.exports={version:"10.3.1"}});var Ni=R((dm,ji)=>{"use strict";var{EventEmitter:df}=require("node:events"),{lsCacheSym:hf,levelValSym:pf,setLevelSym:tn,getLevelSym:Ii,chindingsSym:Rt,mixinSym:mf,asJsonSym:Fi,writeSym:gf,mixinMergeStrategySym:yf,timeSym:wf,timeSliceIndexSym:bf,streamSym:Mi,serializersSym:we,formattersSym:rt,errorKeySym:Sf,messageKeySym:_f,useOnlyCustomLevelsSym:xf,needsMetadataGsym:vf,redactFmtSym:kf,stringifySym:Cf,formatOptsSym:Tf,stringifiersSym:Af,msgPrefixSym:rn,hooksSym:Ef}=Pe(),{getLevel:Of,setLevel:$f,isLevelEnabled:Rf,mappings:If,initialLsCache:Pf,genLsCache:Ff,assertNoLevelCollisions:Mf}=Zr(),{asChindings:nn,asJson:Df,buildFormatters:en,stringify:Pi,noop:Di}=Et(),{version:Lf}=Qr(),jf=Ir(),Nf=class{},Li={constructor:Nf,child:qf,bindings:Uf,setBindings:Bf,flush:Vf,isLevelEnabled:Rf,version:Lf,get level(){return this[Ii]()},set level(t){this[tn](t)},get levelVal(){return this[pf]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[rn]},get[Symbol.toStringTag](){return"Pino"},[hf]:Pf,[gf]:Wf,[Fi]:Df,[Ii]:Of,[tn]:$f};Object.setPrototypeOf(Li,df.prototype);ji.exports=function(){return Object.create(Li)};var $t=t=>t;function qf(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[we],n=this[rt],s=Object.create(this);if(e==null)return s[rt].bindings!==$t&&(s[rt]=en(n.level,$t,n.log)),s[Rt]=nn(s,t),this.onChild!==Di&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[we]=Object.create(null);for(let u in r)s[we][u]=r[u];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let u=a[i];s[we][u]=r[u]}for(let u in e.serializers)s[we][u]=e.serializers[u];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let u=l[o];s[we][u]=e.serializers[u]}}else s[we]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:u}=e.formatters;s[rt]=en(a||n.level,l||$t,u||n.log)}else s[rt]=en(n.level,$t,n.log);if(e.hasOwnProperty("customLevels")===!0&&(Mf(this.levels,e.customLevels),s.levels=If(e.customLevels,s[xf]),Ff(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=jf(s.redact,Pi),l={stringify:a[kf]};s[Cf]=Pi,s[Af]=a,s[Tf]=l}if(typeof e.msgPrefix=="string"&&(s[rn]=(this[rn]||"")+e.msgPrefix),s[Rt]=nn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[tn](a)}return this.onChild(s),s}function Uf(){let e=`{${this[Rt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Bf(t){let e=nn(this,t);this[Rt]=e}function Hf(t,e){return Object.assign(e,t)}function Wf(t,e,r){let n=this[wf](),s=this[mf],i=this[Sf],o=this[_f],a=this[yf]||Hf,l,u=this[Ef].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(l=a(l,s(l,r,this)));let d=this[Fi](l,e,r,n),f=this[Mi];f[vf]===!0&&(f.lastLevel=r,f.lastObj=l,f.lastMsg=e,f.lastTime=n.slice(this[bf]),f.lastLogger=this),f.write(u?u(d):d)}function Vf(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Mi];typeof e.flush=="function"?e.flush(t||Di):t&&t()}});var Hi=R((ln,Bi)=>{"use strict";var{hasOwnProperty:nt}=Object.prototype,Se=an();Se.configure=an;Se.stringify=Se;Se.default=Se;ln.stringify=Se;ln.configure=an;Bi.exports=Se;var zf=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function ce(t){return t.length<5e3&&!zf.test(t)?`"${t}"`:JSON.stringify(t)}function sn(t,e){if(t.length>200||e)return t.sort(e);for(let r=1;r<t.length;r++){let n=t[r],s=r;for(;s!==0&&t[s-1]>n;)t[s]=t[s-1],s--;t[s]=n}return t}var Kf=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function on(t){return Kf.call(t)!==void 0&&t.length!==0}function qi(t,e,r){t.length<r&&(r=t.length);let n=e===","?"":" ",s=`"0":${n}${t[0]}`;for(let i=1;i<r;i++)s+=`${e}"${i}":${n}${t[i]}`;return s}function Jf(t){if(nt.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function Gf(t){let e;if(nt.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function Xf(t,e){let r;if(nt.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function Ui(t,e){let r;if(nt.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function be(t){return t===1?"1 item":`${t} items`}function Yf(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function Zf(t){if(nt.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function an(t){t={...t};let e=Zf(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Jf(t),n=Xf(t,"bigint"),s=Gf(t),i=typeof s=="function"?s:void 0,o=Ui(t,"maximumDepth"),a=Ui(t,"maximumBreadth");function l(h,c,m,y,w,b){let _=c[h];switch(typeof _=="object"&&_!==null&&typeof _.toJSON=="function"&&(_=_.toJSON(h)),_=y.call(c,h,_),typeof _){case"string":return ce(_);case"object":{if(_===null)return"null";if(m.indexOf(_)!==-1)return r;let S="",v=",",$=b;if(Array.isArray(_)){if(_.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(_),w!==""&&(b+=w,S+=`
26
- ${b}`,v=`,
27
- ${b}`);let F=Math.min(_.length,a),q=0;for(;q<F-1;q++){let U=l(String(q),_,m,y,w,b);S+=U!==void 0?U:"null",S+=v}let N=l(String(q),_,m,y,w,b);if(S+=N!==void 0?N:"null",_.length-1>a){let U=_.length-a-1;S+=`${v}"... ${be(U)} not stringified"`}return w!==""&&(S+=`
28
- ${$}`),m.pop(),`[${S}]`}let T=Object.keys(_),O=T.length;if(O===0)return"{}";if(o<m.length+1)return'"[Object]"';let C="",I="";w!==""&&(b+=w,v=`,
29
- ${b}`,C=" ");let L=Math.min(O,a);s&&!on(_)&&(T=sn(T,i)),m.push(_);for(let F=0;F<L;F++){let q=T[F],N=l(q,_,m,y,w,b);N!==void 0&&(S+=`${I}${ce(q)}:${C}${N}`,I=v)}if(O>a){let F=O-a;S+=`${I}"...":${C}"${be(F)} not stringified"`,I=v}return w!==""&&I.length>1&&(S=`
23
+ `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Jn(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})}Xn.Command=vr});var ts=I(J=>{var{Argument:Zn}=xt(),{Command:kr}=Yn(),{CommanderError:pl,InvalidArgumentError:Qn}=st(),{Help:hl}=mr(),{Option:es}=br();J.program=new kr;J.createCommand=t=>new kr(t);J.createOption=(t,e)=>new es(t,e);J.createArgument=(t,e)=>new Zn(t,e);J.Command=kr;J.Option=es;J.Argument=Zn;J.Help=hl;J.CommanderError=pl;J.InvalidArgumentError=Qn;J.InvalidOptionArgumentError=Qn});var Tr=I((Yh,ls)=>{"use strict";var ot=t=>t&&typeof t.message=="string",$r=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return ot(r)?r:void 0}else return ot(e)?e:void 0},os=(t,e)=>{if(!ot(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
+ causes have become circular...`;let n=$r(t);return n?(e.add(t),r+`
25
+ caused by: `+os(n,e)):r},ml=t=>os(t,new Set),as=(t,e,r)=>{if(!ot(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=$r(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+as(s,e,i)}else return n},gl=t=>as(t,new Set);ls.exports={isErrorLike:ot,getErrorCause:$r,stackWithCauses:ml,messageWithCauses:gl}});var Ar=I((Zh,us)=>{"use strict";var yl=Symbol("circular-ref-tag"),vt=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[vt]},set:function(t){this[vt]=t}}});Object.defineProperty(cs,vt,{writable:!0,value:{}});us.exports={pinoErrProto:cs,pinoErrorSymbols:{seen:yl,rawSymbol:vt}}});var ps=I((Qh,ds)=>{"use strict";ds.exports=Or;var{messageWithCauses:wl,stackWithCauses:bl,isErrorLike:fs}=Tr(),{pinoErrProto:Sl,pinoErrorSymbols:_l}=Ar(),{seen:Er}=_l,{toString:xl}=Object.prototype;function Or(t){if(!fs(t))return t;t[Er]=void 0;let e=Object.create(Sl);e.type=xl.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=wl(t),e.stack=bl(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Or(r)));for(let r in t)if(e[r]===void 0){let n=t[r];fs(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Er)&&(e[r]=Or(n)):e[r]=n}return delete t[Er],e.raw=t,e}});var ms=I((em,hs)=>{"use strict";hs.exports=Ct;var{isErrorLike:Rr}=Tr(),{pinoErrProto:vl,pinoErrorSymbols:kl}=Ar(),{seen:kt}=kl,{toString:Cl}=Object.prototype;function Ct(t){if(!Rr(t))return t;t[kt]=void 0;let e=Object.create(vl);e.type=Cl.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=>Ct(r))),Rr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,kt)&&(e.cause=Ct(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];Rr(n)?Object.prototype.hasOwnProperty.call(n,kt)||(e[r]=Ct(n)):e[r]=n}return delete t[kt],e.raw=t,e}});var bs=I((tm,ws)=>{"use strict";ws.exports={mapHttpRequest:$l,reqSerializer:ys};var Ir=Symbol("pino-raw-req-ref"),gs=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[Ir]},set:function(t){this[Ir]=t}}});Object.defineProperty(gs,Ir,{writable:!0,value:{}});function ys(t){let e=t.info||t.socket,r=Object.create(gs);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 $l(t){return{req:ys(t)}}});var vs=I((rm,xs)=>{"use strict";xs.exports={mapHttpResponse:Tl,resSerializer:_s};var Pr=Symbol("pino-raw-res-ref"),Ss=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Pr]},set:function(t){this[Pr]=t}}});Object.defineProperty(Ss,Pr,{writable:!0,value:{}});function _s(t){let e=Object.create(Ss);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function Tl(t){return{res:_s(t)}}});var Fr=I((nm,ks)=>{"use strict";var Mr=ps(),Al=ms(),$t=bs(),Tt=vs();ks.exports={err:Mr,errWithCause:Al,mapHttpRequest:$t.mapHttpRequest,mapHttpResponse:Tt.mapHttpResponse,req:$t.reqSerializer,res:Tt.resSerializer,wrapErrorSerializer:function(e){return e===Mr?e:function(n){return e(Mr(n))}},wrapRequestSerializer:function(e){return e===$t.reqSerializer?e:function(n){return e($t.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Tt.resSerializer?e:function(n){return e(Tt.resSerializer(n))}}}});var Lr=I((sm,Cs)=>{"use strict";function El(t,e){return e}Cs.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=El;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 Rs=I((im,Os)=>{"use strict";function Dr(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]=Dr(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]=Dr(t[r]));return e}return t}function $s(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 Ts(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 As(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 At=Symbol("PATH_NOT_FOUND");function Ol(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return At;r=r[n]}return r}function Rl(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 Il(t,e,r,n=!1){for(let s of e){let i=$s(s);if(i.includes("*"))Es(t,i,r,s,n);else if(n)As(t,i);else{let o=Ol(t,i);if(o===At)continue;let a=typeof r=="function"?r(o,i):r;Ts(t,i,a)}}}function Es(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 f=[...o,l.toString()],u=typeof r=="function"?r(a[l],f):r;a[l]=u}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let f in a)Object.prototype.hasOwnProperty.call(a,f)&&l.push(f);for(let f of l)delete a[f]}else for(let l in a){let f=[...o,l],u=typeof r=="function"?r(a[l],f):r;a[l]=u}}else Pl(t,e,r,i,n,s)}function Pl(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function f(u,d){if(d===o.length){if(Array.isArray(u))for(let h=0;h<u.length;h++)l[d]=h.toString(),f(u[h],d+1);else if(typeof u=="object"&&u!==null)for(let h in u)l[d]=h,f(u[h],d+1)}else if(d<o.length){let h=o[d];u&&typeof u=="object"&&u!==null&&h in u&&(l[d]=h,f(u[h],d+1))}else if(a.includes("*"))Es(u,a,typeof r=="function"?(p,c)=>{let m=[...l.slice(0,d),...c];return r(p,m)}:r,s,i);else if(i)As(u,a);else{let h=typeof r=="function"?r(Rl(u,a),[...l.slice(0,d),...a]):r;Ts(u,a,h)}}if(o.length===0)f(t,0);else{let u=t;for(let d=0;d<o.length;d++){let h=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[h],l[d]=h}u!=null&&f(u,o.length)}}function Ml(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=$s(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 Fl(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 f=l.toString();s.has(f)||s.has("*")?a[l]=r(n[l],s.get(f)||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 Ll(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 Dl(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)Ll(e)}function jl(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;Dl(e);let o=Ml(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let f=Fl(l,o),u=l,d=r;return typeof r=="function"&&(d=r),Il(f,e,d,i),n===!1?(f.restore=function(){return Dr(u)},f):typeof n=="function"?n(f):JSON.stringify(f)}}Os.exports=jl});var Ne=I((om,Is)=>{"use strict";var Nl=Symbol("pino.setLevel"),ql=Symbol("pino.getLevel"),Ul=Symbol("pino.levelVal"),Bl=Symbol("pino.levelComp"),Hl=Symbol("pino.useLevelLabels"),Wl=Symbol("pino.useOnlyCustomLevels"),Vl=Symbol("pino.mixin"),zl=Symbol("pino.lsCache"),Kl=Symbol("pino.chindings"),Gl=Symbol("pino.asJson"),Jl=Symbol("pino.write"),Xl=Symbol("pino.redactFmt"),Yl=Symbol("pino.time"),Zl=Symbol("pino.timeSliceIndex"),Ql=Symbol("pino.stream"),ec=Symbol("pino.stringify"),tc=Symbol("pino.stringifySafe"),rc=Symbol("pino.stringifiers"),nc=Symbol("pino.end"),sc=Symbol("pino.formatOpts"),ic=Symbol("pino.messageKey"),oc=Symbol("pino.errorKey"),ac=Symbol("pino.nestedKey"),lc=Symbol("pino.nestedKeyStr"),cc=Symbol("pino.mixinMergeStrategy"),uc=Symbol("pino.msgPrefix"),fc=Symbol("pino.wildcardFirst"),dc=Symbol.for("pino.serializers"),pc=Symbol.for("pino.formatters"),hc=Symbol.for("pino.hooks"),mc=Symbol.for("pino.metadata");Is.exports={setLevelSym:Nl,getLevelSym:ql,levelValSym:Ul,levelCompSym:Bl,useLevelLabelsSym:Hl,mixinSym:Vl,lsCacheSym:zl,chindingsSym:Kl,asJsonSym:Gl,writeSym:Jl,serializersSym:dc,redactFmtSym:Xl,timeSym:Yl,timeSliceIndexSym:Zl,streamSym:Ql,stringifySym:ec,stringifySafeSym:tc,stringifiersSym:rc,endSym:nc,formatOptsSym:sc,messageKeySym:ic,errorKeySym:oc,nestedKeySym:ac,wildcardFirstSym:fc,needsMetadataGsym:mc,useOnlyCustomLevelsSym:Wl,formattersSym:pc,hooksSym:hc,nestedKeyStrSym:lc,mixinMergeStrategySym:cc,msgPrefixSym:uc}});var Nr=I((am,Ls)=>{"use strict";var Ps=Rs(),{redactFmtSym:gc,wildcardFirstSym:Et}=Ne(),jr=/[^.[\]]+|\[([^[\]]*?)\]/g,Ms="[Redacted]",Fs=!1;function yc(t,e){let{paths:r,censor:n,remove:s}=wc(t),i=r.reduce((l,f)=>{jr.lastIndex=0;let u=jr.exec(f),d=jr.exec(f),h=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(h==="*"&&(h=Et),d===null)return l[h]=null,l;if(l[h]===null)return l;let{index:p}=d,c=`${f.substr(p,f.length-1)}`;return l[h]=l[h]||[],h!==Et&&l[h].length===0&&l[h].push(...l[Et]||[]),h===Et&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(c)}),l[h].push(c),l},{}),o={[gc]:Ps({paths:r,censor:n,serialize:e,strict:Fs,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,f)=>{if(i[f]===null)l[f]=u=>a(u,[f]);else{let u=typeof n=="function"?(d,h)=>n(d,[f,...h]):n;l[f]=Ps({paths:i[f],censor:u,serialize:e,strict:Fs,remove:s})}return l},o)}function wc(t){if(Array.isArray(t))return t={paths:t,censor:Ms},t;let{paths:e,censor:r=Ms,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}}Ls.exports=yc});var Ns=I((lm,js)=>{"use strict";var bc=()=>"",Sc=()=>`,"time":${Date.now()}`,_c=()=>`,"time":${Math.round(Date.now()/1e3)}`,xc=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,vc=1000000n,Ds=1000000000n,kc=BigInt(Date.now())*vc,Cc=process.hrtime.bigint(),$c=()=>{let t=process.hrtime.bigint()-Cc,e=kc+t,r=e/Ds,n=e%Ds,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"),f=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${f}:${u}:${d}.${n.toString().padStart(9,"0")}Z"`};js.exports={nullTime:bc,epochTime:Sc,unixTime:_c,isoTime:xc,isoTimeNano:$c}});var Us=I((cm,qs)=>{"use strict";function Tc(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}qs.exports=Ac;function Ac(t,e,r){var n=r&&r.stringify||Tc,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 f="",u=1-s,d=-1,h=t&&t.length||0,p=0;p<h;){if(t.charCodeAt(p)===37&&p+1<h){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<p&&(f+=t.slice(d,p)),f+=Number(e[u]),d=p+2,p++;break;case 105:if(u>=l||e[u]==null)break;d<p&&(f+=t.slice(d,p)),f+=Math.floor(Number(e[u])),d=p+2,p++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<p&&(f+=t.slice(d,p));var c=typeof e[u];if(c==="string"){f+="'"+e[u]+"'",d=p+2,p++;break}if(c==="function"){f+=e[u].name||"<anonymous>",d=p+2,p++;break}f+=n(e[u]),d=p+2,p++;break;case 115:if(u>=l)break;d<p&&(f+=t.slice(d,p)),f+=String(e[u]),d=p+2,p++;break;case 37:d<p&&(f+=t.slice(d,p)),f+="%",d=p+2,p++,u--;break}++u}++p}return d===-1?t:(d<h&&(f+=t.slice(d)),f)}});var Ur=I((um,qr)=>{"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));qr.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(););};qr.exports=t}});var Js=I((fm,Gs)=>{"use strict";var D=require("fs"),Ec=require("events"),Oc=require("util").inherits,Bs=require("path"),Hr=Ur(),Rc=require("assert"),Ot=100,Rt=Buffer.allocUnsafe(0),Ic=16*1024,Hs="buffer",Ws="utf8",[Pc,Mc]=(process.versions.node||"0.0").split(".").map(Number),Fc=Pc>=22&&Mc>=7;function Vs(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&&D.mkdirSync(Bs.dirname(t),{recursive:!0});let i=D.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?D.mkdir(Bs.dirname(t),{recursive:!0},i=>{if(i)return r(i);D.open(t,n,s,r)}):D.open(t,n,s,r)}function te(t){if(!(this instanceof te))return new te(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:f,retryEAGAIN:u,fsync:d,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||Ic,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=p,this.retryEAGAIN=u||(()=>!0),this.mkdir=f||!1;let c,m;if(h===Hs)this._writingBuf=Rt,this.write=jc,this.flush=qc,this.flushSync=Bc,this._actualWrite=Wc,c=()=>D.writeSync(this.fd,this._writingBuf),m=()=>D.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===Ws)this._writingBuf="",this.write=Dc,this.flush=Nc,this.flushSync=Uc,this._actualWrite=Hc,c=()=>Buffer.isBuffer(this._writingBuf)?D.writeSync(this.fd,this._writingBuf):D.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?D.write(this.fd,this._writingBuf,this.release):D.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Ws}" and "${Hs}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Vs(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(y,w)=>{if(y){if((y.code==="EAGAIN"||y.code==="EBUSY")&&this.retryEAGAIN(y,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Hr(Ot),this.release(void 0,0)}catch(S){this.release(S)}else setTimeout(m,Ot);else this._writing=!1,this.emit("error",y);return}this.emit("write",w);let b=Br(this._writingBuf,this._len,w);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let S=c(),k=Br(this._writingBuf,this._len,S);this._len=k.len,this._writingBuf=k.writingBuf}while(this._writingBuf.length)}catch(S){this.release(S);return}}this._fsync&&D.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,It(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Lc,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 Br(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 Lc(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Oc(te,Ec);function zs(t,e){return t.length===0?Rt:t.length===1?t[0]:Buffer.concat(t,e)}function Dc(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 jc(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 Ks(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{D.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 Nc(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&&Ks.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function qc(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&&Ks.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}te.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&&D.close(e,r=>{if(r)return this.emit("error",r)})}),Vs(this.file,this)};te.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():It(this)))};function Uc(){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)?D.writeSync(this.fd,t):D.writeSync(this.fd,t,"utf8"),r=Br(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;Hr(Ot)}}try{D.fsyncSync(this.fd)}catch{}}function Bc(){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=Rt);let t=Rt;for(;this._bufs.length||t.length;){t.length<=0&&(t=zs(this._bufs[0],this._lens[0]));try{let e=D.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;Hr(Ot)}}}te.prototype.destroy=function(){this.destroyed||It(this)};function Hc(){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)?D.writeSync(this.fd,this._writingBuf):D.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else D.write(this.fd,this._writingBuf,t)}function Wc(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:zs(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=D.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else Fc&&(this._writingBuf=Buffer.from(this._writingBuf)),D.write(this.fd,this._writingBuf,t)}function It(t){if(t.fd===-1){t.once("ready",It.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Rc(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{D.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?D.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")}}te.SonicBoom=te;te.default=te;Gs.exports=te});var Wr=I((dm,ei)=>{"use strict";var re={exit:[],beforeExit:[]},Xs={exit:Kc,beforeExit:Gc},qe;function Vc(){qe===void 0&&(qe=new FinalizationRegistry(Jc))}function zc(t){re[t].length>0||process.on(t,Xs[t])}function Ys(t){re[t].length>0||(process.removeListener(t,Xs[t]),re.exit.length===0&&re.beforeExit.length===0&&(qe=void 0))}function Kc(){Zs("exit")}function Gc(){Zs("beforeExit")}function Zs(t){for(let e of re[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}re[t]=[]}function Jc(t){for(let e of["exit","beforeExit"]){let r=re[e].indexOf(t);re[e].splice(r,r+1),Ys(e)}}function Qs(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");zc(t);let n=new WeakRef(e);n.fn=r,Vc(),qe.register(e,n),re[t].push(n)}function Xc(t,e){Qs("exit",t,e)}function Yc(t,e){Qs("beforeExit",t,e)}function Zc(t){if(qe!==void 0){qe.unregister(t);for(let e of["exit","beforeExit"])re[e]=re[e].filter(r=>{let n=r.deref();return n&&n!==t}),Ys(e)}}ei.exports={register:Xc,registerBeforeExit:Yc,unregister:Zc}});var ti=I((pm,Qc)=>{Qc.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 ni=I((hm,ri)=>{"use strict";function eu(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())),f=Atomics.waitAsync(t,e,a,l);f.async?f.value.then(o):setImmediate(o)};o()}function tu(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())),f=Atomics.waitAsync(t,e,r,l);f.async?f.value.then(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}ri.exports={wait:eu,waitDiff:tu}});var ii=I((mm,si)=>{"use strict";si.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var yi=I((gm,gi)=>{"use strict";var{version:ru}=ti(),{EventEmitter:nu}=require("events"),{Worker:su}=require("worker_threads"),{join:iu}=require("path"),{pathToFileURL:ou}=require("url"),{wait:au}=ni(),{WRITE_INDEX:le,READ_INDEX:xe,SEQ_INDEX:Vr}=ii(),lu=require("buffer"),cu=require("assert"),g=Symbol("kImpl"),uu=lu.constants.MAX_STRING_LENGTH;function oi(){}function Jr(t,e){Atomics.add(t[g].state,Vr,1),e(),Atomics.add(t[g].state,Vr,1),Atomics.notify(t[g].state,Vr)}function ai(t){Jr(t,()=>{Atomics.store(t[g].state,xe,0),Atomics.store(t[g].state,le,0)})}var at=class{constructor(e){this._value=e}deref(){return this._value}},Pt=class{register(){}unregister(){}},fu=process.env.NODE_V8_COVERAGE?Pt:global.FinalizationRegistry||Pt,du=process.env.NODE_V8_COVERAGE?at:global.WeakRef||at,li=new fu(t=>{t.exited||t.terminate()});function pu(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||iu(__dirname,"lib","worker.js"),o=new su(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:ou(r).href,dataBuf:t[g].dataBuf,stateBuf:t[g].stateBuf,workerData:{$context:{threadStreamVersion:ru},...n}}});return o.stream=new at(t),o.on("message",hu),o.on("exit",fi),li.register(t,o),o}function ci(t){cu(!t[g].sync),t[g].needDrain&&(t[g].needDrain=!1,t.emit("drain"))}function ui(t){for(;;){let e=Atomics.load(t[g].state,le),r=t[g].data.length-e;if(r>0){if(t[g].bufLen===0){t[g].flushing=!1,t[g].ending?Xr(t):t[g].needDrain&&process.nextTick(ci,t);return}hi(t,r,oi);continue}if(r===0){if(e===0&&t[g].bufLen===0)return;Mt(t,()=>{t.destroyed||(ai(t),ui(t))});return}X(t,new Error("overwritten"));return}}function hu(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 du(e),Mt(e,()=>{e[g].ready=!0,e.emit("ready")});break;case"ERROR":X(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"){X(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:X(e,new Error("this should not happen: "+t.code))}}function fi(t){let e=this.stream.deref();e!==void 0&&(li.unregister(e),e.worker.exited=!0,e.worker.off("exit",fi),X(e,t!==0?new Error("the worker thread exited"):null))}var Kr=class extends nu{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=pu(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 Gr(this,new Error("the worker has exited")),!1;if(this[g].ending)return Gr(this,new Error("the worker is ending")),!1;if(this[g].flushing&&this[g].bufLen+r.length>=uu)try{zr(this),this[g].flushing=!0}catch(n){return X(this,n),!1}if(this[g].buf.push(r),this[g].bufLen+=r.length,this[g].sync)try{return zr(this),!0}catch(n){return X(this,n),!1}return this[g].flushing||(this[g].flushing=!0,setImmediate(ui,this)),this[g].needDrain=this[g].data.length-this[g].bufLen-Atomics.load(this[g].state,le)<=0,!this[g].needDrain}end(){this[g].destroyed||(this[g].ending=!0,Xr(this))}flush(e){e=typeof e=="function"?e:oi,di(this,r=>{if(r){process.nextTick(e,r);return}pi(this,e)})}flushSync(){this[g].destroyed||(zr(this),mi(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 di(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(di,t,e);return}Mt(t,e)}function Mt(t,e){let r=Atomics.load(t[g].state,le);au(t[g].state,xe,r,1/0,(n,s)=>{if(n){X(t,n),e(n);return}if(s!=="ok"){Mt(t,e);return}e()})}function pi(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].ready){let n=()=>{i(),pi(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),X(t,n),process.nextTick(e,n)}}function mu(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 Gr(t,e){setImmediate(()=>{t.emit("error",e)})}function X(t,e){t[g].destroyed||(t[g].destroyed=!0,mu(t,e),e&&(t[g].errored=e,Gr(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 hi(t,e,r){let s=Atomics.load(t[g].state,le),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 Jr(t,()=>{Atomics.store(t[g].state,le,s)}),r(),!0}function Xr(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,xe);Jr(t,()=>{Atomics.store(t[g].state,le,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[g].state,xe,e,1e3),e=Atomics.load(t[g].state,xe),e===-2){X(t,new Error("end() failed"));return}if(++r===10){X(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[g].finished=!0,t.emit("finish")})}catch(e){X(t,e)}}}function zr(t){let e=()=>{t[g].ending?Xr(t):t[g].needDrain&&process.nextTick(ci,t)};for(t[g].flushing=!1;t[g].bufLen!==0;){let r=Atomics.load(t[g].state,le),n=t[g].data.length-r;if(n===0){mi(t),ai(t);continue}else if(n<0)throw new Error("overwritten");hi(t,n,e)}}function mi(t){if(t[g].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[g].state,le),r=0;for(;;){let n=Atomics.load(t[g].state,xe);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[g].state,xe,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}gi.exports=Kr});var Qr=I((ym,Si)=>{"use strict";var{createRequire:gu}=require("module"),{existsSync:yu}=require("node:fs"),wu=Lr(),{join:Yr,isAbsolute:bi,sep:bu}=require("node:path"),{fileURLToPath:Su}=require("node:url"),_u=Ur(),Zr=Wr(),xu=yi();function vu(t){Zr.register(t,Au),Zr.registerBeforeExit(t,Eu),t.on("close",function(){Zr.unregister(t)})}function ku(){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 Cu(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&&wi(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(wi(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function wi(t){let e=$u(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=Su(r)}catch{return!1}return bi(r)&&!yu(r)}function $u(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function Tu(t,e,r,n,s){if(!r.execArgv&&ku()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=Cu(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new xu({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&&vu(i)}function a(){i.closed||(i.flushSync(),_u(100),i.end())}return i}function Au(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Eu(t){t.flushSync()}function Ou(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=wu(),sync:a=!1}=t,l={...t.options},f=typeof o=="string"?[o]:o,u=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&r)throw new Error("only one of target or targets can be specified");r?(d=u["pino-worker"]||Yr(__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&&(d=u["pino-worker"]||Yr(__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":d;return Tu(p(d),l,i,a,h);function p(c){if(c=u[c]||c,bi(c)||c.indexOf("file://")===0)return c;if(c==="pino/file")return Yr(__dirname,"..","file.js");let m;for(let y of f)try{let w=y==="node:repl"?process.cwd()+bu:y;m=gu(w).resolve(c);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${c}"`);return m}}Si.exports=Ou});var Dt=I((wm,Pi)=>{"use strict";var Ru=require("node:diagnostics_channel"),_i=Us(),{mapHttpRequest:Iu,mapHttpResponse:Pu}=Fr(),tn=Js(),xi=Wr(),{lsCacheSym:Mu,chindingsSym:Ti,writeSym:vi,serializersSym:Ai,formatOptsSym:ki,endSym:Fu,stringifiersSym:Ei,stringifySym:Oi,stringifySafeSym:rn,wildcardFirstSym:Ri,nestedKeySym:Lu,formattersSym:Ii,messageKeySym:Du,errorKeySym:ju,nestedKeyStrSym:Nu,msgPrefixSym:Ft}=Ne(),{isMainThread:qu}=require("worker_threads"),Uu=Qr(),[Bu]=process.versions.node.split(".").map(t=>Number(t)),Ci=Ru.tracingChannel("pino_asJson"),en=Bu>=25?t=>JSON.stringify(t):Wu;function Ue(){}function Hu(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=Iu(n):typeof n.setHeader=="function"&&(n=Pu(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Ft]=="string"&&i!==void 0&&i!==null&&(i=this[Ft]+i),this[vi](n,_i(i,o,this[ki]),t)}else{let i=n===void 0?s.shift():n;typeof this[Ft]=="string"&&i!==void 0&&i!==null&&(i=this[Ft]+i),this[vi](null,_i(i,s,this[ki]),t)}}}function Wu(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 Vu(t,e,r,n){if(Ci.hasSubscribers===!1)return $i.call(this,t,e,r,n);let s={instance:this,arguments};return Ci.traceSync($i,s,this,t,e,r,n)}function $i(t,e,r,n){let s=this[Oi],i=this[rn],o=this[Ei],a=this[Fu],l=this[Ti],f=this[Ai],u=this[Ii],d=this[Du],h=this[ju],p=this[Mu][r]+n;p=p+l;let c;u.log&&(t=u.log(t));let m=o[Ri],y="";for(let b in t)if(c=t[b],Object.prototype.hasOwnProperty.call(t,b)&&c!==void 0){f[b]?c=f[b](c):b===h&&f.err&&(c=f.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=(_||en)(c);break;default:c=(_||s)(c,i)}if(c===void 0)continue;let S=en(b);y+=","+S+":"+c}let w="";if(e!==void 0){c=f[d]?f[d](e):e;let b=o[d]||m;switch(typeof c){case"function":break;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":b&&(c=b(c)),w=',"'+d+'":'+c;break;case"string":c=(b||en)(c),w=',"'+d+'":'+c;break;default:c=(b||s)(c,i),w=',"'+d+'":'+c}}return this[Lu]&&y?p+this[Nu]+y.slice(1)+"}"+w+a:p+y+w+a}function zu(t,e){let r,n=t[Ti],s=t[Oi],i=t[rn],o=t[Ei],a=o[Ri],l=t[Ai],f=t[Ii].bindings;e=f(e);for(let u in e)if(r=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&r!==void 0)===!0){if(r=l[u]?l[u](r):r,r=(o[u]||a||s)(r,i),r===void 0)continue;n+=',"'+u+'":'+r}return n}function Ku(t){return t.write!==t.constructor.prototype.write}function Lt(t){let e=new tn(t);return e.on("error",r),!t.sync&&qu&&(xi.register(e,Gu),e.on("close",function(){xi.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Ue,e.end=Ue,e.flushSync=Ue,e.destroy=Ue;return}e.removeListener("error",r),e.emit("error",n)}}function Gu(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Ju(t){return function(r,n,s={},i){if(typeof s=="string")i=Lt({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=Lt({dest:i})}else if(s instanceof tn||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof tn||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=Uu({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=Ue),i||(Ku(process.stdout)?i=process.stdout:i=Lt({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function Xu(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[rn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Yu(t,e,r){return{level:t,bindings:e,log:r}}function Zu(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Pi.exports={noop:Ue,buildSafeSonicBoom:Lt,asChindings:zu,asJson:Vu,genLog:Hu,createArgsNormalizer:Ju,stringify:Xu,buildFormatters:Yu,normalizeDestFileDescriptor:Zu}});var jt=I((bm,Mi)=>{var Qu={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},ef={ASC:"ASC",DESC:"DESC"};Mi.exports={DEFAULT_LEVELS:Qu,SORTING_ORDER:ef}});var on=I((Sm,ji)=>{"use strict";var{lsCacheSym:tf,levelValSym:nn,useOnlyCustomLevelsSym:rf,streamSym:nf,formattersSym:sf,hooksSym:of,levelCompSym:Fi}=Ne(),{noop:af,genLog:ve}=Dt(),{DEFAULT_LEVELS:ie,SORTING_ORDER:Li}=jt(),Di={fatal:t=>{let e=ve(ie.fatal,t);return function(...r){let n=this[nf];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>ve(ie.error,t),warn:t=>ve(ie.warn,t),info:t=>ve(ie.info,t),debug:t=>ve(ie.debug,t),trace:t=>ve(ie.trace,t)},sn=Object.keys(ie).reduce((t,e)=>(t[ie[e]]=e,t),{}),lf=Object.keys(sn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function cf(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[tf]=n,t}function uf(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 ff(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[nn],s=this[nn]=r[t],i=this[rf],o=this[Fi],a=this[of].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=af;continue}this[l]=uf(l,i)?Di[l](a):ve(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function df(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function pf(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Fi](r,this[nn])}function hf(t,e,r){return t===Li.DESC?e<=r:e>=r}function mf(t){return typeof t=="string"?hf.bind(null,t):t}function gf(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:sn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:ie,t);return{labels:n,values:s}}function yf(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(sn).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:ie,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function wf(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 bf(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Li).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}ji.exports={initialLsCache:lf,genLsCache:cf,levelMethods:Di,getLevel:df,setLevel:ff,isLevelEnabled:pf,mappings:gf,assertNoLevelCollisions:wf,assertDefaultLevelFound:yf,genLevelComparison:mf,assertLevelComparison:bf}});var an=I((_m,Ni)=>{"use strict";Ni.exports={version:"10.3.1"}});var Ki=I((vm,zi)=>{"use strict";var{EventEmitter:Sf}=require("node:events"),{lsCacheSym:_f,levelValSym:xf,setLevelSym:cn,getLevelSym:qi,chindingsSym:qt,mixinSym:vf,asJsonSym:Bi,writeSym:kf,mixinMergeStrategySym:Cf,timeSym:$f,timeSliceIndexSym:Tf,streamSym:Hi,serializersSym:ke,formattersSym:lt,errorKeySym:Af,messageKeySym:Ef,useOnlyCustomLevelsSym:Of,needsMetadataGsym:Rf,redactFmtSym:If,stringifySym:Pf,formatOptsSym:Mf,stringifiersSym:Ff,msgPrefixSym:un,hooksSym:Lf}=Ne(),{getLevel:Df,setLevel:jf,isLevelEnabled:Nf,mappings:qf,initialLsCache:Uf,genLsCache:Bf,assertNoLevelCollisions:Hf}=on(),{asChindings:fn,asJson:Wf,buildFormatters:ln,stringify:Ui,noop:Wi}=Dt(),{version:Vf}=an(),zf=Nr(),Kf=class{},Vi={constructor:Kf,child:Gf,bindings:Jf,setBindings:Xf,flush:Qf,isLevelEnabled:Nf,version:Vf,get level(){return this[qi]()},set level(t){this[cn](t)},get levelVal(){return this[xf]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[un]},get[Symbol.toStringTag](){return"Pino"},[_f]:Uf,[kf]:Zf,[Bi]:Wf,[qi]:Df,[cn]:jf};Object.setPrototypeOf(Vi,Sf.prototype);zi.exports=function(){return Object.create(Vi)};var Nt=t=>t;function Gf(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[ke],n=this[lt],s=Object.create(this);if(e==null)return s[lt].bindings!==Nt&&(s[lt]=ln(n.level,Nt,n.log)),s[qt]=fn(s,t),this.onChild!==Wi&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[ke]=Object.create(null);for(let f in r)s[ke][f]=r[f];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let f=a[i];s[ke][f]=r[f]}for(let f in e.serializers)s[ke][f]=e.serializers[f];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let f=l[o];s[ke][f]=e.serializers[f]}}else s[ke]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:f}=e.formatters;s[lt]=ln(a||n.level,l||Nt,f||n.log)}else s[lt]=ln(n.level,Nt,n.log);if(e.hasOwnProperty("customLevels")===!0&&(Hf(this.levels,e.customLevels),s.levels=qf(e.customLevels,s[Of]),Bf(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=zf(s.redact,Ui),l={stringify:a[If]};s[Pf]=Ui,s[Ff]=a,s[Mf]=l}if(typeof e.msgPrefix=="string"&&(s[un]=(this[un]||"")+e.msgPrefix),s[qt]=fn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[cn](a)}return this.onChild(s),s}function Jf(){let e=`{${this[qt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Xf(t){let e=fn(this,t);this[qt]=e}function Yf(t,e){return Object.assign(e,t)}function Zf(t,e,r){let n=this[$f](),s=this[vf],i=this[Af],o=this[Ef],a=this[Cf]||Yf,l,f=this[Lf].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 u=this[Bi](l,e,r,n),d=this[Hi];d[Rf]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[Tf]),d.lastLogger=this),d.write(f?f(u):u)}function Qf(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Hi];typeof e.flush=="function"?e.flush(t||Wi):t&&t()}});var Yi=I((mn,Xi)=>{"use strict";var{hasOwnProperty:ct}=Object.prototype,$e=hn();$e.configure=hn;$e.stringify=$e;$e.default=$e;mn.stringify=$e;mn.configure=hn;Xi.exports=$e;var ed=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function me(t){return t.length<5e3&&!ed.test(t)?`"${t}"`:JSON.stringify(t)}function dn(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 td=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function pn(t){return td.call(t)!==void 0&&t.length!==0}function Gi(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 rd(t){if(ct.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 nd(t){let e;if(ct.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 sd(t,e){let r;if(ct.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 Ji(t,e){let r;if(ct.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 Ce(t){return t===1?"1 item":`${t} items`}function id(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function od(t){if(ct.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 hn(t){t={...t};let e=od(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=rd(t),n=sd(t,"bigint"),s=nd(t),i=typeof s=="function"?s:void 0,o=Ji(t,"maximumDepth"),a=Ji(t,"maximumBreadth");function l(p,c,m,y,w,b){let _=c[p];switch(typeof _=="object"&&_!==null&&typeof _.toJSON=="function"&&(_=_.toJSON(p)),_=y.call(c,p,_),typeof _){case"string":return me(_);case"object":{if(_===null)return"null";if(m.indexOf(_)!==-1)return r;let S="",k=",",R=b;if(Array.isArray(_)){if(_.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(_),w!==""&&(b+=w,S+=`
26
+ ${b}`,k=`,
27
+ ${b}`);let L=Math.min(_.length,a),H=0;for(;H<L-1;H++){let W=l(String(H),_,m,y,w,b);S+=W!==void 0?W:"null",S+=k}let U=l(String(H),_,m,y,w,b);if(S+=U!==void 0?U:"null",_.length-1>a){let W=_.length-a-1;S+=`${k}"... ${Ce(W)} not stringified"`}return w!==""&&(S+=`
28
+ ${R}`),m.pop(),`[${S}]`}let T=Object.keys(_),O=T.length;if(O===0)return"{}";if(o<m.length+1)return'"[Object]"';let $="",P="";w!==""&&(b+=w,k=`,
29
+ ${b}`,$=" ");let N=Math.min(O,a);s&&!pn(_)&&(T=dn(T,i)),m.push(_);for(let L=0;L<N;L++){let H=T[L],U=l(H,_,m,y,w,b);U!==void 0&&(S+=`${P}${me(H)}:${$}${U}`,P=k)}if(O>a){let L=O-a;S+=`${P}"...":${$}"${Ce(L)} not stringified"`,P=k}return w!==""&&P.length>1&&(S=`
30
30
  ${b}${S}
31
- ${$}`),m.pop(),`{${S}}`}case"number":return isFinite(_)?String(_):e?e(_):"null";case"boolean":return _===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(_);default:return e?e(_):void 0}}function u(h,c,m,y,w,b){switch(typeof c=="object"&&c!==null&&typeof c.toJSON=="function"&&(c=c.toJSON(h)),typeof c){case"string":return ce(c);case"object":{if(c===null)return"null";if(m.indexOf(c)!==-1)return r;let _=b,S="",v=",";if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),w!==""&&(b+=w,S+=`
32
- ${b}`,v=`,
33
- ${b}`);let O=Math.min(c.length,a),C=0;for(;C<O-1;C++){let L=u(String(C),c[C],m,y,w,b);S+=L!==void 0?L:"null",S+=v}let I=u(String(C),c[C],m,y,w,b);if(S+=I!==void 0?I:"null",c.length-1>a){let L=c.length-a-1;S+=`${v}"... ${be(L)} not stringified"`}return w!==""&&(S+=`
34
- ${_}`),m.pop(),`[${S}]`}m.push(c);let $="";w!==""&&(b+=w,v=`,
35
- ${b}`,$=" ");let T="";for(let O of y){let C=u(O,c[O],m,y,w,b);C!==void 0&&(S+=`${T}${ce(O)}:${$}${C}`,T=v)}return w!==""&&T.length>1&&(S=`
31
+ ${R}`),m.pop(),`{${S}}`}case"number":return isFinite(_)?String(_):e?e(_):"null";case"boolean":return _===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(_);default:return e?e(_):void 0}}function f(p,c,m,y,w,b){switch(typeof c=="object"&&c!==null&&typeof c.toJSON=="function"&&(c=c.toJSON(p)),typeof c){case"string":return me(c);case"object":{if(c===null)return"null";if(m.indexOf(c)!==-1)return r;let _=b,S="",k=",";if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),w!==""&&(b+=w,S+=`
32
+ ${b}`,k=`,
33
+ ${b}`);let O=Math.min(c.length,a),$=0;for(;$<O-1;$++){let N=f(String($),c[$],m,y,w,b);S+=N!==void 0?N:"null",S+=k}let P=f(String($),c[$],m,y,w,b);if(S+=P!==void 0?P:"null",c.length-1>a){let N=c.length-a-1;S+=`${k}"... ${Ce(N)} not stringified"`}return w!==""&&(S+=`
34
+ ${_}`),m.pop(),`[${S}]`}m.push(c);let R="";w!==""&&(b+=w,k=`,
35
+ ${b}`,R=" ");let T="";for(let O of y){let $=f(O,c[O],m,y,w,b);$!==void 0&&(S+=`${T}${me(O)}:${R}${$}`,T=k)}return w!==""&&T.length>1&&(S=`
36
36
  ${b}${S}
37
- ${_}`),m.pop(),`{${S}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function d(h,c,m,y,w){switch(typeof c){case"string":return ce(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(h),typeof c!="object")return d(h,c,m,y,w);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let b=w;if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),w+=y;let C=`
38
- ${w}`,I=`,
39
- ${w}`,L=Math.min(c.length,a),F=0;for(;F<L-1;F++){let N=d(String(F),c[F],m,y,w);C+=N!==void 0?N:"null",C+=I}let q=d(String(F),c[F],m,y,w);if(C+=q!==void 0?q:"null",c.length-1>a){let N=c.length-a-1;C+=`${I}"... ${be(N)} not stringified"`}return C+=`
40
- ${b}`,m.pop(),`[${C}]`}let _=Object.keys(c),S=_.length;if(S===0)return"{}";if(o<m.length+1)return'"[Object]"';w+=y;let v=`,
41
- ${w}`,$="",T="",O=Math.min(S,a);on(c)&&($+=qi(c,v,a),_=_.slice(c.length),O-=c.length,T=v),s&&(_=sn(_,i)),m.push(c);for(let C=0;C<O;C++){let I=_[C],L=d(I,c[I],m,y,w);L!==void 0&&($+=`${T}${ce(I)}: ${L}`,T=v)}if(S>a){let C=S-a;$+=`${T}"...": "${be(C)} not stringified"`,T=v}return T!==""&&($=`
42
- ${w}${$}
43
- ${b}`),m.pop(),`{${$}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function f(h,c,m){switch(typeof c){case"string":return ce(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(h),typeof c!="object")return f(h,c,m);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let y="",w=c.length!==void 0;if(w&&Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c);let $=Math.min(c.length,a),T=0;for(;T<$-1;T++){let C=f(String(T),c[T],m);y+=C!==void 0?C:"null",y+=","}let O=f(String(T),c[T],m);if(y+=O!==void 0?O:"null",c.length-1>a){let C=c.length-a-1;y+=`,"... ${be(C)} not stringified"`}return m.pop(),`[${y}]`}let b=Object.keys(c),_=b.length;if(_===0)return"{}";if(o<m.length+1)return'"[Object]"';let S="",v=Math.min(_,a);w&&on(c)&&(y+=qi(c,",",a),b=b.slice(c.length),v-=c.length,S=","),s&&(b=sn(b,i)),m.push(c);for(let $=0;$<v;$++){let T=b[$],O=f(T,c[T],m);O!==void 0&&(y+=`${S}${ce(T)}:${O}`,S=",")}if(_>a){let $=_-a;y+=`${S}"...":"${be($)} not stringified"`}return m.pop(),`{${y}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function p(h,c,m){if(arguments.length>1){let y="";if(typeof m=="number"?y=" ".repeat(Math.min(m,10)):typeof m=="string"&&(y=m.slice(0,10)),c!=null){if(typeof c=="function")return l("",{"":h},[],c,y,"");if(Array.isArray(c))return u("",h,[],Yf(c),y,"")}if(y.length!==0)return d("",h,[],y,"")}return f("",h,[])}return p}});var Ki=R((hm,zi)=>{"use strict";var cn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Vi}=Ot(),Qf=Vi.info;function ed(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(Vi);r.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(f=>{r[f]=e.levels[f]});let n={write:s,add:a,remove:l,emit:i,flushSync:o,end:u,minLevel:0,lastId:0,streams:[],clone:d,[cn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(f){let p,h=this.lastLevel,{streams:c}=this,m=0,y;for(let w=td(c.length,e.dedupe);nd(w,c.length,e.dedupe);w=rd(w,e.dedupe))if(p=c[w],p.level<=h){if(m!==0&&m!==p.level)break;if(y=p.stream,y[cn]){let{lastTime:b,lastMsg:_,lastObj:S,lastLogger:v}=this;y.lastLevel=h,y.lastTime=b,y.lastMsg=_,y.lastObj=S,y.lastLogger=v}y.write(f),e.dedupe&&(m=p.level)}else if(!e.dedupe)break}function i(...f){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.emit(...f)}function o(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync()}function a(f){if(!f)return n;let p=typeof f.write=="function"||f.stream,h=f.write?f:f.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:c,streamLevels:m}=this,y;typeof f.levelVal=="number"?y=f.levelVal:typeof f.level=="string"?y=m[f.level]:typeof f.level=="number"?y=f.level:y=Qf;let w={stream:h,level:y,levelVal:void 0,id:++n.lastId};return c.unshift(w),c.sort(Wi),this.minLevel=c[0].level,n}function l(f){let{streams:p}=this,h=p.findIndex(c=>c.id===f);return h>=0&&(p.splice(h,1),p.sort(Wi),this.minLevel=p.length>0?p[0].level:-1),n}function u(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync(),f.end()}function d(f){let p=new Array(this.streams.length);for(let h=0;h<p.length;h++)p[h]={level:f,stream:this.streams[h].stream};return{write:s,add:a,remove:l,minLevel:f,streams:p,clone:d,emit:i,flushSync:o,[cn]:!0}}}function Wi(t,e){return t.level-e.level}function td(t,e){return e?t-1:0}function rd(t,e){return e?t-1:t+1}function nd(t,e,r){return r?t>=0:t<e}zi.exports=ed});var ao=R((pm,K)=>{"use strict";var sd=require("node:os"),to=Er(),id=Or(),od=Ir(),ro=Rs(),ad=Ni(),no=Pe(),{configure:ld}=Hi(),{assertDefaultLevelFound:cd,mappings:so,genLsCache:ud,genLevelComparison:fd,assertLevelComparison:dd}=Zr(),{DEFAULT_LEVELS:io,SORTING_ORDER:hd}=Ot(),{createArgsNormalizer:pd,asChindings:md,buildSafeSonicBoom:Ji,buildFormatters:gd,stringify:un,normalizeDestFileDescriptor:Gi,noop:yd}=Et(),{version:wd}=Qr(),{chindingsSym:Xi,redactFmtSym:bd,serializersSym:Yi,timeSym:Sd,timeSliceIndexSym:_d,streamSym:xd,stringifySym:Zi,stringifySafeSym:fn,stringifiersSym:Qi,setLevelSym:vd,endSym:kd,formatOptsSym:Cd,messageKeySym:Td,errorKeySym:Ad,nestedKeySym:Ed,mixinSym:Od,levelCompSym:$d,useOnlyCustomLevelsSym:Rd,formattersSym:eo,hooksSym:Id,nestedKeyStrSym:Pd,mixinMergeStrategySym:Fd,msgPrefixSym:Md}=no,{epochTime:oo,nullTime:Dd}=ro,{pid:Ld}=process,jd=sd.hostname(),Nd=to.err,qd={level:"info",levelComparison:hd.ASC,levels:io,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Ld,hostname:jd},serializers:Object.assign(Object.create(null),{err:Nd}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:oo,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Ud=pd(qd),Bd=Object.assign(Object.create(null),to);function dn(...t){let e={},{opts:r,stream:n}=Ud(e,id(),...t);r.level&&typeof r.level=="string"&&io[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:u,nestedKey:d,base:f,name:p,level:h,customLevels:c,levelComparison:m,mixin:y,mixinMergeStrategy:w,useOnlyCustomLevels:b,formatters:_,hooks:S,depthLimit:v,edgeLimit:$,onChild:T,msgPrefix:O}=r,C=ld({maximumDepth:v,maximumBreadth:$}),I=gd(_.level,_.bindings,_.log),L=un.bind({[fn]:C}),F=s?od(s,L):{},q=s?{stringify:F[bd]}:{stringify:L},N="}"+(i?`\r
37
+ ${_}`),m.pop(),`{${S}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function u(p,c,m,y,w){switch(typeof c){case"string":return me(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(p),typeof c!="object")return u(p,c,m,y,w);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let b=w;if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),w+=y;let $=`
38
+ ${w}`,P=`,
39
+ ${w}`,N=Math.min(c.length,a),L=0;for(;L<N-1;L++){let U=u(String(L),c[L],m,y,w);$+=U!==void 0?U:"null",$+=P}let H=u(String(L),c[L],m,y,w);if($+=H!==void 0?H:"null",c.length-1>a){let U=c.length-a-1;$+=`${P}"... ${Ce(U)} not stringified"`}return $+=`
40
+ ${b}`,m.pop(),`[${$}]`}let _=Object.keys(c),S=_.length;if(S===0)return"{}";if(o<m.length+1)return'"[Object]"';w+=y;let k=`,
41
+ ${w}`,R="",T="",O=Math.min(S,a);pn(c)&&(R+=Gi(c,k,a),_=_.slice(c.length),O-=c.length,T=k),s&&(_=dn(_,i)),m.push(c);for(let $=0;$<O;$++){let P=_[$],N=u(P,c[P],m,y,w);N!==void 0&&(R+=`${T}${me(P)}: ${N}`,T=k)}if(S>a){let $=S-a;R+=`${T}"...": "${Ce($)} not stringified"`,T=k}return T!==""&&(R=`
42
+ ${w}${R}
43
+ ${b}`),m.pop(),`{${R}}`}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){switch(typeof c){case"string":return me(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);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let y="",w=c.length!==void 0;if(w&&Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c);let R=Math.min(c.length,a),T=0;for(;T<R-1;T++){let $=d(String(T),c[T],m);y+=$!==void 0?$:"null",y+=","}let O=d(String(T),c[T],m);if(y+=O!==void 0?O:"null",c.length-1>a){let $=c.length-a-1;y+=`,"... ${Ce($)} not stringified"`}return m.pop(),`[${y}]`}let b=Object.keys(c),_=b.length;if(_===0)return"{}";if(o<m.length+1)return'"[Object]"';let S="",k=Math.min(_,a);w&&pn(c)&&(y+=Gi(c,",",a),b=b.slice(c.length),k-=c.length,S=","),s&&(b=dn(b,i)),m.push(c);for(let R=0;R<k;R++){let T=b[R],O=d(T,c[T],m);O!==void 0&&(y+=`${S}${me(T)}:${O}`,S=",")}if(_>a){let R=_-a;y+=`${S}"...":"${Ce(R)} 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 f("",p,[],id(c),y,"")}if(y.length!==0)return u("",p,[],y,"")}return d("",p,[])}return h}});var to=I((km,eo)=>{"use strict";var gn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Qi}=jt(),ad=Qi.info;function ld(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(Qi);r.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(d=>{r[d]=e.levels[d]});let n={write:s,add:a,remove:l,emit:i,flushSync:o,end:f,minLevel:0,lastId:0,streams:[],clone:u,[gn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(d){let h,p=this.lastLevel,{streams:c}=this,m=0,y;for(let w=cd(c.length,e.dedupe);fd(w,c.length,e.dedupe);w=ud(w,e.dedupe))if(h=c[w],h.level<=p){if(m!==0&&m!==h.level)break;if(y=h.stream,y[gn]){let{lastTime:b,lastMsg:_,lastObj:S,lastLogger:k}=this;y.lastLevel=p,y.lastTime=b,y.lastMsg=_,y.lastObj=S,y.lastLogger=k}y.write(d),e.dedupe&&(m=h.level)}else if(!e.dedupe)break}function i(...d){for(let{stream:h}of this.streams)typeof h.emit=="function"&&h.emit(...d)}function o(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync()}function a(d){if(!d)return n;let h=typeof d.write=="function"||d.stream,p=d.write?d:d.stream;if(!h)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:c,streamLevels:m}=this,y;typeof d.levelVal=="number"?y=d.levelVal:typeof d.level=="string"?y=m[d.level]:typeof d.level=="number"?y=d.level:y=ad;let w={stream:p,level:y,levelVal:void 0,id:++n.lastId};return c.unshift(w),c.sort(Zi),this.minLevel=c[0].level,n}function l(d){let{streams:h}=this,p=h.findIndex(c=>c.id===d);return p>=0&&(h.splice(p,1),h.sort(Zi),this.minLevel=h.length>0?h[0].level:-1),n}function f(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function u(d){let h=new Array(this.streams.length);for(let p=0;p<h.length;p++)h[p]={level:d,stream:this.streams[p].stream};return{write:s,add:a,remove:l,minLevel:d,streams:h,clone:u,emit:i,flushSync:o,[gn]:!0}}}function Zi(t,e){return t.level-e.level}function cd(t,e){return e?t-1:0}function ud(t,e){return e?t-1:t+1}function fd(t,e,r){return r?t>=0:t<e}eo.exports=ld});var go=I((Cm,Y)=>{"use strict";var dd=require("node:os"),co=Fr(),pd=Lr(),hd=Nr(),uo=Ns(),md=Ki(),fo=Ne(),{configure:gd}=Yi(),{assertDefaultLevelFound:yd,mappings:po,genLsCache:wd,genLevelComparison:bd,assertLevelComparison:Sd}=on(),{DEFAULT_LEVELS:ho,SORTING_ORDER:_d}=jt(),{createArgsNormalizer:xd,asChindings:vd,buildSafeSonicBoom:ro,buildFormatters:kd,stringify:yn,normalizeDestFileDescriptor:no,noop:Cd}=Dt(),{version:$d}=an(),{chindingsSym:so,redactFmtSym:Td,serializersSym:io,timeSym:Ad,timeSliceIndexSym:Ed,streamSym:Od,stringifySym:oo,stringifySafeSym:wn,stringifiersSym:ao,setLevelSym:Rd,endSym:Id,formatOptsSym:Pd,messageKeySym:Md,errorKeySym:Fd,nestedKeySym:Ld,mixinSym:Dd,levelCompSym:jd,useOnlyCustomLevelsSym:Nd,formattersSym:lo,hooksSym:qd,nestedKeyStrSym:Ud,mixinMergeStrategySym:Bd,msgPrefixSym:Hd}=fo,{epochTime:mo,nullTime:Wd}=uo,{pid:Vd}=process,zd=dd.hostname(),Kd=co.err,Gd={level:"info",levelComparison:_d.ASC,levels:ho,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Vd,hostname:zd},serializers:Object.assign(Object.create(null),{err:Kd}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:mo,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Jd=xd(Gd),Xd=Object.assign(Object.create(null),co);function bn(...t){let e={},{opts:r,stream:n}=Jd(e,pd(),...t);r.level&&typeof r.level=="string"&&ho[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:f,nestedKey:u,base:d,name:h,level:p,customLevels:c,levelComparison:m,mixin:y,mixinMergeStrategy:w,useOnlyCustomLevels:b,formatters:_,hooks:S,depthLimit:k,edgeLimit:R,onChild:T,msgPrefix:O}=r,$=gd({maximumDepth:k,maximumBreadth:R}),P=kd(_.level,_.bindings,_.log),N=yn.bind({[wn]:$}),L=s?hd(s,N):{},H=s?{stringify:L[Td]}:{stringify:N},U="}"+(i?`\r
44
44
  `:`
45
- `),U=md.bind(null,{[Xi]:"",[Yi]:o,[Qi]:F,[Zi]:un,[fn]:C,[eo]:I}),P="";f!==null&&(p===void 0?P=U(f):P=U(Object.assign({},f,{name:p})));let B=a instanceof Function?a:a?oo:Dd,er=B().indexOf(":")+1;if(b&&!c)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(y&&typeof y!="function")throw Error(`Unknown mixin type "${typeof y}" - expected "function"`);if(O&&typeof O!="string")throw Error(`Unknown msgPrefix type "${typeof O}" - expected "string"`);cd(h,c,b);let tr=so(c,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:tr,messageKey:l,errorKey:u}}),dd(m);let rr=fd(m);return Object.assign(e,{levels:tr,[$d]:rr,[Rd]:b,[xd]:n,[Sd]:B,[_d]:er,[Zi]:un,[fn]:C,[Qi]:F,[kd]:N,[Cd]:q,[Td]:l,[Ad]:u,[Ed]:d,[Pd]:d?`,${JSON.stringify(d)}:{`:"",[Yi]:o,[Od]:y,[Fd]:w,[Xi]:P,[eo]:I,[Id]:S,silent:yd,onChild:T,[Md]:O}),Object.setPrototypeOf(e,ad()),ud(e),e[vd](h),e}K.exports=dn;K.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=Gi(t.dest||process.stdout.fd),Ji(t)):Ji({dest:Gi(t),minLength:0});K.exports.transport=zr();K.exports.multistream=Ki();K.exports.levels=so();K.exports.stdSerializers=Bd;K.exports.stdTimeFunctions=Object.assign({},ro);K.exports.symbols=no;K.exports.version=wd;K.exports.default=dn;K.exports.pino=dn});var Jn=k(Kn(),1),{program:kp,createCommand:Cp,createArgument:Tp,createOption:Ap,CommanderError:Ep,InvalidArgumentError:Op,InvalidOptionArgumentError:$p,Command:Gn,Argument:Rp,Option:Ip,Help:Pp}=Jn.default;var X=k(require("fs")),me=k(require("path")),Xn=k(require("os"));var Ze={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:200,timeout:12e4,autoMode:!1,contextBudget:12e4,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0}},ne={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","stepfun-ai/step-3.5-flash","nvidia/llama-3.1-nemotron-70b-instruct","qwen/qwen2.5-coder-32b-instruct","deepseek-ai/deepseek-coder-33b-instruct"]};var Re=me.join(Xn.homedir(),".hablas"),wr=me.join(Re,"config.json");function Ie(t={}){let e={};if(X.existsSync(wr))try{e=JSON.parse(X.readFileSync(wr,"utf-8"))}catch{}let r={...Ze,...e,tools:{...Ze.tools,...e.tools||{},runCommand:{...Ze.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...Ze.workspace,...e.workspace||{}}};if(process.env.HABLAS_API_URL&&(r.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(r.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_MODEL&&(r.model=process.env.HABLAS_MODEL),process.env.HABLAS_PROVIDER){let n=process.env.HABLAS_PROVIDER;(n==="ollama"||n==="custom"||n==="nvidia")&&(r.provider=n)}if(t.model&&(r.model=t.model),t.host&&(r.ollamaHost=t.host),t.project&&(r.workingDirectory=me.resolve(t.project)),t.provider){let n=t.provider;(n==="ollama"||n==="custom"||n==="nvidia")&&(r.provider=n)}return t.apiUrl&&(r.apiUrl=t.apiUrl),t.apiKey&&(r.apiKey=t.apiKey),r.apiUrl&&r.provider==="ollama"&&(r.provider="custom"),r}function Qe(t){X.existsSync(Re)||X.mkdirSync(Re,{recursive:!0}),X.writeFileSync(wr,JSON.stringify(t,null,2),"utf-8")}function Yn(){let t=[Re,me.join(Re,"logs"),me.join(Re,"backup")];for(let e of t)X.existsSync(e)||X.mkdirSync(e,{recursive:!0})}var hn=k(ao()),pn=k(require("path")),lo=k(require("os")),It=k(require("fs"));function mn(t){let e=pn.join(lo.homedir(),".hablas","logs");It.existsSync(e)||It.mkdirSync(e,{recursive:!0});let r=pn.join(e,`session-${Date.now()}.log`);return(0,hn.default)({level:"info"},hn.default.destination({dest:r,sync:!1}))}var Pt=k(require("fs")),st=k(require("path"));function co(){let t=[st.resolve(__dirname,"..","package.json"),st.resolve(__dirname,"..","..","package.json"),st.resolve(process.cwd(),"package.json"),st.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(Pt.existsSync(e)){let r=JSON.parse(Pt.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Ta=k(require("fs")),Aa=k(require("path"));var Ft=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(n=>n.name):[]}catch{return[]}}async chatWithTools(e,r,n){let s={model:this.model,messages:e,stream:!1};r.length>0&&(s.tools=r);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)};n&&(i.signal=n);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,r){let n=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:r});if(!n.ok)throw new Error(`Ollama error: ${n.status} ${n.statusText}`);let s=n.body?.getReader();if(!s)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await s.read();if(a)break;o+=i.decode(l,{stream:!0});let u=o.split(`
46
- `);o=u.pop()||"";for(let d of u)if(d.trim())try{let f=JSON.parse(d);f.message?.content&&(yield f.message.content)}catch{}}}};var uo=12e4,Hd=6e4,Mt=3,fo=1e3,Wd=20;function ho(t){return t.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let r=e.tool_calls.filter(n=>n?.function?.name);if(r.length>0)return{role:"assistant",content:e.content||null,tool_calls:r.map((n,s)=>({id:`call_${s}`,type:"function",function:{name:n.function?.name||"",arguments:JSON.stringify(n.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function Vd(t){return t.map(e=>({type:"function",function:e.function}))}function zd(t){return t.filter(e=>e?.function?.name).map(e=>{let r={};try{r=JSON.parse(e.function?.arguments||"{}")}catch{r={_raw:e.function?.arguments}}return{function:{name:e.function?.name||"",arguments:r}}})}function po(t){return new Promise(e=>setTimeout(e,t))}function mo(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var it=class{apiUrl;apiKey;model;constructor(e){this.apiUrl=e.apiUrl||"https://api.openai.com/v1",this.apiKey=e.apiKey,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}setApiUrl(e){this.apiUrl=e}getApiUrl(){return this.apiUrl}setApiKey(e){this.apiKey=e}async checkConnection(){try{let e=this.apiUrl.replace(/\/+$/,"")+"/models";return(await fetch(e,{headers:this.getHeaders(),signal:AbortSignal.timeout(15e3)})).ok}catch{return!1}}async listModels(){try{let e=[],r=!0,n,s=0;for(;r&&s<Wd;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;n&&o.set("after",n),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let l=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(Hd)});if(!l.ok)break;let u=await l.json();if(Array.isArray(u))e.push(...u.map(d=>d.id||d.name||d).filter(Boolean)),r=!1;else if(u.data&&Array.isArray(u.data)){let d=u.data.map(f=>f.id||f.name).filter(Boolean);e.push(...d),u.has_more&&d.length>0?(n=d[d.length-1],s++):r=!1}else u.models&&Array.isArray(u.models)&&e.push(...u.models.map(d=>d.name||d.id).filter(Boolean)),r=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,r,n){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:ho(e)};r.length>0&&(i.tools=Vd(r),i.tool_choice="auto");let o=null;for(let a=0;a<=Mt;a++)try{let l=new AbortController,u=setTimeout(()=>l.abort(),uo),d={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:n||l.signal};try{let f=await fetch(s,d);if(clearTimeout(u),!f.ok){let m=await f.text().catch(()=>"");if(!mo(null,f.status))throw new Error(`API error: ${f.status} ${f.statusText} \u2014 ${m}`);if(o=new Error(`API error: ${f.status} ${f.statusText} \u2014 ${m}`),a<Mt){let y=fo*Math.pow(2,a);await po(y);continue}throw o}let h=(await f.json()).choices?.[0];if(!h)throw new Error("API returned empty response");let c=h.message.tool_calls?zd(h.message.tool_calls):void 0;return{message:{role:h.message.role||"assistant",content:h.message.content||"",tool_calls:c},done:!0,done_reason:h.finish_reason}}catch(f){if(clearTimeout(u),f.name==="AbortError"&&n?.aborted)throw f;if(mo(f)&&(o=f,a<Mt)){let p=fo*Math.pow(2,a);await po(p);continue}throw f}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Mt)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,r){let n=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:ho(e),stream:!0}),signal:r||AbortSignal.timeout(uo)});if(!s.ok)throw new Error(`API error: ${s.status} ${s.statusText}`);let i=s.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:u}=await i.read();if(l)break;a+=o.decode(u,{stream:!0});let d=a.split(`
47
- `);a=d.pop()||"";for(let f of d){let p=f.trim();if(!(!p||p==="data: [DONE]")&&p.startsWith("data: "))try{let c=JSON.parse(p.slice(6)).choices?.[0]?.delta?.content;c&&(yield c)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function De(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:ne.apiUrl};return new it(e)}return t.provider==="custom"&&t.apiUrl?new it(t):new Ft(t)}function Le(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var D=k(require("fs/promises")),vn=k(require("fs")),ue=k(require("path"));function ie(){}ie.prototype={diff:function(e,r){var n,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=s.callback;typeof s=="function"&&(i=s,s={}),this.options=s;var o=this;function a(S){return i?(setTimeout(function(){i(void 0,S)},0),!0):S}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,u=e.length,d=1,f=l+u;s.maxEditLength&&(f=Math.min(f,s.maxEditLength));var p=(n=s.timeout)!==null&&n!==void 0?n:1/0,h=Date.now()+p,c=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(c[0],r,e,0);if(c[0].oldPos+1>=u&&m+1>=l)return a([{value:this.join(r),count:r.length}]);var y=-1/0,w=1/0;function b(){for(var S=Math.max(y,-d);S<=Math.min(w,d);S+=2){var v=void 0,$=c[S-1],T=c[S+1];$&&(c[S-1]=void 0);var O=!1;if(T){var C=T.oldPos-S;O=T&&0<=C&&C<l}var I=$&&$.oldPos+1<u;if(!O&&!I){c[S]=void 0;continue}if(!I||O&&$.oldPos+1<T.oldPos?v=o.addToPath(T,!0,void 0,0):v=o.addToPath($,void 0,!0,1),m=o.extractCommon(v,r,e,S),v.oldPos+1>=u&&m+1>=l)return a(Kd(o,v.lastComponent,r,e,o.useLongestToken));c[S]=v,v.oldPos+1>=u&&(w=Math.min(w,S-1)),m+1>=l&&(y=Math.max(y,S+1))}d++}if(i)(function S(){setTimeout(function(){if(d>f||Date.now()>h)return i();b()||S()},0)})();else for(;d<=f&&Date.now()<=h;){var _=b();if(_)return _}},addToPath:function(e,r,n,s){var i=e.lastComponent;return i&&i.added===r&&i.removed===n?{oldPos:e.oldPos+s,lastComponent:{count:i.count+1,added:r,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+s,lastComponent:{count:1,added:r,removed:n,previousComponent:i}}},extractCommon:function(e,r,n,s){for(var i=r.length,o=n.length,a=e.oldPos,l=a-s,u=0;l+1<i&&a+1<o&&this.equals(r[l+1],n[a+1]);)l++,a++,u++;return u&&(e.lastComponent={count:u,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,r){return this.options.comparator?this.options.comparator(e,r):e===r||this.options.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function Kd(t,e,r,n,s){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,u=0,d=0;a<l;a++){var f=i[a];if(f.removed){if(f.value=t.join(n.slice(d,d+f.count)),d+=f.count,a&&i[a-1].added){var h=i[a-1];i[a-1]=i[a],i[a]=h}}else{if(!f.added&&s){var p=r.slice(u,u+f.count);p=p.map(function(m,y){var w=n[d+y];return w.length>m.length?w:m}),f.value=t.join(p)}else f.value=t.join(r.slice(u,u+f.count));u+=f.count,f.added||(d+=f.count)}}var c=i[l-1];return l>1&&typeof c.value=="string"&&(c.added||c.removed)&&t.equals("",c.value)&&(i[l-2].value+=c.value,i.pop()),i}var Om=new ie;var go=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,yo=/\S/,wo=new ie;wo.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!yo.test(t)&&!yo.test(e)};wo.tokenize=function(t){for(var e=t.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),r=0;r<e.length-1;r++)!e[r+1]&&e[r+2]&&go.test(e[r])&&go.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var Sn=new ie;Sn.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
48
- `));var e=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var n=0;n<r.length;n++){var s=r[n];n%2&&!this.options.newlineIsToken?e[e.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),e.push(s))}return e};function Jd(t,e,r){return Sn.diff(t,e,r)}var Gd=new ie;Gd.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var Xd=new ie;Xd.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Dt(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Dt=function(e){return typeof e}:Dt=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Dt(t)}function gn(t){return Yd(t)||Zd(t)||Qd(t)||eh()}function Yd(t){if(Array.isArray(t))return yn(t)}function Zd(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Qd(t,e){if(t){if(typeof t=="string")return yn(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return yn(t,e)}}function yn(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function eh(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
49
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var th=Object.prototype.toString,ot=new ie;ot.useLongestToken=!0;ot.tokenize=Sn.tokenize;ot.castInput=function(t){var e=this.options,r=e.undefinedReplacement,n=e.stringifyReplacer,s=n===void 0?function(i,o){return typeof o>"u"?r:o}:n;return typeof t=="string"?t:JSON.stringify(wn(t,null,null,s),s," ")};ot.equals=function(t,e){return ie.prototype.equals.call(ot,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function wn(t,e,r,n,s){e=e||[],r=r||[],n&&(t=n(s,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var o;if(th.call(t)==="[object Array]"){for(e.push(t),o=new Array(t.length),r.push(o),i=0;i<t.length;i+=1)o[i]=wn(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),Dt(t)==="object"&&t!==null){e.push(t),o={},r.push(o);var a=[],l;for(l in t)t.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],o[l]=wn(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var bn=new ie;bn.tokenize=function(t){return t.slice()};bn.join=bn.removeEmpty=function(t){return t};function rh(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Jd(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(w){return w.map(function(b){return" "+b})}for(var u=[],d=0,f=0,p=[],h=1,c=1,m=function(b){var _=a[b],S=_.lines||_.value.replace(/\n$/,"").split(`
50
- `);if(_.lines=S,_.added||_.removed){var v;if(!d){var $=a[b-1];d=h,f=c,$&&(p=o.context>0?l($.lines.slice(-o.context)):[],d-=p.length,f-=p.length)}(v=p).push.apply(v,gn(S.map(function(N){return(_.added?"+":"-")+N}))),_.added?c+=S.length:h+=S.length}else{if(d)if(S.length<=o.context*2&&b<a.length-2){var T;(T=p).push.apply(T,gn(l(S)))}else{var O,C=Math.min(S.length,o.context);(O=p).push.apply(O,gn(l(S.slice(0,C))));var I={oldStart:d,oldLines:h-d+C,newStart:f,newLines:c-f+C,lines:p};if(b>=a.length-2&&S.length<=o.context){var L=/\n$/.test(r),F=/\n$/.test(n),q=S.length==0&&p.length>I.oldLines;!L&&q&&r.length>0&&p.splice(I.oldLines,0,"\"),(!L&&!q||!F)&&p.push("\")}u.push(I),d=0,f=0,p=[]}h+=S.length,c+=S.length}},y=0;y<a.length;y++)m(y);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:u}}function bo(t){if(Array.isArray(t))return t.map(bo).join(`
45
+ `),W=vd.bind(null,{[so]:"",[io]:o,[ao]:L,[oo]:yn,[wn]:$,[lo]:P}),F="";d!==null&&(h===void 0?F=W(d):F=W(Object.assign({},d,{name:h})));let V=a instanceof Function?a:a?mo:Wd,ar=V().indexOf(":")+1;if(b&&!c)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(y&&typeof y!="function")throw Error(`Unknown mixin type "${typeof y}" - expected "function"`);if(O&&typeof O!="string")throw Error(`Unknown msgPrefix type "${typeof O}" - expected "string"`);yd(p,c,b);let lr=po(c,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:lr,messageKey:l,errorKey:f}}),Sd(m);let cr=bd(m);return Object.assign(e,{levels:lr,[jd]:cr,[Nd]:b,[Od]:n,[Ad]:V,[Ed]:ar,[oo]:yn,[wn]:$,[ao]:L,[Id]:U,[Pd]:H,[Md]:l,[Fd]:f,[Ld]:u,[Ud]:u?`,${JSON.stringify(u)}:{`:"",[io]:o,[Dd]:y,[Bd]:w,[so]:F,[lo]:P,[qd]:S,silent:Cd,onChild:T,[Hd]:O}),Object.setPrototypeOf(e,md()),wd(e),e[Rd](p),e}Y.exports=bn;Y.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=no(t.dest||process.stdout.fd),ro(t)):ro({dest:no(t),minLength:0});Y.exports.transport=Qr();Y.exports.multistream=to();Y.exports.levels=po();Y.exports.stdSerializers=Xd;Y.exports.stdTimeFunctions=Object.assign({},uo);Y.exports.symbols=fo;Y.exports.version=$d;Y.exports.default=bn;Y.exports.pino=bn});var rs=C(ts(),1),{program:Fh,createCommand:Lh,createArgument:Dh,createOption:jh,CommanderError:Nh,InvalidArgumentError:qh,InvalidOptionArgumentError:Uh,Command:ns,Argument:Bh,Option:Hh,Help:Wh}=rs.default;var ee=C(require("fs")),_e=C(require("path")),ss=C(require("os"));var it={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}},se={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 Le=_e.join(ss.homedir(),".hablas"),Cr=_e.join(Le,"config.json");function De(t={}){let e={};if(ee.existsSync(Cr))try{e=JSON.parse(ee.readFileSync(Cr,"utf-8"))}catch{}let r={...it,...e,tools:{...it.tools,...e.tools||{},runCommand:{...it.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...it.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=_e.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 je(t){ee.existsSync(Le)||ee.mkdirSync(Le,{recursive:!0}),ee.writeFileSync(Cr,JSON.stringify(t,null,2),"utf-8")}function is(){let t=[Le,_e.join(Le,"logs"),_e.join(Le,"backup")];for(let e of t)ee.existsSync(e)||ee.mkdirSync(e,{recursive:!0})}var Sn=C(go()),_n=C(require("path")),yo=C(require("os")),Ut=C(require("fs"));function xn(t){let e=_n.join(yo.homedir(),".hablas","logs");Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0});let r=_n.join(e,`session-${Date.now()}.log`);return(0,Sn.default)({level:"info"},Sn.default.destination({dest:r,sync:!1}))}var Bt=C(require("fs")),ut=C(require("path"));function wo(){let t=[ut.resolve(__dirname,"..","package.json"),ut.resolve(__dirname,"..","..","package.json"),ut.resolve(process.cwd(),"package.json"),ut.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(Bt.existsSync(e)){let r=JSON.parse(Bt.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Ma=C(require("fs")),Fa=C(require("path"));var Ht=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 f=o.split(`
46
+ `);o=f.pop()||"";for(let u of f)if(u.trim())try{let d=JSON.parse(u);d.message?.content&&(yield d.message.content)}catch{}}}};var bo=12e4,Yd=6e4,Wt=3,So=1e3,Zd=20;function _o(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 Qd(t){return t.map(e=>({type:"function",function:e.function}))}function ep(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 xo(t){return new Promise(e=>setTimeout(e,t))}function vo(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var ft=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<Zd;){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(Yd)});if(!l.ok)break;let f=await l.json();if(Array.isArray(f))e.push(...f.map(u=>u.id||u.name||u).filter(Boolean)),r=!1;else if(f.data&&Array.isArray(f.data)){let u=f.data.map(d=>d.id||d.name).filter(Boolean);e.push(...u),f.has_more&&u.length>0?(n=u[u.length-1],s++):r=!1}else f.models&&Array.isArray(f.models)&&e.push(...f.models.map(u=>u.name||u.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:_o(e)};r.length>0&&(i.tools=Qd(r),i.tool_choice="auto");let o=null;for(let a=0;a<=Wt;a++)try{let l=new AbortController,f=setTimeout(()=>l.abort(),bo),u={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:n||l.signal};try{let d=await fetch(s,u);if(clearTimeout(f),!d.ok){let m=await d.text().catch(()=>"");if(!vo(null,d.status))throw new Error(`API error: ${d.status} ${d.statusText} \u2014 ${m}`);if(o=new Error(`API error: ${d.status} ${d.statusText} \u2014 ${m}`),a<Wt){let y=So*Math.pow(2,a);await xo(y);continue}throw o}let p=(await d.json()).choices?.[0];if(!p)throw new Error("API returned empty response");let c=p.message.tool_calls?ep(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(d){if(clearTimeout(f),d.name==="AbortError"&&n?.aborted)throw d;if(vo(d)&&(o=d,a<Wt)){let h=So*Math.pow(2,a);await xo(h);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Wt)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:_o(e),stream:!0}),signal:r||AbortSignal.timeout(bo)});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:f}=await i.read();if(l)break;a+=o.decode(f,{stream:!0});let u=a.split(`
47
+ `);a=u.pop()||"";for(let d of u){let h=d.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 Be(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:se.apiUrl};return new ft(e)}return t.provider==="custom"&&t.apiUrl?new ft(t):new Ht(t)}function He(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")),On=C(require("fs")),ge=C(require("path"));function ce(){}ce.prototype={diff:function(e,r){var n,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=s.callback;typeof s=="function"&&(i=s,s={}),this.options=s;var o=this;function a(S){return i?(setTimeout(function(){i(void 0,S)},0),!0):S}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,f=e.length,u=1,d=l+f;s.maxEditLength&&(d=Math.min(d,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>=f&&m+1>=l)return a([{value:this.join(r),count:r.length}]);var y=-1/0,w=1/0;function b(){for(var S=Math.max(y,-u);S<=Math.min(w,u);S+=2){var k=void 0,R=c[S-1],T=c[S+1];R&&(c[S-1]=void 0);var O=!1;if(T){var $=T.oldPos-S;O=T&&0<=$&&$<l}var P=R&&R.oldPos+1<f;if(!O&&!P){c[S]=void 0;continue}if(!P||O&&R.oldPos+1<T.oldPos?k=o.addToPath(T,!0,void 0,0):k=o.addToPath(R,void 0,!0,1),m=o.extractCommon(k,r,e,S),k.oldPos+1>=f&&m+1>=l)return a(tp(o,k.lastComponent,r,e,o.useLongestToken));c[S]=k,k.oldPos+1>=f&&(w=Math.min(w,S-1)),m+1>=l&&(y=Math.max(y,S+1))}u++}if(i)(function S(){setTimeout(function(){if(u>d||Date.now()>p)return i();b()||S()},0)})();else for(;u<=d&&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,f=0;l+1<i&&a+1<o&&this.equals(r[l+1],n[a+1]);)l++,a++,f++;return f&&(e.lastComponent={count:f,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 tp(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,f=0,u=0;a<l;a++){var d=i[a];if(d.removed){if(d.value=t.join(n.slice(u,u+d.count)),u+=d.count,a&&i[a-1].added){var p=i[a-1];i[a-1]=i[a],i[a]=p}}else{if(!d.added&&s){var h=r.slice(f,f+d.count);h=h.map(function(m,y){var w=n[u+y];return w.length>m.length?w:m}),d.value=t.join(h)}else d.value=t.join(r.slice(f,f+d.count));f+=d.count,d.added||(u+=d.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 qm=new ce;var ko=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Co=/\S/,$o=new ce;$o.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!Co.test(t)&&!Co.test(e)};$o.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]&&ko.test(e[r])&&ko.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var Tn=new ce;Tn.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 rp(t,e,r){return Tn.diff(t,e,r)}var np=new ce;np.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var sp=new ce;sp.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Vt(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Vt=function(e){return typeof e}:Vt=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Vt(t)}function vn(t){return ip(t)||op(t)||ap(t)||lp()}function ip(t){if(Array.isArray(t))return kn(t)}function op(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 kn(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 kn(t,e)}}function kn(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 lp(){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 cp=Object.prototype.toString,dt=new ce;dt.useLongestToken=!0;dt.tokenize=Tn.tokenize;dt.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(Cn(t,null,null,s),s," ")};dt.equals=function(t,e){return ce.prototype.equals.call(dt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function Cn(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(cp.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]=Cn(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),Vt(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]=Cn(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var $n=new ce;$n.tokenize=function(t){return t.slice()};$n.join=$n.removeEmpty=function(t){return t};function up(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=rp(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(w){return w.map(function(b){return" "+b})}for(var f=[],u=0,d=0,h=[],p=1,c=1,m=function(b){var _=a[b],S=_.lines||_.value.replace(/\n$/,"").split(`
50
+ `);if(_.lines=S,_.added||_.removed){var k;if(!u){var R=a[b-1];u=p,d=c,R&&(h=o.context>0?l(R.lines.slice(-o.context)):[],u-=h.length,d-=h.length)}(k=h).push.apply(k,vn(S.map(function(U){return(_.added?"+":"-")+U}))),_.added?c+=S.length:p+=S.length}else{if(u)if(S.length<=o.context*2&&b<a.length-2){var T;(T=h).push.apply(T,vn(l(S)))}else{var O,$=Math.min(S.length,o.context);(O=h).push.apply(O,vn(l(S.slice(0,$))));var P={oldStart:u,oldLines:p-u+$,newStart:d,newLines:c-d+$,lines:h};if(b>=a.length-2&&S.length<=o.context){var N=/\n$/.test(r),L=/\n$/.test(n),H=S.length==0&&h.length>P.oldLines;!N&&H&&r.length>0&&h.splice(P.oldLines,0,"\"),(!N&&!H||!L)&&h.push("\")}f.push(P),u=0,d=0,h=[]}p+=S.length,c+=S.length}},y=0;y<a.length;y++)m(y);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:f}}function To(t){if(Array.isArray(t))return t.map(To).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 nh(t,e,r,n,s,i,o){return bo(rh(t,e,r,n,s,i,o))}function So(t,e,r,n,s,i){return nh(t,t,e,r,n,s,i)}function _n(t,e,r){return So(t,e,r,"original","modified")}var te=k(require("fs/promises")),xn=k(require("fs")),je=k(require("path")),xo=k(require("os")),at=je.join(xo.homedir(),".hablas","backup"),_o=10;async function _e(t){try{if(!xn.existsSync(t))return;xn.existsSync(at)||await te.mkdir(at,{recursive:!0});let e=await te.readFile(t,"utf-8"),r=je.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=je.join(at,s);await te.writeFile(i,e,"utf-8");let a=(await te.readdir(at)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>_o)for(let l of a.slice(_o))await te.unlink(je.join(at,l))}catch{}}function ko(t){let e=h=>ue.resolve(t,h);return[{name:"read_file",description:"Read the FULL content of a file with line numbers (complete read, no truncation by default per user requirement for 1000/2000+ line files like architecture docs). Use start_line/end_line ONLY if you explicitly need a specific section. Never re-read the same path this turn \u2014 use previous tool observations from history.",safety:"safe",parameters:{path:{type:"string",description:"File path to read",required:!0},start_line:{type:"number",description:"Starting line number (1-based, optional)",required:!1},end_line:{type:"number",description:"Ending line number (inclusive, optional)",required:!1}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[read_file]: path is required"};let c=e(h.path),y=(await D.readFile(c,"utf-8")).split(`
54
- `),w=y.length,b=h.start_line?Math.max(1,h.start_line):1,_=h.end_line?Math.min(w,h.end_line):w,S=y.slice(b-1,_),v=String(_).length,$=S.map((C,I)=>`${String(b+I).padStart(v," ")} | ${C}`),T=`[${h.path} \u2014 lines ${b}-${_} of ${w}]`,O=_<w?`
53
+ `}function fp(t,e,r,n,s,i,o){return To(up(t,e,r,n,s,i,o))}function Ao(t,e,r,n,s,i){return fp(t,t,e,r,n,s,i)}function An(t,e,r){return Ao(t,e,r,"original","modified")}var oe=C(require("fs/promises")),En=C(require("fs")),We=C(require("path")),Oo=C(require("os")),pt=We.join(Oo.homedir(),".hablas","backup"),Eo=10;async function Te(t){try{if(!En.existsSync(t))return;En.existsSync(pt)||await oe.mkdir(pt,{recursive:!0});let e=await oe.readFile(t,"utf-8"),r=We.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=We.join(pt,s);await oe.writeFile(i,e,"utf-8");let a=(await oe.readdir(pt)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Eo)for(let l of a.slice(Eo))await oe.unlink(We.join(pt,l))}catch{}}function Io(t){let e=p=>ge.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
+ `),w=y.length,b=p.start_line?Math.max(1,p.start_line):1,_=p.end_line?Math.min(w,p.end_line):w,S=y.slice(b-1,_),k=String(_).length,R=S.map(($,P)=>`${String(b+P).padStart(k," ")} | ${$}`),T=`[${p.path} \u2014 lines ${b}-${_} of ${w}]`,O=_<w?`
55
55
  ... [Partial read. Total lines: ${w}.]`:"";return{success:!0,output:`${T}
56
- ${$.join(`
57
- `)}${O}`}}catch(c){return{success:!1,output:"",error:`[read_file]: ${c.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(h.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let c=e(h.path);return vn.existsSync(c)&&await _e(c),await D.mkdir(ue.dirname(c),{recursive:!0}),await D.writeFile(c,h.content,"utf-8"),{success:!0,output:`Written: ${h.path}`}}catch(c){return{success:!1,output:"",error:`[write_file]: ${c.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!h.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let c=e(h.path),m=await D.readFile(c,"utf-8"),y=h.old_content,w=h.new_content,b=vo(m,y);if(b===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(b>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${b} locations in the file. Provide more surrounding context to be specific.`};await _e(c);let _=m.replace(y,w);await D.writeFile(c,_,"utf-8");let S=_n(h.path,m,_);return{success:!0,output:`Edited: ${h.path}
58
- ${S}`}}catch(c){return{success:!1,output:"",error:`[edit_file]: ${c.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!h.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!h.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(h.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let c=e(h.path),m=await D.readFile(c,"utf-8"),y=m.split(`
59
- `),w=y.length,b=h.start_line,_=h.end_line;if(b<1||b>w)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${w} lines)`};if(_<b||_>w)return{success:!1,output:"",error:`[patch_file]: end_line ${_} is out of range (start_line=${b}, total=${w})`};await _e(c);let S=y.slice(0,b-1),v=y.slice(_),$=h.new_content.split(`
60
- `),T=[...S,...$,...v].join(`
61
- `);await D.writeFile(c,T,"utf-8");let O=_n(h.path,m,T),C=_-b+1,I=$.length;return{success:!0,output:`Patched: ${h.path} (replaced ${C} lines with ${I})
62
- ${O}`}}catch(c){return{success:!1,output:"",error:`[patch_file]: ${c.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!h.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(h.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let c=e(h.path),m=await D.readFile(c,"utf-8"),y=h.search,w=h.replace,b=h.is_regex;await _e(c);let _,S;if(b){let v=new RegExp(y,"g");S=(m.match(v)||[]).length,_=m.replace(v,w)}else S=vo(m,y),_=m.split(y).join(w);return S===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await D.writeFile(c,_,"utf-8"),{success:!0,output:`Replaced ${S} occurrence(s) in ${h.path}`})}catch(c){return{success:!1,output:"",error:`[search_and_replace]: ${c.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(h.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let c=e(h.path);return await D.mkdir(ue.dirname(c),{recursive:!0}),vn.existsSync(c)&&await _e(c),await D.appendFile(c,h.content,"utf-8"),{success:!0,output:`Appended to: ${h.path}`}}catch(c){return{success:!1,output:"",error:`[append_to_file]: ${c.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let c=e(h.path);return await _e(c),await D.unlink(c),{success:!0,output:`Deleted: ${h.path}`}}catch(c){return{success:!1,output:"",error:`[delete_file]: ${c.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async h=>{try{if(!h.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!h.to)return{success:!1,output:"",error:"[move_file]: to is required"};let c=e(h.from),m=e(h.to);return await D.mkdir(ue.dirname(m),{recursive:!0}),await D.rename(c,m),{success:!0,output:`Moved: ${h.from} \u2192 ${h.to}`}}catch(c){return{success:!1,output:"",error:`[move_file]: ${c.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let c=e(h.path);return await D.mkdir(c,{recursive:!0}),{success:!0,output:`Created directory: ${h.path}`}}catch(c){return{success:!1,output:"",error:`[create_dir]: ${c.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async h=>{try{let c=e(h.path||"."),m=h.depth||3;return{success:!0,output:await Co(c,"",m,0)||"(empty directory)"}}catch(c){return{success:!1,output:"",error:`[list_dir]: ${c.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let c=e(h.path),m=await D.stat(c);return{success:!0,output:[`Path: ${h.path}`,`Size: ${ih(m.size)}`,`Type: ${m.isDirectory()?"directory":"file"}`,`Modified: ${m.mtime.toISOString()}`,`Created: ${m.birthtime.toISOString()}`].join(`
63
- `)}}catch(c){return{success:!1,output:"",error:`[get_file_info]: ${c.message}`}}}}]}function vo(t,e){let r=0,n=0;for(;;){let s=t.indexOf(e,n);if(s===-1)break;r++,n=s+e.length}return r}var sh=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Co(t,e,r,n){if(n>=r)return"";let i=(await D.readdir(t,{withFileTypes:!0})).filter(a=>!sh.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],u=a===i.length-1,d=u?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${d}${f} ${l.name}
64
- `,l.isDirectory()){let p=e+(u?" ":"\u2502 ");o+=await Co(ue.join(t,l.name),p,r,n+1)}}return o}function ih(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Eo=require("child_process");var To=require("child_process"),Lt=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,r){let n=`bg_${this.nextId++}`,s=r?.timeout||this.config.defaultTimeout,i=(0,To.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...r?.env}}),o={id:n,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
56
+ ${R.join(`
57
+ `)}${O}`}}catch(c){return{success:!1,output:"",error:`[read_file]: ${c.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async 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 On.existsSync(c)&&await Te(c),await j.mkdir(ge.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,w=p.new_content,b=Ro(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 Te(c);let _=m.replace(y,w);await j.writeFile(c,_,"utf-8");let S=An(p.path,m,_);return{success:!0,output:`Edited: ${p.path}
58
+ ${S}`}}catch(c){return{success:!1,output:"",error:`[edit_file]: ${c.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async 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
+ `),w=y.length,b=p.start_line,_=p.end_line;if(b<1||b>w)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${w} lines)`};if(_<b||_>w)return{success:!1,output:"",error:`[patch_file]: end_line ${_} is out of range (start_line=${b}, total=${w})`};await Te(c);let S=y.slice(0,b-1),k=y.slice(_),R=p.new_content.split(`
60
+ `),T=[...S,...R,...k].join(`
61
+ `);await j.writeFile(c,T,"utf-8");let O=An(p.path,m,T),$=_-b+1,P=R.length;return{success:!0,output:`Patched: ${p.path} (replaced ${$} lines with ${P})
62
+ ${O}`}}catch(c){return{success:!1,output:"",error:`[patch_file]: ${c.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async 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,w=p.replace,b=p.is_regex;await Te(c);let _,S;if(b){let k=new RegExp(y,"g");S=(m.match(k)||[]).length,_=m.replace(k,w)}else S=Ro(m,y),_=m.split(y).join(w);return S===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await j.writeFile(c,_,"utf-8"),{success:!0,output:`Replaced ${S} 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(ge.dirname(c),{recursive:!0}),On.existsSync(c)&&await Te(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 Te(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(ge.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 Po(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: ${pp(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 Ro(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 dp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Po(t,e,r,n){if(n>=r)return"";let i=(await j.readdir(t,{withFileTypes:!0})).filter(a=>!dp.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],f=a===i.length-1,u=f?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${u}${d} ${l.name}
64
+ `,l.isDirectory()){let h=e+(f?" ":"\u2502 ");o+=await Po(ge.join(t,l.name),h,r,n+1)}}return o}function pp(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Lo=require("child_process");var Mo=require("child_process"),zt=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,Mo.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 oh=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],kn=null;function Ao(t){return kn||(kn=new Lt({workingDir:t})),kn}function Oo(t,e){return{name:"run_command",description:"Execute any shell command and return output. Set run_in_background=true for long-running processes (servers, watchers). Use bash_output to read output later.",safety:"confirm",parameters:{command:{type:"string",description:"Shell command to execute",required:!0},run_in_background:{type:"boolean",description:"Run in background for long processes (default: false)",required:!1},timeout:{type:"number",description:"Timeout in ms (default: 120000)",required:!1}},execute:async r=>{let n=r.command,s=r.run_in_background===!0,i=r.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...oh,...o];if(a.length>0){for(let l of a)if(n.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(s){let l=Ao(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
70
- PID: ${Ao(t).getProcess(l)?.pid}
71
- Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let u=(0,Eo.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",p=>{d+=p}),u.stderr?.on("data",p=>{f+=p}),u.on("close",p=>{l(p===0?{success:!0,output:d||"(no output)"}:{success:!1,output:d,error:f||`Exit code: ${p}`})}),u.on("error",p=>{l({success:!1,output:"",error:p.message})})})}}}var jt=k(require("fs/promises")),fe=k(require("path")),ah=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),lh=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function $o(t){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let r=e.query,n=fe.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await Ro(n,s,i,t),i.length===0)return{success:!0,output:`No matches found for: "${r}"`};let o=i.slice(0,50).join(`
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 hp=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],Rn=null;function Fo(t){return Rn||(Rn=new zt({workingDir:t})),Rn}function Do(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=[...hp,...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=Fo(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
70
+ PID: ${Fo(t).getProcess(l)?.pid}
71
+ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let f=(0,Lo.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),u="",d="";f.stdout?.on("data",h=>{u+=h}),f.stderr?.on("data",h=>{d+=h}),f.on("close",h=>{l(h===0?{success:!0,output:u||"(no output)"}:{success:!1,output:u,error:d||`Exit code: ${h}`})}),f.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var Kt=C(require("fs/promises")),ye=C(require("path")),mp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),gp=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=ye.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await No(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 Ro(t,e,r,n){let s=await jt.readdir(t,{withFileTypes:!0});for(let i of s){if(ah.has(i.name)||i.name.startsWith("."))continue;let o=fe.join(t,i.name);if(i.isDirectory())await Ro(o,e,r,n);else if(lh.has(fe.extname(i.name)))try{let l=(await jt.readFile(o,"utf-8")).split(`
74
- `),u=fe.relative(n,o);for(let d=0;d<l.length;d++)e.test(l[d])&&(r.push(`${u}:${d+1}: ${l[d].trim()}`),e.lastIndex=0)}catch{}}}var Cn=require("child_process"),J=k(require("fs")),de=k(require("path"));function ch(t){let e=[],r=de.join(t,"tsconfig.json");if(!J.existsSync(r))return e;try{(0,Cn.execSync)("npx tsc --noEmit 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let s=n,o=(s.stdout||s.message||"").split(`
75
- `);for(let a of o){let l=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);l&&e.push({file:l[1],line:parseInt(l[2],10),severity:l[3]==="error"?"error":"warning",message:l[4].trim(),source:"typescript"})}}return e}function uh(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>J.existsSync(de.join(t,n))))return e;try{(0,Cn.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let i=n.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:de.relative(t,a.filePath),line:l.line||0,severity:l.severity===2?"error":"warning",message:`${l.message} (${l.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
76
- `);for(let a of o){let l=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);l&&e.push({file:"unknown",line:parseInt(l[1],10),severity:l[3]==="error"?"error":"warning",message:`${l[4]} (${l[5]})`,source:"eslint"})}}}return e}function fh(t,e,r){let n;try{n=J.readFileSync(t,"utf-8")}catch{return}let s=de.relative(e,t),i=n.split(`
77
- `);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&r.push({file:s,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&r.push({file:s,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&r.push({file:s,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&r.push({file:s,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function dh(t){let e=[],r=[".ts",".tsx",".js",".jsx"];function n(s,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=J.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let u=de.join(s,l),d;try{d=J.statSync(u)}catch{continue}d.isDirectory()?n(u,i+1):r.some(f=>l.endsWith(f))&&fh(u,t,e)}}return n(t),e.slice(0,20)}function hh(t){let e=[];e.push(...ch(t)),e.push(...uh(t)),e.push(...dh(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function Io(t){if(t.length===0)return" \u2713 No bugs detected";let e=[],r=t.filter(i=>i.severity==="error").length,n=t.filter(i=>i.severity==="warning").length,s=t.filter(i=>i.severity==="info").length;e.push(` Found ${t.length} issue${t.length>1?"s":""}: ${r} errors, ${n} warnings, ${s} info`),e.push("");for(let i of t.slice(0,15)){let o=i.severity==="error"?"\u2717":i.severity==="warning"?"\u26A0":"\u2139",a=i.line>0?`:${i.line}`:"";e.push(` ${o} ${i.file}${a}`),e.push(` ${i.message}`),i.suggestedFix&&e.push(` \u2192 ${i.suggestedFix}`)}return t.length>15&&e.push(` ... and ${t.length-15} more`),e.join(`
78
- `)}function ph(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=de.join(e,n.file);try{let o=J.readFileSync(s,"utf-8").split(`
79
- `);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],J.writeFileSync(s,o.join(`
80
- `),"utf-8"),r.push({bug:n,fixed:!0,action:"Commented out console.log"}))}catch{r.push({bug:n,fixed:!1,action:"Failed to read/write file"})}}else r.push({bug:n,fixed:!1,action:"Requires manual fix or LLM assistance"});return r}function Po(t){return{name:"detect_bugs",description:"Scan the project for bugs using TypeScript checking, ESLint, and pattern analysis. Returns a report of found issues.",safety:"safe",parameters:{path:{type:"string",description:"Project path to scan (default: current directory)",required:!1},fix:{type:"string",description:'Set to "true" to auto-fix simple issues',required:!1}},execute:async e=>{let r=e.path||t,n=e.fix==="true"||e.fix===!0;try{let s=hh(r);if(n&&s.length>0){let o=ph(s,r).filter(l=>l.fixed).length;return{success:!0,output:`${Io(s)}
81
-
82
- Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:Io(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Fo=2*1024*1024,Mo=15e3,Do=32e3,mh="HablasBot/2.0 (+https://hablas.dev)";function gh(t){let e=t;return e=e.replace(/<(script|style|nav|footer|header|aside|iframe|noscript)[^>]*>[\s\S]*?<\/\1>/gi,""),e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/<\/(p|div|section|article|li|tr|h[1-6])>/gi,`
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 No(t,e,r,n){let s=await Kt.readdir(t,{withFileTypes:!0});for(let i of s){if(mp.has(i.name)||i.name.startsWith("."))continue;let o=ye.join(t,i.name);if(i.isDirectory())await No(o,e,r,n);else if(gp.has(ye.extname(i.name)))try{let l=(await Kt.readFile(o,"utf-8")).split(`
74
+ `),f=ye.relative(n,o);for(let u=0;u<l.length;u++)e.test(l[u])&&(r.push(`${f}:${u+1}: ${l[u].trim()}`),e.lastIndex=0)}catch{}}}var In=require("child_process"),Z=C(require("fs")),we=C(require("path"));function yp(t){let e=[],r=we.join(t,"tsconfig.json");if(!Z.existsSync(r))return e;try{(0,In.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 wp(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>Z.existsSync(we.join(t,n))))return e;try{(0,In.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:we.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 bp(t,e,r){let n;try{n=Z.readFileSync(t,"utf-8")}catch{return}let s=we.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 Sp(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=Z.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let f=we.join(s,l),u;try{u=Z.statSync(f)}catch{continue}u.isDirectory()?n(f,i+1):r.some(d=>l.endsWith(d))&&bp(f,t,e)}}return n(t),e.slice(0,20)}function _p(t){let e=[];e.push(...yp(t)),e.push(...wp(t)),e.push(...Sp(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function qo(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 xp(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=we.join(e,n.file);try{let o=Z.readFileSync(s,"utf-8").split(`
79
+ `);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],Z.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 Uo(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=_p(r);if(n&&s.length>0){let o=xp(s,r).filter(l=>l.fixed).length;return{success:!0,output:`${qo(s)}
81
+
82
+ Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:qo(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Bo=2*1024*1024,Ho=15e3,Wo=32e3,vp="HablasBot/2.0 (+https://hablas.dev)";function kp(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 yh(t){let e=t.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let r=t.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return r?r[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function wh(t,e){let r=[],n=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,s,i=new Set;for(;(s=n.exec(t))!==null;){let o=s[1].trim(),a=s[2].replace(/<[^>]+>/g,"").trim();if(!(o.startsWith("#")||o.startsWith("javascript:")||o.startsWith("mailto:"))){try{o=new URL(o,e).href}catch{continue}i.has(o)||(i.add(o),r.push({text:a||o,url:o}))}}return r}async function Lo(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Mo);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":mh,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(r),!n.ok)return{html:"",finalUrl:n.url||t,status:n.status};let s=n.headers.get("content-type")||"";if(!s.includes("text/")&&!s.includes("application/xhtml")&&!s.includes("application/json"))return{html:`[Binary content: ${s}]`,finalUrl:n.url||t,status:n.status};let i=n.body?.getReader();if(!i)return{html:"",finalUrl:n.url||t,status:n.status};let o=[],a=0;for(;a<Fo;){let{done:d,value:f}=await i.read();if(d)break;o.push(f),a+=f.length}if(a>=Fo)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(d=>l.decode(d,{stream:!0})).join("")+l.decode(),finalUrl:n.url||t,status:n.status}}catch(n){clearTimeout(r);let s=n instanceof Error?n:new Error(String(n));throw s.name==="AbortError"?new Error(`Timeout after ${Mo/1e3}s`):s}}function jo(){return[{name:"scrape_url",description:"Fetch a web page and extract its readable text content. Returns clean text/markdown without HTML tags. Use this to read documentation, articles, blog posts, or any web page.",safety:"safe",parameters:{url:{type:"string",description:"The URL to scrape (must start with http:// or https://)",required:!0}},execute:async t=>{let e=t.url;if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:r,finalUrl:n,status:s}=await Lo(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=yh(r),o=gh(r);return o.length>Do&&(o=o.slice(0,Do)+`
89
+ `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function Cp(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 $p(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 Vo(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Ho);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":vp,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<Bo;){let{done:u,value:d}=await i.read();if(u)break;o.push(d),a+=d.length}if(a>=Bo)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(u=>l.decode(u,{stream:!0})).join("")+l.decode(),finalUrl: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 ${Ho/1e3}s`):s}}function zo(){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 Vo(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=Cp(r),o=kp(r);return o.length>Wo&&(o=o.slice(0,Wo)+`
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 Lo(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=wh(n,s);if(r&&(o=o.filter(l=>l.url.toLowerCase().includes(r)||l.text.toLowerCase().includes(r))),o.length===0)return{success:!0,output:"No links found"+(r?` matching "${r}"`:"")};let a=o.slice(0,100).map((l,u)=>`${u+1}. [${l.text}](${l.url})`).join(`
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 Vo(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=$p(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,f)=>`${f+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 bh=3600*1e3,Ne=new Map;function Sh(t){let e=Ne.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>bh?(Ne.delete(t.toLowerCase().trim()),null):e.results:null}function _h(t,e){if(Ne.size>200){let r=Ne.keys().next().value;r!==void 0&&Ne.delete(r)}Ne.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function xh(t,e){let r=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!r)return null;try{let n=new URLSearchParams({q:t,count:String(Math.min(e,10))}),s=await fetch(`https://api.search.brave.com/res/v1/web/search?${n}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":r},signal:AbortSignal.timeout(1e4)});return s.ok?((await s.json()).web?.results??[]).slice(0,e).map(a=>({title:a.title||"",url:a.url||"",snippet:a.description||"",source:"brave"})):null}catch{return null}}async function vh(t,e){try{let r=new URLSearchParams({q:t}),n=await fetch(`https://html.duckduckgo.com/html/?${r}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!n.ok)return null;let s=await n.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(s))!==null&&i.length<e;){let l=a[1],u=a[2].replace(/<[^>]+>/g,"").trim(),d=a[3].replace(/<[^>]+>/g,"").trim(),f=l.match(/uddg=([^&]+)/);if(f)try{l=decodeURIComponent(f[1])}catch{}u&&l&&!l.startsWith("/")&&i.push({title:u,url:l,snippet:d,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,u=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let d=a[1],f=a[2].replace(/<[^>]+>/g,"").trim();f&&f.length>5&&!u.has(d)&&!d.includes("duckduckgo.com")&&(u.add(d),i.push({title:f,url:d,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function kh(t,e=5){let r=Sh(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>xh(t,e)},{name:"duckduckgo",fn:()=>vh(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return _h(t,i),i}catch{}return[]}function No(){return{name:"web_search",description:"Search the web for current information. Returns titles, URLs, and snippets from search results. Use this to find documentation, answers, latest versions, news, or any information not in your training data.",safety:"safe",parameters:{query:{type:"string",description:"The search query",required:!0},max_results:{type:"number",description:"Max results to return (default: 5, max: 10)",required:!1}},execute:async t=>{let e=t.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let r=Math.min(Math.max(1,t.max_results||5),10);try{let n=await kh(e.trim(),r);if(n.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let s=[`Search results for: "${e}" (${n.length} results, source: ${n[0].source})`,""];for(let i=0;i<n.length;i++){let o=n[i];s.push(`[${i+1}] ${o.title}`),s.push(` ${o.url}`),o.snippet&&s.push(` ${o.snippet}`),s.push("")}return{success:!0,output:s.join(`
96
- `)}}catch(n){return{success:!1,output:"",error:`Search failed: ${n instanceof Error?n.message:String(n)}`}}}}}var oe=k(require("fs")),Wo=k(require("path")),qo=50*1024*1024,Uo=4e4;function Bo(t){let e=t.toString("latin1"),r={},n=[],s=0,i=e.match(/\/Type\s*\/Page\b/g);s=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(r.title=xe(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=xe(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=xe(l[1]));let u=e.match(/\/Creator\s*\(([^)]*)\)/);u&&(r.creator=xe(u[1]));let d=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=d.exec(e))!==null;){let h=f[1],c=Ho(h);c.trim()&&n.push(c);try{let m=require("zlib"),y=Buffer.from(h,"latin1"),w=m.inflateSync(y).toString("latin1"),b=Ho(w);b.trim()&&!n.includes(b)&&n.push(b)}catch{}}return{text:n.join(`
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 Tp=3600*1e3,Ve=new Map;function Ap(t){let e=Ve.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>Tp?(Ve.delete(t.toLowerCase().trim()),null):e.results:null}function Ep(t,e){if(Ve.size>200){let r=Ve.keys().next().value;r!==void 0&&Ve.delete(r)}Ve.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Op(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 Rp(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],f=a[2].replace(/<[^>]+>/g,"").trim(),u=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}f&&l&&!l.startsWith("/")&&i.push({title:f,url:l,snippet:u,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,f=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let u=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!f.has(u)&&!u.includes("duckduckgo.com")&&(f.add(u),i.push({title:d,url:u,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function Ip(t,e=5){let r=Ap(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>Op(t,e)},{name:"duckduckgo",fn:()=>Rp(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return Ep(t,i),i}catch{}return[]}function Ko(){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 Ip(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 ue=C(require("fs")),Zo=C(require("path")),Go=50*1024*1024,Jo=4e4;function Xo(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=Ae(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=Ae(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=Ae(l[1]));let f=e.match(/\/Creator\s*\(([^)]*)\)/);f&&(r.creator=Ae(f[1]));let u=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=u.exec(e))!==null;){let p=d[1],c=Yo(p);c.trim()&&n.push(c);try{let m=require("zlib"),y=Buffer.from(p,"latin1"),w=m.inflateSync(y).toString("latin1"),b=Yo(w);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 Ho(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(xe(n[1]));let s=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(n=s.exec(t))!==null;){let l=n[1].match(/\(([^)]*)\)/g);if(l){let u=l.map(d=>xe(d.slice(1,-1))).join("");e.push(u)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(xe(n[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
101
- `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function xe(t){return t.replace(/\\n/g,`
102
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,r)=>String.fromCharCode(parseInt(r,8)))}function Vo(t){let e=r=>Wo.resolve(t,r);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async r=>{let n=e(r.path);if(!oe.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};if(!n.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${r.path}`};let s=oe.statSync(n);if(s.size>qo)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${qo/1024/1024}MB)`};try{let i=oe.readFileSync(n),{text:o,pages:a,metadata:l}=Bo(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
100
+ `).trim(),pages:s,metadata:r}}function Yo(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(Ae(n[1]));let s=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(n=s.exec(t))!==null;){let l=n[1].match(/\(([^)]*)\)/g);if(l){let f=l.map(u=>Ae(u.slice(1,-1))).join("");e.push(f)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(Ae(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 Ae(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 Qo(t){let e=r=>Zo.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(!ue.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=ue.statSync(n);if(s.size>Go)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${Go/1024/1024}MB)`};try{let i=ue.readFileSync(n),{text:o,pages:a,metadata:l}=Xo(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>Uo&&(u=u.slice(0,Uo)+`
104
+ [No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let f=o;return f.length>Jo&&(f=f.slice(0,Jo)+`
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(!oe.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=oe.statSync(n),i=oe.readFileSync(n),{pages:o,metadata:a}=Bo(i);return{success:!0,output:[`File: ${r.path}`,`Size: ${(s.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${s.mtime.toISOString()}`].filter(Boolean).join(`
109
- `)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var Jo=require("child_process"),Nt=k(require("fs")),Go=k(require("os")),Xo=k(require("path")),Yo=1e4,zo=16e3;function qe(t){try{let{execSync:e}=require("child_process");return e(`which ${t} 2>/dev/null || where ${t} 2>NUL`,{stdio:"ignore"}),!0}catch{return!1}}var Ko={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>qe("tsx")?`tsx "${t}"`:qe("ts-node")?`ts-node --transpileOnly "${t}"`:`node --no-warnings -e "require('esbuild').buildSync({entryPoints:['${t}'],write:false,format:'cjs'}).outputFiles.forEach(f=>eval(f.text))"`,available:()=>!0},python:{extension:".py",command:t=>qe("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>qe("python3")||qe("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>qe("bash")}};async function Ch(t,e,r=Yo){let n=Ko[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Ko).join(", ")}`,exitCode:1,duration:0,language:e};if(!n.available())return{success:!1,stdout:"",stderr:`Language "${e}" is not available on this system. Install the runtime first.`,exitCode:1,duration:0,language:e};let s=Go.tmpdir(),i=Xo.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{Nt.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let u=(0,Jo.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),d="",f="";u.stdout?.on("data",p=>{d+=p}),u.stderr?.on("data",p=>{f+=p}),u.on("close",p=>{let h=Date.now()-a;l({success:p===0,stdout:d.slice(0,zo),stderr:f.slice(0,zo/2),exitCode:p??1,duration:h,language:e})}),u.on("error",p=>{let h=Date.now()-a;l({success:!1,stdout:"",stderr:p.message,exitCode:1,duration:h,language:e})})})}finally{try{Nt.unlinkSync(i)}catch{}}}function Th(t){return/\b(interface|type|enum|as\s+\w|:\s*(string|number|boolean|any)\b|<[A-Z]\w*>)/.test(t)?"typescript":/^(import\s+\w|from\s+\w|def\s+\w|class\s+\w|print\s*\(|if\s+__name__)/m.test(t)?"python":/^(#!\/bin\/bash|echo\s|export\s|if\s+\[|for\s+\w+\s+in)/m.test(t)?"bash":"javascript"}function Zo(){return[{name:"execute_code",description:"Execute a code snippet and return the output. Supports JavaScript, TypeScript, Python, and Bash. Code runs in a temporary file with a timeout. Use this to test code, run calculations, verify logic, or prototype solutions.",safety:"confirm",parameters:{code:{type:"string",description:"The code to execute",required:!0},language:{type:"string",description:"Language: javascript, typescript, python, bash (auto-detected if omitted)",required:!1},timeout:{type:"number",description:"Timeout in milliseconds (default: 10000, max: 30000)",required:!1}},execute:async t=>{let e=t.code;if(!e?.trim())return{success:!1,output:"",error:"Code is required"};let r=t.language?.toLowerCase()||Th(e),n=Math.min(Math.max(1e3,t.timeout||Yo),3e4),s=await Ch(e,r,n),i=[];return i.push(`Language: ${s.language} | Exit: ${s.exitCode} | Duration: ${s.duration}ms`),i.push(""),s.stdout&&(i.push("Output:"),i.push(s.stdout)),s.stderr&&(i.push(s.stdout?`
108
+ ${f}`}}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(!ue.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=ue.statSync(n),i=ue.readFileSync(n),{pages:o,metadata:a}=Xo(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 ra=require("child_process"),Gt=C(require("fs")),na=C(require("os")),sa=C(require("path")),ia=1e4,ea=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 ta={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 Pp(t,e,r=ia){let n=ta[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(ta).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=na.tmpdir(),i=sa.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{Gt.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let f=(0,ra.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),u="",d="";f.stdout?.on("data",h=>{u+=h}),f.stderr?.on("data",h=>{d+=h}),f.on("close",h=>{let p=Date.now()-a;l({success:h===0,stdout:u.slice(0,ea),stderr:d.slice(0,ea/2),exitCode:h??1,duration:p,language:e})}),f.on("error",h=>{let p=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:p,language:e})})})}finally{try{Gt.unlinkSync(i)}catch{}}}function Mp(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 oa(){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()||Mp(e),n=Math.min(Math.max(1e3,t.timeout||ia),3e4),s=await Pp(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 Ue=class{tools=new Map;constructor(e,r){let n=ko(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",Oo(e,r)),this.tools.set("search_codebase",$o(e)),this.tools.set("detect_bugs",Po(e)),this.tools.set("web_search",No());for(let s of jo())this.tools.set(s.name,s);for(let s of Vo(e))this.tools.set(s.name,s);for(let s of Zo())this.tools.set(s.name,s)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let r=this.tools.get(e.name);return r?r.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let r={},n=[];for(let[s,i]of Object.entries(e.parameters))r[s]={type:i.type==="number"?"number":"string",description:i.description},i.required&&n.push(s);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:r,required:n}}}})}getToolDescriptions(){return this.getAll().map(r=>{let n=Object.entries(r.parameters).map(([s,i])=>` ${s}: ${i.type} \u2014 ${i.description}`).join(`
111
+ `),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var Ke=class{tools=new Map;constructor(e,r){let n=Io(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",Do(e,r)),this.tools.set("search_codebase",jo(e)),this.tools.set("detect_bugs",Uo(e)),this.tools.set("web_search",Ko());for(let s of zo())this.tools.set(s.name,s);for(let s of Qo(e))this.tools.set(s.name,s);for(let s of oa())this.tools.set(s.name,s)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let r=this.tools.get(e.name);return r?r.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let r={},n=[];for(let[s,i]of Object.entries(e.parameters))r[s]={type:i.type==="number"?"number":"string",description:i.description},i.required&&n.push(s);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:r,required:n}}}})}getToolDescriptions(){return this.getAll().map(r=>{let n=Object.entries(r.parameters).map(([s,i])=>` ${s}: ${i.type} \u2014 ${i.description}`).join(`
112
112
  `);return`- ${r.name} [${r.safety}]: ${r.description}
113
113
  ${n}`}).join(`
114
114
 
115
- `)}};var Qo=k(require("crypto"));function Tn(t){return Math.ceil(t.length/3.5)}function lt(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
116
- ... [truncated to fit context budget]`}var Be=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,r,n){let s=this.computeHash(r),i=this.cache.get(e);if(i&&i.hash===s){i.lastUsed=Date.now(),i.accessCount++;return}let o=Tn(r),a=n?.importance??this.autoImportance(e,r);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:r,hash:s,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:n?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,r){let n=this.cache.get(e);return n?n.hash!==this.computeHash(r):!0}buildContext(e){let r=e||this.budget,n=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),s=0,i=[];for(let o of n){if(s+o.tokenCount>r){if(o.importance>=7){let a=r-s;if(a>200){let l=lt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
115
+ `)}};var aa=C(require("crypto"));function Pn(t){return Math.ceil(t.length/3.5)}function ht(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
116
+ ... [truncated to fit context budget]`}var Ge=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=Pn(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=ht(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
117
117
  ${l}`),s+=a}}continue}i.push(`--- ${o.path} ---
118
118
  ${o.content}`),s+=o.tokenCount}return i.join(`
119
119
 
120
- `)}buildAgentContext(e,r){let n=r||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(u=>i.length===0?!0:i.some(d=>u.path.includes(d))).sort((u,d)=>this.computeScore(d)-this.computeScore(u)),a=0,l=[];for(let u of o){if(a+u.tokenCount>n)break;l.push(`--- ${u.path} ---
121
- ${u.content}`),a+=u.tokenCount}return l.join(`
120
+ `)}buildAgentContext(e,r){let n=r||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(f=>i.length===0?!0:i.some(u=>f.path.includes(u))).sort((f,u)=>this.computeScore(u)-this.computeScore(f)),a=0,l=[];for(let f of o){if(a+f.tokenCount>n)break;l.push(`--- ${f.path} ---
121
+ ${f.content}`),a+=f.tokenCount}return l.join(`
122
122
 
123
- `)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,r)=>r.importance-e.importance)}evictToFit(e){let r=Array.from(this.cache.entries()).map(([s,i])=>({key:s,...i,score:this.computeScore(i)})).sort((s,i)=>s.score-i.score),n=0;for(let s of r){if(n>=e)break;s.importance>=9||(n+=s.tokenCount,this.usedTokens-=s.tokenCount,this.cache.delete(s.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let s=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-s/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,r){let n=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(n=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=3);let s=Tn(r);return s>2e3&&(n=Math.max(1,n-1)),s>5e3&&(n=Math.max(1,n-2)),n}autoTag(e){let r=[];return/\.(ts|tsx)$/.test(e)&&r.push("typescript"),/\.(js|jsx)$/.test(e)&&r.push("javascript"),/\.json$/.test(e)&&r.push("config"),/\.md$/.test(e)&&r.push("documentation"),/\.(css|scss|sass)$/.test(e)&&r.push("style"),/\.(test|spec)\./i.test(e)&&r.push("test"),/src\//.test(e)&&r.push("source"),r}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let r=this.accessHistory[this.accessHistory.length-1];if(r&&Date.now()-this.getGroupTime(r)<3e4){if(!r.includes(e)){r.push(e);for(let n of r)if(n!==e){let s=this.cache.get(n);s&&!s.relatedFiles.includes(e)&&s.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return Qo.createHash("md5").update(e).digest("hex")}};var Ah=0;function ct(){return`msg_${Date.now()}_${++Ah}`}function He(t){return Math.ceil(t.length/4)}var We=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,r=50,n=32e3){this.maxMessages=r,this.maxTokens=n,this.sessionId=`session_${Date.now()}`;let s=He(e);this.messages.push({id:ct(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:s,compressed:!1,tags:["system"]}),this.totalTokens=s}getSessionId(){return this.sessionId}addUserMessage(e,r){let n=ct(),s=He(e);return this.messages.push({id:n,role:"user",content:e,timestamp:Date.now(),priority:r?.priority||"high",tokenEstimate:s,compressed:!1,tags:r?.tags||["user-input"]}),this.totalTokens+=s,this.trimIfNeeded(),n}addAssistantMessage(e,r,n){let s=ct(),i=He(e),o={id:s,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:n||"hablas",tokenEstimate:i,compressed:!1,tags:n?[`agent:${n}`]:["assistant"]};return r&&r.length>0&&(o.tool_calls=r,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,n&&this.agentMessageCounts.set(n,(this.agentMessageCounts.get(n)||0)+1),this.trimIfNeeded(),s}addToolMessage(e,r){let n=ct(),s=He(e);return this.messages.push({id:n,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:s,compressed:!1,tags:r?[`tool:${r}`]:["tool-result"]}),this.totalTokens+=s,this.trimIfNeeded(),n}getMessages(){return this.messages.map(e=>{let r={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls),r})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(r=>r.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let r=He(e),n=this.messages.filter(s=>s.priority==="critical"&&s.role!=="system");this.messages=[{id:ct(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]},...n],this.recalculateTokens()}takeSnapshot(e){let r={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(n=>({...n})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(r),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),r.id}rollback(e){let r=this.snapshots.find(n=>n.id===e);return r?(this.messages=r.messages.map(n=>({...n})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,r){let n=this.messages.length,s=new t(r,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?s.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&s.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:n,session:s}),s}mergeFork(e,r){let n=this.forks.get(e);if(!n)return!1;let s=n.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(r)this.addAssistantMessage(`[Agent @${e} result]: ${r}`,void 0,e);else if(s.length>0){let i=s.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let r=e.toLowerCase();return this.messages.filter(n=>n.content.toLowerCase().includes(r))}getMessagesByTag(e){return this.messages.filter(r=>r.tags.includes(e))}getLastByRole(e,r=1){return this.messages.filter(n=>n.role===e).slice(-r)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(r=>r.role==="tool"&&!r.compressed&&r.tokenEstimate>200);for(let r of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let r=this.messages.filter(n=>n.role==="assistant"&&!n.compressed&&n.priority!=="critical"&&n.tokenEstimate>300);for(let n of r.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(n)}}if(this.messages.length>this.maxMessages){let r=this.messages[0],n=this.messages.slice(1),s={critical:3,high:2,normal:1,low:0},i=n.sort((o,a)=>{let l=s[a.priority]-s[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[r,...i],this.recalculateTokens()}}compressMessage(e){let r=e.content.length,n=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
123
+ `)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,r)=>r.importance-e.importance)}evictToFit(e){let r=Array.from(this.cache.entries()).map(([s,i])=>({key:s,...i,score:this.computeScore(i)})).sort((s,i)=>s.score-i.score),n=0;for(let s of r){if(n>=e)break;s.importance>=9||(n+=s.tokenCount,this.usedTokens-=s.tokenCount,this.cache.delete(s.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let s=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-s/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,r){let n=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(n=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=3);let s=Pn(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 aa.createHash("md5").update(e).digest("hex")}};var Fp=0;function mt(){return`msg_${Date.now()}_${++Fp}`}function Je(t){return Math.ceil(t.length/4)}var Xe=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=Je(e);this.messages.push({id:mt(),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=mt(),s=Je(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=mt(),i=Je(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=mt(),s=Je(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=Je(e),n=this.messages.filter(s=>s.priority==="critical"&&s.role!=="system");this.messages=[{id:mt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]},...n],this.recalculateTokens()}takeSnapshot(e){let r={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(n=>({...n})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(r),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),r.id}rollback(e){let r=this.snapshots.find(n=>n.id===e);return r?(this.messages=r.messages.map(n=>({...n})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,r){let n=this.messages.length,s=new t(r,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?s.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&s.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:n,session:s}),s}mergeFork(e,r){let n=this.forks.get(e);if(!n)return!1;let s=n.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(r)this.addAssistantMessage(`[Agent @${e} result]: ${r}`,void 0,e);else if(s.length>0){let i=s.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let r=e.toLowerCase();return this.messages.filter(n=>n.content.toLowerCase().includes(r))}getMessagesByTag(e){return this.messages.filter(r=>r.tags.includes(e))}getLastByRole(e,r=1){return this.messages.filter(n=>n.role===e).slice(-r)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(r=>r.role==="tool"&&!r.compressed&&r.tokenEstimate>200);for(let r of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let r=this.messages.filter(n=>n.role==="assistant"&&!n.compressed&&n.priority!=="critical"&&n.tokenEstimate>300);for(let n of r.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(n)}}if(this.messages.length>this.maxMessages){let r=this.messages[0],n=this.messages.slice(1),s={critical:3,high:2,normal:1,low:0},i=n.sort((o,a)=>{let l=s[a.priority]-s[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[r,...i],this.recalculateTokens()}}compressMessage(e){let r=e.content.length,n=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
124
124
  ...(compressed from `+r+" chars)":e.content=e.content.slice(0,400)+`
125
- ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=He(e.content),this.totalTokens-=n-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,r)=>e+r.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let r=JSON.parse(e);if(!r.messages||!Array.isArray(r.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=r.sessionId||`session_${Date.now()}`,this.messages=r.messages,this.totalTokens=r.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(r.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}};var ze=k(require("fs")),ea=k(require("path"));var A=k(require("fs")),E=k(require("path"));function Eh(t){let e=E.join(t,"package.json");if(A.existsSync(e))try{let r=JSON.parse(A.readFileSync(e,"utf-8")),n={...r.dependencies,...r.devDependencies};if(n.next)return"next";if(n.nuxt)return"nuxt";if(n["@angular/core"])return"angular";if(n.svelte||n["@sveltejs/kit"])return"svelte";if(n.vue)return"vue";if(n.react)return"react";if(n["@nestjs/core"])return"nest";if(n.fastify)return"fastify";if(n.express)return"express"}catch{}if(A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml")))try{let r=A.existsSync(E.join(t,"requirements.txt"))?A.readFileSync(E.join(t,"requirements.txt"),"utf-8"):"";if(r.includes("django"))return"django";if(r.includes("flask"))return"flask";if(r.includes("fastapi"))return"fastapi"}catch{}if(A.existsSync(E.join(t,"Cargo.toml")))try{if(A.readFileSync(E.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(A.existsSync(E.join(t,"go.mod")))try{if(A.readFileSync(E.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Oh(t){return A.existsSync(E.join(t,"pnpm-lock.yaml"))?"pnpm":A.existsSync(E.join(t,"yarn.lock"))?"yarn":A.existsSync(E.join(t,"bun.lockb"))?"bun":A.existsSync(E.join(t,"package-lock.json"))?"npm":A.existsSync(E.join(t,"Cargo.toml"))?"cargo":A.existsSync(E.join(t,"go.mod"))?"go":A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml"))?"pip":"unknown"}function $h(t){return A.existsSync(E.join(t,"tsconfig.json"))?"TypeScript":A.existsSync(E.join(t,"package.json"))?"JavaScript":A.existsSync(E.join(t,"Cargo.toml"))?"Rust":A.existsSync(E.join(t,"go.mod"))?"Go":A.existsSync(E.join(t,"pyproject.toml"))||A.existsSync(E.join(t,"requirements.txt"))?"Python":"Unknown"}function Rh(t){let e=E.join(t,".git","HEAD");if(!A.existsSync(e))return null;try{let r=A.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function Ve(t){let e=Eh(t),r=Oh(t),n=$h(t),s=Rh(t),i=A.existsSync(E.join(t,"Dockerfile"))||A.existsSync(E.join(t,"docker-compose.yml"))||A.existsSync(E.join(t,"docker-compose.yaml")),o=A.existsSync(E.join(t,".github","workflows"))||A.existsSync(E.join(t,".gitlab-ci.yml"))||A.existsSync(E.join(t,"Jenkinsfile")),a=A.existsSync(E.join(t,"__tests__"))||A.existsSync(E.join(t,"tests"))||A.existsSync(E.join(t,"test"))||A.existsSync(E.join(t,"spec")),l=A.existsSync(E.join(t,".git")),u=[],d=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of d)A.existsSync(E.join(t,m))&&u.push(m);let f=[],p=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let m of p)A.existsSync(E.join(t,m))&&f.push(m);let h=[],c=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let m of c)A.existsSync(E.join(t,m))&&h.push(m);return{rootPath:t,framework:e,packageManager:r,language:n,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:s,envFiles:u,configFiles:f,entryPoints:h}}function qt(t){let e=[` Project: ${E.basename(t.rootPath)}`,` Framework: ${t.framework}`,` Language: ${t.language}`,` Package: ${t.packageManager}`,` Git: ${t.hasGit?`\u2713 (${t.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${t.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${t.hasCICD?"\u2713":"\u2717"}`,` Tests: ${t.hasTests?"\u2713":"\u2717"}`];return t.envFiles.length>0&&e.push(` Env files: ${t.envFiles.join(", ")}`),e.join(`
126
- `)}async function Ke(t,e){let r=[],n=ea.join(t,"package.json");if(ze.existsSync(n))try{let o=JSON.parse(ze.readFileSync(n,"utf-8"));r.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&r.push(`Description: ${o.description}`)}catch{}let s=Ve(t);r.push(`Framework: ${s.framework}`),r.push(`Language: ${s.language}`),r.push(`Package Manager: ${s.packageManager}`),r.push(`Git: ${s.hasGit?s.gitBranch||"present":"absent"}`);let i=Ih(t,16);return i.length>0&&r.push(`Top-level: ${i.join(", ")}`),e?.workspace?.envParsing&&s.envFiles.length>0&&r.push(`Env files: ${s.envFiles.join(", ")}`),r.push(`Directory: ${t}`),r.join(`
127
- `)}function Ih(t,e){try{return ze.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function Je(t,e){return`You are Hablas, a single powerful AI software engineering agent created by Abdulmoin Hablas.
125
+ ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=Je(e.content),this.totalTokens-=n-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,r)=>e+r.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let r=JSON.parse(e);if(!r.messages||!Array.isArray(r.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=r.sessionId||`session_${Date.now()}`,this.messages=r.messages,this.totalTokens=r.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(r.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}};var Ze=C(require("fs")),la=C(require("path"));var A=C(require("fs")),E=C(require("path"));function Lp(t){let e=E.join(t,"package.json");if(A.existsSync(e))try{let r=JSON.parse(A.readFileSync(e,"utf-8")),n={...r.dependencies,...r.devDependencies};if(n.next)return"next";if(n.nuxt)return"nuxt";if(n["@angular/core"])return"angular";if(n.svelte||n["@sveltejs/kit"])return"svelte";if(n.vue)return"vue";if(n.react)return"react";if(n["@nestjs/core"])return"nest";if(n.fastify)return"fastify";if(n.express)return"express"}catch{}if(A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml")))try{let r=A.existsSync(E.join(t,"requirements.txt"))?A.readFileSync(E.join(t,"requirements.txt"),"utf-8"):"";if(r.includes("django"))return"django";if(r.includes("flask"))return"flask";if(r.includes("fastapi"))return"fastapi"}catch{}if(A.existsSync(E.join(t,"Cargo.toml")))try{if(A.readFileSync(E.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(A.existsSync(E.join(t,"go.mod")))try{if(A.readFileSync(E.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Dp(t){return A.existsSync(E.join(t,"pnpm-lock.yaml"))?"pnpm":A.existsSync(E.join(t,"yarn.lock"))?"yarn":A.existsSync(E.join(t,"bun.lockb"))?"bun":A.existsSync(E.join(t,"package-lock.json"))?"npm":A.existsSync(E.join(t,"Cargo.toml"))?"cargo":A.existsSync(E.join(t,"go.mod"))?"go":A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml"))?"pip":"unknown"}function jp(t){return A.existsSync(E.join(t,"tsconfig.json"))?"TypeScript":A.existsSync(E.join(t,"package.json"))?"JavaScript":A.existsSync(E.join(t,"Cargo.toml"))?"Rust":A.existsSync(E.join(t,"go.mod"))?"Go":A.existsSync(E.join(t,"pyproject.toml"))||A.existsSync(E.join(t,"requirements.txt"))?"Python":"Unknown"}function Np(t){let e=E.join(t,".git","HEAD");if(!A.existsSync(e))return null;try{let r=A.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function Ye(t){let e=Lp(t),r=Dp(t),n=jp(t),s=Np(t),i=A.existsSync(E.join(t,"Dockerfile"))||A.existsSync(E.join(t,"docker-compose.yml"))||A.existsSync(E.join(t,"docker-compose.yaml")),o=A.existsSync(E.join(t,".github","workflows"))||A.existsSync(E.join(t,".gitlab-ci.yml"))||A.existsSync(E.join(t,"Jenkinsfile")),a=A.existsSync(E.join(t,"__tests__"))||A.existsSync(E.join(t,"tests"))||A.existsSync(E.join(t,"test"))||A.existsSync(E.join(t,"spec")),l=A.existsSync(E.join(t,".git")),f=[],u=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of u)A.existsSync(E.join(t,m))&&f.push(m);let d=[],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)A.existsSync(E.join(t,m))&&d.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)A.existsSync(E.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:f,configFiles:d,entryPoints:p}}function Jt(t){let e=[` Project: ${E.basename(t.rootPath)}`,` Framework: ${t.framework}`,` Language: ${t.language}`,` Package: ${t.packageManager}`,` Git: ${t.hasGit?`\u2713 (${t.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${t.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${t.hasCICD?"\u2713":"\u2717"}`,` Tests: ${t.hasTests?"\u2713":"\u2717"}`];return t.envFiles.length>0&&e.push(` Env files: ${t.envFiles.join(", ")}`),e.join(`
126
+ `)}async function Qe(t,e){let r=[],n=la.join(t,"package.json");if(Ze.existsSync(n))try{let o=JSON.parse(Ze.readFileSync(n,"utf-8"));r.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&r.push(`Description: ${o.description}`)}catch{}let s=Ye(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=qp(t,16);return i.length>0&&r.push(`Top-level: ${i.join(", ")}`),e?.workspace?.envParsing&&s.envFiles.length>0&&r.push(`Env files: ${s.envFiles.join(", ")}`),r.push(`Directory: ${t}`),r.join(`
127
+ `)}function qp(t,e){try{return Ze.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function et(t,e){return`You are Hablas, a single powerful AI software engineering agent created by Abdulmoin Hablas.
128
128
 
129
129
  Identity:
130
130
  - You are the only visible agent.
@@ -150,10 +150,10 @@ Core execution rules:
150
150
  8. If the task is implementation, verify before claiming success.
151
151
  9. If you cannot verify, say exactly what remains unverified.
152
152
 
153
- ${Ph(e)}
153
+ ${Up(e)}
154
154
 
155
155
  Current project context:
156
- ${t}`}function Ph(t){if(t.kind==="casual")return`Task profile:
156
+ ${t}`}function Up(t){if(t.kind==="casual")return`Task profile:
157
157
  - Casual social turn.
158
158
  - No tools unless absolutely unavoidable.`;if(t.kind==="read")return`Task profile:
159
159
  - Read-only or project-inspection task.
@@ -165,8 +165,11 @@ ${t}`}function Ph(t){if(t.kind==="casual")return`Task profile:
165
165
  - Deliver a structured recommendation, not drama.`;let e=t.continuity?"- Continue from existing work. Do not restart the project from zero.":"- Implementation task.",r=t.oneStepDelivery?"- The user requested one-step delivery with no follow-up questions. Complete as much as possible in one pass.":"- Ask a clarifying question only if the task is truly blocked.";return`Task profile:
166
166
  ${e}
167
167
  ${r}
168
+ - You MUST use workspace tools for implementation work.
169
+ - Do not answer with raw code blocks as the main result if you can create or modify files directly.
170
+ - The task is not complete unless you actually inspect and then create/modify the relevant files.
168
171
  - Prefer minimal correct edits over broad rewrites.
169
- - Verify changes before claiming completion.`}var Fh=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Mh=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,Dh=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Lh=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate)\b/i,jh=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,Nh=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,qh=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function ut(t){let e=t.trim(),r=e.toLowerCase(),n=Mh.test(r),s=Dh.test(r),i=Lh.test(r)||n||s,o=jh.test(r)&&!i,a=Nh.test(r),l=!i&&(qh.test(r)||e.endsWith("?"));return Fh.test(e)&&!a&&!i&&!o?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:i?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:n,oneStepDelivery:s,requiresProjectContext:!0,reason:n?"Continuation of existing work requires reading and modifying project artifacts.":"Implementation request requires tool-based execution."}:o?{kind:"analysis",needsTools:a,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:a,reason:a?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:l||a?{kind:"read",needsTools:a,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:a,reason:a?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}function Uh(t,e){if(!e.needsTools)return[{id:"respond",title:"Respond directly and clearly."}];if(e.kind==="read")return[{id:"inspect",title:"Inspect the minimum relevant files."},{id:"answer",title:"Answer precisely from observed facts."}];if(e.kind==="analysis")return[{id:"inspect-context",title:"Inspect only the files needed for analysis."},{id:"reason",title:"Form a concise architectural recommendation."},{id:"answer",title:"Present the result as Hablas only."}];let r=[];return e.continuity&&r.push({id:"continuity",title:"Load existing project context and continue instead of restarting."}),r.push({id:"inspect",title:"Inspect the relevant code and files."}),r.push({id:"implement",title:"Apply the smallest correct implementation."}),r.push({id:"verify",title:"Run verification before claiming completion."}),r.push({id:"answer",title:"Summarize the outcome clearly."}),e.oneStepDelivery&&r.unshift({id:"delivery-contract",title:"Treat the request as no-questions one-step delivery."}),r}function ta(t){let e=ut(t);return{input:t,profile:e,plan:Uh(t,e)}}var ra=k(require("readline")),Bt=require("process"),Ut=class{rl=ra.createInterface({input:Bt.stdin,output:Bt.stdout,terminal:!0});async prompt(e){return new Promise(r=>{this.rl.question(e,n=>r(n))})}async confirm(e){return(await this.prompt(`${e} [Y/n] `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return(await this.prompt(`${e} Type yes to confirm: `)).trim().toLowerCase()==="yes"}close(){this.rl.close()}};var Bh={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},Hh=`
172
+ - Verify changes before claiming completion.`}var Bp=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Hp=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,Wp=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Vp=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,zp=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,Kp=/\b(frontend|backend|store|shop|website|web app|landing page|page|component|ui|ux|auth|login|dashboard|api|endpoint|schema|database|project|application|app)\b/i,Gp=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,Jp=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,ca=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function gt(t){let e=t.trim(),r=e.toLowerCase(),n=Hp.test(r),s=Wp.test(r),i=Vp.test(r)||zp.test(r),o=Kp.test(r),a=Gp.test(r),l=i||n||s||o&&e.length>18&&!ca.test(r)&&!a,f=a&&!i&&!n&&!s,u=Jp.test(r)||o,d=!l&&!f&&(ca.test(r)||e.endsWith("?"));return Bp.test(e)&&!u&&!l&&!f?{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."}:f?{kind:"analysis",needsTools:u,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||u?{kind:"read",needsTools:u,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"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 Xp(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 ua(t){let e=gt(t);return{input:t,profile:e,plan:Xp(t,e)}}var fa=C(require("readline")),Yt=require("process"),Xt=class{rl=fa.createInterface({input:Yt.stdin,output:Yt.stdout,terminal:!0});async prompt(e){return new Promise(r=>{this.rl.question(e,n=>r(n))})}async confirm(e){return(await this.prompt(`${e} [Y/n] `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return(await this.prompt(`${e} Type yes to confirm: `)).trim().toLowerCase()==="yes"}close(){this.rl.close()}};var Yp={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},Zp=`
170
173
  ## Reasoning Protocol
171
174
 
172
175
  Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
@@ -195,15 +198,15 @@ After receiving a tool result, think again:
195
198
  - One tool call per turn. Wait for the result before the next call.
196
199
  - If a tool fails, analyze the error in <thinking> before retrying.
197
200
  - When done, give a concise final answer WITHOUT <thinking> tags.
198
- `.trim(),Wh=`
201
+ `.trim(),Qp=`
199
202
  ## Reasoning
200
203
  For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
201
204
  The user will NOT see thinking blocks. One tool call per turn.
202
- `.trim(),An=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...Bh,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,r="M"){return!this.config.thinkingEnabled||r==="XS"?e:r==="S"?`${e}
205
+ `.trim(),Mn=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...Yp,...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}
203
206
 
204
- ${Wh}`:`${e}
207
+ ${Qp}`:`${e}
205
208
 
206
- ${Hh}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let r=[],n=e,s=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=s.exec(e))!==null;)r.push(i[1].trim());n=n.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)r.push(i[1].trim());n=n.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(n);a&&(r.push(a[1].trim()),n=n.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(n);return l&&(r.push(l[1].trim()),n=n.replace(/<think>[\s\S]*$/i,"")),{thinking:r.join(`
209
+ ${Zp}`}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(`
207
210
 
208
211
  `).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`
209
212
  <self_eval>
@@ -226,21 +229,21 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
226
229
  }
227
230
  </self_eval>
228
231
  `.trim()}parseSelfEval(e){let r=[/^\s*(\{[\s\S]*\})\s*$/,/```(?:json)?\s*\n([\s\S]*?)\n```/,/<self_eval_result>([\s\S]*?)<\/self_eval_result>/,/(\{[\s\S]*?"score"[\s\S]*?"completed"[\s\S]*?\})/];for(let n of r){let s=e.match(n);if(s)try{let i=JSON.parse(s[1]);return this.normalizeSelfEval(i)}catch{}}return null}normalizeSelfEval(e){let r=typeof e.score=="number"?Math.max(0,Math.min(10,Math.round(e.score))):5,n=typeof e.completed=="boolean"?e.completed:r>=7,s=typeof e.rationale=="string"?e.rationale.slice(0,500):"No rationale provided",i=Array.isArray(e.issues)?e.issues.filter(a=>typeof a=="string").slice(0,5):[],o="medium";return e.confidence==="high"||e.confidence==="medium"||e.confidence==="low"?o=e.confidence:r>=8?o="high":r<=4&&(o="low"),{score:r,completed:n,rationale:s,issues:i,confidence:o}}buildBudgetWarningPrompt(){let e=this.remainingBudget();return e<=0?"[SYSTEM] You have exceeded the maximum reasoning steps. You MUST provide your final answer NOW. Do not call any more tools.":e<=3?`[SYSTEM] You have only ${e} step(s) remaining. Wrap up your work and provide a final answer soon.`:null}buildReflectionHint(e,r,n){return r?"":["<thinking>",`Tool "${e}" FAILED. Before retrying:`,"1. What went wrong? Analyze the error message carefully.","2. Can I fix the arguments and retry?","3. Is there an alternative approach?",`Error preview: ${n.slice(0,300)}`,"</thinking>"].join(`
229
- `)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(s=>s.action).length,n=this.turnSteps.filter(s=>s.reflection).length;return`${e} steps, ${r} actions, ${n} reflections`}};function Ht(t){return new An(t)}var Vh=[{test:t=>/ENOENT|no such file|not found|does not exist/i.test(t),errorClass:"file_not_found",strategy:"read_first",explanation:"The file or directory does not exist.",suggestion:"Use list_dir to check what files exist, then retry with the correct path.",alternatives:["list_dir","search_codebase"],autoRetry:!1},{test:t=>/EACCES|permission denied/i.test(t),errorClass:"permission_denied",strategy:"graceful_fail",explanation:"Permission denied \u2014 the process lacks access rights.",suggestion:"Check file ownership or try a different path. Do NOT use sudo.",alternatives:[],autoRetry:!1},{test:t=>/EISDIR|is a directory/i.test(t),errorClass:"path_is_directory",strategy:"retry_fixed",explanation:"The path points to a directory, not a file.",suggestion:"Append the filename to the path. Use list_dir to see contents.",alternatives:["list_dir"],autoRetry:!1},{test:t=>/EEXIST|already exists/i.test(t),errorClass:"file_already_exists",strategy:"read_first",explanation:"A file or directory already exists at that path.",suggestion:"Read the existing file first, then decide whether to overwrite or edit it.",alternatives:["read_file","edit_file"],autoRetry:!1},{test:t=>/no match|not found in file|search string not found/i.test(t),errorClass:"search_no_match",strategy:"read_first",explanation:"The search string was not found in the file.",suggestion:"Read the file first to see its actual content, then use the exact text for search/replace.",alternatives:["read_file","search_codebase"],autoRetry:!1},{test:t=>/command not found|not recognized/i.test(t),errorClass:"command_not_found",strategy:"alternative_tool",explanation:"The command does not exist on this system.",suggestion:"Check if the program is installed, or use a different command that achieves the same goal.",alternatives:["run_command"],autoRetry:!1},{test:t=>/timeout|timed out|ETIMEDOUT/i.test(t),errorClass:"command_timeout",strategy:"retry_fixed",explanation:"The command took too long and was terminated.",suggestion:"Try a simpler version of the command, or increase the timeout, or run it in background.",alternatives:[],autoRetry:!1},{test:t=>/exit code|exited with|non-zero/i.test(t),errorClass:"command_exit_error",strategy:"retry_fixed",explanation:"The command executed but returned an error.",suggestion:"Read the error output carefully. Fix the root cause (missing dependency, wrong syntax, etc.).",alternatives:[],autoRetry:!1},{test:t=>/syntax error|unexpected token|parse error|SyntaxError/i.test(t),errorClass:"syntax_error",strategy:"retry_fixed",explanation:"The content has a syntax error.",suggestion:"Review the generated code for syntax issues, fix them, and retry.",alternatives:[],autoRetry:!1},{test:t=>/ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(t),errorClass:"network_error",strategy:"retry_same",explanation:"Network connection failed.",suggestion:"This may be transient. Retry the same operation, or check connectivity.",alternatives:[],autoRetry:!0},{test:t=>/invalid argument|missing required|expected.*but got|type error/i.test(t),errorClass:"invalid_arguments",strategy:"retry_fixed",explanation:"The tool was called with invalid or missing arguments.",suggestion:"Check the tool's parameter requirements and provide correct values.",alternatives:[],autoRetry:!1},{test:t=>/ENOMEM|out of memory|resource|too large|max.*exceeded/i.test(t),errorClass:"resource_limit",strategy:"decompose_task",explanation:"Resource limit exceeded (memory, file size, etc.).",suggestion:"Break the task into smaller pieces, or process less data at once.",alternatives:[],autoRetry:!1}],En=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,r,n){let s=this.failures.get(e),i=s?s.count+1:1,o={tool:e,count:i,lastError:r,lastStrategy:"retry_same"};if(i>this.maxRetriesPerTool)return o.lastStrategy="ask_user",this.failures.set(e,o),{errorClass:"unknown",strategy:"ask_user",explanation:`Tool "${e}" has failed ${i} times in this turn.`,suggestion:`Stop retrying "${e}". Ask the user for clarification or try a completely different approach.`,alternatives:this.suggestAlternatives(e),autoRetry:!1};for(let a of Vh)if(a.test(r)){let l=s?.lastStrategy===a.strategy&&i>=2,u=l?"decompose_task":a.strategy;return o.lastStrategy=u,this.failures.set(e,o),{errorClass:a.errorClass,strategy:u,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,r){let n=[`ERROR: ${r}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&n.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":n.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":n.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":n.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":n.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":n.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":n.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return n.join(`
230
- `)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let r=this.failures.get(e);return r?r.count<=1&&r.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function Wt(t=3){return new En(t)}var ae=k(require("fs")),zt=k(require("path")),na=k(require("os")),Vt=zt.join(na.homedir(),".hablas","model-formats.json");function zh(){try{if(ae.existsSync(Vt))return JSON.parse(ae.readFileSync(Vt,"utf-8"))}catch{}return{}}function Kh(t){try{let e=zt.dirname(Vt);ae.existsSync(e)||ae.mkdirSync(e,{recursive:!0}),ae.writeFileSync(Vt,JSON.stringify(t,null,2),"utf-8")}catch{}}function sa(t,e){let r=0,n=!1,s=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){s=!1;continue}if(o==="\\"&&n){s=!0;continue}if(o==='"'){n=!n;continue}if(!n&&(o==="{"&&r++,o==="}"&&(r--,r===0)))return t.slice(e,i+1)}return null}function ft(t){if(typeof t.name=="string"&&t.arguments&&typeof t.arguments=="object")return{tool:t.name,args:t.arguments};if(typeof t.tool=="string"&&t.args&&typeof t.args=="object")return{tool:t.tool,args:t.args};if(typeof t.name=="string"&&t.parameters&&typeof t.parameters=="object")return{tool:t.name,args:t.parameters};if(t.function&&typeof t.function=="object"){let e=t.function;if(typeof e.name=="string"){let r={};if(typeof e.arguments=="string")try{r=JSON.parse(e.arguments)}catch{r={}}else e.arguments&&typeof e.arguments=="object"&&(r=e.arguments);return{tool:e.name,args:r}}}return null}function Jh(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Gh(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim()),i=ft(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function Xh(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim());if(s.parameters||s.name){let i=ft(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function Yh(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;){let s=n[1],i=ia(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function ia(t){let e=[],r=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info"];for(let n of r){let s=new RegExp(`<<?${n}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${n}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",l={},u=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,d;for(;(d=u.exec(o))!==null;){let p=d[1].toLowerCase(),h=d[2]??d[3]??d[4];l[p]=Jh(h)}let f=a.trim();f&&(n==="write_file"||n==="append_to_file"?l.content=a:n==="run_command"?l.command=f:n==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),n==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:n,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function Zh(t){return ia(t)}function Qh(t){let e=[],r=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim()),i=ft(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function ep(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=sa(t,n.index);if(s)try{let i=JSON.parse(s),o=ft(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function tp(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=sa(t,n.index);if(s)try{let i=JSON.parse(s),o=ft(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function rp(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,n,s=!1;for(;(n=r.exec(t))!==null;){let i=n[1],o=/<function=([^>]+)>/i.exec(i);if(o){s=!0;let a=o[1].trim(),l={},u=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,d;for(;(d=u.exec(i))!==null;){let f=d[1].trim(),p=d[2].trim();p==="true"?p=!0:p==="false"?p=!1:!isNaN(Number(p))&&p!==""&&(p=Number(p)),l[f]=p}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:n[0]})}}if(!s&&/<function=([^>]+)>/i.test(t)){let i=/<function=([^>]+)>/i.exec(t);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=l.exec(t))!==null;){let d=u[1].trim(),f=u[2].trim();f==="true"?f=!0:f==="false"?f=!1:!isNaN(Number(f))&&f!==""&&(f=Number(f)),a[d]=f}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var On=[{format:"xml_tool_call_wrapper",parse:Yh},{format:"xml_prompt",parse:Zh},{format:"xml_tags",parse:Gh},{format:"xml_parameters",parse:rp},{format:"hermes",parse:Xh},{format:"markdown_json",parse:Qh},{format:"function_call",parse:ep},{format:"json_object",parse:tp}],Rn=class{registry;constructor(){this.registry=zh()}parse(e,r,n){if(r&&Array.isArray(r)&&r.length>0){let i=r.filter(o=>o?.function?.name&&typeof o.function.name=="string");if(i.length>0){let o=i.map(a=>({function:{name:a.function.name,arguments:a.function.arguments||{}}}));return n&&this.learnFormat(n,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let s=e||"";if(!s.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(n){let i=this.registry[n];if(i&&i.format!=="native"){let o=On.find(a=>a.format===i.format);if(o){let a=o.parse(s);if(a.length>0)return this.learnFormat(n,i.format),this.buildResult(a,s)}}}for(let{parse:i}of On){let o=i(s);if(o.length>0){let a=o[0].format;return n&&this.learnFormat(n,a),this.buildResult(o,s)}}return{toolCalls:[],displayContent:s.trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let r=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(r)||/<function=/i.test(r)||r.includes("```tool_call")||r.includes("```json")&&r.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info)[\s>]/i.test(r)||r.startsWith("{")&&(r.includes('"name"')||r.includes('"tool"'))&&(r.includes('"arguments"')||r.includes('"args"')||r.includes('"parameters"'))||r.includes('"function"')&&r.includes('"name"'))}detectFormat(e){for(let{format:r,parse:n}of On)if(n(e).length>0)return r;return"unknown"}learnFormat(e,r){let n=this.registry[e];n&&n.format===r?(n.successCount++,n.lastUsed=new Date().toISOString()):this.registry[e]={format:r,successCount:1,lastUsed:new Date().toISOString()},Kh(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[r,n]of Object.entries(this.registry))e[r]={format:n.format,successCount:n.successCount};return e}buildResult(e,r){let n=e.map(o=>({function:{name:o.tool,arguments:o.args}})),s=r,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)s=s.replace(o.rawMatch,"");return s=s.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),s=s.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),s=s.replace(/\n{3,}/g,`
231
-
232
- `),{toolCalls:n,displayContent:s.trim(),format:e[0]?.format??"unknown"}}},$n=null;function oa(){return $n||($n=new Rn),$n}var np=600,aa=2e3,la=2;function sp(t,e,r){let s=oa().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function ip(t,e){return t==="write_file"&&typeof e.path=="string"?`create ${e.path}`:(t==="edit_file"||t==="patch_file"||t==="search_and_replace")&&typeof e.path=="string"?`modify ${e.path}`:t==="read_file"&&typeof e.path=="string"?`read ${e.path}`:t==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function op(t){let e=(t||"").toLowerCase();return e.includes("eacces")||e.includes("permission")||e.includes("enospc")||e.includes("readonly")||e.includes("security")||e.includes("[write_file]")||e.includes("[delete_file]")||e.includes("[move_file]")||e.includes("[search_and_replace]")}async function ca(t,e,r,n){let s=0,i=Date.now();for(;s<=la;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=la)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:s};s++,n.info({tool:e,retry:s,error:o.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-i,retries:s}}async function ua(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:u,skipTools:d}=t,f=t.reactEngine??Ht(),p=t.errorRecovery??Wt(),h=d?[]:n.getOllamaTools(),c=r.getModel(),m=t.maxIterations??np,y=[],w=[],b=[],_="",S=0,v=!1;for(;S<m;){if(S++,u?.aborted)return{output:_,toolsUsed:he(y),toolResults:w,touchedFiles:he(b),iterations:S,success:!1,error:"Aborted",completedNaturally:v};let $=f.buildBudgetWarningPrompt();$&&s.addUserMessage($,{priority:"critical",tags:["system-budget"]});let T;try{T=await r.chatWithTools(s.getMessages(),h,u)}catch(N){let U=N;if(U.name==="AbortError"||u?.aborted)return{output:_,toolsUsed:he(y),toolResults:w,touchedFiles:he(b),iterations:S,success:!1,error:"Aborted",completedNaturally:v};if(S<=1){a.onNotice?.(`Transient model error: ${U.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(P=>setTimeout(P,1e3)),S--;continue}return a.onError?.(U.message??"Model request failed"),{output:_,toolsUsed:he(y),toolResults:w,touchedFiles:he(b),iterations:S,success:!1,error:U.message,completedNaturally:v}}let O=T.message?.content||"",C=T.message?.tool_calls,I=f.parseThinking(O);I.hasThinking&&(f.recordStep({thought:I.thinking}),o.debug({thinking:I.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:L,displayContent:F}=sp(C,O,c);if(F&&F.trim()&&(_=F,await a.onAssistantText?.(F,e)),L.length===0){s.addAssistantMessage(O,void 0,e.role),v=!0;break}s.addAssistantMessage(O,L,e.role);let q=L.length;for(let N=0;N<L.length;N++){let U=L[N];if(!U?.function?.name)continue;let P=U.function.name,B=U.function.arguments||{},er=n.getSafetyLevel(P)??"confirm";if(!n.get(P)){a.onNotice?.(`Unknown tool: ${P} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${P}". Available: ${n.getAll().map(Ee=>Ee.name).join(", ")}`);continue}if(await l(P,er,B)==="skip"){s.addToolMessage(`Tool ${P} was skipped by policy/user.`);break}y.push(P),typeof B.path=="string"&&b.push(B.path);let rr=ip(P,B);a.onToolStart?.(P,rr,B),a.onToolCall?.(),f.recordStep({thought:I.hasThinking?`Executing: ${P}`:"",action:P,actionInput:B});let H=await ca(n,P,B,o);a.onToolEnd?.(P,H.success,H.error||H.output,H.duration,B);let Ae;if(H.success)Ae=lt(H.output,aa),f.recordObservation(Ae.slice(0,300)),w.push({tool:P,success:!0,summary:H.output.slice(0,150)});else{let Ee=H.error||"Unknown error",Oe=p.analyze(P,Ee,B);if(Ae=p.buildRecoveryMessage(Oe,Ee),f.recordObservation(`FAILED: ${Ee}`,`Recovery: ${Oe.strategy} \u2014 ${Oe.suggestion}`),o.info({tool:P,errorClass:Oe.errorClass,strategy:Oe.strategy},"Error recovery analysis"),w.push({tool:P,success:!1,summary:Ee.slice(0,150)}),Oe.autoRetry&&!f.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let $e=await ca(n,P,B,o);a.onToolEnd?.(P,$e.success,$e.output,$e.duration,B),$e.success&&(Ae=lt($e.output,aa),f.recordObservation(Ae.slice(0,300),"Auto-retry succeeded"),w[w.length-1]={tool:P,success:!0,summary:$e.output.slice(0,150)})}}if(s.addToolMessage(Ae),H.success&&P==="read_file"&&typeof B.path=="string"&&i?.addFile(B.path,H.output),o.info({tool:P,success:H.success,durationMs:H.duration,retries:H.retries},"Tool executed"),!H.success&&op(H.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}q>1&&N<q-1}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return S>=m&&!v&&a.onNotice?.(`Reached max iterations (${m}). Stopping.`,"warn"),o.info({summary:f.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:_,toolsUsed:he(y),toolResults:w,touchedFiles:he(b),iterations:S,success:!0,completedNaturally:v}}function he(t){return[...new Set(t)]}function fa(t){return async(e,r)=>{let n=e.replace(/_/g," ");return!t.autoMode&&t.interactive?r==="confirm"&&t.confirm?await t.confirm(`Proceed with ${n}?`)?"allow":"skip":r==="dangerous"&&t.confirmDangerous?await t.confirmDangerous(`Dangerous: ${n}`)?"allow":"skip":"allow":!t.autoMode&&r==="dangerous"?"skip":"allow"}}async function da(t){let{client:e,session:r,abortSignal:n,onChunk:s}=t,i="",o=null;for(let a=0;a<2;a++)try{i="";for await(let l of e.streamChat(r.getMessages(),n))i+=l,s?.(l);return r.addAssistantMessage(i||""),i}catch(l){if(o=l,l?.name==="AbortError"||n?.aborted)throw l;if(a===1)break}throw o||new Error("Text turn failed")}var Jt=k(require("fs")),In=k(require("os")),Kt=k(require("path"));function ap(){let t=[Kt.resolve(__dirname,"..","package.json"),Kt.resolve(__dirname,"..","..","package.json"),Kt.resolve(process.cwd(),"package.json")];for(let e of t)try{if(Jt.existsSync(e)){let r=JSON.parse(Jt.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var ha=ap(),pa=process.stdout.isTTY===!0,lp=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb";function ve(t,e){return!pa||lp?t:`${e}${t}\x1B[0m`}var x={strong:t=>ve(t,"\x1B[1;37m"),muted:t=>ve(t,"\x1B[38;5;244m"),accent:t=>ve(t,"\x1B[38;5;81m"),info:t=>ve(t,"\x1B[38;5;110m"),success:t=>ve(t,"\x1B[38;5;108m"),warning:t=>ve(t,"\x1B[38;5;179m"),error:t=>ve(t,"\x1B[38;5;167m")};function ma(t,e){let r=e.replace(In.homedir(),"~"),n="\u2500".repeat(88);return["",x.muted(n),` ${x.strong("HABLAS")} ${x.muted("single-agent engineering runtime")}`,` ${x.muted("version")} ${x.accent(ha)} ${x.muted("model")} ${x.accent(t)}`,` ${x.muted("workspace")} ${x.muted(r)}`,x.muted(n),` ${x.muted("\u203A Type naturally to get started")}`,` ${x.muted("\u203A /help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")}`,""].join(`
233
- `)}function ga(t){return`
234
- ${x.muted("\u2500".repeat(28))} ${x.accent("Turn #"+t)} ${x.muted("\u2500".repeat(28))}`}function Gt(){return`
235
- ${x.accent("Hablas")} ${x.muted("\xB7 response")}`}function ya(){return["",` ${x.strong("Commands")}`,` ${x.muted("/help")} show help`,` ${x.muted("/status")} show current status`,` ${x.muted("/model")} show or switch the active model`,` ${x.muted("/models")} list available models`,` ${x.muted("/provider")} inspect or switch provider`,` ${x.muted("/history")} show recent turns`,` ${x.muted("/clear")} clear the session`,` ${x.muted("/workspace")} inspect the current workspace`,` ${x.muted("/doctor")} run diagnostics`,` ${x.muted("/version")} show version`,` ${x.muted("/about")} product identity`,` ${x.muted("/exit")} quit`,""].join(`
236
- `)}function wa(t){return["",` ${x.strong("Status")}`,` ${x.muted("provider")} ${x.info(t.provider)}`,` ${x.muted("model")} ${x.info(t.model)}`,` ${x.muted("workspace")} ${x.muted(t.workingDir.replace(In.homedir(),"~"))}`,` ${x.muted("connected")} ${t.connected?x.success("yes"):x.error("no")}`,` ${x.muted("messages")} ${x.info(String(t.messageCount))}`,t.totalTokens!==void 0?` ${x.muted("tokens")} ${x.info(String(t.totalTokens))}`:"",""].filter(Boolean).join(`
237
- `)}function G(t){return` ${x.info(t)}`}function ke(t){return` ${x.success("\u2713")} ${t}`}function le(t){return` ${x.warning("\u26A0")} ${t}`}function Ce(t){return` ${x.error("\u2717")} ${t}`}function ba(){return` ${x.strong("Hablas")} ${x.accent("v"+ha)}`}function Sa(){return` ${x.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime by Abdulmoin Hablas`}function _a(t,e){return` ${x.muted("tool")} ${x.accent(t)} ${x.muted("\xB7")} ${e}`}function xa(t,e,r){let n=t?x.success("\u2713"):x.error("\u2717"),s=e.replace(/\s+/g," ").trim().slice(0,140);return` ${n} ${s||(t?"done":"failed")} ${x.muted(`(${r}ms)`)}`}var Ge=class{constructor(e){this.label=e}frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;timer=null;start(){pa&&(this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${x.accent(this.frames[this.index])} ${x.muted(this.label)}`),this.index=(this.index+1)%this.frames.length},80)))}stop(e){this.timer&&(clearInterval(this.timer),this.timer=null,process.stdout.write("\r\x1B[K")),e&&console.log(G(e))}};async function Xt(t,e){let r=ta(t),n=await Ke(e.workingDir,e.config);if(e.session.updateSystemPrompt(Je(n,r.profile)),r.profile.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context and do not restart from zero.]",{priority:"critical",tags:["runtime-note","continuity"]}),r.profile.oneStepDelivery&&e.session.addUserMessage("[Execution note: complete as much as possible in one pass with no unnecessary follow-up questions.]",{priority:"critical",tags:["runtime-note","one-step"]}),e.session.addUserMessage(t,{priority:"high",tags:[`kind:${r.profile.kind}`]}),!r.profile.needsTools){let l=new Ge("Hablas is reasoning");l.start();let u=!1,d="";try{let f=await da({client:e.client,session:e.session,onChunk:p=>{u||(l.stop(),console.log(Gt()),process.stdout.write(" "),u=!0),process.stdout.write(p),d+=p}});u?process.stdout.write(`
238
- `):(l.stop(),console.log(Gt()),console.log(" "+f));return}catch(f){l.stop(),console.log(Ce(f?.message||"Text turn failed"));return}}let s=Ht({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=Wt(3),o={onAssistantText:async l=>{console.log(Gt()),console.log(" "+l)},onToolStart:(l,u)=>{console.log(_a(l,u))},onToolEnd:(l,u,d,f)=>{console.log(xa(u,d,f))},onNotice:(l,u)=>{console.log(u==="retry"?G(`Retrying: ${l}`):G(l))},onError:l=>{console.log(Ce(l))},onToolCall:()=>e.onToolCall?.()},a=fa({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?l=>e.input.confirm(l):void 0,confirmDangerous:e.input?l=>e.input.confirmDangerous(l):void 0});await ua({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:o,safetyPolicy:a,reactEngine:s,errorRecovery:i,skipTools:!1})}var Pn=k(require("fs")),va=k(require("path")),Q=k(require("os")),ka=require("child_process");async function Yt(t){let e=[],r=process.version,n=parseInt(r.slice(1).split(".")[0],10);e.push({name:"Node.js",status:n>=20?"ok":n>=18?"warn":"error",message:n>=20?`${r} (recommended)`:n>=18?`${r} (works, but 20+ recommended)`:`${r} (too old, need 20+)`});let s=va.join(Q.homedir(),".hablas");if(e.push({name:"Config directory",status:Pn.existsSync(s)?"ok":"warn",message:Pn.existsSync(s)?s:"Not created yet (will be created on first use)"}),t.provider==="ollama")try{let i=await fetch(`${t.ollamaHost}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let o=await i.json(),a=Array.isArray(o.models)?o.models.length:0;e.push({name:"Ollama",status:"ok",message:`Connected \u2014 ${a} models available`})}else e.push({name:"Ollama",status:"error",message:`HTTP ${i.status}`})}catch(i){let o=i instanceof Error?i.message:String(i);e.push({name:"Ollama",status:"error",message:o.includes("ECONNREFUSED")?"Not running \u2014 start with: ollama serve":`Connection failed: ${o}`})}else{let i=t.apiUrl||"unknown";try{let o=await fetch(`${i}/models`,{signal:AbortSignal.timeout(5e3),headers:{Authorization:"Bearer test"}});e.push({name:"API Provider",status:o.ok||o.status===401?"ok":"warn",message:`${i} \u2014 reachable`})}catch{e.push({name:"API Provider",status:"warn",message:`${i} \u2014 could not verify`})}}try{let i=Q.homedir();if(process.platform!=="win32"){let a=(0,ka.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",u=a[4]||"?";e.push({name:"Disk space",status:parseInt(u)>90?"warn":"ok",message:`${l} available (${u} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:t.model?"ok":"warn",message:t.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${Q.platform()} ${Q.arch()} \u2014 ${Q.cpus().length} cores, ${Math.round(Q.totalmem()/1024/1024/1024)}GB RAM`}),e}function Zt(t){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},r={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},n="\x1B[0m",s="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of t){let u=`${r[l.status]}${e[l.status]}${n}`,d=l.name.padEnd(18);i.push(` ${u} ${d}${s}${l.message}${n}`)}let o=t.filter(l=>l.status==="error").length,a=t.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${r.error}${o} error(s) found \u2014 fix these for hablas to work properly${n}`):a>0?i.push(` ${r.warn}${a} warning(s) \u2014 hablas should work but check the items above${n}`):i.push(` ${r.ok}All checks passed \u2014 hablas is ready!${n}`),i.push(""),i.join(`
239
- `)}async function Ca(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(ya());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Sa());return;case"/version":console.log(ba());return;case"/clear":e.session.clear(),console.log(ke("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(G("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l}: ${a.content.replace(/\s+/g," ").slice(0,160)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(wa({model:e.client.getModel(),provider:Le(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(G(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),Qe(e.config),console.log(ke(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=s.join(" ").toLowerCase(),a=o?i.filter(l=>l.toLowerCase().includes(o)):i;if(a.length===0){console.log(le("No matching models found."));return}console.log(""),a.slice(0,60).forEach((l,u)=>console.log(` ${String(u+1).padStart(2," ")}. ${l}`)),a.length>60&&console.log(` ... ${a.length-60} more`),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(G(`Provider: ${Le(e.config)}`)),console.log(G(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?ke("Connection OK"):Ce("Connection failed"));return}if(i==="ollama")e.config.provider="ollama",e.config.apiUrl="",e.config.apiKey="";else if(i==="nvidia")e.config.provider="nvidia",e.config.apiUrl=ne.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=ne.defaultModel);else if(i==="custom"){if(!s[1]){console.log(le("Usage: /provider custom <url> [api-key]"));return}e.config.provider="custom",e.config.apiUrl=s[1],s[2]&&(e.config.apiKey=s[2])}else{console.log(le("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=De(e.config);e.setClient(o),Qe(e.config),console.log(ke(`Provider switched to ${Le(e.config)}`));return}case"/doctor":{let i=await Yt({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Zt(i));return}case"/workspace":{console.log(""),console.log(qt(Ve(e.workingDir))),console.log("");return}default:console.log(le(`Unknown command: ${n}`))}}async function Ea(t,e){Yn();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=De(t),s=new Ue(r,t),i=new Be(t),o=await Ke(r,t),a=new We(Je(o,ut("hello")),t.historySize),l=new Ut;console.log(ma(t.model,r)),Ta.existsSync(Aa.join(r,".git"))||console.log(le("Not in a Git repository. Versioning and auto-sync features are limited."));let u=new Ge("Connecting");u.start();let d=await n.checkConnection();if(u.stop(d?"ready":"offline"),d){let y=await n.listModels();console.log(ke(`Connected \xB7 ${y.length} models available`))}else console.log(le(`Connection failed for ${Le(t)}. You can still inspect local files and switch provider with /provider.`));console.log(G("Hablas is ready. Single-agent runtime active.")),console.log("");let f=0,p=0,h=Date.now(),c=new AbortController,m=0;for(process.on("SIGINT",()=>{let y=Date.now();y-m<1500&&(console.log(""),console.log(G(`Session summary \xB7 turns=${f} \xB7 toolCalls=${p} \xB7 duration=${Math.round((Date.now()-h)/1e3)}s`)),l.close(),process.exit(0)),m=y,c.abort(),c=new AbortController,console.log(""),console.log(le("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let w=(await l.prompt(" \u203A ")).trim();if(w){if(w.startsWith("/")){if(await Ca(w,{config:t,client:n,setClient:_=>{n=_},session:a,workingDir:r})==="quit")break;continue}f+=1,console.log(ga(f)),c=new AbortController;try{await Xt(w,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{p+=1}})}catch(b){if(b?.name==="AbortError")continue;console.log(Ce(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}l.close()}async function Oa(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=De(e),i=new Ue(n,e),o=new Be(e),a=await Ke(n,e),l=new We(Je(a,ut(t)),e.historySize);await Xt(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1})}var Qt=k(require("fs")),Te=k(require("path")),cp=[{pattern:/(?:api[_-]?key|apikey)\s*[:=]\s*['"][a-zA-Z0-9_\-]{20,}['"]/gi,name:"API Key",severity:"critical"},{pattern:/(?:secret|password|passwd|pwd)\s*[:=]\s*['"][^'"]{8,}['"]/gi,name:"Secret/Password",severity:"critical"},{pattern:/(?:aws_access_key_id)\s*[:=]\s*['"]?AKIA[A-Z0-9]{16}['"]?/gi,name:"AWS Access Key",severity:"critical"},{pattern:/(?:aws_secret_access_key)\s*[:=]\s*['"]?[A-Za-z0-9/+=]{40}['"]?/gi,name:"AWS Secret Key",severity:"critical"},{pattern:/ghp_[A-Za-z0-9]{36}/g,name:"GitHub Token",severity:"critical"},{pattern:/gho_[A-Za-z0-9]{36}/g,name:"GitHub OAuth Token",severity:"critical"},{pattern:/sk-[A-Za-z0-9]{48}/g,name:"OpenAI API Key",severity:"critical"},{pattern:/xox[baprs]-[A-Za-z0-9\-]{10,}/g,name:"Slack Token",severity:"high"},{pattern:/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g,name:"Private Key",severity:"critical"},{pattern:/(?:mongodb(?:\+srv)?:\/\/)[^\s'"]+/g,name:"MongoDB Connection String",severity:"high"},{pattern:/(?:postgres|postgresql|mysql):\/\/[^\s'"]+/g,name:"Database URL",severity:"high"},{pattern:/(?:Bearer\s+)[A-Za-z0-9\-._~+/]+=*/g,name:"Bearer Token",severity:"medium"}],up=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),fp=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function dp(t,e){let r=[],n=e.split(`
240
- `);for(let{pattern:s,name:i,severity:o}of cp){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let u=e.substring(0,a.index).split(`
241
- `).length,d=n[u-1]||"";d.trim().startsWith("#")||d.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:u,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function hp(t,e){let r=[],n=e.split(`
242
- `),s=Te.extname(t);return[".ts",".js",".tsx",".jsx"].includes(s)&&n.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&r.push({severity:"medium",type:"code",file:t,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),r}function $a(t,e=[]){try{let r=Qt.readdirSync(t,{withFileTypes:!0});for(let n of r){if(up.has(n.name))continue;let s=Te.join(t,n.name);if(n.isDirectory())$a(s,e);else if(n.isFile()){let i=Te.extname(n.name);fp.has(i)||e.push(s)}}}catch{}return e}function Ra(t){let e=Date.now(),r=$a(t),n=[];for(let o of r)try{let a=Qt.readFileSync(o,"utf-8"),l=Te.relative(t,o),u=dp(l,a);n.push(...u);let d=hp(l,a);n.push(...d)}catch{}let s=Date.now()-e,i={critical:n.filter(o=>o.severity==="critical").length,high:n.filter(o=>o.severity==="high").length,medium:n.filter(o=>o.severity==="medium").length,low:n.filter(o=>o.severity==="low").length,info:n.filter(o=>o.severity==="info").length};return{issues:n,scannedFiles:r.length,duration:s,summary:i}}function Ia(t){let e=[];if(e.push(`
232
+ `)}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 yt(t){return new Mn(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}],Fn=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,f=l?"decompose_task":a.strategy;return o.lastStrategy=f,this.failures.set(e,o),{errorClass:a.errorClass,strategy:f,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(`
233
+ `)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let r=this.failures.get(e);return r?r.count<=1&&r.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function wt(t=3){return new Fn(t)}var fe=C(require("fs")),Qt=C(require("path")),da=C(require("os")),Zt=Qt.join(da.homedir(),".hablas","model-formats.json");function th(){try{if(fe.existsSync(Zt))return JSON.parse(fe.readFileSync(Zt,"utf-8"))}catch{}return{}}function rh(t){try{let e=Qt.dirname(Zt);fe.existsSync(e)||fe.mkdirSync(e,{recursive:!0}),fe.writeFileSync(Zt,JSON.stringify(t,null,2),"utf-8")}catch{}}function pa(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 bt(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 nh(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function sh(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=bt(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function ih(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=bt(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function oh(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"];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={},f=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,u;for(;(u=f.exec(o))!==null;){let h=u[1].toLowerCase(),p=u[2]??u[3]??u[4];l[h]=nh(p)}let d=a.trim();d&&(n==="write_file"||n==="append_to_file"?l.content=a:n==="run_command"?l.command=d: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 ah(t){return ha(t)}function lh(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=bt(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function ch(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=pa(t,n.index);if(s)try{let i=JSON.parse(s),o=bt(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function uh(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=pa(t,n.index);if(s)try{let i=JSON.parse(s),o=bt(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function fh(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={},f=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=f.exec(i))!==null;){let d=u[1].trim(),h=u[2].trim();h==="true"?h=!0:h==="false"?h=!1:!isNaN(Number(h))&&h!==""&&(h=Number(h)),l[d]=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,f;for(;(f=l.exec(t))!==null;){let u=f[1].trim(),d=f[2].trim();d==="true"?d=!0:d==="false"?d=!1:!isNaN(Number(d))&&d!==""&&(d=Number(d)),a[u]=d}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var Ln=[{format:"xml_tool_call_wrapper",parse:oh},{format:"xml_prompt",parse:ah},{format:"xml_tags",parse:sh},{format:"xml_parameters",parse:fh},{format:"hermes",parse:ih},{format:"markdown_json",parse:lh},{format:"function_call",parse:ch},{format:"json_object",parse:uh}],jn=class{registry;constructor(){this.registry=th()}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=Ln.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 Ln){let o=i(s);if(o.length>0){let a=o[0].format;return n&&this.learnFormat(n,a),this.buildResult(o,s)}}return{toolCalls:[],displayContent:s.trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let r=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(r)||/<function=/i.test(r)||r.includes("```tool_call")||r.includes("```json")&&r.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info)[\s>]/i.test(r)||r.startsWith("{")&&(r.includes('"name"')||r.includes('"tool"'))&&(r.includes('"arguments"')||r.includes('"args"')||r.includes('"parameters"'))||r.includes('"function"')&&r.includes('"name"'))}detectFormat(e){for(let{format:r,parse:n}of Ln)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=s.replace(/\n{3,}/g,`
234
+
235
+ `),{toolCalls:n,displayContent:s.trim(),format:e[0]?.format??"unknown"}}},Dn=null;function ma(){return Dn||(Dn=new jn),Dn}var dh=600,ga=2e3,ya=2;function ph(t,e,r){let s=ma().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function hh(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 mh(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 wa(t,e,r,n){let s=0,i=Date.now();for(;s<=ya;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=ya)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 Nn(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:f,skipTools:u}=t,d=t.reactEngine??yt(),h=t.errorRecovery??wt(),p=u?[]:n.getOllamaTools(),c=r.getModel(),m=t.maxIterations??dh,y=[],w=[],b=[],_="",S=0,k=!1;for(;S<m;){if(S++,f?.aborted)return{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!1,error:"Aborted",completedNaturally:k};let R=d.buildBudgetWarningPrompt();R&&s.addUserMessage(R,{priority:"critical",tags:["system-budget"]});let T;try{T=await r.chatWithTools(s.getMessages(),p,f)}catch(U){let W=U;if(W.name==="AbortError"||f?.aborted)return{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!1,error:"Aborted",completedNaturally:k};if(S<=1){a.onNotice?.(`Transient model error: ${W.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(F=>setTimeout(F,1e3)),S--;continue}return a.onError?.(W.message??"Model request failed"),{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!1,error:W.message,completedNaturally:k}}let O=T.message?.content||"",$=T.message?.tool_calls,P=d.parseThinking(O);P.hasThinking&&(d.recordStep({thought:P.thinking}),o.debug({thinking:P.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:N,displayContent:L}=ph($,O,c);if(L&&L.trim()&&(_=L,await a.onAssistantText?.(L,e)),N.length===0){s.addAssistantMessage(O,void 0,e.role),k=!0;break}s.addAssistantMessage(O,N,e.role);let H=N.length;for(let U=0;U<N.length;U++){let W=N[U];if(!W?.function?.name)continue;let F=W.function.name,V=W.function.arguments||{},ar=n.getSafetyLevel(F)??"confirm";if(!n.get(F)){a.onNotice?.(`Unknown tool: ${F} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${F}". Available: ${n.getAll().map(Pe=>Pe.name).join(", ")}`);continue}if(await l(F,ar,V)==="skip"){s.addToolMessage(`Tool ${F} was skipped by policy/user.`);break}y.push(F),typeof V.path=="string"&&b.push(V.path);let cr=hh(F,V);a.onToolStart?.(F,cr,V),a.onToolCall?.(),d.recordStep({thought:P.hasThinking?`Executing: ${F}`:"",action:F,actionInput:V});let z=await wa(n,F,V,o);a.onToolEnd?.(F,z.success,z.error||z.output,z.duration,V);let Ie;if(z.success)Ie=ht(z.output,ga),d.recordObservation(Ie.slice(0,300)),w.push({tool:F,success:!0,summary:z.output.slice(0,150)});else{let Pe=z.error||"Unknown error",Me=h.analyze(F,Pe,V);if(Ie=h.buildRecoveryMessage(Me,Pe),d.recordObservation(`FAILED: ${Pe}`,`Recovery: ${Me.strategy} \u2014 ${Me.suggestion}`),o.info({tool:F,errorClass:Me.errorClass,strategy:Me.strategy},"Error recovery analysis"),w.push({tool:F,success:!1,summary:Pe.slice(0,150)}),Me.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let Fe=await wa(n,F,V,o);a.onToolEnd?.(F,Fe.success,Fe.output,Fe.duration,V),Fe.success&&(Ie=ht(Fe.output,ga),d.recordObservation(Ie.slice(0,300),"Auto-retry succeeded"),w[w.length-1]={tool:F,success:!0,summary:Fe.output.slice(0,150)})}}if(s.addToolMessage(Ie),z.success&&F==="read_file"&&typeof V.path=="string"&&i?.addFile(V.path,z.output),o.info({tool:F,success:z.success,durationMs:z.duration,retries:z.retries},"Tool executed"),!z.success&&mh(z.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}H>1&&U<H-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return S>=m&&!k&&a.onNotice?.(`Reached max iterations (${m}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!0,completedNaturally:k}}function be(t){return[...new Set(t)]}function ba(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 Sa(t){let{client:e,session:r,abortSignal:n,onChunk:s}=t,i="",o=null;for(let a=0;a<2;a++)try{i="";for await(let l of e.streamChat(r.getMessages(),n))i+=l,s?.(l);return r.addAssistantMessage(i||""),i}catch(l){if(o=l,l?.name==="AbortError"||n?.aborted)throw l;if(a===1)break}throw o||new Error("Text turn failed")}var tr=C(require("fs")),qn=C(require("os")),er=C(require("path"));function gh(){let t=[er.resolve(__dirname,"..","package.json"),er.resolve(__dirname,"..","..","package.json"),er.resolve(process.cwd(),"package.json")];for(let e of t)try{if(tr.existsSync(e)){let r=JSON.parse(tr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var _a=gh(),xa=process.stdout.isTTY===!0,yh=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb";function Ee(t,e){return!xa||yh?t:`${e}${t}\x1B[0m`}var v={strong:t=>Ee(t,"\x1B[1;37m"),muted:t=>Ee(t,"\x1B[38;5;244m"),accent:t=>Ee(t,"\x1B[38;5;81m"),info:t=>Ee(t,"\x1B[38;5;110m"),success:t=>Ee(t,"\x1B[38;5;108m"),warning:t=>Ee(t,"\x1B[38;5;179m"),error:t=>Ee(t,"\x1B[38;5;167m")};function va(t,e){let r=e.replace(qn.homedir(),"~"),n="\u2500".repeat(88);return["",v.muted(n),` ${v.strong("HABLAS")} ${v.muted("single-agent engineering runtime")}`,` ${v.muted("version")} ${v.accent(_a)} ${v.muted("model")} ${v.accent(t)}`,` ${v.muted("workspace")} ${v.muted(r)}`,v.muted(n),` ${v.muted("\u203A Type naturally to get started")}`,` ${v.muted("\u203A /help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")}`,""].join(`
236
+ `)}function ka(t){return`
237
+ ${v.muted("\u2500".repeat(28))} ${v.accent("Turn #"+t)} ${v.muted("\u2500".repeat(28))}`}function rt(){return`
238
+ ${v.accent("Hablas")} ${v.muted("\xB7 response")}`}function Ca(){return["",` ${v.strong("Commands")}`,` ${v.muted("/help")} show help`,` ${v.muted("/status")} show current status`,` ${v.muted("/model")} show or switch the active model`,` ${v.muted("/models")} list available models`,` ${v.muted("/provider")} inspect or switch provider`,` ${v.muted("/history")} show recent turns`,` ${v.muted("/clear")} clear the session`,` ${v.muted("/workspace")} inspect the current workspace`,` ${v.muted("/doctor")} run diagnostics`,` ${v.muted("/version")} show version`,` ${v.muted("/about")} product identity`,` ${v.muted("/exit")} quit`,""].join(`
239
+ `)}function $a(t){return["",` ${v.strong("Status")}`,` ${v.muted("provider")} ${v.info(t.provider)}`,` ${v.muted("model")} ${v.info(t.model)}`,` ${v.muted("workspace")} ${v.muted(t.workingDir.replace(qn.homedir(),"~"))}`,` ${v.muted("connected")} ${t.connected?v.success("yes"):v.error("no")}`,` ${v.muted("messages")} ${v.info(String(t.messageCount))}`,t.totalTokens!==void 0?` ${v.muted("tokens")} ${v.info(String(t.totalTokens))}`:"",""].filter(Boolean).join(`
240
+ `)}function Q(t){return` ${v.info(t)}`}function Oe(t){return` ${v.success("\u2713")} ${t}`}function de(t){return` ${v.warning("\u26A0")} ${t}`}function Se(t){return` ${v.error("\u2717")} ${t}`}function Ta(){return` ${v.strong("Hablas")} ${v.accent("v"+_a)}`}function Aa(){return` ${v.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime by Abdulmoin Hablas`}function Ea(t,e){return` ${v.muted("tool")} ${v.accent(t)} ${v.muted("\xB7")} ${e}`}function Oa(t,e,r){let n=t?v.success("\u2713"):v.error("\u2717"),s=e.replace(/\s+/g," ").trim().slice(0,140);return` ${n} ${s||(t?"done":"failed")} ${v.muted(`(${r}ms)`)}`}var tt=class{constructor(e){this.label=e}frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;timer=null;start(){xa&&(this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${v.accent(this.frames[this.index])} ${v.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(Q(e))}};async function rr(t,e){let r=ua(t),n=await Qe(e.workingDir,e.config);if(e.session.updateSystemPrompt(et(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 u=new tt("Hablas is reasoning");u.start();let d=!1,h="";try{let p=await Sa({client:e.client,session:e.session,onChunk:c=>{d||(u.stop(),console.log(rt()),process.stdout.write(" "),d=!0),process.stdout.write(c),h+=c}});d?process.stdout.write(`
241
+ `):(u.stop(),console.log(rt()),console.log(" "+p));return}catch(p){u.stop(),console.log(Se(p?.message||"Text turn failed"));return}}let s=yt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=wt(3),o=[],a={onAssistantText:async u=>{o.push(u),r.profile.kind!=="implementation"&&(console.log(rt()),console.log(" "+u))},onToolStart:(u,d)=>{console.log(Ea(u,d))},onToolEnd:(u,d,h,p)=>{console.log(Oa(d,h,p))},onNotice:(u,d)=>{console.log(d==="retry"?Q(`Retrying: ${u}`):Q(u))},onError:u=>{console.log(Se(u))},onToolCall:()=>e.onToolCall?.()},l=ba({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?u=>e.input.confirm(u):void 0,confirmDangerous:e.input?u=>e.input.confirmDangerous(u):void 0}),f=await Nn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:a,safetyPolicy:l,reactEngine:s,errorRecovery:i,skipTools:!1});if(r.profile.kind==="implementation"&&f.toolsUsed.length>0&&o.length>0&&(console.log(rt()),console.log(" "+o[o.length-1])),r.profile.kind==="implementation"&&f.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 u=[];(await Nn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...a,onAssistantText:async h=>{u.push(h)}},safetyPolicy:l,reactEngine:yt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:wt(3),skipTools:!1})).toolsUsed.length===0?console.log(Se("Implementation request failed to enter a real tool-execution path. Refusing to present inline-code-only output as a completed result.")):u.length>0&&(console.log(rt()),console.log(" "+u[u.length-1]))}}var Un=C(require("fs")),Ra=C(require("path")),ne=C(require("os")),Ia=require("child_process");async function nr(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=Ra.join(ne.homedir(),".hablas");if(e.push({name:"Config directory",status:Un.existsSync(s)?"ok":"warn",message:Un.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=ne.homedir();if(process.platform!=="win32"){let a=(0,Ia.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",f=a[4]||"?";e.push({name:"Disk space",status:parseInt(f)>90?"warn":"ok",message:`${l} available (${f} 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:`${ne.platform()} ${ne.arch()} \u2014 ${ne.cpus().length} cores, ${Math.round(ne.totalmem()/1024/1024/1024)}GB RAM`}),e}function sr(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 f=`${r[l.status]}${e[l.status]}${n}`,u=l.name.padEnd(18);i.push(` ${f} ${u}${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(`
242
+ `)}async function Pa(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Ca());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Aa());return;case"/version":console.log(Ta());return;case"/clear":e.session.clear(),console.log(Oe("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(Q("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($a({model:e.client.getModel(),provider:He(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(Q(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),je(e.config),console.log(Oe(`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(de("No matching models found."));return}console.log(""),a.slice(0,60).forEach((l,f)=>console.log(` ${String(f+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(Q(`Provider: ${He(e.config)}`)),console.log(Q(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Oe("Connection OK"):Se("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=se.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=se.defaultModel);else if(i==="custom"){if(!s[1]){console.log(de("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(de("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=Be(e.config);e.setClient(o),je(e.config),console.log(Oe(`Provider switched to ${He(e.config)}`));return}case"/doctor":{let i=await nr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(sr(i));return}case"/workspace":{console.log(""),console.log(Jt(Ye(e.workingDir))),console.log("");return}default:console.log(de(`Unknown command: ${n}`))}}async function La(t,e){is();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=Be(t),s=new Ke(r,t),i=new Ge(t),o=await Qe(r,t),a=new Xe(et(o,gt("hello")),t.historySize),l=new Xt;console.log(va(t.model,r)),Ma.existsSync(Fa.join(r,".git"))||console.log(de("Not in a Git repository. Versioning and auto-sync features are limited."));let f=new tt("Connecting");f.start();let u=await n.checkConnection();if(f.stop(u?"ready":"offline"),u){let y=await n.listModels();console.log(Oe(`Connected \xB7 ${y.length} models available`))}else console.log(de(`Connection failed for ${He(t)}. You can still inspect local files and switch provider with /provider.`));console.log(Q("Hablas is ready. Single-agent runtime active.")),console.log("");let d=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(Q(`Session summary \xB7 turns=${d} \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(de("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let w=(await l.prompt(" \u203A ")).trim();if(w){if(w.startsWith("/")){if(await Pa(w,{config:t,client:n,setClient:_=>{n=_},session:a,workingDir:r})==="quit")break;continue}d+=1,console.log(ka(d)),c=new AbortController;try{await rr(w,{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(Se(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}l.close()}async function Da(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=Be(e),i=new Ke(n,e),o=new Ge(e),a=await Qe(n,e),l=new Xe(et(a,gt(t)),e.historySize);await rr(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1})}var ir=C(require("fs")),Re=C(require("path")),wh=[{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"}],bh=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Sh=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function _h(t,e){let r=[],n=e.split(`
243
+ `);for(let{pattern:s,name:i,severity:o}of wh){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let f=e.substring(0,a.index).split(`
244
+ `).length,u=n[f-1]||"";u.trim().startsWith("#")||u.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:f,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function xh(t,e){let r=[],n=e.split(`
245
+ `),s=Re.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 ja(t,e=[]){try{let r=ir.readdirSync(t,{withFileTypes:!0});for(let n of r){if(bh.has(n.name))continue;let s=Re.join(t,n.name);if(n.isDirectory())ja(s,e);else if(n.isFile()){let i=Re.extname(n.name);Sh.has(i)||e.push(s)}}}catch{}return e}function Na(t){let e=Date.now(),r=ja(t),n=[];for(let o of r)try{let a=ir.readFileSync(o,"utf-8"),l=Re.relative(t,o),f=_h(l,a);n.push(...f);let u=xh(l,a);n.push(...u)}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 qa(t){let e=[];if(e.push(`
243
246
  Security Scan Complete`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Files scanned: ${t.scannedFiles}`),e.push(` Duration: ${t.duration}ms`),e.push(""),t.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${t.issues.length}`),e.push(` Critical: ${t.summary.critical}`),e.push(` High: ${t.summary.high}`),e.push(` Medium: ${t.summary.medium}`),e.push(` Low: ${t.summary.low}`),e.push("");let r=t.issues.sort((n,s)=>{let i={critical:0,high:1,medium:2,low:3,info:4};return i[n.severity]-i[s.severity]}).slice(0,10);for(let n of r){let s=n.severity==="critical"?"\u{1F534}":n.severity==="high"?"\u{1F7E0}":n.severity==="medium"?"\u{1F7E1}":"\u{1F535}";e.push(` ${s} [${n.severity.toUpperCase()}] ${n.message}`),e.push(` File: ${n.file}${n.line?`:${n.line}`:""}`),e.push(` Fix: ${n.suggestion}`),e.push("")}}return e.join(`
244
- `)}var Xe=k(require("fs")),Fn=k(require("path")),Fa=k(require("os")),pp=Fn.join(Fa.homedir(),".hablas"),Pa=Fn.join(pp,"analytics.json");function Ma(){try{if(Xe.existsSync(Pa))return JSON.parse(Xe.readFileSync(Pa,"utf-8"))}catch{}return mp()}function mp(){return{totalSessions:0,totalMessages:0,totalTokensUsed:0,totalToolCalls:0,totalFilesModified:0,totalLinesWritten:0,totalBugsFixed:0,totalCommits:0,agentUsage:{},commandUsage:{},dailyActivity:{},streak:0,longestStreak:0,firstUsed:new Date().toISOString(),lastUsed:new Date().toISOString()}}function Da(t){let e=[];e.push(`
247
+ `)}var nt=C(require("fs")),Bn=C(require("path")),Ba=C(require("os")),vh=Bn.join(Ba.homedir(),".hablas"),Ua=Bn.join(vh,"analytics.json");function Ha(){try{if(nt.existsSync(Ua))return JSON.parse(nt.readFileSync(Ua,"utf-8"))}catch{}return kh()}function kh(){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 Wa(t){let e=[];e.push(`
245
248
  \u{1F4CA} Developer Analytics`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Sessions: ${t.totalSessions}`),e.push(` Messages: ${t.totalMessages}`),e.push(` Tokens used: ${t.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${t.totalToolCalls}`),e.push(` Files modified: ${t.totalFilesModified}`),e.push(` Lines written: ${t.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${t.totalBugsFixed}`),e.push(` Commits: ${t.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${t.streak} days (best: ${t.longestStreak})`),e.push("");let r=Object.entries(t.agentUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(r.length>0){e.push(" Top Agents:");for(let[s,i]of r)e.push(` @${s}: ${i} uses`);e.push("")}let n=Object.entries(t.commandUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(n.length>0){e.push(" Top Commands:");for(let[s,i]of n)e.push(` ${s}: ${i} calls`)}return e.join(`
246
- `)}var La=k(require("readline"));function pe(t,e){return new Promise(r=>t.question(e,n=>r(n)))}async function ja(t){let e=La.createInterface({input:process.stdin,output:process.stdout,terminal:!0});console.log(""),console.log("Hablas setup"),console.log("1) Ollama (local)"),console.log("2) NVIDIA NIM"),console.log("3) Custom OpenAI-compatible API"),console.log("");let r=(await pe(e,"Choose provider [1-3]: ")).trim();if(r==="1"){let n=(await pe(e,`Ollama host [${t.ollamaHost}]: `)).trim(),s=(await pe(e,`Model [${t.model}]: `)).trim();t.provider="ollama",n&&(t.ollamaHost=n),s&&(t.model=s)}else if(r==="2"){let n=(await pe(e,"NVIDIA API key: ")).trim(),s=(await pe(e,`Model [${ne.defaultModel}]: `)).trim();t.provider="nvidia",t.apiUrl=ne.apiUrl,t.apiKey=n,t.model=s||ne.defaultModel}else if(r==="3"){let n=(await pe(e,"API base URL: ")).trim(),s=(await pe(e,"API key (optional): ")).trim(),i=(await pe(e,"Model ID: ")).trim();t.provider="custom",t.apiUrl=n,t.apiKey=s,i&&(t.model=i)}Qe(t),console.log(""),console.log("Setup complete."),console.log('Use `hablas` for interactive mode or `hablas run "..."` for one-shot execution.'),console.log(""),e.close()}var Na=co(),W=new Gn;W.name("hablas").description(`Hablas CLI v${Na} \u2014 single-agent engineering runtime for the terminal.`).version(Na).option("-m, --model <model>","Model to use").option("-p, --project <path>","Working directory").option("--host <url>","Ollama host URL").option("--provider <type>","LLM provider: ollama | custom | nvidia").option("--api-url <url>","Custom API base URL").option("--api-key <key>","API key for custom or nvidia provider").option("--auto","Auto mode \u2014 skip tool confirmations where allowed").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--setup","Run setup wizard");W.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=W.opts(),r=Ie({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(r.autoMode=!0),e.timeout&&(r.timeout=parseInt(e.timeout,10));let n=mn(r);await Oa(t,r,n)});W.command("doctor").description("Run system diagnostics").action(async()=>{let t=W.opts(),e=Ie({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await Yt({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(Zt(r))});W.command("info").description("Show workspace information").action(async()=>{let t=W.opts(),e=Ie({project:t.project});console.log(""),console.log(qt(Ve(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});W.command("security").description("Run a security scan on the current project").action(async()=>{let t=W.opts(),e=Ie({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(Ia(Ra(r)))});W.command("stats").description("Show local usage statistics").action(async()=>{console.log(Da(Ma()))});W.action(async()=>{let t=W.opts(),e=Ie({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey});if(t.auto&&(e.autoMode=!0),t.timeout&&(e.timeout=parseInt(t.timeout,10)),t.setup){await ja(e);return}let r=mn(e);await Ea(e,r)});W.parse();
249
+ `)}var Va=C(require("readline"));var K="\x1B[36m",or="\x1B[32m",pe="\x1B[33m",M="\x1B[2m",he="\x1B[1m",x="\x1B[0m",Ch="\x1B[35m";function B(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function $h(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var St={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function za(t){let e=Va.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${he}${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${x}`),console.log(`${he}${K} hablas \u2014 Setup Wizard${x}`),console.log(`${M} Configure your AI provider and model${x}`),console.log(`${he}${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${x}`),console.log(),console.log(`${he} Choose your setup:${x}`),console.log(),console.log(` ${Ch}${he}1${x}. ${he}Hablas Integrated Engine${x} ${or}(instant \u2014 no setup needed)${x}`),console.log(` ${M}Pre-configured cloud AI, ready to use immediately${x}`),console.log(),console.log(` ${K}${he}2${x}. ${he}Custom Provider${x} ${M}(bring your own API key)${x}`),console.log(` ${M}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${x}`),console.log(),(await B(e,` ${M}Your choice (1-2):${x} `)).trim()){case"1":{t.provider=St.provider,t.apiUrl=St.apiUrl,t.apiKey=$h(),t.model=St.model,je(t),console.log(),console.log(`${or} \u2713 Hablas Integrated Engine activated!${x}`),console.log(`${M} Model: ${St.model}${x}`),console.log(`${M} API: ${St.apiUrl}${x}`),console.log(`${M} No API key needed \u2014 everything is pre-configured.${x}`);break}case"2":{switch(console.log(),console.log(`${M} Select your provider:${x}`),console.log(` ${K}a${x}. Ollama (local, free, private)`),console.log(` ${K}b${x}. OpenAI API`),console.log(` ${K}c${x}. Groq (fast, free tier)`),console.log(` ${K}d${x}. OpenRouter (many models)`),console.log(` ${K}e${x}. Together AI`),console.log(` ${K}f${x}. DeepSeek`),console.log(` ${K}g${x}. Custom OpenAI-compatible API`),console.log(` ${K}h${x}. NVIDIA NIM (powerful cloud models)`),console.log(),(await B(e,` ${M}Your choice (a-h):${x} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await B(e,` ${M}Ollama host [http://localhost:11434]:${x} `)).trim(),i=(await B(e,` ${M}Model [qwen2.5-coder:7b]:${x} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await B(e,` ${M}OpenAI API Key (sk-...):${x} `)).trim(),i=(await B(e,` ${M}Model [gpt-4o]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${M}Groq API Key (gsk_...):${x} `)).trim(),i=(await B(e,` ${M}Model [llama-3.3-70b-versatile]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${M}OpenRouter API Key (sk-or-...):${x} `)).trim(),i=(await B(e,` ${M}Model [anthropic/claude-3.5-sonnet]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${M}Together API Key:${x} `)).trim(),i=(await B(e,` ${M}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${M}DeepSeek API Key:${x} `)).trim(),i=(await B(e,` ${M}Model [deepseek-chat]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${M}API base URL:${x} `)).trim(),i=(await B(e,` ${M}API key (optional):${x} `)).trim(),o=(await B(e,` ${M}Model ID:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 URL is required \u2014 cancelled${x}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await B(e,` ${M}NVIDIA API Key (nvapi-...):${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),console.log(`${M} Get your key at: https://build.nvidia.com/${x}`),e.close();return}console.log(),console.log(`${M} Available NVIDIA models:${x}`),se.models.forEach((a,l)=>{console.log(` ${K}${l+1}${x}. ${a}`)}),console.log();let i=(await B(e,` ${M}Model number [1]:${x} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=se.apiUrl,t.apiKey=s,t.model=se.models[o]||se.defaultModel;break}default:console.log(`${pe} \u26A0 Invalid choice${x}`),e.close();return}je(t),console.log(),console.log(`${or} \u2713 Custom provider configured successfully${x}`),console.log(`${M} Provider: ${t.provider}${x}`),console.log(`${M} Model: ${t.model}${x}`);break}default:console.log(`${pe} \u26A0 Invalid choice \u2014 please select 1 or 2${x}`),e.close();return}console.log(),console.log(`${he}${or} \u2713 Setup complete!${x}`),console.log(`${M} Use ${K}hablas${x}${M} for interactive mode or ${K}hablas run "..."${x}${M} for one-shot execution.${x}`),console.log(),e.close()}var Ka=wo(),G=new ns;G.name("hablas").description(`Hablas CLI v${Ka} \u2014 single-agent engineering runtime for the terminal.`).version(Ka).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");G.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=G.opts(),r=De({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=xn(r);await Da(t,r,n)});G.command("doctor").description("Run system diagnostics").action(async()=>{let t=G.opts(),e=De({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await nr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(sr(r))});G.command("info").description("Show workspace information").action(async()=>{let t=G.opts(),e=De({project:t.project});console.log(""),console.log(Jt(Ye(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});G.command("security").description("Run a security scan on the current project").action(async()=>{let t=G.opts(),e=De({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(qa(Na(r)))});G.command("stats").description("Show local usage statistics").action(async()=>{console.log(Wa(Ha()))});G.action(async()=>{let t=G.opts(),e=De({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 za(e);return}let r=xn(e);await La(e,r)});G.parse();