hablas-ai 2.2.5 → 2.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/CHANGELOG.md +20 -11
  2. package/dist/index.js +122 -105
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,135 +1,151 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var El=Object.create;var ls=Object.defineProperty;var Al=Object.getOwnPropertyDescriptor;var Ol=Object.getOwnPropertyNames;var Rl=Object.getPrototypeOf,Il=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ml=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ol(e))!Il.call(t,s)&&s!==r&&ls(t,s,{get:()=>e[s],enumerable:!(n=Al(e,s))||n.enumerable});return t};var k=(t,e,r)=>(r=t!=null?El(Rl(t)):{},Ml(e||!t||!t.__esModule?ls(r,"default",{value:t,enumerable:!0}):r,t));var dt=I(kr=>{var Mt=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}},vr=class extends Mt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};kr.CommanderError=Mt;kr.InvalidArgumentError=vr});var Pt=I(Tr=>{var{InvalidArgumentError:Pl}=dt(),$r=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 Pl(`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 Ll(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Tr.Argument=$r;Tr.humanReadableArgName=Ll});var Er=I(cs=>{var{humanReadableArgName:Dl}=Pt(),Cr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,i)=>s.name().localeCompare(i.name())),r}compareOptions(e,r){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?r.push(n):n.long&&!i?r.push(e.createOption(n.long,n.description)):n.short&&!s&&r.push(e.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>Dl(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(u,m){if(m){let g=`${u.padEnd(n+o)}${m}`;return r.wrap(g,s-i,n+o)}return u}function l(u){return u.join(`
2
+ "use strict";var Ol=Object.create;var fs=Object.defineProperty;var Rl=Object.getOwnPropertyDescriptor;var Il=Object.getOwnPropertyNames;var Ml=Object.getPrototypeOf,Pl=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ll=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Il(e))!Pl.call(t,s)&&s!==r&&fs(t,s,{get:()=>e[s],enumerable:!(n=Rl(e,s))||n.enumerable});return t};var A=(t,e,r)=>(r=t!=null?Ol(Ml(t)):{},Ll(e||!t||!t.__esModule?fs(r,"default",{value:t,enumerable:!0}):r,t));var pt=I(kr=>{var Mt=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}},vr=class extends Mt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};kr.CommanderError=Mt;kr.InvalidArgumentError=vr});var Pt=I(Tr=>{var{InvalidArgumentError:jl}=pt(),$r=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 jl(`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 Dl(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Tr.Argument=$r;Tr.humanReadableArgName=Dl});var Ar=I(ds=>{var{humanReadableArgName:Fl}=Pt(),Cr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,i)=>s.name().localeCompare(i.name())),r}compareOptions(e,r){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?r.push(n):n.long&&!i?r.push(e.createOption(n.long,n.description)):n.short&&!s&&r.push(e.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>Fl(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(u,m){if(m){let g=`${u.padEnd(n+o)}${m}`;return r.wrap(g,s-i,n+o)}return u}function l(u){return u.join(`
3
3
  `).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${r.commandUsage(e)}`,""],f=r.commandDescription(e);f.length>0&&(c=c.concat([r.wrap(f,s,0),""]));let d=r.visibleArguments(e).map(u=>a(r.argumentTerm(u),r.argumentDescription(u)));d.length>0&&(c=c.concat(["Arguments:",l(d),""]));let h=r.visibleOptions(e).map(u=>a(r.optionTerm(u),r.optionDescription(u)));if(h.length>0&&(c=c.concat(["Options:",l(h),""])),this.showGlobalOptions){let u=r.visibleGlobalOptions(e).map(m=>a(r.optionTerm(m),r.optionDescription(m)));u.length>0&&(c=c.concat(["Global Options:",l(u),""]))}let p=r.visibleCommands(e).map(u=>a(r.subcommandTerm(u),r.subcommandDescription(u)));return p.length>0&&(c=c.concat(["Commands:",l(p),""])),c.join(`
4
4
  `)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=r-n;if(a<s)return e;let l=e.slice(0,n),c=e.slice(n).replace(`\r
5
5
  `,`
6
6
  `),f=" ".repeat(n),h="\\s\u200B",p=new RegExp(`
7
7
  |.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),u=c.match(p)||[];return l+u.map((m,g)=>m===`
8
8
  `?"":(g>0?f:"")+m.trimEnd()).join(`
9
- `)}};cs.Help=Cr});var Ir=I(Rr=>{var{InvalidArgumentError:jl}=dt(),Ar=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=Nl(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 jl(`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 Fl(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Or=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 Fl(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Nl(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}}Rr.Option=Ar;Rr.DualOptions=Or});var fs=I(us=>{function Ul(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 ql(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=Ul(t,o),l=Math.max(t.length,o.length);(l-a)/l>i&&(a<s?(s=a,n=[o]):a===s&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),r&&(n=n.map(o=>`--${o}`)),n.length>1?`
9
+ `)}};ds.Help=Cr});var Ir=I(Rr=>{var{InvalidArgumentError:Nl}=pt(),Er=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=ql(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 Ul(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Or=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 Ul(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function ql(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}}Rr.Option=Er;Rr.DualOptions=Or});var hs=I(ps=>{function Bl(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 Hl(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=Bl(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]}?)`:""}us.suggestSimilar=ql});var gs=I(ms=>{var Bl=require("node:events").EventEmitter,Mr=require("node:child_process"),pe=require("node:path"),Pr=require("node:fs"),q=require("node:process"),{Argument:Hl,humanReadableArgName:Wl}=Pt(),{CommanderError:Lr}=dt(),{Help:Vl}=Er(),{Option:ds,DualOptions:zl}=Ir(),{suggestSimilar:ps}=fs(),Dr=class t extends Bl{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 Vl,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 Hl(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 Lr(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 ds(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 ds)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,c)=>{let f=a.exec(l);return f?f[0]:c},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(f,d){let h=pe.resolve(f,d);if(Pr.existsSync(h))return h;if(s.includes(pe.extname(d)))return;let p=s.find(u=>Pr.existsSync(`${h}${u}`));if(p)return`${h}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let f;try{f=Pr.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=pe.resolve(pe.dirname(f),a)}if(a){let f=i(a,o);if(!f&&!e._executableFile&&this._scriptPath){let d=pe.basename(this._scriptPath,pe.extname(this._scriptPath));d!==this._name&&(f=i(a,`${d}-${e._name}`))}o=f||o}n=s.includes(pe.extname(o));let l;q.platform!=="win32"?n?(r.unshift(o),r=hs(q.execArgv).concat(r),l=Mr.spawn(q.argv[0],r,{stdio:"inherit"})):l=Mr.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=hs(q.execArgv).concat(r),l=Mr.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 c=this._exitCallback;l.on("close",f=>{f=f??1,c?c(new Lr(f,"commander.executeSubCommandAsync","(close)")):q.exit(f)}),l.on("error",f=>{if(f.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
11
+ (Did you mean ${n[0]}?)`:""}ps.suggestSimilar=Hl});var bs=I(ws=>{var Wl=require("node:events").EventEmitter,Mr=require("node:child_process"),pe=require("node:path"),Pr=require("node:fs"),q=require("node:process"),{Argument:Vl,humanReadableArgName:zl}=Pt(),{CommanderError:Lr}=pt(),{Help:Kl}=Ar(),{Option:ms,DualOptions:Gl}=Ir(),{suggestSimilar:gs}=hs(),jr=class t extends Wl{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 Kl,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 Vl(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 Lr(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 ms(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 ms)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,c)=>{let f=a.exec(l);return f?f[0]:c},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(f,d){let h=pe.resolve(f,d);if(Pr.existsSync(h))return h;if(s.includes(pe.extname(d)))return;let p=s.find(u=>Pr.existsSync(`${h}${u}`));if(p)return`${h}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let f;try{f=Pr.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=pe.resolve(pe.dirname(f),a)}if(a){let f=i(a,o);if(!f&&!e._executableFile&&this._scriptPath){let d=pe.basename(this._scriptPath,pe.extname(this._scriptPath));d!==this._name&&(f=i(a,`${d}-${e._name}`))}o=f||o}n=s.includes(pe.extname(o));let l;q.platform!=="win32"?n?(r.unshift(o),r=ys(q.execArgv).concat(r),l=Mr.spawn(q.argv[0],r,{stdio:"inherit"})):l=Mr.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=ys(q.execArgv).concat(r),l=Mr.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 c=this._exitCallback;l.on("close",f=>{f=f??1,c?c(new Lr(f,"commander.executeSubCommandAsync","(close)")):q.exit(f)}),l.on("error",f=>{if(f.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
17
  - ${d}`;throw new Error(h)}else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)q.exit(1);else{let d=new Lr(1,"commander.executeSubCommandAsync","(error)");d.nestedError=f,c(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 c=this._findOption(l);if(c){if(c.required){let f=i.shift();f===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,f)}else if(c.optional){let f=null;i.length>0&&!o(i[0])&&(f=i.shift()),this.emit(`option:${c.name()}`,f)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),f=this._findOption(l.slice(0,c));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,l.slice(c+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 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 zl(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),c=this.options.find(d=>d.negate&&a===d.attributeName()),f=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:f||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=ps(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=ps(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=>Wl(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=pe.basename(e,pe.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(r&&(s=r(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let r=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.
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 Gl(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),c=this.options.find(d=>d.negate&&a===d.attributeName()),f=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:f||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=gs(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=gs(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=>zl(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=pe.basename(e,pe.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(r&&(s=r(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let r=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 hs(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})}ms.Command=Dr});var xs=I(Q=>{var{Argument:ys}=Pt(),{Command:jr}=gs(),{CommanderError:Kl,InvalidArgumentError:ws}=dt(),{Help:Gl}=Er(),{Option:bs}=Ir();Q.program=new jr;Q.createCommand=t=>new jr(t);Q.createOption=(t,e)=>new bs(t,e);Q.createArgument=(t,e)=>new ys(t,e);Q.Command=jr;Q.Option=bs;Q.Argument=ys;Q.Help=Gl;Q.CommanderError=Kl;Q.InvalidArgumentError=ws;Q.InvalidOptionArgumentError=ws});var Ur=I((eg,Cs)=>{"use strict";var ht=t=>t&&typeof t.message=="string",Nr=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return ht(r)?r:void 0}else return ht(e)?e:void 0},$s=(t,e)=>{if(!ht(t))return"";let r=t.stack||"";if(e.has(t))return r+`
23
+ `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ys(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})}ws.Command=jr});var vs=I(Q=>{var{Argument:Ss}=Pt(),{Command:Dr}=bs(),{CommanderError:Jl,InvalidArgumentError:xs}=pt(),{Help:Yl}=Ar(),{Option:_s}=Ir();Q.program=new Dr;Q.createCommand=t=>new Dr(t);Q.createOption=(t,e)=>new _s(t,e);Q.createArgument=(t,e)=>new Ss(t,e);Q.Command=Dr;Q.Option=_s;Q.Argument=Ss;Q.Help=Yl;Q.CommanderError=Jl;Q.InvalidArgumentError=xs;Q.InvalidOptionArgumentError=xs});var Ur=I((ig,Os)=>{"use strict";var ht=t=>t&&typeof t.message=="string",Nr=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return ht(r)?r:void 0}else return ht(e)?e:void 0},As=(t,e)=>{if(!ht(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
24
  causes have become circular...`;let n=Nr(t);return n?(e.add(t),r+`
25
- caused by: `+$s(n,e)):r},Jl=t=>$s(t,new Set),Ts=(t,e,r)=>{if(!ht(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=Nr(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+Ts(s,e,i)}else return n},Yl=t=>Ts(t,new Set);Cs.exports={isErrorLike:ht,getErrorCause:Nr,stackWithCauses:Jl,messageWithCauses:Yl}});var qr=I((tg,As)=>{"use strict";var Xl=Symbol("circular-ref-tag"),Lt=Symbol("pino-raw-err-ref"),Es=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[Lt]},set:function(t){this[Lt]=t}}});Object.defineProperty(Es,Lt,{writable:!0,value:{}});As.exports={pinoErrProto:Es,pinoErrorSymbols:{seen:Xl,rawSymbol:Lt}}});var Is=I((rg,Rs)=>{"use strict";Rs.exports=Hr;var{messageWithCauses:Zl,stackWithCauses:Ql,isErrorLike:Os}=Ur(),{pinoErrProto:ec,pinoErrorSymbols:tc}=qr(),{seen:Br}=tc,{toString:rc}=Object.prototype;function Hr(t){if(!Os(t))return t;t[Br]=void 0;let e=Object.create(ec);e.type=rc.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=Zl(t),e.stack=Ql(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Hr(r)));for(let r in t)if(e[r]===void 0){let n=t[r];Os(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Br)&&(e[r]=Hr(n)):e[r]=n}return delete t[Br],e.raw=t,e}});var Ps=I((ng,Ms)=>{"use strict";Ms.exports=jt;var{isErrorLike:Wr}=Ur(),{pinoErrProto:nc,pinoErrorSymbols:sc}=qr(),{seen:Dt}=sc,{toString:ic}=Object.prototype;function jt(t){if(!Wr(t))return t;t[Dt]=void 0;let e=Object.create(nc);e.type=ic.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=>jt(r))),Wr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,Dt)&&(e.cause=jt(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];Wr(n)?Object.prototype.hasOwnProperty.call(n,Dt)||(e[r]=jt(n)):e[r]=n}return delete t[Dt],e.raw=t,e}});var Fs=I((sg,js)=>{"use strict";js.exports={mapHttpRequest:oc,reqSerializer:Ds};var Vr=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[Vr]},set:function(t){this[Vr]=t}}});Object.defineProperty(Ls,Vr,{writable:!0,value:{}});function Ds(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 oc(t){return{req:Ds(t)}}});var Bs=I((ig,qs)=>{"use strict";qs.exports={mapHttpResponse:ac,resSerializer:Us};var zr=Symbol("pino-raw-res-ref"),Ns=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[zr]},set:function(t){this[zr]=t}}});Object.defineProperty(Ns,zr,{writable:!0,value:{}});function Us(t){let e=Object.create(Ns);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function ac(t){return{res:Us(t)}}});var Gr=I((og,Hs)=>{"use strict";var Kr=Is(),lc=Ps(),Ft=Fs(),Nt=Bs();Hs.exports={err:Kr,errWithCause:lc,mapHttpRequest:Ft.mapHttpRequest,mapHttpResponse:Nt.mapHttpResponse,req:Ft.reqSerializer,res:Nt.resSerializer,wrapErrorSerializer:function(e){return e===Kr?e:function(n){return e(Kr(n))}},wrapRequestSerializer:function(e){return e===Ft.reqSerializer?e:function(n){return e(Ft.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Nt.resSerializer?e:function(n){return e(Nt.resSerializer(n))}}}});var Jr=I((ag,Ws)=>{"use strict";function cc(t,e){return e}Ws.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=cc;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 Ys=I((lg,Js)=>{"use strict";function Yr(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]=Yr(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]=Yr(t[r]));return e}return t}function Vs(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 zs(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 Ks(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 Ut=Symbol("PATH_NOT_FOUND");function uc(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return Ut;r=r[n]}return r}function fc(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 dc(t,e,r,n=!1){for(let s of e){let i=Vs(s);if(i.includes("*"))Gs(t,i,r,s,n);else if(n)Ks(t,i);else{let o=uc(t,i);if(o===Ut)continue;let a=typeof r=="function"?r(o,i):r;zs(t,i,a)}}}function Gs(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 c=[...o,l.toString()],f=typeof r=="function"?r(a[l],c):r;a[l]=f}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],f=typeof r=="function"?r(a[l],c):r;a[l]=f}}else pc(t,e,r,i,n,s)}function pc(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function c(f,d){if(d===o.length){if(Array.isArray(f))for(let h=0;h<f.length;h++)l[d]=h.toString(),c(f[h],d+1);else if(typeof f=="object"&&f!==null)for(let h in f)l[d]=h,c(f[h],d+1)}else if(d<o.length){let h=o[d];f&&typeof f=="object"&&f!==null&&h in f&&(l[d]=h,c(f[h],d+1))}else if(a.includes("*"))Gs(f,a,typeof r=="function"?(p,u)=>{let m=[...l.slice(0,d),...u];return r(p,m)}:r,s,i);else if(i)Ks(f,a);else{let h=typeof r=="function"?r(fc(f,a),[...l.slice(0,d),...a]):r;zs(f,a,h)}}if(o.length===0)c(t,0);else{let f=t;for(let d=0;d<o.length;d++){let h=o[d];if(f==null||typeof f!="object"||f===null)return;f=f[h],l[d]=h}f!=null&&c(f,o.length)}}function hc(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=Vs(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 mc(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 c=l.toString();s.has(c)||s.has("*")?a[l]=r(n[l],s.get(c)||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 gc(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 yc(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)gc(e)}function wc(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;yc(e);let o=hc(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let c=mc(l,o),f=l,d=r;return typeof r=="function"&&(d=r),dc(c,e,d,i),n===!1?(c.restore=function(){return Yr(f)},c):typeof n=="function"?n(c):JSON.stringify(c)}}Js.exports=wc});var Ke=I((cg,Xs)=>{"use strict";var bc=Symbol("pino.setLevel"),xc=Symbol("pino.getLevel"),Sc=Symbol("pino.levelVal"),_c=Symbol("pino.levelComp"),vc=Symbol("pino.useLevelLabels"),kc=Symbol("pino.useOnlyCustomLevels"),$c=Symbol("pino.mixin"),Tc=Symbol("pino.lsCache"),Cc=Symbol("pino.chindings"),Ec=Symbol("pino.asJson"),Ac=Symbol("pino.write"),Oc=Symbol("pino.redactFmt"),Rc=Symbol("pino.time"),Ic=Symbol("pino.timeSliceIndex"),Mc=Symbol("pino.stream"),Pc=Symbol("pino.stringify"),Lc=Symbol("pino.stringifySafe"),Dc=Symbol("pino.stringifiers"),jc=Symbol("pino.end"),Fc=Symbol("pino.formatOpts"),Nc=Symbol("pino.messageKey"),Uc=Symbol("pino.errorKey"),qc=Symbol("pino.nestedKey"),Bc=Symbol("pino.nestedKeyStr"),Hc=Symbol("pino.mixinMergeStrategy"),Wc=Symbol("pino.msgPrefix"),Vc=Symbol("pino.wildcardFirst"),zc=Symbol.for("pino.serializers"),Kc=Symbol.for("pino.formatters"),Gc=Symbol.for("pino.hooks"),Jc=Symbol.for("pino.metadata");Xs.exports={setLevelSym:bc,getLevelSym:xc,levelValSym:Sc,levelCompSym:_c,useLevelLabelsSym:vc,mixinSym:$c,lsCacheSym:Tc,chindingsSym:Cc,asJsonSym:Ec,writeSym:Ac,serializersSym:zc,redactFmtSym:Oc,timeSym:Rc,timeSliceIndexSym:Ic,streamSym:Mc,stringifySym:Pc,stringifySafeSym:Lc,stringifiersSym:Dc,endSym:jc,formatOptsSym:Fc,messageKeySym:Nc,errorKeySym:Uc,nestedKeySym:qc,wildcardFirstSym:Vc,needsMetadataGsym:Jc,useOnlyCustomLevelsSym:kc,formattersSym:Kc,hooksSym:Gc,nestedKeyStrSym:Bc,mixinMergeStrategySym:Hc,msgPrefixSym:Wc}});var Zr=I((ug,ti)=>{"use strict";var Zs=Ys(),{redactFmtSym:Yc,wildcardFirstSym:qt}=Ke(),Xr=/[^.[\]]+|\[([^[\]]*?)\]/g,Qs="[Redacted]",ei=!1;function Xc(t,e){let{paths:r,censor:n,remove:s}=Zc(t),i=r.reduce((l,c)=>{Xr.lastIndex=0;let f=Xr.exec(c),d=Xr.exec(c),h=f[1]!==void 0?f[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):f[0];if(h==="*"&&(h=qt),d===null)return l[h]=null,l;if(l[h]===null)return l;let{index:p}=d,u=`${c.substr(p,c.length-1)}`;return l[h]=l[h]||[],h!==qt&&l[h].length===0&&l[h].push(...l[qt]||[]),h===qt&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(u)}),l[h].push(u),l},{}),o={[Yc]:Zs({paths:r,censor:n,serialize:e,strict:ei,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=f=>a(f,[c]);else{let f=typeof n=="function"?(d,h)=>n(d,[c,...h]):n;l[c]=Zs({paths:i[c],censor:f,serialize:e,strict:ei,remove:s})}return l},o)}function Zc(t){if(Array.isArray(t))return t={paths:t,censor:Qs},t;let{paths:e,censor:r=Qs,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}}ti.exports=Xc});var si=I((fg,ni)=>{"use strict";var Qc=()=>"",eu=()=>`,"time":${Date.now()}`,tu=()=>`,"time":${Math.round(Date.now()/1e3)}`,ru=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,nu=1000000n,ri=1000000000n,su=BigInt(Date.now())*nu,iu=process.hrtime.bigint(),ou=()=>{let t=process.hrtime.bigint()-iu,e=su+t,r=e/ri,n=e%ri,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"),c=i.getUTCHours().toString().padStart(2,"0"),f=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${f}:${d}.${n.toString().padStart(9,"0")}Z"`};ni.exports={nullTime:Qc,epochTime:eu,unixTime:tu,isoTime:ru,isoTimeNano:ou}});var oi=I((dg,ii)=>{"use strict";function au(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}ii.exports=lu;function lu(t,e,r){var n=r&&r.stringify||au,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 c="",f=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(f>=l||e[f]==null)break;d<p&&(c+=t.slice(d,p)),c+=Number(e[f]),d=p+2,p++;break;case 105:if(f>=l||e[f]==null)break;d<p&&(c+=t.slice(d,p)),c+=Math.floor(Number(e[f])),d=p+2,p++;break;case 79:case 111:case 106:if(f>=l||e[f]===void 0)break;d<p&&(c+=t.slice(d,p));var u=typeof e[f];if(u==="string"){c+="'"+e[f]+"'",d=p+2,p++;break}if(u==="function"){c+=e[f].name||"<anonymous>",d=p+2,p++;break}c+=n(e[f]),d=p+2,p++;break;case 115:if(f>=l)break;d<p&&(c+=t.slice(d,p)),c+=String(e[f]),d=p+2,p++;break;case 37:d<p&&(c+=t.slice(d,p)),c+="%",d=p+2,p++,f--;break}++f}++p}return d===-1?t:(d<h&&(c+=t.slice(d)),c)}});var en=I((pg,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 hi=I((hg,pi)=>{"use strict";var F=require("fs"),cu=require("events"),uu=require("util").inherits,ai=require("path"),rn=en(),fu=require("assert"),Bt=100,Ht=Buffer.allocUnsafe(0),du=16*1024,li="buffer",ci="utf8",[pu,hu]=(process.versions.node||"0.0").split(".").map(Number),mu=pu>=22&&hu>=7;function ui(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&&F.mkdirSync(ai.dirname(t),{recursive:!0});let i=F.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?F.mkdir(ai.dirname(t),{recursive:!0},i=>{if(i)return r(i);F.open(t,n,s,r)}):F.open(t,n,s,r)}function oe(t){if(!(this instanceof oe))return new oe(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:f,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||du,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=f||(()=>!0),this.mkdir=c||!1;let u,m;if(h===li)this._writingBuf=Ht,this.write=wu,this.flush=xu,this.flushSync=_u,this._actualWrite=ku,u=()=>F.writeSync(this.fd,this._writingBuf),m=()=>F.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===ci)this._writingBuf="",this.write=yu,this.flush=bu,this.flushSync=Su,this._actualWrite=vu,u=()=>Buffer.isBuffer(this._writingBuf)?F.writeSync(this.fd,this._writingBuf):F.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?F.write(this.fd,this._writingBuf,this.release):F.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${ci}" and "${li}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")ui(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=(g,x)=>{if(g){if((g.code==="EAGAIN"||g.code==="EBUSY")&&this.retryEAGAIN(g,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{rn(Bt),this.release(void 0,0)}catch(_){this.release(_)}else setTimeout(m,Bt);else this._writing=!1,this.emit("error",g);return}this.emit("write",x);let b=tn(this._writingBuf,this._len,x);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let _=u(),$=tn(this._writingBuf,this._len,_);this._len=$.len,this._writingBuf=$.writingBuf}while(this._writingBuf.length)}catch(_){this.release(_);return}}this._fsync&&F.fsyncSync(this.fd);let S=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):S>this.minLength?this._actualWrite():this._ending?S>0?this._actualWrite():(this._writing=!1,Wt(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(gu,this)):this.emit("drain"))},this.on("newListener",function(g){g==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function tn(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 gu(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}uu(oe,cu);function fi(t,e){return t.length===0?Ht:t.length===1?t[0]:Buffer.concat(t,e)}function yu(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 wu(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 di(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{F.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 bu(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&&di.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function xu(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&&di.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}oe.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&F.close(e,r=>{if(r)return this.emit("error",r)})}),ui(this.file,this)};oe.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():Wt(this)))};function Su(){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)?F.writeSync(this.fd,t):F.writeSync(this.fd,t,"utf8"),r=tn(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;rn(Bt)}}try{F.fsyncSync(this.fd)}catch{}}function _u(){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=Ht);let t=Ht;for(;this._bufs.length||t.length;){t.length<=0&&(t=fi(this._bufs[0],this._lens[0]));try{let e=F.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;rn(Bt)}}}oe.prototype.destroy=function(){this.destroyed||Wt(this)};function vu(){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)?F.writeSync(this.fd,this._writingBuf):F.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else F.write(this.fd,this._writingBuf,t)}function ku(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:fi(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=F.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else mu&&(this._writingBuf=Buffer.from(this._writingBuf)),F.write(this.fd,this._writingBuf,t)}function Wt(t){if(t.fd===-1){t.once("ready",Wt.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],fu(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{F.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?F.close(t.fd,r):r()}function r(n){if(n){t.emit("error",n);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}oe.SonicBoom=oe;oe.default=oe;pi.exports=oe});var nn=I((mg,bi)=>{"use strict";var ae={exit:[],beforeExit:[]},mi={exit:Cu,beforeExit:Eu},Ge;function $u(){Ge===void 0&&(Ge=new FinalizationRegistry(Au))}function Tu(t){ae[t].length>0||process.on(t,mi[t])}function gi(t){ae[t].length>0||(process.removeListener(t,mi[t]),ae.exit.length===0&&ae.beforeExit.length===0&&(Ge=void 0))}function Cu(){yi("exit")}function Eu(){yi("beforeExit")}function yi(t){for(let e of ae[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}ae[t]=[]}function Au(t){for(let e of["exit","beforeExit"]){let r=ae[e].indexOf(t);ae[e].splice(r,r+1),gi(e)}}function wi(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");Tu(t);let n=new WeakRef(e);n.fn=r,$u(),Ge.register(e,n),ae[t].push(n)}function Ou(t,e){wi("exit",t,e)}function Ru(t,e){wi("beforeExit",t,e)}function Iu(t){if(Ge!==void 0){Ge.unregister(t);for(let e of["exit","beforeExit"])ae[e]=ae[e].filter(r=>{let n=r.deref();return n&&n!==t}),gi(e)}}bi.exports={register:Ou,registerBeforeExit:Ru,unregister:Iu}});var xi=I((gg,Mu)=>{Mu.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 _i=I((yg,Si)=>{"use strict";function Pu(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())),c=Atomics.waitAsync(t,e,a,l);c.async?c.value.then(o):setImmediate(o)};o()}function Lu(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())),c=Atomics.waitAsync(t,e,r,l);c.async?c.value.then(f=>{if(f==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}Si.exports={wait:Pu,waitDiff:Lu}});var ki=I((wg,vi)=>{"use strict";vi.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Di=I((bg,Li)=>{"use strict";var{version:Du}=xi(),{EventEmitter:ju}=require("events"),{Worker:Fu}=require("worker_threads"),{join:Nu}=require("path"),{pathToFileURL:Uu}=require("url"),{wait:qu}=_i(),{WRITE_INDEX:he,READ_INDEX:Re,SEQ_INDEX:sn}=ki(),Bu=require("buffer"),Hu=require("assert"),y=Symbol("kImpl"),Wu=Bu.constants.MAX_STRING_LENGTH;function $i(){}function cn(t,e){Atomics.add(t[y].state,sn,1),e(),Atomics.add(t[y].state,sn,1),Atomics.notify(t[y].state,sn)}function Ti(t){cn(t,()=>{Atomics.store(t[y].state,Re,0),Atomics.store(t[y].state,he,0)})}var mt=class{constructor(e){this._value=e}deref(){return this._value}},Vt=class{register(){}unregister(){}},Vu=process.env.NODE_V8_COVERAGE?Vt:global.FinalizationRegistry||Vt,zu=process.env.NODE_V8_COVERAGE?mt:global.WeakRef||mt,Ci=new Vu(t=>{t.exited||t.terminate()});function Ku(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Nu(__dirname,"lib","worker.js"),o=new Fu(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Uu(r).href,dataBuf:t[y].dataBuf,stateBuf:t[y].stateBuf,workerData:{$context:{threadStreamVersion:Du},...n}}});return o.stream=new mt(t),o.on("message",Gu),o.on("exit",Oi),Ci.register(t,o),o}function Ei(t){Hu(!t[y].sync),t[y].needDrain&&(t[y].needDrain=!1,t.emit("drain"))}function Ai(t){for(;;){let e=Atomics.load(t[y].state,he),r=t[y].data.length-e;if(r>0){if(t[y].bufLen===0){t[y].flushing=!1,t[y].ending?un(t):t[y].needDrain&&process.nextTick(Ei,t);return}Mi(t,r,$i);continue}if(r===0){if(e===0&&t[y].bufLen===0)return;zt(t,()=>{t.destroyed||(Ti(t),Ai(t))});return}ee(t,new Error("overwritten"));return}}function Gu(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 zu(e),zt(e,()=>{e[y].ready=!0,e.emit("ready")});break;case"ERROR":ee(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"){ee(e,new Error("this should not happen: "+t.code));break}let r=e[y].flushCallbacks.get(t.id);r&&(e[y].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:ee(e,new Error("this should not happen: "+t.code))}}function Oi(t){let e=this.stream.deref();e!==void 0&&(Ci.unregister(e),e.worker.exited=!0,e.worker.off("exit",Oi),ee(e,t!==0?new Error("the worker thread exited"):null))}var an=class extends ju{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[y]={},this[y].stateBuf=new SharedArrayBuffer(128),this[y].state=new Int32Array(this[y].stateBuf),this[y].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[y].data=Buffer.from(this[y].dataBuf),this[y].sync=e.sync||!1,this[y].ending=!1,this[y].ended=!1,this[y].needDrain=!1,this[y].destroyed=!1,this[y].flushing=!1,this[y].ready=!1,this[y].finished=!1,this[y].errored=null,this[y].closed=!1,this[y].buf=[],this[y].bufHead=0,this[y].bufLen=0,this[y].flushCallbacks=new Map,this[y].nextFlushId=0,this.worker=Ku(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[y].destroyed)return ln(this,new Error("the worker has exited")),!1;if(this[y].ending)return ln(this,new Error("the worker is ending")),!1;if(this[y].flushing&&this[y].bufLen+r.length>=Wu)try{on(this),this[y].flushing=!0}catch(n){return ee(this,n),!1}if(this[y].buf.push(r),this[y].bufLen+=r.length,this[y].sync)try{return on(this),!0}catch(n){return ee(this,n),!1}return this[y].flushing||(this[y].flushing=!0,setImmediate(Ai,this)),this[y].needDrain=this[y].data.length-this[y].bufLen-Atomics.load(this[y].state,he)<=0,!this[y].needDrain}end(){this[y].destroyed||(this[y].ending=!0,un(this))}flush(e){e=typeof e=="function"?e:$i,Ri(this,r=>{if(r){process.nextTick(e,r);return}Ii(this,e)})}flushSync(){this[y].destroyed||(on(this),Pi(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[y].ready}get destroyed(){return this[y].destroyed}get closed(){return this[y].closed}get writable(){return!this[y].destroyed&&!this[y].ending}get writableEnded(){return this[y].ending}get writableFinished(){return this[y].finished}get writableNeedDrain(){return this[y].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[y].errored}};function Ri(t,e){if(t[y].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[y].sync&&(t[y].flushing||t[y].bufLen>0)){setImmediate(Ri,t,e);return}zt(t,e)}function zt(t,e){let r=Atomics.load(t[y].state,he);qu(t[y].state,Re,r,1/0,(n,s)=>{if(n){ee(t,n),e(n);return}if(s!=="ok"){zt(t,e);return}e()})}function Ii(t,e){if(t[y].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[y].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[y].nextFlushId;t[y].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[y].flushCallbacks.delete(r),ee(t,n),process.nextTick(e,n)}}function Ju(t,e){let r=t[y].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 ln(t,e){setImmediate(()=>{t.emit("error",e)})}function ee(t,e){t[y].destroyed||(t[y].destroyed=!0,Ju(t,e),e&&(t[y].errored=e,ln(t,e)),t.worker.exited?setImmediate(()=>{t[y].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[y].closed=!0,t.emit("close")}))}function Mi(t,e,r){let s=Atomics.load(t[y].state,he),i=e;for(;i>0&&t[y].bufLen!==0;){let o=t[y].bufHead,a=t[y].buf[o];if(a.length<=i){a.copy(t[y].data,s),s+=a.length,i-=a.length,t[y].bufLen-=a.length,t[y].bufHead=o+1,t[y].bufHead===t[y].buf.length?(t[y].buf.length=0,t[y].bufHead=0):t[y].bufHead>=1024&&t[y].bufHead*2>=t[y].buf.length&&(t[y].buf.splice(0,t[y].bufHead),t[y].bufHead=0);continue}a.copy(t[y].data,s,0,i),t[y].buf[o]=a.subarray(i),t[y].bufLen-=i,s+=i,i=0}return cn(t,()=>{Atomics.store(t[y].state,he,s)}),r(),!0}function un(t){if(!(t[y].ended||!t[y].ending||t[y].flushing)){t[y].ended=!0;try{t.flushSync();let e=Atomics.load(t[y].state,Re);cn(t,()=>{Atomics.store(t[y].state,he,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[y].state,Re,e,1e3),e=Atomics.load(t[y].state,Re),e===-2){ee(t,new Error("end() failed"));return}if(++r===10){ee(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[y].finished=!0,t.emit("finish")})}catch(e){ee(t,e)}}}function on(t){let e=()=>{t[y].ending?un(t):t[y].needDrain&&process.nextTick(Ei,t)};for(t[y].flushing=!1;t[y].bufLen!==0;){let r=Atomics.load(t[y].state,he),n=t[y].data.length-r;if(n===0){Pi(t),Ti(t);continue}else if(n<0)throw new Error("overwritten");Mi(t,n,e)}}function Pi(t){if(t[y].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[y].state,he),r=0;for(;;){let n=Atomics.load(t[y].state,Re);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[y].state,Re,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}Li.exports=an});var pn=I((xg,Ni)=>{"use strict";var{createRequire:Yu}=require("module"),{existsSync:Xu}=require("node:fs"),Zu=Jr(),{join:fn,isAbsolute:Fi,sep:Qu}=require("node:path"),{fileURLToPath:ef}=require("node:url"),tf=en(),dn=nn(),rf=Di();function nf(t){dn.register(t,cf),dn.registerBeforeExit(t,uf),t.on("close",function(){dn.unregister(t)})}function sf(){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 of(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&&ji(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(ji(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function ji(t){let e=af(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=ef(r)}catch{return!1}return Fi(r)&&!Xu(r)}function af(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function lf(t,e,r,n,s){if(!r.execArgv&&sf()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=of(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new rf({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&&nf(i)}function a(){i.closed||(i.flushSync(),tf(100),i.end())}return i}function cf(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function uf(t){t.flushSync()}function ff(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=Zu(),sync:a=!1}=t,l={...t.options},c=typeof o=="string"?[o]:o,f=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=f["pino-worker"]||fn(__dirname,"worker.js"),l.targets=r.filter(u=>u.target).map(u=>({...u,target:p(u.target)})),l.pipelines=r.filter(u=>u.pipeline).map(u=>u.pipeline.map(m=>({...m,level:u.level,target:p(m.target)})))):e&&(d=f["pino-worker"]||fn(__dirname,"worker.js"),l.pipelines=[e.map(u=>({...u,target:p(u.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let h=r||e?"pino.transport":d;return lf(p(d),l,i,a,h);function p(u){if(u=f[u]||u,Fi(u)||u.indexOf("file://")===0)return u;if(u==="pino/file")return fn(__dirname,"..","file.js");let m;for(let g of c)try{let x=g==="node:repl"?process.cwd()+Qu:g;m=Yu(x).resolve(u);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${u}"`);return m}}Ni.exports=ff});var Jt=I((Sg,Zi)=>{"use strict";var df=require("node:diagnostics_channel"),Ui=oi(),{mapHttpRequest:pf,mapHttpResponse:hf}=Gr(),mn=hi(),qi=nn(),{lsCacheSym:mf,chindingsSym:zi,writeSym:Bi,serializersSym:Ki,formatOptsSym:Hi,endSym:gf,stringifiersSym:Gi,stringifySym:Ji,stringifySafeSym:gn,wildcardFirstSym:Yi,nestedKeySym:yf,formattersSym:Xi,messageKeySym:wf,errorKeySym:bf,nestedKeyStrSym:xf,msgPrefixSym:Kt}=Ke(),{isMainThread:Sf}=require("worker_threads"),_f=pn(),[vf]=process.versions.node.split(".").map(t=>Number(t)),Wi=df.tracingChannel("pino_asJson"),hn=vf>=25?t=>JSON.stringify(t):$f;function Je(){}function kf(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=pf(n):typeof n.setHeader=="function"&&(n=hf(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Kt]=="string"&&i!==void 0&&i!==null&&(i=this[Kt]+i),this[Bi](n,Ui(i,o,this[Hi]),t)}else{let i=n===void 0?s.shift():n;typeof this[Kt]=="string"&&i!==void 0&&i!==null&&(i=this[Kt]+i),this[Bi](null,Ui(i,s,this[Hi]),t)}}}function $f(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 Tf(t,e,r,n){if(Wi.hasSubscribers===!1)return Vi.call(this,t,e,r,n);let s={instance:this,arguments};return Wi.traceSync(Vi,s,this,t,e,r,n)}function Vi(t,e,r,n){let s=this[Ji],i=this[gn],o=this[Gi],a=this[gf],l=this[zi],c=this[Ki],f=this[Xi],d=this[wf],h=this[bf],p=this[mf][r]+n;p=p+l;let u;f.log&&(t=f.log(t));let m=o[Yi],g="";for(let b in t)if(u=t[b],Object.prototype.hasOwnProperty.call(t,b)&&u!==void 0){c[b]?u=c[b](u):b===h&&c.err&&(u=c.err(u));let S=o[b]||m;switch(typeof u){case"undefined":case"function":continue;case"number":Number.isFinite(u)===!1&&(u=null);case"boolean":S&&(u=S(u));break;case"string":u=(S||hn)(u);break;default:u=(S||s)(u,i)}if(u===void 0)continue;let _=hn(b);g+=","+_+":"+u}let x="";if(e!==void 0){u=c[d]?c[d](e):e;let b=o[d]||m;switch(typeof u){case"function":break;case"number":Number.isFinite(u)===!1&&(u=null);case"boolean":b&&(u=b(u)),x=',"'+d+'":'+u;break;case"string":u=(b||hn)(u),x=',"'+d+'":'+u;break;default:u=(b||s)(u,i),x=',"'+d+'":'+u}}return this[yf]&&g?p+this[xf]+g.slice(1)+"}"+x+a:p+g+x+a}function Cf(t,e){let r,n=t[zi],s=t[Ji],i=t[gn],o=t[Gi],a=o[Yi],l=t[Ki],c=t[Xi].bindings;e=c(e);for(let f in e)if(r=e[f],((f.length<5||f!=="level"&&f!=="serializers"&&f!=="formatters"&&f!=="customLevels")&&e.hasOwnProperty(f)&&r!==void 0)===!0){if(r=l[f]?l[f](r):r,r=(o[f]||a||s)(r,i),r===void 0)continue;n+=',"'+f+'":'+r}return n}function Ef(t){return t.write!==t.constructor.prototype.write}function Gt(t){let e=new mn(t);return e.on("error",r),!t.sync&&Sf&&(qi.register(e,Af),e.on("close",function(){qi.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Je,e.end=Je,e.flushSync=Je,e.destroy=Je;return}e.removeListener("error",r),e.emit("error",n)}}function Af(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Of(t){return function(r,n,s={},i){if(typeof s=="string")i=Gt({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=Gt({dest:i})}else if(s instanceof mn||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof mn||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=_f({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=Je),i||(Ef(process.stdout)?i=process.stdout:i=Gt({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function Rf(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[gn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function If(t,e,r){return{level:t,bindings:e,log:r}}function Mf(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Zi.exports={noop:Je,buildSafeSonicBoom:Gt,asChindings:Cf,asJson:Tf,genLog:kf,createArgsNormalizer:Of,stringify:Rf,buildFormatters:If,normalizeDestFileDescriptor:Mf}});var Yt=I((_g,Qi)=>{var Pf={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Lf={ASC:"ASC",DESC:"DESC"};Qi.exports={DEFAULT_LEVELS:Pf,SORTING_ORDER:Lf}});var bn=I((vg,no)=>{"use strict";var{lsCacheSym:Df,levelValSym:yn,useOnlyCustomLevelsSym:jf,streamSym:Ff,formattersSym:Nf,hooksSym:Uf,levelCompSym:eo}=Ke(),{noop:qf,genLog:Ie}=Jt(),{DEFAULT_LEVELS:fe,SORTING_ORDER:to}=Yt(),ro={fatal:t=>{let e=Ie(fe.fatal,t);return function(...r){let n=this[Ff];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>Ie(fe.error,t),warn:t=>Ie(fe.warn,t),info:t=>Ie(fe.info,t),debug:t=>Ie(fe.debug,t),trace:t=>Ie(fe.trace,t)},wn=Object.keys(fe).reduce((t,e)=>(t[fe[e]]=e,t),{}),Bf=Object.keys(wn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Hf(t){let e=t[Nf].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[Df]=n,t}function Wf(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 Vf(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[yn],s=this[yn]=r[t],i=this[jf],o=this[eo],a=this[Uf].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=qf;continue}this[l]=Wf(l,i)?ro[l](a):Ie(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function zf(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Kf(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[eo](r,this[yn])}function Gf(t,e,r){return t===to.DESC?e<=r:e>=r}function Jf(t){return typeof t=="string"?Gf.bind(null,t):t}function Yf(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:wn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:fe,t);return{labels:n,values:s}}function Xf(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(wn).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:fe,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function Zf(t,e){let{labels:r,values:n}=t;for(let s in e){if(s in n)throw Error("levels cannot be overridden");if(e[s]in r)throw Error("pre-existing level values cannot be used for new levels")}}function Qf(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(to).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}no.exports={initialLsCache:Bf,genLsCache:Hf,levelMethods:ro,getLevel:zf,setLevel:Vf,isLevelEnabled:Kf,mappings:Yf,assertNoLevelCollisions:Zf,assertDefaultLevelFound:Xf,genLevelComparison:Jf,assertLevelComparison:Qf}});var xn=I((kg,so)=>{"use strict";so.exports={version:"10.3.1"}});var po=I((Tg,fo)=>{"use strict";var{EventEmitter:ed}=require("node:events"),{lsCacheSym:td,levelValSym:rd,setLevelSym:_n,getLevelSym:io,chindingsSym:Zt,mixinSym:nd,asJsonSym:ao,writeSym:sd,mixinMergeStrategySym:id,timeSym:od,timeSliceIndexSym:ad,streamSym:lo,serializersSym:Me,formattersSym:gt,errorKeySym:ld,messageKeySym:cd,useOnlyCustomLevelsSym:ud,needsMetadataGsym:fd,redactFmtSym:dd,stringifySym:pd,formatOptsSym:hd,stringifiersSym:md,msgPrefixSym:vn,hooksSym:gd}=Ke(),{getLevel:yd,setLevel:wd,isLevelEnabled:bd,mappings:xd,initialLsCache:Sd,genLsCache:_d,assertNoLevelCollisions:vd}=bn(),{asChindings:kn,asJson:kd,buildFormatters:Sn,stringify:oo,noop:co}=Jt(),{version:$d}=xn(),Td=Zr(),Cd=class{},uo={constructor:Cd,child:Ed,bindings:Ad,setBindings:Od,flush:Md,isLevelEnabled:bd,version:$d,get level(){return this[io]()},set level(t){this[_n](t)},get levelVal(){return this[rd]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[vn]},get[Symbol.toStringTag](){return"Pino"},[td]:Sd,[sd]:Id,[ao]:kd,[io]:yd,[_n]:wd};Object.setPrototypeOf(uo,ed.prototype);fo.exports=function(){return Object.create(uo)};var Xt=t=>t;function Ed(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[Me],n=this[gt],s=Object.create(this);if(e==null)return s[gt].bindings!==Xt&&(s[gt]=Sn(n.level,Xt,n.log)),s[Zt]=kn(s,t),this.onChild!==co&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[Me]=Object.create(null);for(let c in r)s[Me][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];s[Me][c]=r[c]}for(let c in e.serializers)s[Me][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];s[Me][c]=e.serializers[c]}}else s[Me]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;s[gt]=Sn(a||n.level,l||Xt,c||n.log)}else s[gt]=Sn(n.level,Xt,n.log);if(e.hasOwnProperty("customLevels")===!0&&(vd(this.levels,e.customLevels),s.levels=xd(e.customLevels,s[ud]),_d(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=Td(s.redact,oo),l={stringify:a[dd]};s[pd]=oo,s[md]=a,s[hd]=l}if(typeof e.msgPrefix=="string"&&(s[vn]=(this[vn]||"")+e.msgPrefix),s[Zt]=kn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[_n](a)}return this.onChild(s),s}function Ad(){let e=`{${this[Zt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Od(t){let e=kn(this,t);this[Zt]=e}function Rd(t,e){return Object.assign(e,t)}function Id(t,e,r){let n=this[od](),s=this[nd],i=this[ld],o=this[cd],a=this[id]||Rd,l,c=this[gd].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 f=this[ao](l,e,r,n),d=this[lo];d[fd]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[ad]),d.lastLogger=this),d.write(c?c(f):f)}function Md(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[lo];typeof e.flush=="function"?e.flush(t||co):t&&t()}});var yo=I((En,go)=>{"use strict";var{hasOwnProperty:yt}=Object.prototype,Le=Cn();Le.configure=Cn;Le.stringify=Le;Le.default=Le;En.stringify=Le;En.configure=Cn;go.exports=Le;var Pd=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function Se(t){return t.length<5e3&&!Pd.test(t)?`"${t}"`:JSON.stringify(t)}function $n(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 Ld=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Tn(t){return Ld.call(t)!==void 0&&t.length!==0}function ho(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 Dd(t){if(yt.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 jd(t){let e;if(yt.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 Fd(t,e){let r;if(yt.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 mo(t,e){let r;if(yt.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function Pe(t){return t===1?"1 item":`${t} items`}function Nd(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function Ud(t){if(yt.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function Cn(t){t={...t};let e=Ud(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Dd(t),n=Fd(t,"bigint"),s=jd(t),i=typeof s=="function"?s:void 0,o=mo(t,"maximumDepth"),a=mo(t,"maximumBreadth");function l(p,u,m,g,x,b){let S=u[p];switch(typeof S=="object"&&S!==null&&typeof S.toJSON=="function"&&(S=S.toJSON(p)),S=g.call(u,p,S),typeof S){case"string":return Se(S);case"object":{if(S===null)return"null";if(m.indexOf(S)!==-1)return r;let _="",$=",",E=b;if(Array.isArray(S)){if(S.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(S),x!==""&&(b+=x,_+=`
26
- ${b}`,$=`,
27
- ${b}`);let j=Math.min(S.length,a),B=0;for(;B<j-1;B++){let J=l(String(B),S,m,g,x,b);_+=J!==void 0?J:"null",_+=$}let W=l(String(B),S,m,g,x,b);if(_+=W!==void 0?W:"null",S.length-1>a){let J=S.length-a-1;_+=`${$}"... ${Pe(J)} not stringified"`}return x!==""&&(_+=`
28
- ${E}`),m.pop(),`[${_}]`}let C=Object.keys(S),R=C.length;if(R===0)return"{}";if(o<m.length+1)return'"[Object]"';let T="",L="";x!==""&&(b+=x,$=`,
29
- ${b}`,T=" ");let U=Math.min(R,a);s&&!Tn(S)&&(C=$n(C,i)),m.push(S);for(let j=0;j<U;j++){let B=C[j],W=l(B,S,m,g,x,b);W!==void 0&&(_+=`${L}${Se(B)}:${T}${W}`,L=$)}if(R>a){let j=R-a;_+=`${L}"...":${T}"${Pe(j)} not stringified"`,L=$}return x!==""&&L.length>1&&(_=`
25
+ caused by: `+As(n,e)):r},Xl=t=>As(t,new Set),Es=(t,e,r)=>{if(!ht(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=Nr(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+Es(s,e,i)}else return n},Zl=t=>Es(t,new Set);Os.exports={isErrorLike:ht,getErrorCause:Nr,stackWithCauses:Xl,messageWithCauses:Zl}});var qr=I((og,Is)=>{"use strict";var Ql=Symbol("circular-ref-tag"),Lt=Symbol("pino-raw-err-ref"),Rs=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[Lt]},set:function(t){this[Lt]=t}}});Object.defineProperty(Rs,Lt,{writable:!0,value:{}});Is.exports={pinoErrProto:Rs,pinoErrorSymbols:{seen:Ql,rawSymbol:Lt}}});var Ls=I((ag,Ps)=>{"use strict";Ps.exports=Hr;var{messageWithCauses:ec,stackWithCauses:tc,isErrorLike:Ms}=Ur(),{pinoErrProto:rc,pinoErrorSymbols:nc}=qr(),{seen:Br}=nc,{toString:sc}=Object.prototype;function Hr(t){if(!Ms(t))return t;t[Br]=void 0;let e=Object.create(rc);e.type=sc.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=ec(t),e.stack=tc(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Hr(r)));for(let r in t)if(e[r]===void 0){let n=t[r];Ms(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Br)&&(e[r]=Hr(n)):e[r]=n}return delete t[Br],e.raw=t,e}});var Ds=I((lg,js)=>{"use strict";js.exports=Dt;var{isErrorLike:Wr}=Ur(),{pinoErrProto:ic,pinoErrorSymbols:oc}=qr(),{seen:jt}=oc,{toString:ac}=Object.prototype;function Dt(t){if(!Wr(t))return t;t[jt]=void 0;let e=Object.create(ic);e.type=ac.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=t.message,e.stack=t.stack,Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Dt(r))),Wr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,jt)&&(e.cause=Dt(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];Wr(n)?Object.prototype.hasOwnProperty.call(n,jt)||(e[r]=Dt(n)):e[r]=n}return delete t[jt],e.raw=t,e}});var qs=I((cg,Us)=>{"use strict";Us.exports={mapHttpRequest:lc,reqSerializer:Ns};var Vr=Symbol("pino-raw-req-ref"),Fs=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[Vr]},set:function(t){this[Vr]=t}}});Object.defineProperty(Fs,Vr,{writable:!0,value:{}});function Ns(t){let e=t.info||t.socket,r=Object.create(Fs);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 lc(t){return{req:Ns(t)}}});var Vs=I((ug,Ws)=>{"use strict";Ws.exports={mapHttpResponse:cc,resSerializer:Hs};var zr=Symbol("pino-raw-res-ref"),Bs=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[zr]},set:function(t){this[zr]=t}}});Object.defineProperty(Bs,zr,{writable:!0,value:{}});function Hs(t){let e=Object.create(Bs);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function cc(t){return{res:Hs(t)}}});var Gr=I((fg,zs)=>{"use strict";var Kr=Ls(),uc=Ds(),Ft=qs(),Nt=Vs();zs.exports={err:Kr,errWithCause:uc,mapHttpRequest:Ft.mapHttpRequest,mapHttpResponse:Nt.mapHttpResponse,req:Ft.reqSerializer,res:Nt.resSerializer,wrapErrorSerializer:function(e){return e===Kr?e:function(n){return e(Kr(n))}},wrapRequestSerializer:function(e){return e===Ft.reqSerializer?e:function(n){return e(Ft.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Nt.resSerializer?e:function(n){return e(Nt.resSerializer(n))}}}});var Jr=I((dg,Ks)=>{"use strict";function fc(t,e){return e}Ks.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=fc;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 Qs=I((pg,Zs)=>{"use strict";function Yr(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]=Yr(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]=Yr(t[r]));return e}return t}function Gs(t){let e=[],r="",n=!1,s=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!n&&a==="."?r&&(e.push(r),r=""):a==="["?(r&&(e.push(r),r=""),n=!0):a==="]"&&n?(e.push(r),r="",n=!1,s=!1):(a==='"'||a==="'")&&n?s?a===i?(s=!1,i=""):r+=a:(s=!0,i=a):r+=a}return r&&e.push(r),e}function Js(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof n!="object"||n===null||!(o in n)||typeof n[o]!="object"||n[o]===null)return!1;n=n[o]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(n))for(let i=0;i<n.length;i++)n[i]=r;else if(typeof n=="object"&&n!==null)for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&(n[i]=r)}else typeof n=="object"&&n!==null&&s in n&&Object.prototype.hasOwnProperty.call(n,s)&&(n[s]=r);return!0}function Ys(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 Ut=Symbol("PATH_NOT_FOUND");function dc(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return Ut;r=r[n]}return r}function pc(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 hc(t,e,r,n=!1){for(let s of e){let i=Gs(s);if(i.includes("*"))Xs(t,i,r,s,n);else if(n)Ys(t,i);else{let o=dc(t,i);if(o===Ut)continue;let a=typeof r=="function"?r(o,i):r;Js(t,i,a)}}}function Xs(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 c=[...o,l.toString()],f=typeof r=="function"?r(a[l],c):r;a[l]=f}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],f=typeof r=="function"?r(a[l],c):r;a[l]=f}}else mc(t,e,r,i,n,s)}function mc(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function c(f,d){if(d===o.length){if(Array.isArray(f))for(let h=0;h<f.length;h++)l[d]=h.toString(),c(f[h],d+1);else if(typeof f=="object"&&f!==null)for(let h in f)l[d]=h,c(f[h],d+1)}else if(d<o.length){let h=o[d];f&&typeof f=="object"&&f!==null&&h in f&&(l[d]=h,c(f[h],d+1))}else if(a.includes("*"))Xs(f,a,typeof r=="function"?(p,u)=>{let m=[...l.slice(0,d),...u];return r(p,m)}:r,s,i);else if(i)Ys(f,a);else{let h=typeof r=="function"?r(pc(f,a),[...l.slice(0,d),...a]):r;Js(f,a,h)}}if(o.length===0)c(t,0);else{let f=t;for(let d=0;d<o.length;d++){let h=o[d];if(f==null||typeof f!="object"||f===null)return;f=f[h],l[d]=h}f!=null&&c(f,o.length)}}function gc(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=Gs(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 yc(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 c=l.toString();s.has(c)||s.has("*")?a[l]=r(n[l],s.get(c)||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 wc(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 bc(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)wc(e)}function Sc(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;bc(e);let o=gc(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let c=yc(l,o),f=l,d=r;return typeof r=="function"&&(d=r),hc(c,e,d,i),n===!1?(c.restore=function(){return Yr(f)},c):typeof n=="function"?n(c):JSON.stringify(c)}}Zs.exports=Sc});var Ge=I((hg,ei)=>{"use strict";var xc=Symbol("pino.setLevel"),_c=Symbol("pino.getLevel"),vc=Symbol("pino.levelVal"),kc=Symbol("pino.levelComp"),$c=Symbol("pino.useLevelLabels"),Tc=Symbol("pino.useOnlyCustomLevels"),Cc=Symbol("pino.mixin"),Ac=Symbol("pino.lsCache"),Ec=Symbol("pino.chindings"),Oc=Symbol("pino.asJson"),Rc=Symbol("pino.write"),Ic=Symbol("pino.redactFmt"),Mc=Symbol("pino.time"),Pc=Symbol("pino.timeSliceIndex"),Lc=Symbol("pino.stream"),jc=Symbol("pino.stringify"),Dc=Symbol("pino.stringifySafe"),Fc=Symbol("pino.stringifiers"),Nc=Symbol("pino.end"),Uc=Symbol("pino.formatOpts"),qc=Symbol("pino.messageKey"),Bc=Symbol("pino.errorKey"),Hc=Symbol("pino.nestedKey"),Wc=Symbol("pino.nestedKeyStr"),Vc=Symbol("pino.mixinMergeStrategy"),zc=Symbol("pino.msgPrefix"),Kc=Symbol("pino.wildcardFirst"),Gc=Symbol.for("pino.serializers"),Jc=Symbol.for("pino.formatters"),Yc=Symbol.for("pino.hooks"),Xc=Symbol.for("pino.metadata");ei.exports={setLevelSym:xc,getLevelSym:_c,levelValSym:vc,levelCompSym:kc,useLevelLabelsSym:$c,mixinSym:Cc,lsCacheSym:Ac,chindingsSym:Ec,asJsonSym:Oc,writeSym:Rc,serializersSym:Gc,redactFmtSym:Ic,timeSym:Mc,timeSliceIndexSym:Pc,streamSym:Lc,stringifySym:jc,stringifySafeSym:Dc,stringifiersSym:Fc,endSym:Nc,formatOptsSym:Uc,messageKeySym:qc,errorKeySym:Bc,nestedKeySym:Hc,wildcardFirstSym:Kc,needsMetadataGsym:Xc,useOnlyCustomLevelsSym:Tc,formattersSym:Jc,hooksSym:Yc,nestedKeyStrSym:Wc,mixinMergeStrategySym:Vc,msgPrefixSym:zc}});var Zr=I((mg,si)=>{"use strict";var ti=Qs(),{redactFmtSym:Zc,wildcardFirstSym:qt}=Ge(),Xr=/[^.[\]]+|\[([^[\]]*?)\]/g,ri="[Redacted]",ni=!1;function Qc(t,e){let{paths:r,censor:n,remove:s}=eu(t),i=r.reduce((l,c)=>{Xr.lastIndex=0;let f=Xr.exec(c),d=Xr.exec(c),h=f[1]!==void 0?f[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):f[0];if(h==="*"&&(h=qt),d===null)return l[h]=null,l;if(l[h]===null)return l;let{index:p}=d,u=`${c.substr(p,c.length-1)}`;return l[h]=l[h]||[],h!==qt&&l[h].length===0&&l[h].push(...l[qt]||[]),h===qt&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(u)}),l[h].push(u),l},{}),o={[Zc]:ti({paths:r,censor:n,serialize:e,strict:ni,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=f=>a(f,[c]);else{let f=typeof n=="function"?(d,h)=>n(d,[c,...h]):n;l[c]=ti({paths:i[c],censor:f,serialize:e,strict:ni,remove:s})}return l},o)}function eu(t){if(Array.isArray(t))return t={paths:t,censor:ri},t;let{paths:e,censor:r=ri,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}}si.exports=Qc});var ai=I((gg,oi)=>{"use strict";var tu=()=>"",ru=()=>`,"time":${Date.now()}`,nu=()=>`,"time":${Math.round(Date.now()/1e3)}`,su=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,iu=1000000n,ii=1000000000n,ou=BigInt(Date.now())*iu,au=process.hrtime.bigint(),lu=()=>{let t=process.hrtime.bigint()-au,e=ou+t,r=e/ii,n=e%ii,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"),c=i.getUTCHours().toString().padStart(2,"0"),f=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${f}:${d}.${n.toString().padStart(9,"0")}Z"`};oi.exports={nullTime:tu,epochTime:ru,unixTime:nu,isoTime:su,isoTimeNano:lu}});var ci=I((yg,li)=>{"use strict";function cu(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}li.exports=uu;function uu(t,e,r){var n=r&&r.stringify||cu,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 c="",f=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(f>=l||e[f]==null)break;d<p&&(c+=t.slice(d,p)),c+=Number(e[f]),d=p+2,p++;break;case 105:if(f>=l||e[f]==null)break;d<p&&(c+=t.slice(d,p)),c+=Math.floor(Number(e[f])),d=p+2,p++;break;case 79:case 111:case 106:if(f>=l||e[f]===void 0)break;d<p&&(c+=t.slice(d,p));var u=typeof e[f];if(u==="string"){c+="'"+e[f]+"'",d=p+2,p++;break}if(u==="function"){c+=e[f].name||"<anonymous>",d=p+2,p++;break}c+=n(e[f]),d=p+2,p++;break;case 115:if(f>=l)break;d<p&&(c+=t.slice(d,p)),c+=String(e[f]),d=p+2,p++;break;case 37:d<p&&(c+=t.slice(d,p)),c+="%",d=p+2,p++,f--;break}++f}++p}return d===-1?t:(d<h&&(c+=t.slice(d)),c)}});var en=I((wg,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 yi=I((bg,gi)=>{"use strict";var N=require("fs"),fu=require("events"),du=require("util").inherits,ui=require("path"),rn=en(),pu=require("assert"),Bt=100,Ht=Buffer.allocUnsafe(0),hu=16*1024,fi="buffer",di="utf8",[mu,gu]=(process.versions.node||"0.0").split(".").map(Number),yu=mu>=22&&gu>=7;function pi(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&&N.mkdirSync(ui.dirname(t),{recursive:!0});let i=N.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?N.mkdir(ui.dirname(t),{recursive:!0},i=>{if(i)return r(i);N.open(t,n,s,r)}):N.open(t,n,s,r)}function ae(t){if(!(this instanceof ae))return new ae(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:f,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||hu,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=f||(()=>!0),this.mkdir=c||!1;let u,m;if(h===fi)this._writingBuf=Ht,this.write=Su,this.flush=_u,this.flushSync=ku,this._actualWrite=Tu,u=()=>N.writeSync(this.fd,this._writingBuf),m=()=>N.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===di)this._writingBuf="",this.write=bu,this.flush=xu,this.flushSync=vu,this._actualWrite=$u,u=()=>Buffer.isBuffer(this._writingBuf)?N.writeSync(this.fd,this._writingBuf):N.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?N.write(this.fd,this._writingBuf,this.release):N.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${di}" and "${fi}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")pi(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=(g,x)=>{if(g){if((g.code==="EAGAIN"||g.code==="EBUSY")&&this.retryEAGAIN(g,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{rn(Bt),this.release(void 0,0)}catch(_){this.release(_)}else setTimeout(m,Bt);else this._writing=!1,this.emit("error",g);return}this.emit("write",x);let b=tn(this._writingBuf,this._len,x);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let _=u(),v=tn(this._writingBuf,this._len,_);this._len=v.len,this._writingBuf=v.writingBuf}while(this._writingBuf.length)}catch(_){this.release(_);return}}this._fsync&&N.fsyncSync(this.fd);let S=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):S>this.minLength?this._actualWrite():this._ending?S>0?this._actualWrite():(this._writing=!1,Wt(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(wu,this)):this.emit("drain"))},this.on("newListener",function(g){g==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function tn(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 wu(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}du(ae,fu);function hi(t,e){return t.length===0?Ht:t.length===1?t[0]:Buffer.concat(t,e)}function bu(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 Su(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 mi(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{N.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 xu(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&&mi.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function _u(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&&mi.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}ae.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&&N.close(e,r=>{if(r)return this.emit("error",r)})}),pi(this.file,this)};ae.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():Wt(this)))};function vu(){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)?N.writeSync(this.fd,t):N.writeSync(this.fd,t,"utf8"),r=tn(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;rn(Bt)}}try{N.fsyncSync(this.fd)}catch{}}function ku(){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=Ht);let t=Ht;for(;this._bufs.length||t.length;){t.length<=0&&(t=hi(this._bufs[0],this._lens[0]));try{let e=N.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;rn(Bt)}}}ae.prototype.destroy=function(){this.destroyed||Wt(this)};function $u(){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)?N.writeSync(this.fd,this._writingBuf):N.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else N.write(this.fd,this._writingBuf,t)}function Tu(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:hi(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=N.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else yu&&(this._writingBuf=Buffer.from(this._writingBuf)),N.write(this.fd,this._writingBuf,t)}function Wt(t){if(t.fd===-1){t.once("ready",Wt.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],pu(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{N.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?N.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")}}ae.SonicBoom=ae;ae.default=ae;gi.exports=ae});var nn=I((Sg,_i)=>{"use strict";var le={exit:[],beforeExit:[]},wi={exit:Eu,beforeExit:Ou},Je;function Cu(){Je===void 0&&(Je=new FinalizationRegistry(Ru))}function Au(t){le[t].length>0||process.on(t,wi[t])}function bi(t){le[t].length>0||(process.removeListener(t,wi[t]),le.exit.length===0&&le.beforeExit.length===0&&(Je=void 0))}function Eu(){Si("exit")}function Ou(){Si("beforeExit")}function Si(t){for(let e of le[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}le[t]=[]}function Ru(t){for(let e of["exit","beforeExit"]){let r=le[e].indexOf(t);le[e].splice(r,r+1),bi(e)}}function xi(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");Au(t);let n=new WeakRef(e);n.fn=r,Cu(),Je.register(e,n),le[t].push(n)}function Iu(t,e){xi("exit",t,e)}function Mu(t,e){xi("beforeExit",t,e)}function Pu(t){if(Je!==void 0){Je.unregister(t);for(let e of["exit","beforeExit"])le[e]=le[e].filter(r=>{let n=r.deref();return n&&n!==t}),bi(e)}}_i.exports={register:Iu,registerBeforeExit:Mu,unregister:Pu}});var vi=I((xg,Lu)=>{Lu.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 $i=I((_g,ki)=>{"use strict";function ju(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())),c=Atomics.waitAsync(t,e,a,l);c.async?c.value.then(o):setImmediate(o)};o()}function Du(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())),c=Atomics.waitAsync(t,e,r,l);c.async?c.value.then(f=>{if(f==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}ki.exports={wait:ju,waitDiff:Du}});var Ci=I((vg,Ti)=>{"use strict";Ti.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Ni=I((kg,Fi)=>{"use strict";var{version:Fu}=vi(),{EventEmitter:Nu}=require("events"),{Worker:Uu}=require("worker_threads"),{join:qu}=require("path"),{pathToFileURL:Bu}=require("url"),{wait:Hu}=$i(),{WRITE_INDEX:he,READ_INDEX:Re,SEQ_INDEX:sn}=Ci(),Wu=require("buffer"),Vu=require("assert"),y=Symbol("kImpl"),zu=Wu.constants.MAX_STRING_LENGTH;function Ai(){}function cn(t,e){Atomics.add(t[y].state,sn,1),e(),Atomics.add(t[y].state,sn,1),Atomics.notify(t[y].state,sn)}function Ei(t){cn(t,()=>{Atomics.store(t[y].state,Re,0),Atomics.store(t[y].state,he,0)})}var mt=class{constructor(e){this._value=e}deref(){return this._value}},Vt=class{register(){}unregister(){}},Ku=process.env.NODE_V8_COVERAGE?Vt:global.FinalizationRegistry||Vt,Gu=process.env.NODE_V8_COVERAGE?mt:global.WeakRef||mt,Oi=new Ku(t=>{t.exited||t.terminate()});function Ju(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||qu(__dirname,"lib","worker.js"),o=new Uu(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Bu(r).href,dataBuf:t[y].dataBuf,stateBuf:t[y].stateBuf,workerData:{$context:{threadStreamVersion:Fu},...n}}});return o.stream=new mt(t),o.on("message",Yu),o.on("exit",Mi),Oi.register(t,o),o}function Ri(t){Vu(!t[y].sync),t[y].needDrain&&(t[y].needDrain=!1,t.emit("drain"))}function Ii(t){for(;;){let e=Atomics.load(t[y].state,he),r=t[y].data.length-e;if(r>0){if(t[y].bufLen===0){t[y].flushing=!1,t[y].ending?un(t):t[y].needDrain&&process.nextTick(Ri,t);return}ji(t,r,Ai);continue}if(r===0){if(e===0&&t[y].bufLen===0)return;zt(t,()=>{t.destroyed||(Ei(t),Ii(t))});return}te(t,new Error("overwritten"));return}}function Yu(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 Gu(e),zt(e,()=>{e[y].ready=!0,e.emit("ready")});break;case"ERROR":te(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"){te(e,new Error("this should not happen: "+t.code));break}let r=e[y].flushCallbacks.get(t.id);r&&(e[y].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:te(e,new Error("this should not happen: "+t.code))}}function Mi(t){let e=this.stream.deref();e!==void 0&&(Oi.unregister(e),e.worker.exited=!0,e.worker.off("exit",Mi),te(e,t!==0?new Error("the worker thread exited"):null))}var an=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[y]={},this[y].stateBuf=new SharedArrayBuffer(128),this[y].state=new Int32Array(this[y].stateBuf),this[y].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[y].data=Buffer.from(this[y].dataBuf),this[y].sync=e.sync||!1,this[y].ending=!1,this[y].ended=!1,this[y].needDrain=!1,this[y].destroyed=!1,this[y].flushing=!1,this[y].ready=!1,this[y].finished=!1,this[y].errored=null,this[y].closed=!1,this[y].buf=[],this[y].bufHead=0,this[y].bufLen=0,this[y].flushCallbacks=new Map,this[y].nextFlushId=0,this.worker=Ju(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[y].destroyed)return ln(this,new Error("the worker has exited")),!1;if(this[y].ending)return ln(this,new Error("the worker is ending")),!1;if(this[y].flushing&&this[y].bufLen+r.length>=zu)try{on(this),this[y].flushing=!0}catch(n){return te(this,n),!1}if(this[y].buf.push(r),this[y].bufLen+=r.length,this[y].sync)try{return on(this),!0}catch(n){return te(this,n),!1}return this[y].flushing||(this[y].flushing=!0,setImmediate(Ii,this)),this[y].needDrain=this[y].data.length-this[y].bufLen-Atomics.load(this[y].state,he)<=0,!this[y].needDrain}end(){this[y].destroyed||(this[y].ending=!0,un(this))}flush(e){e=typeof e=="function"?e:Ai,Pi(this,r=>{if(r){process.nextTick(e,r);return}Li(this,e)})}flushSync(){this[y].destroyed||(on(this),Di(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[y].ready}get destroyed(){return this[y].destroyed}get closed(){return this[y].closed}get writable(){return!this[y].destroyed&&!this[y].ending}get writableEnded(){return this[y].ending}get writableFinished(){return this[y].finished}get writableNeedDrain(){return this[y].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[y].errored}};function Pi(t,e){if(t[y].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[y].sync&&(t[y].flushing||t[y].bufLen>0)){setImmediate(Pi,t,e);return}zt(t,e)}function zt(t,e){let r=Atomics.load(t[y].state,he);Hu(t[y].state,Re,r,1/0,(n,s)=>{if(n){te(t,n),e(n);return}if(s!=="ok"){zt(t,e);return}e()})}function Li(t,e){if(t[y].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[y].ready){let n=()=>{i(),Li(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[y].nextFlushId;t[y].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[y].flushCallbacks.delete(r),te(t,n),process.nextTick(e,n)}}function Xu(t,e){let r=t[y].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 ln(t,e){setImmediate(()=>{t.emit("error",e)})}function te(t,e){t[y].destroyed||(t[y].destroyed=!0,Xu(t,e),e&&(t[y].errored=e,ln(t,e)),t.worker.exited?setImmediate(()=>{t[y].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[y].closed=!0,t.emit("close")}))}function ji(t,e,r){let s=Atomics.load(t[y].state,he),i=e;for(;i>0&&t[y].bufLen!==0;){let o=t[y].bufHead,a=t[y].buf[o];if(a.length<=i){a.copy(t[y].data,s),s+=a.length,i-=a.length,t[y].bufLen-=a.length,t[y].bufHead=o+1,t[y].bufHead===t[y].buf.length?(t[y].buf.length=0,t[y].bufHead=0):t[y].bufHead>=1024&&t[y].bufHead*2>=t[y].buf.length&&(t[y].buf.splice(0,t[y].bufHead),t[y].bufHead=0);continue}a.copy(t[y].data,s,0,i),t[y].buf[o]=a.subarray(i),t[y].bufLen-=i,s+=i,i=0}return cn(t,()=>{Atomics.store(t[y].state,he,s)}),r(),!0}function un(t){if(!(t[y].ended||!t[y].ending||t[y].flushing)){t[y].ended=!0;try{t.flushSync();let e=Atomics.load(t[y].state,Re);cn(t,()=>{Atomics.store(t[y].state,he,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[y].state,Re,e,1e3),e=Atomics.load(t[y].state,Re),e===-2){te(t,new Error("end() failed"));return}if(++r===10){te(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[y].finished=!0,t.emit("finish")})}catch(e){te(t,e)}}}function on(t){let e=()=>{t[y].ending?un(t):t[y].needDrain&&process.nextTick(Ri,t)};for(t[y].flushing=!1;t[y].bufLen!==0;){let r=Atomics.load(t[y].state,he),n=t[y].data.length-r;if(n===0){Di(t),Ei(t);continue}else if(n<0)throw new Error("overwritten");ji(t,n,e)}}function Di(t){if(t[y].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[y].state,he),r=0;for(;;){let n=Atomics.load(t[y].state,Re);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[y].state,Re,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}Fi.exports=an});var pn=I(($g,Bi)=>{"use strict";var{createRequire:Zu}=require("module"),{existsSync:Qu}=require("node:fs"),ef=Jr(),{join:fn,isAbsolute:qi,sep:tf}=require("node:path"),{fileURLToPath:rf}=require("node:url"),nf=en(),dn=nn(),sf=Ni();function of(t){dn.register(t,ff),dn.registerBeforeExit(t,df),t.on("close",function(){dn.unregister(t)})}function af(){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 lf(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=cf(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=rf(r)}catch{return!1}return qi(r)&&!Qu(r)}function cf(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function uf(t,e,r,n,s){if(!r.execArgv&&af()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=lf(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new sf({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&&of(i)}function a(){i.closed||(i.flushSync(),nf(100),i.end())}return i}function ff(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function df(t){t.flushSync()}function pf(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=ef(),sync:a=!1}=t,l={...t.options},c=typeof o=="string"?[o]:o,f=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=f["pino-worker"]||fn(__dirname,"worker.js"),l.targets=r.filter(u=>u.target).map(u=>({...u,target:p(u.target)})),l.pipelines=r.filter(u=>u.pipeline).map(u=>u.pipeline.map(m=>({...m,level:u.level,target:p(m.target)})))):e&&(d=f["pino-worker"]||fn(__dirname,"worker.js"),l.pipelines=[e.map(u=>({...u,target:p(u.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let h=r||e?"pino.transport":d;return uf(p(d),l,i,a,h);function p(u){if(u=f[u]||u,qi(u)||u.indexOf("file://")===0)return u;if(u==="pino/file")return fn(__dirname,"..","file.js");let m;for(let g of c)try{let x=g==="node:repl"?process.cwd()+tf:g;m=Zu(x).resolve(u);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${u}"`);return m}}Bi.exports=pf});var Jt=I((Tg,to)=>{"use strict";var hf=require("node:diagnostics_channel"),Hi=ci(),{mapHttpRequest:mf,mapHttpResponse:gf}=Gr(),mn=yi(),Wi=nn(),{lsCacheSym:yf,chindingsSym:Ji,writeSym:Vi,serializersSym:Yi,formatOptsSym:zi,endSym:wf,stringifiersSym:Xi,stringifySym:Zi,stringifySafeSym:gn,wildcardFirstSym:Qi,nestedKeySym:bf,formattersSym:eo,messageKeySym:Sf,errorKeySym:xf,nestedKeyStrSym:_f,msgPrefixSym:Kt}=Ge(),{isMainThread:vf}=require("worker_threads"),kf=pn(),[$f]=process.versions.node.split(".").map(t=>Number(t)),Ki=hf.tracingChannel("pino_asJson"),hn=$f>=25?t=>JSON.stringify(t):Cf;function Ye(){}function Tf(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=mf(n):typeof n.setHeader=="function"&&(n=gf(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Kt]=="string"&&i!==void 0&&i!==null&&(i=this[Kt]+i),this[Vi](n,Hi(i,o,this[zi]),t)}else{let i=n===void 0?s.shift():n;typeof this[Kt]=="string"&&i!==void 0&&i!==null&&(i=this[Kt]+i),this[Vi](null,Hi(i,s,this[zi]),t)}}}function Cf(t){let e="",r=0,n=!1,s=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&s>=32;o++)s=t.charCodeAt(o),(s===34||s===92)&&(e+=t.slice(r,o)+"\\",r=o,n=!0);return n?e+=t.slice(r):e=t,s<32?JSON.stringify(t):'"'+e+'"'}function Af(t,e,r,n){if(Ki.hasSubscribers===!1)return Gi.call(this,t,e,r,n);let s={instance:this,arguments};return Ki.traceSync(Gi,s,this,t,e,r,n)}function Gi(t,e,r,n){let s=this[Zi],i=this[gn],o=this[Xi],a=this[wf],l=this[Ji],c=this[Yi],f=this[eo],d=this[Sf],h=this[xf],p=this[yf][r]+n;p=p+l;let u;f.log&&(t=f.log(t));let m=o[Qi],g="";for(let b in t)if(u=t[b],Object.prototype.hasOwnProperty.call(t,b)&&u!==void 0){c[b]?u=c[b](u):b===h&&c.err&&(u=c.err(u));let S=o[b]||m;switch(typeof u){case"undefined":case"function":continue;case"number":Number.isFinite(u)===!1&&(u=null);case"boolean":S&&(u=S(u));break;case"string":u=(S||hn)(u);break;default:u=(S||s)(u,i)}if(u===void 0)continue;let _=hn(b);g+=","+_+":"+u}let x="";if(e!==void 0){u=c[d]?c[d](e):e;let b=o[d]||m;switch(typeof u){case"function":break;case"number":Number.isFinite(u)===!1&&(u=null);case"boolean":b&&(u=b(u)),x=',"'+d+'":'+u;break;case"string":u=(b||hn)(u),x=',"'+d+'":'+u;break;default:u=(b||s)(u,i),x=',"'+d+'":'+u}}return this[bf]&&g?p+this[_f]+g.slice(1)+"}"+x+a:p+g+x+a}function Ef(t,e){let r,n=t[Ji],s=t[Zi],i=t[gn],o=t[Xi],a=o[Qi],l=t[Yi],c=t[eo].bindings;e=c(e);for(let f in e)if(r=e[f],((f.length<5||f!=="level"&&f!=="serializers"&&f!=="formatters"&&f!=="customLevels")&&e.hasOwnProperty(f)&&r!==void 0)===!0){if(r=l[f]?l[f](r):r,r=(o[f]||a||s)(r,i),r===void 0)continue;n+=',"'+f+'":'+r}return n}function Of(t){return t.write!==t.constructor.prototype.write}function Gt(t){let e=new mn(t);return e.on("error",r),!t.sync&&vf&&(Wi.register(e,Rf),e.on("close",function(){Wi.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Ye,e.end=Ye,e.flushSync=Ye,e.destroy=Ye;return}e.removeListener("error",r),e.emit("error",n)}}function Rf(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function If(t){return function(r,n,s={},i){if(typeof s=="string")i=Gt({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=Gt({dest:i})}else if(s instanceof mn||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof mn||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=kf({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=Ye),i||(Of(process.stdout)?i=process.stdout:i=Gt({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function Mf(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[gn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Pf(t,e,r){return{level:t,bindings:e,log:r}}function Lf(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}to.exports={noop:Ye,buildSafeSonicBoom:Gt,asChindings:Ef,asJson:Af,genLog:Tf,createArgsNormalizer:If,stringify:Mf,buildFormatters:Pf,normalizeDestFileDescriptor:Lf}});var Yt=I((Cg,ro)=>{var jf={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Df={ASC:"ASC",DESC:"DESC"};ro.exports={DEFAULT_LEVELS:jf,SORTING_ORDER:Df}});var bn=I((Ag,oo)=>{"use strict";var{lsCacheSym:Ff,levelValSym:yn,useOnlyCustomLevelsSym:Nf,streamSym:Uf,formattersSym:qf,hooksSym:Bf,levelCompSym:no}=Ge(),{noop:Hf,genLog:Ie}=Jt(),{DEFAULT_LEVELS:fe,SORTING_ORDER:so}=Yt(),io={fatal:t=>{let e=Ie(fe.fatal,t);return function(...r){let n=this[Uf];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>Ie(fe.error,t),warn:t=>Ie(fe.warn,t),info:t=>Ie(fe.info,t),debug:t=>Ie(fe.debug,t),trace:t=>Ie(fe.trace,t)},wn=Object.keys(fe).reduce((t,e)=>(t[fe[e]]=e,t),{}),Wf=Object.keys(wn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Vf(t){let e=t[qf].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[Ff]=n,t}function zf(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 Kf(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[yn],s=this[yn]=r[t],i=this[Nf],o=this[no],a=this[Bf].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=Hf;continue}this[l]=zf(l,i)?io[l](a):Ie(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function Gf(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Jf(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[no](r,this[yn])}function Yf(t,e,r){return t===so.DESC?e<=r:e>=r}function Xf(t){return typeof t=="string"?Yf.bind(null,t):t}function Zf(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:wn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:fe,t);return{labels:n,values:s}}function Qf(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(wn).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:fe,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function ed(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 td(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(so).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}oo.exports={initialLsCache:Wf,genLsCache:Vf,levelMethods:io,getLevel:Gf,setLevel:Kf,isLevelEnabled:Jf,mappings:Zf,assertNoLevelCollisions:ed,assertDefaultLevelFound:Qf,genLevelComparison:Xf,assertLevelComparison:td}});var Sn=I((Eg,ao)=>{"use strict";ao.exports={version:"10.3.1"}});var go=I((Rg,mo)=>{"use strict";var{EventEmitter:rd}=require("node:events"),{lsCacheSym:nd,levelValSym:sd,setLevelSym:_n,getLevelSym:lo,chindingsSym:Zt,mixinSym:id,asJsonSym:uo,writeSym:od,mixinMergeStrategySym:ad,timeSym:ld,timeSliceIndexSym:cd,streamSym:fo,serializersSym:Me,formattersSym:gt,errorKeySym:ud,messageKeySym:fd,useOnlyCustomLevelsSym:dd,needsMetadataGsym:pd,redactFmtSym:hd,stringifySym:md,formatOptsSym:gd,stringifiersSym:yd,msgPrefixSym:vn,hooksSym:wd}=Ge(),{getLevel:bd,setLevel:Sd,isLevelEnabled:xd,mappings:_d,initialLsCache:vd,genLsCache:kd,assertNoLevelCollisions:$d}=bn(),{asChindings:kn,asJson:Td,buildFormatters:xn,stringify:co,noop:po}=Jt(),{version:Cd}=Sn(),Ad=Zr(),Ed=class{},ho={constructor:Ed,child:Od,bindings:Rd,setBindings:Id,flush:Ld,isLevelEnabled:xd,version:Cd,get level(){return this[lo]()},set level(t){this[_n](t)},get levelVal(){return this[sd]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[vn]},get[Symbol.toStringTag](){return"Pino"},[nd]:vd,[od]:Pd,[uo]:Td,[lo]:bd,[_n]:Sd};Object.setPrototypeOf(ho,rd.prototype);mo.exports=function(){return Object.create(ho)};var Xt=t=>t;function Od(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[Me],n=this[gt],s=Object.create(this);if(e==null)return s[gt].bindings!==Xt&&(s[gt]=xn(n.level,Xt,n.log)),s[Zt]=kn(s,t),this.onChild!==po&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[Me]=Object.create(null);for(let c in r)s[Me][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];s[Me][c]=r[c]}for(let c in e.serializers)s[Me][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];s[Me][c]=e.serializers[c]}}else s[Me]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;s[gt]=xn(a||n.level,l||Xt,c||n.log)}else s[gt]=xn(n.level,Xt,n.log);if(e.hasOwnProperty("customLevels")===!0&&($d(this.levels,e.customLevels),s.levels=_d(e.customLevels,s[dd]),kd(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=Ad(s.redact,co),l={stringify:a[hd]};s[md]=co,s[yd]=a,s[gd]=l}if(typeof e.msgPrefix=="string"&&(s[vn]=(this[vn]||"")+e.msgPrefix),s[Zt]=kn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[_n](a)}return this.onChild(s),s}function Rd(){let e=`{${this[Zt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Id(t){let e=kn(this,t);this[Zt]=e}function Md(t,e){return Object.assign(e,t)}function Pd(t,e,r){let n=this[ld](),s=this[id],i=this[ud],o=this[fd],a=this[ad]||Md,l,c=this[wd].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 f=this[uo](l,e,r,n),d=this[fo];d[pd]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[cd]),d.lastLogger=this),d.write(c?c(f):f)}function Ld(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[fo];typeof e.flush=="function"?e.flush(t||po):t&&t()}});var So=I((An,bo)=>{"use strict";var{hasOwnProperty:yt}=Object.prototype,Le=Cn();Le.configure=Cn;Le.stringify=Le;Le.default=Le;An.stringify=Le;An.configure=Cn;bo.exports=Le;var jd=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function xe(t){return t.length<5e3&&!jd.test(t)?`"${t}"`:JSON.stringify(t)}function $n(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 Dd=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Tn(t){return Dd.call(t)!==void 0&&t.length!==0}function yo(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 Fd(t){if(yt.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(yt.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 Ud(t,e){let r;if(yt.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 wo(t,e){let r;if(yt.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function Pe(t){return t===1?"1 item":`${t} items`}function qd(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function Bd(t){if(yt.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function Cn(t){t={...t};let e=Bd(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Fd(t),n=Ud(t,"bigint"),s=Nd(t),i=typeof s=="function"?s:void 0,o=wo(t,"maximumDepth"),a=wo(t,"maximumBreadth");function l(p,u,m,g,x,b){let S=u[p];switch(typeof S=="object"&&S!==null&&typeof S.toJSON=="function"&&(S=S.toJSON(p)),S=g.call(u,p,S),typeof S){case"string":return xe(S);case"object":{if(S===null)return"null";if(m.indexOf(S)!==-1)return r;let _="",v=",",$=b;if(Array.isArray(S)){if(S.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(S),x!==""&&(b+=x,_+=`
26
+ ${b}`,v=`,
27
+ ${b}`);let D=Math.min(S.length,a),B=0;for(;B<D-1;B++){let J=l(String(B),S,m,g,x,b);_+=J!==void 0?J:"null",_+=v}let W=l(String(B),S,m,g,x,b);if(_+=W!==void 0?W:"null",S.length-1>a){let J=S.length-a-1;_+=`${v}"... ${Pe(J)} not stringified"`}return x!==""&&(_+=`
28
+ ${$}`),m.pop(),`[${_}]`}let C=Object.keys(S),E=C.length;if(E===0)return"{}";if(o<m.length+1)return'"[Object]"';let T="",M="";x!==""&&(b+=x,v=`,
29
+ ${b}`,T=" ");let j=Math.min(E,a);s&&!Tn(S)&&(C=$n(C,i)),m.push(S);for(let D=0;D<j;D++){let B=C[D],W=l(B,S,m,g,x,b);W!==void 0&&(_+=`${M}${xe(B)}:${T}${W}`,M=v)}if(E>a){let D=E-a;_+=`${M}"...":${T}"${Pe(D)} not stringified"`,M=v}return x!==""&&M.length>1&&(_=`
30
30
  ${b}${_}
31
- ${E}`),m.pop(),`{${_}}`}case"number":return isFinite(S)?String(S):e?e(S):"null";case"boolean":return S===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(S);default:return e?e(S):void 0}}function c(p,u,m,g,x,b){switch(typeof u=="object"&&u!==null&&typeof u.toJSON=="function"&&(u=u.toJSON(p)),typeof u){case"string":return Se(u);case"object":{if(u===null)return"null";if(m.indexOf(u)!==-1)return r;let S=b,_="",$=",";if(Array.isArray(u)){if(u.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(u),x!==""&&(b+=x,_+=`
32
- ${b}`,$=`,
33
- ${b}`);let R=Math.min(u.length,a),T=0;for(;T<R-1;T++){let U=c(String(T),u[T],m,g,x,b);_+=U!==void 0?U:"null",_+=$}let L=c(String(T),u[T],m,g,x,b);if(_+=L!==void 0?L:"null",u.length-1>a){let U=u.length-a-1;_+=`${$}"... ${Pe(U)} not stringified"`}return x!==""&&(_+=`
34
- ${S}`),m.pop(),`[${_}]`}m.push(u);let E="";x!==""&&(b+=x,$=`,
35
- ${b}`,E=" ");let C="";for(let R of g){let T=c(R,u[R],m,g,x,b);T!==void 0&&(_+=`${C}${Se(R)}:${E}${T}`,C=$)}return x!==""&&C.length>1&&(_=`
31
+ ${$}`),m.pop(),`{${_}}`}case"number":return isFinite(S)?String(S):e?e(S):"null";case"boolean":return S===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(S);default:return e?e(S):void 0}}function c(p,u,m,g,x,b){switch(typeof u=="object"&&u!==null&&typeof u.toJSON=="function"&&(u=u.toJSON(p)),typeof u){case"string":return xe(u);case"object":{if(u===null)return"null";if(m.indexOf(u)!==-1)return r;let S=b,_="",v=",";if(Array.isArray(u)){if(u.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(u),x!==""&&(b+=x,_+=`
32
+ ${b}`,v=`,
33
+ ${b}`);let E=Math.min(u.length,a),T=0;for(;T<E-1;T++){let j=c(String(T),u[T],m,g,x,b);_+=j!==void 0?j:"null",_+=v}let M=c(String(T),u[T],m,g,x,b);if(_+=M!==void 0?M:"null",u.length-1>a){let j=u.length-a-1;_+=`${v}"... ${Pe(j)} not stringified"`}return x!==""&&(_+=`
34
+ ${S}`),m.pop(),`[${_}]`}m.push(u);let $="";x!==""&&(b+=x,v=`,
35
+ ${b}`,$=" ");let C="";for(let E of g){let T=c(E,u[E],m,g,x,b);T!==void 0&&(_+=`${C}${xe(E)}:${$}${T}`,C=v)}return x!==""&&C.length>1&&(_=`
36
36
  ${b}${_}
37
- ${S}`),m.pop(),`{${_}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(u);default:return e?e(u):void 0}}function f(p,u,m,g,x){switch(typeof u){case"string":return Se(u);case"object":{if(u===null)return"null";if(typeof u.toJSON=="function"){if(u=u.toJSON(p),typeof u!="object")return f(p,u,m,g,x);if(u===null)return"null"}if(m.indexOf(u)!==-1)return r;let b=x;if(Array.isArray(u)){if(u.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(u),x+=g;let T=`
38
- ${x}`,L=`,
39
- ${x}`,U=Math.min(u.length,a),j=0;for(;j<U-1;j++){let W=f(String(j),u[j],m,g,x);T+=W!==void 0?W:"null",T+=L}let B=f(String(j),u[j],m,g,x);if(T+=B!==void 0?B:"null",u.length-1>a){let W=u.length-a-1;T+=`${L}"... ${Pe(W)} not stringified"`}return T+=`
40
- ${b}`,m.pop(),`[${T}]`}let S=Object.keys(u),_=S.length;if(_===0)return"{}";if(o<m.length+1)return'"[Object]"';x+=g;let $=`,
41
- ${x}`,E="",C="",R=Math.min(_,a);Tn(u)&&(E+=ho(u,$,a),S=S.slice(u.length),R-=u.length,C=$),s&&(S=$n(S,i)),m.push(u);for(let T=0;T<R;T++){let L=S[T],U=f(L,u[L],m,g,x);U!==void 0&&(E+=`${C}${Se(L)}: ${U}`,C=$)}if(_>a){let T=_-a;E+=`${C}"...": "${Pe(T)} not stringified"`,C=$}return C!==""&&(E=`
42
- ${x}${E}
43
- ${b}`),m.pop(),`{${E}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(u);default:return e?e(u):void 0}}function d(p,u,m){switch(typeof u){case"string":return Se(u);case"object":{if(u===null)return"null";if(typeof u.toJSON=="function"){if(u=u.toJSON(p),typeof u!="object")return d(p,u,m);if(u===null)return"null"}if(m.indexOf(u)!==-1)return r;let g="",x=u.length!==void 0;if(x&&Array.isArray(u)){if(u.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(u);let E=Math.min(u.length,a),C=0;for(;C<E-1;C++){let T=d(String(C),u[C],m);g+=T!==void 0?T:"null",g+=","}let R=d(String(C),u[C],m);if(g+=R!==void 0?R:"null",u.length-1>a){let T=u.length-a-1;g+=`,"... ${Pe(T)} not stringified"`}return m.pop(),`[${g}]`}let b=Object.keys(u),S=b.length;if(S===0)return"{}";if(o<m.length+1)return'"[Object]"';let _="",$=Math.min(S,a);x&&Tn(u)&&(g+=ho(u,",",a),b=b.slice(u.length),$-=u.length,_=","),s&&(b=$n(b,i)),m.push(u);for(let E=0;E<$;E++){let C=b[E],R=d(C,u[C],m);R!==void 0&&(g+=`${_}${Se(C)}:${R}`,_=",")}if(S>a){let E=S-a;g+=`${_}"...":"${Pe(E)} not stringified"`}return m.pop(),`{${g}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(u);default:return e?e(u):void 0}}function h(p,u,m){if(arguments.length>1){let g="";if(typeof m=="number"?g=" ".repeat(Math.min(m,10)):typeof m=="string"&&(g=m.slice(0,10)),u!=null){if(typeof u=="function")return l("",{"":p},[],u,g,"");if(Array.isArray(u))return c("",p,[],Nd(u),g,"")}if(g.length!==0)return f("",p,[],g,"")}return d("",p,[])}return h}});var So=I((Cg,xo)=>{"use strict";var An=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:bo}=Yt(),qd=bo.info;function Bd(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(bo);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:c,minLevel:0,lastId:0,streams:[],clone:f,[An]:!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:u}=this,m=0,g;for(let x=Hd(u.length,e.dedupe);Vd(x,u.length,e.dedupe);x=Wd(x,e.dedupe))if(h=u[x],h.level<=p){if(m!==0&&m!==h.level)break;if(g=h.stream,g[An]){let{lastTime:b,lastMsg:S,lastObj:_,lastLogger:$}=this;g.lastLevel=p,g.lastTime=b,g.lastMsg=S,g.lastObj=_,g.lastLogger=$}g.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:u,streamLevels:m}=this,g;typeof d.levelVal=="number"?g=d.levelVal:typeof d.level=="string"?g=m[d.level]:typeof d.level=="number"?g=d.level:g=qd;let x={stream:p,level:g,levelVal:void 0,id:++n.lastId};return u.unshift(x),u.sort(wo),this.minLevel=u[0].level,n}function l(d){let{streams:h}=this,p=h.findIndex(u=>u.id===d);return p>=0&&(h.splice(p,1),h.sort(wo),this.minLevel=h.length>0?h[0].level:-1),n}function c(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function f(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:f,emit:i,flushSync:o,[An]:!0}}}function wo(t,e){return t.level-e.level}function Hd(t,e){return e?t-1:0}function Wd(t,e){return e?t-1:t+1}function Vd(t,e,r){return r?t>=0:t<e}xo.exports=Bd});var Lo=I((Eg,te)=>{"use strict";var zd=require("node:os"),Ao=Gr(),Kd=Jr(),Gd=Zr(),Oo=si(),Jd=po(),Ro=Ke(),{configure:Yd}=yo(),{assertDefaultLevelFound:Xd,mappings:Io,genLsCache:Zd,genLevelComparison:Qd,assertLevelComparison:ep}=bn(),{DEFAULT_LEVELS:Mo,SORTING_ORDER:tp}=Yt(),{createArgsNormalizer:rp,asChindings:np,buildSafeSonicBoom:_o,buildFormatters:sp,stringify:On,normalizeDestFileDescriptor:vo,noop:ip}=Jt(),{version:op}=xn(),{chindingsSym:ko,redactFmtSym:ap,serializersSym:$o,timeSym:lp,timeSliceIndexSym:cp,streamSym:up,stringifySym:To,stringifySafeSym:Rn,stringifiersSym:Co,setLevelSym:fp,endSym:dp,formatOptsSym:pp,messageKeySym:hp,errorKeySym:mp,nestedKeySym:gp,mixinSym:yp,levelCompSym:wp,useOnlyCustomLevelsSym:bp,formattersSym:Eo,hooksSym:xp,nestedKeyStrSym:Sp,mixinMergeStrategySym:_p,msgPrefixSym:vp}=Ro,{epochTime:Po,nullTime:kp}=Oo,{pid:$p}=process,Tp=zd.hostname(),Cp=Ao.err,Ep={level:"info",levelComparison:tp.ASC,levels:Mo,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:$p,hostname:Tp},serializers:Object.assign(Object.create(null),{err:Cp}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Po,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Ap=rp(Ep),Op=Object.assign(Object.create(null),Ao);function In(...t){let e={},{opts:r,stream:n}=Ap(e,Kd(),...t);r.level&&typeof r.level=="string"&&Mo[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:f,base:d,name:h,level:p,customLevels:u,levelComparison:m,mixin:g,mixinMergeStrategy:x,useOnlyCustomLevels:b,formatters:S,hooks:_,depthLimit:$,edgeLimit:E,onChild:C,msgPrefix:R}=r,T=Yd({maximumDepth:$,maximumBreadth:E}),L=sp(S.level,S.bindings,S.log),U=On.bind({[Rn]:T}),j=s?Gd(s,U):{},B=s?{stringify:j[ap]}:{stringify:U},W="}"+(i?`\r
37
+ ${S}`),m.pop(),`{${_}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(u);default:return e?e(u):void 0}}function f(p,u,m,g,x){switch(typeof u){case"string":return xe(u);case"object":{if(u===null)return"null";if(typeof u.toJSON=="function"){if(u=u.toJSON(p),typeof u!="object")return f(p,u,m,g,x);if(u===null)return"null"}if(m.indexOf(u)!==-1)return r;let b=x;if(Array.isArray(u)){if(u.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(u),x+=g;let T=`
38
+ ${x}`,M=`,
39
+ ${x}`,j=Math.min(u.length,a),D=0;for(;D<j-1;D++){let W=f(String(D),u[D],m,g,x);T+=W!==void 0?W:"null",T+=M}let B=f(String(D),u[D],m,g,x);if(T+=B!==void 0?B:"null",u.length-1>a){let W=u.length-a-1;T+=`${M}"... ${Pe(W)} not stringified"`}return T+=`
40
+ ${b}`,m.pop(),`[${T}]`}let S=Object.keys(u),_=S.length;if(_===0)return"{}";if(o<m.length+1)return'"[Object]"';x+=g;let v=`,
41
+ ${x}`,$="",C="",E=Math.min(_,a);Tn(u)&&($+=yo(u,v,a),S=S.slice(u.length),E-=u.length,C=v),s&&(S=$n(S,i)),m.push(u);for(let T=0;T<E;T++){let M=S[T],j=f(M,u[M],m,g,x);j!==void 0&&($+=`${C}${xe(M)}: ${j}`,C=v)}if(_>a){let T=_-a;$+=`${C}"...": "${Pe(T)} not stringified"`,C=v}return C!==""&&($=`
42
+ ${x}${$}
43
+ ${b}`),m.pop(),`{${$}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(u);default:return e?e(u):void 0}}function d(p,u,m){switch(typeof u){case"string":return xe(u);case"object":{if(u===null)return"null";if(typeof u.toJSON=="function"){if(u=u.toJSON(p),typeof u!="object")return d(p,u,m);if(u===null)return"null"}if(m.indexOf(u)!==-1)return r;let g="",x=u.length!==void 0;if(x&&Array.isArray(u)){if(u.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(u);let $=Math.min(u.length,a),C=0;for(;C<$-1;C++){let T=d(String(C),u[C],m);g+=T!==void 0?T:"null",g+=","}let E=d(String(C),u[C],m);if(g+=E!==void 0?E:"null",u.length-1>a){let T=u.length-a-1;g+=`,"... ${Pe(T)} not stringified"`}return m.pop(),`[${g}]`}let b=Object.keys(u),S=b.length;if(S===0)return"{}";if(o<m.length+1)return'"[Object]"';let _="",v=Math.min(S,a);x&&Tn(u)&&(g+=yo(u,",",a),b=b.slice(u.length),v-=u.length,_=","),s&&(b=$n(b,i)),m.push(u);for(let $=0;$<v;$++){let C=b[$],E=d(C,u[C],m);E!==void 0&&(g+=`${_}${xe(C)}:${E}`,_=",")}if(S>a){let $=S-a;g+=`${_}"...":"${Pe($)} not stringified"`}return m.pop(),`{${g}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(u);default:return e?e(u):void 0}}function h(p,u,m){if(arguments.length>1){let g="";if(typeof m=="number"?g=" ".repeat(Math.min(m,10)):typeof m=="string"&&(g=m.slice(0,10)),u!=null){if(typeof u=="function")return l("",{"":p},[],u,g,"");if(Array.isArray(u))return c("",p,[],qd(u),g,"")}if(g.length!==0)return f("",p,[],g,"")}return d("",p,[])}return h}});var ko=I((Ig,vo)=>{"use strict";var En=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:_o}=Yt(),Hd=_o.info;function Wd(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(_o);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:c,minLevel:0,lastId:0,streams:[],clone:f,[En]:!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:u}=this,m=0,g;for(let x=Vd(u.length,e.dedupe);Kd(x,u.length,e.dedupe);x=zd(x,e.dedupe))if(h=u[x],h.level<=p){if(m!==0&&m!==h.level)break;if(g=h.stream,g[En]){let{lastTime:b,lastMsg:S,lastObj:_,lastLogger:v}=this;g.lastLevel=p,g.lastTime=b,g.lastMsg=S,g.lastObj=_,g.lastLogger=v}g.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:u,streamLevels:m}=this,g;typeof d.levelVal=="number"?g=d.levelVal:typeof d.level=="string"?g=m[d.level]:typeof d.level=="number"?g=d.level:g=Hd;let x={stream:p,level:g,levelVal:void 0,id:++n.lastId};return u.unshift(x),u.sort(xo),this.minLevel=u[0].level,n}function l(d){let{streams:h}=this,p=h.findIndex(u=>u.id===d);return p>=0&&(h.splice(p,1),h.sort(xo),this.minLevel=h.length>0?h[0].level:-1),n}function c(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function f(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:f,emit:i,flushSync:o,[En]:!0}}}function xo(t,e){return t.level-e.level}function Vd(t,e){return e?t-1:0}function zd(t,e){return e?t-1:t+1}function Kd(t,e,r){return r?t>=0:t<e}vo.exports=Wd});var Fo=I((Mg,re)=>{"use strict";var Gd=require("node:os"),Io=Gr(),Jd=Jr(),Yd=Zr(),Mo=ai(),Xd=go(),Po=Ge(),{configure:Zd}=So(),{assertDefaultLevelFound:Qd,mappings:Lo,genLsCache:ep,genLevelComparison:tp,assertLevelComparison:rp}=bn(),{DEFAULT_LEVELS:jo,SORTING_ORDER:np}=Yt(),{createArgsNormalizer:sp,asChindings:ip,buildSafeSonicBoom:$o,buildFormatters:op,stringify:On,normalizeDestFileDescriptor:To,noop:ap}=Jt(),{version:lp}=Sn(),{chindingsSym:Co,redactFmtSym:cp,serializersSym:Ao,timeSym:up,timeSliceIndexSym:fp,streamSym:dp,stringifySym:Eo,stringifySafeSym:Rn,stringifiersSym:Oo,setLevelSym:pp,endSym:hp,formatOptsSym:mp,messageKeySym:gp,errorKeySym:yp,nestedKeySym:wp,mixinSym:bp,levelCompSym:Sp,useOnlyCustomLevelsSym:xp,formattersSym:Ro,hooksSym:_p,nestedKeyStrSym:vp,mixinMergeStrategySym:kp,msgPrefixSym:$p}=Po,{epochTime:Do,nullTime:Tp}=Mo,{pid:Cp}=process,Ap=Gd.hostname(),Ep=Io.err,Op={level:"info",levelComparison:np.ASC,levels:jo,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Cp,hostname:Ap},serializers:Object.assign(Object.create(null),{err:Ep}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Do,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Rp=sp(Op),Ip=Object.assign(Object.create(null),Io);function In(...t){let e={},{opts:r,stream:n}=Rp(e,Jd(),...t);r.level&&typeof r.level=="string"&&jo[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:f,base:d,name:h,level:p,customLevels:u,levelComparison:m,mixin:g,mixinMergeStrategy:x,useOnlyCustomLevels:b,formatters:S,hooks:_,depthLimit:v,edgeLimit:$,onChild:C,msgPrefix:E}=r,T=Zd({maximumDepth:v,maximumBreadth:$}),M=op(S.level,S.bindings,S.log),j=On.bind({[Rn]:T}),D=s?Yd(s,j):{},B=s?{stringify:D[cp]}:{stringify:j},W="}"+(i?`\r
44
44
  `:`
45
- `),J=np.bind(null,{[ko]:"",[$o]:o,[Co]:j,[To]:On,[Rn]:T,[Eo]:L}),Z="";d!==null&&(h===void 0?Z=J(d):Z=J(Object.assign({},d,{name:h})));let P=a instanceof Function?a:a?Po:kp,D=P().indexOf(":")+1;if(b&&!u)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(g&&typeof g!="function")throw Error(`Unknown mixin type "${typeof g}" - expected "function"`);if(R&&typeof R!="string")throw Error(`Unknown msgPrefix type "${typeof R}" - expected "string"`);Xd(p,u,b);let It=Io(u,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:It,messageKey:l,errorKey:c}}),ep(m);let as=Qd(m);return Object.assign(e,{levels:It,[wp]:as,[bp]:b,[up]:n,[lp]:P,[cp]:D,[To]:On,[Rn]:T,[Co]:j,[dp]:W,[pp]:B,[hp]:l,[mp]:c,[gp]:f,[Sp]:f?`,${JSON.stringify(f)}:{`:"",[$o]:o,[yp]:g,[_p]:x,[ko]:Z,[Eo]:L,[xp]:_,silent:ip,onChild:C,[vp]:R}),Object.setPrototypeOf(e,Jd()),Zd(e),e[fp](p),e}te.exports=In;te.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=vo(t.dest||process.stdout.fd),_o(t)):_o({dest:vo(t),minLength:0});te.exports.transport=pn();te.exports.multistream=So();te.exports.levels=Io();te.exports.stdSerializers=Op;te.exports.stdTimeFunctions=Object.assign({},Oo);te.exports.symbols=Ro;te.exports.version=op;te.exports.default=In;te.exports.pino=In});var Ss=k(xs(),1),{program:Fm,createCommand:Nm,createArgument:Um,createOption:qm,CommanderError:Bm,InvalidArgumentError:Hm,InvalidOptionArgumentError:Wm,Command:_s,Argument:Vm,Option:zm,Help:Km}=Ss.default;var ie=k(require("fs")),Oe=k(require("path")),vs=k(require("os"));var pt={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:5e3,timeout:12e4,autoMode:!1,contextBudget:2e6,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0}},ue={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","stepfun-ai/step-3.5-flash","nvidia/llama-3.1-nemotron-70b-instruct","qwen/qwen2.5-coder-32b-instruct","deepseek-ai/deepseek-coder-33b-instruct"]};var We=Oe.join(vs.homedir(),".hablas"),Fr=Oe.join(We,"config.json");function Ve(t={}){let e={};if(ie.existsSync(Fr))try{e=JSON.parse(ie.readFileSync(Fr,"utf-8"))}catch{}let r={...pt,...e,tools:{...pt.tools,...e.tools||{},runCommand:{...pt.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...pt.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=Oe.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 ze(t){ie.existsSync(We)||ie.mkdirSync(We,{recursive:!0}),ie.writeFileSync(Fr,JSON.stringify(t,null,2),"utf-8")}function ks(){let t=[We,Oe.join(We,"logs"),Oe.join(We,"backup")];for(let e of t)ie.existsSync(e)||ie.mkdirSync(e,{recursive:!0})}var Mn=k(Lo()),Pn=k(require("path")),Do=k(require("os")),Qt=k(require("fs"));function Ln(t){let e=Pn.join(Do.homedir(),".hablas","logs");Qt.existsSync(e)||Qt.mkdirSync(e,{recursive:!0});let r=Pn.join(e,`session-${Date.now()}.log`);return(0,Mn.default)({level:"info"},Mn.default.destination({dest:r,sync:!1}))}var er=k(require("fs")),wt=k(require("path"));function jo(){let t=[wt.resolve(__dirname,"..","package.json"),wt.resolve(__dirname,"..","..","package.json"),wt.resolve(process.cwd(),"package.json"),wt.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(er.existsSync(e)){let r=JSON.parse(er.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var pl=k(require("fs")),hl=k(require("path"));var tr=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 c=o.split(`
46
- `);o=c.pop()||"";for(let f of c)if(f.trim())try{let d=JSON.parse(f);d.message?.content&&(yield d.message.content)}catch{}}}};var Fo=12e4,Rp=6e4,rr=3,No=1e3,Ip=20;function Uo(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 Mp(t){return t.map(e=>({type:"function",function:e.function}))}function Pp(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 qo(t){return new Promise(e=>setTimeout(e,t))}function Bo(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var bt=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<Ip;){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(Rp)});if(!l.ok)break;let c=await l.json();if(Array.isArray(c))e.push(...c.map(f=>f.id||f.name||f).filter(Boolean)),r=!1;else if(c.data&&Array.isArray(c.data)){let f=c.data.map(d=>d.id||d.name).filter(Boolean);e.push(...f),c.has_more&&f.length>0?(n=f[f.length-1],s++):r=!1}else c.models&&Array.isArray(c.models)&&e.push(...c.models.map(f=>f.name||f.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:Uo(e)};r.length>0&&(i.tools=Mp(r),i.tool_choice="auto");let o=null;for(let a=0;a<=rr;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),Fo),f={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:n||l.signal};try{let d=await fetch(s,f);if(clearTimeout(c),!d.ok){let m=await d.text().catch(()=>"");if(!Bo(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<rr){let g=No*Math.pow(2,a);await qo(g);continue}throw o}let p=(await d.json()).choices?.[0];if(!p)throw new Error("API returned empty response");let u=p.message.tool_calls?Pp(p.message.tool_calls):void 0;return{message:{role:p.message.role||"assistant",content:p.message.content||"",tool_calls:u},done:!0,done_reason:p.finish_reason}}catch(d){if(clearTimeout(c),d.name==="AbortError"&&n?.aborted)throw d;if(Bo(d)&&(o=d,a<rr)){let h=No*Math.pow(2,a);await qo(h);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=rr)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:Uo(e),stream:!0}),signal:r||AbortSignal.timeout(Fo)});if(!s.ok)throw new Error(`API error: ${s.status} ${s.statusText}`);let i=s.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:c}=await i.read();if(l)break;a+=o.decode(c,{stream:!0});let f=a.split(`
47
- `);a=f.pop()||"";for(let d of f){let h=d.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let u=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;u&&(yield u)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function Ye(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:ue.apiUrl};return new bt(e)}return t.provider==="custom"&&t.apiUrl?new bt(t):new tr(t)}function De(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var N=k(require("fs/promises")),Hn=k(require("fs")),_e=k(require("path"));function me(){}me.prototype={diff:function(e,r){var n,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=s.callback;typeof s=="function"&&(i=s,s={}),this.options=s;var o=this;function a(_){return i?(setTimeout(function(){i(void 0,_)},0),!0):_}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,c=e.length,f=1,d=l+c;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var h=(n=s.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+h,u=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(u[0],r,e,0);if(u[0].oldPos+1>=c&&m+1>=l)return a([{value:this.join(r),count:r.length}]);var g=-1/0,x=1/0;function b(){for(var _=Math.max(g,-f);_<=Math.min(x,f);_+=2){var $=void 0,E=u[_-1],C=u[_+1];E&&(u[_-1]=void 0);var R=!1;if(C){var T=C.oldPos-_;R=C&&0<=T&&T<l}var L=E&&E.oldPos+1<c;if(!R&&!L){u[_]=void 0;continue}if(!L||R&&E.oldPos+1<C.oldPos?$=o.addToPath(C,!0,void 0,0):$=o.addToPath(E,void 0,!0,1),m=o.extractCommon($,r,e,_),$.oldPos+1>=c&&m+1>=l)return a(Lp(o,$.lastComponent,r,e,o.useLongestToken));u[_]=$,$.oldPos+1>=c&&(x=Math.min(x,_-1)),m+1>=l&&(g=Math.max(g,_+1))}f++}if(i)(function _(){setTimeout(function(){if(f>d||Date.now()>p)return i();b()||_()},0)})();else for(;f<=d&&Date.now()<=p;){var S=b();if(S)return S}},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,c=0;l+1<i&&a+1<o&&this.equals(r[l+1],n[a+1]);)l++,a++,c++;return c&&(e.lastComponent={count:c,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 Lp(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,c=0,f=0;a<l;a++){var d=i[a];if(d.removed){if(d.value=t.join(n.slice(f,f+d.count)),f+=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(c,c+d.count);h=h.map(function(m,g){var x=n[f+g];return x.length>m.length?x:m}),d.value=t.join(h)}else d.value=t.join(r.slice(c,c+d.count));c+=d.count,d.added||(f+=d.count)}}var u=i[l-1];return l>1&&typeof u.value=="string"&&(u.added||u.removed)&&t.equals("",u.value)&&(i[l-2].value+=u.value,i.pop()),i}var Hg=new me;var Ho=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Wo=/\S/,Vo=new me;Vo.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!Wo.test(t)&&!Wo.test(e)};Vo.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]&&Ho.test(e[r])&&Ho.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var Un=new me;Un.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 Dp(t,e,r){return Un.diff(t,e,r)}var jp=new me;jp.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var Fp=new me;Fp.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function nr(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?nr=function(e){return typeof e}:nr=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},nr(t)}function Dn(t){return Np(t)||Up(t)||qp(t)||Bp()}function Np(t){if(Array.isArray(t))return jn(t)}function Up(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function qp(t,e){if(t){if(typeof t=="string")return jn(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 jn(t,e)}}function jn(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 Bp(){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 Hp=Object.prototype.toString,xt=new me;xt.useLongestToken=!0;xt.tokenize=Un.tokenize;xt.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(Fn(t,null,null,s),s," ")};xt.equals=function(t,e){return me.prototype.equals.call(xt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function Fn(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(Hp.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]=Fn(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),nr(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]=Fn(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var Nn=new me;Nn.tokenize=function(t){return t.slice()};Nn.join=Nn.removeEmpty=function(t){return t};function Wp(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Dp(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(x){return x.map(function(b){return" "+b})}for(var c=[],f=0,d=0,h=[],p=1,u=1,m=function(b){var S=a[b],_=S.lines||S.value.replace(/\n$/,"").split(`
50
- `);if(S.lines=_,S.added||S.removed){var $;if(!f){var E=a[b-1];f=p,d=u,E&&(h=o.context>0?l(E.lines.slice(-o.context)):[],f-=h.length,d-=h.length)}($=h).push.apply($,Dn(_.map(function(W){return(S.added?"+":"-")+W}))),S.added?u+=_.length:p+=_.length}else{if(f)if(_.length<=o.context*2&&b<a.length-2){var C;(C=h).push.apply(C,Dn(l(_)))}else{var R,T=Math.min(_.length,o.context);(R=h).push.apply(R,Dn(l(_.slice(0,T))));var L={oldStart:f,oldLines:p-f+T,newStart:d,newLines:u-d+T,lines:h};if(b>=a.length-2&&_.length<=o.context){var U=/\n$/.test(r),j=/\n$/.test(n),B=_.length==0&&h.length>L.oldLines;!U&&B&&r.length>0&&h.splice(L.oldLines,0,"\"),(!U&&!B||!j)&&h.push("\")}c.push(L),f=0,d=0,h=[]}p+=_.length,u+=_.length}},g=0;g<a.length;g++)m(g);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:c}}function zo(t){if(Array.isArray(t))return t.map(zo).join(`
45
+ `),J=ip.bind(null,{[Co]:"",[Ao]:o,[Oo]:D,[Eo]:On,[Rn]:T,[Ro]:M}),Z="";d!==null&&(h===void 0?Z=J(d):Z=J(Object.assign({},d,{name:h})));let L=a instanceof Function?a:a?Do:Tp,F=L().indexOf(":")+1;if(b&&!u)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(g&&typeof g!="function")throw Error(`Unknown mixin type "${typeof g}" - expected "function"`);if(E&&typeof E!="string")throw Error(`Unknown msgPrefix type "${typeof E}" - expected "string"`);Qd(p,u,b);let It=Lo(u,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:It,messageKey:l,errorKey:c}}),rp(m);let us=tp(m);return Object.assign(e,{levels:It,[Sp]:us,[xp]:b,[dp]:n,[up]:L,[fp]:F,[Eo]:On,[Rn]:T,[Oo]:D,[hp]:W,[mp]:B,[gp]:l,[yp]:c,[wp]:f,[vp]:f?`,${JSON.stringify(f)}:{`:"",[Ao]:o,[bp]:g,[kp]:x,[Co]:Z,[Ro]:M,[_p]:_,silent:ap,onChild:C,[$p]:E}),Object.setPrototypeOf(e,Xd()),ep(e),e[pp](p),e}re.exports=In;re.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=To(t.dest||process.stdout.fd),$o(t)):$o({dest:To(t),minLength:0});re.exports.transport=pn();re.exports.multistream=ko();re.exports.levels=Lo();re.exports.stdSerializers=Ip;re.exports.stdTimeFunctions=Object.assign({},Mo);re.exports.symbols=Po;re.exports.version=lp;re.exports.default=In;re.exports.pino=In});var ks=A(vs(),1),{program:Hm,createCommand:Wm,createArgument:Vm,createOption:zm,CommanderError:Km,InvalidArgumentError:Gm,InvalidOptionArgumentError:Jm,Command:$s,Argument:Ym,Option:Xm,Help:Zm}=ks.default;var oe=A(require("fs")),Oe=A(require("path")),Ts=A(require("os"));var We={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:5e3,timeout:12e4,autoMode:!1,contextBudget:2e6,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0},vision:{enabled:!0,primaryModel:"moonshotai/kimi-k2.6",fallbackModel:"meta/llama-3.2-90b-vision-instruct",maxImageBytes:1048576}},ee={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 Ve=Oe.join(Ts.homedir(),".hablas"),Fr=Oe.join(Ve,"config.json");function ze(t={}){let e={};if(oe.existsSync(Fr))try{e=JSON.parse(oe.readFileSync(Fr,"utf-8"))}catch{}let r={...We,...e,tools:{...We.tools,...e.tools||{},runCommand:{...We.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...We.workspace,...e.workspace||{}},vision:{...We.vision,...e.vision||{}}};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_VISION_PRIMARY&&(r.vision.primaryModel=process.env.HABLAS_VISION_PRIMARY),process.env.HABLAS_VISION_FALLBACK&&(r.vision.fallbackModel=process.env.HABLAS_VISION_FALLBACK),process.env.HABLAS_VISION_DISABLED==="true"&&(r.vision.enabled=!1),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=Oe.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 Ke(t){oe.existsSync(Ve)||oe.mkdirSync(Ve,{recursive:!0}),oe.writeFileSync(Fr,JSON.stringify(t,null,2),"utf-8")}function Cs(){let t=[Ve,Oe.join(Ve,"logs"),Oe.join(Ve,"backup")];for(let e of t)oe.existsSync(e)||oe.mkdirSync(e,{recursive:!0})}var Mn=A(Fo()),Pn=A(require("path")),No=A(require("os")),Qt=A(require("fs"));function Ln(t){let e=Pn.join(No.homedir(),".hablas","logs");Qt.existsSync(e)||Qt.mkdirSync(e,{recursive:!0});let r=Pn.join(e,`session-${Date.now()}.log`);return(0,Mn.default)({level:"info"},Mn.default.destination({dest:r,sync:!1}))}var er=A(require("fs")),wt=A(require("path"));function Uo(){let t=[wt.resolve(__dirname,"..","package.json"),wt.resolve(__dirname,"..","..","package.json"),wt.resolve(process.cwd(),"package.json"),wt.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(er.existsSync(e)){let r=JSON.parse(er.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var ml=A(require("fs")),gl=A(require("path"));var tr=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 c=o.split(`
46
+ `);o=c.pop()||"";for(let f of c)if(f.trim())try{let d=JSON.parse(f);d.message?.content&&(yield d.message.content)}catch{}}}};var qo=12e4,Mp=6e4,rr=3,Bo=1e3,Pp=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 Lp(t){return t.map(e=>({type:"function",function:e.function}))}function jp(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 Wo(t){return new Promise(e=>setTimeout(e,t))}function Vo(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var bt=class{apiUrl;apiKey;model;constructor(e){this.apiUrl=e.apiUrl||"https://api.openai.com/v1",this.apiKey=e.apiKey,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}setApiUrl(e){this.apiUrl=e}getApiUrl(){return this.apiUrl}setApiKey(e){this.apiKey=e}async checkConnection(){try{let e=this.apiUrl.replace(/\/+$/,"")+"/models";return(await fetch(e,{headers:this.getHeaders(),signal:AbortSignal.timeout(15e3)})).ok}catch{return!1}}async listModels(){try{let e=[],r=!0,n,s=0;for(;r&&s<Pp;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;n&&o.set("after",n),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let l=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(Mp)});if(!l.ok)break;let c=await l.json();if(Array.isArray(c))e.push(...c.map(f=>f.id||f.name||f).filter(Boolean)),r=!1;else if(c.data&&Array.isArray(c.data)){let f=c.data.map(d=>d.id||d.name).filter(Boolean);e.push(...f),c.has_more&&f.length>0?(n=f[f.length-1],s++):r=!1}else c.models&&Array.isArray(c.models)&&e.push(...c.models.map(f=>f.name||f.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=Lp(r),i.tool_choice="auto");let o=null;for(let a=0;a<=rr;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),qo),f={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:n||l.signal};try{let d=await fetch(s,f);if(clearTimeout(c),!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<rr){let g=Bo*Math.pow(2,a);await Wo(g);continue}throw o}let p=(await d.json()).choices?.[0];if(!p)throw new Error("API returned empty response");let u=p.message.tool_calls?jp(p.message.tool_calls):void 0;return{message:{role:p.message.role||"assistant",content:p.message.content||"",tool_calls:u},done:!0,done_reason:p.finish_reason}}catch(d){if(clearTimeout(c),d.name==="AbortError"&&n?.aborted)throw d;if(Vo(d)&&(o=d,a<rr)){let h=Bo*Math.pow(2,a);await Wo(h);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=rr)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(qo)});if(!s.ok)throw new Error(`API error: ${s.status} ${s.statusText}`);let i=s.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:c}=await i.read();if(l)break;a+=o.decode(c,{stream:!0});let f=a.split(`
47
+ `);a=f.pop()||"";for(let d of f){let h=d.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let u=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;u&&(yield u)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function Xe(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:ee.apiUrl};return new bt(e)}return t.provider==="custom"&&t.apiUrl?new bt(t):new tr(t)}function je(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var U=A(require("fs/promises")),Hn=A(require("fs")),_e=A(require("path"));function me(){}me.prototype={diff:function(e,r){var n,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=s.callback;typeof s=="function"&&(i=s,s={}),this.options=s;var o=this;function a(_){return i?(setTimeout(function(){i(void 0,_)},0),!0):_}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,c=e.length,f=1,d=l+c;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var h=(n=s.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+h,u=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(u[0],r,e,0);if(u[0].oldPos+1>=c&&m+1>=l)return a([{value:this.join(r),count:r.length}]);var g=-1/0,x=1/0;function b(){for(var _=Math.max(g,-f);_<=Math.min(x,f);_+=2){var v=void 0,$=u[_-1],C=u[_+1];$&&(u[_-1]=void 0);var E=!1;if(C){var T=C.oldPos-_;E=C&&0<=T&&T<l}var M=$&&$.oldPos+1<c;if(!E&&!M){u[_]=void 0;continue}if(!M||E&&$.oldPos+1<C.oldPos?v=o.addToPath(C,!0,void 0,0):v=o.addToPath($,void 0,!0,1),m=o.extractCommon(v,r,e,_),v.oldPos+1>=c&&m+1>=l)return a(Dp(o,v.lastComponent,r,e,o.useLongestToken));u[_]=v,v.oldPos+1>=c&&(x=Math.min(x,_-1)),m+1>=l&&(g=Math.max(g,_+1))}f++}if(i)(function _(){setTimeout(function(){if(f>d||Date.now()>p)return i();b()||_()},0)})();else for(;f<=d&&Date.now()<=p;){var S=b();if(S)return S}},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,c=0;l+1<i&&a+1<o&&this.equals(r[l+1],n[a+1]);)l++,a++,c++;return c&&(e.lastComponent={count:c,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 Dp(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,c=0,f=0;a<l;a++){var d=i[a];if(d.removed){if(d.value=t.join(n.slice(f,f+d.count)),f+=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(c,c+d.count);h=h.map(function(m,g){var x=n[f+g];return x.length>m.length?x:m}),d.value=t.join(h)}else d.value=t.join(r.slice(c,c+d.count));c+=d.count,d.added||(f+=d.count)}}var u=i[l-1];return l>1&&typeof u.value=="string"&&(u.added||u.removed)&&t.equals("",u.value)&&(i[l-2].value+=u.value,i.pop()),i}var Gg=new me;var zo=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Ko=/\S/,Go=new me;Go.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!Ko.test(t)&&!Ko.test(e)};Go.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]&&zo.test(e[r])&&zo.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var Un=new me;Un.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 Fp(t,e,r){return Un.diff(t,e,r)}var Np=new me;Np.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var Up=new me;Up.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function nr(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?nr=function(e){return typeof e}:nr=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},nr(t)}function jn(t){return qp(t)||Bp(t)||Hp(t)||Wp()}function qp(t){if(Array.isArray(t))return Dn(t)}function Bp(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Hp(t,e){if(t){if(typeof t=="string")return Dn(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Dn(t,e)}}function Dn(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function Wp(){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 Vp=Object.prototype.toString,St=new me;St.useLongestToken=!0;St.tokenize=Un.tokenize;St.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(Fn(t,null,null,s),s," ")};St.equals=function(t,e){return me.prototype.equals.call(St,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function Fn(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(Vp.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]=Fn(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),nr(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]=Fn(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var Nn=new me;Nn.tokenize=function(t){return t.slice()};Nn.join=Nn.removeEmpty=function(t){return t};function zp(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Fp(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(x){return x.map(function(b){return" "+b})}for(var c=[],f=0,d=0,h=[],p=1,u=1,m=function(b){var S=a[b],_=S.lines||S.value.replace(/\n$/,"").split(`
50
+ `);if(S.lines=_,S.added||S.removed){var v;if(!f){var $=a[b-1];f=p,d=u,$&&(h=o.context>0?l($.lines.slice(-o.context)):[],f-=h.length,d-=h.length)}(v=h).push.apply(v,jn(_.map(function(W){return(S.added?"+":"-")+W}))),S.added?u+=_.length:p+=_.length}else{if(f)if(_.length<=o.context*2&&b<a.length-2){var C;(C=h).push.apply(C,jn(l(_)))}else{var E,T=Math.min(_.length,o.context);(E=h).push.apply(E,jn(l(_.slice(0,T))));var M={oldStart:f,oldLines:p-f+T,newStart:d,newLines:u-d+T,lines:h};if(b>=a.length-2&&_.length<=o.context){var j=/\n$/.test(r),D=/\n$/.test(n),B=_.length==0&&h.length>M.oldLines;!j&&B&&r.length>0&&h.splice(M.oldLines,0,"\"),(!j&&!B||!D)&&h.push("\")}c.push(M),f=0,d=0,h=[]}p+=_.length,u+=_.length}},g=0;g<a.length;g++)m(g);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:c}}function Jo(t){if(Array.isArray(t))return t.map(Jo).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 Vp(t,e,r,n,s,i,o){return zo(Wp(t,e,r,n,s,i,o))}function Ko(t,e,r,n,s,i){return Vp(t,t,e,r,n,s,i)}function qn(t,e,r){return Ko(t,e,r,"original","modified")}var de=k(require("fs/promises")),Bn=k(require("fs")),Xe=k(require("path")),Jo=k(require("os")),St=Xe.join(Jo.homedir(),".hablas","backup"),Go=10;async function je(t){try{if(!Bn.existsSync(t))return;Bn.existsSync(St)||await de.mkdir(St,{recursive:!0});let e=await de.readFile(t,"utf-8"),r=Xe.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=Xe.join(St,s);await de.writeFile(i,e,"utf-8");let a=(await de.readdir(St)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Go)for(let l of a.slice(Go))await de.unlink(Xe.join(St,l))}catch{}}function Xo(t){let e=p=>_e.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 u=e(p.path),g=(await N.readFile(u,"utf-8")).split(`
54
- `),x=g.length,b=p.start_line?Math.max(1,p.start_line):1,S=p.end_line?Math.min(x,p.end_line):x,_=g.slice(b-1,S),$=String(S).length,E=_.map((T,L)=>`${String(b+L).padStart($," ")} | ${T}`),C=`[${p.path} \u2014 lines ${b}-${S} of ${x}]`,R=S<x?`
53
+ `}function Kp(t,e,r,n,s,i,o){return Jo(zp(t,e,r,n,s,i,o))}function Yo(t,e,r,n,s,i){return Kp(t,t,e,r,n,s,i)}function qn(t,e,r){return Yo(t,e,r,"original","modified")}var de=A(require("fs/promises")),Bn=A(require("fs")),Ze=A(require("path")),Zo=A(require("os")),xt=Ze.join(Zo.homedir(),".hablas","backup"),Xo=10;async function De(t){try{if(!Bn.existsSync(t))return;Bn.existsSync(xt)||await de.mkdir(xt,{recursive:!0});let e=await de.readFile(t,"utf-8"),r=Ze.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=Ze.join(xt,s);await de.writeFile(i,e,"utf-8");let a=(await de.readdir(xt)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Xo)for(let l of a.slice(Xo))await de.unlink(Ze.join(xt,l))}catch{}}function ea(t){let e=p=>_e.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 u=e(p.path),g=(await U.readFile(u,"utf-8")).split(`
54
+ `),x=g.length,b=p.start_line?Math.max(1,p.start_line):1,S=p.end_line?Math.min(x,p.end_line):x,_=g.slice(b-1,S),v=String(S).length,$=_.map((T,M)=>`${String(b+M).padStart(v," ")} | ${T}`),C=`[${p.path} \u2014 lines ${b}-${S} of ${x}]`,E=S<x?`
55
55
  ... [Partial read. Total lines: ${x}.]`:"";return{success:!0,output:`${C}
56
- ${E.join(`
57
- `)}${R}`}}catch(u){return{success:!1,output:"",error:`[read_file]: ${u.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 u=e(p.path);return Hn.existsSync(u)&&await je(u),await N.mkdir(_e.dirname(u),{recursive:!0}),await N.writeFile(u,p.content,"utf-8"),{success:!0,output:`Written: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[write_file]: ${u.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 u=e(p.path),m=await N.readFile(u,"utf-8"),g=p.old_content,x=p.new_content,b=Yo(m,g);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 je(u);let S=m.replace(g,x);await N.writeFile(u,S,"utf-8");let _=qn(p.path,m,S);return{success:!0,output:`Edited: ${p.path}
58
- ${_}`}}catch(u){return{success:!1,output:"",error:`[edit_file]: ${u.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 u=e(p.path),m=await N.readFile(u,"utf-8"),g=m.split(`
59
- `),x=g.length,b=p.start_line,S=p.end_line;if(b<1||b>x)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${x} lines)`};if(S<b||S>x)return{success:!1,output:"",error:`[patch_file]: end_line ${S} is out of range (start_line=${b}, total=${x})`};await je(u);let _=g.slice(0,b-1),$=g.slice(S),E=p.new_content.split(`
60
- `),C=[..._,...E,...$].join(`
61
- `);await N.writeFile(u,C,"utf-8");let R=qn(p.path,m,C),T=S-b+1,L=E.length;return{success:!0,output:`Patched: ${p.path} (replaced ${T} lines with ${L})
62
- ${R}`}}catch(u){return{success:!1,output:"",error:`[patch_file]: ${u.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 u=e(p.path),m=await N.readFile(u,"utf-8"),g=p.search,x=p.replace,b=p.is_regex;await je(u);let S,_;if(b){let $=new RegExp(g,"g");_=(m.match($)||[]).length,S=m.replace($,x)}else _=Yo(m,g),S=m.split(g).join(x);return _===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await N.writeFile(u,S,"utf-8"),{success:!0,output:`Replaced ${_} occurrence(s) in ${p.path}`})}catch(u){return{success:!1,output:"",error:`[search_and_replace]: ${u.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 u=e(p.path);return await N.mkdir(_e.dirname(u),{recursive:!0}),Hn.existsSync(u)&&await je(u),await N.appendFile(u,p.content,"utf-8"),{success:!0,output:`Appended to: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[append_to_file]: ${u.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 u=e(p.path);return await je(u),await N.unlink(u),{success:!0,output:`Deleted: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[delete_file]: ${u.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 u=e(p.from),m=e(p.to);return await N.mkdir(_e.dirname(m),{recursive:!0}),await N.rename(u,m),{success:!0,output:`Moved: ${p.from} \u2192 ${p.to}`}}catch(u){return{success:!1,output:"",error:`[move_file]: ${u.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 u=e(p.path);return await N.mkdir(u,{recursive:!0}),{success:!0,output:`Created directory: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[create_dir]: ${u.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 u=e(p.path||"."),m=p.depth||3;return{success:!0,output:await Zo(u,"",m,0)||"(empty directory)"}}catch(u){return{success:!1,output:"",error:`[list_dir]: ${u.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 u=e(p.path),m=await N.stat(u);return{success:!0,output:[`Path: ${p.path}`,`Size: ${Kp(m.size)}`,`Type: ${m.isDirectory()?"directory":"file"}`,`Modified: ${m.mtime.toISOString()}`,`Created: ${m.birthtime.toISOString()}`].join(`
63
- `)}}catch(u){return{success:!1,output:"",error:`[get_file_info]: ${u.message}`}}}}]}function Yo(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 zp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Zo(t,e,r,n){if(n>=r)return"";let i=(await N.readdir(t,{withFileTypes:!0})).filter(a=>!zp.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],c=a===i.length-1,f=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${f}${d} ${l.name}
64
- `,l.isDirectory()){let h=e+(c?" ":"\u2502 ");o+=await Zo(_e.join(t,l.name),h,r,n+1)}}return o}function Kp(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var ta=require("child_process");var Qo=require("child_process"),sr=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,Qo.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
+ ${$.join(`
57
+ `)}${E}`}}catch(u){return{success:!1,output:"",error:`[read_file]: ${u.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 u=e(p.path);return Hn.existsSync(u)&&await De(u),await U.mkdir(_e.dirname(u),{recursive:!0}),await U.writeFile(u,p.content,"utf-8"),{success:!0,output:`Written: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[write_file]: ${u.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 u=e(p.path),m=await U.readFile(u,"utf-8"),g=p.old_content,x=p.new_content,b=Qo(m,g);if(b===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(b>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${b} locations in the file. Provide more surrounding context to be specific.`};await De(u);let S=m.replace(g,x);await U.writeFile(u,S,"utf-8");let _=qn(p.path,m,S);return{success:!0,output:`Edited: ${p.path}
58
+ ${_}`}}catch(u){return{success:!1,output:"",error:`[edit_file]: ${u.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 u=e(p.path),m=await U.readFile(u,"utf-8"),g=m.split(`
59
+ `),x=g.length,b=p.start_line,S=p.end_line;if(b<1||b>x)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${x} lines)`};if(S<b||S>x)return{success:!1,output:"",error:`[patch_file]: end_line ${S} is out of range (start_line=${b}, total=${x})`};await De(u);let _=g.slice(0,b-1),v=g.slice(S),$=p.new_content.split(`
60
+ `),C=[..._,...$,...v].join(`
61
+ `);await U.writeFile(u,C,"utf-8");let E=qn(p.path,m,C),T=S-b+1,M=$.length;return{success:!0,output:`Patched: ${p.path} (replaced ${T} lines with ${M})
62
+ ${E}`}}catch(u){return{success:!1,output:"",error:`[patch_file]: ${u.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 u=e(p.path),m=await U.readFile(u,"utf-8"),g=p.search,x=p.replace,b=p.is_regex;await De(u);let S,_;if(b){let v=new RegExp(g,"g");_=(m.match(v)||[]).length,S=m.replace(v,x)}else _=Qo(m,g),S=m.split(g).join(x);return _===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await U.writeFile(u,S,"utf-8"),{success:!0,output:`Replaced ${_} occurrence(s) in ${p.path}`})}catch(u){return{success:!1,output:"",error:`[search_and_replace]: ${u.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 u=e(p.path);return await U.mkdir(_e.dirname(u),{recursive:!0}),Hn.existsSync(u)&&await De(u),await U.appendFile(u,p.content,"utf-8"),{success:!0,output:`Appended to: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[append_to_file]: ${u.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 u=e(p.path);return await De(u),await U.unlink(u),{success:!0,output:`Deleted: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[delete_file]: ${u.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 u=e(p.from),m=e(p.to);return await U.mkdir(_e.dirname(m),{recursive:!0}),await U.rename(u,m),{success:!0,output:`Moved: ${p.from} \u2192 ${p.to}`}}catch(u){return{success:!1,output:"",error:`[move_file]: ${u.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 u=e(p.path);return await U.mkdir(u,{recursive:!0}),{success:!0,output:`Created directory: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[create_dir]: ${u.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 u=e(p.path||"."),m=p.depth||3;return{success:!0,output:await ta(u,"",m,0)||"(empty directory)"}}catch(u){return{success:!1,output:"",error:`[list_dir]: ${u.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 u=e(p.path),m=await U.stat(u);return{success:!0,output:[`Path: ${p.path}`,`Size: ${Jp(m.size)}`,`Type: ${m.isDirectory()?"directory":"file"}`,`Modified: ${m.mtime.toISOString()}`,`Created: ${m.birthtime.toISOString()}`].join(`
63
+ `)}}catch(u){return{success:!1,output:"",error:`[get_file_info]: ${u.message}`}}}}]}function Qo(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 Gp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function ta(t,e,r,n){if(n>=r)return"";let i=(await U.readdir(t,{withFileTypes:!0})).filter(a=>!Gp.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],c=a===i.length-1,f=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${f}${d} ${l.name}
64
+ `,l.isDirectory()){let h=e+(c?" ":"\u2502 ");o+=await ta(_e.join(t,l.name),h,r,n+1)}}return o}function Jp(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var sa=require("child_process");var ra=require("child_process"),sr=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,ra.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 Gp=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],Wn=null;function ea(t){return Wn||(Wn=new sr({workingDir:t})),Wn}function ra(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=[...Gp,...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=ea(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
70
- PID: ${ea(t).getProcess(l)?.pid}
71
- Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,ta.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),f="",d="";c.stdout?.on("data",h=>{f+=h}),c.stderr?.on("data",h=>{d+=h}),c.on("close",h=>{l(h===0?{success:!0,output:f||"(no output)"}:{success:!1,output:f,error:d||`Exit code: ${h}`})}),c.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var ir=k(require("fs/promises")),ve=k(require("path")),Jp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Yp=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function na(t){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let r=e.query,n=ve.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await sa(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 Yp=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],Wn=null;function na(t){return Wn||(Wn=new sr({workingDir:t})),Wn}function ia(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=[...Yp,...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=na(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
70
+ PID: ${na(t).getProcess(l)?.pid}
71
+ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,sa.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),f="",d="";c.stdout?.on("data",h=>{f+=h}),c.stderr?.on("data",h=>{d+=h}),c.on("close",h=>{l(h===0?{success:!0,output:f||"(no output)"}:{success:!1,output:f,error:d||`Exit code: ${h}`})}),c.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var ir=A(require("fs/promises")),ve=A(require("path")),Xp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Zp=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function oa(t){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let r=e.query,n=ve.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await aa(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 sa(t,e,r,n){let s=await ir.readdir(t,{withFileTypes:!0});for(let i of s){if(Jp.has(i.name)||i.name.startsWith("."))continue;let o=ve.join(t,i.name);if(i.isDirectory())await sa(o,e,r,n);else if(Yp.has(ve.extname(i.name)))try{let l=(await ir.readFile(o,"utf-8")).split(`
74
- `),c=ve.relative(n,o);for(let f=0;f<l.length;f++)e.test(l[f])&&(r.push(`${c}:${f+1}: ${l[f].trim()}`),e.lastIndex=0)}catch{}}}var Vn=require("child_process"),re=k(require("fs")),ke=k(require("path"));function Xp(t){let e=[],r=ke.join(t,"tsconfig.json");if(!re.existsSync(r))return e;try{(0,Vn.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 Zp(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>re.existsSync(ke.join(t,n))))return e;try{(0,Vn.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let i=n.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:ke.relative(t,a.filePath),line:l.line||0,severity:l.severity===2?"error":"warning",message:`${l.message} (${l.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
76
- `);for(let a of o){let l=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);l&&e.push({file:"unknown",line:parseInt(l[1],10),severity:l[3]==="error"?"error":"warning",message:`${l[4]} (${l[5]})`,source:"eslint"})}}}return e}function Qp(t,e,r){let n;try{n=re.readFileSync(t,"utf-8")}catch{return}let s=ke.relative(e,t),i=n.split(`
77
- `);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&r.push({file:s,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&r.push({file:s,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&r.push({file:s,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&r.push({file:s,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function eh(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=re.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let c=ke.join(s,l),f;try{f=re.statSync(c)}catch{continue}f.isDirectory()?n(c,i+1):r.some(d=>l.endsWith(d))&&Qp(c,t,e)}}return n(t),e.slice(0,20)}function th(t){let e=[];e.push(...Xp(t)),e.push(...Zp(t)),e.push(...eh(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function ia(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 rh(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=ke.join(e,n.file);try{let o=re.readFileSync(s,"utf-8").split(`
79
- `);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],re.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 oa(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=th(r);if(n&&s.length>0){let o=rh(s,r).filter(l=>l.fixed).length;return{success:!0,output:`${ia(s)}
81
-
82
- Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:ia(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var aa=2*1024*1024,la=15e3,ca=32e3,nh="HablasBot/2.0 (+https://hablas.dev)";function sh(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 aa(t,e,r,n){let s=await ir.readdir(t,{withFileTypes:!0});for(let i of s){if(Xp.has(i.name)||i.name.startsWith("."))continue;let o=ve.join(t,i.name);if(i.isDirectory())await aa(o,e,r,n);else if(Zp.has(ve.extname(i.name)))try{let l=(await ir.readFile(o,"utf-8")).split(`
74
+ `),c=ve.relative(n,o);for(let f=0;f<l.length;f++)e.test(l[f])&&(r.push(`${c}:${f+1}: ${l[f].trim()}`),e.lastIndex=0)}catch{}}}var Vn=require("child_process"),ne=A(require("fs")),ke=A(require("path"));function Qp(t){let e=[],r=ke.join(t,"tsconfig.json");if(!ne.existsSync(r))return e;try{(0,Vn.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 eh(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>ne.existsSync(ke.join(t,n))))return e;try{(0,Vn.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let i=n.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:ke.relative(t,a.filePath),line:l.line||0,severity:l.severity===2?"error":"warning",message:`${l.message} (${l.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
76
+ `);for(let a of o){let l=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);l&&e.push({file:"unknown",line:parseInt(l[1],10),severity:l[3]==="error"?"error":"warning",message:`${l[4]} (${l[5]})`,source:"eslint"})}}}return e}function th(t,e,r){let n;try{n=ne.readFileSync(t,"utf-8")}catch{return}let s=ke.relative(e,t),i=n.split(`
77
+ `);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&r.push({file:s,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&r.push({file:s,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&r.push({file:s,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&r.push({file:s,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function rh(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=ne.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let c=ke.join(s,l),f;try{f=ne.statSync(c)}catch{continue}f.isDirectory()?n(c,i+1):r.some(d=>l.endsWith(d))&&th(c,t,e)}}return n(t),e.slice(0,20)}function nh(t){let e=[];e.push(...Qp(t)),e.push(...eh(t)),e.push(...rh(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function la(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 sh(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=ke.join(e,n.file);try{let o=ne.readFileSync(s,"utf-8").split(`
79
+ `);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],ne.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 ca(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=nh(r);if(n&&s.length>0){let o=sh(s,r).filter(l=>l.fixed).length;return{success:!0,output:`${la(s)}
81
+
82
+ Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:la(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var ua=2*1024*1024,fa=15e3,da=32e3,ih="HablasBot/2.0 (+https://hablas.dev)";function oh(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 ih(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 oh(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 ua(t){let e=new AbortController,r=setTimeout(()=>e.abort(),la);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":nh,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<aa;){let{done:f,value:d}=await i.read();if(f)break;o.push(d),a+=d.length}if(a>=aa)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(f=>l.decode(f,{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 ${la/1e3}s`):s}}function fa(){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 ua(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=ih(r),o=sh(r);return o.length>ca&&(o=o.slice(0,ca)+`
89
+ `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function ah(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 lh(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 pa(t){let e=new AbortController,r=setTimeout(()=>e.abort(),fa);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":ih,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<ua;){let{done:f,value:d}=await i.read();if(f)break;o.push(d),a+=d.length}if(a>=ua)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(f=>l.decode(f,{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 ${fa/1e3}s`):s}}function ha(){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 pa(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=ah(r),o=oh(r);return o.length>da&&(o=o.slice(0,da)+`
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 ua(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=oh(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,c)=>`${c+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 pa(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=lh(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,c)=>`${c+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 ah=3600*1e3,Ze=new Map;function lh(t){let e=Ze.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>ah?(Ze.delete(t.toLowerCase().trim()),null):e.results:null}function ch(t,e){if(Ze.size>200){let r=Ze.keys().next().value;r!==void 0&&Ze.delete(r)}Ze.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function uh(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 fh(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],c=a[2].replace(/<[^>]+>/g,"").trim(),f=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}c&&l&&!l.startsWith("/")&&i.push({title:c,url:l,snippet:f,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,c=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let f=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!c.has(f)&&!f.includes("duckduckgo.com")&&(c.add(f),i.push({title:d,url:f,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function zn(t,e=5){let r=lh(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>uh(t,e)},{name:"duckduckgo",fn:()=>fh(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return ch(t,i),i}catch{}return[]}function da(){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 zn(e.trim(),r);if(n.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let s=[`Search results for: "${e}" (${n.length} results, source: ${n[0].source})`,""];for(let i=0;i<n.length;i++){let o=n[i];s.push(`[${i+1}] ${o.title}`),s.push(` ${o.url}`),o.snippet&&s.push(` ${o.snippet}`),s.push("")}return{success:!0,output:s.join(`
96
- `)}}catch(n){return{success:!1,output:"",error:`Search failed: ${n instanceof Error?n.message:String(n)}`}}}}}var ge=k(require("fs")),ya=k(require("path")),pa=50*1024*1024,ha=4e4;function ma(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=Fe(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=Fe(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=Fe(l[1]));let c=e.match(/\/Creator\s*\(([^)]*)\)/);c&&(r.creator=Fe(c[1]));let f=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=f.exec(e))!==null;){let p=d[1],u=ga(p);u.trim()&&n.push(u);try{let m=require("zlib"),g=Buffer.from(p,"latin1"),x=m.inflateSync(g).toString("latin1"),b=ga(x);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 ch=3600*1e3,Qe=new Map;function uh(t){let e=Qe.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>ch?(Qe.delete(t.toLowerCase().trim()),null):e.results:null}function fh(t,e){if(Qe.size>200){let r=Qe.keys().next().value;r!==void 0&&Qe.delete(r)}Qe.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function dh(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 ph(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],c=a[2].replace(/<[^>]+>/g,"").trim(),f=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}c&&l&&!l.startsWith("/")&&i.push({title:c,url:l,snippet:f,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,c=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let f=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!c.has(f)&&!f.includes("duckduckgo.com")&&(c.add(f),i.push({title:d,url:f,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function zn(t,e=5){let r=uh(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>dh(t,e)},{name:"duckduckgo",fn:()=>ph(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return fh(t,i),i}catch{}return[]}function ma(){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 zn(e.trim(),r);if(n.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let s=[`Search results for: "${e}" (${n.length} results, source: ${n[0].source})`,""];for(let i=0;i<n.length;i++){let o=n[i];s.push(`[${i+1}] ${o.title}`),s.push(` ${o.url}`),o.snippet&&s.push(` ${o.snippet}`),s.push("")}return{success:!0,output:s.join(`
96
+ `)}}catch(n){return{success:!1,output:"",error:`Search failed: ${n instanceof Error?n.message:String(n)}`}}}}}var ge=A(require("fs")),Sa=A(require("path")),ga=50*1024*1024,ya=4e4;function wa(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=Fe(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=Fe(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=Fe(l[1]));let c=e.match(/\/Creator\s*\(([^)]*)\)/);c&&(r.creator=Fe(c[1]));let f=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=f.exec(e))!==null;){let p=d[1],u=ba(p);u.trim()&&n.push(u);try{let m=require("zlib"),g=Buffer.from(p,"latin1"),x=m.inflateSync(g).toString("latin1"),b=ba(x);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 ga(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(Fe(n[1]));let s=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(n=s.exec(t))!==null;){let l=n[1].match(/\(([^)]*)\)/g);if(l){let c=l.map(f=>Fe(f.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(Fe(n[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
100
+ `).trim(),pages:s,metadata:r}}function ba(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(Fe(n[1]));let s=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(n=s.exec(t))!==null;){let l=n[1].match(/\(([^)]*)\)/g);if(l){let c=l.map(f=>Fe(f.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(Fe(n[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
101
101
  `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function Fe(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 wa(t){let e=r=>ya.resolve(t,r);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async r=>{let n=e(r.path);if(!ge.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};if(!n.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${r.path}`};let s=ge.statSync(n);if(s.size>pa)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${pa/1024/1024}MB)`};try{let i=ge.readFileSync(n),{text:o,pages:a,metadata:l}=ma(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
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 xa(t){let e=r=>Sa.resolve(t,r);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async r=>{let n=e(r.path);if(!ge.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};if(!n.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${r.path}`};let s=ge.statSync(n);if(s.size>ga)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${ga/1024/1024}MB)`};try{let i=ge.readFileSync(n),{text:o,pages:a,metadata:l}=wa(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 c=o;return c.length>ha&&(c=c.slice(0,ha)+`
104
+ [No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let c=o;return c.length>ya&&(c=c.slice(0,ya)+`
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
- ${c}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let n=e(r.path);if(!ge.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=ge.statSync(n),i=ge.readFileSync(n),{pages:o,metadata:a}=ma(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 Sa=require("child_process"),or=k(require("fs")),_a=k(require("os")),va=k(require("path")),ka=1e4,ba=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 xa={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 dh(t,e,r=ka){let n=xa[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(xa).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=_a.tmpdir(),i=va.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{or.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let c=(0,Sa.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),f="",d="";c.stdout?.on("data",h=>{f+=h}),c.stderr?.on("data",h=>{d+=h}),c.on("close",h=>{let p=Date.now()-a;l({success:h===0,stdout:f.slice(0,ba),stderr:d.slice(0,ba/2),exitCode:h??1,duration:p,language:e})}),c.on("error",h=>{let p=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:p,language:e})})})}finally{try{or.unlinkSync(i)}catch{}}}function ph(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 $a(){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()||ph(e),n=Math.min(Math.max(1e3,t.timeout||ka),3e4),s=await dh(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
+ ${c}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let n=e(r.path);if(!ge.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=ge.statSync(n),i=ge.readFileSync(n),{pages:o,metadata:a}=wa(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 ka=require("child_process"),or=A(require("fs")),$a=A(require("os")),Ta=A(require("path")),Ca=1e4,_a=16e3;function et(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 va={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>et("tsx")?`tsx "${t}"`:et("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=>et("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>et("python3")||et("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>et("bash")}};async function hh(t,e,r=Ca){let n=va[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(va).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=$a.tmpdir(),i=Ta.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{or.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let c=(0,ka.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),f="",d="";c.stdout?.on("data",h=>{f+=h}),c.stderr?.on("data",h=>{d+=h}),c.on("close",h=>{let p=Date.now()-a;l({success:h===0,stdout:f.slice(0,_a),stderr:d.slice(0,_a/2),exitCode:h??1,duration:p,language:e})}),c.on("error",h=>{let p=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:p,language:e})})})}finally{try{or.unlinkSync(i)}catch{}}}function mh(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 Aa(){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()||mh(e),n=Math.min(Math.max(1e3,t.timeout||Ca),3e4),s=await hh(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 ar=k(require("fs")),le=k(require("path")),hh=15*1024*1024,mh=15e3;function gh(t,e){if(/image\/png/i.test(t))return".png";if(/image\/jpe?g/i.test(t))return".jpg";if(/image\/webp/i.test(t))return".webp";if(/image\/gif/i.test(t))return".gif";if(/image\/svg\+xml/i.test(t))return".svg";try{return le.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function yh(t){let e="";try{let r=new URL(t);e=`${r.protocol}//${r.host}/`}catch{e=""}return{"User-Agent":"HablasBot/2.0 (+https://hablas.dev)",Accept:"image/*,text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",...e?{Referer:e}:{}}}function wh(t,e){let r=[/<meta[^>]+property=["']og:image["'][^>]+content=["']([^"']+)["']/i,/<meta[^>]+name=["']twitter:image["'][^>]+content=["']([^"']+)["']/i,/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/i,/<img[^>]+src=["']([^"']+)["']/i];for(let n of r){let s=t.match(n);if(s?.[1])try{return new URL(s[1],e).href}catch{}}return null}async function Ta(t){let e=await fetch(t,{signal:AbortSignal.timeout(mh),redirect:"follow",headers:yh(t)});if(!e.ok)throw new Error(`HTTP ${e.status} while downloading asset`);let r=e.headers.get("content-type")||"",n=e.url||t;if(/text\/html|application\/xhtml\+xml/i.test(r)){let o=await e.text(),a=wh(o,n);if(!a)throw new Error("HTML page did not expose a direct image candidate");return Ta(a)}let s=await e.arrayBuffer(),i=Buffer.from(s);if(i.length>hh)throw new Error(`asset too large: ${Math.round(i.length/1024/1024)}MB`);return{bytes:i,contentType:r,finalUrl:n}}function Ca(t){return{name:"download_asset",description:"Download an external asset such as an image or file from a URL and save it inside the project. If a page URL is provided instead of a direct image URL, the tool will try to extract a direct image candidate from standard meta tags before downloading.",safety:"confirm",parameters:{url:{type:"string",description:"Public URL of the asset or image page",required:!0},path:{type:"string",description:"Target project-relative path, e.g. public/hero.jpg or assets/bg.webp",required:!0}},execute:async e=>{let r=String(e.url||""),n=String(e.path||"");if(!r)return{success:!1,output:"",error:"url is required"};if(!n)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(r))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let{bytes:s,contentType:i,finalUrl:o}=await Ta(r),a=le.resolve(t,n),c=le.extname(a)?a:a+gh(i,o);return ar.mkdirSync(le.dirname(c),{recursive:!0}),ar.writeFileSync(c,s),{success:!0,output:`Downloaded asset: ${le.relative(t,c)||le.basename(c)}
111
+ `),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var ar=A(require("fs")),ce=A(require("path")),gh=15*1024*1024,yh=15e3;function wh(t,e){if(/image\/png/i.test(t))return".png";if(/image\/jpe?g/i.test(t))return".jpg";if(/image\/webp/i.test(t))return".webp";if(/image\/gif/i.test(t))return".gif";if(/image\/svg\+xml/i.test(t))return".svg";try{return ce.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function bh(t){let e="";try{let r=new URL(t);e=`${r.protocol}//${r.host}/`}catch{e=""}return{"User-Agent":"HablasBot/2.0 (+https://hablas.dev)",Accept:"image/*,text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",...e?{Referer:e}:{}}}function Sh(t,e){let r=[/<meta[^>]+property=["']og:image["'][^>]+content=["']([^"']+)["']/i,/<meta[^>]+name=["']twitter:image["'][^>]+content=["']([^"']+)["']/i,/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/i,/<img[^>]+src=["']([^"']+)["']/i];for(let n of r){let s=t.match(n);if(s?.[1])try{return new URL(s[1],e).href}catch{}}return null}async function Ea(t){let e=await fetch(t,{signal:AbortSignal.timeout(yh),redirect:"follow",headers:bh(t)});if(!e.ok)throw new Error(`HTTP ${e.status} while downloading asset`);let r=e.headers.get("content-type")||"",n=e.url||t;if(/text\/html|application\/xhtml\+xml/i.test(r)){let o=await e.text(),a=Sh(o,n);if(!a)throw new Error("HTML page did not expose a direct image candidate");return Ea(a)}let s=await e.arrayBuffer(),i=Buffer.from(s);if(i.length>gh)throw new Error(`asset too large: ${Math.round(i.length/1024/1024)}MB`);return{bytes:i,contentType:r,finalUrl:n}}function Oa(t){return{name:"download_asset",description:"Download an external asset such as an image or file from a URL and save it inside the project. If a page URL is provided instead of a direct image URL, the tool will try to extract a direct image candidate from standard meta tags before downloading.",safety:"confirm",parameters:{url:{type:"string",description:"Public URL of the asset or image page",required:!0},path:{type:"string",description:"Target project-relative path, e.g. public/hero.jpg or assets/bg.webp",required:!0}},execute:async e=>{let r=String(e.url||""),n=String(e.path||"");if(!r)return{success:!1,output:"",error:"url is required"};if(!n)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(r))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let{bytes:s,contentType:i,finalUrl:o}=await Ea(r),a=ce.resolve(t,n),c=ce.extname(a)?a:a+wh(i,o);return ar.mkdirSync(ce.dirname(c),{recursive:!0}),ar.writeFileSync(c,s),{success:!0,output:`Downloaded asset: ${ce.relative(t,c)||ce.basename(c)}
112
112
  Final source: ${o}
113
113
  Type: ${i||"unknown"}
114
- Size: ${s.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${s?.message||String(s)}`}}}}}var lr=k(require("fs")),_t=k(require("path"));var bh=15e3,xh=1024*1024,Sh=["images.unsplash.com","unsplash.com","images.pexels.com","pexels.com","cdn.pixabay.com","pixabay.com","upload.wikimedia.org","commons.wikimedia.org"],_h=["rose","roses","tulip","tulips","lily","lilies","bouquet","flower","flowers","floral","blossom","petals","garden"],vh=["coffee","cup","fashion","dress","clothes","makeup","food","burger","shoes","bag","car","watch"];function kh(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(Boolean)}function Ma(t,e){let r=kh(t.join(" ")),n=[...new Set(r.filter(o=>_h.includes(o)))],s=[...new Set(r.filter(o=>vh.includes(o)))],i=0;return i+=n.length*12,i-=s.length*18,e==="hero"&&r.includes("wallpaper")&&(i+=10),e==="hero"&&r.includes("background")&&(i+=8),e==="product"&&(r.includes("bouquet")||r.includes("closeup")||r.includes("close"))&&(i+=8),{score:i,positives:n,negatives:s}}function Pa(t){try{let e=new URL(t).hostname.toLowerCase();return Sh.some(r=>e===r||e.endsWith("."+r))}catch{return!1}}function Ea(t){let e=String(t||"").toLowerCase();return e.includes("hero")||e.includes("wallpaper")||e.includes("background")?"hero":e.includes("product")||e.includes("thumbnail")||e.includes("card")?"product":"generic"}function $h(t,e){if(/image\/png/i.test(t))return".png";if(/image\/jpe?g/i.test(t))return".jpg";if(/image\/webp/i.test(t))return".webp";if(/image\/gif/i.test(t))return".gif";if(/image\/svg\+xml/i.test(t))return".svg";try{return _t.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function Aa(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Oa(t,e){return t[e]|t[e+1]<<8}function Th(t){let e=2;for(;e<t.length-9;){if(t[e]!==255){e++;continue}let r=t[e+1],n=(t[e+2]<<8)+t[e+3];if([192,193,194,195,197,198,199,201,202,203,205,206,207].includes(r))return{height:(t[e+5]<<8)+t[e+6],width:(t[e+7]<<8)+t[e+8]};e+=2+n}return{}}function Ch(t){if(t.toString("ascii",12,16)==="VP8X"&&t.length>=30){let r=1+t.readUIntLE(24,3),n=1+t.readUIntLE(27,3);return{width:r,height:n}}return{}}function Ra(t,e){return t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?{width:Aa(t,16),height:Aa(t,20),ext:".png"}:t.length>=10&&t.toString("ascii",0,3)==="GIF"?{width:Oa(t,6),height:Oa(t,8),ext:".gif"}:t.length>=4&&t[0]===255&&t[1]===216?{...Th(t),ext:".jpg"}:t.length>=16&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?{...Ch(t),ext:".webp"}:{ext:$h(e,"https://x.invalid/file")}}async function Eh(t){let e=await fetch(t,{signal:AbortSignal.timeout(bh),redirect:"follow",headers:{"User-Agent":"HablasBot/2.0 (+https://hablas.dev)",Accept:"image/*,text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",Referer:(()=>{try{let a=new URL(t);return`${a.protocol}//${a.host}/`}catch{return}})()}}),r=e.headers.get("content-type")||"",n=e.url||t,s=await e.arrayBuffer(),i=Buffer.from(s).subarray(0,xh),o=/text\/html|application\/xhtml\+xml/i.test(r)?i.toString("utf-8"):void 0;return{status:e.status,contentType:r,bytes:i,finalUrl:n,html:o}}function Ah(t,e){let r=[],n=[/<meta[^>]+property=["']og:image["'][^>]+content=["']([^"']+)["']/gi,/<meta[^>]+name=["']twitter:image["'][^>]+content=["']([^"']+)["']/gi,/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/gi,/<img[^>]+src=["']([^"']+)["']/gi];for(let s of n){let i;for(;(i=s.exec(t))!==null&&r.length<20;)try{let o=new URL(i[1],e).href;r.includes(o)||r.push(o)}catch{}}return r}function Ia(t,e,r,n){let s=Pa(t),{score:i,positives:o,negatives:a}=Ma([t,e,r],n),l=i+(s?20:0);return/images\.unsplash\.com|images\.pexels\.com|cdn\.pixabay\.com|upload\.wikimedia\.org/i.test(t)&&(l+=10),/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(t)&&(l+=10),{score:l,positives:o,negatives:a,trusted:s}}function La(t){return[{name:"search_image_candidates",description:"Search and rank image candidates for a target use such as hero wallpaper, product photo, or general flower imagery. Uses trusted-source weighting and keyword scoring to reduce unrelated images.",safety:"safe",parameters:{query:{type:"string",description:"What kind of image is needed",required:!0},kind:{type:"string",description:"hero | product | generic",required:!1},max_results:{type:"number",description:"Maximum ranked candidates to return (default: 5)",required:!1}},execute:async e=>{let r=String(e.query||"").trim();if(!r)return{success:!1,output:"",error:"query is required"};let n=Ea(e.kind),s=Math.min(Math.max(1,Number(e.max_results||5)),10),i=await zn(r,Math.max(10,s));if(i.length===0)return{success:!0,output:`No image candidates found for: "${r}"`};let o=i.map(l=>({...l,...Ia(l.url,l.title,l.snippet,n)})).sort((l,c)=>c.score-l.score).slice(0,s),a=[`Ranked image candidates for: "${r}" (${n})`,""];return o.forEach((l,c)=>{a.push(`[${c+1}] score=${l.score} trusted=${l.trusted?"yes":"no"}`),a.push(` ${l.title}`),a.push(` ${l.url}`),l.positives.length&&a.push(` positive: ${l.positives.join(", ")}`),l.negatives.length&&a.push(` negative: ${l.negatives.join(", ")}`),l.snippet&&a.push(` snippet: ${l.snippet}`),a.push("")}),{success:!0,output:a.join(`
115
- `)}}},{name:"inspect_image",description:"Inspect a remote or local image candidate before adoption. Returns content type, dimensions if known, source quality hints, keyword matches, direct-image status, and suitability score.",safety:"safe",parameters:{source:{type:"string",description:"Remote URL or local project-relative path",required:!0},kind:{type:"string",description:"hero | product | generic",required:!1}},execute:async e=>{let r=String(e.source||"").trim();if(!r)return{success:!1,output:"",error:"source is required"};let n=Ea(e.kind),s="unknown",i,o,a=!1,l=!1,c=[],f=[],d=0,h="",p=[],u=r;try{if(/^https?:\/\//i.test(r)){let g=await Eh(r);u=g.finalUrl,s=g.contentType||"unknown",a=/^image\//i.test(s)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(u),l=Pa(u);let x=Ia(u,"","",n);if(c=x.positives,f=x.negatives,d=x.score,g.html)p=Ah(g.html,u).slice(0,8),h=a?"HTML page detected but candidate may still be usable after extracting a direct image URL.":"This is an HTML page, not a direct image. Use one of the extracted direct asset URLs.";else{let b=Ra(g.bytes,s);i=b.width,o=b.height,i&&o&&(n==="hero"&&i>=1200&&o>=600&&(d+=12),n==="product"&&i>=500&&o>=500&&(d+=8)),h=a?"Looks suitable for download if the score matches the target use.":"Not a strong direct image candidate."}}else{let g=_t.resolve(t,r);if(!lr.existsSync(g))return{success:!1,output:"",error:`local file not found: ${r}`};let x=lr.readFileSync(g),b=_t.extname(g).toLowerCase();s=b===".png"?"image/png":b===".jpg"||b===".jpeg"?"image/jpeg":b===".webp"?"image/webp":b===".gif"?"image/gif":b===".svg"?"image/svg+xml":"application/octet-stream",a=!0,u=r;let S=Ra(x,s);i=S.width,o=S.height;let _=Ma([r],n);c=_.positives,f=_.negatives,d=_.score+10,i&&o&&(n==="hero"&&i>=1200&&o>=600&&(d+=12),n==="product"&&i>=500&&o>=500&&(d+=8)),h="Local asset inspection complete."}let m=[`Source: ${u}`,`Kind: ${n}`,`Content-Type: ${s}`,`Direct image: ${a?"yes":"no"}`,`Trusted source: ${l?"yes":"no"}`,i&&o?`Dimensions: ${i}x${o}`:"Dimensions: unknown",`Suitability score: ${d}`,c.length?`Positive signals: ${c.join(", ")}`:"Positive signals: none",f.length?`Negative signals: ${f.join(", ")}`:"Negative signals: none",`Recommendation: ${h||"No recommendation"}`];return p.length&&(m.push("Extracted direct candidates:"),p.forEach((g,x)=>m.push(` ${x+1}. ${g}`))),{success:!0,output:m.join(`
116
- `)}}catch(m){return{success:!1,output:"",error:`image inspection failed: ${m?.message||String(m)}`}}}}]}var et=class{tools=new Map;constructor(e,r){let n=Xo(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",ra(e,r)),this.tools.set("search_codebase",na(e)),this.tools.set("detect_bugs",oa(e)),this.tools.set("web_search",da());for(let s of fa())this.tools.set(s.name,s);for(let s of wa(e))this.tools.set(s.name,s);for(let s of $a())this.tools.set(s.name,s);this.tools.set("download_asset",Ca(e));for(let s of La(e))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(`
114
+ Size: ${s.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${s?.message||String(s)}`}}}}}var lr=A(require("fs")),_t=A(require("path"));var xh=15e3,_h=["images.unsplash.com","unsplash.com","images.pexels.com","pexels.com","cdn.pixabay.com","pixabay.com","upload.wikimedia.org","commons.wikimedia.org"],vh=["rose","roses","tulip","tulips","lily","lilies","bouquet","flower","flowers","floral","blossom","petals","garden"],kh=["coffee","cup","fashion","dress","clothes","makeup","food","burger","shoes","bag","car","watch"];function $h(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(Boolean)}function ja(t,e){let r=$h(t.join(" ")),n=[...new Set(r.filter(o=>vh.includes(o)))],s=[...new Set(r.filter(o=>kh.includes(o)))],i=0;return i+=n.length*12,i-=s.length*18,e==="hero"&&r.includes("wallpaper")&&(i+=10),e==="hero"&&r.includes("background")&&(i+=8),e==="product"&&(r.includes("bouquet")||r.includes("closeup")||r.includes("close"))&&(i+=8),{score:i,positives:n,negatives:s}}function Jn(t){try{let e=new URL(t).hostname.toLowerCase();return _h.some(r=>e===r||e.endsWith("."+r))}catch{return!1}}function Ra(t){let e=String(t||"").toLowerCase();return e.includes("hero")||e.includes("wallpaper")||e.includes("background")?"hero":e.includes("product")||e.includes("thumbnail")||e.includes("card")?"product":"generic"}function Th(t,e){if(/image\/png/i.test(t))return".png";if(/image\/jpe?g/i.test(t))return".jpg";if(/image\/webp/i.test(t))return".webp";if(/image\/gif/i.test(t))return".gif";if(/image\/svg\+xml/i.test(t))return".svg";try{return _t.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function Ia(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Ma(t,e){return t[e]|t[e+1]<<8}function Ch(t){let e=2;for(;e<t.length-9;){if(t[e]!==255){e++;continue}let r=t[e+1],n=(t[e+2]<<8)+t[e+3];if([192,193,194,195,197,198,199,201,202,203,205,206,207].includes(r))return{height:(t[e+5]<<8)+t[e+6],width:(t[e+7]<<8)+t[e+8]};e+=2+n}return{}}function Ah(t){if(t.toString("ascii",12,16)==="VP8X"&&t.length>=30){let r=1+t.readUIntLE(24,3),n=1+t.readUIntLE(27,3);return{width:r,height:n}}return{}}function Kn(t,e){return t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?{width:Ia(t,16),height:Ia(t,20),ext:".png"}:t.length>=10&&t.toString("ascii",0,3)==="GIF"?{width:Ma(t,6),height:Ma(t,8),ext:".gif"}:t.length>=4&&t[0]===255&&t[1]===216?{...Ch(t),ext:".jpg"}:t.length>=16&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?{...Ah(t),ext:".webp"}:{ext:Th(e,"https://x.invalid/file")}}async function Pa(t){let e=await fetch(t,{signal:AbortSignal.timeout(xh),redirect:"follow",headers:{"User-Agent":"HablasBot/2.0 (+https://hablas.dev)",Accept:"image/*,text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",Referer:(()=>{try{let a=new URL(t);return`${a.protocol}//${a.host}/`}catch{return}})()}}),r=e.headers.get("content-type")||"",n=e.url||t,s=await e.arrayBuffer(),i=Buffer.from(s).subarray(0,1024*1024),o=/text\/html|application\/xhtml\+xml/i.test(r)?i.toString("utf-8"):void 0;return{status:e.status,contentType:r,bytes:i,finalUrl:n,html:o}}function Eh(t,e){let r=[],n=[/<meta[^>]+property=["']og:image["'][^>]+content=["']([^"']+)["']/gi,/<meta[^>]+name=["']twitter:image["'][^>]+content=["']([^"']+)["']/gi,/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/gi,/<img[^>]+src=["']([^"']+)["']/gi];for(let s of n){let i;for(;(i=s.exec(t))!==null&&r.length<20;)try{let o=new URL(i[1],e).href;r.includes(o)||r.push(o)}catch{}}return r}function Gn(t,e,r,n){let s=Jn(t),{score:i,positives:o,negatives:a}=ja([t,e,r],n),l=i+(s?20:0);return/images\.unsplash\.com|images\.pexels\.com|cdn\.pixabay\.com|upload\.wikimedia\.org/i.test(t)&&(l+=10),/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(t)&&(l+=10),{score:l,positives:o,negatives:a,trusted:s}}function Oh(t){let e=t.trim(),r=[e],n=e.indexOf("{"),s=e.lastIndexOf("}");n!==-1&&s!==-1&&s>n&&r.push(e.slice(n,s+1));for(let i of r)try{return JSON.parse(i)}catch{}return null}function Rh(t){return`You are Hablas Vision, an internal image-inspection layer for a flower-store engineering agent.
115
+ Return STRICT JSON only with these keys:
116
+ {
117
+ "sourceKind": "flower|bouquet|tulip|rose|lily|mixed|wallpaper|non-flower|unclear",
118
+ "primarySubject": "short description",
119
+ "flowerRelevant": true,
120
+ "recommendedUse": "hero|product|generic|reject",
121
+ "confidence": 0.0,
122
+ "issues": ["..."],
123
+ "summary": "one short sentence"
124
+ }
125
+ Rules:
126
+ - Do not add markdown.
127
+ - Do not add commentary.
128
+ - If the image is unrelated (coffee, clothes, food, lifestyle unrelated to flowers), set flowerRelevant=false and recommendedUse=reject.
129
+ - For kind=${t}, judge whether the image fits that use.
130
+ - Be strict, not generous.`}function Ih(t,e){return[{role:"system",content:Rh(e)},{role:"user",content:[{type:"text",text:`Inspect this image for a ${e} flower-store use case.`},{type:"image_url",image_url:{url:t}}]}]}function Mh(t,e){return`data:${e};base64,${t.toString("base64")}`}async function La(t,e,r,n,s){let i=t.provider==="nvidia"?ee.apiUrl:t.apiUrl;if(!i)throw new Error("No OpenAI-compatible API URL available for vision call");let o={"Content-Type":"application/json"};t.apiKey&&(o.Authorization=`Bearer ${t.apiKey}`);let a=await fetch(i.replace(/\/+$/,"")+"/chat/completions",{method:"POST",headers:o,signal:AbortSignal.timeout(3e4),body:JSON.stringify({model:e,messages:Ih(Mh(r,n),s),temperature:.1,max_tokens:500})});if(!a.ok)throw new Error(`Vision HTTP ${a.status}`);let c=(await a.json())?.choices?.[0]?.message?.content??"",f=Oh(String(c));if(!f)throw new Error("Vision response was not valid JSON");return{model:e,success:!0,sourceKind:String(f.sourceKind||"unclear"),primarySubject:String(f.primarySubject||""),flowerRelevant:!!f.flowerRelevant,recommendedUse:String(f.recommendedUse||"generic"),confidence:Number(f.confidence||0),issues:Array.isArray(f.issues)?f.issues.map(String):[],summary:String(f.summary||""),raw:String(c)}}function Ph(t,e){if(!e||!e.success)return t;let r=t.confidence>=e.confidence?t:e,n=[...new Set([...t.issues||[],...e.issues||[]])];return{...r,issues:n,summary:r.summary||t.summary||e.summary}}function Da(t,e){return[{name:"search_image_candidates",description:"Search and rank image candidates for a target use such as hero wallpaper, product photo, or general flower imagery. Uses trusted-source weighting and keyword scoring to reduce unrelated images.",safety:"safe",parameters:{query:{type:"string",description:"What kind of image is needed",required:!0},kind:{type:"string",description:"hero | product | generic",required:!1},max_results:{type:"number",description:"Maximum ranked candidates to return (default: 5)",required:!1}},execute:async r=>{let n=String(r.query||"").trim();if(!n)return{success:!1,output:"",error:"query is required"};let s=Ra(r.kind),i=Math.min(Math.max(1,Number(r.max_results||5)),10),o=await zn(n,Math.max(10,i));if(o.length===0)return{success:!0,output:`No image candidates found for: "${n}"`};let a=o.map(c=>({...c,...Gn(c.url,c.title,c.snippet,s)})).sort((c,f)=>f.score-c.score).slice(0,i),l=[`Ranked image candidates for: "${n}" (${s})`,""];return a.forEach((c,f)=>{l.push(`[${f+1}] score=${c.score} trusted=${c.trusted?"yes":"no"}`),l.push(` ${c.title}`),l.push(` ${c.url}`),c.positives.length&&l.push(` positive: ${c.positives.join(", ")}`),c.negatives.length&&l.push(` negative: ${c.negatives.join(", ")}`),c.snippet&&l.push(` snippet: ${c.snippet}`),l.push("")}),{success:!0,output:l.join(`
131
+ `)}}},{name:"inspect_image",description:"Inspect a remote or local image candidate before adoption. Returns metadata, suitability score, trusted-source signals, and can internally run Hablas Vision for stricter semantic validation.",safety:"safe",parameters:{source:{type:"string",description:"Remote URL or local project-relative path",required:!0},kind:{type:"string",description:"hero | product | generic",required:!1},use_vision:{type:"string",description:"true or false; defaults to true",required:!1}},execute:async r=>{let n=String(r.source||"").trim();if(!n)return{success:!1,output:"",error:"source is required"};let s=Ra(r.kind),i=String(r.use_vision??"true").toLowerCase()!=="false",o="unknown",a,l,c=!1,f=!1,d=[],h=[],p=0,u="",m=[],g=n,x=null,b=null,S=null,_=null;try{if(/^https?:\/\//i.test(n)){let $=await Pa(n);g=$.finalUrl,o=$.contentType||"unknown",c=/^image\//i.test(o)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(g),f=Jn(g);let C=Gn(g,"","",s);if(d=C.positives,h=C.negatives,p=C.score,$.html)if(m=Eh($.html,g).slice(0,8),m.length>0){let E=m.map(j=>({url:j,...Gn(j,"","",s)})).sort((j,D)=>D.score-j.score)[0],T=await Pa(E.url);g=T.finalUrl,o=T.contentType||o,x=T.bytes,c=/^image\//i.test(o)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(g),f=Jn(g),d=E.positives,h=E.negatives,p=E.score;let M=Kn(x,o);a=M.width,l=M.height,u="Resolved direct image candidate from HTML page metadata."}else u=c?"HTML page detected but candidate may still be usable after extracting a direct image URL.":"This is an HTML page, not a direct image. No direct candidate was found.";else{x=$.bytes;let E=Kn(x,o);a=E.width,l=E.height,a&&l&&(s==="hero"&&a>=1200&&l>=600&&(p+=12),s==="product"&&a>=500&&l>=500&&(p+=8)),u=c?"Looks suitable for download if the score matches the target use.":"Not a strong direct image candidate."}}else{let $=_t.resolve(t,n);if(!lr.existsSync($))return{success:!1,output:"",error:`local file not found: ${n}`};x=lr.readFileSync($).subarray(0,e.vision.maxImageBytes);let C=_t.extname($).toLowerCase();o=C===".png"?"image/png":C===".jpg"||C===".jpeg"?"image/jpeg":C===".webp"?"image/webp":C===".gif"?"image/gif":C===".svg"?"image/svg+xml":"application/octet-stream",c=!0,g=n;let E=Kn(x,o);a=E.width,l=E.height;let T=ja([n],s);d=T.positives,h=T.negatives,p=T.score+10,a&&l&&(s==="hero"&&a>=1200&&l>=600&&(p+=12),s==="product"&&a>=500&&l>=500&&(p+=8)),u="Local asset inspection complete."}if(i&&e.vision.enabled&&x&&/^image\//i.test(o)){try{b=await La(e,e.vision.primaryModel,x.subarray(0,e.vision.maxImageBytes),o,s)}catch($){b={model:e.vision.primaryModel,success:!1,sourceKind:"unclear",primarySubject:"",flowerRelevant:!1,recommendedUse:"reject",confidence:0,issues:[String($?.message||$)],summary:"Primary vision model failed."}}if(!b.success||b.confidence<.6||!b.flowerRelevant)try{S=await La(e,e.vision.fallbackModel,x.subarray(0,e.vision.maxImageBytes),o,s)}catch($){S={model:e.vision.fallbackModel,success:!1,sourceKind:"unclear",primarySubject:"",flowerRelevant:!1,recommendedUse:"reject",confidence:0,issues:[String($?.message||$)],summary:"Fallback vision model failed."}}b?.success&&(_=Ph(b,S&&S.success?S:void 0),_.flowerRelevant||(p-=40),_.recommendedUse==="reject"&&(p-=25),_.recommendedUse===s&&(p+=18),u=_.summary||u)}let v=[`Source: ${g}`,`Kind: ${s}`,`Content-Type: ${o}`,`Direct image: ${c?"yes":"no"}`,`Trusted source: ${f?"yes":"no"}`,a&&l?`Dimensions: ${a}x${l}`:"Dimensions: unknown",`Suitability score: ${p}`,d.length?`Positive signals: ${d.join(", ")}`:"Positive signals: none",h.length?`Negative signals: ${h.join(", ")}`:"Negative signals: none",`Recommendation: ${u||"No recommendation"}`];return m.length&&(v.push("Extracted direct candidates:"),m.slice(0,5).forEach(($,C)=>v.push(` ${C+1}. ${$}`))),b&&(v.push("Vision primary:"),v.push(` model: ${b.model}`),v.push(` success: ${b.success?"yes":"no"}`),v.push(` subject: ${b.primarySubject||"unknown"}`),v.push(` flowerRelevant: ${b.flowerRelevant}`),v.push(` recommendedUse: ${b.recommendedUse}`),v.push(` confidence: ${b.confidence}`),b.issues.length&&v.push(` issues: ${b.issues.join(", ")}`)),S&&(v.push("Vision fallback:"),v.push(` model: ${S.model}`),v.push(` success: ${S.success?"yes":"no"}`),v.push(` subject: ${S.primarySubject||"unknown"}`),v.push(` flowerRelevant: ${S.flowerRelevant}`),v.push(` recommendedUse: ${S.recommendedUse}`),v.push(` confidence: ${S.confidence}`),S.issues.length&&v.push(` issues: ${S.issues.join(", ")}`)),_&&(v.push("Merged vision verdict:"),v.push(` subject: ${_.primarySubject||"unknown"}`),v.push(` flowerRelevant: ${_.flowerRelevant}`),v.push(` recommendedUse: ${_.recommendedUse}`),v.push(` confidence: ${_.confidence}`),v.push(` summary: ${_.summary}`)),{success:!0,output:v.join(`
132
+ `)}}catch(v){return{success:!1,output:"",error:`image inspection failed: ${v?.message||String(v)}`}}}}]}var tt=class{tools=new Map;constructor(e,r){let n=ea(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",ia(e,r)),this.tools.set("search_codebase",oa(e)),this.tools.set("detect_bugs",ca(e)),this.tools.set("web_search",ma());for(let s of ha())this.tools.set(s.name,s);for(let s of xa(e))this.tools.set(s.name,s);for(let s of Aa())this.tools.set(s.name,s);this.tools.set("download_asset",Oa(e));for(let s of Da(e,r))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(`
117
133
  `);return`- ${r.name} [${r.safety}]: ${r.description}
118
134
  ${n}`}).join(`
119
135
 
120
- `)}};var Da=k(require("crypto"));function Kn(t){return Math.ceil(t.length/3.5)}function vt(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
121
- ... [truncated to fit context budget]`}var tt=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,r,n){let s=this.computeHash(r),i=this.cache.get(e);if(i&&i.hash===s){i.lastUsed=Date.now(),i.accessCount++;return}let o=Kn(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=vt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
136
+ `)}};var Fa=A(require("crypto"));function Yn(t){return Math.ceil(t.length/3.5)}function vt(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
137
+ ... [truncated to fit context budget]`}var rt=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=Yn(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=vt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
122
138
  ${l}`),s+=a}}continue}i.push(`--- ${o.path} ---
123
139
  ${o.content}`),s+=o.tokenCount}return i.join(`
124
140
 
125
141
  `)}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(c=>i.length===0?!0:i.some(f=>c.path.includes(f))).sort((c,f)=>this.computeScore(f)-this.computeScore(c)),a=0,l=[];for(let c of o){if(a+c.tokenCount>n)break;l.push(`--- ${c.path} ---
126
142
  ${c.content}`),a+=c.tokenCount}return l.join(`
127
143
 
128
- `)}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=Kn(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 Da.createHash("md5").update(e).digest("hex")}};var Oh=0;function kt(){return`msg_${Date.now()}_${++Oh}`}function rt(t){return Math.ceil(t.length/4)}var nt=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,r=50,n=32e3){this.maxMessages=r,this.maxTokens=n,this.sessionId=`session_${Date.now()}`;let s=rt(e);this.messages.push({id:kt(),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=kt(),s=rt(e);return this.messages.push({id:n,role:"user",content:e,timestamp:Date.now(),priority:r?.priority||"high",tokenEstimate:s,compressed:!1,tags:r?.tags||["user-input"]}),this.totalTokens+=s,this.trimIfNeeded(),n}addAssistantMessage(e,r,n){let s=kt(),i=rt(e),o={id:s,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:n||"hablas",tokenEstimate:i,compressed:!1,tags:n?[`agent:${n}`]:["assistant"]};return r&&r.length>0&&(o.tool_calls=r,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,n&&this.agentMessageCounts.set(n,(this.agentMessageCounts.get(n)||0)+1),this.trimIfNeeded(),s}addToolMessage(e,r){let n=kt(),s=rt(e);return this.messages.push({id:n,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:s,compressed:!1,tags:r?[`tool:${r}`]:["tool-result"]}),this.totalTokens+=s,this.trimIfNeeded(),n}getMessages(){return this.messages.map(e=>{let r={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls),r})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(r=>r.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let r=rt(e),n=this.messages.filter(s=>s.priority==="critical"&&s.role!=="system");this.messages=[{id:kt(),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)+`
144
+ `)}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=Yn(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 Fa.createHash("md5").update(e).digest("hex")}};var Lh=0;function kt(){return`msg_${Date.now()}_${++Lh}`}function nt(t){return Math.ceil(t.length/4)}var st=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=nt(e);this.messages.push({id:kt(),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=kt(),s=nt(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=kt(),i=nt(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=kt(),s=nt(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=nt(e),n=this.messages.filter(s=>s.priority==="critical"&&s.role!=="system");this.messages=[{id:kt(),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)+`
129
145
  ...(compressed from `+r+" chars)":e.content=e.content.slice(0,400)+`
130
- ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=rt(e.content),this.totalTokens-=n-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,r)=>e+r.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let r=JSON.parse(e);if(!r.messages||!Array.isArray(r.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=r.sessionId||`session_${Date.now()}`,this.messages=r.messages,this.totalTokens=r.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(r.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}};var it=k(require("fs")),ja=k(require("path"));var A=k(require("fs")),O=k(require("path"));function Rh(t){let e=O.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(O.join(t,"requirements.txt"))||A.existsSync(O.join(t,"pyproject.toml")))try{let r=A.existsSync(O.join(t,"requirements.txt"))?A.readFileSync(O.join(t,"requirements.txt"),"utf-8"):"";if(r.includes("django"))return"django";if(r.includes("flask"))return"flask";if(r.includes("fastapi"))return"fastapi"}catch{}if(A.existsSync(O.join(t,"Cargo.toml")))try{if(A.readFileSync(O.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(A.existsSync(O.join(t,"go.mod")))try{if(A.readFileSync(O.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Ih(t){return A.existsSync(O.join(t,"pnpm-lock.yaml"))?"pnpm":A.existsSync(O.join(t,"yarn.lock"))?"yarn":A.existsSync(O.join(t,"bun.lockb"))?"bun":A.existsSync(O.join(t,"package-lock.json"))?"npm":A.existsSync(O.join(t,"Cargo.toml"))?"cargo":A.existsSync(O.join(t,"go.mod"))?"go":A.existsSync(O.join(t,"requirements.txt"))||A.existsSync(O.join(t,"pyproject.toml"))?"pip":"unknown"}function Mh(t){return A.existsSync(O.join(t,"tsconfig.json"))?"TypeScript":A.existsSync(O.join(t,"package.json"))?"JavaScript":A.existsSync(O.join(t,"Cargo.toml"))?"Rust":A.existsSync(O.join(t,"go.mod"))?"Go":A.existsSync(O.join(t,"pyproject.toml"))||A.existsSync(O.join(t,"requirements.txt"))?"Python":"Unknown"}function Ph(t){let e=O.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 st(t){let e=Rh(t),r=Ih(t),n=Mh(t),s=Ph(t),i=A.existsSync(O.join(t,"Dockerfile"))||A.existsSync(O.join(t,"docker-compose.yml"))||A.existsSync(O.join(t,"docker-compose.yaml")),o=A.existsSync(O.join(t,".github","workflows"))||A.existsSync(O.join(t,".gitlab-ci.yml"))||A.existsSync(O.join(t,"Jenkinsfile")),a=A.existsSync(O.join(t,"__tests__"))||A.existsSync(O.join(t,"tests"))||A.existsSync(O.join(t,"test"))||A.existsSync(O.join(t,"spec")),l=A.existsSync(O.join(t,".git")),c=[],f=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of f)A.existsSync(O.join(t,m))&&c.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(O.join(t,m))&&d.push(m);let p=[],u=["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 u)A.existsSync(O.join(t,m))&&p.push(m);return{rootPath:t,framework:e,packageManager:r,language:n,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:s,envFiles:c,configFiles:d,entryPoints:p}}function cr(t){let e=[` Project: ${O.basename(t.rootPath)}`,` Framework: ${t.framework}`,` Language: ${t.language}`,` Package: ${t.packageManager}`,` Git: ${t.hasGit?`\u2713 (${t.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${t.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${t.hasCICD?"\u2713":"\u2717"}`,` Tests: ${t.hasTests?"\u2713":"\u2717"}`];return t.envFiles.length>0&&e.push(` Env files: ${t.envFiles.join(", ")}`),e.join(`
131
- `)}async function ot(t,e){let r=[],n=ja.join(t,"package.json");if(it.existsSync(n))try{let o=JSON.parse(it.readFileSync(n,"utf-8"));r.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&r.push(`Description: ${o.description}`)}catch{}let s=st(t);r.push(`Framework: ${s.framework}`),r.push(`Language: ${s.language}`),r.push(`Package Manager: ${s.packageManager}`),r.push(`Git: ${s.hasGit?s.gitBranch||"present":"absent"}`);let i=Lh(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(`
132
- `)}function Lh(t,e){try{return it.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function at(t,e){return`You are Hablas.
146
+ ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=nt(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 ot=A(require("fs")),Na=A(require("path"));var O=A(require("fs")),R=A(require("path"));function jh(t){let e=R.join(t,"package.json");if(O.existsSync(e))try{let r=JSON.parse(O.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(O.existsSync(R.join(t,"requirements.txt"))||O.existsSync(R.join(t,"pyproject.toml")))try{let r=O.existsSync(R.join(t,"requirements.txt"))?O.readFileSync(R.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(O.existsSync(R.join(t,"Cargo.toml")))try{if(O.readFileSync(R.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(O.existsSync(R.join(t,"go.mod")))try{if(O.readFileSync(R.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Dh(t){return O.existsSync(R.join(t,"pnpm-lock.yaml"))?"pnpm":O.existsSync(R.join(t,"yarn.lock"))?"yarn":O.existsSync(R.join(t,"bun.lockb"))?"bun":O.existsSync(R.join(t,"package-lock.json"))?"npm":O.existsSync(R.join(t,"Cargo.toml"))?"cargo":O.existsSync(R.join(t,"go.mod"))?"go":O.existsSync(R.join(t,"requirements.txt"))||O.existsSync(R.join(t,"pyproject.toml"))?"pip":"unknown"}function Fh(t){return O.existsSync(R.join(t,"tsconfig.json"))?"TypeScript":O.existsSync(R.join(t,"package.json"))?"JavaScript":O.existsSync(R.join(t,"Cargo.toml"))?"Rust":O.existsSync(R.join(t,"go.mod"))?"Go":O.existsSync(R.join(t,"pyproject.toml"))||O.existsSync(R.join(t,"requirements.txt"))?"Python":"Unknown"}function Nh(t){let e=R.join(t,".git","HEAD");if(!O.existsSync(e))return null;try{let r=O.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function it(t){let e=jh(t),r=Dh(t),n=Fh(t),s=Nh(t),i=O.existsSync(R.join(t,"Dockerfile"))||O.existsSync(R.join(t,"docker-compose.yml"))||O.existsSync(R.join(t,"docker-compose.yaml")),o=O.existsSync(R.join(t,".github","workflows"))||O.existsSync(R.join(t,".gitlab-ci.yml"))||O.existsSync(R.join(t,"Jenkinsfile")),a=O.existsSync(R.join(t,"__tests__"))||O.existsSync(R.join(t,"tests"))||O.existsSync(R.join(t,"test"))||O.existsSync(R.join(t,"spec")),l=O.existsSync(R.join(t,".git")),c=[],f=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of f)O.existsSync(R.join(t,m))&&c.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)O.existsSync(R.join(t,m))&&d.push(m);let p=[],u=["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 u)O.existsSync(R.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:c,configFiles:d,entryPoints:p}}function cr(t){let e=[` Project: ${R.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(`
147
+ `)}async function at(t,e){let r=[],n=Na.join(t,"package.json");if(ot.existsSync(n))try{let o=JSON.parse(ot.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=it(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=Uh(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(`
148
+ `)}function Uh(t,e){try{return ot.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function lt(t,e){return`You are Hablas.
133
149
 
134
150
  You are a high-caliber single-agent software engineering runtime created by Abdulmoin Hablas.
135
151
  Your standard is not "assistant quality". Your standard is elite production engineering execution.
@@ -370,32 +386,33 @@ For failures:
370
386
  ====================
371
387
  TASK PROFILE
372
388
  ====================
373
- ${Dh(e)}
389
+ ${qh(e)}
374
390
 
375
391
  ====================
376
392
  CURRENT PROJECT CONTEXT
377
393
  ====================
378
- ${t}`}function Dh(t){return t.kind==="casual"?["- Casual/social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short and natural."].join(`
394
+ ${t}`}function qh(t){return t.kind==="casual"?["- Casual/social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short and natural."].join(`
379
395
  `):t.kind==="read"?["- Read-only or project-inspection task.","- Use tools only to inspect the minimum necessary evidence.","- Keep the final answer factual, grounded, tight, and pleasantly professional."].join(`
380
396
  `):t.kind==="analysis"?["- Analysis / architecture task.","- Prefer reasoning first.","- Inspect files only when they materially improve the recommendation.","- Deliver trade-offs, assumptions, and practical guidance."].join(`
381
397
  `):[t.continuity?"- Continue from existing work. Do not restart the project from zero.":"- Implementation task.",t.oneStepDelivery?"- The user requested one-step delivery with minimal follow-up questions.":"- Ask a clarifying question only if the task is truly blocked.","- Real workspace tool usage is mandatory.","- Do not answer with inline code only if files can be created or modified directly.","- The task is not complete unless the relevant files were inspected and then changed or created when needed.","- Verify changes before claiming completion."].join(`
382
- `)}var jh=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Fh=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,Nh=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Uh=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,qh=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,Bh=/\b(frontend|backend|store|shop|website|web app|landing page|page|component|ui|ux|auth|login|dashboard|api|endpoint|schema|database|project|application|app|image|images|photo|photos|wallpaper|background|hero)\b/i,Hh=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,Wh=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,Fa=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function $t(t){let e=t.trim(),r=e.toLowerCase(),n=Fh.test(r),s=Nh.test(r),i=Uh.test(r)||qh.test(r),o=Bh.test(r),a=Hh.test(r),l=i||n||s||o&&e.length>18&&!Fa.test(r)&&!a,c=a&&!i&&!n&&!s,f=Wh.test(r)||o,d=!l&&!c&&(Fa.test(r)||e.endsWith("?"));return jh.test(e)&&!f&&!l&&!c?{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."}:c?{kind:"analysis",needsTools:f,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:f,reason:f?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||f?{kind:"read",needsTools:f,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:f,reason:f?"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 Vh(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 Na(t){let e=$t(t);return{input:t,profile:e,plan:Vh(t,e)}}var Za=k(require("readline")),se=k(require("fs")),Y=k(require("path")),Qa=k(require("os"));var Gn=k(require("os")),fr=k(require("fs")),ur=k(require("path"));function zh(){let t=[ur.resolve(__dirname,"..","package.json"),ur.resolve(__dirname,"..","..","package.json"),ur.resolve(process.cwd(),"package.json")];for(let e of t)try{if(fr.existsSync(e)){let r=JSON.parse(fr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Ua=zh(),Jn=process.stdout.isTTY===!0,Kh=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",qa=process.stdout.columns||100;Jn&&process.stdout.on("resize",()=>{qa=process.stdout.columns||100});var $e=()=>Math.min(Math.max(qa-4,60),100);function ne(t,e){return!Jn||Kh?t:`${e}${t}\x1B[0m`}var w={strong:t=>ne(t,"\x1B[1;38;5;255m"),muted:t=>ne(t,"\x1B[38;5;242m"),accent:t=>ne(t,"\x1B[38;5;145m"),info:t=>ne(t,"\x1B[38;5;110m"),success:t=>ne(t,"\x1B[38;5;108m"),warning:t=>ne(t,"\x1B[38;5;179m"),error:t=>ne(t,"\x1B[38;5;167m"),primary:t=>ne(t,"\x1B[38;5;253m"),secondary:t=>ne(t,"\x1B[38;5;247m"),border:t=>ne(t,"\x1B[38;5;237m"),code:t=>ne(t,"\x1B[38;5;188m"),line:t=>ne(t,"\x1B[38;5;239m")};function Yn(t,e=2){let r=$e()-e,n=t.split(" "),s=[],i="";for(let o of n)(i+" "+o).trim().length>r&&i?(s.push(" ".repeat(e)+i.trim()),i=o):i+=(i?" ":"")+o;return i&&s.push(" ".repeat(e)+i.trim()),s}function Gh(t){let e=$e();if(!t)return w.border("\u2500".repeat(e));let r=t.replace(/\x1b\[[0-9;]*m/g,""),n=Math.max(0,e-r.length-2),s=Math.floor(n/2),i=n-s;return w.border("\u2500".repeat(s))+" "+t+" "+w.border("\u2500".repeat(i))}function Ba(t,e){let r=Math.min($e(),82),n=e.replace(Gn.homedir(),"~"),s=w.border("\u256D"+"\u2500".repeat(r-2)+"\u256E"),i=w.border("\u251C"+"\u2500".repeat(r-2)+"\u2524"),o=w.border("\u2570"+"\u2500".repeat(r-2)+"\u256F"),a="HABLAS",l="single-agent engineering runtime",c=Math.max(0,Math.floor((r-2-a.length)/2)),f=Math.max(0,Math.floor((r-2-l.length)/2)),d=(h,p="")=>{let u=h.replace(/\x1b\[[0-9;]*m/g,""),m=p.replace(/\x1b\[[0-9;]*m/g,""),g=Math.max(1,r-4-u.length-m.length);return`${w.border("\u2502")} ${h}${" ".repeat(g)}${p} ${w.border("\u2502")}`};return["",s,w.border("\u2502")+" ".repeat(c)+w.strong(a)+" ".repeat(r-2-a.length-c)+w.border("\u2502"),w.border("\u2502")+" ".repeat(f)+w.secondary(l)+" ".repeat(r-2-l.length-f)+w.border("\u2502"),i,d(w.muted(`version v${Ua}`),w.muted(t)),d(w.muted(n)),i,d(w.secondary("Type naturally to get started")),d(w.muted("/help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")),o,""].join(`
383
- `)}function Ha(t){return`
384
- `+Gh(`${w.accent("\u25C6")} ${w.strong("Turn #"+t)}`)}function ct(){return`
385
- ${w.accent("\u25C6")} ${w.strong("Hablas")} ${w.muted("[response]")}`}function Wa(t){return` ${w.accent("\u25C9")} ${w.secondary(t)}`}function lt(t){return t.replace(/`([^`]+)`/g,(e,r)=>w.primary(r)).replace(/\*\*([^*]+)\*\*/g,(e,r)=>w.strong(r))}function Jh(t){return/^\s*\|.*\|\s*$/.test(t)}function Yh(t){let r=t.map(c=>c.trim()).filter(Boolean).map(c=>c.split("|").slice(1,-1).map(f=>f.trim())).filter(c=>!c.every(f=>/^:?-{2,}:?$/.test(f)));if(r.length===0)return[];let n=[];for(let c of r)c.forEach((f,d)=>{let h=f.replace(/\x1b\[[0-9;]*m/g,"").length;n[d]=Math.max(n[d]||0,h)});let s=` ${w.border("\u250C"+n.map(c=>"\u2500".repeat(c+2)).join("\u252C")+"\u2510")}`,i=` ${w.border("\u251C"+n.map(c=>"\u2500".repeat(c+2)).join("\u253C")+"\u2524")}`,o=` ${w.border("\u2514"+n.map(c=>"\u2500".repeat(c+2)).join("\u2534")+"\u2518")}`,a=c=>{let f=c.map((d,h)=>{let p=lt(d),u=p.replace(/\x1b\[[0-9;]*m/g,"").length;return` ${p}${" ".repeat(Math.max(0,n[h]-u))} `});return` ${w.border("\u2502")}${f.join(w.border("\u2502"))}${w.border("\u2502")}`},l=[s,a(r[0])];r.length>1&&l.push(i);for(let c of r.slice(1))l.push(a(c));return l.push(o),l}function Tt(t){let e=t.split(`
386
- `),r=[],n=!1,s="",i=[],o=[],a=()=>{if(!i.length)return;let c=String(i.length).length;r.push(` ${w.border("\u250C"+"\u2500".repeat(Math.max(24,$e()-6)))} ${s?w.accent(s):""}`.trimEnd()),i.forEach((f,d)=>{r.push(` ${w.border("\u2502")} ${w.line(String(d+1).padStart(c)+" \u2502")} ${w.code(f)}`)}),r.push(` ${w.border("\u2514"+"\u2500".repeat(Math.max(24,$e()-6)))}`),i=[]},l=()=>{o.length&&(r.push(...Yh(o)),o=[])};for(let c of e){if(c.trimStart().startsWith("```")){l(),n?(a(),n=!1,s=""):(n=!0,s=c.trimStart().slice(3).trim());continue}if(n){i.push(c);continue}if(Jh(c)){o.push(c);continue}else l();if(!c.trim()){r.push("");continue}if(/^---+$/.test(c.trim())){r.push(` ${w.border("\u2500".repeat(Math.max(28,$e()-6)))}`);continue}if(/^#{1,3}\s/.test(c)){r.push(""),r.push(` ${w.strong(lt(c.replace(/^#{1,3}\s/,"")))}`);continue}if(/^[A-Z][A-Za-z0-9 /&_-]{2,}:$/.test(c.trim())){r.push(` ${w.strong(lt(c.trim()))}`);continue}if(/^[-*]\s/.test(c.trim())){r.push(` ${w.accent("\u25B8")} ${lt(c.trim().slice(2))}`);continue}if(/^\d+\.\s/.test(c.trim())){r.push(` ${lt(c.trim())}`);continue}r.push(...Yn(lt(c),2))}return l(),n&&a(),`
398
+ `)}var Bh=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Hh=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,Wh=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Vh=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,zh=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,Kh=/\b(frontend|backend|store|shop|website|web app|landing page|page|component|ui|ux|auth|login|dashboard|api|endpoint|schema|database|project|application|app|image|images|photo|photos|wallpaper|background|hero)\b/i,Gh=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,Jh=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,Ua=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function $t(t){let e=t.trim(),r=e.toLowerCase(),n=Hh.test(r),s=Wh.test(r),i=Vh.test(r)||zh.test(r),o=Kh.test(r),a=Gh.test(r),l=i||n||s||o&&e.length>18&&!Ua.test(r)&&!a,c=a&&!i&&!n&&!s,f=Jh.test(r)||o,d=!l&&!c&&(Ua.test(r)||e.endsWith("?"));return Bh.test(e)&&!f&&!l&&!c?{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."}:c?{kind:"analysis",needsTools:f,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:f,reason:f?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||f?{kind:"read",needsTools:f,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:f,reason:f?"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 Yh(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 qa(t){let e=$t(t);return{input:t,profile:e,plan:Yh(t,e)}}var el=A(require("readline")),ie=A(require("fs")),Y=A(require("path")),tl=A(require("os"));var Xn=A(require("os")),fr=A(require("fs")),ur=A(require("path"));function Xh(){let t=[ur.resolve(__dirname,"..","package.json"),ur.resolve(__dirname,"..","..","package.json"),ur.resolve(process.cwd(),"package.json")];for(let e of t)try{if(fr.existsSync(e)){let r=JSON.parse(fr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Ba=Xh(),Zn=process.stdout.isTTY===!0,Zh=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",Ha=process.stdout.columns||100;Zn&&process.stdout.on("resize",()=>{Ha=process.stdout.columns||100});var $e=()=>Math.min(Math.max(Ha-4,60),100);function se(t,e){return!Zn||Zh?t:`${e}${t}\x1B[0m`}var w={strong:t=>se(t,"\x1B[1;38;5;255m"),muted:t=>se(t,"\x1B[38;5;242m"),accent:t=>se(t,"\x1B[38;5;145m"),info:t=>se(t,"\x1B[38;5;110m"),success:t=>se(t,"\x1B[38;5;108m"),warning:t=>se(t,"\x1B[38;5;179m"),error:t=>se(t,"\x1B[38;5;167m"),primary:t=>se(t,"\x1B[38;5;253m"),secondary:t=>se(t,"\x1B[38;5;247m"),border:t=>se(t,"\x1B[38;5;237m"),code:t=>se(t,"\x1B[38;5;188m"),line:t=>se(t,"\x1B[38;5;239m")};function Qn(t,e=2){let r=$e()-e,n=t.split(" "),s=[],i="";for(let o of n)(i+" "+o).trim().length>r&&i?(s.push(" ".repeat(e)+i.trim()),i=o):i+=(i?" ":"")+o;return i&&s.push(" ".repeat(e)+i.trim()),s}function Qh(t){let e=$e();if(!t)return w.border("\u2500".repeat(e));let r=t.replace(/\x1b\[[0-9;]*m/g,""),n=Math.max(0,e-r.length-2),s=Math.floor(n/2),i=n-s;return w.border("\u2500".repeat(s))+" "+t+" "+w.border("\u2500".repeat(i))}function Wa(t,e){let r=Math.min($e(),82),n=e.replace(Xn.homedir(),"~"),s=w.border("\u256D"+"\u2500".repeat(r-2)+"\u256E"),i=w.border("\u251C"+"\u2500".repeat(r-2)+"\u2524"),o=w.border("\u2570"+"\u2500".repeat(r-2)+"\u256F"),a="HABLAS",l="single-agent engineering runtime",c=Math.max(0,Math.floor((r-2-a.length)/2)),f=Math.max(0,Math.floor((r-2-l.length)/2)),d=(h,p="")=>{let u=h.replace(/\x1b\[[0-9;]*m/g,""),m=p.replace(/\x1b\[[0-9;]*m/g,""),g=Math.max(1,r-4-u.length-m.length);return`${w.border("\u2502")} ${h}${" ".repeat(g)}${p} ${w.border("\u2502")}`};return["",s,w.border("\u2502")+" ".repeat(c)+w.strong(a)+" ".repeat(r-2-a.length-c)+w.border("\u2502"),w.border("\u2502")+" ".repeat(f)+w.secondary(l)+" ".repeat(r-2-l.length-f)+w.border("\u2502"),i,d(w.muted(`version v${Ba}`),w.muted(t)),d(w.muted(n)),i,d(w.secondary("Type naturally to get started")),d(w.muted("/help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")),o,""].join(`
399
+ `)}function Va(t){return`
400
+ `+Qh(`${w.accent("\u25C6")} ${w.strong("Turn #"+t)}`)}function ut(){return`
401
+ ${w.accent("\u25C6")} ${w.strong("Hablas")} ${w.muted("[response]")}`}function za(t){return` ${w.accent("\u25C9")} ${w.secondary(t)}`}function ct(t){return t.replace(/`([^`]+)`/g,(e,r)=>w.primary(r)).replace(/\*\*([^*]+)\*\*/g,(e,r)=>w.strong(r))}function em(t){return/^\s*\|.*\|\s*$/.test(t)}function tm(t){let r=t.map(c=>c.trim()).filter(Boolean).map(c=>c.split("|").slice(1,-1).map(f=>f.trim())).filter(c=>!c.every(f=>/^:?-{2,}:?$/.test(f)));if(r.length===0)return[];let n=[];for(let c of r)c.forEach((f,d)=>{let h=f.replace(/\x1b\[[0-9;]*m/g,"").length;n[d]=Math.max(n[d]||0,h)});let s=` ${w.border("\u250C"+n.map(c=>"\u2500".repeat(c+2)).join("\u252C")+"\u2510")}`,i=` ${w.border("\u251C"+n.map(c=>"\u2500".repeat(c+2)).join("\u253C")+"\u2524")}`,o=` ${w.border("\u2514"+n.map(c=>"\u2500".repeat(c+2)).join("\u2534")+"\u2518")}`,a=c=>{let f=c.map((d,h)=>{let p=ct(d),u=p.replace(/\x1b\[[0-9;]*m/g,"").length;return` ${p}${" ".repeat(Math.max(0,n[h]-u))} `});return` ${w.border("\u2502")}${f.join(w.border("\u2502"))}${w.border("\u2502")}`},l=[s,a(r[0])];r.length>1&&l.push(i);for(let c of r.slice(1))l.push(a(c));return l.push(o),l}function Tt(t){let e=t.split(`
402
+ `),r=[],n=!1,s="",i=[],o=[],a=()=>{if(!i.length)return;let c=String(i.length).length;r.push(` ${w.border("\u250C"+"\u2500".repeat(Math.max(24,$e()-6)))} ${s?w.accent(s):""}`.trimEnd()),i.forEach((f,d)=>{r.push(` ${w.border("\u2502")} ${w.line(String(d+1).padStart(c)+" \u2502")} ${w.code(f)}`)}),r.push(` ${w.border("\u2514"+"\u2500".repeat(Math.max(24,$e()-6)))}`),i=[]},l=()=>{o.length&&(r.push(...tm(o)),o=[])};for(let c of e){if(c.trimStart().startsWith("```")){l(),n?(a(),n=!1,s=""):(n=!0,s=c.trimStart().slice(3).trim());continue}if(n){i.push(c);continue}if(em(c)){o.push(c);continue}else l();if(!c.trim()){r.push("");continue}if(/^---+$/.test(c.trim())){r.push(` ${w.border("\u2500".repeat(Math.max(28,$e()-6)))}`);continue}if(/^#{1,3}\s/.test(c)){r.push(""),r.push(` ${w.strong(ct(c.replace(/^#{1,3}\s/,"")))}`);continue}if(/^[A-Z][A-Za-z0-9 /&_-]{2,}:$/.test(c.trim())){r.push(` ${w.strong(ct(c.trim()))}`);continue}if(/^[-*]\s/.test(c.trim())){r.push(` ${w.accent("\u25B8")} ${ct(c.trim().slice(2))}`);continue}if(/^\d+\.\s/.test(c.trim())){r.push(` ${ct(c.trim())}`);continue}r.push(...Qn(ct(c),2))}return l(),n&&a(),`
387
403
  `+r.join(`
388
404
  `)+`
389
- `}function Va(){return["",` ${w.strong("Hablas commands")}`,"",` ${w.primary("/help")} ${w.muted("show help")}`,` ${w.primary("/status")} ${w.muted("show current runtime status")}`,` ${w.primary("/model")} ${w.muted("show or switch active model")}`,` ${w.primary("/models")} ${w.muted("list available models (supports search)")}`,` ${w.primary("/provider")} ${w.muted("inspect or switch provider")}`,` ${w.primary("/history")} ${w.muted("show recent turns")}`,` ${w.primary("/clear")} ${w.muted("clear the session")}`,` ${w.primary("/workspace")} ${w.muted("inspect workspace info")}`,` ${w.primary("/doctor")} ${w.muted("run diagnostics")}`,` ${w.primary("/version")} ${w.muted("show version")}`,` ${w.primary("/about")} ${w.muted("show product identity")}`,` ${w.primary("/exit")} ${w.muted("quit")}`,"",` ${w.accent("Tips")}`,` ${w.muted("\u2022 Tab completes commands and common file paths.")}`,` ${w.muted("\u2022 Use #filename to reference files quickly.")}`,` ${w.muted("\u2022 Ctrl+C cancels current work. Ctrl+C twice exits.")}`,""].join(`
390
- `)}function za(t){let e=[` ${w.muted("provider")} ${w.info(t.provider)}`,` ${w.muted("model")} ${w.info(t.model)}`,` ${w.muted("workspace")} ${w.muted(t.workingDir.replace(Gn.homedir(),"~"))}`,` ${w.muted("connected")} ${t.connected?w.success("yes"):w.error("no")}`,` ${w.muted("messages")} ${w.info(String(t.messageCount))}`,t.totalTokens!==void 0?` ${w.muted("tokens")} ${w.info(String(t.totalTokens))}`:""].filter(Boolean);return[""," "+w.strong("Status"),""].concat(e).concat([""]).join(`
391
- `)}function K(t){return` ${w.info(t)}`}function Ue(t){return` ${w.success("\u2713")} ${t}`}function Te(t){return` ${w.warning("\u26A0")} ${t}`}function Ce(t){return` ${w.error("\u2717")} ${t}`}function Ka(){return` ${w.strong("Hablas")} ${w.accent("v"+Ua)}`}function Ga(){return` ${w.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime by Abdulmoin Hablas`}function Ja(t,e){let r=Math.max(50,$e()-8),n=`${t.toUpperCase()}`,s=Yn(e,0),i=[];i.push(` ${w.border("\u256D"+"\u2500".repeat(r+2)+"\u256E")}`);let o=Math.max(0,r-n.length);i.push(` ${w.border("\u2502")} ${w.strong(n)}${" ".repeat(o)} ${w.border("\u2502")}`),i.push(` ${w.border("\u251C"+"\u2500".repeat(r+2)+"\u2524")}`);for(let a of s){let l=a.trim(),c=Math.max(0,r-l.replace(/\x1b\[[0-9;]*m/g,"").length);i.push(` ${w.border("\u2502")} ${w.accent(l)}${" ".repeat(c)} ${w.border("\u2502")}`)}return i.join(`
392
- `)}function Ya(t,e,r){let n=Math.max(50,$e()-8),s=t?w.success("\u2713 SUCCESS"):w.error("\u2717 FAILURE"),o=e.split(`
393
- `)[0]?.trim()||""||e.replace(/\s+/g," ").trim()||(t?"done":"failed"),a=`${s} ${o} ${w.muted(`(${r}ms)`)}`,l=Yn(a,0),c=[];for(let f of l){let d=f.trim(),h=Math.max(0,n-d.replace(/\x1b\[[0-9;]*m/g,"").length);c.push(` ${w.border("\u2502")} ${d}${" ".repeat(h)} ${w.border("\u2502")}`)}return c.push(` ${w.border("\u2570"+"\u2500".repeat(n+2)+"\u256F")}`),c.join(`
394
- `)}var Ne=class{constructor(e){this.label=e}frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;timer=null;setLabel(e){this.label=e}start(){!Jn||this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${w.accent(this.frames[this.index])} ${w.muted(this.label)}`),this.index=(this.index+1)%this.frames.length},80))}stop(e){this.timer&&(clearInterval(this.timer),this.timer=null,process.stdout.write("\r\x1B[K")),e&&console.log(K(e))}};var dr=Y.join(Qa.homedir(),".hablas","history"),pr=500,Xh=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Zh=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],Qh=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml",".txt",".env",".sh",".bash",".zsh",".svg",".sql",".png",".jpg",".jpeg",".webp"]),Xa=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],hr=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return Za.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:pr,completer:e=>this.autocomplete(e)})}async prompt(e){return new Promise(r=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,n=>{let s=n.trim();s&&(this.history.push(s),this.history=this.history.slice(-pr),this.saveHistory()),r(n)})})}async confirm(e){return(await this.prompt(` ${w.warning("?")} ${e} ${w.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
405
+ `}function Ka(){return["",` ${w.strong("Hablas commands")}`,"",` ${w.primary("/help")} ${w.muted("show help")}`,` ${w.primary("/status")} ${w.muted("show current runtime status")}`,` ${w.primary("/model")} ${w.muted("show or switch active model")}`,` ${w.primary("/models")} ${w.muted("list available models (supports search)")}`,` ${w.primary("/provider")} ${w.muted("inspect or switch provider")}`,` ${w.primary("/history")} ${w.muted("show recent turns")}`,` ${w.primary("/clear")} ${w.muted("clear the session")}`,` ${w.primary("/workspace")} ${w.muted("inspect workspace info")}`,` ${w.primary("/doctor")} ${w.muted("run diagnostics")}`,` ${w.primary("/version")} ${w.muted("show version")}`,` ${w.primary("/about")} ${w.muted("show product identity")}`,` ${w.primary("/exit")} ${w.muted("quit")}`,"",` ${w.accent("Tips")}`,` ${w.muted("\u2022 Tab completes commands and common file paths.")}`,` ${w.muted("\u2022 Use #filename to reference files quickly.")}`,` ${w.muted("\u2022 Ctrl+C cancels current work. Ctrl+C twice exits.")}`,""].join(`
406
+ `)}function Ga(t){let e=[` ${w.muted("provider")} ${w.info(t.provider)}`,` ${w.muted("model")} ${w.info(t.model)}`,` ${w.muted("workspace")} ${w.muted(t.workingDir.replace(Xn.homedir(),"~"))}`,` ${w.muted("connected")} ${t.connected?w.success("yes"):w.error("no")}`,` ${w.muted("messages")} ${w.info(String(t.messageCount))}`,t.totalTokens!==void 0?` ${w.muted("tokens")} ${w.info(String(t.totalTokens))}`:""].filter(Boolean);return[""," "+w.strong("Status"),""].concat(e).concat([""]).join(`
407
+ `)}function K(t){return` ${w.info(t)}`}function Ue(t){return` ${w.success("\u2713")} ${t}`}function Te(t){return` ${w.warning("\u26A0")} ${t}`}function Ce(t){return` ${w.error("\u2717")} ${t}`}function Ja(){return` ${w.strong("Hablas")} ${w.accent("v"+Ba)}`}function Ya(){return["",` ${w.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime`,"",` ${w.primary("Abdulmoin Hablas")} ${w.muted("Portfolio")}`,` ${w.muted(" https://portfolio-monopoly63s-projects.vercel.app/")}`,""].join(`
408
+ `)}function Xa(t,e){let r=Math.max(50,$e()-8),n=`${t.toUpperCase()}`,s=Qn(e,0),i=[];i.push(` ${w.border("\u256D"+"\u2500".repeat(r+2)+"\u256E")}`);let o=Math.max(0,r-n.length);i.push(` ${w.border("\u2502")} ${w.strong(n)}${" ".repeat(o)} ${w.border("\u2502")}`),i.push(` ${w.border("\u251C"+"\u2500".repeat(r+2)+"\u2524")}`);for(let a of s){let l=a.trim(),c=Math.max(0,r-l.replace(/\x1b\[[0-9;]*m/g,"").length);i.push(` ${w.border("\u2502")} ${w.accent(l)}${" ".repeat(c)} ${w.border("\u2502")}`)}return i.join(`
409
+ `)}function Za(t,e,r){let n=Math.max(50,$e()-8),s=t?w.success("\u2713 SUCCESS"):w.error("\u2717 FAILURE"),o=e.split(`
410
+ `)[0]?.trim()||""||e.replace(/\s+/g," ").trim()||(t?"done":"failed"),a=`${s} ${o} ${w.muted(`(${r}ms)`)}`,l=Qn(a,0),c=[];for(let f of l){let d=f.trim(),h=Math.max(0,n-d.replace(/\x1b\[[0-9;]*m/g,"").length);c.push(` ${w.border("\u2502")} ${d}${" ".repeat(h)} ${w.border("\u2502")}`)}return c.push(` ${w.border("\u2570"+"\u2500".repeat(n+2)+"\u256F")}`),c.join(`
411
+ `)}var Ne=class{constructor(e){this.label=e}frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;timer=null;setLabel(e){this.label=e}start(){!Zn||this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${w.accent(this.frames[this.index])} ${w.muted(this.label)}`),this.index=(this.index+1)%this.frames.length},80))}stop(e){this.timer&&(clearInterval(this.timer),this.timer=null,process.stdout.write("\r\x1B[K")),e&&console.log(K(e))}};var dr=Y.join(tl.homedir(),".hablas","history"),pr=500,rm=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),nm=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],sm=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml",".txt",".env",".sh",".bash",".zsh",".svg",".sql",".png",".jpg",".jpeg",".webp"]),Qa=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],hr=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return el.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:pr,completer:e=>this.autocomplete(e)})}async prompt(e){return new Promise(r=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,n=>{let s=n.trim();s&&(this.history.push(s),this.history=this.history.slice(-pr),this.saveHistory()),r(n)})})}async confirm(e){return(await this.prompt(` ${w.warning("?")} ${e} ${w.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
395
412
  ${w.error("\u26A0")} ${e}`),console.log(` ${w.muted("Type yes to confirm this dangerous action.")}
396
- `),(await this.prompt(` ${w.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let n=Xa.filter(s=>s.startsWith(e));return[n.length?n:Xa,e]}for(let n of Zh)if(e.toLowerCase().includes(n)){let s=e.split(n).pop()??"";if(s&&!s.includes(" "))try{let i=Y.dirname(s)||".",o=Y.basename(s),a=Y.resolve(this.workingDir,i),l=se.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(s))+Y.join(i,c));if(l.length)return[l,e]}catch{}}let r=e.match(/#([\w./-]*)$/);if(r){let n=r[1],s=this.getProjectFiles(),i=s.filter(o=>o.toLowerCase().startsWith(n.toLowerCase())).map(o=>e.slice(0,e.length-r[0].length)+"#"+o);return[i.length?i:s.slice(0,20).map(o=>e.slice(0,e.length-r[0].length)+"#"+o),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let r=[];return this.scanDir(this.workingDir,"",r,3),this.fileCache=r,this.fileCacheTime=e,r}scanDir(e,r,n,s,i=0){if(!(i>=s))try{let o=se.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||Xh.has(a.name))continue;let l=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(Y.join(e,a.name),l,n,s,i+1);else{let c=Y.extname(a.name).toLowerCase();(Qh.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&n.push(l)}}}catch{}}loadHistory(){try{se.existsSync(dr)&&(this.history=se.readFileSync(dr,"utf-8").split(`
397
- `).filter(Boolean).slice(-pr))}catch{}}saveHistory(){try{let e=Y.dirname(dr);se.existsSync(e)||se.mkdirSync(e,{recursive:!0}),se.writeFileSync(dr,this.history.slice(-pr).join(`
398
- `),"utf-8")}catch{}}};var em={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},tm=`
413
+ `),(await this.prompt(` ${w.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let n=Qa.filter(s=>s.startsWith(e));return[n.length?n:Qa,e]}for(let n of nm)if(e.toLowerCase().includes(n)){let s=e.split(n).pop()??"";if(s&&!s.includes(" "))try{let i=Y.dirname(s)||".",o=Y.basename(s),a=Y.resolve(this.workingDir,i),l=ie.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(s))+Y.join(i,c));if(l.length)return[l,e]}catch{}}let r=e.match(/#([\w./-]*)$/);if(r){let n=r[1],s=this.getProjectFiles(),i=s.filter(o=>o.toLowerCase().startsWith(n.toLowerCase())).map(o=>e.slice(0,e.length-r[0].length)+"#"+o);return[i.length?i:s.slice(0,20).map(o=>e.slice(0,e.length-r[0].length)+"#"+o),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let r=[];return this.scanDir(this.workingDir,"",r,3),this.fileCache=r,this.fileCacheTime=e,r}scanDir(e,r,n,s,i=0){if(!(i>=s))try{let o=ie.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||rm.has(a.name))continue;let l=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(Y.join(e,a.name),l,n,s,i+1);else{let c=Y.extname(a.name).toLowerCase();(sm.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&n.push(l)}}}catch{}}loadHistory(){try{ie.existsSync(dr)&&(this.history=ie.readFileSync(dr,"utf-8").split(`
414
+ `).filter(Boolean).slice(-pr))}catch{}}saveHistory(){try{let e=Y.dirname(dr);ie.existsSync(e)||ie.mkdirSync(e,{recursive:!0}),ie.writeFileSync(dr,this.history.slice(-pr).join(`
415
+ `),"utf-8")}catch{}}};var im={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},om=`
399
416
  ## Reasoning Protocol
400
417
 
401
418
  Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
@@ -424,15 +441,15 @@ After receiving a tool result, think again:
424
441
  - One tool call per turn. Wait for the result before the next call.
425
442
  - If a tool fails, analyze the error in <thinking> before retrying.
426
443
  - When done, give a concise final answer WITHOUT <thinking> tags.
427
- `.trim(),rm=`
444
+ `.trim(),am=`
428
445
  ## Reasoning
429
446
  For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
430
447
  The user will NOT see thinking blocks. One tool call per turn.
431
- `.trim(),Xn=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...em,...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}
448
+ `.trim(),es=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...im,...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}
432
449
 
433
- ${rm}`:`${e}
450
+ ${am}`:`${e}
434
451
 
435
- ${tm}`}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(`
452
+ ${om}`}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(`
436
453
 
437
454
  `).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`
438
455
  <self_eval>
@@ -455,18 +472,18 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
455
472
  }
456
473
  </self_eval>
457
474
  `.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(`
458
- `)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(s=>s.action).length,n=this.turnSteps.filter(s=>s.reflection).length;return`${e} steps, ${r} actions, ${n} reflections`}};function Ct(t){return new Xn(t)}var nm=[{test:t=>/ENOENT|no such file|not found|does not exist/i.test(t),errorClass:"file_not_found",strategy:"read_first",explanation:"The file or directory does not exist.",suggestion:"Use list_dir to check what files exist, then retry with the correct path.",alternatives:["list_dir","search_codebase"],autoRetry:!1},{test:t=>/EACCES|permission denied/i.test(t),errorClass:"permission_denied",strategy:"graceful_fail",explanation:"Permission denied \u2014 the process lacks access rights.",suggestion:"Check file ownership or try a different path. Do NOT use sudo.",alternatives:[],autoRetry:!1},{test:t=>/EISDIR|is a directory/i.test(t),errorClass:"path_is_directory",strategy:"retry_fixed",explanation:"The path points to a directory, not a file.",suggestion:"Append the filename to the path. Use list_dir to see contents.",alternatives:["list_dir"],autoRetry:!1},{test:t=>/EEXIST|already exists/i.test(t),errorClass:"file_already_exists",strategy:"read_first",explanation:"A file or directory already exists at that path.",suggestion:"Read the existing file first, then decide whether to overwrite or edit it.",alternatives:["read_file","edit_file"],autoRetry:!1},{test:t=>/no match|not found in file|search string not found/i.test(t),errorClass:"search_no_match",strategy:"read_first",explanation:"The search string was not found in the file.",suggestion:"Read the file first to see its actual content, then use the exact text for search/replace.",alternatives:["read_file","search_codebase"],autoRetry:!1},{test:t=>/command not found|not recognized/i.test(t),errorClass:"command_not_found",strategy:"alternative_tool",explanation:"The command does not exist on this system.",suggestion:"Check if the program is installed, or use a different command that achieves the same goal.",alternatives:["run_command"],autoRetry:!1},{test:t=>/timeout|timed out|ETIMEDOUT/i.test(t),errorClass:"command_timeout",strategy:"retry_fixed",explanation:"The command took too long and was terminated.",suggestion:"Try a simpler version of the command, or increase the timeout, or run it in background.",alternatives:[],autoRetry:!1},{test:t=>/exit code|exited with|non-zero/i.test(t),errorClass:"command_exit_error",strategy:"retry_fixed",explanation:"The command executed but returned an error.",suggestion:"Read the error output carefully. Fix the root cause (missing dependency, wrong syntax, etc.).",alternatives:[],autoRetry:!1},{test:t=>/syntax error|unexpected token|parse error|SyntaxError/i.test(t),errorClass:"syntax_error",strategy:"retry_fixed",explanation:"The content has a syntax error.",suggestion:"Review the generated code for syntax issues, fix them, and retry.",alternatives:[],autoRetry:!1},{test:t=>/ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(t),errorClass:"network_error",strategy:"retry_same",explanation:"Network connection failed.",suggestion:"This may be transient. Retry the same operation, or check connectivity.",alternatives:[],autoRetry:!0},{test:t=>/invalid argument|missing required|expected.*but got|type error/i.test(t),errorClass:"invalid_arguments",strategy:"retry_fixed",explanation:"The tool was called with invalid or missing arguments.",suggestion:"Check the tool's parameter requirements and provide correct values.",alternatives:[],autoRetry:!1},{test:t=>/ENOMEM|out of memory|resource|too large|max.*exceeded/i.test(t),errorClass:"resource_limit",strategy:"decompose_task",explanation:"Resource limit exceeded (memory, file size, etc.).",suggestion:"Break the task into smaller pieces, or process less data at once.",alternatives:[],autoRetry:!1}],Zn=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,r,n){let s=this.failures.get(e),i=s?s.count+1:1,o={tool:e,count:i,lastError:r,lastStrategy:"retry_same"};if(i>this.maxRetriesPerTool)return o.lastStrategy="ask_user",this.failures.set(e,o),{errorClass:"unknown",strategy:"ask_user",explanation:`Tool "${e}" has failed ${i} times in this turn.`,suggestion:`Stop retrying "${e}". Ask the user for clarification or try a completely different approach.`,alternatives:this.suggestAlternatives(e),autoRetry:!1};for(let a of nm)if(a.test(r)){let l=s?.lastStrategy===a.strategy&&i>=2,c=l?"decompose_task":a.strategy;return o.lastStrategy=c,this.failures.set(e,o),{errorClass:a.errorClass,strategy:c,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,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(`
459
- `)}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 Et(t=3){return new Zn(t)}var ye=k(require("fs")),gr=k(require("path")),el=k(require("os")),mr=gr.join(el.homedir(),".hablas","model-formats.json");function sm(){try{if(ye.existsSync(mr))return JSON.parse(ye.readFileSync(mr,"utf-8"))}catch{}return{}}function im(t){try{let e=gr.dirname(mr);ye.existsSync(e)||ye.mkdirSync(e,{recursive:!0}),ye.writeFileSync(mr,JSON.stringify(t,null,2),"utf-8")}catch{}}function tl(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 At(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 om(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function am(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=At(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function lm(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=At(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function cm(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=rl(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function rl(t){let e=[],r=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info","web_search","scrape_url","extract_links","read_pdf","pdf_metadata","execute_code","detect_bugs","download_asset"];for(let n of r){let s=new RegExp(`<<?${n}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${n}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",l={},c=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,f;for(;(f=c.exec(o))!==null;){let h=f[1].toLowerCase(),p=f[2]??f[3]??f[4];l[h]=om(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 um(t){return rl(t)}function fm(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=At(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function dm(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=tl(t,n.index);if(s)try{let i=JSON.parse(s),o=At(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function pm(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=tl(t,n.index);if(s)try{let i=JSON.parse(s),o=At(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function hm(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={},c=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,f;for(;(f=c.exec(i))!==null;){let d=f[1].trim(),h=f[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,c;for(;(c=l.exec(t))!==null;){let f=c[1].trim(),d=c[2].trim();d==="true"?d=!0:d==="false"?d=!1:!isNaN(Number(d))&&d!==""&&(d=Number(d)),a[f]=d}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var Qn=[{format:"xml_tool_call_wrapper",parse:cm},{format:"xml_prompt",parse:um},{format:"xml_tags",parse:am},{format:"xml_parameters",parse:hm},{format:"hermes",parse:lm},{format:"markdown_json",parse:fm},{format:"function_call",parse:dm},{format:"json_object",parse:pm}],ts=class{registry;constructor(){this.registry=sm()}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=Qn.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 Qn){let o=i(s);if(o.length>0){let a=o[0].format;return n&&this.learnFormat(n,a),this.buildResult(o,s)}}return{toolCalls:[],displayContent:this.sanitizeResidualToolMarkup(s).trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let r=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(r)||/<function=/i.test(r)||r.includes("```tool_call")||r.includes("```json")&&r.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\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 Qn)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()},im(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[r,n]of Object.entries(this.registry))e[r]={format:n.format,successCount:n.successCount};return e}buildResult(e,r){let n=e.map(o=>({function:{name:o.tool,arguments:o.args}})),s=r,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)s=s.replace(o.rawMatch,"");return s=s.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),s=s.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),s=this.sanitizeResidualToolMarkup(s),s=s.replace(/\n{3,}/g,`
475
+ `)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(s=>s.action).length,n=this.turnSteps.filter(s=>s.reflection).length;return`${e} steps, ${r} actions, ${n} reflections`}};function Ct(t){return new es(t)}var lm=[{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}],ts=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 lm)if(a.test(r)){let l=s?.lastStrategy===a.strategy&&i>=2,c=l?"decompose_task":a.strategy;return o.lastStrategy=c,this.failures.set(e,o),{errorClass:a.errorClass,strategy:c,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,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(`
476
+ `)}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 At(t=3){return new ts(t)}var ye=A(require("fs")),gr=A(require("path")),rl=A(require("os")),mr=gr.join(rl.homedir(),".hablas","model-formats.json");function cm(){try{if(ye.existsSync(mr))return JSON.parse(ye.readFileSync(mr,"utf-8"))}catch{}return{}}function um(t){try{let e=gr.dirname(mr);ye.existsSync(e)||ye.mkdirSync(e,{recursive:!0}),ye.writeFileSync(mr,JSON.stringify(t,null,2),"utf-8")}catch{}}function nl(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 Et(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 fm(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function dm(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=Et(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function pm(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=Et(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function hm(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=sl(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function sl(t){let e=[],r=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info","web_search","scrape_url","extract_links","read_pdf","pdf_metadata","execute_code","detect_bugs","download_asset"];for(let n of r){let s=new RegExp(`<<?${n}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${n}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",l={},c=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,f;for(;(f=c.exec(o))!==null;){let h=f[1].toLowerCase(),p=f[2]??f[3]??f[4];l[h]=fm(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 mm(t){return sl(t)}function gm(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=Et(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function ym(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=nl(t,n.index);if(s)try{let i=JSON.parse(s),o=Et(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function wm(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=nl(t,n.index);if(s)try{let i=JSON.parse(s),o=Et(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function bm(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={},c=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,f;for(;(f=c.exec(i))!==null;){let d=f[1].trim(),h=f[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,c;for(;(c=l.exec(t))!==null;){let f=c[1].trim(),d=c[2].trim();d==="true"?d=!0:d==="false"?d=!1:!isNaN(Number(d))&&d!==""&&(d=Number(d)),a[f]=d}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var rs=[{format:"xml_tool_call_wrapper",parse:hm},{format:"xml_prompt",parse:mm},{format:"xml_tags",parse:dm},{format:"xml_parameters",parse:bm},{format:"hermes",parse:pm},{format:"markdown_json",parse:gm},{format:"function_call",parse:ym},{format:"json_object",parse:wm}],ss=class{registry;constructor(){this.registry=cm()}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=rs.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 rs){let o=i(s);if(o.length>0){let a=o[0].format;return n&&this.learnFormat(n,a),this.buildResult(o,s)}}return{toolCalls:[],displayContent:this.sanitizeResidualToolMarkup(s).trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let r=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(r)||/<function=/i.test(r)||r.includes("```tool_call")||r.includes("```json")&&r.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\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 rs)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()},um(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[r,n]of Object.entries(this.registry))e[r]={format:n.format,successCount:n.successCount};return e}buildResult(e,r){let n=e.map(o=>({function:{name:o.tool,arguments:o.args}})),s=r,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)s=s.replace(o.rawMatch,"");return s=s.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),s=s.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),s=this.sanitizeResidualToolMarkup(s),s=s.replace(/\n{3,}/g,`
460
477
 
461
478
  `),{toolCalls:n,displayContent:s.trim(),format:e[0]?.format??"unknown"}}sanitizeResidualToolMarkup(e){return e.replace(/<<?tool[-_]call[\s\S]*?<<?\/tool[-_]call\s*>>?/gi,"").replace(/<function=[^>]+>/gi,"").replace(/<parameter=[^>]+>/gi,"").replace(/<\/parameter>/gi,"").replace(/```tool_call[\s\S]*?```/gi,"").replace(/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset)[\s\S]*?(?:<<?\/[a-z_]+>>?|\/>)/gi,"").replace(/\n{3,}/g,`
462
479
 
463
- `)}},es=null;function nl(){return es||(es=new ts),es}var mm=600,gm=2e3,ym=12e3,sl=2;function wm(t,e,r){let s=nl().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function bm(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 xm(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 il(t,e,r,n){let s=0,i=Date.now();for(;s<=sl;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=sl)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 rs(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:f}=t,d=t.reactEngine??Ct(),h=t.errorRecovery??Et(),p=f?[]:n.getOllamaTools(),u=r.getModel(),m=t.maxIterations??mm,g=[],x=[],b=[],S=new Map,_="",$=0,E=!1;for(;$<m;){if($++,c?.aborted)return{output:_,toolsUsed:Ee(g),toolResults:x,touchedFiles:Ee(b),iterations:$,success:!1,error:"Aborted",completedNaturally:E};let C=d.buildBudgetWarningPrompt();C&&s.addUserMessage(C,{priority:"critical",tags:["system-budget"]});let R;try{a.onModelStart?.(x.length>0?"Hablas is deciding the next step":"Hablas is thinking",e),R=await r.chatWithTools(s.getMessages(),p,c),a.onModelStop?.()}catch(J){a.onModelStop?.();let Z=J;if(Z.name==="AbortError"||c?.aborted)return{output:_,toolsUsed:Ee(g),toolResults:x,touchedFiles:Ee(b),iterations:$,success:!1,error:"Aborted",completedNaturally:E};if($<=1){a.onNotice?.(`Transient model error: ${Z.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(P=>setTimeout(P,1e3)),$--;continue}return a.onError?.(Z.message??"Model request failed"),{output:_,toolsUsed:Ee(g),toolResults:x,touchedFiles:Ee(b),iterations:$,success:!1,error:Z.message,completedNaturally:E}}let T=R.message?.content||"",L=R.message?.tool_calls,U=d.parseThinking(T);U.hasThinking&&(d.recordStep({thought:U.thinking}),o.debug({thinking:U.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:j,displayContent:B}=wm(L,T,u);if(B&&B.trim()&&(_=B,await a.onAssistantText?.(B,e)),j.length===0){s.addAssistantMessage(T,void 0,e.role),E=!0;break}s.addAssistantMessage(T,j,e.role);let W=j.length;for(let J=0;J<j.length;J++){let Z=j[J];if(!Z?.function?.name)continue;let P=Z.function.name,D=Z.function.arguments||{},It=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(z=>z.name).join(", ")}`);continue}if(await l(P,It,D)==="skip"){s.addToolMessage(`Tool ${P} was skipped by policy/user.`);break}let Cl=bm(P,D),ft=P==="read_file"?JSON.stringify({path:D.path||"",start:D.start_line||"",end:D.end_line||""}):"";if(P==="read_file"&&ft&&S.has(ft)){let z=S.get(ft)||"";s.addToolMessage(z),d.recordObservation(z.slice(0,300),"Reused cached file read");continue}g.push(P),typeof D.path=="string"&&b.push(D.path),typeof D.from=="string"&&b.push(D.from),typeof D.to=="string"&&b.push(D.to),a.onToolStart?.(P,Cl,D),a.onToolCall?.(),d.recordStep({thought:U.hasThinking?`Executing: ${P}`:"",action:P,actionInput:D});let V=await il(n,P,D,o);a.onToolEnd?.(P,V.success,V.error||V.output,V.duration,D);let Ae;if(V.success)Ae=ol(P,V.output),d.recordObservation(Ae.slice(0,300)),x.push({tool:P,success:!0,summary:V.output.slice(0,150)});else{let z=V.error||"Unknown error",Be=h.analyze(P,z,D);if(Ae=h.buildRecoveryMessage(Be,z),d.recordObservation(`FAILED: ${z}`,`Recovery: ${Be.strategy} \u2014 ${Be.suggestion}`),o.info({tool:P,errorClass:Be.errorClass,strategy:Be.strategy},"Error recovery analysis"),x.push({tool:P,success:!1,summary:z.slice(0,150)}),Be.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let He=await il(n,P,D,o);a.onToolEnd?.(P,He.success,He.output,He.duration,D),He.success&&(Ae=ol(P,He.output),d.recordObservation(Ae.slice(0,300),"Auto-retry succeeded"),x[x.length-1]={tool:P,success:!0,summary:He.output.slice(0,150)})}}if(s.addToolMessage(Ae),V.success&&P==="read_file"&&typeof D.path=="string"&&(i?.addFile(D.path,V.output),ft&&S.set(ft,Ae)),V.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(P)&&typeof D.path=="string")for(let z of[...S.keys()])z.includes(`"path":"${String(D.path).replace(/\"/g,'\\"')}"`)&&S.delete(z);if(V.success&&P==="move_file")for(let z of[...S.keys()])(D.from&&z.includes(`"path":"${String(D.from).replace(/\"/g,'\\"')}"`)||D.to&&z.includes(`"path":"${String(D.to).replace(/\"/g,'\\"')}"`))&&S.delete(z);if(o.info({tool:P,success:V.success,durationMs:V.duration,retries:V.retries},"Tool executed"),!V.success&&xm(V.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}W>1&&J<W-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return $>=m&&!E&&a.onNotice?.(`Reached max iterations (${m}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:_,toolsUsed:Ee(g),toolResults:x,touchedFiles:Ee(b),iterations:$,success:!0,completedNaturally:E}}function Ee(t){return[...new Set(t)]}function ol(t,e){return t==="read_file"?e:t==="web_search"||t==="scrape_url"||t==="extract_links"||t==="read_pdf"?vt(e,ym):vt(e,gm)}function al(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 ll(t){let{client:e,session:r,abortSignal:n,onStart:s,onChunk:i,onComplete:o}=t,a="",l=null;for(let c=0;c<2;c++)try{a="";for await(let f of e.streamChat(r.getMessages(),n))a+=f,i?.(f);return r.addAssistantMessage(a||""),a}catch(f){if(l=f,f?.name==="AbortError"||n?.aborted)throw f;if(c===1)break}throw l||new Error("Text turn failed")}async function yr(t,e){let r=Na(t),n=await ot(e.workingDir,e.config);if(e.session.updateSystemPrompt(at(n,r.profile)),r.profile.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context and do not restart from zero.]",{priority:"critical",tags:["runtime-note","continuity"]}),r.profile.oneStepDelivery&&e.session.addUserMessage("[Execution note: complete as much as possible in one pass with no unnecessary follow-up questions.]",{priority:"critical",tags:["runtime-note","one-step"]}),e.session.addUserMessage(t,{priority:"high",tags:[`kind:${r.profile.kind}`]}),!r.profile.needsTools){let p=new Ne("Hablas is thinking"),u=!1;p.start();try{let m=await ll({client:e.client,session:e.session,onStart:()=>{p.start()},onChunk:g=>{u||(p.stop(),console.log(ct()),process.stdout.write(" "),u=!0),process.stdout.write(g)},onComplete:()=>{u&&process.stdout.write(`
464
- `)}});u||(p.stop(),console.log(ct()),console.log(Tt(m)));return}catch(m){p.stop(),console.log(Ce(m?.message||"Text turn failed"));return}}let s=Ct({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=Et(3),o=[],a=new Ne("Hablas is thinking"),l="",c=p=>["list_dir","read_file","search_codebase","get_file_info"].includes(p)?"Analyzing current project structure":["web_search"].includes(p)?"Searching trusted web sources":["search_image_candidates","inspect_image","scrape_url","extract_links"].includes(p)?"Selecting better image candidates":["download_asset"].includes(p)?"Downloading verified floral assets":["write_file","patch_file","edit_file","search_and_replace","append_to_file","move_file","create_dir","delete_file"].includes(p)?"Applying frontend upgrade":["run_command","execute_code","detect_bugs"].includes(p)?"Running verification":"Working",f={onModelStart:p=>{a.stop(),a.setLabel(p),a.start()},onModelStop:()=>{a.stop()},onAssistantText:async p=>{o.push(p),r.profile.kind!=="implementation"&&(console.log(ct()),console.log(Tt(p)))},onToolStart:(p,u)=>{a.stop();let m=c(p);m!==l&&(console.log(Wa(m)),l=m),console.log(Ja(p,u))},onToolEnd:(p,u,m,g)=>{console.log(Ya(u,m,g))},onNotice:(p,u)=>{console.log(u==="retry"?K(`Retrying: ${p}`):K(p))},onError:p=>{console.log(Ce(p))},onToolCall:()=>e.onToolCall?.()},d=al({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?p=>e.input.confirm(p):void 0,confirmDangerous:e.input?p=>e.input.confirmDangerous(p):void 0}),h=await rs({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:f,safetyPolicy:d,reactEngine:s,errorRecovery:i,skipTools:!1});if(r.profile.kind==="implementation"&&h.toolsUsed.length>0&&o.length>0&&(console.log(ct()),console.log(Tt(o[o.length-1]))),r.profile.kind==="implementation"&&h.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 p=[];(await rs({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...f,onAssistantText:async m=>{p.push(m)}},safetyPolicy:d,reactEngine:Ct({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:Et(3),skipTools:!1})).toolsUsed.length===0?console.log(Ce("Implementation request failed to enter a real tool-execution path. Refusing to present inline-code-only output as a completed result.")):p.length>0&&(console.log(ct()),console.log(Tt(p[p.length-1])))}}var ns=k(require("fs")),cl=k(require("path")),ce=k(require("os")),ul=require("child_process");async function wr(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=cl.join(ce.homedir(),".hablas");if(e.push({name:"Config directory",status:ns.existsSync(s)?"ok":"warn",message:ns.existsSync(s)?s:"Not created yet (will be created on first use)"}),t.provider==="ollama")try{let i=await fetch(`${t.ollamaHost}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let o=await i.json(),a=Array.isArray(o.models)?o.models.length:0;e.push({name:"Ollama",status:"ok",message:`Connected \u2014 ${a} models available`})}else e.push({name:"Ollama",status:"error",message:`HTTP ${i.status}`})}catch(i){let o=i instanceof Error?i.message:String(i);e.push({name:"Ollama",status:"error",message:o.includes("ECONNREFUSED")?"Not running \u2014 start with: ollama serve":`Connection failed: ${o}`})}else{let i=t.apiUrl||"unknown";try{let o=await fetch(`${i}/models`,{signal:AbortSignal.timeout(5e3),headers:{Authorization:"Bearer test"}});e.push({name:"API Provider",status:o.ok||o.status===401?"ok":"warn",message:`${i} \u2014 reachable`})}catch{e.push({name:"API Provider",status:"warn",message:`${i} \u2014 could not verify`})}}try{let i=ce.homedir();if(process.platform!=="win32"){let a=(0,ul.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",c=a[4]||"?";e.push({name:"Disk space",status:parseInt(c)>90?"warn":"ok",message:`${l} available (${c} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:t.model?"ok":"warn",message:t.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${ce.platform()} ${ce.arch()} \u2014 ${ce.cpus().length} cores, ${Math.round(ce.totalmem()/1024/1024/1024)}GB RAM`}),e}function br(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 c=`${r[l.status]}${e[l.status]}${n}`,f=l.name.padEnd(18);i.push(` ${c} ${f}${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(`
465
- `)}async function fl(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Va());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Ga());return;case"/version":console.log(Ka());return;case"/clear":e.session.clear(),console.log(Ue("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(K("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(za({model:e.client.getModel(),provider:De(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(K(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),ze(e.config),console.log(Ue(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=20,a=1,l="";if(s.length>0){let u=s[s.length-1],m=parseInt(u,10);!Number.isNaN(m)&&m>0?(a=m,l=s.slice(0,-1).join(" ").toLowerCase().trim()):l=s.join(" ").toLowerCase().trim()}let c=l?i.filter(u=>u.toLowerCase().includes(l)):i;if(c.length===0){console.log(Te("No matching models found."));return}let f=Math.max(1,Math.ceil(c.length/o)),d=Math.min(Math.max(a,1),f),h=(d-1)*o,p=c.slice(h,h+o);console.log(""),console.log(K(`Models${l?` \xB7 search: ${l}`:""} \xB7 page ${d}/${f}`)),console.log(""),p.forEach((u,m)=>{let g=u===e.client.getModel();console.log(` ${String(h+m+1).padStart(2," ")}. ${u}${g?" * active":""}`)}),console.log(""),f>1&&console.log(K(`Use /models ${l?l+" ":""}${d<f?d+1:f} for next page.`)),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(K(`Provider: ${De(e.config)}`)),console.log(K(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Ue("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=ue.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=ue.defaultModel);else if(i==="custom"){if(!s[1]){console.log(Te("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(Te("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=Ye(e.config);e.setClient(o),ze(e.config),console.log(Ue(`Provider switched to ${De(e.config)}`));return}case"/doctor":{let i=await wr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(br(i));return}case"/workspace":{console.log(""),console.log(cr(st(e.workingDir))),console.log("");return}default:console.log(Te(`Unknown command: ${n}`))}}var we=k(require("fs")),ss=k(require("path"));function is(t){let e=ss.join(t,".hablas");return we.existsSync(e)||we.mkdirSync(e,{recursive:!0}),e}function dl(t){return ss.join(is(t),"session.json")}function xr(t,e){let r=dl(t);try{return we.existsSync(r)?(e.fromJSON(we.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function Ot(t,e){let r=dl(t);try{we.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}async function ml(t,e){ks();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=Ye(t);is(r);let s=new et(r,t),i=new tt(t),o=await ot(r,t),a=new nt(at(o,$t("hello")),t.historySize,t.contextBudget);xr(r,a);let l=new hr(r);console.log(Ba(t.model,r));let c=new Ne("Connecting");c.start();let f=await n.checkConnection();if(c.stop(),f){let g=await n.listModels();console.log(Ue(`online \xB7 ${De(t)} \xB7 ${g.length} models available`))}else console.log(Te(`offline \xB7 ${De(t)} \xB7 you can still inspect local files and switch provider with /provider`));pl.existsSync(hl.join(r,".git"))||console.log(K("workspace mode: standalone (no git repository detected)")),console.log(K("Hablas is ready.")),console.log("");let d=0,h=0,p=Date.now(),u=new AbortController,m=0;for(process.on("SIGINT",()=>{let g=Date.now();g-m<1500&&(console.log(""),console.log(K(`Session summary \xB7 turns=${d} \xB7 toolCalls=${h} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),m=g,u.abort(),u=new AbortController,console.log(""),console.log(Te("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let x=(await l.prompt(" \u203A ")).trim();if(x){if(x.startsWith("/")){let b=await fl(x,{config:t,client:n,setClient:S=>{n=S},session:a,workingDir:r});if(Ot(r,a),b==="quit")break;continue}d+=1,console.log(Ha(d)),u=new AbortController;try{await yr(x,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{h+=1}}),Ot(r,a)}catch(b){if(b?.name==="AbortError")continue;console.log(Ce(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}l.close()}async function gl(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=Ye(e),i=new et(n,e),o=new tt(e),a=await ot(n,e),l=new nt(at(a,$t(t)),e.historySize,e.contextBudget);xr(n,l),await yr(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1}),Ot(n,l)}var Sr=k(require("fs")),qe=k(require("path")),Sm=[{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"}],_m=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),vm=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function km(t,e){let r=[],n=e.split(`
466
- `);for(let{pattern:s,name:i,severity:o}of Sm){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let c=e.substring(0,a.index).split(`
467
- `).length,f=n[c-1]||"";f.trim().startsWith("#")||f.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:c,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function $m(t,e){let r=[],n=e.split(`
468
- `),s=qe.extname(t);return[".ts",".js",".tsx",".jsx"].includes(s)&&n.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&r.push({severity:"medium",type:"code",file:t,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),r}function yl(t,e=[]){try{let r=Sr.readdirSync(t,{withFileTypes:!0});for(let n of r){if(_m.has(n.name))continue;let s=qe.join(t,n.name);if(n.isDirectory())yl(s,e);else if(n.isFile()){let i=qe.extname(n.name);vm.has(i)||e.push(s)}}}catch{}return e}function wl(t){let e=Date.now(),r=yl(t),n=[];for(let o of r)try{let a=Sr.readFileSync(o,"utf-8"),l=qe.relative(t,o),c=km(l,a);n.push(...c);let f=$m(l,a);n.push(...f)}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 bl(t){let e=[];if(e.push(`
480
+ `)}},ns=null;function il(){return ns||(ns=new ss),ns}var Sm=600,xm=2e3,_m=12e3,ol=2;function vm(t,e,r){let s=il().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function km(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 $m(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 al(t,e,r,n){let s=0,i=Date.now();for(;s<=ol;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=ol)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 is(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:f}=t,d=t.reactEngine??Ct(),h=t.errorRecovery??At(),p=f?[]:n.getOllamaTools(),u=r.getModel(),m=t.maxIterations??Sm,g=[],x=[],b=[],S=new Map,_="",v=0,$=!1;for(;v<m;){if(v++,c?.aborted)return{output:_,toolsUsed:Ae(g),toolResults:x,touchedFiles:Ae(b),iterations:v,success:!1,error:"Aborted",completedNaturally:$};let C=d.buildBudgetWarningPrompt();C&&s.addUserMessage(C,{priority:"critical",tags:["system-budget"]});let E;try{a.onModelStart?.(x.length>0?"Hablas is deciding the next step":"Hablas is thinking",e),E=await r.chatWithTools(s.getMessages(),p,c),a.onModelStop?.()}catch(J){a.onModelStop?.();let Z=J;if(Z.name==="AbortError"||c?.aborted)return{output:_,toolsUsed:Ae(g),toolResults:x,touchedFiles:Ae(b),iterations:v,success:!1,error:"Aborted",completedNaturally:$};if(v<=1){a.onNotice?.(`Transient model error: ${Z.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(L=>setTimeout(L,1e3)),v--;continue}return a.onError?.(Z.message??"Model request failed"),{output:_,toolsUsed:Ae(g),toolResults:x,touchedFiles:Ae(b),iterations:v,success:!1,error:Z.message,completedNaturally:$}}let T=E.message?.content||"",M=E.message?.tool_calls,j=d.parseThinking(T);j.hasThinking&&(d.recordStep({thought:j.thinking}),o.debug({thinking:j.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:D,displayContent:B}=vm(M,T,u);if(B&&B.trim()&&(_=B,await a.onAssistantText?.(B,e)),D.length===0){s.addAssistantMessage(T,void 0,e.role),$=!0;break}s.addAssistantMessage(T,D,e.role);let W=D.length;for(let J=0;J<D.length;J++){let Z=D[J];if(!Z?.function?.name)continue;let L=Z.function.name,F=Z.function.arguments||{},It=n.getSafetyLevel(L)??"confirm";if(!n.get(L)){a.onNotice?.(`Unknown tool: ${L} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${L}". Available: ${n.getAll().map(z=>z.name).join(", ")}`);continue}if(await l(L,It,F)==="skip"){s.addToolMessage(`Tool ${L} was skipped by policy/user.`);break}let El=km(L,F),dt=L==="read_file"?JSON.stringify({path:F.path||"",start:F.start_line||"",end:F.end_line||""}):"";if(L==="read_file"&&dt&&S.has(dt)){let z=S.get(dt)||"";s.addToolMessage(z),d.recordObservation(z.slice(0,300),"Reused cached file read");continue}g.push(L),typeof F.path=="string"&&b.push(F.path),typeof F.from=="string"&&b.push(F.from),typeof F.to=="string"&&b.push(F.to),a.onToolStart?.(L,El,F),a.onToolCall?.(),d.recordStep({thought:j.hasThinking?`Executing: ${L}`:"",action:L,actionInput:F});let V=await al(n,L,F,o);a.onToolEnd?.(L,V.success,V.error||V.output,V.duration,F);let Ee;if(V.success)Ee=ll(L,V.output),d.recordObservation(Ee.slice(0,300)),x.push({tool:L,success:!0,summary:V.output.slice(0,150)});else{let z=V.error||"Unknown error",Be=h.analyze(L,z,F);if(Ee=h.buildRecoveryMessage(Be,z),d.recordObservation(`FAILED: ${z}`,`Recovery: ${Be.strategy} \u2014 ${Be.suggestion}`),o.info({tool:L,errorClass:Be.errorClass,strategy:Be.strategy},"Error recovery analysis"),x.push({tool:L,success:!1,summary:z.slice(0,150)}),Be.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let He=await al(n,L,F,o);a.onToolEnd?.(L,He.success,He.output,He.duration,F),He.success&&(Ee=ll(L,He.output),d.recordObservation(Ee.slice(0,300),"Auto-retry succeeded"),x[x.length-1]={tool:L,success:!0,summary:He.output.slice(0,150)})}}if(s.addToolMessage(Ee),V.success&&L==="read_file"&&typeof F.path=="string"&&(i?.addFile(F.path,V.output),dt&&S.set(dt,Ee)),V.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(L)&&typeof F.path=="string")for(let z of[...S.keys()])z.includes(`"path":"${String(F.path).replace(/\"/g,'\\"')}"`)&&S.delete(z);if(V.success&&L==="move_file")for(let z of[...S.keys()])(F.from&&z.includes(`"path":"${String(F.from).replace(/\"/g,'\\"')}"`)||F.to&&z.includes(`"path":"${String(F.to).replace(/\"/g,'\\"')}"`))&&S.delete(z);if(o.info({tool:L,success:V.success,durationMs:V.duration,retries:V.retries},"Tool executed"),!V.success&&$m(V.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}W>1&&J<W-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return v>=m&&!$&&a.onNotice?.(`Reached max iterations (${m}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:_,toolsUsed:Ae(g),toolResults:x,touchedFiles:Ae(b),iterations:v,success:!0,completedNaturally:$}}function Ae(t){return[...new Set(t)]}function ll(t,e){return t==="read_file"?e:t==="web_search"||t==="scrape_url"||t==="extract_links"||t==="read_pdf"?vt(e,_m):vt(e,xm)}function cl(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 ul(t){let{client:e,session:r,abortSignal:n,onStart:s,onChunk:i,onComplete:o}=t,a="",l=null;for(let c=0;c<2;c++)try{a="";for await(let f of e.streamChat(r.getMessages(),n))a+=f,i?.(f);return r.addAssistantMessage(a||""),a}catch(f){if(l=f,f?.name==="AbortError"||n?.aborted)throw f;if(c===1)break}throw l||new Error("Text turn failed")}async function yr(t,e){let r=qa(t),n=await at(e.workingDir,e.config);if(e.session.updateSystemPrompt(lt(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 p=new Ne("Hablas is thinking"),u=!1;p.start();try{let m=await ul({client:e.client,session:e.session,onStart:()=>{p.start()},onChunk:g=>{u||(p.stop(),console.log(ut()),process.stdout.write(" "),u=!0),process.stdout.write(g)},onComplete:()=>{u&&process.stdout.write(`
481
+ `)}});u||(p.stop(),console.log(ut()),console.log(Tt(m)));return}catch(m){p.stop(),console.log(Ce(m?.message||"Text turn failed"));return}}let s=Ct({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=At(3),o=[],a=new Ne("Hablas is thinking"),l="",c=p=>["list_dir","read_file","search_codebase","get_file_info"].includes(p)?"Analyzing current project structure":["web_search"].includes(p)?"Searching trusted web sources":["search_image_candidates","inspect_image","scrape_url","extract_links"].includes(p)?"Selecting better image candidates":["download_asset"].includes(p)?"Downloading verified floral assets":["write_file","patch_file","edit_file","search_and_replace","append_to_file","move_file","create_dir","delete_file"].includes(p)?"Applying frontend upgrade":["run_command","execute_code","detect_bugs"].includes(p)?"Running verification":"Working",f={onModelStart:p=>{a.stop(),a.setLabel(p),a.start()},onModelStop:()=>{a.stop()},onAssistantText:async p=>{o.push(p),r.profile.kind!=="implementation"&&(console.log(ut()),console.log(Tt(p)))},onToolStart:(p,u)=>{a.stop();let m=c(p);m!==l&&(console.log(za(m)),l=m),console.log(Xa(p,u))},onToolEnd:(p,u,m,g)=>{console.log(Za(u,m,g))},onNotice:(p,u)=>{console.log(u==="retry"?K(`Retrying: ${p}`):K(p))},onError:p=>{console.log(Ce(p))},onToolCall:()=>e.onToolCall?.()},d=cl({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?p=>e.input.confirm(p):void 0,confirmDangerous:e.input?p=>e.input.confirmDangerous(p):void 0}),h=await is({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:f,safetyPolicy:d,reactEngine:s,errorRecovery:i,skipTools:!1});if(r.profile.kind==="implementation"&&h.toolsUsed.length>0&&o.length>0&&(console.log(ut()),console.log(Tt(o[o.length-1]))),r.profile.kind==="implementation"&&h.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 p=[];(await is({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...f,onAssistantText:async m=>{p.push(m)}},safetyPolicy:d,reactEngine:Ct({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:At(3),skipTools:!1})).toolsUsed.length===0?console.log(Ce("Implementation request failed to enter a real tool-execution path. Refusing to present inline-code-only output as a completed result.")):p.length>0&&(console.log(ut()),console.log(Tt(p[p.length-1])))}}var os=A(require("fs")),fl=A(require("path")),ue=A(require("os")),dl=require("child_process");async function wr(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=fl.join(ue.homedir(),".hablas");if(e.push({name:"Config directory",status:os.existsSync(s)?"ok":"warn",message:os.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=ue.homedir();if(process.platform!=="win32"){let a=(0,dl.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",c=a[4]||"?";e.push({name:"Disk space",status:parseInt(c)>90?"warn":"ok",message:`${l} available (${c} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:t.model?"ok":"warn",message:t.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${ue.platform()} ${ue.arch()} \u2014 ${ue.cpus().length} cores, ${Math.round(ue.totalmem()/1024/1024/1024)}GB RAM`}),e}function br(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 c=`${r[l.status]}${e[l.status]}${n}`,f=l.name.padEnd(18);i.push(` ${c} ${f}${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(`
482
+ `)}async function pl(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Ka());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Ya());return;case"/version":console.log(Ja());return;case"/clear":e.session.clear(),console.log(Ue("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(K("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(Ga({model:e.client.getModel(),provider:je(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(K(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),Ke(e.config),console.log(Ue(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=20,a=1,l="";if(s.length>0){let u=s[s.length-1],m=parseInt(u,10);!Number.isNaN(m)&&m>0?(a=m,l=s.slice(0,-1).join(" ").toLowerCase().trim()):l=s.join(" ").toLowerCase().trim()}let c=l?i.filter(u=>u.toLowerCase().includes(l)):i;if(c.length===0){console.log(Te("No matching models found."));return}let f=Math.max(1,Math.ceil(c.length/o)),d=Math.min(Math.max(a,1),f),h=(d-1)*o,p=c.slice(h,h+o);console.log(""),console.log(K(`Models${l?` \xB7 search: ${l}`:""} \xB7 page ${d}/${f}`)),console.log(""),p.forEach((u,m)=>{let g=u===e.client.getModel();console.log(` ${String(h+m+1).padStart(2," ")}. ${u}${g?" * active":""}`)}),console.log(""),f>1&&console.log(K(`Use /models ${l?l+" ":""}${d<f?d+1:f} for next page.`)),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(K(`Provider: ${je(e.config)}`)),console.log(K(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Ue("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=ee.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=ee.defaultModel);else if(i==="custom"){if(!s[1]){console.log(Te("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(Te("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=Xe(e.config);e.setClient(o),Ke(e.config),console.log(Ue(`Provider switched to ${je(e.config)}`));return}case"/doctor":{let i=await wr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(br(i));return}case"/workspace":{console.log(""),console.log(cr(it(e.workingDir))),console.log("");return}default:console.log(Te(`Unknown command: ${n}`))}}var we=A(require("fs")),as=A(require("path"));function ls(t){let e=as.join(t,".hablas");return we.existsSync(e)||we.mkdirSync(e,{recursive:!0}),e}function hl(t){return as.join(ls(t),"session.json")}function Sr(t,e){let r=hl(t);try{return we.existsSync(r)?(e.fromJSON(we.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function Ot(t,e){let r=hl(t);try{we.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}async function yl(t,e){Cs();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=Xe(t);ls(r);let s=new tt(r,t),i=new rt(t),o=await at(r,t),a=new st(lt(o,$t("hello")),t.historySize,t.contextBudget);Sr(r,a);let l=new hr(r);console.log(Wa(t.model,r));let c=new Ne("Connecting");c.start();let f=await n.checkConnection();if(c.stop(),f){let g=await n.listModels();console.log(Ue(`online \xB7 ${je(t)} \xB7 ${g.length} models available`))}else console.log(Te(`offline \xB7 ${je(t)} \xB7 you can still inspect local files and switch provider with /provider`));ml.existsSync(gl.join(r,".git"))||console.log(K("workspace mode: standalone (no git repository detected)")),console.log(K("Hablas is ready.")),console.log("");let d=0,h=0,p=Date.now(),u=new AbortController,m=0;for(process.on("SIGINT",()=>{let g=Date.now();g-m<1500&&(console.log(""),console.log(K(`Session summary \xB7 turns=${d} \xB7 toolCalls=${h} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),m=g,u.abort(),u=new AbortController,console.log(""),console.log(Te("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let x=(await l.prompt(" \u203A ")).trim();if(x){if(x.startsWith("/")){let b=await pl(x,{config:t,client:n,setClient:S=>{n=S},session:a,workingDir:r});if(Ot(r,a),b==="quit")break;continue}d+=1,console.log(Va(d)),u=new AbortController;try{await yr(x,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{h+=1}}),Ot(r,a)}catch(b){if(b?.name==="AbortError")continue;console.log(Ce(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}l.close()}async function wl(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=Xe(e),i=new tt(n,e),o=new rt(e),a=await at(n,e),l=new st(lt(a,$t(t)),e.historySize,e.contextBudget);Sr(n,l),await yr(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1}),Ot(n,l)}var xr=A(require("fs")),qe=A(require("path")),Tm=[{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"}],Cm=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Am=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function Em(t,e){let r=[],n=e.split(`
483
+ `);for(let{pattern:s,name:i,severity:o}of Tm){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let c=e.substring(0,a.index).split(`
484
+ `).length,f=n[c-1]||"";f.trim().startsWith("#")||f.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:c,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function Om(t,e){let r=[],n=e.split(`
485
+ `),s=qe.extname(t);return[".ts",".js",".tsx",".jsx"].includes(s)&&n.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&r.push({severity:"medium",type:"code",file:t,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),r}function bl(t,e=[]){try{let r=xr.readdirSync(t,{withFileTypes:!0});for(let n of r){if(Cm.has(n.name))continue;let s=qe.join(t,n.name);if(n.isDirectory())bl(s,e);else if(n.isFile()){let i=qe.extname(n.name);Am.has(i)||e.push(s)}}}catch{}return e}function Sl(t){let e=Date.now(),r=bl(t),n=[];for(let o of r)try{let a=xr.readFileSync(o,"utf-8"),l=qe.relative(t,o),c=Em(l,a);n.push(...c);let f=Om(l,a);n.push(...f)}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 xl(t){let e=[];if(e.push(`
469
486
  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(`
470
- `)}var ut=k(require("fs")),os=k(require("path")),Sl=k(require("os")),Tm=os.join(Sl.homedir(),".hablas"),xl=os.join(Tm,"analytics.json");function _l(){try{if(ut.existsSync(xl))return JSON.parse(ut.readFileSync(xl,"utf-8"))}catch{}return Cm()}function Cm(){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 vl(t){let e=[];e.push(`
487
+ `)}var ft=A(require("fs")),cs=A(require("path")),vl=A(require("os")),Rm=cs.join(vl.homedir(),".hablas"),_l=cs.join(Rm,"analytics.json");function kl(){try{if(ft.existsSync(_l))return JSON.parse(ft.readFileSync(_l,"utf-8"))}catch{}return Im()}function Im(){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 $l(t){let e=[];e.push(`
471
488
  \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(`
472
- `)}var kl=k(require("readline"));var G="\x1B[36m",_r="\x1B[32m",be="\x1B[33m",M="\x1B[2m",xe="\x1B[1m",v="\x1B[0m",Em="\x1B[35m";function H(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function Am(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var Rt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function $l(t){let e=kl.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${xe}${G} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${v}`),console.log(`${xe}${G} hablas \u2014 Setup Wizard${v}`),console.log(`${M} Configure your AI provider and model${v}`),console.log(`${xe}${G} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${v}`),console.log(),console.log(`${xe} Choose your setup:${v}`),console.log(),console.log(` ${Em}${xe}1${v}. ${xe}Hablas Integrated Engine${v} ${_r}(instant \u2014 no setup needed)${v}`),console.log(` ${M}Pre-configured cloud AI, ready to use immediately${v}`),console.log(),console.log(` ${G}${xe}2${v}. ${xe}Custom Provider${v} ${M}(bring your own API key)${v}`),console.log(` ${M}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${v}`),console.log(),(await H(e,` ${M}Your choice (1-2):${v} `)).trim()){case"1":{t.provider=Rt.provider,t.apiUrl=Rt.apiUrl,t.apiKey=Am(),t.model=Rt.model,ze(t),console.log(),console.log(`${_r} \u2713 Hablas Integrated Engine activated!${v}`),console.log(`${M} Model: ${Rt.model}${v}`),console.log(`${M} API: ${Rt.apiUrl}${v}`),console.log(`${M} No API key needed \u2014 everything is pre-configured.${v}`);break}case"2":{switch(console.log(),console.log(`${M} Select your provider:${v}`),console.log(` ${G}a${v}. Ollama (local, free, private)`),console.log(` ${G}b${v}. OpenAI API`),console.log(` ${G}c${v}. Groq (fast, free tier)`),console.log(` ${G}d${v}. OpenRouter (many models)`),console.log(` ${G}e${v}. Together AI`),console.log(` ${G}f${v}. DeepSeek`),console.log(` ${G}g${v}. Custom OpenAI-compatible API`),console.log(` ${G}h${v}. NVIDIA NIM (powerful cloud models)`),console.log(),(await H(e,` ${M}Your choice (a-h):${v} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await H(e,` ${M}Ollama host [http://localhost:11434]:${v} `)).trim(),i=(await H(e,` ${M}Model [qwen2.5-coder:7b]:${v} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await H(e,` ${M}OpenAI API Key (sk-...):${v} `)).trim(),i=(await H(e,` ${M}Model [gpt-4o]:${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.openai.com/v1",t.apiKey=s,t.model=i||"gpt-4o";break}case"c":{let s=(await H(e,` ${M}Groq API Key (gsk_...):${v} `)).trim(),i=(await H(e,` ${M}Model [llama-3.3-70b-versatile]:${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.groq.com/openai/v1",t.apiKey=s,t.model=i||"llama-3.3-70b-versatile";break}case"d":{let s=(await H(e,` ${M}OpenRouter API Key (sk-or-...):${v} `)).trim(),i=(await H(e,` ${M}Model [anthropic/claude-3.5-sonnet]:${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://openrouter.ai/api/v1",t.apiKey=s,t.model=i||"anthropic/claude-3.5-sonnet";break}case"e":{let s=(await H(e,` ${M}Together API Key:${v} `)).trim(),i=(await H(e,` ${M}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.together.xyz/v1",t.apiKey=s,t.model=i||"meta-llama/Llama-3.3-70B-Instruct-Turbo";break}case"f":{let s=(await H(e,` ${M}DeepSeek API Key:${v} `)).trim(),i=(await H(e,` ${M}Model [deepseek-chat]:${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.deepseek.com/v1",t.apiKey=s,t.model=i||"deepseek-chat";break}case"g":{let s=(await H(e,` ${M}API base URL:${v} `)).trim(),i=(await H(e,` ${M}API key (optional):${v} `)).trim(),o=(await H(e,` ${M}Model ID:${v} `)).trim();if(!s){console.log(`${be} \u26A0 URL is required \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await H(e,` ${M}NVIDIA API Key (nvapi-...):${v} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${v}`),console.log(`${M} Get your key at: https://build.nvidia.com/${v}`),e.close();return}console.log(),console.log(`${M} Available NVIDIA models:${v}`),ue.models.forEach((a,l)=>{console.log(` ${G}${l+1}${v}. ${a}`)}),console.log();let i=(await H(e,` ${M}Model number [1]:${v} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=ue.apiUrl,t.apiKey=s,t.model=ue.models[o]||ue.defaultModel;break}default:console.log(`${be} \u26A0 Invalid choice${v}`),e.close();return}ze(t),console.log(),console.log(`${_r} \u2713 Custom provider configured successfully${v}`),console.log(`${M} Provider: ${t.provider}${v}`),console.log(`${M} Model: ${t.model}${v}`);break}default:console.log(`${be} \u26A0 Invalid choice \u2014 please select 1 or 2${v}`),e.close();return}console.log(),console.log(`${xe}${_r} \u2713 Setup complete!${v}`),console.log(`${M} Use ${G}hablas${v}${M} for interactive mode or ${G}hablas run "..."${v}${M} for one-shot execution.${v}`),console.log(),e.close()}var Tl=jo(),X=new _s;X.name("hablas").description(`Hablas CLI v${Tl} \u2014 single-agent engineering runtime for the terminal.`).version(Tl).option("-m, --model <model>","Model to use").option("-p, --project <path>","Working directory").option("--host <url>","Ollama host URL").option("--provider <type>","LLM provider: ollama | custom | nvidia").option("--api-url <url>","Custom API base URL").option("--api-key <key>","API key for custom or nvidia provider").option("--auto","Auto mode \u2014 skip tool confirmations where allowed").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--setup","Run setup wizard");X.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=X.opts(),r=Ve({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=Ln(r);await gl(t,r,n)});X.command("doctor").description("Run system diagnostics").action(async()=>{let t=X.opts(),e=Ve({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await wr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(br(r))});X.command("info").description("Show workspace information").action(async()=>{let t=X.opts(),e=Ve({project:t.project});console.log(""),console.log(cr(st(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});X.command("security").description("Run a security scan on the current project").action(async()=>{let t=X.opts(),e=Ve({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(bl(wl(r)))});X.command("stats").description("Show local usage statistics").action(async()=>{console.log(vl(_l()))});X.action(async()=>{let t=X.opts(),e=Ve({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 $l(e);return}let r=Ln(e);await ml(e,r)});X.parse();
489
+ `)}var Tl=A(require("readline"));var G="\x1B[36m",_r="\x1B[32m",be="\x1B[33m",P="\x1B[2m",Se="\x1B[1m",k="\x1B[0m",Mm="\x1B[35m";function H(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function Pm(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var Rt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function Cl(t){let e=Tl.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${Se}${G} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${k}`),console.log(`${Se}${G} hablas \u2014 Setup Wizard${k}`),console.log(`${P} Configure your AI provider and model${k}`),console.log(`${Se}${G} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${k}`),console.log(),console.log(`${Se} Choose your setup:${k}`),console.log(),console.log(` ${Mm}${Se}1${k}. ${Se}Hablas Integrated Engine${k} ${_r}(instant \u2014 no setup needed)${k}`),console.log(` ${P}Pre-configured cloud AI, ready to use immediately${k}`),console.log(),console.log(` ${G}${Se}2${k}. ${Se}Custom Provider${k} ${P}(bring your own API key)${k}`),console.log(` ${P}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${k}`),console.log(),(await H(e,` ${P}Your choice (1-2):${k} `)).trim()){case"1":{t.provider=Rt.provider,t.apiUrl=Rt.apiUrl,t.apiKey=Pm(),t.model=Rt.model,Ke(t),console.log(),console.log(`${_r} \u2713 Hablas Integrated Engine activated!${k}`),console.log(`${P} Model: ${Rt.model}${k}`),console.log(`${P} API: ${Rt.apiUrl}${k}`),console.log(`${P} No API key needed \u2014 everything is pre-configured.${k}`);break}case"2":{switch(console.log(),console.log(`${P} Select your provider:${k}`),console.log(` ${G}a${k}. Ollama (local, free, private)`),console.log(` ${G}b${k}. OpenAI API`),console.log(` ${G}c${k}. Groq (fast, free tier)`),console.log(` ${G}d${k}. OpenRouter (many models)`),console.log(` ${G}e${k}. Together AI`),console.log(` ${G}f${k}. DeepSeek`),console.log(` ${G}g${k}. Custom OpenAI-compatible API`),console.log(` ${G}h${k}. NVIDIA NIM (powerful cloud models)`),console.log(),(await H(e,` ${P}Your choice (a-h):${k} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await H(e,` ${P}Ollama host [http://localhost:11434]:${k} `)).trim(),i=(await H(e,` ${P}Model [qwen2.5-coder:7b]:${k} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await H(e,` ${P}OpenAI API Key (sk-...):${k} `)).trim(),i=(await H(e,` ${P}Model [gpt-4o]:${k} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.openai.com/v1",t.apiKey=s,t.model=i||"gpt-4o";break}case"c":{let s=(await H(e,` ${P}Groq API Key (gsk_...):${k} `)).trim(),i=(await H(e,` ${P}Model [llama-3.3-70b-versatile]:${k} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.groq.com/openai/v1",t.apiKey=s,t.model=i||"llama-3.3-70b-versatile";break}case"d":{let s=(await H(e,` ${P}OpenRouter API Key (sk-or-...):${k} `)).trim(),i=(await H(e,` ${P}Model [anthropic/claude-3.5-sonnet]:${k} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://openrouter.ai/api/v1",t.apiKey=s,t.model=i||"anthropic/claude-3.5-sonnet";break}case"e":{let s=(await H(e,` ${P}Together API Key:${k} `)).trim(),i=(await H(e,` ${P}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${k} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.together.xyz/v1",t.apiKey=s,t.model=i||"meta-llama/Llama-3.3-70B-Instruct-Turbo";break}case"f":{let s=(await H(e,` ${P}DeepSeek API Key:${k} `)).trim(),i=(await H(e,` ${P}Model [deepseek-chat]:${k} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.deepseek.com/v1",t.apiKey=s,t.model=i||"deepseek-chat";break}case"g":{let s=(await H(e,` ${P}API base URL:${k} `)).trim(),i=(await H(e,` ${P}API key (optional):${k} `)).trim(),o=(await H(e,` ${P}Model ID:${k} `)).trim();if(!s){console.log(`${be} \u26A0 URL is required \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await H(e,` ${P}NVIDIA API Key (nvapi-...):${k} `)).trim();if(!s){console.log(`${be} \u26A0 No key provided \u2014 cancelled${k}`),console.log(`${P} Get your key at: https://build.nvidia.com/${k}`),e.close();return}console.log(),console.log(`${P} Available NVIDIA models:${k}`),ee.models.forEach((a,l)=>{console.log(` ${G}${l+1}${k}. ${a}`)}),console.log();let i=(await H(e,` ${P}Model number [1]:${k} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=ee.apiUrl,t.apiKey=s,t.model=ee.models[o]||ee.defaultModel;break}default:console.log(`${be} \u26A0 Invalid choice${k}`),e.close();return}Ke(t),console.log(),console.log(`${_r} \u2713 Custom provider configured successfully${k}`),console.log(`${P} Provider: ${t.provider}${k}`),console.log(`${P} Model: ${t.model}${k}`);break}default:console.log(`${be} \u26A0 Invalid choice \u2014 please select 1 or 2${k}`),e.close();return}console.log(),console.log(`${Se}${_r} \u2713 Setup complete!${k}`),console.log(`${P} Use ${G}hablas${k}${P} for interactive mode or ${G}hablas run "..."${k}${P} for one-shot execution.${k}`),console.log(),e.close()}var Al=Uo(),X=new $s;X.name("hablas").description(`Hablas CLI v${Al} \u2014 single-agent engineering runtime for the terminal.`).version(Al).option("-m, --model <model>","Model to use").option("-p, --project <path>","Working directory").option("--host <url>","Ollama host URL").option("--provider <type>","LLM provider: ollama | custom | nvidia").option("--api-url <url>","Custom API base URL").option("--api-key <key>","API key for custom or nvidia provider").option("--auto","Auto mode \u2014 skip tool confirmations where allowed").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--setup","Run setup wizard");X.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=X.opts(),r=ze({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=Ln(r);await wl(t,r,n)});X.command("doctor").description("Run system diagnostics").action(async()=>{let t=X.opts(),e=ze({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await wr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(br(r))});X.command("info").description("Show workspace information").action(async()=>{let t=X.opts(),e=ze({project:t.project});console.log(""),console.log(cr(it(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});X.command("security").description("Run a security scan on the current project").action(async()=>{let t=X.opts(),e=ze({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(xl(Sl(r)))});X.command("stats").description("Show local usage statistics").action(async()=>{console.log($l(kl()))});X.action(async()=>{let t=X.opts(),e=ze({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 Cl(e);return}let r=Ln(e);await yl(e,r)});X.parse();