hablas-ai 2.2.12 → 2.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +151 -122
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,117 +1,117 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var pc=Object.create;var Is=Object.defineProperty;var mc=Object.getOwnPropertyDescriptor;var hc=Object.getOwnPropertyNames;var gc=Object.getPrototypeOf,yc=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var wc=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of hc(e))!yc.call(t,s)&&s!==r&&Is(t,s,{get:()=>e[s],enumerable:!(n=mc(e,s))||n.enumerable});return t};var C=(t,e,r)=>(r=t!=null?pc(gc(t)):{},wc(e||!t||!t.__esModule?Is(r,"default",{value:t,enumerable:!0}):r,t));var bt=R(Fr=>{var Ut=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}},Dr=class extends Ut{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Fr.CommanderError=Ut;Fr.InvalidArgumentError=Dr});var Bt=R(qr=>{var{InvalidArgumentError:bc}=bt(),Nr=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 bc(`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 xc(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}qr.Argument=Nr;qr.humanReadableArgName=xc});var Br=R(Rs=>{var{humanReadableArgName:Sc}=Bt(),Ur=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=>Sc(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(f,h){if(h){let g=`${f.padEnd(n+o)}${h}`;return r.wrap(g,s-i,n+o)}return f}function l(f){return f.join(`
3
- `).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(c=c.concat([r.wrap(u,s,0),""]));let d=r.visibleArguments(e).map(f=>a(r.argumentTerm(f),r.argumentDescription(f)));d.length>0&&(c=c.concat(["Arguments:",l(d),""]));let m=r.visibleOptions(e).map(f=>a(r.optionTerm(f),r.optionDescription(f)));if(m.length>0&&(c=c.concat(["Options:",l(m),""])),this.showGlobalOptions){let f=r.visibleGlobalOptions(e).map(h=>a(r.optionTerm(h),r.optionDescription(h)));f.length>0&&(c=c.concat(["Global Options:",l(f),""]))}let p=r.visibleCommands(e).map(f=>a(r.subcommandTerm(f),r.subcommandDescription(f)));return p.length>0&&(c=c.concat(["Commands:",l(p),""])),c.join(`
2
+ "use strict";var Rc=Object.create;var Fs=Object.defineProperty;var Ic=Object.getOwnPropertyDescriptor;var Mc=Object.getOwnPropertyNames;var jc=Object.getPrototypeOf,Pc=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Lc=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Mc(e))!Pc.call(t,s)&&s!==r&&Fs(t,s,{get:()=>e[s],enumerable:!(n=Ic(e,s))||n.enumerable});return t};var C=(t,e,r)=>(r=t!=null?Rc(jc(t)):{},Lc(e||!t||!t.__esModule?Fs(r,"default",{value:t,enumerable:!0}):r,t));var _t=I(Br=>{var Vt=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}},qr=class extends Vt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Br.CommanderError=Vt;Br.InvalidArgumentError=qr});var Kt=I(Wr=>{var{InvalidArgumentError:Dc}=_t(),Hr=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 Dc(`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 Fc(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Wr.Argument=Hr;Wr.humanReadableArgName=Fc});var Kr=I(Ns=>{var{humanReadableArgName:Nc}=Kt(),Vr=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=>Nc(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(f,g){if(g){let h=`${f.padEnd(n+o)}${g}`;return r.wrap(h,s-i,n+o)}return f}function l(f){return f.join(`
3
+ `).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(c=c.concat([r.wrap(u,s,0),""]));let d=r.visibleArguments(e).map(f=>a(r.argumentTerm(f),r.argumentDescription(f)));d.length>0&&(c=c.concat(["Arguments:",l(d),""]));let m=r.visibleOptions(e).map(f=>a(r.optionTerm(f),r.optionDescription(f)));if(m.length>0&&(c=c.concat(["Options:",l(m),""])),this.showGlobalOptions){let f=r.visibleGlobalOptions(e).map(g=>a(r.optionTerm(g),r.optionDescription(g)));f.length>0&&(c=c.concat(["Global Options:",l(f),""]))}let p=r.visibleCommands(e).map(f=>a(r.subcommandTerm(f),r.subcommandDescription(f)));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
  `),u=" ".repeat(n),m="\\s\u200B",p=new RegExp(`
7
- |.{1,${a-1}}([${m}]|$)|[^${m}]+?([${m}]|$)`,"g"),f=c.match(p)||[];return l+f.map((h,g)=>h===`
8
- `?"":(g>0?u:"")+h.trimEnd()).join(`
9
- `)}};Rs.Help=Ur});var zr=R(Vr=>{var{InvalidArgumentError:vc}=bt(),Hr=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=kc(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 vc(`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 _c(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Wr=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 _c(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function kc(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}}Vr.Option=Hr;Vr.DualOptions=Wr});var js=R(Ms=>{function $c(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 Tc(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=$c(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?`
7
+ |.{1,${a-1}}([${m}]|$)|[^${m}]+?([${m}]|$)`,"g"),f=c.match(p)||[];return l+f.map((g,h)=>g===`
8
+ `?"":(h>0?u:"")+g.trimEnd()).join(`
9
+ `)}};Ns.Help=Vr});var Yr=I(Jr=>{var{InvalidArgumentError:Uc}=_t(),zr=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=Bc(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 Uc(`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 qc(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Gr=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 qc(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Bc(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}}Jr.Option=zr;Jr.DualOptions=Gr});var qs=I(Us=>{function Hc(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 Wc(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=Hc(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]}?)`:""}Ms.suggestSimilar=Tc});var Ns=R(Fs=>{var Cc=require("node:events").EventEmitter,Kr=require("node:child_process"),ye=require("node:path"),Gr=require("node:fs"),B=require("node:process"),{Argument:Ec,humanReadableArgName:Ac}=Bt(),{CommanderError:Jr}=bt(),{Help:Oc}=Br(),{Option:Ps,DualOptions:Ic}=zr(),{suggestSimilar:Ls}=js(),Yr=class t extends Cc{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=>B.stdout.write(r),writeErr:r=>B.stderr.write(r),getOutHelpWidth:()=>B.stdout.isTTY?B.stdout.columns:void 0,getErrHelpWidth:()=>B.stderr.isTTY?B.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 Oc,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 Ec(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 Jr(e,r,n)),B.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 Ps(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 Ps)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 u=a.exec(l);return u?u[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){B.versions?.electron&&(r.from="electron");let s=B.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(r.from="eval")}e===void 0&&(e=B.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":B.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let m=ye.resolve(u,d);if(Gr.existsSync(m))return m;if(s.includes(ye.extname(d)))return;let p=s.find(f=>Gr.existsSync(`${m}${f}`));if(p)return`${m}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Gr.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=ye.resolve(ye.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=ye.basename(this._scriptPath,ye.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}n=s.includes(ye.extname(o));let l;B.platform!=="win32"?n?(r.unshift(o),r=Ds(B.execArgv).concat(r),l=Kr.spawn(B.argv[0],r,{stdio:"inherit"})):l=Kr.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=Ds(B.execArgv).concat(r),l=Kr.spawn(B.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{B.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let c=this._exitCallback;l.on("close",u=>{u=u??1,c?c(new Jr(u,"commander.executeSubCommandAsync","(close)")):B.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",m=`'${o}' does not exist
11
+ (Did you mean ${n[0]}?)`:""}Us.suggestSimilar=Wc});var Ks=I(Vs=>{var Vc=require("node:events").EventEmitter,Xr=require("node:child_process"),ve=require("node:path"),Qr=require("node:fs"),H=require("node:process"),{Argument:Kc,humanReadableArgName:zc}=Kt(),{CommanderError:Zr}=_t(),{Help:Gc}=Kr(),{Option:Bs,DualOptions:Jc}=Yr(),{suggestSimilar:Hs}=qs(),en=class t extends Vc{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=>H.stdout.write(r),writeErr:r=>H.stderr.write(r),getOutHelpWidth:()=>H.stdout.isTTY?H.stdout.columns:void 0,getErrHelpWidth:()=>H.stderr.isTTY?H.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 Gc,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 Kc(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 Zr(e,r,n)),H.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 Bs(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 Bs)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 u=a.exec(l);return u?u[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){H.versions?.electron&&(r.from="electron");let s=H.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(r.from="eval")}e===void 0&&(e=H.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":H.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let m=ve.resolve(u,d);if(Qr.existsSync(m))return m;if(s.includes(ve.extname(d)))return;let p=s.find(f=>Qr.existsSync(`${m}${f}`));if(p)return`${m}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Qr.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=ve.resolve(ve.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=ve.basename(this._scriptPath,ve.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}n=s.includes(ve.extname(o));let l;H.platform!=="win32"?n?(r.unshift(o),r=Ws(H.execArgv).concat(r),l=Xr.spawn(H.argv[0],r,{stdio:"inherit"})):l=Xr.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=Ws(H.execArgv).concat(r),l=Xr.spawn(H.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{H.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let c=this._exitCallback;l.on("close",u=>{u=u??1,c?c(new Zr(u,"commander.executeSubCommandAsync","(close)")):H.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",m=`'${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
- - ${d}`;throw new Error(m)}else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)B.exit(1);else{let d=new Jr(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,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 u=i.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;i.length>0&&!o(i[0])&&(u=i.shift()),this.emit(`option:${c.name()}`,u)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),u=this._findOption(l.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,l.slice(c+1));continue}}if(o(l)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(l)){r.push(l),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){r.push(l),i.length>0&&r.push(...i);break}else if(this._defaultCommandName){n.push(l),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(l),i.length>0&&s.push(...i);break}s.push(l)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
17
+ - ${d}`;throw new Error(m)}else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)H.exit(1);else{let d=new Zr(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,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 u=i.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;i.length>0&&!o(i[0])&&(u=i.shift()),this.emit(`option:${c.name()}`,u)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),u=this._findOption(l.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,l.slice(c+1));continue}}if(o(l)&&(s=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 B.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()}`,B.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ic(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()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:u||o},s=o=>{let a=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=Ls(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=Ls(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=>Ac(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=ye.basename(e,ye.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=B.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 H.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()}`,H.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Jc(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()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:u||o},s=o=>{let a=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=Hs(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=Hs(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=>zc(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=ve.basename(e,ve.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=H.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 Ds(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})}Fs.Command=Yr});var Hs=R(re=>{var{Argument:qs}=Bt(),{Command:Xr}=Ns(),{CommanderError:Rc,InvalidArgumentError:Us}=bt(),{Help:Mc}=Br(),{Option:Bs}=zr();re.program=new Xr;re.createCommand=t=>new Xr(t);re.createOption=(t,e)=>new Bs(t,e);re.createArgument=(t,e)=>new qs(t,e);re.Command=Xr;re.Option=Bs;re.Argument=qs;re.Help=Mc;re.CommanderError=Rc;re.InvalidArgumentError=Us;re.InvalidOptionArgumentError=Us});var en=R((hy,Ys)=>{"use strict";var xt=t=>t&&typeof t.message=="string",Zr=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return xt(r)?r:void 0}else return xt(e)?e:void 0},Gs=(t,e)=>{if(!xt(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
- causes have become circular...`;let n=Zr(t);return n?(e.add(t),r+`
25
- caused by: `+Gs(n,e)):r},jc=t=>Gs(t,new Set),Js=(t,e,r)=>{if(!xt(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=Zr(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+Js(s,e,i)}else return n},Pc=t=>Js(t,new Set);Ys.exports={isErrorLike:xt,getErrorCause:Zr,stackWithCauses:jc,messageWithCauses:Pc}});var tn=R((gy,Qs)=>{"use strict";var Lc=Symbol("circular-ref-tag"),Ht=Symbol("pino-raw-err-ref"),Xs=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[Ht]},set:function(t){this[Ht]=t}}});Object.defineProperty(Xs,Ht,{writable:!0,value:{}});Qs.exports={pinoErrProto:Xs,pinoErrorSymbols:{seen:Lc,rawSymbol:Ht}}});var ti=R((yy,ei)=>{"use strict";ei.exports=nn;var{messageWithCauses:Dc,stackWithCauses:Fc,isErrorLike:Zs}=en(),{pinoErrProto:Nc,pinoErrorSymbols:qc}=tn(),{seen:rn}=qc,{toString:Uc}=Object.prototype;function nn(t){if(!Zs(t))return t;t[rn]=void 0;let e=Object.create(Nc);e.type=Uc.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=Dc(t),e.stack=Fc(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>nn(r)));for(let r in t)if(e[r]===void 0){let n=t[r];Zs(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,rn)&&(e[r]=nn(n)):e[r]=n}return delete t[rn],e.raw=t,e}});var ni=R((wy,ri)=>{"use strict";ri.exports=Vt;var{isErrorLike:sn}=en(),{pinoErrProto:Bc,pinoErrorSymbols:Hc}=tn(),{seen:Wt}=Hc,{toString:Wc}=Object.prototype;function Vt(t){if(!sn(t))return t;t[Wt]=void 0;let e=Object.create(Bc);e.type=Wc.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=>Vt(r))),sn(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,Wt)&&(e.cause=Vt(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];sn(n)?Object.prototype.hasOwnProperty.call(n,Wt)||(e[r]=Vt(n)):e[r]=n}return delete t[Wt],e.raw=t,e}});var ai=R((by,oi)=>{"use strict";oi.exports={mapHttpRequest:Vc,reqSerializer:ii};var on=Symbol("pino-raw-req-ref"),si=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[on]},set:function(t){this[on]=t}}});Object.defineProperty(si,on,{writable:!0,value:{}});function ii(t){let e=t.info||t.socket,r=Object.create(si);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 Vc(t){return{req:ii(t)}}});var fi=R((xy,ui)=>{"use strict";ui.exports={mapHttpResponse:zc,resSerializer:ci};var an=Symbol("pino-raw-res-ref"),li=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[an]},set:function(t){this[an]=t}}});Object.defineProperty(li,an,{writable:!0,value:{}});function ci(t){let e=Object.create(li);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function zc(t){return{res:ci(t)}}});var cn=R((Sy,di)=>{"use strict";var ln=ti(),Kc=ni(),zt=ai(),Kt=fi();di.exports={err:ln,errWithCause:Kc,mapHttpRequest:zt.mapHttpRequest,mapHttpResponse:Kt.mapHttpResponse,req:zt.reqSerializer,res:Kt.resSerializer,wrapErrorSerializer:function(e){return e===ln?e:function(n){return e(ln(n))}},wrapRequestSerializer:function(e){return e===zt.reqSerializer?e:function(n){return e(zt.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Kt.resSerializer?e:function(n){return e(Kt.resSerializer(n))}}}});var un=R((vy,pi)=>{"use strict";function Gc(t,e){return e}pi.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=Gc;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 bi=R((_y,wi)=>{"use strict";function fn(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]=fn(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]=fn(t[r]));return e}return t}function mi(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 hi(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 gi(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 Gt=Symbol("PATH_NOT_FOUND");function Jc(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return Gt;r=r[n]}return r}function Yc(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 Xc(t,e,r,n=!1){for(let s of e){let i=mi(s);if(i.includes("*"))yi(t,i,r,s,n);else if(n)gi(t,i);else{let o=Jc(t,i);if(o===Gt)continue;let a=typeof r=="function"?r(o,i):r;hi(t,i,a)}}}function yi(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()],u=typeof r=="function"?r(a[l],c):r;a[l]=u}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],u=typeof r=="function"?r(a[l],c):r;a[l]=u}}else Qc(t,e,r,i,n,s)}function Qc(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function c(u,d){if(d===o.length){if(Array.isArray(u))for(let m=0;m<u.length;m++)l[d]=m.toString(),c(u[m],d+1);else if(typeof u=="object"&&u!==null)for(let m in u)l[d]=m,c(u[m],d+1)}else if(d<o.length){let m=o[d];u&&typeof u=="object"&&u!==null&&m in u&&(l[d]=m,c(u[m],d+1))}else if(a.includes("*"))yi(u,a,typeof r=="function"?(p,f)=>{let h=[...l.slice(0,d),...f];return r(p,h)}:r,s,i);else if(i)gi(u,a);else{let m=typeof r=="function"?r(Yc(u,a),[...l.slice(0,d),...a]):r;hi(u,a,m)}}if(o.length===0)c(t,0);else{let u=t;for(let d=0;d<o.length;d++){let m=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[m],l[d]=m}u!=null&&c(u,o.length)}}function Zc(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=mi(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 eu(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 tu(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 ru(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)tu(e)}function nu(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;ru(e);let o=Zc(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let c=eu(l,o),u=l,d=r;return typeof r=="function"&&(d=r),Xc(c,e,d,i),n===!1?(c.restore=function(){return fn(u)},c):typeof n=="function"?n(c):JSON.stringify(c)}}wi.exports=nu});var et=R((ky,xi)=>{"use strict";var su=Symbol("pino.setLevel"),iu=Symbol("pino.getLevel"),ou=Symbol("pino.levelVal"),au=Symbol("pino.levelComp"),lu=Symbol("pino.useLevelLabels"),cu=Symbol("pino.useOnlyCustomLevels"),uu=Symbol("pino.mixin"),fu=Symbol("pino.lsCache"),du=Symbol("pino.chindings"),pu=Symbol("pino.asJson"),mu=Symbol("pino.write"),hu=Symbol("pino.redactFmt"),gu=Symbol("pino.time"),yu=Symbol("pino.timeSliceIndex"),wu=Symbol("pino.stream"),bu=Symbol("pino.stringify"),xu=Symbol("pino.stringifySafe"),Su=Symbol("pino.stringifiers"),vu=Symbol("pino.end"),_u=Symbol("pino.formatOpts"),ku=Symbol("pino.messageKey"),$u=Symbol("pino.errorKey"),Tu=Symbol("pino.nestedKey"),Cu=Symbol("pino.nestedKeyStr"),Eu=Symbol("pino.mixinMergeStrategy"),Au=Symbol("pino.msgPrefix"),Ou=Symbol("pino.wildcardFirst"),Iu=Symbol.for("pino.serializers"),Ru=Symbol.for("pino.formatters"),Mu=Symbol.for("pino.hooks"),ju=Symbol.for("pino.metadata");xi.exports={setLevelSym:su,getLevelSym:iu,levelValSym:ou,levelCompSym:au,useLevelLabelsSym:lu,mixinSym:uu,lsCacheSym:fu,chindingsSym:du,asJsonSym:pu,writeSym:mu,serializersSym:Iu,redactFmtSym:hu,timeSym:gu,timeSliceIndexSym:yu,streamSym:wu,stringifySym:bu,stringifySafeSym:xu,stringifiersSym:Su,endSym:vu,formatOptsSym:_u,messageKeySym:ku,errorKeySym:$u,nestedKeySym:Tu,wildcardFirstSym:Ou,needsMetadataGsym:ju,useOnlyCustomLevelsSym:cu,formattersSym:Ru,hooksSym:Mu,nestedKeyStrSym:Cu,mixinMergeStrategySym:Eu,msgPrefixSym:Au}});var pn=R(($y,ki)=>{"use strict";var Si=bi(),{redactFmtSym:Pu,wildcardFirstSym:Jt}=et(),dn=/[^.[\]]+|\[([^[\]]*?)\]/g,vi="[Redacted]",_i=!1;function Lu(t,e){let{paths:r,censor:n,remove:s}=Du(t),i=r.reduce((l,c)=>{dn.lastIndex=0;let u=dn.exec(c),d=dn.exec(c),m=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(m==="*"&&(m=Jt),d===null)return l[m]=null,l;if(l[m]===null)return l;let{index:p}=d,f=`${c.substr(p,c.length-1)}`;return l[m]=l[m]||[],m!==Jt&&l[m].length===0&&l[m].push(...l[Jt]||[]),m===Jt&&Object.keys(l).forEach(function(h){l[h]&&l[h].push(f)}),l[m].push(f),l},{}),o={[Pu]:Si({paths:r,censor:n,serialize:e,strict:_i,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]=u=>a(u,[c]);else{let u=typeof n=="function"?(d,m)=>n(d,[c,...m]):n;l[c]=Si({paths:i[c],censor:u,serialize:e,strict:_i,remove:s})}return l},o)}function Du(t){if(Array.isArray(t))return t={paths:t,censor:vi},t;let{paths:e,censor:r=vi,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}}ki.exports=Lu});var Ci=R((Ty,Ti)=>{"use strict";var Fu=()=>"",Nu=()=>`,"time":${Date.now()}`,qu=()=>`,"time":${Math.round(Date.now()/1e3)}`,Uu=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,Bu=1000000n,$i=1000000000n,Hu=BigInt(Date.now())*Bu,Wu=process.hrtime.bigint(),Vu=()=>{let t=process.hrtime.bigint()-Wu,e=Hu+t,r=e/$i,n=e%$i,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"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${u}:${d}.${n.toString().padStart(9,"0")}Z"`};Ti.exports={nullTime:Fu,epochTime:Nu,unixTime:qu,isoTime:Uu,isoTimeNano:Vu}});var Ai=R((Cy,Ei)=>{"use strict";function zu(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}Ei.exports=Ku;function Ku(t,e,r){var n=r&&r.stringify||zu,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="",u=1-s,d=-1,m=t&&t.length||0,p=0;p<m;){if(t.charCodeAt(p)===37&&p+1<m){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<p&&(c+=t.slice(d,p)),c+=Number(e[u]),d=p+2,p++;break;case 105:if(u>=l||e[u]==null)break;d<p&&(c+=t.slice(d,p)),c+=Math.floor(Number(e[u])),d=p+2,p++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<p&&(c+=t.slice(d,p));var f=typeof e[u];if(f==="string"){c+="'"+e[u]+"'",d=p+2,p++;break}if(f==="function"){c+=e[u].name||"<anonymous>",d=p+2,p++;break}c+=n(e[u]),d=p+2,p++;break;case 115:if(u>=l)break;d<p&&(c+=t.slice(d,p)),c+=String(e[u]),d=p+2,p++;break;case 37:d<p&&(c+=t.slice(d,p)),c+="%",d=p+2,p++,u--;break}++u}++p}return d===-1?t:(d<m&&(c+=t.slice(d)),c)}});var hn=R((Ey,mn)=>{"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));mn.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(););};mn.exports=t}});var Di=R((Ay,Li)=>{"use strict";var F=require("fs"),Gu=require("events"),Ju=require("util").inherits,Oi=require("path"),yn=hn(),Yu=require("assert"),Yt=100,Xt=Buffer.allocUnsafe(0),Xu=16*1024,Ii="buffer",Ri="utf8",[Qu,Zu]=(process.versions.node||"0.0").split(".").map(Number),ef=Qu>=22&&Zu>=7;function Mi(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(Oi.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(Oi.dirname(t),{recursive:!0},i=>{if(i)return r(i);F.open(t,n,s,r)}):F.open(t,n,s,r)}function fe(t){if(!(this instanceof fe))return new fe(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:u,fsync:d,contentMode:m,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||Xu,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=p,this.retryEAGAIN=u||(()=>!0),this.mkdir=c||!1;let f,h;if(m===Ii)this._writingBuf=Xt,this.write=nf,this.flush=of,this.flushSync=lf,this._actualWrite=uf,f=()=>F.writeSync(this.fd,this._writingBuf),h=()=>F.write(this.fd,this._writingBuf,this.release);else if(m===void 0||m===Ri)this._writingBuf="",this.write=rf,this.flush=sf,this.flushSync=af,this._actualWrite=cf,f=()=>Buffer.isBuffer(this._writingBuf)?F.writeSync(this.fd,this._writingBuf):F.writeSync(this.fd,this._writingBuf,"utf8"),h=()=>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 "${Ri}" and "${Ii}", but passed ${m}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Mi(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,S)=>{if(g){if((g.code==="EAGAIN"||g.code==="EBUSY")&&this.retryEAGAIN(g,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{yn(Yt),this.release(void 0,0)}catch(v){this.release(v)}else setTimeout(h,Yt);else this._writing=!1,this.emit("error",g);return}this.emit("write",S);let b=gn(this._writingBuf,this._len,S);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){h();return}try{do{let v=f(),E=gn(this._writingBuf,this._len,v);this._len=E.len,this._writingBuf=E.writingBuf}while(this._writingBuf.length)}catch(v){this.release(v);return}}this._fsync&&F.fsyncSync(this.fd);let x=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):x>this.minLength?this._actualWrite():this._ending?x>0?this._actualWrite():(this._writing=!1,Qt(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(tf,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 gn(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 tf(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Ju(fe,Gu);function ji(t,e){return t.length===0?Xt:t.length===1?t[0]:Buffer.concat(t,e)}function rf(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 nf(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 Pi(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 sf(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&&Pi.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function of(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&&Pi.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}fe.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)})}),Mi(this.file,this)};fe.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():Qt(this)))};function af(){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=gn(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;yn(Yt)}}try{F.fsyncSync(this.fd)}catch{}}function lf(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=Xt);let t=Xt;for(;this._bufs.length||t.length;){t.length<=0&&(t=ji(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;yn(Yt)}}}fe.prototype.destroy=function(){this.destroyed||Qt(this)};function cf(){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 uf(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:ji(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 ef&&(this._writingBuf=Buffer.from(this._writingBuf)),F.write(this.fd,this._writingBuf,t)}function Qt(t){if(t.fd===-1){t.once("ready",Qt.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Yu(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")}}fe.SonicBoom=fe;fe.default=fe;Li.exports=fe});var wn=R((Oy,Bi)=>{"use strict";var de={exit:[],beforeExit:[]},Fi={exit:pf,beforeExit:mf},tt;function ff(){tt===void 0&&(tt=new FinalizationRegistry(hf))}function df(t){de[t].length>0||process.on(t,Fi[t])}function Ni(t){de[t].length>0||(process.removeListener(t,Fi[t]),de.exit.length===0&&de.beforeExit.length===0&&(tt=void 0))}function pf(){qi("exit")}function mf(){qi("beforeExit")}function qi(t){for(let e of de[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}de[t]=[]}function hf(t){for(let e of["exit","beforeExit"]){let r=de[e].indexOf(t);de[e].splice(r,r+1),Ni(e)}}function Ui(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");df(t);let n=new WeakRef(e);n.fn=r,ff(),tt.register(e,n),de[t].push(n)}function gf(t,e){Ui("exit",t,e)}function yf(t,e){Ui("beforeExit",t,e)}function wf(t){if(tt!==void 0){tt.unregister(t);for(let e of["exit","beforeExit"])de[e]=de[e].filter(r=>{let n=r.deref();return n&&n!==t}),Ni(e)}}Bi.exports={register:gf,registerBeforeExit:yf,unregister:wf}});var Hi=R((Iy,bf)=>{bf.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 Vi=R((Ry,Wi)=>{"use strict";function xf(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 Sf(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(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}Wi.exports={wait:xf,waitDiff:Sf}});var Ki=R((My,zi)=>{"use strict";zi.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var io=R((jy,so)=>{"use strict";var{version:vf}=Hi(),{EventEmitter:_f}=require("events"),{Worker:kf}=require("worker_threads"),{join:$f}=require("path"),{pathToFileURL:Tf}=require("url"),{wait:Cf}=Vi(),{WRITE_INDEX:we,READ_INDEX:Fe,SEQ_INDEX:bn}=Ki(),Ef=require("buffer"),Af=require("assert"),w=Symbol("kImpl"),Of=Ef.constants.MAX_STRING_LENGTH;function Gi(){}function _n(t,e){Atomics.add(t[w].state,bn,1),e(),Atomics.add(t[w].state,bn,1),Atomics.notify(t[w].state,bn)}function Ji(t){_n(t,()=>{Atomics.store(t[w].state,Fe,0),Atomics.store(t[w].state,we,0)})}var St=class{constructor(e){this._value=e}deref(){return this._value}},Zt=class{register(){}unregister(){}},If=process.env.NODE_V8_COVERAGE?Zt:global.FinalizationRegistry||Zt,Rf=process.env.NODE_V8_COVERAGE?St:global.WeakRef||St,Yi=new If(t=>{t.exited||t.terminate()});function Mf(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||$f(__dirname,"lib","worker.js"),o=new kf(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Tf(r).href,dataBuf:t[w].dataBuf,stateBuf:t[w].stateBuf,workerData:{$context:{threadStreamVersion:vf},...n}}});return o.stream=new St(t),o.on("message",jf),o.on("exit",Zi),Yi.register(t,o),o}function Xi(t){Af(!t[w].sync),t[w].needDrain&&(t[w].needDrain=!1,t.emit("drain"))}function Qi(t){for(;;){let e=Atomics.load(t[w].state,we),r=t[w].data.length-e;if(r>0){if(t[w].bufLen===0){t[w].flushing=!1,t[w].ending?kn(t):t[w].needDrain&&process.nextTick(Xi,t);return}ro(t,r,Gi);continue}if(r===0){if(e===0&&t[w].bufLen===0)return;er(t,()=>{t.destroyed||(Ji(t),Qi(t))});return}se(t,new Error("overwritten"));return}}function jf(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 Rf(e),er(e,()=>{e[w].ready=!0,e.emit("ready")});break;case"ERROR":se(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"){se(e,new Error("this should not happen: "+t.code));break}let r=e[w].flushCallbacks.get(t.id);r&&(e[w].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:se(e,new Error("this should not happen: "+t.code))}}function Zi(t){let e=this.stream.deref();e!==void 0&&(Yi.unregister(e),e.worker.exited=!0,e.worker.off("exit",Zi),se(e,t!==0?new Error("the worker thread exited"):null))}var Sn=class extends _f{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[w]={},this[w].stateBuf=new SharedArrayBuffer(128),this[w].state=new Int32Array(this[w].stateBuf),this[w].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[w].data=Buffer.from(this[w].dataBuf),this[w].sync=e.sync||!1,this[w].ending=!1,this[w].ended=!1,this[w].needDrain=!1,this[w].destroyed=!1,this[w].flushing=!1,this[w].ready=!1,this[w].finished=!1,this[w].errored=null,this[w].closed=!1,this[w].buf=[],this[w].bufHead=0,this[w].bufLen=0,this[w].flushCallbacks=new Map,this[w].nextFlushId=0,this.worker=Mf(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[w].destroyed)return vn(this,new Error("the worker has exited")),!1;if(this[w].ending)return vn(this,new Error("the worker is ending")),!1;if(this[w].flushing&&this[w].bufLen+r.length>=Of)try{xn(this),this[w].flushing=!0}catch(n){return se(this,n),!1}if(this[w].buf.push(r),this[w].bufLen+=r.length,this[w].sync)try{return xn(this),!0}catch(n){return se(this,n),!1}return this[w].flushing||(this[w].flushing=!0,setImmediate(Qi,this)),this[w].needDrain=this[w].data.length-this[w].bufLen-Atomics.load(this[w].state,we)<=0,!this[w].needDrain}end(){this[w].destroyed||(this[w].ending=!0,kn(this))}flush(e){e=typeof e=="function"?e:Gi,eo(this,r=>{if(r){process.nextTick(e,r);return}to(this,e)})}flushSync(){this[w].destroyed||(xn(this),no(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[w].ready}get destroyed(){return this[w].destroyed}get closed(){return this[w].closed}get writable(){return!this[w].destroyed&&!this[w].ending}get writableEnded(){return this[w].ending}get writableFinished(){return this[w].finished}get writableNeedDrain(){return this[w].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[w].errored}};function eo(t,e){if(t[w].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[w].sync&&(t[w].flushing||t[w].bufLen>0)){setImmediate(eo,t,e);return}er(t,e)}function er(t,e){let r=Atomics.load(t[w].state,we);Cf(t[w].state,Fe,r,1/0,(n,s)=>{if(n){se(t,n),e(n);return}if(s!=="ok"){er(t,e);return}e()})}function to(t,e){if(t[w].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[w].ready){let n=()=>{i(),to(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[w].nextFlushId;t[w].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[w].flushCallbacks.delete(r),se(t,n),process.nextTick(e,n)}}function Pf(t,e){let r=t[w].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 vn(t,e){setImmediate(()=>{t.emit("error",e)})}function se(t,e){t[w].destroyed||(t[w].destroyed=!0,Pf(t,e),e&&(t[w].errored=e,vn(t,e)),t.worker.exited?setImmediate(()=>{t[w].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[w].closed=!0,t.emit("close")}))}function ro(t,e,r){let s=Atomics.load(t[w].state,we),i=e;for(;i>0&&t[w].bufLen!==0;){let o=t[w].bufHead,a=t[w].buf[o];if(a.length<=i){a.copy(t[w].data,s),s+=a.length,i-=a.length,t[w].bufLen-=a.length,t[w].bufHead=o+1,t[w].bufHead===t[w].buf.length?(t[w].buf.length=0,t[w].bufHead=0):t[w].bufHead>=1024&&t[w].bufHead*2>=t[w].buf.length&&(t[w].buf.splice(0,t[w].bufHead),t[w].bufHead=0);continue}a.copy(t[w].data,s,0,i),t[w].buf[o]=a.subarray(i),t[w].bufLen-=i,s+=i,i=0}return _n(t,()=>{Atomics.store(t[w].state,we,s)}),r(),!0}function kn(t){if(!(t[w].ended||!t[w].ending||t[w].flushing)){t[w].ended=!0;try{t.flushSync();let e=Atomics.load(t[w].state,Fe);_n(t,()=>{Atomics.store(t[w].state,we,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[w].state,Fe,e,1e3),e=Atomics.load(t[w].state,Fe),e===-2){se(t,new Error("end() failed"));return}if(++r===10){se(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[w].finished=!0,t.emit("finish")})}catch(e){se(t,e)}}}function xn(t){let e=()=>{t[w].ending?kn(t):t[w].needDrain&&process.nextTick(Xi,t)};for(t[w].flushing=!1;t[w].bufLen!==0;){let r=Atomics.load(t[w].state,we),n=t[w].data.length-r;if(n===0){no(t),Ji(t);continue}else if(n<0)throw new Error("overwritten");ro(t,n,e)}}function no(t){if(t[w].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[w].state,we),r=0;for(;;){let n=Atomics.load(t[w].state,Fe);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[w].state,Fe,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}so.exports=Sn});var Cn=R((Py,lo)=>{"use strict";var{createRequire:Lf}=require("module"),{existsSync:Df}=require("node:fs"),Ff=un(),{join:$n,isAbsolute:ao,sep:Nf}=require("node:path"),{fileURLToPath:qf}=require("node:url"),Uf=hn(),Tn=wn(),Bf=io();function Hf(t){Tn.register(t,Gf),Tn.registerBeforeExit(t,Jf),t.on("close",function(){Tn.unregister(t)})}function Wf(){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 Vf(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&&oo(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(oo(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function oo(t){let e=zf(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=qf(r)}catch{return!1}return ao(r)&&!Df(r)}function zf(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function Kf(t,e,r,n,s){if(!r.execArgv&&Wf()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=Vf(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new Bf({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&&Hf(i)}function a(){i.closed||(i.flushSync(),Uf(100),i.end())}return i}function Gf(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Jf(t){t.flushSync()}function Yf(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=Ff(),sync:a=!1}=t,l={...t.options},c=typeof o=="string"?[o]:o,u=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&r)throw new Error("only one of target or targets can be specified");r?(d=u["pino-worker"]||$n(__dirname,"worker.js"),l.targets=r.filter(f=>f.target).map(f=>({...f,target:p(f.target)})),l.pipelines=r.filter(f=>f.pipeline).map(f=>f.pipeline.map(h=>({...h,level:f.level,target:p(h.target)})))):e&&(d=u["pino-worker"]||$n(__dirname,"worker.js"),l.pipelines=[e.map(f=>({...f,target:p(f.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let m=r||e?"pino.transport":d;return Kf(p(d),l,i,a,m);function p(f){if(f=u[f]||f,ao(f)||f.indexOf("file://")===0)return f;if(f==="pino/file")return $n(__dirname,"..","file.js");let h;for(let g of c)try{let S=g==="node:repl"?process.cwd()+Nf:g;h=Lf(S).resolve(f);break}catch{continue}if(!h)throw new Error(`unable to determine transport target for "${f}"`);return h}}lo.exports=Yf});var nr=R((Ly,vo)=>{"use strict";var Xf=require("node:diagnostics_channel"),co=Ai(),{mapHttpRequest:Qf,mapHttpResponse:Zf}=cn(),An=Di(),uo=wn(),{lsCacheSym:ed,chindingsSym:go,writeSym:fo,serializersSym:yo,formatOptsSym:po,endSym:td,stringifiersSym:wo,stringifySym:bo,stringifySafeSym:On,wildcardFirstSym:xo,nestedKeySym:rd,formattersSym:So,messageKeySym:nd,errorKeySym:sd,nestedKeyStrSym:id,msgPrefixSym:tr}=et(),{isMainThread:od}=require("worker_threads"),ad=Cn(),[ld]=process.versions.node.split(".").map(t=>Number(t)),mo=Xf.tracingChannel("pino_asJson"),En=ld>=25?t=>JSON.stringify(t):ud;function rt(){}function cd(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=Qf(n):typeof n.setHeader=="function"&&(n=Zf(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[tr]=="string"&&i!==void 0&&i!==null&&(i=this[tr]+i),this[fo](n,co(i,o,this[po]),t)}else{let i=n===void 0?s.shift():n;typeof this[tr]=="string"&&i!==void 0&&i!==null&&(i=this[tr]+i),this[fo](null,co(i,s,this[po]),t)}}}function ud(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 fd(t,e,r,n){if(mo.hasSubscribers===!1)return ho.call(this,t,e,r,n);let s={instance:this,arguments};return mo.traceSync(ho,s,this,t,e,r,n)}function ho(t,e,r,n){let s=this[bo],i=this[On],o=this[wo],a=this[td],l=this[go],c=this[yo],u=this[So],d=this[nd],m=this[sd],p=this[ed][r]+n;p=p+l;let f;u.log&&(t=u.log(t));let h=o[xo],g="";for(let b in t)if(f=t[b],Object.prototype.hasOwnProperty.call(t,b)&&f!==void 0){c[b]?f=c[b](f):b===m&&c.err&&(f=c.err(f));let x=o[b]||h;switch(typeof f){case"undefined":case"function":continue;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":x&&(f=x(f));break;case"string":f=(x||En)(f);break;default:f=(x||s)(f,i)}if(f===void 0)continue;let v=En(b);g+=","+v+":"+f}let S="";if(e!==void 0){f=c[d]?c[d](e):e;let b=o[d]||h;switch(typeof f){case"function":break;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":b&&(f=b(f)),S=',"'+d+'":'+f;break;case"string":f=(b||En)(f),S=',"'+d+'":'+f;break;default:f=(b||s)(f,i),S=',"'+d+'":'+f}}return this[rd]&&g?p+this[id]+g.slice(1)+"}"+S+a:p+g+S+a}function dd(t,e){let r,n=t[go],s=t[bo],i=t[On],o=t[wo],a=o[xo],l=t[yo],c=t[So].bindings;e=c(e);for(let u in e)if(r=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&r!==void 0)===!0){if(r=l[u]?l[u](r):r,r=(o[u]||a||s)(r,i),r===void 0)continue;n+=',"'+u+'":'+r}return n}function pd(t){return t.write!==t.constructor.prototype.write}function rr(t){let e=new An(t);return e.on("error",r),!t.sync&&od&&(uo.register(e,md),e.on("close",function(){uo.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=rt,e.end=rt,e.flushSync=rt,e.destroy=rt;return}e.removeListener("error",r),e.emit("error",n)}}function md(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function hd(t){return function(r,n,s={},i){if(typeof s=="string")i=rr({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=rr({dest:i})}else if(s instanceof An||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof An||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=ad({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=rt),i||(pd(process.stdout)?i=process.stdout:i=rr({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function gd(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[On])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function yd(t,e,r){return{level:t,bindings:e,log:r}}function wd(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}vo.exports={noop:rt,buildSafeSonicBoom:rr,asChindings:dd,asJson:fd,genLog:cd,createArgsNormalizer:hd,stringify:gd,buildFormatters:yd,normalizeDestFileDescriptor:wd}});var sr=R((Dy,_o)=>{var bd={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},xd={ASC:"ASC",DESC:"DESC"};_o.exports={DEFAULT_LEVELS:bd,SORTING_ORDER:xd}});var Mn=R((Fy,Co)=>{"use strict";var{lsCacheSym:Sd,levelValSym:In,useOnlyCustomLevelsSym:vd,streamSym:_d,formattersSym:kd,hooksSym:$d,levelCompSym:ko}=et(),{noop:Td,genLog:Ne}=nr(),{DEFAULT_LEVELS:he,SORTING_ORDER:$o}=sr(),To={fatal:t=>{let e=Ne(he.fatal,t);return function(...r){let n=this[_d];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>Ne(he.error,t),warn:t=>Ne(he.warn,t),info:t=>Ne(he.info,t),debug:t=>Ne(he.debug,t),trace:t=>Ne(he.trace,t)},Rn=Object.keys(he).reduce((t,e)=>(t[he[e]]=e,t),{}),Cd=Object.keys(Rn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Ed(t){let e=t[kd].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[Sd]=n,t}function Ad(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 Od(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[In],s=this[In]=r[t],i=this[vd],o=this[ko],a=this[$d].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=Td;continue}this[l]=Ad(l,i)?To[l](a):Ne(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function Id(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Rd(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[ko](r,this[In])}function Md(t,e,r){return t===$o.DESC?e<=r:e>=r}function jd(t){return typeof t=="string"?Md.bind(null,t):t}function Pd(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:Rn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:he,t);return{labels:n,values:s}}function Ld(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(Rn).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:he,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function Dd(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 Fd(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values($o).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Co.exports={initialLsCache:Cd,genLsCache:Ed,levelMethods:To,getLevel:Id,setLevel:Od,isLevelEnabled:Rd,mappings:Pd,assertNoLevelCollisions:Dd,assertDefaultLevelFound:Ld,genLevelComparison:jd,assertLevelComparison:Fd}});var jn=R((Ny,Eo)=>{"use strict";Eo.exports={version:"10.3.1"}});var Lo=R((Uy,Po)=>{"use strict";var{EventEmitter:Nd}=require("node:events"),{lsCacheSym:qd,levelValSym:Ud,setLevelSym:Ln,getLevelSym:Ao,chindingsSym:or,mixinSym:Bd,asJsonSym:Io,writeSym:Hd,mixinMergeStrategySym:Wd,timeSym:Vd,timeSliceIndexSym:zd,streamSym:Ro,serializersSym:qe,formattersSym:vt,errorKeySym:Kd,messageKeySym:Gd,useOnlyCustomLevelsSym:Jd,needsMetadataGsym:Yd,redactFmtSym:Xd,stringifySym:Qd,formatOptsSym:Zd,stringifiersSym:ep,msgPrefixSym:Dn,hooksSym:tp}=et(),{getLevel:rp,setLevel:np,isLevelEnabled:sp,mappings:ip,initialLsCache:op,genLsCache:ap,assertNoLevelCollisions:lp}=Mn(),{asChindings:Fn,asJson:cp,buildFormatters:Pn,stringify:Oo,noop:Mo}=nr(),{version:up}=jn(),fp=pn(),dp=class{},jo={constructor:dp,child:pp,bindings:mp,setBindings:hp,flush:wp,isLevelEnabled:sp,version:up,get level(){return this[Ao]()},set level(t){this[Ln](t)},get levelVal(){return this[Ud]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[Dn]},get[Symbol.toStringTag](){return"Pino"},[qd]:op,[Hd]:yp,[Io]:cp,[Ao]:rp,[Ln]:np};Object.setPrototypeOf(jo,Nd.prototype);Po.exports=function(){return Object.create(jo)};var ir=t=>t;function pp(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[qe],n=this[vt],s=Object.create(this);if(e==null)return s[vt].bindings!==ir&&(s[vt]=Pn(n.level,ir,n.log)),s[or]=Fn(s,t),this.onChild!==Mo&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[qe]=Object.create(null);for(let c in r)s[qe][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];s[qe][c]=r[c]}for(let c in e.serializers)s[qe][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];s[qe][c]=e.serializers[c]}}else s[qe]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;s[vt]=Pn(a||n.level,l||ir,c||n.log)}else s[vt]=Pn(n.level,ir,n.log);if(e.hasOwnProperty("customLevels")===!0&&(lp(this.levels,e.customLevels),s.levels=ip(e.customLevels,s[Jd]),ap(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=fp(s.redact,Oo),l={stringify:a[Xd]};s[Qd]=Oo,s[ep]=a,s[Zd]=l}if(typeof e.msgPrefix=="string"&&(s[Dn]=(this[Dn]||"")+e.msgPrefix),s[or]=Fn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[Ln](a)}return this.onChild(s),s}function mp(){let e=`{${this[or].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function hp(t){let e=Fn(this,t);this[or]=e}function gp(t,e){return Object.assign(e,t)}function yp(t,e,r){let n=this[Vd](),s=this[Bd],i=this[Kd],o=this[Gd],a=this[Wd]||gp,l,c=this[tp].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(l=a(l,s(l,r,this)));let u=this[Io](l,e,r,n),d=this[Ro];d[Yd]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[zd]),d.lastLogger=this),d.write(c?c(u):u)}function wp(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Ro];typeof e.flush=="function"?e.flush(t||Mo):t&&t()}});var qo=R((Bn,No)=>{"use strict";var{hasOwnProperty:_t}=Object.prototype,Be=Un();Be.configure=Un;Be.stringify=Be;Be.default=Be;Bn.stringify=Be;Bn.configure=Un;No.exports=Be;var bp=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function Ce(t){return t.length<5e3&&!bp.test(t)?`"${t}"`:JSON.stringify(t)}function Nn(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 xp=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function qn(t){return xp.call(t)!==void 0&&t.length!==0}function Do(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 Sp(t){if(_t.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 vp(t){let e;if(_t.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 _p(t,e){let r;if(_t.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function Fo(t,e){let r;if(_t.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 Ue(t){return t===1?"1 item":`${t} items`}function kp(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function $p(t){if(_t.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 Un(t){t={...t};let e=$p(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Sp(t),n=_p(t,"bigint"),s=vp(t),i=typeof s=="function"?s:void 0,o=Fo(t,"maximumDepth"),a=Fo(t,"maximumBreadth");function l(p,f,h,g,S,b){let x=f[p];switch(typeof x=="object"&&x!==null&&typeof x.toJSON=="function"&&(x=x.toJSON(p)),x=g.call(f,p,x),typeof x){case"string":return Ce(x);case"object":{if(x===null)return"null";if(h.indexOf(x)!==-1)return r;let v="",E=",",_=b;if(Array.isArray(x)){if(x.length===0)return"[]";if(o<h.length+1)return'"[Array]"';h.push(x),S!==""&&(b+=S,v+=`
26
- ${b}`,E=`,
27
- ${b}`);let D=Math.min(x.length,a),H=0;for(;H<D-1;H++){let X=l(String(H),x,h,g,S,b);v+=X!==void 0?X:"null",v+=E}let z=l(String(H),x,h,g,S,b);if(v+=z!==void 0?z:"null",x.length-1>a){let X=x.length-a-1;v+=`${E}"... ${Ue(X)} not stringified"`}return S!==""&&(v+=`
28
- ${_}`),h.pop(),`[${v}]`}let T=Object.keys(x),A=T.length;if(A===0)return"{}";if(o<h.length+1)return'"[Object]"';let k="",M="";S!==""&&(b+=S,E=`,
29
- ${b}`,k=" ");let q=Math.min(A,a);s&&!qn(x)&&(T=Nn(T,i)),h.push(x);for(let D=0;D<q;D++){let H=T[D],z=l(H,x,h,g,S,b);z!==void 0&&(v+=`${M}${Ce(H)}:${k}${z}`,M=E)}if(A>a){let D=A-a;v+=`${M}"...":${k}"${Ue(D)} not stringified"`,M=E}return S!==""&&M.length>1&&(v=`
30
- ${b}${v}
31
- ${_}`),h.pop(),`{${v}}`}case"number":return isFinite(x)?String(x):e?e(x):"null";case"boolean":return x===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(x);default:return e?e(x):void 0}}function c(p,f,h,g,S,b){switch(typeof f=="object"&&f!==null&&typeof f.toJSON=="function"&&(f=f.toJSON(p)),typeof f){case"string":return Ce(f);case"object":{if(f===null)return"null";if(h.indexOf(f)!==-1)return r;let x=b,v="",E=",";if(Array.isArray(f)){if(f.length===0)return"[]";if(o<h.length+1)return'"[Array]"';h.push(f),S!==""&&(b+=S,v+=`
32
- ${b}`,E=`,
33
- ${b}`);let A=Math.min(f.length,a),k=0;for(;k<A-1;k++){let q=c(String(k),f[k],h,g,S,b);v+=q!==void 0?q:"null",v+=E}let M=c(String(k),f[k],h,g,S,b);if(v+=M!==void 0?M:"null",f.length-1>a){let q=f.length-a-1;v+=`${E}"... ${Ue(q)} not stringified"`}return S!==""&&(v+=`
34
- ${x}`),h.pop(),`[${v}]`}h.push(f);let _="";S!==""&&(b+=S,E=`,
35
- ${b}`,_=" ");let T="";for(let A of g){let k=c(A,f[A],h,g,S,b);k!==void 0&&(v+=`${T}${Ce(A)}:${_}${k}`,T=E)}return S!==""&&T.length>1&&(v=`
36
- ${b}${v}
37
- ${x}`),h.pop(),`{${v}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(f);default:return e?e(f):void 0}}function u(p,f,h,g,S){switch(typeof f){case"string":return Ce(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(p),typeof f!="object")return u(p,f,h,g,S);if(f===null)return"null"}if(h.indexOf(f)!==-1)return r;let b=S;if(Array.isArray(f)){if(f.length===0)return"[]";if(o<h.length+1)return'"[Array]"';h.push(f),S+=g;let k=`
38
- ${S}`,M=`,
39
- ${S}`,q=Math.min(f.length,a),D=0;for(;D<q-1;D++){let z=u(String(D),f[D],h,g,S);k+=z!==void 0?z:"null",k+=M}let H=u(String(D),f[D],h,g,S);if(k+=H!==void 0?H:"null",f.length-1>a){let z=f.length-a-1;k+=`${M}"... ${Ue(z)} not stringified"`}return k+=`
40
- ${b}`,h.pop(),`[${k}]`}let x=Object.keys(f),v=x.length;if(v===0)return"{}";if(o<h.length+1)return'"[Object]"';S+=g;let E=`,
41
- ${S}`,_="",T="",A=Math.min(v,a);qn(f)&&(_+=Do(f,E,a),x=x.slice(f.length),A-=f.length,T=E),s&&(x=Nn(x,i)),h.push(f);for(let k=0;k<A;k++){let M=x[k],q=u(M,f[M],h,g,S);q!==void 0&&(_+=`${T}${Ce(M)}: ${q}`,T=E)}if(v>a){let k=v-a;_+=`${T}"...": "${Ue(k)} not stringified"`,T=E}return T!==""&&(_=`
42
- ${S}${_}
43
- ${b}`),h.pop(),`{${_}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(f);default:return e?e(f):void 0}}function d(p,f,h){switch(typeof f){case"string":return Ce(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(p),typeof f!="object")return d(p,f,h);if(f===null)return"null"}if(h.indexOf(f)!==-1)return r;let g="",S=f.length!==void 0;if(S&&Array.isArray(f)){if(f.length===0)return"[]";if(o<h.length+1)return'"[Array]"';h.push(f);let _=Math.min(f.length,a),T=0;for(;T<_-1;T++){let k=d(String(T),f[T],h);g+=k!==void 0?k:"null",g+=","}let A=d(String(T),f[T],h);if(g+=A!==void 0?A:"null",f.length-1>a){let k=f.length-a-1;g+=`,"... ${Ue(k)} not stringified"`}return h.pop(),`[${g}]`}let b=Object.keys(f),x=b.length;if(x===0)return"{}";if(o<h.length+1)return'"[Object]"';let v="",E=Math.min(x,a);S&&qn(f)&&(g+=Do(f,",",a),b=b.slice(f.length),E-=f.length,v=","),s&&(b=Nn(b,i)),h.push(f);for(let _=0;_<E;_++){let T=b[_],A=d(T,f[T],h);A!==void 0&&(g+=`${v}${Ce(T)}:${A}`,v=",")}if(x>a){let _=x-a;g+=`${v}"...":"${Ue(_)} not stringified"`}return h.pop(),`{${g}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(f);default:return e?e(f):void 0}}function m(p,f,h){if(arguments.length>1){let g="";if(typeof h=="number"?g=" ".repeat(Math.min(h,10)):typeof h=="string"&&(g=h.slice(0,10)),f!=null){if(typeof f=="function")return l("",{"":p},[],f,g,"");if(Array.isArray(f))return c("",p,[],kp(f),g,"")}if(g.length!==0)return u("",p,[],g,"")}return d("",p,[])}return m}});var Wo=R((By,Ho)=>{"use strict";var Hn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Bo}=sr(),Tp=Bo.info;function Cp(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:u,[Hn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(d){let m,p=this.lastLevel,{streams:f}=this,h=0,g;for(let S=Ep(f.length,e.dedupe);Op(S,f.length,e.dedupe);S=Ap(S,e.dedupe))if(m=f[S],m.level<=p){if(h!==0&&h!==m.level)break;if(g=m.stream,g[Hn]){let{lastTime:b,lastMsg:x,lastObj:v,lastLogger:E}=this;g.lastLevel=p,g.lastTime=b,g.lastMsg=x,g.lastObj=v,g.lastLogger=E}g.write(d),e.dedupe&&(h=m.level)}else if(!e.dedupe)break}function i(...d){for(let{stream:m}of this.streams)typeof m.emit=="function"&&m.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 m=typeof d.write=="function"||d.stream,p=d.write?d:d.stream;if(!m)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:f,streamLevels:h}=this,g;typeof d.levelVal=="number"?g=d.levelVal:typeof d.level=="string"?g=h[d.level]:typeof d.level=="number"?g=d.level:g=Tp;let S={stream:p,level:g,levelVal:void 0,id:++n.lastId};return f.unshift(S),f.sort(Uo),this.minLevel=f[0].level,n}function l(d){let{streams:m}=this,p=m.findIndex(f=>f.id===d);return p>=0&&(m.splice(p,1),m.sort(Uo),this.minLevel=m.length>0?m[0].level:-1),n}function c(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function u(d){let m=new Array(this.streams.length);for(let p=0;p<m.length;p++)m[p]={level:d,stream:this.streams[p].stream};return{write:s,add:a,remove:l,minLevel:d,streams:m,clone:u,emit:i,flushSync:o,[Hn]:!0}}}function Uo(t,e){return t.level-e.level}function Ep(t,e){return e?t-1:0}function Ap(t,e){return e?t-1:t+1}function Op(t,e,r){return r?t>=0:t<e}Ho.exports=Cp});var sa=R((Hy,ie)=>{"use strict";var Ip=require("node:os"),Qo=cn(),Rp=un(),Mp=pn(),Zo=Ci(),jp=Lo(),ea=et(),{configure:Pp}=qo(),{assertDefaultLevelFound:Lp,mappings:ta,genLsCache:Dp,genLevelComparison:Fp,assertLevelComparison:Np}=Mn(),{DEFAULT_LEVELS:ra,SORTING_ORDER:qp}=sr(),{createArgsNormalizer:Up,asChindings:Bp,buildSafeSonicBoom:Vo,buildFormatters:Hp,stringify:Wn,normalizeDestFileDescriptor:zo,noop:Wp}=nr(),{version:Vp}=jn(),{chindingsSym:Ko,redactFmtSym:zp,serializersSym:Go,timeSym:Kp,timeSliceIndexSym:Gp,streamSym:Jp,stringifySym:Jo,stringifySafeSym:Vn,stringifiersSym:Yo,setLevelSym:Yp,endSym:Xp,formatOptsSym:Qp,messageKeySym:Zp,errorKeySym:em,nestedKeySym:tm,mixinSym:rm,levelCompSym:nm,useOnlyCustomLevelsSym:sm,formattersSym:Xo,hooksSym:im,nestedKeyStrSym:om,mixinMergeStrategySym:am,msgPrefixSym:lm}=ea,{epochTime:na,nullTime:cm}=Zo,{pid:um}=process,fm=Ip.hostname(),dm=Qo.err,pm={level:"info",levelComparison:qp.ASC,levels:ra,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:um,hostname:fm},serializers:Object.assign(Object.create(null),{err:dm}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:na,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},mm=Up(pm),hm=Object.assign(Object.create(null),Qo);function zn(...t){let e={},{opts:r,stream:n}=mm(e,Rp(),...t);r.level&&typeof r.level=="string"&&ra[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:u,base:d,name:m,level:p,customLevels:f,levelComparison:h,mixin:g,mixinMergeStrategy:S,useOnlyCustomLevels:b,formatters:x,hooks:v,depthLimit:E,edgeLimit:_,onChild:T,msgPrefix:A}=r,k=Pp({maximumDepth:E,maximumBreadth:_}),M=Hp(x.level,x.bindings,x.log),q=Wn.bind({[Vn]:k}),D=s?Mp(s,q):{},H=s?{stringify:D[zp]}:{stringify:q},z="}"+(i?`\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 Ws(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})}Vs.Command=en});var Ys=I(ie=>{var{Argument:zs}=Kt(),{Command:tn}=Ks(),{CommanderError:Yc,InvalidArgumentError:Gs}=_t(),{Help:Xc}=Kr(),{Option:Js}=Yr();ie.program=new tn;ie.createCommand=t=>new tn(t);ie.createOption=(t,e)=>new Js(t,e);ie.createArgument=(t,e)=>new zs(t,e);ie.Command=tn;ie.Option=Js;ie.Argument=zs;ie.Help=Xc;ie.CommanderError=Yc;ie.InvalidArgumentError=Gs;ie.InvalidOptionArgumentError=Gs});var sn=I((Wy,ni)=>{"use strict";var kt=t=>t&&typeof t.message=="string",nn=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return kt(r)?r:void 0}else return kt(e)?e:void 0},ti=(t,e)=>{if(!kt(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
+ causes have become circular...`;let n=nn(t);return n?(e.add(t),r+`
25
+ caused by: `+ti(n,e)):r},Qc=t=>ti(t,new Set),ri=(t,e,r)=>{if(!kt(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=nn(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+ri(s,e,i)}else return n},Zc=t=>ri(t,new Set);ni.exports={isErrorLike:kt,getErrorCause:nn,stackWithCauses:Qc,messageWithCauses:Zc}});var on=I((Vy,ii)=>{"use strict";var eu=Symbol("circular-ref-tag"),zt=Symbol("pino-raw-err-ref"),si=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[zt]},set:function(t){this[zt]=t}}});Object.defineProperty(si,zt,{writable:!0,value:{}});ii.exports={pinoErrProto:si,pinoErrorSymbols:{seen:eu,rawSymbol:zt}}});var li=I((Ky,ai)=>{"use strict";ai.exports=ln;var{messageWithCauses:tu,stackWithCauses:ru,isErrorLike:oi}=sn(),{pinoErrProto:nu,pinoErrorSymbols:su}=on(),{seen:an}=su,{toString:iu}=Object.prototype;function ln(t){if(!oi(t))return t;t[an]=void 0;let e=Object.create(nu);e.type=iu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=tu(t),e.stack=ru(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>ln(r)));for(let r in t)if(e[r]===void 0){let n=t[r];oi(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,an)&&(e[r]=ln(n)):e[r]=n}return delete t[an],e.raw=t,e}});var ui=I((zy,ci)=>{"use strict";ci.exports=Jt;var{isErrorLike:cn}=sn(),{pinoErrProto:ou,pinoErrorSymbols:au}=on(),{seen:Gt}=au,{toString:lu}=Object.prototype;function Jt(t){if(!cn(t))return t;t[Gt]=void 0;let e=Object.create(ou);e.type=lu.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))),cn(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,Gt)&&(e.cause=Jt(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];cn(n)?Object.prototype.hasOwnProperty.call(n,Gt)||(e[r]=Jt(n)):e[r]=n}return delete t[Gt],e.raw=t,e}});var mi=I((Gy,pi)=>{"use strict";pi.exports={mapHttpRequest:cu,reqSerializer:di};var un=Symbol("pino-raw-req-ref"),fi=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[un]},set:function(t){this[un]=t}}});Object.defineProperty(fi,un,{writable:!0,value:{}});function di(t){let e=t.info||t.socket,r=Object.create(fi);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 cu(t){return{req:di(t)}}});var wi=I((Jy,yi)=>{"use strict";yi.exports={mapHttpResponse:uu,resSerializer:gi};var fn=Symbol("pino-raw-res-ref"),hi=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[fn]},set:function(t){this[fn]=t}}});Object.defineProperty(hi,fn,{writable:!0,value:{}});function gi(t){let e=Object.create(hi);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function uu(t){return{res:gi(t)}}});var pn=I((Yy,bi)=>{"use strict";var dn=li(),fu=ui(),Yt=mi(),Xt=wi();bi.exports={err:dn,errWithCause:fu,mapHttpRequest:Yt.mapHttpRequest,mapHttpResponse:Xt.mapHttpResponse,req:Yt.reqSerializer,res:Xt.resSerializer,wrapErrorSerializer:function(e){return e===dn?e:function(n){return e(dn(n))}},wrapRequestSerializer:function(e){return e===Yt.reqSerializer?e:function(n){return e(Yt.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Xt.resSerializer?e:function(n){return e(Xt.resSerializer(n))}}}});var mn=I((Xy,xi)=>{"use strict";function du(t,e){return e}xi.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=du;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 Ti=I((Qy,$i)=>{"use strict";function hn(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]=hn(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]=hn(t[r]));return e}return t}function vi(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 Si(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 _i(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 Qt=Symbol("PATH_NOT_FOUND");function pu(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return Qt;r=r[n]}return r}function mu(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 hu(t,e,r,n=!1){for(let s of e){let i=vi(s);if(i.includes("*"))ki(t,i,r,s,n);else if(n)_i(t,i);else{let o=pu(t,i);if(o===Qt)continue;let a=typeof r=="function"?r(o,i):r;Si(t,i,a)}}}function ki(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()],u=typeof r=="function"?r(a[l],c):r;a[l]=u}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],u=typeof r=="function"?r(a[l],c):r;a[l]=u}}else gu(t,e,r,i,n,s)}function gu(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function c(u,d){if(d===o.length){if(Array.isArray(u))for(let m=0;m<u.length;m++)l[d]=m.toString(),c(u[m],d+1);else if(typeof u=="object"&&u!==null)for(let m in u)l[d]=m,c(u[m],d+1)}else if(d<o.length){let m=o[d];u&&typeof u=="object"&&u!==null&&m in u&&(l[d]=m,c(u[m],d+1))}else if(a.includes("*"))ki(u,a,typeof r=="function"?(p,f)=>{let g=[...l.slice(0,d),...f];return r(p,g)}:r,s,i);else if(i)_i(u,a);else{let m=typeof r=="function"?r(mu(u,a),[...l.slice(0,d),...a]):r;Si(u,a,m)}}if(o.length===0)c(t,0);else{let u=t;for(let d=0;d<o.length;d++){let m=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[m],l[d]=m}u!=null&&c(u,o.length)}}function yu(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=vi(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 wu(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 bu(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 xu(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)bu(e)}function vu(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;xu(e);let o=yu(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let c=wu(l,o),u=l,d=r;return typeof r=="function"&&(d=r),hu(c,e,d,i),n===!1?(c.restore=function(){return hn(u)},c):typeof n=="function"?n(c):JSON.stringify(c)}}$i.exports=vu});var it=I((Zy,Ci)=>{"use strict";var Su=Symbol("pino.setLevel"),_u=Symbol("pino.getLevel"),ku=Symbol("pino.levelVal"),$u=Symbol("pino.levelComp"),Tu=Symbol("pino.useLevelLabels"),Cu=Symbol("pino.useOnlyCustomLevels"),Eu=Symbol("pino.mixin"),Au=Symbol("pino.lsCache"),Ou=Symbol("pino.chindings"),Ru=Symbol("pino.asJson"),Iu=Symbol("pino.write"),Mu=Symbol("pino.redactFmt"),ju=Symbol("pino.time"),Pu=Symbol("pino.timeSliceIndex"),Lu=Symbol("pino.stream"),Du=Symbol("pino.stringify"),Fu=Symbol("pino.stringifySafe"),Nu=Symbol("pino.stringifiers"),Uu=Symbol("pino.end"),qu=Symbol("pino.formatOpts"),Bu=Symbol("pino.messageKey"),Hu=Symbol("pino.errorKey"),Wu=Symbol("pino.nestedKey"),Vu=Symbol("pino.nestedKeyStr"),Ku=Symbol("pino.mixinMergeStrategy"),zu=Symbol("pino.msgPrefix"),Gu=Symbol("pino.wildcardFirst"),Ju=Symbol.for("pino.serializers"),Yu=Symbol.for("pino.formatters"),Xu=Symbol.for("pino.hooks"),Qu=Symbol.for("pino.metadata");Ci.exports={setLevelSym:Su,getLevelSym:_u,levelValSym:ku,levelCompSym:$u,useLevelLabelsSym:Tu,mixinSym:Eu,lsCacheSym:Au,chindingsSym:Ou,asJsonSym:Ru,writeSym:Iu,serializersSym:Ju,redactFmtSym:Mu,timeSym:ju,timeSliceIndexSym:Pu,streamSym:Lu,stringifySym:Du,stringifySafeSym:Fu,stringifiersSym:Nu,endSym:Uu,formatOptsSym:qu,messageKeySym:Bu,errorKeySym:Hu,nestedKeySym:Wu,wildcardFirstSym:Gu,needsMetadataGsym:Qu,useOnlyCustomLevelsSym:Cu,formattersSym:Yu,hooksSym:Xu,nestedKeyStrSym:Vu,mixinMergeStrategySym:Ku,msgPrefixSym:zu}});var yn=I((ew,Ri)=>{"use strict";var Ei=Ti(),{redactFmtSym:Zu,wildcardFirstSym:Zt}=it(),gn=/[^.[\]]+|\[([^[\]]*?)\]/g,Ai="[Redacted]",Oi=!1;function ef(t,e){let{paths:r,censor:n,remove:s}=tf(t),i=r.reduce((l,c)=>{gn.lastIndex=0;let u=gn.exec(c),d=gn.exec(c),m=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(m==="*"&&(m=Zt),d===null)return l[m]=null,l;if(l[m]===null)return l;let{index:p}=d,f=`${c.substr(p,c.length-1)}`;return l[m]=l[m]||[],m!==Zt&&l[m].length===0&&l[m].push(...l[Zt]||[]),m===Zt&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(f)}),l[m].push(f),l},{}),o={[Zu]:Ei({paths:r,censor:n,serialize:e,strict:Oi,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]=u=>a(u,[c]);else{let u=typeof n=="function"?(d,m)=>n(d,[c,...m]):n;l[c]=Ei({paths:i[c],censor:u,serialize:e,strict:Oi,remove:s})}return l},o)}function tf(t){if(Array.isArray(t))return t={paths:t,censor:Ai},t;let{paths:e,censor:r=Ai,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}}Ri.exports=ef});var ji=I((tw,Mi)=>{"use strict";var rf=()=>"",nf=()=>`,"time":${Date.now()}`,sf=()=>`,"time":${Math.round(Date.now()/1e3)}`,of=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,af=1000000n,Ii=1000000000n,lf=BigInt(Date.now())*af,cf=process.hrtime.bigint(),uf=()=>{let t=process.hrtime.bigint()-cf,e=lf+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"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${u}:${d}.${n.toString().padStart(9,"0")}Z"`};Mi.exports={nullTime:rf,epochTime:nf,unixTime:sf,isoTime:of,isoTimeNano:uf}});var Li=I((rw,Pi)=>{"use strict";function ff(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}Pi.exports=df;function df(t,e,r){var n=r&&r.stringify||ff,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="",u=1-s,d=-1,m=t&&t.length||0,p=0;p<m;){if(t.charCodeAt(p)===37&&p+1<m){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<p&&(c+=t.slice(d,p)),c+=Number(e[u]),d=p+2,p++;break;case 105:if(u>=l||e[u]==null)break;d<p&&(c+=t.slice(d,p)),c+=Math.floor(Number(e[u])),d=p+2,p++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<p&&(c+=t.slice(d,p));var f=typeof e[u];if(f==="string"){c+="'"+e[u]+"'",d=p+2,p++;break}if(f==="function"){c+=e[u].name||"<anonymous>",d=p+2,p++;break}c+=n(e[u]),d=p+2,p++;break;case 115:if(u>=l)break;d<p&&(c+=t.slice(d,p)),c+=String(e[u]),d=p+2,p++;break;case 37:d<p&&(c+=t.slice(d,p)),c+="%",d=p+2,p++,u--;break}++u}++p}return d===-1?t:(d<m&&(c+=t.slice(d)),c)}});var bn=I((nw,wn)=>{"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));wn.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(););};wn.exports=t}});var Wi=I((sw,Hi)=>{"use strict";var N=require("fs"),pf=require("events"),mf=require("util").inherits,Di=require("path"),vn=bn(),hf=require("assert"),er=100,tr=Buffer.allocUnsafe(0),gf=16*1024,Fi="buffer",Ni="utf8",[yf,wf]=(process.versions.node||"0.0").split(".").map(Number),bf=yf>=22&&wf>=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&&N.mkdirSync(Di.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(Di.dirname(t),{recursive:!0},i=>{if(i)return r(i);N.open(t,n,s,r)}):N.open(t,n,s,r)}function me(t){if(!(this instanceof me))return new me(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:u,fsync:d,contentMode:m,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||gf,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=p,this.retryEAGAIN=u||(()=>!0),this.mkdir=c||!1;let f,g;if(m===Fi)this._writingBuf=tr,this.write=Sf,this.flush=kf,this.flushSync=Tf,this._actualWrite=Ef,f=()=>N.writeSync(this.fd,this._writingBuf),g=()=>N.write(this.fd,this._writingBuf,this.release);else if(m===void 0||m===Ni)this._writingBuf="",this.write=vf,this.flush=_f,this.flushSync=$f,this._actualWrite=Cf,f=()=>Buffer.isBuffer(this._writingBuf)?N.writeSync(this.fd,this._writingBuf):N.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>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 "${Ni}" and "${Fi}", but passed ${m}`);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=(h,b)=>{if(h){if((h.code==="EAGAIN"||h.code==="EBUSY")&&this.retryEAGAIN(h,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{vn(er),this.release(void 0,0)}catch(S){this.release(S)}else setTimeout(g,er);else this._writing=!1,this.emit("error",h);return}this.emit("write",b);let w=xn(this._writingBuf,this._len,b);if(this._len=w.len,this._writingBuf=w.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let S=f(),E=xn(this._writingBuf,this._len,S);this._len=E.len,this._writingBuf=E.writingBuf}while(this._writingBuf.length)}catch(S){this.release(S);return}}this._fsync&&N.fsyncSync(this.fd);let x=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):x>this.minLength?this._actualWrite():this._ending?x>0?this._actualWrite():(this._writing=!1,rr(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(xf,this)):this.emit("drain"))},this.on("newListener",function(h){h==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function xn(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 xf(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}mf(me,pf);function qi(t,e){return t.length===0?tr:t.length===1?t[0]:Buffer.concat(t,e)}function vf(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 Sf(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 Bi(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 _f(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&&Bi.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function kf(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&&Bi.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}me.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)})}),Ui(this.file,this)};me.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():rr(this)))};function $f(){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=xn(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;vn(er)}}try{N.fsyncSync(this.fd)}catch{}}function Tf(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=tr);let t=tr;for(;this._bufs.length||t.length;){t.length<=0&&(t=qi(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;vn(er)}}}me.prototype.destroy=function(){this.destroyed||rr(this)};function Cf(){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 Ef(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:qi(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 bf&&(this._writingBuf=Buffer.from(this._writingBuf)),N.write(this.fd,this._writingBuf,t)}function rr(t){if(t.fd===-1){t.once("ready",rr.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],hf(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")}}me.SonicBoom=me;me.default=me;Hi.exports=me});var Sn=I((iw,Ji)=>{"use strict";var he={exit:[],beforeExit:[]},Vi={exit:Rf,beforeExit:If},ot;function Af(){ot===void 0&&(ot=new FinalizationRegistry(Mf))}function Of(t){he[t].length>0||process.on(t,Vi[t])}function Ki(t){he[t].length>0||(process.removeListener(t,Vi[t]),he.exit.length===0&&he.beforeExit.length===0&&(ot=void 0))}function Rf(){zi("exit")}function If(){zi("beforeExit")}function zi(t){for(let e of he[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}he[t]=[]}function Mf(t){for(let e of["exit","beforeExit"]){let r=he[e].indexOf(t);he[e].splice(r,r+1),Ki(e)}}function Gi(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");Of(t);let n=new WeakRef(e);n.fn=r,Af(),ot.register(e,n),he[t].push(n)}function jf(t,e){Gi("exit",t,e)}function Pf(t,e){Gi("beforeExit",t,e)}function Lf(t){if(ot!==void 0){ot.unregister(t);for(let e of["exit","beforeExit"])he[e]=he[e].filter(r=>{let n=r.deref();return n&&n!==t}),Ki(e)}}Ji.exports={register:jf,registerBeforeExit:Pf,unregister:Lf}});var Yi=I((ow,Df)=>{Df.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 Qi=I((aw,Xi)=>{"use strict";function Ff(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 Nf(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(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}Xi.exports={wait:Ff,waitDiff:Nf}});var eo=I((lw,Zi)=>{"use strict";Zi.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var po=I((cw,fo)=>{"use strict";var{version:Uf}=Yi(),{EventEmitter:qf}=require("events"),{Worker:Bf}=require("worker_threads"),{join:Hf}=require("path"),{pathToFileURL:Wf}=require("url"),{wait:Vf}=Qi(),{WRITE_INDEX:Se,READ_INDEX:He,SEQ_INDEX:_n}=eo(),Kf=require("buffer"),zf=require("assert"),v=Symbol("kImpl"),Gf=Kf.constants.MAX_STRING_LENGTH;function to(){}function Cn(t,e){Atomics.add(t[v].state,_n,1),e(),Atomics.add(t[v].state,_n,1),Atomics.notify(t[v].state,_n)}function ro(t){Cn(t,()=>{Atomics.store(t[v].state,He,0),Atomics.store(t[v].state,Se,0)})}var $t=class{constructor(e){this._value=e}deref(){return this._value}},nr=class{register(){}unregister(){}},Jf=process.env.NODE_V8_COVERAGE?nr:global.FinalizationRegistry||nr,Yf=process.env.NODE_V8_COVERAGE?$t:global.WeakRef||$t,no=new Jf(t=>{t.exited||t.terminate()});function Xf(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Hf(__dirname,"lib","worker.js"),o=new Bf(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Wf(r).href,dataBuf:t[v].dataBuf,stateBuf:t[v].stateBuf,workerData:{$context:{threadStreamVersion:Uf},...n}}});return o.stream=new $t(t),o.on("message",Qf),o.on("exit",oo),no.register(t,o),o}function so(t){zf(!t[v].sync),t[v].needDrain&&(t[v].needDrain=!1,t.emit("drain"))}function io(t){for(;;){let e=Atomics.load(t[v].state,Se),r=t[v].data.length-e;if(r>0){if(t[v].bufLen===0){t[v].flushing=!1,t[v].ending?En(t):t[v].needDrain&&process.nextTick(so,t);return}co(t,r,to);continue}if(r===0){if(e===0&&t[v].bufLen===0)return;sr(t,()=>{t.destroyed||(ro(t),io(t))});return}ae(t,new Error("overwritten"));return}}function Qf(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 Yf(e),sr(e,()=>{e[v].ready=!0,e.emit("ready")});break;case"ERROR":ae(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"){ae(e,new Error("this should not happen: "+t.code));break}let r=e[v].flushCallbacks.get(t.id);r&&(e[v].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:ae(e,new Error("this should not happen: "+t.code))}}function oo(t){let e=this.stream.deref();e!==void 0&&(no.unregister(e),e.worker.exited=!0,e.worker.off("exit",oo),ae(e,t!==0?new Error("the worker thread exited"):null))}var $n=class extends qf{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[v]={},this[v].stateBuf=new SharedArrayBuffer(128),this[v].state=new Int32Array(this[v].stateBuf),this[v].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[v].data=Buffer.from(this[v].dataBuf),this[v].sync=e.sync||!1,this[v].ending=!1,this[v].ended=!1,this[v].needDrain=!1,this[v].destroyed=!1,this[v].flushing=!1,this[v].ready=!1,this[v].finished=!1,this[v].errored=null,this[v].closed=!1,this[v].buf=[],this[v].bufHead=0,this[v].bufLen=0,this[v].flushCallbacks=new Map,this[v].nextFlushId=0,this.worker=Xf(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[v].destroyed)return Tn(this,new Error("the worker has exited")),!1;if(this[v].ending)return Tn(this,new Error("the worker is ending")),!1;if(this[v].flushing&&this[v].bufLen+r.length>=Gf)try{kn(this),this[v].flushing=!0}catch(n){return ae(this,n),!1}if(this[v].buf.push(r),this[v].bufLen+=r.length,this[v].sync)try{return kn(this),!0}catch(n){return ae(this,n),!1}return this[v].flushing||(this[v].flushing=!0,setImmediate(io,this)),this[v].needDrain=this[v].data.length-this[v].bufLen-Atomics.load(this[v].state,Se)<=0,!this[v].needDrain}end(){this[v].destroyed||(this[v].ending=!0,En(this))}flush(e){e=typeof e=="function"?e:to,ao(this,r=>{if(r){process.nextTick(e,r);return}lo(this,e)})}flushSync(){this[v].destroyed||(kn(this),uo(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[v].ready}get destroyed(){return this[v].destroyed}get closed(){return this[v].closed}get writable(){return!this[v].destroyed&&!this[v].ending}get writableEnded(){return this[v].ending}get writableFinished(){return this[v].finished}get writableNeedDrain(){return this[v].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[v].errored}};function ao(t,e){if(t[v].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[v].sync&&(t[v].flushing||t[v].bufLen>0)){setImmediate(ao,t,e);return}sr(t,e)}function sr(t,e){let r=Atomics.load(t[v].state,Se);Vf(t[v].state,He,r,1/0,(n,s)=>{if(n){ae(t,n),e(n);return}if(s!=="ok"){sr(t,e);return}e()})}function lo(t,e){if(t[v].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[v].ready){let n=()=>{i(),lo(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[v].nextFlushId;t[v].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[v].flushCallbacks.delete(r),ae(t,n),process.nextTick(e,n)}}function Zf(t,e){let r=t[v].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 Tn(t,e){setImmediate(()=>{t.emit("error",e)})}function ae(t,e){t[v].destroyed||(t[v].destroyed=!0,Zf(t,e),e&&(t[v].errored=e,Tn(t,e)),t.worker.exited?setImmediate(()=>{t[v].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[v].closed=!0,t.emit("close")}))}function co(t,e,r){let s=Atomics.load(t[v].state,Se),i=e;for(;i>0&&t[v].bufLen!==0;){let o=t[v].bufHead,a=t[v].buf[o];if(a.length<=i){a.copy(t[v].data,s),s+=a.length,i-=a.length,t[v].bufLen-=a.length,t[v].bufHead=o+1,t[v].bufHead===t[v].buf.length?(t[v].buf.length=0,t[v].bufHead=0):t[v].bufHead>=1024&&t[v].bufHead*2>=t[v].buf.length&&(t[v].buf.splice(0,t[v].bufHead),t[v].bufHead=0);continue}a.copy(t[v].data,s,0,i),t[v].buf[o]=a.subarray(i),t[v].bufLen-=i,s+=i,i=0}return Cn(t,()=>{Atomics.store(t[v].state,Se,s)}),r(),!0}function En(t){if(!(t[v].ended||!t[v].ending||t[v].flushing)){t[v].ended=!0;try{t.flushSync();let e=Atomics.load(t[v].state,He);Cn(t,()=>{Atomics.store(t[v].state,Se,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[v].state,He,e,1e3),e=Atomics.load(t[v].state,He),e===-2){ae(t,new Error("end() failed"));return}if(++r===10){ae(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[v].finished=!0,t.emit("finish")})}catch(e){ae(t,e)}}}function kn(t){let e=()=>{t[v].ending?En(t):t[v].needDrain&&process.nextTick(so,t)};for(t[v].flushing=!1;t[v].bufLen!==0;){let r=Atomics.load(t[v].state,Se),n=t[v].data.length-r;if(n===0){uo(t),ro(t);continue}else if(n<0)throw new Error("overwritten");co(t,n,e)}}function uo(t){if(t[v].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[v].state,Se),r=0;for(;;){let n=Atomics.load(t[v].state,He);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[v].state,He,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}fo.exports=$n});var Rn=I((uw,go)=>{"use strict";var{createRequire:ed}=require("module"),{existsSync:td}=require("node:fs"),rd=mn(),{join:An,isAbsolute:ho,sep:nd}=require("node:path"),{fileURLToPath:sd}=require("node:url"),id=bn(),On=Sn(),od=po();function ad(t){On.register(t,dd),On.registerBeforeExit(t,pd),t.on("close",function(){On.unregister(t)})}function ld(){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 cd(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&&mo(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(mo(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function mo(t){let e=ud(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=sd(r)}catch{return!1}return ho(r)&&!td(r)}function ud(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function fd(t,e,r,n,s){if(!r.execArgv&&ld()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=cd(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new od({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&&ad(i)}function a(){i.closed||(i.flushSync(),id(100),i.end())}return i}function dd(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function pd(t){t.flushSync()}function md(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=rd(),sync:a=!1}=t,l={...t.options},c=typeof o=="string"?[o]:o,u=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&r)throw new Error("only one of target or targets can be specified");r?(d=u["pino-worker"]||An(__dirname,"worker.js"),l.targets=r.filter(f=>f.target).map(f=>({...f,target:p(f.target)})),l.pipelines=r.filter(f=>f.pipeline).map(f=>f.pipeline.map(g=>({...g,level:f.level,target:p(g.target)})))):e&&(d=u["pino-worker"]||An(__dirname,"worker.js"),l.pipelines=[e.map(f=>({...f,target:p(f.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let m=r||e?"pino.transport":d;return fd(p(d),l,i,a,m);function p(f){if(f=u[f]||f,ho(f)||f.indexOf("file://")===0)return f;if(f==="pino/file")return An(__dirname,"..","file.js");let g;for(let h of c)try{let b=h==="node:repl"?process.cwd()+nd:h;g=ed(b).resolve(f);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${f}"`);return g}}go.exports=md});var ar=I((fw,Ao)=>{"use strict";var hd=require("node:diagnostics_channel"),yo=Li(),{mapHttpRequest:gd,mapHttpResponse:yd}=pn(),Mn=Wi(),wo=Sn(),{lsCacheSym:wd,chindingsSym:_o,writeSym:bo,serializersSym:ko,formatOptsSym:xo,endSym:bd,stringifiersSym:$o,stringifySym:To,stringifySafeSym:jn,wildcardFirstSym:Co,nestedKeySym:xd,formattersSym:Eo,messageKeySym:vd,errorKeySym:Sd,nestedKeyStrSym:_d,msgPrefixSym:ir}=it(),{isMainThread:kd}=require("worker_threads"),$d=Rn(),[Td]=process.versions.node.split(".").map(t=>Number(t)),vo=hd.tracingChannel("pino_asJson"),In=Td>=25?t=>JSON.stringify(t):Ed;function at(){}function Cd(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=gd(n):typeof n.setHeader=="function"&&(n=yd(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[ir]=="string"&&i!==void 0&&i!==null&&(i=this[ir]+i),this[bo](n,yo(i,o,this[xo]),t)}else{let i=n===void 0?s.shift():n;typeof this[ir]=="string"&&i!==void 0&&i!==null&&(i=this[ir]+i),this[bo](null,yo(i,s,this[xo]),t)}}}function Ed(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 Ad(t,e,r,n){if(vo.hasSubscribers===!1)return So.call(this,t,e,r,n);let s={instance:this,arguments};return vo.traceSync(So,s,this,t,e,r,n)}function So(t,e,r,n){let s=this[To],i=this[jn],o=this[$o],a=this[bd],l=this[_o],c=this[ko],u=this[Eo],d=this[vd],m=this[Sd],p=this[wd][r]+n;p=p+l;let f;u.log&&(t=u.log(t));let g=o[Co],h="";for(let w in t)if(f=t[w],Object.prototype.hasOwnProperty.call(t,w)&&f!==void 0){c[w]?f=c[w](f):w===m&&c.err&&(f=c.err(f));let x=o[w]||g;switch(typeof f){case"undefined":case"function":continue;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":x&&(f=x(f));break;case"string":f=(x||In)(f);break;default:f=(x||s)(f,i)}if(f===void 0)continue;let S=In(w);h+=","+S+":"+f}let b="";if(e!==void 0){f=c[d]?c[d](e):e;let w=o[d]||g;switch(typeof f){case"function":break;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":w&&(f=w(f)),b=',"'+d+'":'+f;break;case"string":f=(w||In)(f),b=',"'+d+'":'+f;break;default:f=(w||s)(f,i),b=',"'+d+'":'+f}}return this[xd]&&h?p+this[_d]+h.slice(1)+"}"+b+a:p+h+b+a}function Od(t,e){let r,n=t[_o],s=t[To],i=t[jn],o=t[$o],a=o[Co],l=t[ko],c=t[Eo].bindings;e=c(e);for(let u in e)if(r=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&r!==void 0)===!0){if(r=l[u]?l[u](r):r,r=(o[u]||a||s)(r,i),r===void 0)continue;n+=',"'+u+'":'+r}return n}function Rd(t){return t.write!==t.constructor.prototype.write}function or(t){let e=new Mn(t);return e.on("error",r),!t.sync&&kd&&(wo.register(e,Id),e.on("close",function(){wo.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=at,e.end=at,e.flushSync=at,e.destroy=at;return}e.removeListener("error",r),e.emit("error",n)}}function Id(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Md(t){return function(r,n,s={},i){if(typeof s=="string")i=or({dest:s}),s={};else if(typeof i=="string"){if(s&&s.transport)throw Error("only one of option.transport or stream can be specified");i=or({dest:i})}else if(s instanceof 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=$d({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=at),i||(Rd(process.stdout)?i=process.stdout:i=or({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function jd(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[jn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Pd(t,e,r){return{level:t,bindings:e,log:r}}function Ld(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Ao.exports={noop:at,buildSafeSonicBoom:or,asChindings:Od,asJson:Ad,genLog:Cd,createArgsNormalizer:Md,stringify:jd,buildFormatters:Pd,normalizeDestFileDescriptor:Ld}});var lr=I((dw,Oo)=>{var Dd={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Fd={ASC:"ASC",DESC:"DESC"};Oo.exports={DEFAULT_LEVELS:Dd,SORTING_ORDER:Fd}});var Dn=I((pw,jo)=>{"use strict";var{lsCacheSym:Nd,levelValSym:Pn,useOnlyCustomLevelsSym:Ud,streamSym:qd,formattersSym:Bd,hooksSym:Hd,levelCompSym:Ro}=it(),{noop:Wd,genLog:We}=ar(),{DEFAULT_LEVELS:be,SORTING_ORDER:Io}=lr(),Mo={fatal:t=>{let e=We(be.fatal,t);return function(...r){let n=this[qd];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>We(be.error,t),warn:t=>We(be.warn,t),info:t=>We(be.info,t),debug:t=>We(be.debug,t),trace:t=>We(be.trace,t)},Ln=Object.keys(be).reduce((t,e)=>(t[be[e]]=e,t),{}),Vd=Object.keys(Ln).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Kd(t){let e=t[Bd].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[Nd]=n,t}function zd(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 Gd(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[Pn],s=this[Pn]=r[t],i=this[Ud],o=this[Ro],a=this[Hd].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=Wd;continue}this[l]=zd(l,i)?Mo[l](a):We(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function Jd(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Yd(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Ro](r,this[Pn])}function Xd(t,e,r){return t===Io.DESC?e<=r:e>=r}function Qd(t){return typeof t=="string"?Xd.bind(null,t):t}function Zd(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:Ln,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:be,t);return{labels:n,values:s}}function ep(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(Ln).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:be,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function tp(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 rp(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Io).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}jo.exports={initialLsCache:Vd,genLsCache:Kd,levelMethods:Mo,getLevel:Jd,setLevel:Gd,isLevelEnabled:Yd,mappings:Zd,assertNoLevelCollisions:tp,assertDefaultLevelFound:ep,genLevelComparison:Qd,assertLevelComparison:rp}});var Fn=I((mw,Po)=>{"use strict";Po.exports={version:"10.3.1"}});var Ho=I((gw,Bo)=>{"use strict";var{EventEmitter:np}=require("node:events"),{lsCacheSym:sp,levelValSym:ip,setLevelSym:Un,getLevelSym:Lo,chindingsSym:ur,mixinSym:op,asJsonSym:Fo,writeSym:ap,mixinMergeStrategySym:lp,timeSym:cp,timeSliceIndexSym:up,streamSym:No,serializersSym:Ve,formattersSym:Tt,errorKeySym:fp,messageKeySym:dp,useOnlyCustomLevelsSym:pp,needsMetadataGsym:mp,redactFmtSym:hp,stringifySym:gp,formatOptsSym:yp,stringifiersSym:wp,msgPrefixSym:qn,hooksSym:bp}=it(),{getLevel:xp,setLevel:vp,isLevelEnabled:Sp,mappings:_p,initialLsCache:kp,genLsCache:$p,assertNoLevelCollisions:Tp}=Dn(),{asChindings:Bn,asJson:Cp,buildFormatters:Nn,stringify:Do,noop:Uo}=ar(),{version:Ep}=Fn(),Ap=yn(),Op=class{},qo={constructor:Op,child:Rp,bindings:Ip,setBindings:Mp,flush:Lp,isLevelEnabled:Sp,version:Ep,get level(){return this[Lo]()},set level(t){this[Un](t)},get levelVal(){return this[ip]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[qn]},get[Symbol.toStringTag](){return"Pino"},[sp]:kp,[ap]:Pp,[Fo]:Cp,[Lo]:xp,[Un]:vp};Object.setPrototypeOf(qo,np.prototype);Bo.exports=function(){return Object.create(qo)};var cr=t=>t;function Rp(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[Ve],n=this[Tt],s=Object.create(this);if(e==null)return s[Tt].bindings!==cr&&(s[Tt]=Nn(n.level,cr,n.log)),s[ur]=Bn(s,t),this.onChild!==Uo&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[Ve]=Object.create(null);for(let c in r)s[Ve][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];s[Ve][c]=r[c]}for(let c in e.serializers)s[Ve][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];s[Ve][c]=e.serializers[c]}}else s[Ve]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;s[Tt]=Nn(a||n.level,l||cr,c||n.log)}else s[Tt]=Nn(n.level,cr,n.log);if(e.hasOwnProperty("customLevels")===!0&&(Tp(this.levels,e.customLevels),s.levels=_p(e.customLevels,s[pp]),$p(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=Ap(s.redact,Do),l={stringify:a[hp]};s[gp]=Do,s[wp]=a,s[yp]=l}if(typeof e.msgPrefix=="string"&&(s[qn]=(this[qn]||"")+e.msgPrefix),s[ur]=Bn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[Un](a)}return this.onChild(s),s}function Ip(){let e=`{${this[ur].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Mp(t){let e=Bn(this,t);this[ur]=e}function jp(t,e){return Object.assign(e,t)}function Pp(t,e,r){let n=this[cp](),s=this[op],i=this[fp],o=this[dp],a=this[lp]||jp,l,c=this[bp].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(l=a(l,s(l,r,this)));let u=this[Fo](l,e,r,n),d=this[No];d[mp]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[up]),d.lastLogger=this),d.write(c?c(u):u)}function Lp(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[No];typeof e.flush=="function"?e.flush(t||Uo):t&&t()}});var zo=I((Kn,Ko)=>{"use strict";var{hasOwnProperty:Ct}=Object.prototype,ze=Vn();ze.configure=Vn;ze.stringify=ze;ze.default=ze;Kn.stringify=ze;Kn.configure=Vn;Ko.exports=ze;var Dp=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function Ie(t){return t.length<5e3&&!Dp.test(t)?`"${t}"`:JSON.stringify(t)}function Hn(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 Fp=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Wn(t){return Fp.call(t)!==void 0&&t.length!==0}function Wo(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 Np(t){if(Ct.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function Up(t){let e;if(Ct.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function qp(t,e){let r;if(Ct.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function Vo(t,e){let r;if(Ct.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function Ke(t){return t===1?"1 item":`${t} items`}function Bp(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function Hp(t){if(Ct.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function Vn(t){t={...t};let e=Hp(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Np(t),n=qp(t,"bigint"),s=Up(t),i=typeof s=="function"?s:void 0,o=Vo(t,"maximumDepth"),a=Vo(t,"maximumBreadth");function l(p,f,g,h,b,w){let x=f[p];switch(typeof x=="object"&&x!==null&&typeof x.toJSON=="function"&&(x=x.toJSON(p)),x=h.call(f,p,x),typeof x){case"string":return Ie(x);case"object":{if(x===null)return"null";if(g.indexOf(x)!==-1)return r;let S="",E=",",_=w;if(Array.isArray(x)){if(x.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(x),b!==""&&(w+=b,S+=`
26
+ ${w}`,E=`,
27
+ ${w}`);let F=Math.min(x.length,a),K=0;for(;K<F-1;K++){let ee=l(String(K),x,g,h,b,w);S+=ee!==void 0?ee:"null",S+=E}let J=l(String(K),x,g,h,b,w);if(S+=J!==void 0?J:"null",x.length-1>a){let ee=x.length-a-1;S+=`${E}"... ${Ke(ee)} not stringified"`}return b!==""&&(S+=`
28
+ ${_}`),g.pop(),`[${S}]`}let T=Object.keys(x),A=T.length;if(A===0)return"{}";if(o<g.length+1)return'"[Object]"';let k="",M="";b!==""&&(w+=b,E=`,
29
+ ${w}`,k=" ");let B=Math.min(A,a);s&&!Wn(x)&&(T=Hn(T,i)),g.push(x);for(let F=0;F<B;F++){let K=T[F],J=l(K,x,g,h,b,w);J!==void 0&&(S+=`${M}${Ie(K)}:${k}${J}`,M=E)}if(A>a){let F=A-a;S+=`${M}"...":${k}"${Ke(F)} not stringified"`,M=E}return b!==""&&M.length>1&&(S=`
30
+ ${w}${S}
31
+ ${_}`),g.pop(),`{${S}}`}case"number":return isFinite(x)?String(x):e?e(x):"null";case"boolean":return x===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(x);default:return e?e(x):void 0}}function c(p,f,g,h,b,w){switch(typeof f=="object"&&f!==null&&typeof f.toJSON=="function"&&(f=f.toJSON(p)),typeof f){case"string":return Ie(f);case"object":{if(f===null)return"null";if(g.indexOf(f)!==-1)return r;let x=w,S="",E=",";if(Array.isArray(f)){if(f.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(f),b!==""&&(w+=b,S+=`
32
+ ${w}`,E=`,
33
+ ${w}`);let A=Math.min(f.length,a),k=0;for(;k<A-1;k++){let B=c(String(k),f[k],g,h,b,w);S+=B!==void 0?B:"null",S+=E}let M=c(String(k),f[k],g,h,b,w);if(S+=M!==void 0?M:"null",f.length-1>a){let B=f.length-a-1;S+=`${E}"... ${Ke(B)} not stringified"`}return b!==""&&(S+=`
34
+ ${x}`),g.pop(),`[${S}]`}g.push(f);let _="";b!==""&&(w+=b,E=`,
35
+ ${w}`,_=" ");let T="";for(let A of h){let k=c(A,f[A],g,h,b,w);k!==void 0&&(S+=`${T}${Ie(A)}:${_}${k}`,T=E)}return b!==""&&T.length>1&&(S=`
36
+ ${w}${S}
37
+ ${x}`),g.pop(),`{${S}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(f);default:return e?e(f):void 0}}function u(p,f,g,h,b){switch(typeof f){case"string":return Ie(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(p),typeof f!="object")return u(p,f,g,h,b);if(f===null)return"null"}if(g.indexOf(f)!==-1)return r;let w=b;if(Array.isArray(f)){if(f.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(f),b+=h;let k=`
38
+ ${b}`,M=`,
39
+ ${b}`,B=Math.min(f.length,a),F=0;for(;F<B-1;F++){let J=u(String(F),f[F],g,h,b);k+=J!==void 0?J:"null",k+=M}let K=u(String(F),f[F],g,h,b);if(k+=K!==void 0?K:"null",f.length-1>a){let J=f.length-a-1;k+=`${M}"... ${Ke(J)} not stringified"`}return k+=`
40
+ ${w}`,g.pop(),`[${k}]`}let x=Object.keys(f),S=x.length;if(S===0)return"{}";if(o<g.length+1)return'"[Object]"';b+=h;let E=`,
41
+ ${b}`,_="",T="",A=Math.min(S,a);Wn(f)&&(_+=Wo(f,E,a),x=x.slice(f.length),A-=f.length,T=E),s&&(x=Hn(x,i)),g.push(f);for(let k=0;k<A;k++){let M=x[k],B=u(M,f[M],g,h,b);B!==void 0&&(_+=`${T}${Ie(M)}: ${B}`,T=E)}if(S>a){let k=S-a;_+=`${T}"...": "${Ke(k)} not stringified"`,T=E}return T!==""&&(_=`
42
+ ${b}${_}
43
+ ${w}`),g.pop(),`{${_}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(f);default:return e?e(f):void 0}}function d(p,f,g){switch(typeof f){case"string":return Ie(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(p),typeof f!="object")return d(p,f,g);if(f===null)return"null"}if(g.indexOf(f)!==-1)return r;let h="",b=f.length!==void 0;if(b&&Array.isArray(f)){if(f.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(f);let _=Math.min(f.length,a),T=0;for(;T<_-1;T++){let k=d(String(T),f[T],g);h+=k!==void 0?k:"null",h+=","}let A=d(String(T),f[T],g);if(h+=A!==void 0?A:"null",f.length-1>a){let k=f.length-a-1;h+=`,"... ${Ke(k)} not stringified"`}return g.pop(),`[${h}]`}let w=Object.keys(f),x=w.length;if(x===0)return"{}";if(o<g.length+1)return'"[Object]"';let S="",E=Math.min(x,a);b&&Wn(f)&&(h+=Wo(f,",",a),w=w.slice(f.length),E-=f.length,S=","),s&&(w=Hn(w,i)),g.push(f);for(let _=0;_<E;_++){let T=w[_],A=d(T,f[T],g);A!==void 0&&(h+=`${S}${Ie(T)}:${A}`,S=",")}if(x>a){let _=x-a;h+=`${S}"...":"${Ke(_)} not stringified"`}return g.pop(),`{${h}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(f);default:return e?e(f):void 0}}function m(p,f,g){if(arguments.length>1){let h="";if(typeof g=="number"?h=" ".repeat(Math.min(g,10)):typeof g=="string"&&(h=g.slice(0,10)),f!=null){if(typeof f=="function")return l("",{"":p},[],f,h,"");if(Array.isArray(f))return c("",p,[],Bp(f),h,"")}if(h.length!==0)return u("",p,[],h,"")}return d("",p,[])}return m}});var Xo=I((yw,Yo)=>{"use strict";var zn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Jo}=lr(),Wp=Jo.info;function Vp(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(Jo);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:u,[zn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(d){let m,p=this.lastLevel,{streams:f}=this,g=0,h;for(let b=Kp(f.length,e.dedupe);Gp(b,f.length,e.dedupe);b=zp(b,e.dedupe))if(m=f[b],m.level<=p){if(g!==0&&g!==m.level)break;if(h=m.stream,h[zn]){let{lastTime:w,lastMsg:x,lastObj:S,lastLogger:E}=this;h.lastLevel=p,h.lastTime=w,h.lastMsg=x,h.lastObj=S,h.lastLogger=E}h.write(d),e.dedupe&&(g=m.level)}else if(!e.dedupe)break}function i(...d){for(let{stream:m}of this.streams)typeof m.emit=="function"&&m.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 m=typeof d.write=="function"||d.stream,p=d.write?d:d.stream;if(!m)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:f,streamLevels:g}=this,h;typeof d.levelVal=="number"?h=d.levelVal:typeof d.level=="string"?h=g[d.level]:typeof d.level=="number"?h=d.level:h=Wp;let b={stream:p,level:h,levelVal:void 0,id:++n.lastId};return f.unshift(b),f.sort(Go),this.minLevel=f[0].level,n}function l(d){let{streams:m}=this,p=m.findIndex(f=>f.id===d);return p>=0&&(m.splice(p,1),m.sort(Go),this.minLevel=m.length>0?m[0].level:-1),n}function c(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function u(d){let m=new Array(this.streams.length);for(let p=0;p<m.length;p++)m[p]={level:d,stream:this.streams[p].stream};return{write:s,add:a,remove:l,minLevel:d,streams:m,clone:u,emit:i,flushSync:o,[zn]:!0}}}function Go(t,e){return t.level-e.level}function Kp(t,e){return e?t-1:0}function zp(t,e){return e?t-1:t+1}function Gp(t,e,r){return r?t>=0:t<e}Yo.exports=Vp});var fa=I((ww,le)=>{"use strict";var Jp=require("node:os"),ia=pn(),Yp=mn(),Xp=yn(),oa=ji(),Qp=Ho(),aa=it(),{configure:Zp}=zo(),{assertDefaultLevelFound:em,mappings:la,genLsCache:tm,genLevelComparison:rm,assertLevelComparison:nm}=Dn(),{DEFAULT_LEVELS:ca,SORTING_ORDER:sm}=lr(),{createArgsNormalizer:im,asChindings:om,buildSafeSonicBoom:Qo,buildFormatters:am,stringify:Gn,normalizeDestFileDescriptor:Zo,noop:lm}=ar(),{version:cm}=Fn(),{chindingsSym:ea,redactFmtSym:um,serializersSym:ta,timeSym:fm,timeSliceIndexSym:dm,streamSym:pm,stringifySym:ra,stringifySafeSym:Jn,stringifiersSym:na,setLevelSym:mm,endSym:hm,formatOptsSym:gm,messageKeySym:ym,errorKeySym:wm,nestedKeySym:bm,mixinSym:xm,levelCompSym:vm,useOnlyCustomLevelsSym:Sm,formattersSym:sa,hooksSym:_m,nestedKeyStrSym:km,mixinMergeStrategySym:$m,msgPrefixSym:Tm}=aa,{epochTime:ua,nullTime:Cm}=oa,{pid:Em}=process,Am=Jp.hostname(),Om=ia.err,Rm={level:"info",levelComparison:sm.ASC,levels:ca,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Em,hostname:Am},serializers:Object.assign(Object.create(null),{err:Om}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:ua,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Im=im(Rm),Mm=Object.assign(Object.create(null),ia);function Yn(...t){let e={},{opts:r,stream:n}=Im(e,Yp(),...t);r.level&&typeof r.level=="string"&&ca[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:u,base:d,name:m,level:p,customLevels:f,levelComparison:g,mixin:h,mixinMergeStrategy:b,useOnlyCustomLevels:w,formatters:x,hooks:S,depthLimit:E,edgeLimit:_,onChild:T,msgPrefix:A}=r,k=Zp({maximumDepth:E,maximumBreadth:_}),M=am(x.level,x.bindings,x.log),B=Gn.bind({[Jn]:k}),F=s?Xp(s,B):{},K=s?{stringify:F[um]}:{stringify:B},J="}"+(i?`\r
44
44
  `:`
45
- `),X=Bp.bind(null,{[Ko]:"",[Go]:o,[Yo]:D,[Jo]:Wn,[Vn]:k,[Xo]:M}),te="";d!==null&&(m===void 0?te=X(d):te=X(Object.assign({},d,{name:m})));let P=a instanceof Function?a:a?na:cm,L=P().indexOf(":")+1;if(b&&!f)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(A&&typeof A!="string")throw Error(`Unknown msgPrefix type "${typeof A}" - expected "string"`);Lp(p,f,b);let qt=ta(f,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:qt,messageKey:l,errorKey:c}}),Np(h);let Os=Fp(h);return Object.assign(e,{levels:qt,[nm]:Os,[sm]:b,[Jp]:n,[Kp]:P,[Gp]:L,[Jo]:Wn,[Vn]:k,[Yo]:D,[Xp]:z,[Qp]:H,[Zp]:l,[em]:c,[tm]:u,[om]:u?`,${JSON.stringify(u)}:{`:"",[Go]:o,[rm]:g,[am]:S,[Ko]:te,[Xo]:M,[im]:v,silent:Wp,onChild:T,[lm]:A}),Object.setPrototypeOf(e,jp()),Dp(e),e[Yp](p),e}ie.exports=zn;ie.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=zo(t.dest||process.stdout.fd),Vo(t)):Vo({dest:zo(t),minLength:0});ie.exports.transport=Cn();ie.exports.multistream=Wo();ie.exports.levels=ta();ie.exports.stdSerializers=hm;ie.exports.stdTimeFunctions=Object.assign({},Zo);ie.exports.symbols=ea;ie.exports.version=Vp;ie.exports.default=zn;ie.exports.pino=zn});var Ws=C(Hs(),1),{program:Zg,createCommand:ey,createArgument:ty,createOption:ry,CommanderError:ny,InvalidArgumentError:sy,InvalidOptionArgumentError:iy,Command:Vs,Argument:oy,Option:ay,Help:ly}=Ws.default;var ue=C(require("fs")),De=C(require("path")),zs=C(require("os"));var Ye={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}},ne={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","stepfun-ai/step-3.5-flash","nvidia/llama-3.1-nemotron-70b-instruct","qwen/qwen2.5-coder-32b-instruct","deepseek-ai/deepseek-coder-33b-instruct"]};var Xe=De.join(zs.homedir(),".hablas"),Qr=De.join(Xe,"config.json");function Qe(t={}){let e={};if(ue.existsSync(Qr))try{e=JSON.parse(ue.readFileSync(Qr,"utf-8"))}catch{}let r={...Ye,...e,tools:{...Ye.tools,...e.tools||{},runCommand:{...Ye.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...Ye.workspace,...e.workspace||{}},vision:{...Ye.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=De.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){ue.existsSync(Xe)||ue.mkdirSync(Xe,{recursive:!0}),ue.writeFileSync(Qr,JSON.stringify(t,null,2),"utf-8")}function Ks(){let t=[Xe,De.join(Xe,"logs"),De.join(Xe,"backup")];for(let e of t)ue.existsSync(e)||ue.mkdirSync(e,{recursive:!0})}var Kn=C(sa()),Gn=C(require("path")),ia=C(require("os")),ar=C(require("fs"));function Jn(t){let e=Gn.join(ia.homedir(),".hablas","logs");ar.existsSync(e)||ar.mkdirSync(e,{recursive:!0});let r=Gn.join(e,`session-${Date.now()}.log`);return(0,Kn.default)({level:"info"},Kn.default.destination({dest:r,sync:!1}))}var lr=C(require("fs")),kt=C(require("path"));function oa(){let t=[kt.resolve(__dirname,"..","package.json"),kt.resolve(__dirname,"..","..","package.json"),kt.resolve(process.cwd(),"package.json"),kt.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(lr.existsSync(e)){let r=JSON.parse(lr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Yl=C(require("fs")),Xl=C(require("path"));var cr=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 u of c)if(u.trim())try{let d=JSON.parse(u);d.message?.content&&(yield d.message.content)}catch{}}}};var aa=12e4,gm=6e4,ur=3,la=1e3,ym=20;function ca(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 wm(t){return t.map(e=>({type:"function",function:e.function}))}function bm(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 ua(t){return new Promise(e=>setTimeout(e,t))}function fa(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var $t=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<ym;){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(gm)});if(!l.ok)break;let c=await l.json();if(Array.isArray(c))e.push(...c.map(u=>u.id||u.name||u).filter(Boolean)),r=!1;else if(c.data&&Array.isArray(c.data)){let u=c.data.map(d=>d.id||d.name).filter(Boolean);e.push(...u),c.has_more&&u.length>0?(n=u[u.length-1],s++):r=!1}else c.models&&Array.isArray(c.models)&&e.push(...c.models.map(u=>u.name||u.id).filter(Boolean)),r=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,r,n){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:ca(e)};r.length>0&&(i.tools=wm(r),i.tool_choice="auto");let o=null;for(let a=0;a<=ur;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),aa),u={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:n||l.signal};try{let d=await fetch(s,u);if(clearTimeout(c),!d.ok){let h=await d.text().catch(()=>"");if(!fa(null,d.status))throw new Error(`API error: ${d.status} ${d.statusText} \u2014 ${h}`);if(o=new Error(`API error: ${d.status} ${d.statusText} \u2014 ${h}`),a<ur){let g=la*Math.pow(2,a);await ua(g);continue}throw o}let p=(await d.json()).choices?.[0];if(!p)throw new Error("API returned empty response");let f=p.message.tool_calls?bm(p.message.tool_calls):void 0;return{message:{role:p.message.role||"assistant",content:p.message.content||"",tool_calls:f},done:!0,done_reason:p.finish_reason}}catch(d){if(clearTimeout(c),d.name==="AbortError"&&n?.aborted)throw d;if(fa(d)&&(o=d,a<ur)){let m=la*Math.pow(2,a);await ua(m);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=ur)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:ca(e),stream:!0}),signal:r||AbortSignal.timeout(aa)});if(!s.ok)throw new Error(`API error: ${s.status} ${s.statusText}`);let i=s.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:c}=await i.read();if(l)break;a+=o.decode(c,{stream:!0});let u=a.split(`
47
- `);a=u.pop()||"";for(let d of u){let m=d.trim();if(!(!m||m==="data: [DONE]")&&m.startsWith("data: "))try{let f=JSON.parse(m.slice(6)).choices?.[0]?.delta?.content;f&&(yield f)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function nt(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:ne.apiUrl};return new $t(e)}return t.provider==="custom"&&t.apiUrl?new $t(t):new cr(t)}function He(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var N=C(require("fs/promises")),ns=C(require("fs")),Ee=C(require("path"));function be(){}be.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(v){return i?(setTimeout(function(){i(void 0,v)},0),!0):v}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,u=1,d=l+c;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var m=(n=s.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+m,f=[{oldPos:-1,lastComponent:void 0}],h=this.extractCommon(f[0],r,e,0);if(f[0].oldPos+1>=c&&h+1>=l)return a([{value:this.join(r),count:r.length}]);var g=-1/0,S=1/0;function b(){for(var v=Math.max(g,-u);v<=Math.min(S,u);v+=2){var E=void 0,_=f[v-1],T=f[v+1];_&&(f[v-1]=void 0);var A=!1;if(T){var k=T.oldPos-v;A=T&&0<=k&&k<l}var M=_&&_.oldPos+1<c;if(!A&&!M){f[v]=void 0;continue}if(!M||A&&_.oldPos+1<T.oldPos?E=o.addToPath(T,!0,void 0,0):E=o.addToPath(_,void 0,!0,1),h=o.extractCommon(E,r,e,v),E.oldPos+1>=c&&h+1>=l)return a(xm(o,E.lastComponent,r,e,o.useLongestToken));f[v]=E,E.oldPos+1>=c&&(S=Math.min(S,v-1)),h+1>=l&&(g=Math.max(g,v+1))}u++}if(i)(function v(){setTimeout(function(){if(u>d||Date.now()>p)return i();b()||v()},0)})();else for(;u<=d&&Date.now()<=p;){var x=b();if(x)return x}},addToPath:function(e,r,n,s){var i=e.lastComponent;return i&&i.added===r&&i.removed===n?{oldPos:e.oldPos+s,lastComponent:{count:i.count+1,added:r,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+s,lastComponent:{count:1,added:r,removed:n,previousComponent:i}}},extractCommon:function(e,r,n,s){for(var i=r.length,o=n.length,a=e.oldPos,l=a-s,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 xm(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,u=0;a<l;a++){var d=i[a];if(d.removed){if(d.value=t.join(n.slice(u,u+d.count)),u+=d.count,a&&i[a-1].added){var p=i[a-1];i[a-1]=i[a],i[a]=p}}else{if(!d.added&&s){var m=r.slice(c,c+d.count);m=m.map(function(h,g){var S=n[u+g];return S.length>h.length?S:h}),d.value=t.join(m)}else d.value=t.join(r.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}var f=i[l-1];return l>1&&typeof f.value=="string"&&(f.added||f.removed)&&t.equals("",f.value)&&(i[l-2].value+=f.value,i.pop()),i}var sw=new be;var da=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,pa=/\S/,ma=new be;ma.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!pa.test(t)&&!pa.test(e)};ma.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]&&da.test(e[r])&&da.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var es=new be;es.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 Sm(t,e,r){return es.diff(t,e,r)}var vm=new be;vm.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var _m=new be;_m.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function fr(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?fr=function(e){return typeof e}:fr=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},fr(t)}function Yn(t){return km(t)||$m(t)||Tm(t)||Cm()}function km(t){if(Array.isArray(t))return Xn(t)}function $m(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Tm(t,e){if(t){if(typeof t=="string")return Xn(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 Xn(t,e)}}function Xn(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 Cm(){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 Em=Object.prototype.toString,Tt=new be;Tt.useLongestToken=!0;Tt.tokenize=es.tokenize;Tt.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(Qn(t,null,null,s),s," ")};Tt.equals=function(t,e){return be.prototype.equals.call(Tt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function Qn(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(Em.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]=Qn(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),fr(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]=Qn(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var Zn=new be;Zn.tokenize=function(t){return t.slice()};Zn.join=Zn.removeEmpty=function(t){return t};function Am(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Sm(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(S){return S.map(function(b){return" "+b})}for(var c=[],u=0,d=0,m=[],p=1,f=1,h=function(b){var x=a[b],v=x.lines||x.value.replace(/\n$/,"").split(`
50
- `);if(x.lines=v,x.added||x.removed){var E;if(!u){var _=a[b-1];u=p,d=f,_&&(m=o.context>0?l(_.lines.slice(-o.context)):[],u-=m.length,d-=m.length)}(E=m).push.apply(E,Yn(v.map(function(z){return(x.added?"+":"-")+z}))),x.added?f+=v.length:p+=v.length}else{if(u)if(v.length<=o.context*2&&b<a.length-2){var T;(T=m).push.apply(T,Yn(l(v)))}else{var A,k=Math.min(v.length,o.context);(A=m).push.apply(A,Yn(l(v.slice(0,k))));var M={oldStart:u,oldLines:p-u+k,newStart:d,newLines:f-d+k,lines:m};if(b>=a.length-2&&v.length<=o.context){var q=/\n$/.test(r),D=/\n$/.test(n),H=v.length==0&&m.length>M.oldLines;!q&&H&&r.length>0&&m.splice(M.oldLines,0,"\"),(!q&&!H||!D)&&m.push("\")}c.push(M),u=0,d=0,m=[]}p+=v.length,f+=v.length}},g=0;g<a.length;g++)h(g);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:c}}function ha(t){if(Array.isArray(t))return t.map(ha).join(`
45
+ `),ee=om.bind(null,{[ea]:"",[ta]:o,[na]:F,[ra]:Gn,[Jn]:k,[sa]:M}),se="";d!==null&&(m===void 0?se=ee(d):se=ee(Object.assign({},d,{name:m})));let P=a instanceof Function?a:a?ua:Cm,D=P().indexOf(":")+1;if(w&&!f)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(h&&typeof h!="function")throw Error(`Unknown mixin type "${typeof h}" - expected "function"`);if(A&&typeof A!="string")throw Error(`Unknown msgPrefix type "${typeof A}" - expected "string"`);em(p,f,w);let Wt=la(f,w);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:Wt,messageKey:l,errorKey:c}}),nm(g);let Ds=rm(g);return Object.assign(e,{levels:Wt,[vm]:Ds,[Sm]:w,[pm]:n,[fm]:P,[dm]:D,[ra]:Gn,[Jn]:k,[na]:F,[hm]:J,[gm]:K,[ym]:l,[wm]:c,[bm]:u,[km]:u?`,${JSON.stringify(u)}:{`:"",[ta]:o,[xm]:h,[$m]:b,[ea]:se,[sa]:M,[_m]:S,silent:lm,onChild:T,[Tm]:A}),Object.setPrototypeOf(e,Qp()),tm(e),e[mm](p),e}le.exports=Yn;le.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=Zo(t.dest||process.stdout.fd),Qo(t)):Qo({dest:Zo(t),minLength:0});le.exports.transport=Rn();le.exports.multistream=Xo();le.exports.levels=la();le.exports.stdSerializers=Mm;le.exports.stdTimeFunctions=Object.assign({},oa);le.exports.symbols=aa;le.exports.version=cm;le.exports.default=Yn;le.exports.pino=Yn});var Xs=C(Ys(),1),{program:Ey,createCommand:Ay,createArgument:Oy,createOption:Ry,CommanderError:Iy,InvalidArgumentError:My,InvalidOptionArgumentError:jy,Command:Qs,Argument:Py,Option:Ly,Help:Dy}=Xs.default;var pe=C(require("fs")),Be=C(require("path")),Zs=C(require("os"));var tt={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}},oe={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 rt=Be.join(Zs.homedir(),".hablas"),rn=Be.join(rt,"config.json");function nt(t={}){let e={};if(pe.existsSync(rn))try{e=JSON.parse(pe.readFileSync(rn,"utf-8"))}catch{}let r={...tt,...e,tools:{...tt.tools,...e.tools||{},runCommand:{...tt.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...tt.workspace,...e.workspace||{}},vision:{...tt.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=Be.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 st(t){pe.existsSync(rt)||pe.mkdirSync(rt,{recursive:!0}),pe.writeFileSync(rn,JSON.stringify(t,null,2),"utf-8")}function ei(){let t=[rt,Be.join(rt,"logs"),Be.join(rt,"backup")];for(let e of t)pe.existsSync(e)||pe.mkdirSync(e,{recursive:!0})}var Xn=C(fa()),Qn=C(require("path")),da=C(require("os")),fr=C(require("fs"));function Zn(t){let e=Qn.join(da.homedir(),".hablas","logs");fr.existsSync(e)||fr.mkdirSync(e,{recursive:!0});let r=Qn.join(e,`session-${Date.now()}.log`);return(0,Xn.default)({level:"info"},Xn.default.destination({dest:r,sync:!1}))}var dr=C(require("fs")),Et=C(require("path"));function pa(){let t=[Et.resolve(__dirname,"..","package.json"),Et.resolve(__dirname,"..","..","package.json"),Et.resolve(process.cwd(),"package.json"),Et.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(dr.existsSync(e)){let r=JSON.parse(dr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var mc=C(require("fs")),hc=C(require("path"));var pr=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 u of c)if(u.trim())try{let d=JSON.parse(u);d.message?.content&&(yield d.message.content)}catch{}}}};var ma=12e4,jm=6e4,mr=3,ha=1e3,Pm=20;function ga(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 Lm(t){return t.map(e=>({type:"function",function:e.function}))}function Dm(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 ya(t){return new Promise(e=>setTimeout(e,t))}function wa(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var At=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<Pm;){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(jm)});if(!l.ok)break;let c=await l.json();if(Array.isArray(c))e.push(...c.map(u=>u.id||u.name||u).filter(Boolean)),r=!1;else if(c.data&&Array.isArray(c.data)){let u=c.data.map(d=>d.id||d.name).filter(Boolean);e.push(...u),c.has_more&&u.length>0?(n=u[u.length-1],s++):r=!1}else c.models&&Array.isArray(c.models)&&e.push(...c.models.map(u=>u.name||u.id).filter(Boolean)),r=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,r,n){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:ga(e)};r.length>0&&(i.tools=Lm(r),i.tool_choice="auto");let o=null;for(let a=0;a<=mr;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),ma),u={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:n||l.signal};try{let d=await fetch(s,u);if(clearTimeout(c),!d.ok){let g=await d.text().catch(()=>"");if(!wa(null,d.status))throw new Error(`API error: ${d.status} ${d.statusText} \u2014 ${g}`);if(o=new Error(`API error: ${d.status} ${d.statusText} \u2014 ${g}`),a<mr){let h=ha*Math.pow(2,a);await ya(h);continue}throw o}let p=(await d.json()).choices?.[0];if(!p)throw new Error("API returned empty response");let f=p.message.tool_calls?Dm(p.message.tool_calls):void 0;return{message:{role:p.message.role||"assistant",content:p.message.content||"",tool_calls:f},done:!0,done_reason:p.finish_reason}}catch(d){if(clearTimeout(c),d.name==="AbortError"&&n?.aborted)throw d;if(wa(d)&&(o=d,a<mr)){let m=ha*Math.pow(2,a);await ya(m);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=mr)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:ga(e),stream:!0}),signal:r||AbortSignal.timeout(ma)});if(!s.ok)throw new Error(`API error: ${s.status} ${s.statusText}`);let i=s.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:c}=await i.read();if(l)break;a+=o.decode(c,{stream:!0});let u=a.split(`
47
+ `);a=u.pop()||"";for(let d of u){let m=d.trim();if(!(!m||m==="data: [DONE]")&&m.startsWith("data: "))try{let f=JSON.parse(m.slice(6)).choices?.[0]?.delta?.content;f&&(yield f)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function lt(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:oe.apiUrl};return new At(e)}return t.provider==="custom"&&t.apiUrl?new At(t):new pr(t)}function Ge(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=C(require("fs/promises")),as=C(require("fs")),Me=C(require("path"));function _e(){}_e.prototype={diff:function(e,r){var n,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=s.callback;typeof s=="function"&&(i=s,s={}),this.options=s;var o=this;function a(S){return i?(setTimeout(function(){i(void 0,S)},0),!0):S}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,c=e.length,u=1,d=l+c;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var m=(n=s.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+m,f=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(f[0],r,e,0);if(f[0].oldPos+1>=c&&g+1>=l)return a([{value:this.join(r),count:r.length}]);var h=-1/0,b=1/0;function w(){for(var S=Math.max(h,-u);S<=Math.min(b,u);S+=2){var E=void 0,_=f[S-1],T=f[S+1];_&&(f[S-1]=void 0);var A=!1;if(T){var k=T.oldPos-S;A=T&&0<=k&&k<l}var M=_&&_.oldPos+1<c;if(!A&&!M){f[S]=void 0;continue}if(!M||A&&_.oldPos+1<T.oldPos?E=o.addToPath(T,!0,void 0,0):E=o.addToPath(_,void 0,!0,1),g=o.extractCommon(E,r,e,S),E.oldPos+1>=c&&g+1>=l)return a(Fm(o,E.lastComponent,r,e,o.useLongestToken));f[S]=E,E.oldPos+1>=c&&(b=Math.min(b,S-1)),g+1>=l&&(h=Math.max(h,S+1))}u++}if(i)(function S(){setTimeout(function(){if(u>d||Date.now()>p)return i();w()||S()},0)})();else for(;u<=d&&Date.now()<=p;){var x=w();if(x)return x}},addToPath:function(e,r,n,s){var i=e.lastComponent;return i&&i.added===r&&i.removed===n?{oldPos:e.oldPos+s,lastComponent:{count:i.count+1,added:r,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+s,lastComponent:{count:1,added:r,removed:n,previousComponent:i}}},extractCommon:function(e,r,n,s){for(var i=r.length,o=n.length,a=e.oldPos,l=a-s,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 Fm(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,u=0;a<l;a++){var d=i[a];if(d.removed){if(d.value=t.join(n.slice(u,u+d.count)),u+=d.count,a&&i[a-1].added){var p=i[a-1];i[a-1]=i[a],i[a]=p}}else{if(!d.added&&s){var m=r.slice(c,c+d.count);m=m.map(function(g,h){var b=n[u+h];return b.length>g.length?b:g}),d.value=t.join(m)}else d.value=t.join(r.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}var f=i[l-1];return l>1&&typeof f.value=="string"&&(f.added||f.removed)&&t.equals("",f.value)&&(i[l-2].value+=f.value,i.pop()),i}var Mw=new _e;var ba=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,xa=/\S/,va=new _e;va.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!xa.test(t)&&!xa.test(e)};va.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]&&ba.test(e[r])&&ba.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var ss=new _e;ss.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 Nm(t,e,r){return ss.diff(t,e,r)}var Um=new _e;Um.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var qm=new _e;qm.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function hr(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?hr=function(e){return typeof e}:hr=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},hr(t)}function es(t){return Bm(t)||Hm(t)||Wm(t)||Vm()}function Bm(t){if(Array.isArray(t))return ts(t)}function Hm(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Wm(t,e){if(t){if(typeof t=="string")return ts(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 ts(t,e)}}function ts(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 Vm(){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 Km=Object.prototype.toString,Ot=new _e;Ot.useLongestToken=!0;Ot.tokenize=ss.tokenize;Ot.castInput=function(t){var e=this.options,r=e.undefinedReplacement,n=e.stringifyReplacer,s=n===void 0?function(i,o){return typeof o>"u"?r:o}:n;return typeof t=="string"?t:JSON.stringify(rs(t,null,null,s),s," ")};Ot.equals=function(t,e){return _e.prototype.equals.call(Ot,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function rs(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(Km.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]=rs(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),hr(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]=rs(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var ns=new _e;ns.tokenize=function(t){return t.slice()};ns.join=ns.removeEmpty=function(t){return t};function zm(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Nm(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(b){return b.map(function(w){return" "+w})}for(var c=[],u=0,d=0,m=[],p=1,f=1,g=function(w){var x=a[w],S=x.lines||x.value.replace(/\n$/,"").split(`
50
+ `);if(x.lines=S,x.added||x.removed){var E;if(!u){var _=a[w-1];u=p,d=f,_&&(m=o.context>0?l(_.lines.slice(-o.context)):[],u-=m.length,d-=m.length)}(E=m).push.apply(E,es(S.map(function(J){return(x.added?"+":"-")+J}))),x.added?f+=S.length:p+=S.length}else{if(u)if(S.length<=o.context*2&&w<a.length-2){var T;(T=m).push.apply(T,es(l(S)))}else{var A,k=Math.min(S.length,o.context);(A=m).push.apply(A,es(l(S.slice(0,k))));var M={oldStart:u,oldLines:p-u+k,newStart:d,newLines:f-d+k,lines:m};if(w>=a.length-2&&S.length<=o.context){var B=/\n$/.test(r),F=/\n$/.test(n),K=S.length==0&&m.length>M.oldLines;!B&&K&&r.length>0&&m.splice(M.oldLines,0,"\"),(!B&&!K||!F)&&m.push("\")}c.push(M),u=0,d=0,m=[]}p+=S.length,f+=S.length}},h=0;h<a.length;h++)g(h);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:c}}function Sa(t){if(Array.isArray(t))return t.map(Sa).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 Om(t,e,r,n,s,i,o){return ha(Am(t,e,r,n,s,i,o))}function ga(t,e,r,n,s,i){return Om(t,t,e,r,n,s,i)}function ts(t,e,r){return ga(t,e,r,"original","modified")}var ge=C(require("fs/promises")),rs=C(require("fs")),st=C(require("path")),wa=C(require("os")),Ct=st.join(wa.homedir(),".hablas","backup"),ya=10;async function We(t){try{if(!rs.existsSync(t))return;rs.existsSync(Ct)||await ge.mkdir(Ct,{recursive:!0});let e=await ge.readFile(t,"utf-8"),r=st.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=st.join(Ct,s);await ge.writeFile(i,e,"utf-8");let a=(await ge.readdir(Ct)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>ya)for(let l of a.slice(ya))await ge.unlink(st.join(Ct,l))}catch{}}function xa(t){let e=p=>Ee.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 f=e(p.path),g=(await N.readFile(f,"utf-8")).split(`
54
- `),S=g.length,b=p.start_line?Math.max(1,p.start_line):1,x=p.end_line?Math.min(S,p.end_line):S,v=g.slice(b-1,x),E=String(x).length,_=v.map((k,M)=>`${String(b+M).padStart(E," ")} | ${k}`),T=`[${p.path} \u2014 lines ${b}-${x} of ${S}]`,A=x<S?`
55
- ... [Partial read. Total lines: ${S}.]`:"";return{success:!0,output:`${T}
53
+ `}function Gm(t,e,r,n,s,i,o){return Sa(zm(t,e,r,n,s,i,o))}function _a(t,e,r,n,s,i){return Gm(t,t,e,r,n,s,i)}function is(t,e,r){return _a(t,e,r,"original","modified")}var xe=C(require("fs/promises")),os=C(require("fs")),ct=C(require("path")),$a=C(require("os")),Rt=ct.join($a.homedir(),".hablas","backup"),ka=10;async function Je(t){try{if(!os.existsSync(t))return;os.existsSync(Rt)||await xe.mkdir(Rt,{recursive:!0});let e=await xe.readFile(t,"utf-8"),r=ct.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=ct.join(Rt,s);await xe.writeFile(i,e,"utf-8");let a=(await xe.readdir(Rt)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>ka)for(let l of a.slice(ka))await xe.unlink(ct.join(Rt,l))}catch{}}function Ca(t){let e=p=>Me.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 f=e(p.path),h=(await U.readFile(f,"utf-8")).split(`
54
+ `),b=h.length,w=p.start_line?Math.max(1,p.start_line):1,x=p.end_line?Math.min(b,p.end_line):b,S=h.slice(w-1,x),E=String(x).length,_=S.map((k,M)=>`${String(w+M).padStart(E," ")} | ${k}`),T=`[${p.path} \u2014 lines ${w}-${x} of ${b}]`,A=x<b?`
55
+ ... [Partial read. Total lines: ${b}.]`:"";return{success:!0,output:`${T}
56
56
  ${_.join(`
57
- `)}${A}`}}catch(f){return{success:!1,output:"",error:`[read_file]: ${f.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async 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 f=e(p.path);return ns.existsSync(f)&&await We(f),await N.mkdir(Ee.dirname(f),{recursive:!0}),await N.writeFile(f,p.content,"utf-8"),{success:!0,output:`Written: ${p.path}`}}catch(f){return{success:!1,output:"",error:`[write_file]: ${f.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. 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 f=e(p.path),h=await N.readFile(f,"utf-8"),g=p.old_content,S=p.new_content,b=ba(h,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 We(f);let x=h.replace(g,S);await N.writeFile(f,x,"utf-8");let v=ts(p.path,h,x);return{success:!0,output:`Edited: ${p.path}
58
- ${v}`}}catch(f){return{success:!1,output:"",error:`[edit_file]: ${f.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async 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 f=e(p.path),h=await N.readFile(f,"utf-8"),g=h.split(`
59
- `),S=g.length,b=p.start_line,x=p.end_line;if(b<1||b>S)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${S} lines)`};if(x<b||x>S)return{success:!1,output:"",error:`[patch_file]: end_line ${x} is out of range (start_line=${b}, total=${S})`};await We(f);let v=g.slice(0,b-1),E=g.slice(x),_=p.new_content.split(`
60
- `),T=[...v,..._,...E].join(`
61
- `);await N.writeFile(f,T,"utf-8");let A=ts(p.path,h,T),k=x-b+1,M=_.length;return{success:!0,output:`Patched: ${p.path} (replaced ${k} lines with ${M})
62
- ${A}`}}catch(f){return{success:!1,output:"",error:`[patch_file]: ${f.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async 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 f=e(p.path),h=await N.readFile(f,"utf-8"),g=p.search,S=p.replace,b=p.is_regex;await We(f);let x,v;if(b){let E=new RegExp(g,"g");v=(h.match(E)||[]).length,x=h.replace(E,S)}else v=ba(h,g),x=h.split(g).join(S);return v===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await N.writeFile(f,x,"utf-8"),{success:!0,output:`Replaced ${v} occurrence(s) in ${p.path}`})}catch(f){return{success:!1,output:"",error:`[search_and_replace]: ${f.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async 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 f=e(p.path);return await N.mkdir(Ee.dirname(f),{recursive:!0}),ns.existsSync(f)&&await We(f),await N.appendFile(f,p.content,"utf-8"),{success:!0,output:`Appended to: ${p.path}`}}catch(f){return{success:!1,output:"",error:`[append_to_file]: ${f.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let f=e(p.path);return await We(f),await N.unlink(f),{success:!0,output:`Deleted: ${p.path}`}}catch(f){return{success:!1,output:"",error:`[delete_file]: ${f.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async 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 f=e(p.from),h=e(p.to);return await N.mkdir(Ee.dirname(h),{recursive:!0}),await N.rename(f,h),{success:!0,output:`Moved: ${p.from} \u2192 ${p.to}`}}catch(f){return{success:!1,output:"",error:`[move_file]: ${f.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let f=e(p.path);return await N.mkdir(f,{recursive:!0}),{success:!0,output:`Created directory: ${p.path}`}}catch(f){return{success:!1,output:"",error:`[create_dir]: ${f.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async p=>{try{let f=e(p.path||"."),h=p.depth||3;return{success:!0,output:await Sa(f,"",h,0)||"(empty directory)"}}catch(f){return{success:!1,output:"",error:`[list_dir]: ${f.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let f=e(p.path),h=await N.stat(f);return{success:!0,output:[`Path: ${p.path}`,`Size: ${Rm(h.size)}`,`Type: ${h.isDirectory()?"directory":"file"}`,`Modified: ${h.mtime.toISOString()}`,`Created: ${h.birthtime.toISOString()}`].join(`
63
- `)}}catch(f){return{success:!1,output:"",error:`[get_file_info]: ${f.message}`}}}}]}function ba(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 Im=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Sa(t,e,r,n){if(n>=r)return"";let i=(await N.readdir(t,{withFileTypes:!0})).filter(a=>!Im.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],c=a===i.length-1,u=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${u}${d} ${l.name}
64
- `,l.isDirectory()){let m=e+(c?" ":"\u2502 ");o+=await Sa(Ee.join(t,l.name),m,r,n+1)}}return o}function Rm(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var ka=require("child_process");var va=require("child_process"),dr=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,va.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...r?.env}}),o={id:n,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
57
+ `)}${A}`}}catch(f){return{success:!1,output:"",error:`[read_file]: ${f.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async 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 f=e(p.path);return as.existsSync(f)&&await Je(f),await U.mkdir(Me.dirname(f),{recursive:!0}),await U.writeFile(f,p.content,"utf-8"),{success:!0,output:`Written: ${p.path}`}}catch(f){return{success:!1,output:"",error:`[write_file]: ${f.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. 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 f=e(p.path),g=await U.readFile(f,"utf-8"),h=p.old_content,b=p.new_content,w=Ta(g,h);if(w===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(w>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${w} locations in the file. Provide more surrounding context to be specific.`};await Je(f);let x=g.replace(h,b);await U.writeFile(f,x,"utf-8");let S=is(p.path,g,x);return{success:!0,output:`Edited: ${p.path}
58
+ ${S}`}}catch(f){return{success:!1,output:"",error:`[edit_file]: ${f.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async 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 f=e(p.path),g=await U.readFile(f,"utf-8"),h=g.split(`
59
+ `),b=h.length,w=p.start_line,x=p.end_line;if(w<1||w>b)return{success:!1,output:"",error:`[patch_file]: start_line ${w} is out of range (file has ${b} lines)`};if(x<w||x>b)return{success:!1,output:"",error:`[patch_file]: end_line ${x} is out of range (start_line=${w}, total=${b})`};await Je(f);let S=h.slice(0,w-1),E=h.slice(x),_=p.new_content.split(`
60
+ `),T=[...S,..._,...E].join(`
61
+ `);await U.writeFile(f,T,"utf-8");let A=is(p.path,g,T),k=x-w+1,M=_.length;return{success:!0,output:`Patched: ${p.path} (replaced ${k} lines with ${M})
62
+ ${A}`}}catch(f){return{success:!1,output:"",error:`[patch_file]: ${f.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async 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 f=e(p.path),g=await U.readFile(f,"utf-8"),h=p.search,b=p.replace,w=p.is_regex;await Je(f);let x,S;if(w){let E=new RegExp(h,"g");S=(g.match(E)||[]).length,x=g.replace(E,b)}else S=Ta(g,h),x=g.split(h).join(b);return S===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await U.writeFile(f,x,"utf-8"),{success:!0,output:`Replaced ${S} occurrence(s) in ${p.path}`})}catch(f){return{success:!1,output:"",error:`[search_and_replace]: ${f.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async 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 f=e(p.path);return await U.mkdir(Me.dirname(f),{recursive:!0}),as.existsSync(f)&&await Je(f),await U.appendFile(f,p.content,"utf-8"),{success:!0,output:`Appended to: ${p.path}`}}catch(f){return{success:!1,output:"",error:`[append_to_file]: ${f.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let f=e(p.path);return await Je(f),await U.unlink(f),{success:!0,output:`Deleted: ${p.path}`}}catch(f){return{success:!1,output:"",error:`[delete_file]: ${f.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async 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 f=e(p.from),g=e(p.to);return await U.mkdir(Me.dirname(g),{recursive:!0}),await U.rename(f,g),{success:!0,output:`Moved: ${p.from} \u2192 ${p.to}`}}catch(f){return{success:!1,output:"",error:`[move_file]: ${f.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let f=e(p.path);return await U.mkdir(f,{recursive:!0}),{success:!0,output:`Created directory: ${p.path}`}}catch(f){return{success:!1,output:"",error:`[create_dir]: ${f.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async p=>{try{let f=e(p.path||"."),g=p.depth||3;return{success:!0,output:await Ea(f,"",g,0)||"(empty directory)"}}catch(f){return{success:!1,output:"",error:`[list_dir]: ${f.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let f=e(p.path),g=await U.stat(f);return{success:!0,output:[`Path: ${p.path}`,`Size: ${Ym(g.size)}`,`Type: ${g.isDirectory()?"directory":"file"}`,`Modified: ${g.mtime.toISOString()}`,`Created: ${g.birthtime.toISOString()}`].join(`
63
+ `)}}catch(f){return{success:!1,output:"",error:`[get_file_info]: ${f.message}`}}}}]}function Ta(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 Jm=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Ea(t,e,r,n){if(n>=r)return"";let i=(await U.readdir(t,{withFileTypes:!0})).filter(a=>!Jm.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],c=a===i.length-1,u=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${u}${d} ${l.name}
64
+ `,l.isDirectory()){let m=e+(c?" ":"\u2502 ");o+=await Ea(Me.join(t,l.name),m,r,n+1)}}return o}function Ym(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Ra=require("child_process");var Aa=require("child_process"),gr=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,Aa.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 Mm=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],ss=null;function _a(t){return ss||(ss=new dr({workingDir:t})),ss}function $a(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=[...Mm,...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=_a(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
70
- PID: ${_a(t).getProcess(l)?.pid}
71
- Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,ka.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),u="",d="";c.stdout?.on("data",m=>{u+=m}),c.stderr?.on("data",m=>{d+=m}),c.on("close",m=>{l(m===0?{success:!0,output:u||"(no output)"}:{success:!1,output:u,error:d||`Exit code: ${m}`})}),c.on("error",m=>{l({success:!1,output:"",error:m.message})})})}}}var pr=C(require("fs/promises")),Ae=C(require("path")),jm=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Pm=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function Ta(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=Ae.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await Ca(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 Xm=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],ls=null;function Oa(t){return ls||(ls=new gr({workingDir:t})),ls}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=[...Xm,...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=Oa(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
70
+ PID: ${Oa(t).getProcess(l)?.pid}
71
+ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,Ra.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),u="",d="";c.stdout?.on("data",m=>{u+=m}),c.stderr?.on("data",m=>{d+=m}),c.on("close",m=>{l(m===0?{success:!0,output:u||"(no output)"}:{success:!1,output:u,error:d||`Exit code: ${m}`})}),c.on("error",m=>{l({success:!1,output:"",error:m.message})})})}}}var yr=C(require("fs/promises")),je=C(require("path")),Qm=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Zm=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function Ma(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=je.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await ja(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 Ca(t,e,r,n){let s=await pr.readdir(t,{withFileTypes:!0});for(let i of s){if(jm.has(i.name)||i.name.startsWith("."))continue;let o=Ae.join(t,i.name);if(i.isDirectory())await Ca(o,e,r,n);else if(Pm.has(Ae.extname(i.name)))try{let l=(await pr.readFile(o,"utf-8")).split(`
74
- `),c=Ae.relative(n,o);for(let u=0;u<l.length;u++)e.test(l[u])&&(r.push(`${c}:${u+1}: ${l[u].trim()}`),e.lastIndex=0)}catch{}}}var is=require("child_process"),oe=C(require("fs")),Oe=C(require("path"));function Lm(t){let e=[],r=Oe.join(t,"tsconfig.json");if(!oe.existsSync(r))return e;try{(0,is.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 Dm(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>oe.existsSync(Oe.join(t,n))))return e;try{(0,is.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:Oe.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 Fm(t,e,r){let n;try{n=oe.readFileSync(t,"utf-8")}catch{return}let s=Oe.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 Nm(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=oe.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let c=Oe.join(s,l),u;try{u=oe.statSync(c)}catch{continue}u.isDirectory()?n(c,i+1):r.some(d=>l.endsWith(d))&&Fm(c,t,e)}}return n(t),e.slice(0,20)}function qm(t){let e=[];e.push(...Lm(t)),e.push(...Dm(t)),e.push(...Nm(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function Ea(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 Um(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=Oe.join(e,n.file);try{let o=oe.readFileSync(s,"utf-8").split(`
79
- `);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],oe.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 Aa(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=qm(r);if(n&&s.length>0){let o=Um(s,r).filter(l=>l.fixed).length;return{success:!0,output:`${Ea(s)}
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 ja(t,e,r,n){let s=await yr.readdir(t,{withFileTypes:!0});for(let i of s){if(Qm.has(i.name)||i.name.startsWith("."))continue;let o=je.join(t,i.name);if(i.isDirectory())await ja(o,e,r,n);else if(Zm.has(je.extname(i.name)))try{let l=(await yr.readFile(o,"utf-8")).split(`
74
+ `),c=je.relative(n,o);for(let u=0;u<l.length;u++)e.test(l[u])&&(r.push(`${c}:${u+1}: ${l[u].trim()}`),e.lastIndex=0)}catch{}}}var cs=require("child_process"),ce=C(require("fs")),Pe=C(require("path"));function eh(t){let e=[],r=Pe.join(t,"tsconfig.json");if(!ce.existsSync(r))return e;try{(0,cs.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 th(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>ce.existsSync(Pe.join(t,n))))return e;try{(0,cs.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:Pe.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 rh(t,e,r){let n;try{n=ce.readFileSync(t,"utf-8")}catch{return}let s=Pe.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 nh(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=ce.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let c=Pe.join(s,l),u;try{u=ce.statSync(c)}catch{continue}u.isDirectory()?n(c,i+1):r.some(d=>l.endsWith(d))&&rh(c,t,e)}}return n(t),e.slice(0,20)}function sh(t){let e=[];e.push(...eh(t)),e.push(...th(t)),e.push(...nh(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function Pa(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 ih(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=Pe.join(e,n.file);try{let o=ce.readFileSync(s,"utf-8").split(`
79
+ `);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],ce.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 La(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=sh(r);if(n&&s.length>0){let o=ih(s,r).filter(l=>l.fixed).length;return{success:!0,output:`${Pa(s)}
81
81
 
82
- Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:Ea(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Oa=2*1024*1024,Ia=15e3,Ra=32e3,Bm="HablasBot/2.0 (+https://hablas.dev)";function Hm(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,`
82
+ Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:Pa(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Da=2*1024*1024,Fa=15e3,Na=32e3,oh="HablasBot/2.0 (+https://hablas.dev)";function ah(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 Wm(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 Vm(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 Ma(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Ia);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":Bm,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<Oa;){let{done:u,value:d}=await i.read();if(u)break;o.push(d),a+=d.length}if(a>=Oa)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(u=>l.decode(u,{stream:!0})).join("")+l.decode(),finalUrl:n.url||t,status:n.status}}catch(n){clearTimeout(r);let s=n instanceof Error?n:new Error(String(n));throw s.name==="AbortError"?new Error(`Timeout after ${Ia/1e3}s`):s}}function ja(){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 Ma(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=Wm(r),o=Hm(r);return o.length>Ra&&(o=o.slice(0,Ra)+`
89
+ `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function lh(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 ch(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(),Fa);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":oh,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<Da;){let{done:u,value:d}=await i.read();if(u)break;o.push(d),a+=d.length}if(a>=Da)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(u=>l.decode(u,{stream:!0})).join("")+l.decode(),finalUrl:n.url||t,status:n.status}}catch(n){clearTimeout(r);let s=n instanceof Error?n:new Error(String(n));throw s.name==="AbortError"?new Error(`Timeout after ${Fa/1e3}s`):s}}function qa(){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=lh(r),o=ah(r);return o.length>Na&&(o=o.slice(0,Na)+`
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 Ma(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Vm(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 Ua(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=ch(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 zm=3600*1e3,it=new Map;function Km(t){let e=it.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>zm?(it.delete(t.toLowerCase().trim()),null):e.results:null}function Gm(t,e){if(it.size>200){let r=it.keys().next().value;r!==void 0&&it.delete(r)}it.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Jm(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 Ym(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(),u=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}c&&l&&!l.startsWith("/")&&i.push({title:c,url:l,snippet:u,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,c=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let u=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!c.has(u)&&!u.includes("duckduckgo.com")&&(c.add(u),i.push({title:d,url:u,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function os(t,e=5){let r=Km(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>Jm(t,e)},{name:"duckduckgo",fn:()=>Ym(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return Gm(t,i),i}catch{}return[]}function Pa(){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 os(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 xe=C(require("fs")),qa=C(require("path")),La=50*1024*1024,Da=4e4;function Fa(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=Ve(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=Ve(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=Ve(l[1]));let c=e.match(/\/Creator\s*\(([^)]*)\)/);c&&(r.creator=Ve(c[1]));let u=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=u.exec(e))!==null;){let p=d[1],f=Na(p);f.trim()&&n.push(f);try{let h=require("zlib"),g=Buffer.from(p,"latin1"),S=h.inflateSync(g).toString("latin1"),b=Na(S);b.trim()&&!n.includes(b)&&n.push(b)}catch{}}return{text:n.join(`
95
+ ${a}`}}catch(n){let s=n instanceof Error?n.message:String(n);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${s}`}}}}]}var uh=3600*1e3,ut=new Map;function fh(t){let e=ut.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>uh?(ut.delete(t.toLowerCase().trim()),null):e.results:null}function dh(t,e){if(ut.size>200){let r=ut.keys().next().value;r!==void 0&&ut.delete(r)}ut.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function ph(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 mh(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(),u=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}c&&l&&!l.startsWith("/")&&i.push({title:c,url:l,snippet:u,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,c=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let u=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!c.has(u)&&!u.includes("duckduckgo.com")&&(c.add(u),i.push({title:d,url:u,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function us(t,e=5){let r=fh(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>ph(t,e)},{name:"duckduckgo",fn:()=>mh(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return dh(t,i),i}catch{}return[]}function Ba(){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 us(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 ke=C(require("fs")),za=C(require("path")),Ha=50*1024*1024,Wa=4e4;function Va(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=Ye(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=Ye(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=Ye(l[1]));let c=e.match(/\/Creator\s*\(([^)]*)\)/);c&&(r.creator=Ye(c[1]));let u=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=u.exec(e))!==null;){let p=d[1],f=Ka(p);f.trim()&&n.push(f);try{let g=require("zlib"),h=Buffer.from(p,"latin1"),b=g.inflateSync(h).toString("latin1"),w=Ka(b);w.trim()&&!n.includes(w)&&n.push(w)}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 Na(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(Ve(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(u=>Ve(u.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(Ve(n[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
101
- `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function Ve(t){return t.replace(/\\n/g,`
102
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,r)=>String.fromCharCode(parseInt(r,8)))}function Ua(t){let e=r=>qa.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(!xe.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=xe.statSync(n);if(s.size>La)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${La/1024/1024}MB)`};try{let i=xe.readFileSync(n),{text:o,pages:a,metadata:l}=Fa(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
100
+ `).trim(),pages:s,metadata:r}}function Ka(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(Ye(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(u=>Ye(u.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(Ye(n[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
101
+ `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function Ye(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 Ga(t){let e=r=>za.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(!ke.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=ke.statSync(n);if(s.size>Ha)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${Ha/1024/1024}MB)`};try{let i=ke.readFileSync(n),{text:o,pages:a,metadata:l}=Va(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>Da&&(c=c.slice(0,Da)+`
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>Wa&&(c=c.slice(0,Wa)+`
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(!xe.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=xe.statSync(n),i=xe.readFileSync(n),{pages:o,metadata:a}=Fa(i);return{success:!0,output:[`File: ${r.path}`,`Size: ${(s.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${s.mtime.toISOString()}`].filter(Boolean).join(`
109
- `)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var Wa=require("child_process"),mr=C(require("fs")),Va=C(require("os")),za=C(require("path")),Ka=1e4,Ba=16e3;function ot(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 Ha={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>ot("tsx")?`tsx "${t}"`:ot("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=>ot("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>ot("python3")||ot("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>ot("bash")}};async function Xm(t,e,r=Ka){let n=Ha[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Ha).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=Va.tmpdir(),i=za.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{mr.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let c=(0,Wa.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),u="",d="";c.stdout?.on("data",m=>{u+=m}),c.stderr?.on("data",m=>{d+=m}),c.on("close",m=>{let p=Date.now()-a;l({success:m===0,stdout:u.slice(0,Ba),stderr:d.slice(0,Ba/2),exitCode:m??1,duration:p,language:e})}),c.on("error",m=>{let p=Date.now()-a;l({success:!1,stdout:"",stderr:m.message,exitCode:1,duration:p,language:e})})})}finally{try{mr.unlinkSync(i)}catch{}}}function Qm(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 Ga(){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()||Qm(e),n=Math.min(Math.max(1e3,t.timeout||Ka),3e4),s=await Xm(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(!ke.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=ke.statSync(n),i=ke.readFileSync(n),{pages:o,metadata:a}=Va(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 Xa=require("child_process"),wr=C(require("fs")),Qa=C(require("os")),Za=C(require("path")),el=1e4,Ja=16e3;function ft(t){try{let{execSync:e}=require("child_process");return e(`which ${t} 2>/dev/null || where ${t} 2>NUL`,{stdio:"ignore"}),!0}catch{return!1}}var Ya={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>ft("tsx")?`tsx "${t}"`:ft("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=>ft("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>ft("python3")||ft("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>ft("bash")}};async function hh(t,e,r=el){let n=Ya[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Ya).join(", ")}`,exitCode:1,duration:0,language:e};if(!n.available())return{success:!1,stdout:"",stderr:`Language "${e}" is not available on this system. Install the runtime first.`,exitCode:1,duration:0,language:e};let s=Qa.tmpdir(),i=Za.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{wr.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let c=(0,Xa.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),u="",d="";c.stdout?.on("data",m=>{u+=m}),c.stderr?.on("data",m=>{d+=m}),c.on("close",m=>{let p=Date.now()-a;l({success:m===0,stdout:u.slice(0,Ja),stderr:d.slice(0,Ja/2),exitCode:m??1,duration:p,language:e})}),c.on("error",m=>{let p=Date.now()-a;l({success:!1,stdout:"",stderr:m.message,exitCode:1,duration:p,language:e})})})}finally{try{wr.unlinkSync(i)}catch{}}}function gh(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 tl(){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()||gh(e),n=Math.min(Math.max(1e3,t.timeout||el),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 yr=C(require("fs")),pe=C(require("path"));var Zm=["images.unsplash.com","unsplash.com","images.pexels.com","pexels.com","cdn.pixabay.com","pixabay.com","upload.wikimedia.org","commons.wikimedia.org"],eh=["rose","roses","tulip","tulips","lily","lilies","bouquet","flower","flowers","floral","blossom","petals","garden"],th=["coffee","cup","fashion","dress","clothes","makeup","food","burger","shoes","bag","car","watch"],rh=new Set(["image","images","photo","photos","picture","pictures","free","download","correct","true","new","asset","assets","website","site","ecommerce","store","shop","high","quality","stock","beautiful","nice","wallpaper","background","thumbnail","card","product","products","closeup","close","hd","4k","8k","for","with","and","the","a","an"]);function Ja(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(Boolean)}function as(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 hr(t,e){let r=Ja(t),n=new Set,s=[];for(let o of r)rh.has(o)||n.has(o)||(n.add(o),s.push(o));e==="hero"&&!s.includes("flowers")&&!s.includes("flower")&&s.push("flowers");let i=s.slice(0,6);return i.length>0?i.join(" "):r.slice(0,5).join(" ")||t.trim()}function Et(t){try{let e=new URL(t).hostname.toLowerCase();return Zm.some(r=>e===r||e.endsWith("."+r))}catch{return!1}}function ls(t,e){let r=Ja(t.join(" ")),n=[...new Set(r.filter(o=>eh.includes(o)))],s=[...new Set(r.filter(o=>th.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 Ie(t,e,r,n){let s=Et(t),{score:i,positives:o,negatives:a}=ls([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),(/\/photos\//i.test(t)||/\/photo\//i.test(t))&&(l+=6),{score:l,positives:o,negatives:a,trusted:s}}function Ya(t,e){let n=hr(t,e).replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");return n?[{source:"unsplash-search",url:`https://unsplash.com/s/photos/${n}`},{source:"pexels-search",url:`https://www.pexels.com/search/${n}/`},{source:"pixabay-search",url:`https://pixabay.com/images/search/${n}/`}]:[]}function Xa(t,e){let r=hr(t,e),n=[`${r} site:unsplash.com/photos`,`${r} site:images.unsplash.com`,`${r} site:pexels.com/photo`,`${r} site:images.pexels.com`,`${r} site:pixabay.com/photos`,`${r} site:cdn.pixabay.com`,`${r} site:commons.wikimedia.org/wiki/File:`,`${r} site:upload.wikimedia.org`];return[...new Set(n.filter(s=>s.trim().length>0))]}function Qa(t,e){try{let r=new URL(t,e);return/^https?:$/i.test(r.protocol)?r.href:null}catch{return null}}function nh(t,e,r,n,s){let i;for(;(i=e.exec(t))!==null&&s.length<n;){let o=i[1]||i[2]||i[3]||"",a=Qa(o,r);a&&!s.includes(a)&&s.push(a)}}function gr(t,e){let r=[],n=[/<meta[^>]+property=["']og:image["'][^>]+content=["']([^"']+)["']/gi,/<meta[^>]+name=["']twitter:image["'][^>]+content=["']([^"']+)["']/gi,/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/gi,/<img[^>]+data-src=["']([^"']+)["']/gi,/<img[^>]+src=["']([^"']+)["']/gi,/<source[^>]+srcset=["']([^"']+)["']/gi,/<img[^>]+srcset=["']([^"']+)["']/gi];for(let s of n){let i;for(;(i=s.exec(t))!==null&&r.length<24;){let o=(i[1]||"").split(",")[0]?.trim().split(/\s+/)[0]||"",a=Qa(o,e);a&&!r.includes(a)&&r.push(a)}}return r.filter(s=>Et(s)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(s))}function Za(t,e){let r=[];return nh(t,/<a[^>]+href=["']([^"']+)["']/gi,e,80,r),r.filter(n=>{try{let s=new URL(n),i=s.hostname.toLowerCase(),o=s.pathname;return i==="unsplash.com"&&/^\/photos\/[^/?#]+/i.test(o)||i.endsWith(".unsplash.com")&&/^\/photos\/[^/?#]+/i.test(o)?!0:i==="www.pexels.com"||i==="pexels.com"?/^\/photo\/[^?#]+/i.test(o):i==="pixabay.com"?/^\/photos\/[^?#]+/i.test(o):i==="commons.wikimedia.org"?/^\/wiki\/File:/i.test(o):!1}catch{return!1}}).filter((n,s,i)=>i.indexOf(n)===s).slice(0,20)}var el=15*1024*1024,tl=15e3,sh=5;function ih(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 pe.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function rl(t){let e="";try{let r=new URL(t);e=`${r.protocol}//${r.host}/`}catch{e=""}return{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",Accept:"image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8,text/html,application/xhtml+xml;q=0.9","Accept-Language":"en-US,en;q=0.9",...e?{Referer:e}:{}}}async function oh(t){let e=await fetch(t,{signal:AbortSignal.timeout(tl),redirect:"follow",headers:rl(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))throw new Error("HTML page returned where a direct image was expected");let s=await e.arrayBuffer(),i=Buffer.from(s);if(i.length>el)throw new Error(`asset too large: ${Math.round(i.length/1024/1024)}MB`);return{bytes:i,contentType:r,finalUrl:n}}async function ah(t,e="generic",r=0){if(r>2)throw new Error("asset resolution exceeded maximum HTML indirection depth");let n=await fetch(t,{signal:AbortSignal.timeout(tl),redirect:"follow",headers:rl(t)});if(!n.ok)throw new Error(`HTTP ${n.status} while downloading asset`);let s=n.headers.get("content-type")||"",i=n.url||t;if(/text\/html|application\/xhtml\+xml/i.test(s)){let l=await n.text(),c=gr(l,i).map(d=>({url:d,...Ie(d,"","",e)})).sort((d,m)=>m.score-d.score).slice(0,sh);if(c.length===0)throw new Error("HTML page did not expose a direct image candidate");let u="no candidate attempt made";for(let d of c)try{return await oh(d.url)}catch(m){u=String(m?.message||m)}throw new Error(`all ranked HTML image candidates failed: ${u}`)}let o=await n.arrayBuffer(),a=Buffer.from(o);if(a.length>el)throw new Error(`asset too large: ${Math.round(a.length/1024/1024)}MB`);return{bytes:a,contentType:s,finalUrl:i}}function lh(t){let e=t.toLowerCase();return e.includes("hero")||e.includes("wallpaper")||e.includes("background")?"hero":e.includes("product")||e.includes("products")?"product":"generic"}function nl(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. For image pages, the tool now ranks multiple embedded image candidates and downloads the strongest working direct image instead of trusting the first HTML metadata hit blindly.",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 ah(r,lh(n)),a=pe.resolve(t,n),c=pe.extname(a)?a:a+ih(i,o);return yr.mkdirSync(pe.dirname(c),{recursive:!0}),yr.writeFileSync(c,s),{success:!0,output:`Downloaded asset: ${pe.relative(t,c)||pe.basename(c)}
111
+ `),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var vr=C(require("fs")),ge=C(require("path"));var yh=["images.unsplash.com","unsplash.com","images.pexels.com","pexels.com","cdn.pixabay.com","pixabay.com","upload.wikimedia.org","commons.wikimedia.org"],wh=["rose","roses","tulip","tulips","lily","lilies","bouquet","flower","flowers","floral","blossom","petals","garden"],bh=["coffee","cup","fashion","dress","clothes","makeup","food","burger","shoes","bag","car","watch"],xh=new Set(["image","images","photo","photos","picture","pictures","free","download","correct","true","new","asset","assets","website","site","ecommerce","store","shop","high","quality","stock","beautiful","nice","wallpaper","background","thumbnail","card","product","products","closeup","close","hd","4k","8k","for","with","and","the","a","an"]);function rl(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(Boolean)}function fs(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 br(t,e){let r=rl(t),n=new Set,s=[];for(let o of r)xh.has(o)||n.has(o)||(n.add(o),s.push(o));e==="hero"&&!s.includes("flowers")&&!s.includes("flower")&&s.push("flowers");let i=s.slice(0,6);return i.length>0?i.join(" "):r.slice(0,5).join(" ")||t.trim()}function It(t){try{let e=new URL(t).hostname.toLowerCase();return yh.some(r=>e===r||e.endsWith("."+r))}catch{return!1}}function ds(t,e){let r=rl(t.join(" ")),n=[...new Set(r.filter(o=>wh.includes(o)))],s=[...new Set(r.filter(o=>bh.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 Le(t,e,r,n){let s=It(t),{score:i,positives:o,negatives:a}=ds([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),(/\/photos\//i.test(t)||/\/photo\//i.test(t))&&(l+=6),{score:l,positives:o,negatives:a,trusted:s}}function nl(t,e){let n=br(t,e).replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");return n?[{source:"unsplash-search",url:`https://unsplash.com/s/photos/${n}`},{source:"pexels-search",url:`https://www.pexels.com/search/${n}/`},{source:"pixabay-search",url:`https://pixabay.com/images/search/${n}/`}]:[]}function sl(t,e){let r=br(t,e),n=[`${r} site:unsplash.com/photos`,`${r} site:images.unsplash.com`,`${r} site:pexels.com/photo`,`${r} site:images.pexels.com`,`${r} site:pixabay.com/photos`,`${r} site:cdn.pixabay.com`,`${r} site:commons.wikimedia.org/wiki/File:`,`${r} site:upload.wikimedia.org`];return[...new Set(n.filter(s=>s.trim().length>0))]}function il(t,e){try{let r=new URL(t,e);return/^https?:$/i.test(r.protocol)?r.href:null}catch{return null}}function vh(t,e,r,n,s){let i;for(;(i=e.exec(t))!==null&&s.length<n;){let o=i[1]||i[2]||i[3]||"",a=il(o,r);a&&!s.includes(a)&&s.push(a)}}function xr(t,e){let r=[],n=[/<meta[^>]+property=["']og:image["'][^>]+content=["']([^"']+)["']/gi,/<meta[^>]+name=["']twitter:image["'][^>]+content=["']([^"']+)["']/gi,/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/gi,/<img[^>]+data-src=["']([^"']+)["']/gi,/<img[^>]+src=["']([^"']+)["']/gi,/<source[^>]+srcset=["']([^"']+)["']/gi,/<img[^>]+srcset=["']([^"']+)["']/gi];for(let s of n){let i;for(;(i=s.exec(t))!==null&&r.length<24;){let o=(i[1]||"").split(",")[0]?.trim().split(/\s+/)[0]||"",a=il(o,e);a&&!r.includes(a)&&r.push(a)}}return r.filter(s=>It(s)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(s))}function ol(t,e){let r=[];return vh(t,/<a[^>]+href=["']([^"']+)["']/gi,e,80,r),r.filter(n=>{try{let s=new URL(n),i=s.hostname.toLowerCase(),o=s.pathname;return i==="unsplash.com"&&/^\/photos\/[^/?#]+/i.test(o)||i.endsWith(".unsplash.com")&&/^\/photos\/[^/?#]+/i.test(o)?!0:i==="www.pexels.com"||i==="pexels.com"?/^\/photo\/[^?#]+/i.test(o):i==="pixabay.com"?/^\/photos\/[^?#]+/i.test(o):i==="commons.wikimedia.org"?/^\/wiki\/File:/i.test(o):!1}catch{return!1}}).filter((n,s,i)=>i.indexOf(n)===s).slice(0,20)}var al=15*1024*1024,ll=15e3,Sh=5;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 ge.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function cl(t){let e="";try{let r=new URL(t);e=`${r.protocol}//${r.host}/`}catch{e=""}return{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",Accept:"image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8,text/html,application/xhtml+xml;q=0.9","Accept-Language":"en-US,en;q=0.9",...e?{Referer:e}:{}}}async function kh(t){let e=await fetch(t,{signal:AbortSignal.timeout(ll),redirect:"follow",headers:cl(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))throw new Error("HTML page returned where a direct image was expected");let s=await e.arrayBuffer(),i=Buffer.from(s);if(i.length>al)throw new Error(`asset too large: ${Math.round(i.length/1024/1024)}MB`);return{bytes:i,contentType:r,finalUrl:n}}async function $h(t,e="generic",r=0){if(r>2)throw new Error("asset resolution exceeded maximum HTML indirection depth");let n=await fetch(t,{signal:AbortSignal.timeout(ll),redirect:"follow",headers:cl(t)});if(!n.ok)throw new Error(`HTTP ${n.status} while downloading asset`);let s=n.headers.get("content-type")||"",i=n.url||t;if(/text\/html|application\/xhtml\+xml/i.test(s)){let l=await n.text(),c=xr(l,i).map(d=>({url:d,...Le(d,"","",e)})).sort((d,m)=>m.score-d.score).slice(0,Sh);if(c.length===0)throw new Error("HTML page did not expose a direct image candidate");let u="no candidate attempt made";for(let d of c)try{return await kh(d.url)}catch(m){u=String(m?.message||m)}throw new Error(`all ranked HTML image candidates failed: ${u}`)}let o=await n.arrayBuffer(),a=Buffer.from(o);if(a.length>al)throw new Error(`asset too large: ${Math.round(a.length/1024/1024)}MB`);return{bytes:a,contentType:s,finalUrl:i}}function Th(t){let e=t.toLowerCase();return e.includes("hero")||e.includes("wallpaper")||e.includes("background")?"hero":e.includes("product")||e.includes("products")?"product":"generic"}function ul(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. For image pages, the tool now ranks multiple embedded image candidates and downloads the strongest working direct image instead of trusting the first HTML metadata hit blindly.",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 $h(r,Th(n)),a=ge.resolve(t,n),c=ge.extname(a)?a:a+_h(i,o);return vr.mkdirSync(ge.dirname(c),{recursive:!0}),vr.writeFileSync(c,s),{success:!0,output:`Downloaded asset: ${ge.relative(t,c)||ge.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 wr=C(require("fs")),br=C(require("path"));var fs=15e3,ch=4;function sl(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function il(t,e){return t[e]|t[e+1]<<8}function uh(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 fh(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 cs(t,e){return t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?{width:sl(t,16),height:sl(t,20),ext:".png"}:t.length>=10&&t.toString("ascii",0,3)==="GIF"?{width:il(t,6),height:il(t,8),ext:".gif"}:t.length>=4&&t[0]===255&&t[1]===216?{...uh(t),ext:".jpg"}:t.length>=16&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?{...fh(t),ext:".webp"}:{ext:e.includes("svg")?".svg":".bin"}}function al(t){return{"User-Agent":"HablasBot/2.0 (+https://hablas.dev)",Accept:"image/*,text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",Referer:(()=>{try{let e=new URL(t);return`${e.protocol}//${e.host}/`}catch{return}})()}}async function ll(t){let e=await fetch(t,{signal:AbortSignal.timeout(fs),redirect:"follow",headers:al(t)});if(!e.ok)throw new Error(`HTTP ${e.status} while fetching image source`);let 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}}async function dh(t){let e=await fetch(t,{signal:AbortSignal.timeout(fs),redirect:"follow",headers:al(t)});if(!e.ok)throw new Error(`HTTP ${e.status}`);return{status:e.status,finalUrl:e.url||t,html:await e.text()}}async function ph(t,e){let r=new URLSearchParams({action:"query",generator:"search",gsrsearch:hr(t,"generic"),gsrnamespace:"6",gsrlimit:String(Math.min(Math.max(e,1),10)),prop:"imageinfo",iiprop:"url",iiurlwidth:"1600",format:"json",origin:"*"}),n=await fetch(`https://commons.wikimedia.org/w/api.php?${r.toString()}`,{signal:AbortSignal.timeout(fs),headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",Accept:"application/json","Accept-Language":"en-US,en;q=0.9"}});if(!n.ok)throw new Error(`Wikimedia HTTP ${n.status}`);let s=await n.json();return Object.values(s?.query?.pages||{}).map(o=>({title:String(o?.title||""),url:String(o?.imageinfo?.[0]?.url||o?.imageinfo?.[0]?.thumburl||""),snippet:String(o?.title||"").replace(/^File:/i,""),source:"wikimedia-api"})).filter(o=>o.url.startsWith("http")).slice(0,e)}function mh(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 hh(t){return`You are Hablas Vision, an internal image-inspection layer for a flower-store engineering agent.
114
+ Size: ${s.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${s?.message||String(s)}`}}}}}var Sr=C(require("fs")),_r=C(require("path"));var hs=15e3,Ch=4;function fl(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function dl(t,e){return t[e]|t[e+1]<<8}function Eh(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 ps(t,e){return t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?{width:fl(t,16),height:fl(t,20),ext:".png"}:t.length>=10&&t.toString("ascii",0,3)==="GIF"?{width:dl(t,6),height:dl(t,8),ext:".gif"}:t.length>=4&&t[0]===255&&t[1]===216?{...Eh(t),ext:".jpg"}:t.length>=16&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?{...Ah(t),ext:".webp"}:{ext:e.includes("svg")?".svg":".bin"}}function ml(t){return{"User-Agent":"HablasBot/2.0 (+https://hablas.dev)",Accept:"image/*,text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",Referer:(()=>{try{let e=new URL(t);return`${e.protocol}//${e.host}/`}catch{return}})()}}async function hl(t){let e=await fetch(t,{signal:AbortSignal.timeout(hs),redirect:"follow",headers:ml(t)});if(!e.ok)throw new Error(`HTTP ${e.status} while fetching image source`);let 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}}async function Oh(t){let e=await fetch(t,{signal:AbortSignal.timeout(hs),redirect:"follow",headers:ml(t)});if(!e.ok)throw new Error(`HTTP ${e.status}`);return{status:e.status,finalUrl:e.url||t,html:await e.text()}}async function Rh(t,e){let r=new URLSearchParams({action:"query",generator:"search",gsrsearch:br(t,"generic"),gsrnamespace:"6",gsrlimit:String(Math.min(Math.max(e,1),10)),prop:"imageinfo",iiprop:"url",iiurlwidth:"1600",format:"json",origin:"*"}),n=await fetch(`https://commons.wikimedia.org/w/api.php?${r.toString()}`,{signal:AbortSignal.timeout(hs),headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",Accept:"application/json","Accept-Language":"en-US,en;q=0.9"}});if(!n.ok)throw new Error(`Wikimedia HTTP ${n.status}`);let s=await n.json();return Object.values(s?.query?.pages||{}).map(o=>({title:String(o?.title||""),url:String(o?.imageinfo?.[0]?.url||o?.imageinfo?.[0]?.thumburl||""),snippet:String(o?.title||"").replace(/^File:/i,""),source:"wikimedia-api"})).filter(o=>o.url.startsWith("http")).slice(0,e)}function Ih(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 Mh(t){return`You are Hablas Vision, an internal image-inspection layer for a flower-store engineering agent.
115
115
  Return STRICT JSON only with these keys:
116
116
  {
117
117
  "sourceKind": "flower|bouquet|tulip|rose|lily|mixed|wallpaper|non-flower|unclear",
@@ -127,70 +127,72 @@ Rules:
127
127
  - Do not add commentary.
128
128
  - If the image is unrelated (coffee, clothes, food, lifestyle unrelated to flowers), set flowerRelevant=false and recommendedUse=reject.
129
129
  - For kind=${t}, judge whether the image fits that use.
130
- - Be strict, not generous.`}function gh(t,e){return[{role:"system",content:hh(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 yh(t,e){return`data:${e};base64,${t.toString("base64")}`}async function ol(t,e,r,n,s){let i=t.provider==="nvidia"?ne.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:gh(yh(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??"",u=mh(String(c));if(!u)throw new Error("Vision response was not valid JSON");return{model:e,success:!0,sourceKind:String(u.sourceKind||"unclear"),primarySubject:String(u.primarySubject||""),flowerRelevant:!!u.flowerRelevant,recommendedUse:String(u.recommendedUse||"generic"),confidence:Number(u.confidence||0),issues:Array.isArray(u.issues)?u.issues.map(String):[],summary:String(u.summary||""),raw:String(c)}}function wh(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 us(t,e,r){return!e||!r?0:t==="hero"&&e>=1200&&r>=600?12:t==="product"&&e>=500&&r>=500?8:t==="generic"&&e>=700&&r>=500?6:0}function bh(t){let{kind:e,trusted:r,directImage:n,score:s,mergedVision:i}=t;return i?.success?!i.flowerRelevant||i.recommendedUse==="reject"?"reject":i.confidence>=.8&&n&&r&&(i.recommendedUse===e||i.recommendedUse==="generic")?"accept":i.confidence>=.62&&n?"review":"reject":r&&n&&s>=32?"accept":s>=18?"review":"reject"}async function xh(t,e,r){let n=gr(e,t);if(n.length===0)throw new Error("HTML page did not expose a strong direct image candidate");let s=n.map(o=>({url:o,...Ie(o,"","",r)})).sort((o,a)=>a.score-o.score).slice(0,ch),i=null;for(let o of s)try{let a=await ll(o.url);if(!/^image\//i.test(a.contentType)&&!/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(a.finalUrl))continue;let l=cs(a.bytes,a.contentType),c=o.score+us(r,l.width,l.height),u={finalSource:a.finalUrl,contentType:a.contentType||"unknown",bytes:a.bytes,width:l.width,height:l.height,trusted:Et(a.finalUrl),positives:o.positives,negatives:o.negatives,score:c};(!i||u.score>i.score)&&(i=u)}catch{}if(!i)throw new Error("No downloadable direct image candidate survived HTML resolution");return{...i,extractedDirectCandidates:n}}function cl(t,e){return[{name:"search_image_candidates",description:"Search and rank trusted image page candidates for a target use such as hero wallpaper, product photo, or flower imagery. Uses source-specific trusted search pages first, then site-filtered web fallback, to reduce unrelated results and brittle generic search behavior.",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=as(r.kind),i=Math.min(Math.max(1,Number(r.max_results||5)),10),o=new Map,a=[];for(let u of Ya(n,s))try{let d=await dh(u.url),m=Za(d.html,d.finalUrl);if(m.length===0){a.push(`${u.source}: no trusted image page links extracted`);continue}for(let p of m.slice(0,i*2)){if(o.has(p))continue;let f=Ie(p,u.source,n,s);o.set(p,{title:`${u.source} candidate`,url:p,snippet:`Discovered from ${u.source}`,source:u.source,score:f.score,positives:f.positives,negatives:f.negatives,trusted:f.trusted})}}catch(d){a.push(`${u.source}: ${String(d?.message||d)}`)}if(o.size<i*2)try{let u=await ph(n,Math.max(4,i));for(let d of u){if(o.has(d.url))continue;let m=Ie(d.url,d.title,d.snippet,s);o.set(d.url,{title:d.title,url:d.url,snippet:d.snippet||"Wikimedia Commons image result",source:d.source,score:m.score,positives:m.positives,negatives:m.negatives,trusted:m.trusted})}}catch(u){a.push(`wikimedia-api: ${String(u?.message||u)}`)}if(o.size<i)for(let u of Xa(n,s)){let d=await os(u,Math.max(8,i));for(let m of d){if(o.has(m.url))continue;let p=Ie(m.url,m.title,m.snippet,s);o.set(m.url,{title:m.title||`${m.source} candidate`,url:m.url,snippet:m.snippet||`Fallback web result from ${m.source}`,source:m.source,score:p.score,positives:p.positives,negatives:p.negatives,trusted:p.trusted})}if(o.size>=i*2)break}let l=[...o.values()].sort((u,d)=>d.score-u.score).slice(0,i);if(l.length===0){let u=a.length>0?`
130
+ - Be strict, not generous.`}function jh(t,e){return[{role:"system",content:Mh(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 Ph(t,e){return`data:${e};base64,${t.toString("base64")}`}async function pl(t,e,r,n,s){let i=t.provider==="nvidia"?oe.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:jh(Ph(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??"",u=Ih(String(c));if(!u)throw new Error("Vision response was not valid JSON");return{model:e,success:!0,sourceKind:String(u.sourceKind||"unclear"),primarySubject:String(u.primarySubject||""),flowerRelevant:!!u.flowerRelevant,recommendedUse:String(u.recommendedUse||"generic"),confidence:Number(u.confidence||0),issues:Array.isArray(u.issues)?u.issues.map(String):[],summary:String(u.summary||""),raw:String(c)}}function Lh(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 ms(t,e,r){return!e||!r?0:t==="hero"&&e>=1200&&r>=600?12:t==="product"&&e>=500&&r>=500?8:t==="generic"&&e>=700&&r>=500?6:0}function Dh(t){let{kind:e,trusted:r,directImage:n,score:s,mergedVision:i}=t;return i?.success?!i.flowerRelevant||i.recommendedUse==="reject"?"reject":i.confidence>=.8&&n&&r&&(i.recommendedUse===e||i.recommendedUse==="generic")?"accept":i.confidence>=.62&&n?"review":"reject":r&&n&&s>=32?"accept":s>=18?"review":"reject"}async function Fh(t,e,r){let n=xr(e,t);if(n.length===0)throw new Error("HTML page did not expose a strong direct image candidate");let s=n.map(o=>({url:o,...Le(o,"","",r)})).sort((o,a)=>a.score-o.score).slice(0,Ch),i=null;for(let o of s)try{let a=await hl(o.url);if(!/^image\//i.test(a.contentType)&&!/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(a.finalUrl))continue;let l=ps(a.bytes,a.contentType),c=o.score+ms(r,l.width,l.height),u={finalSource:a.finalUrl,contentType:a.contentType||"unknown",bytes:a.bytes,width:l.width,height:l.height,trusted:It(a.finalUrl),positives:o.positives,negatives:o.negatives,score:c};(!i||u.score>i.score)&&(i=u)}catch{}if(!i)throw new Error("No downloadable direct image candidate survived HTML resolution");return{...i,extractedDirectCandidates:n}}function gl(t,e){return[{name:"search_image_candidates",description:"Search and rank trusted image page candidates for a target use such as hero wallpaper, product photo, or flower imagery. Uses source-specific trusted search pages first, then site-filtered web fallback, to reduce unrelated results and brittle generic search behavior.",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=fs(r.kind),i=Math.min(Math.max(1,Number(r.max_results||5)),10),o=new Map,a=[];for(let u of nl(n,s))try{let d=await Oh(u.url),m=ol(d.html,d.finalUrl);if(m.length===0){a.push(`${u.source}: no trusted image page links extracted`);continue}for(let p of m.slice(0,i*2)){if(o.has(p))continue;let f=Le(p,u.source,n,s);o.set(p,{title:`${u.source} candidate`,url:p,snippet:`Discovered from ${u.source}`,source:u.source,score:f.score,positives:f.positives,negatives:f.negatives,trusted:f.trusted})}}catch(d){a.push(`${u.source}: ${String(d?.message||d)}`)}if(o.size<i*2)try{let u=await Rh(n,Math.max(4,i));for(let d of u){if(o.has(d.url))continue;let m=Le(d.url,d.title,d.snippet,s);o.set(d.url,{title:d.title,url:d.url,snippet:d.snippet||"Wikimedia Commons image result",source:d.source,score:m.score,positives:m.positives,negatives:m.negatives,trusted:m.trusted})}}catch(u){a.push(`wikimedia-api: ${String(u?.message||u)}`)}if(o.size<i)for(let u of sl(n,s)){let d=await us(u,Math.max(8,i));for(let m of d){if(o.has(m.url))continue;let p=Le(m.url,m.title,m.snippet,s);o.set(m.url,{title:m.title||`${m.source} candidate`,url:m.url,snippet:m.snippet||`Fallback web result from ${m.source}`,source:m.source,score:p.score,positives:p.positives,negatives:p.negatives,trusted:p.trusted})}if(o.size>=i*2)break}let l=[...o.values()].sort((u,d)=>d.score-u.score).slice(0,i);if(l.length===0){let u=a.length>0?`
131
131
  Sources tried:
132
132
  - ${a.join(`
133
133
  - `)}`:"";return{success:!0,output:`No image candidates found for: "${n}"${u}`}}let c=[`Ranked image candidates for: "${n}" (${s})`,""];return l.forEach((u,d)=>{c.push(`[${d+1}] score=${u.score} trusted=${u.trusted?"yes":"no"} source=${u.source}`),c.push(` ${u.title}`),c.push(` ${u.url}`),u.positives.length&&c.push(` positive: ${u.positives.join(", ")}`),u.negatives.length&&c.push(` negative: ${u.negatives.join(", ")}`),u.snippet&&c.push(` snippet: ${u.snippet}`),c.push("")}),a.length>0&&(c.push("Source notes:"),a.slice(0,6).forEach(u=>c.push(`- ${u}`))),{success:!0,output:c.join(`
134
- `)}}},{name:"inspect_image",description:"Inspect a remote or local image candidate before adoption. Returns metadata, direct-image resolution, trusted-source signals, a semantic verdict from internal vision when available, and an explicit adoption verdict.",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=as(r.kind),i=String(r.use_vision??"true").toLowerCase()!=="false",o="unknown",a,l,c=!1,u=!1,d=[],m=[],p=0,f="",h=[],g=n,S=null,b=null,x=null,v=null;try{if(/^https?:\/\//i.test(n)){let T=await ll(n);g=T.finalUrl,o=T.contentType||"unknown",c=/^image\//i.test(o)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(g),u=Et(g);let A=Ie(g,"","",s);if(d=A.positives,m=A.negatives,p=A.score,T.html){let k=await xh(g,T.html,s);g=k.finalSource,o=k.contentType,S=k.bytes,a=k.width,l=k.height,c=!0,u=k.trusted,d=k.positives,m=k.negatives,p=k.score,h=k.extractedDirectCandidates,f="Resolved best direct image candidate from HTML page."}else{S=T.bytes;let k=cs(S,o);a=k.width,l=k.height,p+=us(s,a,l),f=c?"Direct image candidate inspected.":"Not a strong direct image candidate."}}else{let T=br.resolve(t,n);if(!wr.existsSync(T))return{success:!1,output:"",error:`local file not found: ${n}`};S=wr.readFileSync(T).subarray(0,e.vision.maxImageBytes);let A=br.extname(T).toLowerCase();o=A===".png"?"image/png":A===".jpg"||A===".jpeg"?"image/jpeg":A===".webp"?"image/webp":A===".gif"?"image/gif":A===".svg"?"image/svg+xml":"application/octet-stream",c=!0,g=n;let k=cs(S,o);a=k.width,l=k.height;let M=ls([n],s);d=M.positives,m=M.negatives,p=M.score+10+us(s,a,l),f="Local asset inspection complete."}if(i&&e.vision.enabled&&S&&/^image\//i.test(o)){try{b=await ol(e,e.vision.primaryModel,S.subarray(0,e.vision.maxImageBytes),o,s)}catch(T){b={model:e.vision.primaryModel,success:!1,sourceKind:"unclear",primarySubject:"",flowerRelevant:!1,recommendedUse:"reject",confidence:0,issues:[String(T?.message||T)],summary:"Primary vision model failed."}}if(!b.success||b.confidence<.6||!b.flowerRelevant)try{x=await ol(e,e.vision.fallbackModel,S.subarray(0,e.vision.maxImageBytes),o,s)}catch(T){x={model:e.vision.fallbackModel,success:!1,sourceKind:"unclear",primarySubject:"",flowerRelevant:!1,recommendedUse:"reject",confidence:0,issues:[String(T?.message||T)],summary:"Fallback vision model failed."}}b?.success&&(v=wh(b,x&&x.success?x:void 0),v.flowerRelevant||(p-=40),v.recommendedUse==="reject"&&(p-=25),v.recommendedUse===s&&(p+=18),f=v.summary||f)}let E=bh({kind:s,trusted:u,directImage:c,score:p,mergedVision:v}),_=[`Source: ${n}`,`Resolved asset URL: ${g}`,`Kind: ${s}`,`Content-Type: ${o}`,`Direct image: ${c?"yes":"no"}`,`Trusted source: ${u?"yes":"no"}`,a&&l?`Dimensions: ${a}x${l}`:"Dimensions: unknown",`Suitability score: ${p}`,`Adoption verdict: ${E}`,d.length?`Positive signals: ${d.join(", ")}`:"Positive signals: none",m.length?`Negative signals: ${m.join(", ")}`:"Negative signals: none",`Recommendation: ${f||"No recommendation"}`];return h.length&&(_.push("Extracted direct candidates:"),h.slice(0,5).forEach((T,A)=>_.push(` ${A+1}. ${T}`))),b&&(_.push("Vision primary:"),_.push(` model: ${b.model}`),_.push(` success: ${b.success?"yes":"no"}`),_.push(` subject: ${b.primarySubject||"unknown"}`),_.push(` flowerRelevant: ${b.flowerRelevant}`),_.push(` recommendedUse: ${b.recommendedUse}`),_.push(` confidence: ${b.confidence}`),b.issues.length&&_.push(` issues: ${b.issues.join(", ")}`)),x&&(_.push("Vision fallback:"),_.push(` model: ${x.model}`),_.push(` success: ${x.success?"yes":"no"}`),_.push(` subject: ${x.primarySubject||"unknown"}`),_.push(` flowerRelevant: ${x.flowerRelevant}`),_.push(` recommendedUse: ${x.recommendedUse}`),_.push(` confidence: ${x.confidence}`),x.issues.length&&_.push(` issues: ${x.issues.join(", ")}`)),v&&(_.push("Merged vision verdict:"),_.push(` subject: ${v.primarySubject||"unknown"}`),_.push(` flowerRelevant: ${v.flowerRelevant}`),_.push(` recommendedUse: ${v.recommendedUse}`),_.push(` confidence: ${v.confidence}`),_.push(` summary: ${v.summary}`)),{success:!0,output:_.join(`
135
- `)}}catch(E){return{success:!1,output:"",error:`image inspection failed: ${E?.message||String(E)}`}}}}]}var Q=C(require("fs")),ms=C(require("path")),pl=C(require("os")),ml=C(require("crypto")),At=ms.join(pl.homedir(),".hablas"),ds=ms.join(At,"memory.json"),ul=1,fl=2e3,Sh=1600,vh=8e3;function _h(){return ml.randomBytes(8).toString("hex")}function dl(t){return t==="critical"?4:t==="high"?3:t==="normal"?2:1}function kh(t,e){let r=t+".tmp."+process.pid;Q.writeFileSync(r,e,"utf-8"),Q.renameSync(r,t)}var ps=class{store;dirty=!1;flushTimer=null;constructor(){this.store=this.load()}load(){try{if(Q.existsSync(At)||Q.mkdirSync(At,{recursive:!0}),Q.existsSync(ds)){let e=JSON.parse(Q.readFileSync(ds,"utf-8"));if(e.version===ul)return e}}catch{}return{version:ul,entries:{},keyIndex:{},tagIndex:{},projectIndex:{}}}scheduleFlush(){this.dirty=!0,!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flush(),this.flushTimer=null},500))}flush(){if(this.dirty)try{Q.existsSync(At)||Q.mkdirSync(At,{recursive:!0}),kh(ds,JSON.stringify(this.store,null,2)),this.dirty=!1}catch{}}addToIndex(e){this.store.keyIndex[e.key]=e.id;for(let r of e.tags)this.store.tagIndex[r]||(this.store.tagIndex[r]=[]),this.store.tagIndex[r].includes(e.id)||this.store.tagIndex[r].push(e.id);e.project&&(this.store.projectIndex[e.project]||(this.store.projectIndex[e.project]=[]),this.store.projectIndex[e.project].includes(e.id)||this.store.projectIndex[e.project].push(e.id))}removeFromIndex(e){delete this.store.keyIndex[e.key];for(let r of e.tags)this.store.tagIndex[r]&&(this.store.tagIndex[r]=this.store.tagIndex[r].filter(n=>n!==e.id),this.store.tagIndex[r].length||delete this.store.tagIndex[r]);e.project&&this.store.projectIndex[e.project]&&(this.store.projectIndex[e.project]=this.store.projectIndex[e.project].filter(r=>r!==e.id),this.store.projectIndex[e.project].length||delete this.store.projectIndex[e.project])}remember(e){let r=this.store.keyIndex[e.key],n=Date.now(),s=e.value.slice(0,vh);if(r&&this.store.entries[r]){let a=this.store.entries[r];return this.removeFromIndex(a),a.value=s,a.updatedAt=n,e.tags&&(a.tags=e.tags),e.priority&&(a.priority=e.priority),e.ttl!==void 0&&(a.ttl=n+e.ttl),this.addToIndex(a),this.scheduleFlush(),a.id}this.maybeEvict();let i=_h(),o={id:i,kind:e.kind,key:e.key,value:s,tags:e.tags??[],project:e.project,priority:e.priority??"normal",createdAt:n,updatedAt:n,accessCount:0,lastAccessed:n,ttl:e.ttl?n+e.ttl:void 0};return this.store.entries[i]=o,this.addToIndex(o),this.scheduleFlush(),i}recall(e){let r=this.store.keyIndex[e];if(!r)return null;let n=this.store.entries[r];return n?n.ttl&&Date.now()>n.ttl?(this.forget(e),null):(n.accessCount++,n.lastAccessed=Date.now(),this.scheduleFlush(),n):null}forget(e){let r=this.store.keyIndex[e];if(!r)return!1;let n=this.store.entries[r];return n?(this.removeFromIndex(n),delete this.store.entries[r],this.scheduleFlush(),!0):!1}search(e,r){let n=Date.now(),s=r?.limit??10,i=r?.minScore??.1,o=e.toLowerCase(),a=o.split(/\s+/).filter(c=>c.length>2),l=[];for(let c of Object.values(this.store.entries)){if(c.ttl&&n>c.ttl||r?.kind&&c.kind!==r.kind||r?.project&&c.project!==r.project)continue;let u=0,d="value",m=c.key.toLowerCase(),p=c.value.toLowerCase();if(m===o)u=1,d="key";else if(m.includes(o))u=Math.max(u,.8),d="key";else if(c.tags.some(f=>f.toLowerCase().includes(o)))u=Math.max(u,.7),d="tag";else{let f=a.filter(h=>p.includes(h)).length;f>0&&(u=Math.max(u,f/Math.max(a.length,1)*.6),d="value")}u>0&&(u=Math.min(1,u+dl(c.priority)*.05+Math.min(.1,c.accessCount*.01)),l.push({entry:c,score:u,matchedOn:d}))}return l.filter(c=>c.score>=i).sort((c,u)=>u.score-c.score).slice(0,s)}getProjectMemory(e){return(this.store.projectIndex[e]??[]).map(r=>this.store.entries[r]).filter(r=>!!r&&(!r.ttl||Date.now()<r.ttl))}getByKind(e,r=20){return Object.values(this.store.entries).filter(n=>n.kind===e&&(!n.ttl||Date.now()<n.ttl)).sort((n,s)=>s.updatedAt-n.updatedAt).slice(0,r)}getRecent(e=10){return Object.values(this.store.entries).filter(r=>!r.ttl||Date.now()<r.ttl).sort((r,n)=>n.lastAccessed-r.lastAccessed).slice(0,e)}getStats(){let e={total:0};for(let r of Object.values(this.store.entries))e.total++,e[r.kind]=(e[r.kind]??0)+1;return e}maybeEvict(){let e=Object.keys(this.store.entries).length;if(e<fl)return;let r=Date.now();for(let n of Object.values(this.store.entries))n.ttl&&r>n.ttl&&(this.removeFromIndex(n),delete this.store.entries[n.id],e--);if(e>=fl){let n=Object.values(this.store.entries).map(s=>({id:s.id,score:dl(s.priority)*10+s.accessCount+s.lastAccessed/1e12})).sort((s,i)=>s.score-i.score);for(let{id:s}of n.slice(0,e-Sh)){let i=this.store.entries[s];i&&(this.removeFromIndex(i),delete this.store.entries[s])}}}rememberProject(e,r){this.remember({kind:"project",key:`project:${e}`,priority:"high",value:`Name: ${r.name}
134
+ `)}}},{name:"inspect_image",description:"Inspect a remote or local image candidate before adoption. Returns metadata, direct-image resolution, trusted-source signals, a semantic verdict from internal vision when available, and an explicit adoption verdict.",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=fs(r.kind),i=String(r.use_vision??"true").toLowerCase()!=="false",o="unknown",a,l,c=!1,u=!1,d=[],m=[],p=0,f="",g=[],h=n,b=null,w=null,x=null,S=null;try{if(/^https?:\/\//i.test(n)){let T=await hl(n);h=T.finalUrl,o=T.contentType||"unknown",c=/^image\//i.test(o)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(h),u=It(h);let A=Le(h,"","",s);if(d=A.positives,m=A.negatives,p=A.score,T.html){let k=await Fh(h,T.html,s);h=k.finalSource,o=k.contentType,b=k.bytes,a=k.width,l=k.height,c=!0,u=k.trusted,d=k.positives,m=k.negatives,p=k.score,g=k.extractedDirectCandidates,f="Resolved best direct image candidate from HTML page."}else{b=T.bytes;let k=ps(b,o);a=k.width,l=k.height,p+=ms(s,a,l),f=c?"Direct image candidate inspected.":"Not a strong direct image candidate."}}else{let T=_r.resolve(t,n);if(!Sr.existsSync(T))return{success:!1,output:"",error:`local file not found: ${n}`};b=Sr.readFileSync(T).subarray(0,e.vision.maxImageBytes);let A=_r.extname(T).toLowerCase();o=A===".png"?"image/png":A===".jpg"||A===".jpeg"?"image/jpeg":A===".webp"?"image/webp":A===".gif"?"image/gif":A===".svg"?"image/svg+xml":"application/octet-stream",c=!0,h=n;let k=ps(b,o);a=k.width,l=k.height;let M=ds([n],s);d=M.positives,m=M.negatives,p=M.score+10+ms(s,a,l),f="Local asset inspection complete."}if(i&&e.vision.enabled&&b&&/^image\//i.test(o)){try{w=await pl(e,e.vision.primaryModel,b.subarray(0,e.vision.maxImageBytes),o,s)}catch(T){w={model:e.vision.primaryModel,success:!1,sourceKind:"unclear",primarySubject:"",flowerRelevant:!1,recommendedUse:"reject",confidence:0,issues:[String(T?.message||T)],summary:"Primary vision model failed."}}if(!w.success||w.confidence<.6||!w.flowerRelevant)try{x=await pl(e,e.vision.fallbackModel,b.subarray(0,e.vision.maxImageBytes),o,s)}catch(T){x={model:e.vision.fallbackModel,success:!1,sourceKind:"unclear",primarySubject:"",flowerRelevant:!1,recommendedUse:"reject",confidence:0,issues:[String(T?.message||T)],summary:"Fallback vision model failed."}}w?.success&&(S=Lh(w,x&&x.success?x:void 0),S.flowerRelevant||(p-=40),S.recommendedUse==="reject"&&(p-=25),S.recommendedUse===s&&(p+=18),f=S.summary||f)}let E=Dh({kind:s,trusted:u,directImage:c,score:p,mergedVision:S}),_=[`Source: ${n}`,`Resolved asset URL: ${h}`,`Kind: ${s}`,`Content-Type: ${o}`,`Direct image: ${c?"yes":"no"}`,`Trusted source: ${u?"yes":"no"}`,a&&l?`Dimensions: ${a}x${l}`:"Dimensions: unknown",`Suitability score: ${p}`,`Adoption verdict: ${E}`,d.length?`Positive signals: ${d.join(", ")}`:"Positive signals: none",m.length?`Negative signals: ${m.join(", ")}`:"Negative signals: none",`Recommendation: ${f||"No recommendation"}`];return g.length&&(_.push("Extracted direct candidates:"),g.slice(0,5).forEach((T,A)=>_.push(` ${A+1}. ${T}`))),w&&(_.push("Vision primary:"),_.push(` model: ${w.model}`),_.push(` success: ${w.success?"yes":"no"}`),_.push(` subject: ${w.primarySubject||"unknown"}`),_.push(` flowerRelevant: ${w.flowerRelevant}`),_.push(` recommendedUse: ${w.recommendedUse}`),_.push(` confidence: ${w.confidence}`),w.issues.length&&_.push(` issues: ${w.issues.join(", ")}`)),x&&(_.push("Vision fallback:"),_.push(` model: ${x.model}`),_.push(` success: ${x.success?"yes":"no"}`),_.push(` subject: ${x.primarySubject||"unknown"}`),_.push(` flowerRelevant: ${x.flowerRelevant}`),_.push(` recommendedUse: ${x.recommendedUse}`),_.push(` confidence: ${x.confidence}`),x.issues.length&&_.push(` issues: ${x.issues.join(", ")}`)),S&&(_.push("Merged vision verdict:"),_.push(` subject: ${S.primarySubject||"unknown"}`),_.push(` flowerRelevant: ${S.flowerRelevant}`),_.push(` recommendedUse: ${S.recommendedUse}`),_.push(` confidence: ${S.confidence}`),_.push(` summary: ${S.summary}`)),{success:!0,output:_.join(`
135
+ `)}}catch(E){return{success:!1,output:"",error:`image inspection failed: ${E?.message||String(E)}`}}}}]}var te=C(require("fs")),ws=C(require("path")),xl=C(require("os")),vl=C(require("crypto")),Mt=ws.join(xl.homedir(),".hablas"),gs=ws.join(Mt,"memory.json"),yl=1,wl=2e3,Nh=1600,Uh=8e3;function qh(){return vl.randomBytes(8).toString("hex")}function bl(t){return t==="critical"?4:t==="high"?3:t==="normal"?2:1}function Bh(t,e){let r=t+".tmp."+process.pid;te.writeFileSync(r,e,"utf-8"),te.renameSync(r,t)}var ys=class{store;dirty=!1;flushTimer=null;constructor(){this.store=this.load()}load(){try{if(te.existsSync(Mt)||te.mkdirSync(Mt,{recursive:!0}),te.existsSync(gs)){let e=JSON.parse(te.readFileSync(gs,"utf-8"));if(e.version===yl)return e}}catch{}return{version:yl,entries:{},keyIndex:{},tagIndex:{},projectIndex:{}}}scheduleFlush(){this.dirty=!0,!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flush(),this.flushTimer=null},500))}flush(){if(this.dirty)try{te.existsSync(Mt)||te.mkdirSync(Mt,{recursive:!0}),Bh(gs,JSON.stringify(this.store,null,2)),this.dirty=!1}catch{}}addToIndex(e){this.store.keyIndex[e.key]=e.id;for(let r of e.tags)this.store.tagIndex[r]||(this.store.tagIndex[r]=[]),this.store.tagIndex[r].includes(e.id)||this.store.tagIndex[r].push(e.id);e.project&&(this.store.projectIndex[e.project]||(this.store.projectIndex[e.project]=[]),this.store.projectIndex[e.project].includes(e.id)||this.store.projectIndex[e.project].push(e.id))}removeFromIndex(e){delete this.store.keyIndex[e.key];for(let r of e.tags)this.store.tagIndex[r]&&(this.store.tagIndex[r]=this.store.tagIndex[r].filter(n=>n!==e.id),this.store.tagIndex[r].length||delete this.store.tagIndex[r]);e.project&&this.store.projectIndex[e.project]&&(this.store.projectIndex[e.project]=this.store.projectIndex[e.project].filter(r=>r!==e.id),this.store.projectIndex[e.project].length||delete this.store.projectIndex[e.project])}remember(e){let r=this.store.keyIndex[e.key],n=Date.now(),s=e.value.slice(0,Uh);if(r&&this.store.entries[r]){let a=this.store.entries[r];return this.removeFromIndex(a),a.value=s,a.updatedAt=n,e.tags&&(a.tags=e.tags),e.priority&&(a.priority=e.priority),e.ttl!==void 0&&(a.ttl=n+e.ttl),this.addToIndex(a),this.scheduleFlush(),a.id}this.maybeEvict();let i=qh(),o={id:i,kind:e.kind,key:e.key,value:s,tags:e.tags??[],project:e.project,priority:e.priority??"normal",createdAt:n,updatedAt:n,accessCount:0,lastAccessed:n,ttl:e.ttl?n+e.ttl:void 0};return this.store.entries[i]=o,this.addToIndex(o),this.scheduleFlush(),i}recall(e){let r=this.store.keyIndex[e];if(!r)return null;let n=this.store.entries[r];return n?n.ttl&&Date.now()>n.ttl?(this.forget(e),null):(n.accessCount++,n.lastAccessed=Date.now(),this.scheduleFlush(),n):null}forget(e){let r=this.store.keyIndex[e];if(!r)return!1;let n=this.store.entries[r];return n?(this.removeFromIndex(n),delete this.store.entries[r],this.scheduleFlush(),!0):!1}search(e,r){let n=Date.now(),s=r?.limit??10,i=r?.minScore??.1,o=e.toLowerCase(),a=o.split(/\s+/).filter(c=>c.length>2),l=[];for(let c of Object.values(this.store.entries)){if(c.ttl&&n>c.ttl||r?.kind&&c.kind!==r.kind||r?.project&&c.project!==r.project)continue;let u=0,d="value",m=c.key.toLowerCase(),p=c.value.toLowerCase();if(m===o)u=1,d="key";else if(m.includes(o))u=Math.max(u,.8),d="key";else if(c.tags.some(f=>f.toLowerCase().includes(o)))u=Math.max(u,.7),d="tag";else{let f=a.filter(g=>p.includes(g)).length;f>0&&(u=Math.max(u,f/Math.max(a.length,1)*.6),d="value")}u>0&&(u=Math.min(1,u+bl(c.priority)*.05+Math.min(.1,c.accessCount*.01)),l.push({entry:c,score:u,matchedOn:d}))}return l.filter(c=>c.score>=i).sort((c,u)=>u.score-c.score).slice(0,s)}getProjectMemory(e){return(this.store.projectIndex[e]??[]).map(r=>this.store.entries[r]).filter(r=>!!r&&(!r.ttl||Date.now()<r.ttl))}getByKind(e,r=20){return Object.values(this.store.entries).filter(n=>n.kind===e&&(!n.ttl||Date.now()<n.ttl)).sort((n,s)=>s.updatedAt-n.updatedAt).slice(0,r)}getRecent(e=10){return Object.values(this.store.entries).filter(r=>!r.ttl||Date.now()<r.ttl).sort((r,n)=>n.lastAccessed-r.lastAccessed).slice(0,e)}getStats(){let e={total:0};for(let r of Object.values(this.store.entries))e.total++,e[r.kind]=(e[r.kind]??0)+1;return e}maybeEvict(){let e=Object.keys(this.store.entries).length;if(e<wl)return;let r=Date.now();for(let n of Object.values(this.store.entries))n.ttl&&r>n.ttl&&(this.removeFromIndex(n),delete this.store.entries[n.id],e--);if(e>=wl){let n=Object.values(this.store.entries).map(s=>({id:s.id,score:bl(s.priority)*10+s.accessCount+s.lastAccessed/1e12})).sort((s,i)=>s.score-i.score);for(let{id:s}of n.slice(0,e-Nh)){let i=this.store.entries[s];i&&(this.removeFromIndex(i),delete this.store.entries[s])}}}rememberProject(e,r){this.remember({kind:"project",key:`project:${e}`,priority:"high",value:`Name: ${r.name}
136
136
  Stack: ${r.stack}${r.summary?`
137
137
  Summary: ${r.summary}`:""}`,tags:["project",r.stack.toLowerCase().slice(0,20)],project:e})}rememberDecision(e,r,n){this.remember({kind:"decision",key:`decision:${e}:${r.slice(0,60)}`,value:`Decision: ${r}
138
138
  Rationale: ${n}`,tags:["decision","architecture"],project:e,priority:"high"})}rememberPreference(e,r){this.remember({kind:"preference",key:`pref:${e}`,value:r,tags:["preference","user"],priority:"high"})}rememberTaskSummary(e,r,n){this.remember({kind:"task_summary",key:`task:${e}:${r.slice(0,60)}:${Date.now()}`,value:`Task: ${r}
139
139
  Outcome: ${n}`,tags:["task","completed"],project:e,priority:"normal",ttl:720*60*60*1e3})}buildContextBlock(e,r=3e3){let n=[];if(e){let i=this.getProjectMemory(e);if(i.length>0){n.push("## Memory: this project");for(let o of i.slice(0,8))n.push(`[${o.kind}] ${o.value.replace(/\n/g," \u2014 ").slice(0,200)}`)}}let s=this.getByKind("preference",5);if(s.length>0){n.push("## Memory: user preferences");for(let i of s)n.push(`- ${i.key.replace("pref:","")}: ${i.value.slice(0,100)}`)}return n.join(`
140
- `).slice(0,r)}},xr=null;function W(){return xr||(xr=new ps),xr}function hl(){xr?.flush()}var Sr=["project","preference","decision","pattern","tool_outcome","fact","task_summary"];function gl(){return[{name:"remember",description:"Store a fact, decision, preference, or pattern in persistent memory that survives across sessions. Use this to remember important project decisions, user preferences, or recurring patterns you want to recall later.",safety:"safe",parameters:{key:{type:"string",description:'Unique semantic key, e.g. "pref:coding-style" or "decision:/home/user/app:state-management"',required:!0},value:{type:"string",description:"The content to remember \u2014 decision, preference, fact, or outcome text",required:!0},kind:{type:"string",description:`Category: ${Sr.join(" | ")}`,required:!0},tags:{type:"string",description:'Comma-separated tags for grouping, e.g. "typescript,react,architecture"',required:!1},project:{type:"string",description:"Absolute project path this memory belongs to (optional)",required:!1},priority:{type:"string",description:"critical | high | normal | low (default: normal)",required:!1}},execute:async t=>{try{let e=t.kind;if(!Sr.includes(e))return{success:!1,output:"",error:`Invalid kind "${t.kind}". Must be one of: ${Sr.join(", ")}`};let r=t.key,n=t.value;if(!r||!n)return{success:!1,output:"",error:"key and value are required"};let s=t.tags?t.tags.split(",").map(a=>a.trim()).filter(Boolean):[],i=t.priority??"normal",o=W().remember({kind:e,key:r,value:n,tags:s,project:t.project,priority:i});return{success:!0,output:`Remembered [${e}] key="${r}" (id=${o})`}}catch(e){return{success:!1,output:"",error:`[remember]: ${e.message}`}}}},{name:"recall",description:"Retrieve a specific memory entry by its exact key. Returns null if not found.",safety:"safe",parameters:{key:{type:"string",description:"The exact key used when storing the memory",required:!0}},execute:async t=>{try{let e=W().recall(t.key);return e?{success:!0,output:[`Key: ${e.key}`,`Kind: ${e.kind}`,`Priority: ${e.priority}`,`Tags: ${e.tags.join(", ")||"\u2014"}`,`Value:
140
+ `).slice(0,r)}},kr=null;function V(){return kr||(kr=new ys),kr}function Sl(){kr?.flush()}var $r=["project","preference","decision","pattern","tool_outcome","fact","task_summary"];function _l(){return[{name:"remember",description:"Store a fact, decision, preference, or pattern in persistent memory that survives across sessions. Use this to remember important project decisions, user preferences, or recurring patterns you want to recall later.",safety:"safe",parameters:{key:{type:"string",description:'Unique semantic key, e.g. "pref:coding-style" or "decision:/home/user/app:state-management"',required:!0},value:{type:"string",description:"The content to remember \u2014 decision, preference, fact, or outcome text",required:!0},kind:{type:"string",description:`Category: ${$r.join(" | ")}`,required:!0},tags:{type:"string",description:'Comma-separated tags for grouping, e.g. "typescript,react,architecture"',required:!1},project:{type:"string",description:"Absolute project path this memory belongs to (optional)",required:!1},priority:{type:"string",description:"critical | high | normal | low (default: normal)",required:!1}},execute:async t=>{try{let e=t.kind;if(!$r.includes(e))return{success:!1,output:"",error:`Invalid kind "${t.kind}". Must be one of: ${$r.join(", ")}`};let r=t.key,n=t.value;if(!r||!n)return{success:!1,output:"",error:"key and value are required"};let s=t.tags?t.tags.split(",").map(a=>a.trim()).filter(Boolean):[],i=t.priority??"normal",o=V().remember({kind:e,key:r,value:n,tags:s,project:t.project,priority:i});return{success:!0,output:`Remembered [${e}] key="${r}" (id=${o})`}}catch(e){return{success:!1,output:"",error:`[remember]: ${e.message}`}}}},{name:"recall",description:"Retrieve a specific memory entry by its exact key. Returns null if not found.",safety:"safe",parameters:{key:{type:"string",description:"The exact key used when storing the memory",required:!0}},execute:async t=>{try{let e=V().recall(t.key);return e?{success:!0,output:[`Key: ${e.key}`,`Kind: ${e.kind}`,`Priority: ${e.priority}`,`Tags: ${e.tags.join(", ")||"\u2014"}`,`Value:
141
141
  ${e.value}`,`Last accessed: ${new Date(e.lastAccessed).toISOString()} (${e.accessCount}x)`].join(`
142
- `)}:{success:!0,output:`No memory found for key "${t.key}"`}}catch(e){return{success:!1,output:"",error:`[recall]: ${e.message}`}}}},{name:"search_memory",description:"Semantic search across all persistent memories. Use this at the start of complex tasks to retrieve relevant past decisions, preferences, and project knowledge.",safety:"safe",parameters:{query:{type:"string",description:"Natural language search query",required:!0},kind:{type:"string",description:`Optional filter by kind: ${Sr.join(" | ")}`,required:!1},project:{type:"string",description:"Optional: limit to a specific project path",required:!1},limit:{type:"number",description:"Max results (default: 8)",required:!1}},execute:async t=>{try{let e=W().search(t.query,{kind:t.kind,project:t.project,limit:t.limit||8});if(e.length===0)return{success:!0,output:"No relevant memories found."};let r=e.map((n,s)=>`${s+1}. [${n.entry.kind}] key="${n.entry.key}" score=${n.score.toFixed(2)}
142
+ `)}:{success:!0,output:`No memory found for key "${t.key}"`}}catch(e){return{success:!1,output:"",error:`[recall]: ${e.message}`}}}},{name:"search_memory",description:"Semantic search across all persistent memories. Use this at the start of complex tasks to retrieve relevant past decisions, preferences, and project knowledge.",safety:"safe",parameters:{query:{type:"string",description:"Natural language search query",required:!0},kind:{type:"string",description:`Optional filter by kind: ${$r.join(" | ")}`,required:!1},project:{type:"string",description:"Optional: limit to a specific project path",required:!1},limit:{type:"number",description:"Max results (default: 8)",required:!1}},execute:async t=>{try{let e=V().search(t.query,{kind:t.kind,project:t.project,limit:t.limit||8});if(e.length===0)return{success:!0,output:"No relevant memories found."};let r=e.map((n,s)=>`${s+1}. [${n.entry.kind}] key="${n.entry.key}" score=${n.score.toFixed(2)}
143
143
  ${n.entry.value.replace(/\n/g," \u2014 ").slice(0,180)}`);return{success:!0,output:`Found ${e.length} relevant memories:
144
144
 
145
145
  ${r.join(`
146
146
 
147
- `)}`}}catch(e){return{success:!1,output:"",error:`[search_memory]: ${e.message}`}}}},{name:"forget",description:"Delete a memory entry by its exact key. Use when a decision or preference is no longer valid.",safety:"safe",parameters:{key:{type:"string",description:"The exact key of the memory to delete",required:!0}},execute:async t=>{try{return{success:!0,output:W().forget(t.key)?`Deleted memory "${t.key}"`:`No memory found for key "${t.key}"`}}catch(e){return{success:!1,output:"",error:`[forget]: ${e.message}`}}}},{name:"memory_stats",description:"Show memory storage statistics: total entries, breakdown by kind, most recently accessed.",safety:"safe",parameters:{},execute:async()=>{try{let t=W().getStats(),e=W().getRecent(5);return{success:!0,output:[`Total memories: ${t.total}`,"Breakdown:",...Object.entries(t).filter(([n])=>n!=="total").map(([n,s])=>` ${n}: ${s}`),"","Most recently accessed:",...e.map(n=>` [${n.kind}] ${n.key.slice(0,60)} \u2014 ${new Date(n.lastAccessed).toISOString()}`)].join(`
148
- `)}}catch(t){return{success:!1,output:"",error:`[memory_stats]: ${t.message}`}}}}]}var yl=require("child_process");function Se(t,e,r=1e4){try{return{ok:!0,output:(0,yl.execSync)(t,{cwd:e,timeout:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){return{ok:!1,output:(n.stderr?.toString()||n.stdout?.toString()||n.message||"command failed").trim()}}}function vr(t){let e=Se("git rev-parse --is-inside-work-tree",t,3e3);return e.ok&&e.output==="true"}function wl(t){return[{name:"git_status",description:"Show the current git status: staged files, unstaged changes, untracked files, stash count, branch tracking state (ahead/behind remote). Use this to understand the state of the repository before making changes.",safety:"safe",parameters:{short:{type:"string",description:'Set to "true" for a compact one-line-per-file view (default: false)',required:!1}},execute:async e=>{if(!vr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.short==="true",n=[],s=Se("git branch --show-current",t),i=Se('git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null || echo "no-remote"',t);if(n.push(`Branch: ${s.output||"(detached HEAD)"}`),i.ok&&i.output!=="no-remote"){let c=Se(`git rev-list --left-right --count HEAD...${i.output}`,t);if(c.ok){let[u,d]=c.output.split(" ").map(Number);u>0&&n.push(`Ahead of remote: ${u} commit(s)`),d>0&&n.push(`Behind remote: ${d} commit(s)`)}n.push(`Remote: ${i.output}`)}let a=Se(r?"git status --short":"git status --porcelain=v1",t);if(a.ok&&a.output){n.push(""),n.push("Changes:");let c=a.output.split(`
149
- `).filter(Boolean),u=c.filter(p=>!"? ".includes(p[0])),d=c.filter(p=>p[1]!==" "&&p[0]===" "),m=c.filter(p=>p.startsWith("??"));u.length>0&&(n.push(" Staged:"),u.forEach(p=>n.push(` ${p.slice(0,2)} ${p.slice(3)}`))),d.length>0&&(n.push(" Unstaged:"),d.forEach(p=>n.push(` ${p.slice(0,2)} ${p.slice(3)}`))),m.length>0&&(n.push(` Untracked: ${m.length} file(s)`),m.length<=5&&m.forEach(p=>n.push(` ${p.slice(3)}`)))}else n.push("Working tree: clean");let l=Se("git stash list --oneline",t);if(l.ok&&l.output){let c=l.output.split(`
147
+ `)}`}}catch(e){return{success:!1,output:"",error:`[search_memory]: ${e.message}`}}}},{name:"forget",description:"Delete a memory entry by its exact key. Use when a decision or preference is no longer valid.",safety:"safe",parameters:{key:{type:"string",description:"The exact key of the memory to delete",required:!0}},execute:async t=>{try{return{success:!0,output:V().forget(t.key)?`Deleted memory "${t.key}"`:`No memory found for key "${t.key}"`}}catch(e){return{success:!1,output:"",error:`[forget]: ${e.message}`}}}},{name:"memory_stats",description:"Show memory storage statistics: total entries, breakdown by kind, most recently accessed.",safety:"safe",parameters:{},execute:async()=>{try{let t=V().getStats(),e=V().getRecent(5);return{success:!0,output:[`Total memories: ${t.total}`,"Breakdown:",...Object.entries(t).filter(([n])=>n!=="total").map(([n,s])=>` ${n}: ${s}`),"","Most recently accessed:",...e.map(n=>` [${n.kind}] ${n.key.slice(0,60)} \u2014 ${new Date(n.lastAccessed).toISOString()}`)].join(`
148
+ `)}}catch(t){return{success:!1,output:"",error:`[memory_stats]: ${t.message}`}}}}]}var kl=require("child_process");function $e(t,e,r=1e4){try{return{ok:!0,output:(0,kl.execSync)(t,{cwd:e,timeout:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){return{ok:!1,output:(n.stderr?.toString()||n.stdout?.toString()||n.message||"command failed").trim()}}}function Tr(t){let e=$e("git rev-parse --is-inside-work-tree",t,3e3);return e.ok&&e.output==="true"}function $l(t){return[{name:"git_status",description:"Show the current git status: staged files, unstaged changes, untracked files, stash count, branch tracking state (ahead/behind remote). Use this to understand the state of the repository before making changes.",safety:"safe",parameters:{short:{type:"string",description:'Set to "true" for a compact one-line-per-file view (default: false)',required:!1}},execute:async e=>{if(!Tr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.short==="true",n=[],s=$e("git branch --show-current",t),i=$e('git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null || echo "no-remote"',t);if(n.push(`Branch: ${s.output||"(detached HEAD)"}`),i.ok&&i.output!=="no-remote"){let c=$e(`git rev-list --left-right --count HEAD...${i.output}`,t);if(c.ok){let[u,d]=c.output.split(" ").map(Number);u>0&&n.push(`Ahead of remote: ${u} commit(s)`),d>0&&n.push(`Behind remote: ${d} commit(s)`)}n.push(`Remote: ${i.output}`)}let a=$e(r?"git status --short":"git status --porcelain=v1",t);if(a.ok&&a.output){n.push(""),n.push("Changes:");let c=a.output.split(`
149
+ `).filter(Boolean),u=c.filter(p=>!"? ".includes(p[0])),d=c.filter(p=>p[1]!==" "&&p[0]===" "),m=c.filter(p=>p.startsWith("??"));u.length>0&&(n.push(" Staged:"),u.forEach(p=>n.push(` ${p.slice(0,2)} ${p.slice(3)}`))),d.length>0&&(n.push(" Unstaged:"),d.forEach(p=>n.push(` ${p.slice(0,2)} ${p.slice(3)}`))),m.length>0&&(n.push(` Untracked: ${m.length} file(s)`),m.length<=5&&m.forEach(p=>n.push(` ${p.slice(3)}`)))}else n.push("Working tree: clean");let l=$e("git stash list --oneline",t);if(l.ok&&l.output){let c=l.output.split(`
150
150
  `).filter(Boolean).length;n.push(`Stash: ${c} stashed change(s)`)}return{success:!0,output:n.join(`
151
- `)}}},{name:"git_diff",description:"Show the diff for a file or the whole working tree. Useful to understand exactly what changed before or after edits.",safety:"safe",parameters:{path:{type:"string",description:"File path to diff (optional \u2014 omit for full diff)",required:!1},staged:{type:"string",description:'Set "true" to show staged diff (default: unstaged)',required:!1},lines:{type:"number",description:"Context lines around each change (default: 3)",required:!1}},execute:async e=>{if(!vr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.staged==="true"?"--cached ":"",n=e.lines?`-U${e.lines}`:"-U3",s=e.path?`-- "${e.path}"`:"",i=`git diff ${r}${n} ${s}`.trim(),o=Se(i,t);if(!o.ok)return{success:!1,output:"",error:o.output};if(!o.output)return{success:!0,output:e.path?`No diff for ${e.path}`:"No changes detected."};let a=8e3;return{success:!0,output:o.output.length>a?o.output.slice(0,a)+`
152
- ... [diff truncated]`:o.output}}},{name:"git_log",description:"Show recent git commit history with author, date, and message. Optionally filter by file.",safety:"safe",parameters:{limit:{type:"number",description:"Number of commits to show (default: 10)",required:!1},path:{type:"string",description:"File path to filter commits by (optional)",required:!1},stats:{type:"string",description:'Set "true" to include file change stats per commit',required:!1}},execute:async e=>{if(!vr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.limit||10,n=e.path?`-- "${e.path}"`:"",s=e.stats==="true"?"--stat":"",o=`git log -${r} --format="%h %as %an %s" ${s} ${n}`.trim(),a=Se(o,t);return a.ok?{success:!0,output:a.output||"No commits found."}:{success:!1,output:"",error:a.output}}},{name:"git_branch",description:"List git branches, show current branch, and tracking info.",safety:"safe",parameters:{all:{type:"string",description:'Set "true" to include remote branches (default: local only)',required:!1}},execute:async e=>{if(!vr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.all==="true"?"-a":"",n=Se(`git branch ${r} -vv`,t);return n.ok?{success:!0,output:n.output||"No branches found."}:{success:!1,output:"",error:n.output}}}]}var at=class{tools=new Map;constructor(e,r){let n=xa(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",$a(e,r)),this.tools.set("search_codebase",Ta(e)),this.tools.set("detect_bugs",Aa(e)),this.tools.set("web_search",Pa());for(let s of ja())this.tools.set(s.name,s);for(let s of Ua(e))this.tools.set(s.name,s);for(let s of Ga())this.tools.set(s.name,s);this.tools.set("download_asset",nl(e));for(let s of cl(e,r))this.tools.set(s.name,s);for(let s of gl())this.tools.set(s.name,s);for(let s of wl(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(`
151
+ `)}}},{name:"git_diff",description:"Show the diff for a file or the whole working tree. Useful to understand exactly what changed before or after edits.",safety:"safe",parameters:{path:{type:"string",description:"File path to diff (optional \u2014 omit for full diff)",required:!1},staged:{type:"string",description:'Set "true" to show staged diff (default: unstaged)',required:!1},lines:{type:"number",description:"Context lines around each change (default: 3)",required:!1}},execute:async e=>{if(!Tr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.staged==="true"?"--cached ":"",n=e.lines?`-U${e.lines}`:"-U3",s=e.path?`-- "${e.path}"`:"",i=`git diff ${r}${n} ${s}`.trim(),o=$e(i,t);if(!o.ok)return{success:!1,output:"",error:o.output};if(!o.output)return{success:!0,output:e.path?`No diff for ${e.path}`:"No changes detected."};let a=8e3;return{success:!0,output:o.output.length>a?o.output.slice(0,a)+`
152
+ ... [diff truncated]`:o.output}}},{name:"git_log",description:"Show recent git commit history with author, date, and message. Optionally filter by file.",safety:"safe",parameters:{limit:{type:"number",description:"Number of commits to show (default: 10)",required:!1},path:{type:"string",description:"File path to filter commits by (optional)",required:!1},stats:{type:"string",description:'Set "true" to include file change stats per commit',required:!1}},execute:async e=>{if(!Tr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.limit||10,n=e.path?`-- "${e.path}"`:"",s=e.stats==="true"?"--stat":"",o=`git log -${r} --format="%h %as %an %s" ${s} ${n}`.trim(),a=$e(o,t);return a.ok?{success:!0,output:a.output||"No commits found."}:{success:!1,output:"",error:a.output}}},{name:"git_branch",description:"List git branches, show current branch, and tracking info.",safety:"safe",parameters:{all:{type:"string",description:'Set "true" to include remote branches (default: local only)',required:!1}},execute:async e=>{if(!Tr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.all==="true"?"-a":"",n=$e(`git branch ${r} -vv`,t);return n.ok?{success:!0,output:n.output||"No branches found."}:{success:!1,output:"",error:n.output}}}]}var dt=class{tools=new Map;constructor(e,r){let n=Ca(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",Ma(e)),this.tools.set("detect_bugs",La(e)),this.tools.set("web_search",Ba());for(let s of qa())this.tools.set(s.name,s);for(let s of Ga(e))this.tools.set(s.name,s);for(let s of tl())this.tools.set(s.name,s);this.tools.set("download_asset",ul(e));for(let s of gl(e,r))this.tools.set(s.name,s);for(let s of _l())this.tools.set(s.name,s);for(let s of $l(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(`
153
153
  `);return`- ${r.name} [${r.safety}]: ${r.description}
154
154
  ${n}`}).join(`
155
155
 
156
- `)}};var bl=C(require("crypto"));function hs(t){return Math.ceil(t.length/3.5)}function Ot(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
157
- ... [truncated to fit context budget]`}var lt=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=hs(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=Ot(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
156
+ `)}};var Tl=C(require("crypto"));function bs(t){return Math.ceil(t.length/3.5)}function jt(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
157
+ ... [truncated to fit context budget]`}var pt=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=bs(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=jt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
158
158
  ${l}`),s+=a}}continue}i.push(`--- ${o.path} ---
159
159
  ${o.content}`),s+=o.tokenCount}return i.join(`
160
160
 
161
161
  `)}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(u=>c.path.includes(u))).sort((c,u)=>this.computeScore(u)-this.computeScore(c)),a=0,l=[];for(let c of o){if(a+c.tokenCount>n)break;l.push(`--- ${c.path} ---
162
162
  ${c.content}`),a+=c.tokenCount}return l.join(`
163
163
 
164
- `)}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=hs(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 bl.createHash("md5").update(e).digest("hex")}};var $h=0;function It(){return`msg_${Date.now()}_${++$h}`}function ct(t){return Math.ceil(t.length/4)}var ut=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=ct(e);this.messages.push({id:It(),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=It(),s=ct(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=It(),i=ct(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=It(),s=ct(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=ct(e),n={id:It(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]};if(this.messages.length===0){this.messages=[n],this.recalculateTokens();return}this.messages[0]=n,this.recalculateTokens(),this.trimIfNeeded()}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)+`
164
+ `)}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=bs(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 Tl.createHash("md5").update(e).digest("hex")}};var Hh=0;function Pt(){return`msg_${Date.now()}_${++Hh}`}function mt(t){return Math.ceil(t.length/4)}var ht=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=mt(e);this.messages.push({id:Pt(),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=Pt(),s=mt(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=Pt(),i=mt(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=Pt(),s=mt(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=mt(e),n={id:Pt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]};if(this.messages.length===0){this.messages=[n],this.recalculateTokens();return}this.messages[0]=n,this.recalculateTokens(),this.trimIfNeeded()}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)+`
165
165
  ...(compressed from `+r+" chars)":e.content=e.content.slice(0,400)+`
166
- ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=ct(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 dt=C(require("fs")),xl=C(require("path"));var O=C(require("fs")),I=C(require("path"));function Th(t){let e=I.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(I.join(t,"requirements.txt"))||O.existsSync(I.join(t,"pyproject.toml")))try{let r=O.existsSync(I.join(t,"requirements.txt"))?O.readFileSync(I.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(I.join(t,"Cargo.toml")))try{if(O.readFileSync(I.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(O.existsSync(I.join(t,"go.mod")))try{if(O.readFileSync(I.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Ch(t){return O.existsSync(I.join(t,"pnpm-lock.yaml"))?"pnpm":O.existsSync(I.join(t,"yarn.lock"))?"yarn":O.existsSync(I.join(t,"bun.lockb"))?"bun":O.existsSync(I.join(t,"package-lock.json"))?"npm":O.existsSync(I.join(t,"Cargo.toml"))?"cargo":O.existsSync(I.join(t,"go.mod"))?"go":O.existsSync(I.join(t,"requirements.txt"))||O.existsSync(I.join(t,"pyproject.toml"))?"pip":"unknown"}function Eh(t){return O.existsSync(I.join(t,"tsconfig.json"))?"TypeScript":O.existsSync(I.join(t,"package.json"))?"JavaScript":O.existsSync(I.join(t,"Cargo.toml"))?"Rust":O.existsSync(I.join(t,"go.mod"))?"Go":O.existsSync(I.join(t,"pyproject.toml"))||O.existsSync(I.join(t,"requirements.txt"))?"Python":"Unknown"}function Ah(t){let e=I.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 ft(t){let e=Th(t),r=Ch(t),n=Eh(t),s=Ah(t),i=O.existsSync(I.join(t,"Dockerfile"))||O.existsSync(I.join(t,"docker-compose.yml"))||O.existsSync(I.join(t,"docker-compose.yaml")),o=O.existsSync(I.join(t,".github","workflows"))||O.existsSync(I.join(t,".gitlab-ci.yml"))||O.existsSync(I.join(t,"Jenkinsfile")),a=O.existsSync(I.join(t,"__tests__"))||O.existsSync(I.join(t,"tests"))||O.existsSync(I.join(t,"test"))||O.existsSync(I.join(t,"spec")),l=O.existsSync(I.join(t,".git")),c=[],u=[".env",".env.local",".env.development",".env.production",".env.example"];for(let h of u)O.existsSync(I.join(t,h))&&c.push(h);let d=[],m=["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 h of m)O.existsSync(I.join(t,h))&&d.push(h);let p=[],f=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let h of f)O.existsSync(I.join(t,h))&&p.push(h);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 _r(t){let e=[` Project: ${I.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(`
167
- `)}async function pt(t,e){let r=[],n=xl.join(t,"package.json");if(dt.existsSync(n))try{let o=JSON.parse(dt.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=ft(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=Oh(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(`
168
- `)}function Oh(t,e){try{return dt.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function mt(t,e,r){return["You are Hablas.","","You are a high-caliber single-agent software engineering runtime created by Abdulmoin Hablas.","Your bar is elite production execution: correct judgment, concrete delivery, honest verification, and calm ownership.","",J("CORE IDENTITY",["- You are the ONLY visible agent.","- You never mention internal teams, hidden layers, specialist personas, routing systems, orchestration, or agent delegation.","- You are one runtime, one conversation surface, and one unified engineering mind.","- You think with the depth of a principal engineer, systems architect, debugger, reviewer, product thinker, researcher, and delivery lead \u2014 but you answer as one coherent operator.","- Do not invent public modes, specialist theatre, or assistant handoffs.","- Image understanding, when needed, lives ONLY inside image tooling. Vision is a tool capability of inspect_image, not a second assistant, not a second runtime, and not a public model choice for Hablas."]),"",J("PERSONALITY / INTERACTION",["- Warm-professional","- Precise","- Calm","- Direct","- Technically serious","- Evidence-driven","- Quietly proactive","- High-ownership","- No emojis","- No hype","- No filler","- No motivational fluff","- No fake confidence","- No cold robotic emptiness","","Communication rules:","- Match the user's language naturally. If the user writes Arabic, answer in Arabic. If English, answer in English. If mixed, respond in the most natural useful mix.","- For simple greetings or short social turns, reply with one short warm line plus readiness when helpful. Never return an empty-feeling answer.","- Keep identity answers compact unless the user explicitly asks for detail.","- During engineering work, reduce small talk and move the work forward.","- Prefer decisive wording when evidence exists. When uncertainty exists, state it precisely instead of hedging vaguely.","- After meaningful work, optionally suggest one concrete high-value next step \u2014 not a generic list of ideas.","- Do not echo the user's exact wording unless it improves clarity.","- Do not expose internal chain-of-thought.","- Sound like a strong engineering partner, not a sterile shell and not a chatty motivational bot."]),"",J("MISSION",["Your mission is to convert user intent into correct, concrete engineering outcomes.","That means you must:","- understand the real task","- respect the user's architecture and constraints","- inspect reality before making claims","- use the correct tools when action is required","- modify real files when implementation is requested","- verify before claiming success","- report honestly what changed, what was verified, and what remains uncertain"]),"",J("DECISION PRIORITIES",["When trade-offs appear, prioritize in this order:","1. Reality and correctness","2. Actual task completion","3. Preserving the user's stated architecture, constraints, and product direction","4. Minimal correct change surface","5. Verification and regression awareness","6. Clarity of delivery","7. Speed","- Prefer honest partial progress over polished fiction.","- Default to safe, conservative assumptions only when they let you continue correctly. Ask only when ambiguity would materially risk the result or cause destructive wrong work."]),"",J("INTERPRETATION MODEL",["Interpret requests by BEHAVIOR CLASS, not by literal phrase matching.","The same intent may appear in Arabic, English, mixed language, slang, shorthand, typos, or incomplete wording.","Your job is to infer the class of work, not wait for perfect phrasing.","","Internal behavior classes:","1. Social / casual turn","2. Read-only inspection / factual project question","3. Analysis / architecture / design reasoning","4. Implementation / modification / upgrade / repair","5. Continuation of existing unfinished work","6. One-step delivery with minimal back-and-forth","7. Web / asset / external-resource acquisition","","You must infer these classes from intent, not exact wording.","Never gate behavior on specific trigger words, exact commands, or a fixed phrase list.","Typos do NOT downgrade the task.","If the user clearly wants a real project outcome, treat it as execution work even if the wording is imperfect."]),"",J("TURN OPERATING LOOP",["Run every non-trivial turn through this internal execution cadence:","1. ORIENT \u2014 infer the real goal, success criteria, constraints, requested depth, and whether the user wants analysis or execution.","2. GROUND \u2014 inspect the relevant files, commands, or external evidence before making project-specific claims.","3. PLAN \u2014 choose the smallest correct path that satisfies the request.","4. EXECUTE \u2014 do the work with tools; avoid performative narration and avoid stalling in explanation.","5. VERIFY \u2014 run the strongest reasonable checks available for the change.","6. DELIVER \u2014 present the result in a clean, executive format tailored to the task.","","Execution cadence rules:","- For implementation work, do not ask performative questions when a safe assumption lets you continue.","- For continuation work, start from existing artifacts instead of reimagining the project from zero.","- For one-step delivery requests, maximize completion in one pass while remaining honest about limits.","- If your previous direction was weak, correct course fast instead of defending it."]),"",J("NON-NEGOTIABLE RULES",["1. If the task does not need tools, answer directly.","2. If the task needs tools, use tools.","3. If the task is implementation-oriented, prose-only output is insufficient.","4. Read before editing when content is unknown.","5. Do not reread the same file unless:"," - it changed, or"," - you need a different section not already captured.","6. One tool call at a time.","7. Never output raw tool JSON, XML, pseudo-calls, or internal formatting in user-facing text.","8. Never claim a file was created, edited, downloaded, tested, verified, or fixed unless a tool actually did it.","9. Ground project-specific claims in observed files, command output, or current web evidence.","10. Verify before claiming completion.","11. If not verified, say so explicitly.","12. Ask clarifying questions only when genuinely blocked.","13. Prefer minimal correct edits over broad rewrites unless the user explicitly wants a rewrite.","14. Preserve the user's architecture, naming, and product direction unless they explicitly ask to change them.","15. Do not invent blockers. If you can proceed safely, proceed.","16. Do not return empty or placeholder replies for social turns or completed work."]),"",J("TOOL CONTRACTS",["Choose tools by function, not habit.","","Filesystem and code editing:","- read_file: inspect actual content","- list_dir: inspect structure","- get_file_info: inspect file metadata/existence","- write_file: create new files or full rewrites","- patch_file: preferred for line-based targeted edits","- edit_file: exact-content surgical replacement when exact source text is known","- search_and_replace: bulk exact/regex replacement","- append_to_file: append intentionally","- move_file: rename/relocate","- delete_file: remove only when truly necessary","- create_dir: create folder structure","","Code understanding:","- search_codebase: find symbols, patterns, references, duplication, structure","- detect_bugs: run static issue detection when it helps","- execute_code: run isolated logic snippets when that is the correct verification route","","Build / verification / runtime:","- run_command: install, build, test, lint, typecheck, run, verify","","Git intelligence (read-only, safe):","- git_status: understand repo state before/after edits","- git_diff: inspect exact line-level changes for a file or whole tree","- git_log: recent commit history, optionally filtered by file","- git_branch: list branches and tracking info","","Persistent memory (cross-session, critical):","- search_memory: for complex tasks call this FIRST \u2014 retrieves past decisions/preferences","- remember: store key decisions and preferences that survive session restarts","- recall: retrieve a specific memory by exact key","- forget: delete an outdated or wrong memory","","Memory usage rules:","- complex implementation: call search_memory FIRST","- after significant work: call remember with the key decision/outcome","- user states a preference: call remember immediately","- casual or trivial turns: skip memory tools","","Web / internet / assets:","- web_search: current information, libraries, APIs, docs, images, references","- search_image_candidates: search and rank image candidates using trusted-source weighting and keyword scoring","- inspect_image: inspect a remote image candidate or image page before adoption; use it to check dimensions, direct-image status, source quality, suitability, and tool-local vision analysis when needed","- scrape_url: inspect page content","- extract_links: collect concrete links from a page","- download_asset: bring real external assets into the project (hero images, wallpaper, icons, etc.)","- read_pdf / pdf_metadata: inspect PDF-based specs and docs","","Tool usage principles:","- Use the minimum necessary sequence.","- Use web tools when the task depends on current internet resources or external assets.","- For image-heavy work, prefer: search_image_candidates -> inspect_image -> download_asset.","- Use download_asset when the user wants an actual local asset in the project, not just a URL suggestion.","- Prefer trusted image sources and high-confidence candidates over brute-force downloading random links.","- Avoid repeated blind retries on weak or blocked image URLs; inspect or switch candidate first.","- For image acquisition or replacement, stay inside the image toolchain. Do not fall back to run_command, execute_code, curl, powershell, or guessed public image IDs unless the user explicitly asked for low-level debugging.","- If a source is rate-limited or weak, switch trusted source or candidate instead of improvising with shell hacks.","- For frontend work, prefer integrating real local assets over leaving everything as remote placeholder links if practical.","- For implementation tasks, tool usage is part of the work itself, not an optional add-on."]),"",J("WORK MODE CONTRACTS",["A) SOCIAL / CASUAL","- 1\u20132 natural sentences","- warm but compact","- no tools unless absolutely necessary","- if the user is just greeting, acknowledge and signal readiness","","B) READ-ONLY INSPECTION","- answer first, then support with evidence when useful","- inspect the minimum relevant evidence","- answer factually","- do not invent unseen details","- avoid giant reports for small questions","","C) ANALYSIS / ARCHITECTURE","- reason from constraints first","- inspect files only when needed to ground the recommendation","- deliver assumptions, trade-offs, constraints, and the practical next move","- do not drift into implementation if the user asked for analysis only","","D) IMPLEMENTATION / MODIFICATION / UPGRADE / FIX","- inspect -> change -> verify -> report","- enter a real tool-based execution path","- make actual file changes when needed","- finish with a tangible result, not a plan disguised as a result","- if blocked, state the exact blocker and the nearest completed state","","E) CONTINUATION OF EXISTING WORK","- continue from what exists","- reuse current artifacts, files, and structure","- do not restart the project from zero unless explicitly told to rewrite it from scratch","","F) ONE-STEP DELIVERY","- minimize unnecessary back-and-forth","- complete as much as possible in one pass","- remain honest about what was and was not verified","","G) WEB / UI / ASSET WORK","- inspect the current files first","- improve actual files, not just describe improvements","- think about hierarchy, spacing, typography, responsiveness, visual quality, coherence, and usability","- for internet images/assets, rank candidates, inspect them, then download the strongest option","- prefer trusted sources and semantically relevant candidates","- if assets already exist locally, prefer reusing or upgrading them intelligently","- if inspect_image returns weak semantic confidence, switch candidate instead of forcing a weak download","- for bulk replace-all image tasks, avoid expensive forensic auditing of every old asset unless the user explicitly asked for an audit; do a light inventory and move into replacement flow","- do not brute-force many low-quality downloads when stronger candidates are available"]),"",J("DEBUGGING / REVIEW / QUALITY BAR",["When debugging:","- symptom -> evidence -> hypothesis -> verification -> fix -> verification again","- focus on root cause, not surface symptoms","- keep the fix minimal and justified","","Before finalizing technical work, silently review for:","- correctness","- security","- maintainability","- consistency with existing code","- regressions","- verification status","- whether the user asked for a real result and actually got one"]),"",J("ANTI-FAILURE RULES",["- If the task is implementation-oriented and you responded without tools, your response is likely incomplete.","- If the task involves project files and you did not inspect the relevant files, your confidence should be low.","- If the task involves modification but no files were changed, the task is likely incomplete.","- If the task involves internet images/assets and you only discussed URLs without integrating anything, the task is likely incomplete unless the user asked for ideas only.","- If you detect that your previous direction was too weak, correct course and execute properly.","- If continuity is needed but you ignored prior context, your answer quality is degraded."]),"",J("FINAL RESPONSE CONTRACT",["For casual turns:","- keep it short, warm, and natural","- avoid robotic phrasing","","For read-only and analysis answers:","- answer directly","- structure only as much as the task needs","- cite observed evidence in plain language when relevant","","For implementation, upgrade, refactor, frontend, asset, or repair work:","- present the final answer as a compact executive report","- use markdown headings when the work is substantial","- prefer this structure:"," - ## Completed"," - ## Changed Files and Assets"," - ## Verification"," - ## Remaining Notes","- under each section, use short bullets or a compact table when useful","- mention any added/downloaded assets explicitly","- mention what was verified explicitly","- mention what remains unverified or incomplete explicitly","- when useful, end with one compact high-value next step or recommendation","- keep the report clean and premium, not chatty and not status-theatre","","For failures:","- be explicit, technical, honest","- do not pretend the task succeeded","- if partial work happened, say exactly what succeeded and what failed","- if nothing changed, say that clearly"]),"",...(()=>{if(!r)return[];let n=W().buildContextBlock(r,2500);return n.trim()?[J("PERSISTENT MEMORY",n),""]:[]})(),J("TASK PROFILE",Rh(e)),"",J("CURRENT PROJECT CONTEXT",Ih(t))].join(`
169
- `)}function J(t,e){let r=Array.isArray(e)?e.join(`
166
+ ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=mt(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 yt=C(require("fs")),Cl=C(require("path"));var O=C(require("fs")),R=C(require("path"));function Wh(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 Vh(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 Kh(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 zh(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 gt(t){let e=Wh(t),r=Vh(t),n=Kh(t),s=zh(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=[],u=[".env",".env.local",".env.development",".env.production",".env.example"];for(let g of u)O.existsSync(R.join(t,g))&&c.push(g);let d=[],m=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let g of m)O.existsSync(R.join(t,g))&&d.push(g);let p=[],f=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let g of f)O.existsSync(R.join(t,g))&&p.push(g);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(`
167
+ `)}async function wt(t,e){let r=[],n=Cl.join(t,"package.json");if(yt.existsSync(n))try{let o=JSON.parse(yt.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=gt(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=Gh(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(`
168
+ `)}function Gh(t,e){try{return yt.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function bt(t,e,r){return["You are Hablas.","","You are a high-caliber single-agent software engineering runtime created by Abdulmoin Hablas.","Your bar is elite production execution: correct judgment, concrete delivery, honest verification, and calm ownership.","",Q("CORE IDENTITY",["- You are the ONLY visible agent.","- You never mention internal teams, hidden layers, specialist personas, routing systems, orchestration, or agent delegation.","- You are one runtime, one conversation surface, and one unified engineering mind.","- You think with the depth of a principal engineer, systems architect, debugger, reviewer, product thinker, researcher, and delivery lead \u2014 but you answer as one coherent operator.","- Do not invent public modes, specialist theatre, or assistant handoffs.","- Image understanding, when needed, lives ONLY inside image tooling. Vision is a tool capability of inspect_image, not a second assistant, not a second runtime, and not a public model choice for Hablas."]),"",Q("PERSONALITY / INTERACTION",["- Warm-professional","- Precise","- Calm","- Direct","- Technically serious","- Evidence-driven","- Quietly proactive","- High-ownership","- No emojis","- No hype","- No filler","- No motivational fluff","- No fake confidence","- No cold robotic emptiness","","Communication rules:","- Match the user's language naturally. If the user writes Arabic, answer in Arabic. If English, answer in English. If mixed, respond in the most natural useful mix.","- For simple greetings or short social turns, reply with one short warm line plus readiness when helpful. Never return an empty-feeling answer.","- Keep identity answers compact unless the user explicitly asks for detail.","- During engineering work, reduce small talk and move the work forward.","- Prefer decisive wording when evidence exists. When uncertainty exists, state it precisely instead of hedging vaguely.","- After meaningful work, optionally suggest one concrete high-value next step \u2014 not a generic list of ideas.","- Do not echo the user's exact wording unless it improves clarity.","- Do not expose internal chain-of-thought.","- Sound like a strong engineering partner, not a sterile shell and not a chatty motivational bot."]),"",Q("MISSION",["Your mission is to convert user intent into correct, concrete engineering outcomes.","That means you must:","- understand the real task","- respect the user's architecture and constraints","- inspect reality before making claims","- use the correct tools when action is required","- modify real files when implementation is requested","- verify before claiming success","- report honestly what changed, what was verified, and what remains uncertain"]),"",Q("DECISION PRIORITIES",["When trade-offs appear, prioritize in this order:","1. Reality and correctness","2. Actual task completion","3. Preserving the user's stated architecture, constraints, and product direction","4. Minimal correct change surface","5. Verification and regression awareness","6. Clarity of delivery","7. Speed","- Prefer honest partial progress over polished fiction.","- Default to safe, conservative assumptions only when they let you continue correctly. Ask only when ambiguity would materially risk the result or cause destructive wrong work."]),"",Q("INTERPRETATION MODEL",["Interpret requests by BEHAVIOR CLASS, not by literal phrase matching.","The same intent may appear in Arabic, English, mixed language, slang, shorthand, typos, or incomplete wording.","Your job is to infer the class of work, not wait for perfect phrasing.","","Internal behavior classes:","1. Social / casual turn","2. Read-only inspection / factual project question","3. Analysis / architecture / design reasoning","4. Implementation / modification / upgrade / repair","5. Continuation of existing unfinished work","6. One-step delivery with minimal back-and-forth","7. Web / asset / external-resource acquisition","","You must infer these classes from intent, not exact wording.","Never gate behavior on specific trigger words, exact commands, or a fixed phrase list.","Typos do NOT downgrade the task.","If the user clearly wants a real project outcome, treat it as execution work even if the wording is imperfect."]),"",Q("TURN OPERATING LOOP",["Run every non-trivial turn through this internal execution cadence:","1. ORIENT \u2014 infer the real goal, success criteria, constraints, requested depth, and whether the user wants analysis or execution.","2. GROUND \u2014 inspect the relevant files, commands, or external evidence before making project-specific claims.","3. PLAN \u2014 choose the smallest correct path that satisfies the request.","4. EXECUTE \u2014 do the work with tools; avoid performative narration and avoid stalling in explanation.","5. VERIFY \u2014 run the strongest reasonable checks available for the change.","6. DELIVER \u2014 present the result in a clean, executive format tailored to the task.","","Execution cadence rules:","- For implementation work, do not ask performative questions when a safe assumption lets you continue.","- For continuation work, start from existing artifacts instead of reimagining the project from zero.","- For one-step delivery requests, maximize completion in one pass while remaining honest about limits.","- If your previous direction was weak, correct course fast instead of defending it."]),"",Q("NON-NEGOTIABLE RULES",["1. If the task does not need tools, answer directly.","2. If the task needs tools, use tools.","3. If the task is implementation-oriented, prose-only output is insufficient.","4. Read before editing when content is unknown.","5. Do not reread the same file unless:"," - it changed, or"," - you need a different section not already captured.","6. One tool call at a time.","7. Never output raw tool JSON, XML, pseudo-calls, or internal formatting in user-facing text.","8. Never claim a file was created, edited, downloaded, tested, verified, or fixed unless a tool actually did it.","9. Ground project-specific claims in observed files, command output, or current web evidence.","10. Verify before claiming completion.","11. If not verified, say so explicitly.","12. Ask clarifying questions only when genuinely blocked.","13. Prefer minimal correct edits over broad rewrites unless the user explicitly wants a rewrite.","14. Preserve the user's architecture, naming, and product direction unless they explicitly ask to change them.","15. Do not invent blockers. If you can proceed safely, proceed.","16. Do not return empty or placeholder replies for social turns or completed work."]),"",Q("TOOL CONTRACTS",["Choose tools by function, not habit.","","Filesystem and code editing:","- read_file: inspect actual content","- list_dir: inspect structure","- get_file_info: inspect file metadata/existence","- write_file: create new files or full rewrites","- patch_file: preferred for line-based targeted edits","- edit_file: exact-content surgical replacement when exact source text is known","- search_and_replace: bulk exact/regex replacement","- append_to_file: append intentionally","- move_file: rename/relocate","- delete_file: remove only when truly necessary","- create_dir: create folder structure","","Code understanding:","- search_codebase: find symbols, patterns, references, duplication, structure","- detect_bugs: run static issue detection when it helps","- execute_code: run isolated logic snippets when that is the correct verification route","","Build / verification / runtime:","- run_command: install, build, test, lint, typecheck, run, verify","","Git intelligence (read-only, safe):","- git_status: understand repo state before/after edits","- git_diff: inspect exact line-level changes for a file or whole tree","- git_log: recent commit history, optionally filtered by file","- git_branch: list branches and tracking info","","Persistent memory (cross-session, critical):","- search_memory: for complex tasks call this FIRST \u2014 retrieves past decisions/preferences","- remember: store key decisions and preferences that survive session restarts","- recall: retrieve a specific memory by exact key","- forget: delete an outdated or wrong memory","","Memory usage rules:","- complex implementation: call search_memory FIRST","- after significant work: call remember with the key decision/outcome","- user states a preference: call remember immediately","- casual or trivial turns: skip memory tools","","Web / internet / assets:","- web_search: current information, libraries, APIs, docs, images, references","- search_image_candidates: search and rank image candidates using trusted-source weighting and keyword scoring","- inspect_image: inspect a remote image candidate or image page before adoption; use it to check dimensions, direct-image status, source quality, suitability, and tool-local vision analysis when needed","- scrape_url: inspect page content","- extract_links: collect concrete links from a page","- download_asset: bring real external assets into the project (hero images, wallpaper, icons, etc.)","- read_pdf / pdf_metadata: inspect PDF-based specs and docs","","Tool usage principles:","- Use the minimum necessary sequence.","- Use web tools when the task depends on current internet resources or external assets.","- For image-heavy work, prefer: search_image_candidates -> inspect_image -> download_asset.","- Use download_asset when the user wants an actual local asset in the project, not just a URL suggestion.","- Prefer trusted image sources and high-confidence candidates over brute-force downloading random links.","- Avoid repeated blind retries on weak or blocked image URLs; inspect or switch candidate first.","- For image acquisition or replacement, stay inside the image toolchain. Do not fall back to run_command, execute_code, curl, powershell, or guessed public image IDs unless the user explicitly asked for low-level debugging.","- If a source is rate-limited or weak, switch trusted source or candidate instead of improvising with shell hacks.","- For frontend work, prefer integrating real local assets over leaving everything as remote placeholder links if practical.","- For implementation tasks, tool usage is part of the work itself, not an optional add-on."]),"",Q("WORK MODE CONTRACTS",["A) SOCIAL / CASUAL","- 1\u20132 natural sentences","- warm but compact","- no tools unless absolutely necessary","- if the user is just greeting, acknowledge and signal readiness","","B) READ-ONLY INSPECTION","- answer first, then support with evidence when useful","- inspect the minimum relevant evidence","- answer factually","- do not invent unseen details","- avoid giant reports for small questions","","C) ANALYSIS / ARCHITECTURE","- reason from constraints first","- inspect files only when needed to ground the recommendation","- deliver assumptions, trade-offs, constraints, and the practical next move","- do not drift into implementation if the user asked for analysis only","","D) IMPLEMENTATION / MODIFICATION / UPGRADE / FIX","- inspect -> change -> verify -> report","- enter a real tool-based execution path","- make actual file changes when needed","- finish with a tangible result, not a plan disguised as a result","- if blocked, state the exact blocker and the nearest completed state","","E) CONTINUATION OF EXISTING WORK","- continue from what exists","- reuse current artifacts, files, and structure","- do not restart the project from zero unless explicitly told to rewrite it from scratch","","F) ONE-STEP DELIVERY","- minimize unnecessary back-and-forth","- complete as much as possible in one pass","- remain honest about what was and was not verified","","G) WEB / UI / ASSET WORK","- inspect the current files first","- improve actual files, not just describe improvements","- think about hierarchy, spacing, typography, responsiveness, visual quality, coherence, and usability","- for internet images/assets, rank candidates, inspect them, then download the strongest option","- prefer trusted sources and semantically relevant candidates","- if assets already exist locally, prefer reusing or upgrading them intelligently","- if inspect_image returns weak semantic confidence, switch candidate instead of forcing a weak download","- for bulk replace-all image tasks, avoid expensive forensic auditing of every old asset unless the user explicitly asked for an audit; do a light inventory and move into replacement flow","- do not brute-force many low-quality downloads when stronger candidates are available"]),"",Q("DEBUGGING / REVIEW / QUALITY BAR",["When debugging:","- symptom -> evidence -> hypothesis -> verification -> fix -> verification again","- focus on root cause, not surface symptoms","- keep the fix minimal and justified","","Before finalizing technical work, silently review for:","- correctness","- security","- maintainability","- consistency with existing code","- regressions","- verification status","- whether the user asked for a real result and actually got one"]),"",Q("ANTI-FAILURE RULES",["- If the task is implementation-oriented and you responded without tools, your response is likely incomplete.","- If the task involves project files and you did not inspect the relevant files, your confidence should be low.","- If the task involves modification but no files were changed, the task is likely incomplete.","- If the task involves internet images/assets and you only discussed URLs without integrating anything, the task is likely incomplete unless the user asked for ideas only.","- If you detect that your previous direction was too weak, correct course and execute properly.","- If continuity is needed but you ignored prior context, your answer quality is degraded."]),"",Q("FINAL RESPONSE CONTRACT",["For casual turns:","- keep it short, warm, and natural","- avoid robotic phrasing","","For read-only and analysis answers:","- answer directly","- structure only as much as the task needs","- cite observed evidence in plain language when relevant","","For implementation, upgrade, refactor, frontend, asset, or repair work:","- present the final answer as a compact executive report","- use markdown headings when the work is substantial","- prefer this structure:"," - ## Completed"," - ## Changed Files and Assets"," - ## Verification"," - ## Remaining Notes","- under each section, use short bullets or a compact table when useful","- mention any added/downloaded assets explicitly","- mention what was verified explicitly","- mention what remains unverified or incomplete explicitly","- when useful, end with one compact high-value next step or recommendation","- keep the report clean and premium, not chatty and not status-theatre","","For failures:","- be explicit, technical, honest","- do not pretend the task succeeded","- if partial work happened, say exactly what succeeded and what failed","- if nothing changed, say that clearly"]),"",...(()=>{if(!r)return[];let n=V().buildContextBlock(r,2500);return n.trim()?[Q("PERSISTENT MEMORY",n),""]:[]})(),Q("TASK PROFILE",Yh(e)),"",Q("CURRENT PROJECT CONTEXT",Jh(t))].join(`
169
+ `)}function Q(t,e){let r=Array.isArray(e)?e.join(`
170
170
  `):e;return["====================",t,"====================",r].join(`
171
- `)}function Ih(t){return t.trim()||"No project context captured."}function Rh(t){return t.kind==="casual"?["- Casual/social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short, natural, and never empty-feeling.","- If the user is only greeting, acknowledge warmly and signal readiness."].join(`
171
+ `)}function Jh(t){return t.trim()||"No project context captured."}function Yh(t){return t.kind==="casual"?["- Casual/social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short, natural, and never empty-feeling.","- If the user is only greeting, acknowledge warmly and signal readiness."].join(`
172
172
  `):t.kind==="read"?["- Read-only or project-inspection task.","- Use tools only to inspect the minimum necessary evidence.","- Answer directly, then support with observed facts when useful.","- Keep the final answer factual, grounded, tight, and pleasantly professional."].join(`
173
173
  `):t.kind==="analysis"?["- Analysis / architecture task.","- Prefer reasoning from constraints first.","- Inspect files only when they materially improve the recommendation.","- Deliver trade-offs, assumptions, practical guidance, and the best next move."].join(`
174
174
  `):[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.","- Preserve the existing architecture unless the user explicitly asks for a structural change.","- Verify changes before claiming completion.","- End with a compact executive report, not a vague narrative."].join(`
175
- `)}var Mh=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make|deploy|configure|setup|set\s*up|install|integrate|connect|enable|disable|replace|rewrite|convert|transform|optimize|improve|upgrade|scaffold|init|initialize|bootstrap|wire|patch|apply|inject)\b/i,jh=/\b(انشئ|اعمل|ابني|طور|عدل|صلح|حدث|اضف|احذف|ارسل|فعل|شغل|حول|ضبط|هيئ|نفذ|اكتب|غير|بناء|تطوير|تعديل|اضافة|حذف|انشاء|تنفيذ|كود|برمج)\b/i,Ph=/\b(continue|resume|proceed|keep|finish|complete|pick\s*up|unfinished|remaining|previous|existing|current project|from the prd|where we left)\b/i,Lh=/\b(كمل|استمر|اكمل|واصل|ارجع|خلينا|لسا|بقي|ما خلصنا)\b/i,Dh=/\b(read|show|list|check|inspect|what|which|where|when|how|explain|describe|tell me|what is|what are|find out|look at|view|examine|analyze|review)\b/i,Fh=/\b(اقرا|اعرض|اشوف|شو|وين|كيف|ليش|وضح|اشرح|فين|ما هو|ما هي|بين|فسر)\b/i,Nh=/\b(architecture|design|blueprint|plan|approach|trade.?off|compare|research|investigate|document|strategy|structure|pattern|best practice|recommendation|suggest|advise|evaluate|assess|pros|cons)\b/i,qh=/\b(معمارية|تصميم|خطة|مقارنة|بحث|دراسة|هيكل|نهج|اقتراح|توصية|تقييم)\b/i,Uh=/\b(one\s*step|no\s*questions|just\s*do|just\s*give|deliver|finished|complete\s*in\s*one|all\s*at\s*once|without\s*asking)\b/i,Bh=/\b(بدون\s*اسئلة|مباشرة|فورا|دفعة\s*واحدة|كامل|بس\s*اعمل|عطني\s*النتيجة)\b/i,Hh=/^(hi|hello|hey|thanks|thank you|ok|okay|yes|no|sure|got it|great|nice|cool|perfect|awesome)[.!?\s]*$/i,Wh=/^(اه|تمام|شكرا|شكراً|مرحبا|اهلا|هلا|يلا|ماشي|حسنا|طيب|كيفك|صح)[.!?\s]*$/i,Sl=/\b(frontend|backend|api|endpoint|database|schema|component|page|route|store|auth|login|signup|dashboard|sidebar|navbar|header|footer|modal|form|button|card|table|chart|css|scss|style|theme|animation|responsive|mobile|typescript|javascript|python|rust|go|java|kotlin|swift|flutter|react|vue|svelte|next|nuxt|express|fastapi|django|rails|docker|k8s|kubernetes|ci|cd|github|actions|workflow|test|spec|coverage|lint|eslint|prettier|webpack|vite|build|bundle|deploy|nginx|postgres|mysql|mongo|redis|graphql|rest|grpc|websocket|socket)\b/i,Vh=/\b(واجهة|خلفية|قاعدة\s*بيانات|مكون|صفحة|مسار|تسجيل|لوحة\s*تحكم|تصميم|موبايل|اختبار|نشر|بناء)\b/i,zh=/\b(full|entire|complete|whole|all|comprehensive|production|enterprise|scalable|real-time|multi|complex|advanced|sophisticated|from\s*scratch|ground\s*up)\b/i,Kh=/\b(كامل|شامل|متكامل|احترافي|متقدم|من\s*الصفر|كل\s*شيء)\b/i,Gh=/\b(files?|components?|modules?|pages?|screens?|services?|controllers?|models?|views?|routes?|handlers?|hooks?|utils?|helpers?|types?|interfaces?)\b/i;function Jh(t){let e=(t.match(/[\u0600-\u06FF]/g)||[]).length,r=(t.match(/[a-zA-Z]/g)||[]).length,n=e+r;if(n===0)return"english";let s=e/n;return s>.7?"arabic":s<.2?"english":"mixed"}function Rt(t,e){let r=t.trim().replace(/\s+/g," ");if(r.length<=80)return r;let n=r.match(/^[^.!?\n]{10,80}/)?.[0];return n?n.trim()+"\u2026":r.slice(0,80)+"\u2026"}function Mt(t,e){if(e==="casual")return{complexity:"trivial",estimatedSteps:0};if(e==="read")return{complexity:"simple",estimatedSteps:2};let r=0;(zh.test(t)||Kh.test(t))&&(r+=3),Gh.test(t)&&(r+=2);let n=t.split(/\s+/).length;return n>50&&(r+=1),n>100&&(r+=2),t.includes(`
176
- `)&&(r+=1),Sl.test(t)&&(r+=1),e==="analysis"?r>=4?{complexity:"complex",estimatedSteps:8}:r>=2?{complexity:"moderate",estimatedSteps:4}:{complexity:"simple",estimatedSteps:2}:r>=7?{complexity:"epic",estimatedSteps:40}:r>=5?{complexity:"complex",estimatedSteps:20}:r>=3?{complexity:"moderate",estimatedSteps:10}:r>=1?{complexity:"simple",estimatedSteps:5}:{complexity:"simple",estimatedSteps:3}}function gs(t){let e=t.trim(),r=Jh(e),n=[],s=Mh.test(e),i=jh.test(e),o=s||i;s&&n.push("impl:en"),i&&n.push("impl:ar");let a=Ph.test(e)||Lh.test(e);a&&n.push("continuity");let l=Uh.test(e)||Bh.test(e);l&&n.push("one-step");let c=Dh.test(e)||Fh.test(e);c&&n.push("read");let u=Nh.test(e)||qh.test(e);u&&n.push("analysis");let d=Sl.test(e)||Vh.test(e);d&&n.push("eng-context");let m=/\b(project|repo|repository|codebase|workspace|file|src|package\.json|config)\b/i.test(e)||d;if(m&&n.push("project-ref"),(Hh.test(e)||Wh.test(e))&&!d&&!o&&!u){let{complexity:h,estimatedSteps:g}=Mt(e,"casual");return{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Social turn detected.",complexity:h,estimatedSteps:g,intent:Rt(e,r),language:r,confidence:.95,signals:n}}if(o||a||l||d&&e.length>20&&!c&&!u){let{complexity:h,estimatedSteps:g}=Mt(e,"implementation");return{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:a,oneStepDelivery:l,requiresProjectContext:!0,reason:a?"Continuation of previous work.":"Implementation task detected.",complexity:h,estimatedSteps:g,intent:Rt(e,r),language:r,confidence:.9,signals:n}}if(u&&!o){let{complexity:h,estimatedSteps:g}=Mt(e,"analysis");return{kind:"analysis",needsTools:m,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:m,reason:"Architecture or design analysis requested.",complexity:h,estimatedSteps:g,intent:Rt(e,r),language:r,confidence:.85,signals:n}}if(c||m){let{complexity:h,estimatedSteps:g}=Mt(e,"read");return{kind:"read",needsTools:m,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:m,reason:"Read-only or factual query.",complexity:h,estimatedSteps:g,intent:Rt(e,r),language:r,confidence:.8,signals:n}}let{complexity:p,estimatedSteps:f}=Mt(e,"analysis");return{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Default: analytical response.",complexity:p,estimatedSteps:f,intent:Rt(e,r),language:r,confidence:.6,signals:n}}function Yh(t){if(!t.needsTools)return[{id:"respond",title:"Respond directly and clearly."}];if(t.kind==="read")return[{id:"inspect",title:"Inspect the minimum relevant files."},{id:"answer",title:"Answer precisely from observed facts."}];if(t.kind==="analysis")return[{id:"memory",title:"Check persistent memory for relevant past decisions."},{id:"inspect",title:"Inspect only the files needed for analysis."},{id:"reason",title:"Form a concise architectural recommendation."},{id:"answer",title:"Present the result clearly."}];let e=[];return e.push({id:"memory",title:"Check persistent memory for relevant project context."}),t.continuity&&e.push({id:"continuity",title:"Load existing project context \u2014 do not restart from zero."}),t.oneStepDelivery&&e.push({id:"delivery-contract",title:"One-pass delivery \u2014 no follow-up questions."}),e.push({id:"inspect",title:"Inspect the relevant files and project structure."}),(t.complexity==="complex"||t.complexity==="epic")&&e.push({id:"plan",title:"Form a concrete step-by-step implementation plan."}),e.push({id:"implement",title:"Apply the correct implementation using tools."}),e.push({id:"verify",title:"Verify: run build/tests, check for regressions."}),e.push({id:"memory-save",title:"Save key decisions to persistent memory."}),e.push({id:"answer",title:"Report: what was done, what was verified, what remains."}),e}function vl(t){let e=gs(t);return{input:t,profile:e,plan:Yh(e)}}var Pl=C(require("readline")),ce=C(require("fs")),Z=C(require("path")),Ll=C(require("os"));var Re=C(require("process")),Xh=Re.stdout.isTTY===!0,ab=Re.env.NO_COLOR!==void 0||Re.env.TERM==="dumb",Qh=Re.stdout.columns||100;Xh&&Re.stdout.on("resize",()=>{Qh=Re.stdout.columns||100});var ys=C(require("os")),$r=C(require("fs")),kr=C(require("path"));function Zh(){let t=[kr.resolve(__dirname,"..","package.json"),kr.resolve(__dirname,"..","..","package.json"),kr.resolve(process.cwd(),"package.json")];for(let e of t)try{if($r.existsSync(e)){let r=JSON.parse($r.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var _l=Zh(),ws=process.stdout.isTTY===!0,eg=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",kl=process.stdout.columns||100;ws&&process.stdout.on("resize",()=>{kl=process.stdout.columns||100});var Me=()=>Math.min(Math.max(kl-4,60),100);function ae(t,e){return!ws||eg?t:`${e}${t}\x1B[0m`}var y={strong:t=>ae(t,"\x1B[1;38;5;255m"),muted:t=>ae(t,"\x1B[38;5;242m"),accent:t=>ae(t,"\x1B[38;5;145m"),info:t=>ae(t,"\x1B[38;5;110m"),success:t=>ae(t,"\x1B[38;5;108m"),warning:t=>ae(t,"\x1B[38;5;179m"),error:t=>ae(t,"\x1B[38;5;167m"),primary:t=>ae(t,"\x1B[38;5;253m"),secondary:t=>ae(t,"\x1B[38;5;247m"),border:t=>ae(t,"\x1B[38;5;237m"),code:t=>ae(t,"\x1B[38;5;188m"),line:t=>ae(t,"\x1B[38;5;239m")};function bs(t,e=2){let r=Me()-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 tg(t){let e=Me();if(!t)return y.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 y.border("\u2500".repeat(s))+" "+t+" "+y.border("\u2500".repeat(i))}function $l(t,e){let r=Math.min(Me(),82),n=e.replace(ys.homedir(),"~"),s=y.border("\u256D"+"\u2500".repeat(r-2)+"\u256E"),i=y.border("\u251C"+"\u2500".repeat(r-2)+"\u2524"),o=y.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)),u=Math.max(0,Math.floor((r-2-l.length)/2)),d=(m,p="")=>{let f=m.replace(/\x1b\[[0-9;]*m/g,""),h=p.replace(/\x1b\[[0-9;]*m/g,""),g=Math.max(1,r-4-f.length-h.length);return`${y.border("\u2502")} ${m}${" ".repeat(g)}${p} ${y.border("\u2502")}`};return["",s,y.border("\u2502")+" ".repeat(c)+y.strong(a)+" ".repeat(r-2-a.length-c)+y.border("\u2502"),y.border("\u2502")+" ".repeat(u)+y.secondary(l)+" ".repeat(r-2-l.length-u)+y.border("\u2502"),i,d(y.muted(`version v${_l}`),y.muted(t)),d(y.muted(n)),i,d(y.secondary("Type naturally to get started")),d(y.muted("/help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")),o,""].join(`
177
- `)}function Tl(t){return`
178
- `+tg(`${y.accent("\u25C6")} ${y.strong("Turn #"+t)}`)}function gt(){return`
179
- ${y.accent("\u25C6")} ${y.strong("Hablas")} ${y.muted("[response]")}`}function Cl(t){return` ${y.accent("\u25C9")} ${y.secondary(t)}`}function ht(t){return t.replace(/`([^`]+)`/g,(e,r)=>y.primary(r)).replace(/\*\*([^*]+)\*\*/g,(e,r)=>y.strong(r))}function rg(t){return/^\s*\|.*\|\s*$/.test(t)}function ng(t){let r=t.map(c=>c.trim()).filter(Boolean).map(c=>c.split("|").slice(1,-1).map(u=>u.trim())).filter(c=>!c.every(u=>/^:?-{2,}:?$/.test(u)));if(r.length===0)return[];let n=[];for(let c of r)c.forEach((u,d)=>{let m=u.replace(/\x1b\[[0-9;]*m/g,"").length;n[d]=Math.max(n[d]||0,m)});let s=` ${y.border("\u250C"+n.map(c=>"\u2500".repeat(c+2)).join("\u252C")+"\u2510")}`,i=` ${y.border("\u251C"+n.map(c=>"\u2500".repeat(c+2)).join("\u253C")+"\u2524")}`,o=` ${y.border("\u2514"+n.map(c=>"\u2500".repeat(c+2)).join("\u2534")+"\u2518")}`,a=c=>{let u=c.map((d,m)=>{let p=ht(d),f=p.replace(/\x1b\[[0-9;]*m/g,"").length;return` ${p}${" ".repeat(Math.max(0,n[m]-f))} `});return` ${y.border("\u2502")}${u.join(y.border("\u2502"))}${y.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 jt(t){let e=t.split(`
180
- `),r=[],n=!1,s="",i=[],o=[],a=()=>{if(!i.length)return;let c=String(i.length).length;r.push(` ${y.border("\u250C"+"\u2500".repeat(Math.max(24,Me()-6)))} ${s?y.accent(s):""}`.trimEnd()),i.forEach((u,d)=>{r.push(` ${y.border("\u2502")} ${y.line(String(d+1).padStart(c)+" \u2502")} ${y.code(u)}`)}),r.push(` ${y.border("\u2514"+"\u2500".repeat(Math.max(24,Me()-6)))}`),i=[]},l=()=>{o.length&&(r.push(...ng(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(rg(c)){o.push(c);continue}else l();if(!c.trim()){r.push("");continue}if(/^---+$/.test(c.trim())){r.push(` ${y.border("\u2500".repeat(Math.max(28,Me()-6)))}`);continue}if(/^#{1,3}\s/.test(c)){r.push(""),r.push(` ${y.strong(ht(c.replace(/^#{1,3}\s/,"")))}`);continue}if(/^[A-Z][A-Za-z0-9 /&_-]{2,}:$/.test(c.trim())){r.push(` ${y.strong(ht(c.trim()))}`);continue}if(/^[-*]\s/.test(c.trim())){r.push(` ${y.accent("\u25B8")} ${ht(c.trim().slice(2))}`);continue}if(/^\d+\.\s/.test(c.trim())){r.push(` ${ht(c.trim())}`);continue}r.push(...bs(ht(c),2))}return l(),n&&a(),`
175
+ `)}var Xh=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make|deploy|configure|setup|set\s*up|install|integrate|connect|enable|disable|replace|rewrite|convert|transform|optimize|improve|upgrade|scaffold|init|initialize|bootstrap|wire|patch|apply|inject)\b/i,Qh=/\b(انشئ|اعمل|ابني|طور|عدل|صلح|حدث|اضف|احذف|ارسل|فعل|شغل|حول|ضبط|هيئ|نفذ|اكتب|غير|بناء|تطوير|تعديل|اضافة|حذف|انشاء|تنفيذ|كود|برمج)\b/i,Zh=/\b(continue|resume|proceed|keep|finish|complete|pick\s*up|unfinished|remaining|previous|existing|current project|from the prd|where we left)\b/i,eg=/\b(كمل|استمر|اكمل|واصل|ارجع|خلينا|لسا|بقي|ما خلصنا)\b/i,tg=/\b(read|show|list|check|inspect|what|which|where|when|how|explain|describe|tell me|what is|what are|find out|look at|view|examine|analyze|review)\b/i,rg=/\b(اقرا|اعرض|اشوف|شو|وين|كيف|ليش|وضح|اشرح|فين|ما هو|ما هي|بين|فسر)\b/i,ng=/\b(architecture|design|blueprint|plan|approach|trade.?off|compare|research|investigate|document|strategy|structure|pattern|best practice|recommendation|suggest|advise|evaluate|assess|pros|cons)\b/i,sg=/\b(معمارية|تصميم|خطة|مقارنة|بحث|دراسة|هيكل|نهج|اقتراح|توصية|تقييم)\b/i,ig=/\b(one\s*step|no\s*questions|just\s*do|just\s*give|deliver|finished|complete\s*in\s*one|all\s*at\s*once|without\s*asking)\b/i,og=/\b(بدون\s*اسئلة|مباشرة|فورا|دفعة\s*واحدة|كامل|بس\s*اعمل|عطني\s*النتيجة)\b/i,ag=/^(hi|hello|hey|thanks|thank you|ok|okay|yes|no|sure|got it|great|nice|cool|perfect|awesome)[.!?\s]*$/i,lg=/^(اه|تمام|شكرا|شكراً|مرحبا|اهلا|هلا|يلا|ماشي|حسنا|طيب|كيفك|صح)[.!?\s]*$/i,El=/\b(frontend|backend|api|endpoint|database|schema|component|page|route|store|auth|login|signup|dashboard|sidebar|navbar|header|footer|modal|form|button|card|table|chart|css|scss|style|theme|animation|responsive|mobile|typescript|javascript|python|rust|go|java|kotlin|swift|flutter|react|vue|svelte|next|nuxt|express|fastapi|django|rails|docker|k8s|kubernetes|ci|cd|github|actions|workflow|test|spec|coverage|lint|eslint|prettier|webpack|vite|build|bundle|deploy|nginx|postgres|mysql|mongo|redis|graphql|rest|grpc|websocket|socket)\b/i,cg=/\b(واجهة|خلفية|قاعدة\s*بيانات|مكون|صفحة|مسار|تسجيل|لوحة\s*تحكم|تصميم|موبايل|اختبار|نشر|بناء)\b/i,ug=/\b(full|entire|complete|whole|all|comprehensive|production|enterprise|scalable|real-time|multi|complex|advanced|sophisticated|from\s*scratch|ground\s*up)\b/i,fg=/\b(كامل|شامل|متكامل|احترافي|متقدم|من\s*الصفر|كل\s*شيء)\b/i,dg=/\b(files?|components?|modules?|pages?|screens?|services?|controllers?|models?|views?|routes?|handlers?|hooks?|utils?|helpers?|types?|interfaces?)\b/i;function pg(t){let e=(t.match(/[\u0600-\u06FF]/g)||[]).length,r=(t.match(/[a-zA-Z]/g)||[]).length,n=e+r;if(n===0)return"english";let s=e/n;return s>.7?"arabic":s<.2?"english":"mixed"}function Lt(t,e){let r=t.trim().replace(/\s+/g," ");if(r.length<=80)return r;let n=r.match(/^[^.!?\n]{10,80}/)?.[0];return n?n.trim()+"\u2026":r.slice(0,80)+"\u2026"}function Dt(t,e){if(e==="casual")return{complexity:"trivial",estimatedSteps:0};if(e==="read")return{complexity:"simple",estimatedSteps:2};let r=0;(ug.test(t)||fg.test(t))&&(r+=3),dg.test(t)&&(r+=2);let n=t.split(/\s+/).length;return n>50&&(r+=1),n>100&&(r+=2),t.includes(`
176
+ `)&&(r+=1),El.test(t)&&(r+=1),e==="analysis"?r>=4?{complexity:"complex",estimatedSteps:8}:r>=2?{complexity:"moderate",estimatedSteps:4}:{complexity:"simple",estimatedSteps:2}:r>=7?{complexity:"epic",estimatedSteps:40}:r>=5?{complexity:"complex",estimatedSteps:20}:r>=3?{complexity:"moderate",estimatedSteps:10}:r>=1?{complexity:"simple",estimatedSteps:5}:{complexity:"simple",estimatedSteps:3}}function xs(t){let e=t.trim(),r=pg(e),n=[],s=Xh.test(e),i=Qh.test(e),o=s||i;s&&n.push("impl:en"),i&&n.push("impl:ar");let a=Zh.test(e)||eg.test(e);a&&n.push("continuity");let l=ig.test(e)||og.test(e);l&&n.push("one-step");let c=tg.test(e)||rg.test(e);c&&n.push("read");let u=ng.test(e)||sg.test(e);u&&n.push("analysis");let d=El.test(e)||cg.test(e);d&&n.push("eng-context");let m=/\b(project|repo|repository|codebase|workspace|file|src|package\.json|config)\b/i.test(e)||d;if(m&&n.push("project-ref"),(ag.test(e)||lg.test(e))&&!d&&!o&&!u){let{complexity:g,estimatedSteps:h}=Dt(e,"casual");return{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Social turn detected.",complexity:g,estimatedSteps:h,intent:Lt(e,r),language:r,confidence:.95,signals:n}}if(o||a||l||d&&e.length>20&&!c&&!u){let{complexity:g,estimatedSteps:h}=Dt(e,"implementation");return{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:a,oneStepDelivery:l,requiresProjectContext:!0,reason:a?"Continuation of previous work.":"Implementation task detected.",complexity:g,estimatedSteps:h,intent:Lt(e,r),language:r,confidence:.9,signals:n}}if(u&&!o){let{complexity:g,estimatedSteps:h}=Dt(e,"analysis");return{kind:"analysis",needsTools:m,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:m,reason:"Architecture or design analysis requested.",complexity:g,estimatedSteps:h,intent:Lt(e,r),language:r,confidence:.85,signals:n}}if(c||m){let{complexity:g,estimatedSteps:h}=Dt(e,"read");return{kind:"read",needsTools:m,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:m,reason:"Read-only or factual query.",complexity:g,estimatedSteps:h,intent:Lt(e,r),language:r,confidence:.8,signals:n}}let{complexity:p,estimatedSteps:f}=Dt(e,"analysis");return{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Default: analytical response.",complexity:p,estimatedSteps:f,intent:Lt(e,r),language:r,confidence:.6,signals:n}}function mg(t){if(!t.needsTools)return[{id:"respond",title:"Respond directly and clearly."}];if(t.kind==="read")return[{id:"inspect",title:"Inspect the minimum relevant files."},{id:"answer",title:"Answer precisely from observed facts."}];if(t.kind==="analysis")return[{id:"memory",title:"Check persistent memory for relevant past decisions."},{id:"inspect",title:"Inspect only the files needed for analysis."},{id:"reason",title:"Form a concise architectural recommendation."},{id:"answer",title:"Present the result clearly."}];let e=[];return e.push({id:"memory",title:"Check persistent memory for relevant project context."}),t.continuity&&e.push({id:"continuity",title:"Load existing project context \u2014 do not restart from zero."}),t.oneStepDelivery&&e.push({id:"delivery-contract",title:"One-pass delivery \u2014 no follow-up questions."}),e.push({id:"inspect",title:"Inspect the relevant files and project structure."}),(t.complexity==="complex"||t.complexity==="epic")&&e.push({id:"plan",title:"Form a concrete step-by-step implementation plan."}),e.push({id:"implement",title:"Apply the correct implementation using tools."}),e.push({id:"verify",title:"Verify: run build/tests, check for regressions."}),e.push({id:"memory-save",title:"Save key decisions to persistent memory."}),e.push({id:"answer",title:"Report: what was done, what was verified, what remains."}),e}function Al(t){let e=xs(t);return{input:t,profile:e,plan:mg(e)}}var Vl=C(require("readline")),de=C(require("fs")),re=C(require("path")),Kl=C(require("os"));var De=C(require("process")),Ol=De.stdout.isTTY===!0,hg=De.env.NO_COLOR!==void 0||De.env.TERM==="dumb",Rl=De.stdout.columns||100;Ol&&De.stdout.on("resize",()=>{Rl=De.stdout.columns||100});var ue=()=>Math.min(Math.max(Rl-4,60),110);function q(t,e){return!Ol||hg?t:`${e}${t}\x1B[0m`}var y={strong:t=>q(t,"\x1B[1;38;5;255m"),muted:t=>q(t,"\x1B[38;5;242m"),accent:t=>q(t,"\x1B[38;5;111m"),accentAlt:t=>q(t,"\x1B[38;5;147m"),info:t=>q(t,"\x1B[38;5;117m"),success:t=>q(t,"\x1B[38;5;114m"),warning:t=>q(t,"\x1B[38;5;179m"),error:t=>q(t,"\x1B[38;5;203m"),primary:t=>q(t,"\x1B[38;5;253m"),secondary:t=>q(t,"\x1B[38;5;247m"),border:t=>q(t,"\x1B[38;5;238m"),borderHi:t=>q(t,"\x1B[38;5;244m"),code:t=>q(t,"\x1B[38;5;222m"),lineNum:t=>q(t,"\x1B[38;5;241m"),dim:t=>q(t,"\x1B[2m"),bold:t=>q(t,"\x1B[1m"),green:t=>q(t,"\x1B[38;5;114m"),red:t=>q(t,"\x1B[38;5;203m"),yellow:t=>q(t,"\x1B[38;5;221m"),blue:t=>q(t,"\x1B[38;5;111m"),purple:t=>q(t,"\x1B[38;5;147m"),cyan:t=>q(t,"\x1B[38;5;152m"),orange:t=>q(t,"\x1B[38;5;209m"),white:t=>q(t,"\x1B[38;5;255m")};function ye(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function vs(t,e,r=" "){let n=ye(t);return n<e?t+r.repeat(e-n):t}var L={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2502",ml:"\u251C",mr:"\u2524",mt:"\u252C",mb:"\u2534",mc:"\u253C"};var Ss=C(require("os")),Ar=C(require("fs")),Er=C(require("path"));function gg(){let t=[Er.resolve(__dirname,"..","package.json"),Er.resolve(__dirname,"..","..","package.json"),Er.resolve(process.cwd(),"package.json")];for(let e of t)try{if(Ar.existsSync(e)){let r=JSON.parse(Ar.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var _s=gg(),Il=process.stdout.isTTY===!0;function z(t,e=L.h){return e.repeat(t)}function yg(t,e,r){let n=Math.max(1,r-ye(t)-ye(e));return t+" ".repeat(n)+e}function Pl(t,e){let r=Math.min(ue(),86),n=e.replace(Ss.homedir(),"~"),s=r-2,i=y.border(L.tl+z(s)+L.tr),o=y.border(L.ml+z(s)+L.mr),a=y.border(L.bl+z(s)+L.br),l=h=>{let b=Math.max(0,s-2-ye(h));return y.border(L.v)+" "+h+" ".repeat(b)+" "+y.border(L.v)},c=(h,b)=>y.border(L.v)+" "+yg(h,b,s-2)+" "+y.border(L.v),u=" H A B L A S ",d=Math.max(0,Math.floor((s-ye(u))/2)),m=y.border(L.v)+" ".repeat(d)+y.strong(u)+" ".repeat(s-d-ye(u))+y.border(L.v),p="single-agent engineering runtime",f=Math.max(0,Math.floor((s-p.length)/2)),g=y.border(L.v)+" ".repeat(f)+y.muted(p)+" ".repeat(s-f-p.length)+y.border(L.v);return["",i,m,g,o,c(y.muted("v"+_s),y.muted(t)),l(y.muted("workspace ")+y.secondary(n)),o,l(y.secondary("Type your task \xB7 /help for commands \xB7 Ctrl+C to cancel \xB7 Ctrl+C twice to exit")),a,""].join(`
177
+ `)}function Ll(t){let e=ue(),r=` Turn ${t} `,n=Math.floor((e-ye(r)-2)/2);return`
178
+ `+y.border(z(n))+y.borderHi(r)+y.border(z(e-n-ye(r)))+`
179
+ `}function xt(){return`
180
+ ${y.accent("\u25C6")} ${y.strong("Hablas")}`}function Dl(t){return`
181
+ ${y.accent("\xB7")} ${y.secondary(t)}`}function Fl(t,e){let r=wg[t]??"\u2699";return` ${y.muted(r+" ")}${y.muted(t)} ${y.dim(e)}`}function Nl(t,e,r){let n=r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`,s=t?y.success("\u2713"):y.error("\u2717"),i=e.slice(0,60).replace(/\n/g," "),o=e.length>60?"\u2026":"";return` ${s} ${y.dim(n+" ")}${y.muted(i+o)}`}var wg={read_file:"\u{1F4C4}",write_file:"\u270D",edit_file:"\u270F",patch_file:"\u{1FA79}",search_and_replace:"\u2194",append_to_file:"\u2193",delete_file:"\u{1F5D1}",move_file:"\u2192",create_dir:"\u{1F4C1}",list_dir:"\u{1F4C2}",get_file_info:"\u2139",search_codebase:"\u{1F50D}",run_command:"\u25B6",execute_code:"\u26A1",detect_bugs:"\u{1F41B}",web_search:"\u{1F310}",scrape_url:"\u26CF",extract_links:"\u{1F517}",download_asset:"\u2B07",read_pdf:"\u{1F4D5}",pdf_metadata:"\u{1F4CB}",search_image_candidates:"\u{1F5BC}",inspect_image:"\u{1F441}",remember:"\u{1F4BE}",recall:"\u{1F9E0}",search_memory:"\u{1F50E}",forget:"\u{1F5D1}",memory_stats:"\u{1F4CA}",git_status:"\u{1F4E1}",git_diff:"\xB1",git_log:"\u{1F4DC}",git_branch:"\u{1F33F}"};function Fe(t){return t.replace(/`([^`]+)`/g,(e,r)=>y.code(r)).replace(/\*\*([^*]+)\*\*/g,(e,r)=>y.strong(r)).replace(/\*([^*]+)\*/g,(e,r)=>y.secondary(r)).replace(/~~([^~]+)~~/g,(e,r)=>y.muted(r))}function Ml(t,e=2){let r=ue()-e-2,n=t.split(" "),s=[],i="";for(let o of n){let a=i.replace(/\x1b\[[0-9;]*m/g,""),l=o.replace(/\x1b\[[0-9;]*m/g,"");(a+" "+l).trim().length>r&&i?(s.push(" ".repeat(e)+i.trim()),i=o):i+=(i?" ":"")+o}return i.trim()&&s.push(" ".repeat(e)+i.trim()),s}function bg(t,e){let r=[],n=Math.max(28,ue()-6),s=e?` ${y.yellow(e)}`:"";r.push(` ${y.border(L.tl+z(n)+" ")}${s}`);let i=String(t.length).length;for(let o=0;o<t.length;o++){let a=y.lineNum(String(o+1).padStart(i));r.push(` ${y.border(L.v)} ${a} ${y.border("\u2502")} ${y.code(t[o])}`)}return r.push(` ${y.border(L.bl+z(n))}`),r}function xg(t){let r=t.map(c=>c.trim()).filter(Boolean).map(c=>c.split("|").slice(1,-1).map(u=>u.trim())).filter(c=>!c.every(u=>/^:?-{2,}:?$/.test(u)));if(!r.length)return[];let n=[];for(let c of r)c.forEach((u,d)=>{n[d]=Math.max(n[d]??0,ye(u))});let s=` ${y.border(L.tl+n.map(c=>z(c+2)).join(L.mt)+L.tr)}`,i=` ${y.border(L.ml+n.map(c=>z(c+2)).join(L.mc)+L.mr)}`,o=` ${y.border(L.bl+n.map(c=>z(c+2)).join(L.mb)+L.br)}`,a=(c,u=!1)=>{let d=c.map((m,p)=>{let f=u?y.strong(Fe(m)):Fe(m);return" "+vs(f,n[p])+" "});return` ${y.border(L.v)}${d.join(y.border(L.v))}${y.border(L.v)}`},l=[s,a(r[0],!0)];r.length>1&&l.push(i);for(let c of r.slice(1))l.push(a(c));return l.push(o),l}function Ft(t){let e=t.split(`
182
+ `),r=[],n=!1,s="",i=[],o=[],a=()=>{i.length&&(r.push(...bg(i,s)),i=[],s="")},l=()=>{o.length&&(r.push(...xg(o)),o=[])};for(let c of e){if(c.trimStart().startsWith("```")){l(),n?(a(),n=!1):(n=!0,s=c.trimStart().slice(3).trim());continue}if(n){i.push(c);continue}if(/^\s*\|.*\|\s*$/.test(c)){o.push(c);continue}else l();if(!c.trim()){r.push("");continue}if(/^---+$/.test(c.trim())){r.push(` ${y.border(z(Math.max(28,ue()-6)))}`);continue}let d=c.match(/^#\s+(.*)/),m=c.match(/^##\s+(.*)/),p=c.match(/^###\s+(.*)/);if(d){r.push(""),r.push(` ${y.strong(Fe(d[1]))}`),r.push(` ${y.border(z(Math.min(ye(d[1])+2,ue()-4)))}`);continue}if(m){r.push(""),r.push(` ${y.accent("\u25C6")} ${y.strong(Fe(m[1]))}`);continue}if(p){r.push(""),r.push(` ${y.secondary("\u25C7")} ${y.primary(Fe(p[1]))}`);continue}if(/^\s*>\s/.test(c)){let g=c.replace(/^\s*>\s?/,"");r.push(` ${y.border("\u258E")} ${y.secondary(Fe(g))}`);continue}let f=c.match(/^(\s*)([-*•]|\d+\.)\s+(.*)/);if(f){let g=f[1].length,b=/\d+\./.test(f[2])?y.accent(f[2]):y.accent("\u25B8"),w=Fe(f[3]),x=Ml(w,g+5);r.push(" ".repeat(g+2)+b+" "+(x[0]?.trimStart()??""));for(let S=1;S<x.length;S++)r.push(" ".repeat(g+5)+x[S].trimStart());continue}r.push(...Ml(Fe(c),2))}return l(),n&&a(),`
181
183
  `+r.join(`
182
184
  `)+`
183
- `}function El(){return["",` ${y.strong("Hablas commands")}`,"",` ${y.primary("/help")} ${y.muted("show help")}`,` ${y.primary("/status")} ${y.muted("show current runtime status")}`,` ${y.primary("/model")} ${y.muted("show or switch active model")}`,` ${y.primary("/models")} ${y.muted("list available models (supports search)")}`,` ${y.primary("/provider")} ${y.muted("inspect or switch provider")}`,` ${y.primary("/history")} ${y.muted("show recent turns")}`,` ${y.primary("/clear")} ${y.muted("clear the session")}`,` ${y.primary("/workspace")} ${y.muted("inspect workspace info")}`,` ${y.primary("/doctor")} ${y.muted("run diagnostics")}`,` ${y.primary("/version")} ${y.muted("show version")}`,` ${y.primary("/about")} ${y.muted("show product identity")}`,` ${y.primary("/exit")} ${y.muted("quit")}`,"",` ${y.accent("Memory commands")}`,` ${y.primary("/memory")} ${y.muted("show memory stats and recent entries")}`,` ${y.primary("/remember")} ${y.muted("/remember <key> <value> \u2014 store a fact")}`,` ${y.primary("/forget")} ${y.muted("/forget <key> \u2014 delete a memory")}`,` ${y.primary("/memory-search")} ${y.muted("/memory-search <query> \u2014 semantic memory search")}`,"",` ${y.accent("Tips")}`,` ${y.muted("\u2022 Tab completes commands and common file paths.")}`,` ${y.muted("\u2022 Use #filename to reference files quickly.")}`,` ${y.muted("\u2022 Ctrl+C cancels current work. Ctrl+C twice exits.")}`,""].join(`
184
- `)}function Al(t){let e=[` ${y.muted("provider")} ${y.info(t.provider)}`,` ${y.muted("model")} ${y.info(t.model)}`,` ${y.muted("workspace")} ${y.muted(t.workingDir.replace(ys.homedir(),"~"))}`,` ${y.muted("connected")} ${t.connected?y.success("yes"):y.error("no")}`,` ${y.muted("messages")} ${y.info(String(t.messageCount))}`,t.totalTokens!==void 0?` ${y.muted("tokens")} ${y.info(String(t.totalTokens))}`:""].filter(Boolean);return[""," "+y.strong("Status"),""].concat(e).concat([""]).join(`
185
- `)}function U(t){return` ${y.info(t)}`}function ve(t){return` ${y.success("\u2713")} ${t}`}function le(t){return` ${y.warning("\u26A0")} ${t}`}function je(t){return` ${y.error("\u2717")} ${t}`}function Ol(){return` ${y.strong("Hablas")} ${y.accent("v"+_l)}`}function Il(){return["",` ${y.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime`,"",` ${y.primary("Abdulmoin Hablas")} ${y.muted("Portfolio")}`,` ${y.muted(" https://portfolio-monopoly63s-projects.vercel.app/")}`,""].join(`
186
- `)}function Rl(t,e){let r=Math.max(50,Me()-8),n=`${t.toUpperCase()}`,s=bs(e,0),i=[];i.push(` ${y.border("\u256D"+"\u2500".repeat(r+2)+"\u256E")}`);let o=Math.max(0,r-n.length);i.push(` ${y.border("\u2502")} ${y.strong(n)}${" ".repeat(o)} ${y.border("\u2502")}`),i.push(` ${y.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(` ${y.border("\u2502")} ${y.accent(l)}${" ".repeat(c)} ${y.border("\u2502")}`)}return i.join(`
187
- `)}function Ml(t,e,r){let n=Math.max(50,Me()-8),s=t?y.success("\u2713 SUCCESS"):y.error("\u2717 FAILURE"),o=e.split(`
188
- `)[0]?.trim()||""||e.replace(/\s+/g," ").trim()||(t?"done":"failed"),a=`${s} ${o} ${y.muted(`(${r}ms)`)}`,l=bs(a,0),c=[];for(let u of l){let d=u.trim(),m=Math.max(0,n-d.replace(/\x1b\[[0-9;]*m/g,"").length);c.push(` ${y.border("\u2502")} ${d}${" ".repeat(m)} ${y.border("\u2502")}`)}return c.push(` ${y.border("\u2570"+"\u2500".repeat(n+2)+"\u256F")}`),c.join(`
189
- `)}var ze=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(){!ws||this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${y.accent(this.frames[this.index])} ${y.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(U(e))}};var Tr=Z.join(Ll.homedir(),".hablas","history"),Cr=500,sg=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),ig=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],og=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"]),jl=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],Er=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return Pl.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:Cr,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(-Cr),this.saveHistory()),r(n)})})}async confirm(e){return(await this.prompt(` ${y.warning("?")} ${e} ${y.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
185
+ `}function Te(t){return` ${y.success("\u2713")} ${y.primary(t)}`}function Ne(t){return` ${y.error("\u2717")} ${y.error(t)}`}function fe(t){return` ${y.warning("\u26A0")} ${y.warning(t)}`}function W(t){return` ${y.accent("\xB7")} ${y.secondary(t)}`}function Ul(){let t=Math.min(ue(),72),e=(r,n)=>` ${y.accent(vs(r,20))}${y.muted(n)}`;return["",` ${y.strong("Commands")}`,` ${y.border(z(t-4))}`,e("/help","show this help"),e("/status","runtime status \u2014 model, provider, tokens, tools"),e("/model [name]","show or switch active model"),e("/models [q]","list available models (optional search)"),e("/provider","inspect or switch provider"),e("/history","show recent conversation turns"),e("/clear","clear session history"),e("/workspace","inspect workspace files and git info"),e("/doctor","run diagnostics"),e("/version","show version"),e("/about","product identity and capabilities"),e("/exit","quit"),"",` ${y.strong("Memory")}`,` ${y.border(z(t-4))}`,e("/memory","show memory stats and recent entries"),e("/remember k v","store a persistent fact"),e("/forget k","delete a memory entry"),e("/memory-search q","search memory by keyword"),"",` ${y.strong("Tips")}`,` ${y.border(z(t-4))}`,` ${y.muted("\xB7")} ${y.secondary("Ctrl+C cancels the current operation")}`,` ${y.muted("\xB7")} ${y.secondary("Ctrl+C twice exits")}`,` ${y.muted("\xB7")} ${y.secondary("Memory persists across sessions in ~/.hablas/")}`,` ${y.muted("\xB7")} ${y.secondary("Git tools work automatically in repos")}`,""].join(`
186
+ `)}var jl=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Xe=class{label;timer=null;frame=0;active=!1;constructor(e){this.label=e}setLabel(e){this.label=e}start(){!Il||this.active||(this.active=!0,this.timer=setInterval(()=>{let e=jl[this.frame%jl.length];process.stdout.write(`\r ${y.accent(e)} ${y.secondary(this.label+"\u2026")} `),this.frame++},80))}stop(){this.active&&(this.active=!1,this.timer&&(clearInterval(this.timer),this.timer=null),Il&&process.stdout.write("\r\x1B[2K"))}};function ks(t){if(!t.toolsUsed.length)return"";let e=[""],r=Math.min(ue(),72);e.push(` ${y.border(z(r-4))}`);let n=t.durationMs<1e3?`${t.durationMs}ms`:`${(t.durationMs/1e3).toFixed(1)}s`,s=[];if(s.push(y.muted(`${t.toolsUsed.length} ops`)),t.filesChanged.length&&s.push(y.success(`${t.filesChanged.length} files`)),t.commandsRun.length&&s.push(y.accent(`${t.commandsRun.length} cmds`)),t.errors.length&&s.push(y.error(`${t.errors.length} errors`)),s.push(y.muted(n)),e.push(` ${s.join(y.muted(" \xB7 "))}`),t.filesChanged.length){for(let i of t.filesChanged.slice(0,6))e.push(` ${y.muted(" ")}${y.success("~")} ${y.secondary(i)}`);t.filesChanged.length>6&&e.push(` ${y.muted(" \u2026 and "+(t.filesChanged.length-6)+" more")}`)}return e.push(` ${y.border(z(r-4))}`),e.join(`
187
+ `)}function ql(t){let e=Math.min(ue(),72),r=(i,o)=>` ${y.secondary(i.padEnd(18))}${y.primary(o)}`,n=t.workingDir.replace(Ss.homedir(),"~"),s=["",` ${y.strong("Runtime status")}`,` ${y.border(z(e-4))}`,r("model",t.model),r("provider",t.provider),r("workspace",n),r("connection",t.connected?y.success("online"):y.warning("offline"))];return t.messageCount!==void 0&&s.push(r("messages",String(t.messageCount))),t.totalTokens!==void 0&&s.push(r("tokens used",String(t.totalTokens))),t.toolCount!==void 0&&s.push(r("tools",String(t.toolCount)+" registered")),t.autoMode!==void 0&&s.push(r("auto mode",t.autoMode?y.warning("on"):y.success("off"))),s.push(""),s.join(`
188
+ `)}function Bl(){return`
189
+ ${y.accent("Hablas")} ${y.muted("v"+_s)} ${y.secondary("\u2014 single-agent engineering runtime")}
190
+ `}function Hl(){let t=Math.min(ue(),72);return["",` ${y.strong("Hablas")} ${y.muted("v"+_s)}`,` ${y.border(z(t-4))}`,` ${y.secondary("single-agent engineering runtime")}`,"",` ${y.muted("\xB7")} ${y.primary("File I/O")} read, write, patch, search, move, delete`,` ${y.muted("\xB7")} ${y.primary("Shell")} run commands, execute code, detect bugs`,` ${y.muted("\xB7")} ${y.primary("Web")} search, scrape, PDF, image intelligence`,` ${y.muted("\xB7")} ${y.primary("Memory")} persistent cross-session knowledge store`,` ${y.muted("\xB7")} ${y.primary("Git")} status, diff, log, branch \u2014 read-only`,` ${y.muted("\xB7")} ${y.primary("Planning")} automatic execution plans for complex tasks`,` ${y.muted("\xB7")} ${y.primary("Compression")} smart context compression for long sessions`,"",` ${y.muted("by Abdulmoin Hablas")}`,""].join(`
191
+ `)}var Or=re.join(Kl.homedir(),".hablas","history"),Rr=500,vg=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Sg=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],_g=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"]),Wl=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],Ir=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return Vl.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:Rr,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(-Rr),this.saveHistory()),r(n)})})}async confirm(e){return(await this.prompt(` ${y.warning("?")} ${e} ${y.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
190
192
  ${y.error("\u26A0")} ${e}`),console.log(` ${y.muted("Type yes to confirm this dangerous action.")}
191
- `),(await this.prompt(` ${y.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let n=jl.filter(s=>s.startsWith(e));return[n.length?n:jl,e]}for(let n of ig)if(e.toLowerCase().includes(n)){let s=e.split(n).pop()??"";if(s&&!s.includes(" "))try{let i=Z.dirname(s)||".",o=Z.basename(s),a=Z.resolve(this.workingDir,i),l=ce.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(s))+Z.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=ce.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||sg.has(a.name))continue;let l=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(Z.join(e,a.name),l,n,s,i+1);else{let c=Z.extname(a.name).toLowerCase();(og.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&n.push(l)}}}catch{}}loadHistory(){try{ce.existsSync(Tr)&&(this.history=ce.readFileSync(Tr,"utf-8").split(`
192
- `).filter(Boolean).slice(-Cr))}catch{}}saveHistory(){try{let e=Z.dirname(Tr);ce.existsSync(e)||ce.mkdirSync(e,{recursive:!0}),ce.writeFileSync(Tr,this.history.slice(-Cr).join(`
193
- `),"utf-8")}catch{}}};var ag={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},lg=`
193
+ `),(await this.prompt(` ${y.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let n=Wl.filter(s=>s.startsWith(e));return[n.length?n:Wl,e]}for(let n of Sg)if(e.toLowerCase().includes(n)){let s=e.split(n).pop()??"";if(s&&!s.includes(" "))try{let i=re.dirname(s)||".",o=re.basename(s),a=re.resolve(this.workingDir,i),l=de.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(s))+re.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=de.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||vg.has(a.name))continue;let l=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(re.join(e,a.name),l,n,s,i+1);else{let c=re.extname(a.name).toLowerCase();(_g.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&n.push(l)}}}catch{}}loadHistory(){try{de.existsSync(Or)&&(this.history=de.readFileSync(Or,"utf-8").split(`
194
+ `).filter(Boolean).slice(-Rr))}catch{}}saveHistory(){try{let e=re.dirname(Or);de.existsSync(e)||de.mkdirSync(e,{recursive:!0}),de.writeFileSync(Or,this.history.slice(-Rr).join(`
195
+ `),"utf-8")}catch{}}};var kg={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},$g=`
194
196
  ## Reasoning Protocol
195
197
 
196
198
  Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
@@ -219,15 +221,15 @@ After receiving a tool result, think again:
219
221
  - One tool call per turn. Wait for the result before the next call.
220
222
  - If a tool fails, analyze the error in <thinking> before retrying.
221
223
  - When done, give a concise final answer WITHOUT <thinking> tags.
222
- `.trim(),cg=`
224
+ `.trim(),Tg=`
223
225
  ## Reasoning
224
226
  For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
225
227
  The user will NOT see thinking blocks. One tool call per turn.
226
- `.trim(),xs=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...ag,...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}
228
+ `.trim(),$s=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...kg,...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}
227
229
 
228
- ${cg}`:`${e}
230
+ ${Tg}`:`${e}
229
231
 
230
- ${lg}`}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(`
232
+ ${$g}`}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(`
231
233
 
232
234
  `).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`
233
235
  <self_eval>
@@ -250,18 +252,45 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
250
252
  }
251
253
  </self_eval>
252
254
  `.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(`
253
- `)}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 Pt(t){return new xs(t)}var ug=[{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}],Ss=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 ug)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(`
254
- `)}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 Lt(t=3){return new Ss(t)}var _e=C(require("fs")),Or=C(require("path")),Dl=C(require("os")),Ar=Or.join(Dl.homedir(),".hablas","model-formats.json");function fg(){try{if(_e.existsSync(Ar))return JSON.parse(_e.readFileSync(Ar,"utf-8"))}catch{}return{}}function dg(t){try{let e=Or.dirname(Ar);_e.existsSync(e)||_e.mkdirSync(e,{recursive:!0}),_e.writeFileSync(Ar,JSON.stringify(t,null,2),"utf-8")}catch{}}function Fl(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 Dt(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 pg(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function mg(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=Dt(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function hg(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=Dt(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function gg(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=Nl(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function Nl(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","search_image_candidates","inspect_image","remember","recall","search_memory","forget","memory_stats","git_status","git_diff","git_log","git_branch"];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,u;for(;(u=c.exec(o))!==null;){let m=u[1].toLowerCase(),p=u[2]??u[3]??u[4];l[m]=pg(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 yg(t){return Nl(t)}function wg(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=Dt(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function bg(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=Fl(t,n.index);if(s)try{let i=JSON.parse(s),o=Dt(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function xg(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=Fl(t,n.index);if(s)try{let i=JSON.parse(s),o=Dt(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function Sg(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,u;for(;(u=c.exec(i))!==null;){let d=u[1].trim(),m=u[2].trim();m==="true"?m=!0:m==="false"?m=!1:!isNaN(Number(m))&&m!==""&&(m=Number(m)),l[d]=m}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 u=c[1].trim(),d=c[2].trim();d==="true"?d=!0:d==="false"?d=!1:!isNaN(Number(d))&&d!==""&&(d=Number(d)),a[u]=d}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var vs=[{format:"xml_tool_call_wrapper",parse:gg},{format:"xml_prompt",parse:yg},{format:"xml_tags",parse:mg},{format:"xml_parameters",parse:Sg},{format:"hermes",parse:hg},{format:"markdown_json",parse:wg},{format:"function_call",parse:bg},{format:"json_object",parse:xg}],ks=class{registry;constructor(){this.registry=fg()}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=vs.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 vs){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 vs)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()},dg(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,`
255
+ `)}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 Nt(t){return new $s(t)}var Cg=[{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 Cg)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(`
256
+ `)}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 Ut(t=3){return new Ts(t)}var Ce=C(require("fs")),jr=C(require("path")),zl=C(require("os")),Mr=jr.join(zl.homedir(),".hablas","model-formats.json");function Eg(){try{if(Ce.existsSync(Mr))return JSON.parse(Ce.readFileSync(Mr,"utf-8"))}catch{}return{}}function Ag(t){try{let e=jr.dirname(Mr);Ce.existsSync(e)||Ce.mkdirSync(e,{recursive:!0}),Ce.writeFileSync(Mr,JSON.stringify(t,null,2),"utf-8")}catch{}}function Gl(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 qt(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 Og(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Rg(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=qt(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function Ig(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=qt(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function Mg(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=Jl(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function Jl(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","search_image_candidates","inspect_image","remember","recall","search_memory","forget","memory_stats","git_status","git_diff","git_log","git_branch"];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,u;for(;(u=c.exec(o))!==null;){let m=u[1].toLowerCase(),p=u[2]??u[3]??u[4];l[m]=Og(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 jg(t){return Jl(t)}function Pg(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=qt(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function Lg(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=Gl(t,n.index);if(s)try{let i=JSON.parse(s),o=qt(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function Dg(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=Gl(t,n.index);if(s)try{let i=JSON.parse(s),o=qt(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function Fg(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,u;for(;(u=c.exec(i))!==null;){let d=u[1].trim(),m=u[2].trim();m==="true"?m=!0:m==="false"?m=!1:!isNaN(Number(m))&&m!==""&&(m=Number(m)),l[d]=m}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 u=c[1].trim(),d=c[2].trim();d==="true"?d=!0:d==="false"?d=!1:!isNaN(Number(d))&&d!==""&&(d=Number(d)),a[u]=d}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var Cs=[{format:"xml_tool_call_wrapper",parse:Mg},{format:"xml_prompt",parse:jg},{format:"xml_tags",parse:Rg},{format:"xml_parameters",parse:Fg},{format:"hermes",parse:Ig},{format:"markdown_json",parse:Pg},{format:"function_call",parse:Lg},{format:"json_object",parse:Dg}],As=class{registry;constructor(){this.registry=Eg()}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=Cs.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 Cs){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 Cs)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()},Ag(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,`
255
257
 
256
258
  `),{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|search_image_candidates|inspect_image)[\s\S]*?(?:<<?\/[a-z_]+>>?|\/>)/gi,"").replace(/\n{3,}/g,`
257
259
 
258
- `)}},_s=null;function ql(){return _s||(_s=new ks),_s}var vg=600,_g=2e3,kg=12e3,Ul=2;function $g(t,e,r){let s=ql().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function Tg(t,e){return t==="write_file"&&typeof e.path=="string"?`create ${e.path}`:["edit_file","patch_file","search_and_replace"].includes(t)&&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):t==="remember"&&typeof e.key=="string"?`remember: ${String(e.key).slice(0,60)}`:t==="recall"&&typeof e.key=="string"?`recall: ${String(e.key).slice(0,60)}`:t==="search_memory"&&typeof e.query=="string"?`search memory: "${String(e.query).slice(0,50)}"`:t==="forget"&&typeof e.key=="string"?`forget: ${String(e.key).slice(0,60)}`:t==="memory_stats"?"check memory stats":t==="git_status"?"check git status":t==="git_diff"&&typeof e.path=="string"?`diff ${e.path}`:t==="git_diff"?"diff working tree":t==="git_log"&&typeof e.path=="string"?`log ${e.path}`:t==="git_log"?"recent commits":t==="git_branch"?"list branches":typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function Cg(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 Bl(t,e,r,n){let s=0,i=Date.now();for(;s<=Ul;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=Ul)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 $s(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:u}=t,d=t.reactEngine??Pt(),m=t.errorRecovery??Lt(),p=u?[]:n.getOllamaTools(),f=r.getModel(),h=t.maxIterations??vg,g=[],S=[],b=[],x=new Map,v="",E=0,_=!1;for(;E<h;){if(E++,c?.aborted)return{output:v,toolsUsed:Pe(g),toolResults:S,touchedFiles:Pe(b),iterations:E,success:!1,error:"Aborted",completedNaturally:_};let T=d.buildBudgetWarningPrompt();T&&s.addUserMessage(T,{priority:"critical",tags:["system-budget"]});let A;try{a.onModelStart?.(S.length>0?"Hablas is deciding the next step":"Hablas is thinking",e),A=await r.chatWithTools(s.getMessages(),p,c),a.onModelStop?.()}catch(X){a.onModelStop?.();let te=X;if(te.name==="AbortError"||c?.aborted)return{output:v,toolsUsed:Pe(g),toolResults:S,touchedFiles:Pe(b),iterations:E,success:!1,error:"Aborted",completedNaturally:_};if(E<=1){a.onNotice?.(`Transient model error: ${te.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(P=>setTimeout(P,1e3)),E--;continue}return a.onError?.(te.message??"Model request failed"),{output:v,toolsUsed:Pe(g),toolResults:S,touchedFiles:Pe(b),iterations:E,success:!1,error:te.message,completedNaturally:_}}let k=A.message?.content||"",M=A.message?.tool_calls,q=d.parseThinking(k);q.hasThinking&&(d.recordStep({thought:q.thinking}),o.debug({thinking:q.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:D,displayContent:H}=$g(M,k,f);if(H&&H.trim()&&(v=H,await a.onAssistantText?.(H,e)),D.length===0){s.addAssistantMessage(k,void 0,e.role),_=!0;break}s.addAssistantMessage(k,D,e.role);let z=D.length;for(let X=0;X<D.length;X++){let te=D[X];if(!te?.function?.name)continue;let P=te.function.name,L=te.function.arguments||{},qt=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(G=>G.name).join(", ")}`);continue}if(await l(P,qt,L)==="skip"){s.addToolMessage(`Tool ${P} was skipped by policy/user.`);break}let dc=Tg(P,L),wt=P==="read_file"?JSON.stringify({path:L.path||"",start:L.start_line||"",end:L.end_line||""}):"";if(P==="read_file"&&wt&&x.has(wt)){let G=x.get(wt)||"";s.addToolMessage(G),d.recordObservation(G.slice(0,300),"Reused cached file read");continue}g.push(P),typeof L.path=="string"&&b.push(L.path),typeof L.from=="string"&&b.push(L.from),typeof L.to=="string"&&b.push(L.to),a.onToolStart?.(P,dc,L),a.onToolCall?.(),d.recordStep({thought:q.hasThinking?`Executing: ${P}`:"",action:P,actionInput:L});let K=await Bl(n,P,L,o);a.onToolEnd?.(P,K.success,K.error||K.output,K.duration,L);let Le;if(K.success)Le=Hl(P,K.output),d.recordObservation(Le.slice(0,300)),S.push({tool:P,success:!0,summary:K.output.slice(0,150)});else{let G=K.error||"Unknown error",Ge=m.analyze(P,G,L);if(Le=m.buildRecoveryMessage(Ge,G),d.recordObservation(`FAILED: ${G}`,`Recovery: ${Ge.strategy} \u2014 ${Ge.suggestion}`),o.info({tool:P,errorClass:Ge.errorClass,strategy:Ge.strategy},"Error recovery analysis"),S.push({tool:P,success:!1,summary:G.slice(0,150)}),Ge.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let Je=await Bl(n,P,L,o);a.onToolEnd?.(P,Je.success,Je.output,Je.duration,L),Je.success&&(Le=Hl(P,Je.output),d.recordObservation(Le.slice(0,300),"Auto-retry succeeded"),S[S.length-1]={tool:P,success:!0,summary:Je.output.slice(0,150)})}}if(s.addToolMessage(Le),K.success&&P==="read_file"&&typeof L.path=="string"&&(i?.addFile(L.path,K.output),wt&&x.set(wt,Le)),K.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(P)&&typeof L.path=="string")for(let G of[...x.keys()])G.includes(`"path":"${String(L.path).replace(/\"/g,'\\"')}"`)&&x.delete(G);if(K.success&&P==="move_file")for(let G of[...x.keys()])(L.from&&G.includes(`"path":"${String(L.from).replace(/\"/g,'\\"')}"`)||L.to&&G.includes(`"path":"${String(L.to).replace(/\"/g,'\\"')}"`))&&x.delete(G);if(o.info({tool:P,success:K.success,durationMs:K.duration,retries:K.retries},"Tool executed"),!K.success&&Cg(K.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}z>1&&X<z-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return E>=h&&!_&&a.onNotice?.(`Reached max iterations (${h}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:v,toolsUsed:Pe(g),toolResults:S,touchedFiles:Pe(b),iterations:E,success:!0,completedNaturally:_}}function Pe(t){return[...new Set(t)]}function Hl(t,e){return t==="read_file"?e:t==="web_search"||t==="scrape_url"||t==="extract_links"||t==="read_pdf"?Ot(e,kg):Ot(e,_g)}function Wl(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 Vl(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="",s?.();for await(let u of e.streamChat(r.getMessages(),n))a+=u,i?.(u);return r.addAssistantMessage(a||""),o?.(),a}catch(u){if(l=u,u?.name==="AbortError"||n?.aborted)throw u;if(c===1)break}throw l||new Error("Text turn failed")}async function Ir(t,e){let r=vl(t),n=await pt(e.workingDir,e.config);if(e.session.updateSystemPrompt(mt(n,r.profile,e.workingDir)),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 ze("Hablas is thinking"),f=!1;p.start();try{let h=await Vl({client:e.client,session:e.session,onStart:()=>{p.start()},onChunk:g=>{f||(p.stop(),console.log(gt()),process.stdout.write(" "),f=!0),process.stdout.write(g)},onComplete:()=>{f&&process.stdout.write(`
259
- `)}});f||(p.stop(),console.log(gt()),console.log(jt(h)));return}catch(h){p.stop(),console.log(je(h?.message||"Text turn failed"));return}}let s=Pt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=Lt(3),o=[],a=new ze("Hablas is thinking"),l="",c=p=>["list_dir","read_file","search_codebase","get_file_info"].includes(p)?"Analyzing project structure":["web_search"].includes(p)?"Searching the web":["search_image_candidates","inspect_image","scrape_url","extract_links"].includes(p)?"Fetching web content":["download_asset"].includes(p)?"Downloading asset":["write_file","patch_file","edit_file","search_and_replace","append_to_file","move_file","create_dir","delete_file"].includes(p)?"Editing files":["run_command","execute_code","detect_bugs"].includes(p)?"Running verification":["remember","recall","search_memory","forget","memory_stats"].includes(p)?"Accessing memory":["git_status","git_diff","git_log","git_branch"].includes(p)?"Reading git history":"Working",u={onModelStart:p=>{a.stop(),a.setLabel(p),a.start()},onModelStop:()=>{a.stop()},onAssistantText:async p=>{o.push(p),r.profile.kind!=="implementation"&&(console.log(gt()),console.log(jt(p)))},onToolStart:(p,f)=>{a.stop();let h=c(p);h!==l&&(console.log(Cl(h)),l=h),console.log(Rl(p,f))},onToolEnd:(p,f,h,g)=>{console.log(Ml(f,h,g))},onNotice:(p,f)=>{console.log(f==="retry"?U(`Retrying: ${p}`):U(p))},onError:p=>{console.log(je(p))},onToolCall:()=>e.onToolCall?.()},d=Wl({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}),m=await $s({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:u,safetyPolicy:d,reactEngine:s,errorRecovery:i,skipTools:!1});r.profile.kind==="implementation"&&m.toolsUsed.length>0&&o.length>0&&(console.log(gt()),console.log(jt(o[o.length-1])));try{W().flush()}catch{}if(r.profile.kind==="implementation"&&m.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 $s({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...u,onAssistantText:async h=>{p.push(h)}},safetyPolicy:d,reactEngine:Pt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:Lt(3),skipTools:!1})).toolsUsed.length===0?console.log(je("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(gt()),console.log(jt(p[p.length-1])))}}var Ts=C(require("fs")),zl=C(require("path")),me=C(require("os")),Kl=require("child_process");async function Rr(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=zl.join(me.homedir(),".hablas");if(e.push({name:"Config directory",status:Ts.existsSync(s)?"ok":"warn",message:Ts.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=me.homedir();if(process.platform!=="win32"){let a=(0,Kl.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:`${me.platform()} ${me.arch()} \u2014 ${me.cpus().length} cores, ${Math.round(me.totalmem()/1024/1024/1024)}GB RAM`}),e}function Mr(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}`,u=l.name.padEnd(18);i.push(` ${c} ${u}${s}${l.message}${n}`)}let o=t.filter(l=>l.status==="error").length,a=t.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${r.error}${o} error(s) found \u2014 fix these for hablas to work properly${n}`):a>0?i.push(` ${r.warn}${a} warning(s) \u2014 hablas should work but check the items above${n}`):i.push(` ${r.ok}All checks passed \u2014 hablas is ready!${n}`),i.push(""),i.join(`
260
- `)}async function Gl(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(El());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Il());return;case"/version":console.log(Ol());return;case"/clear":e.session.clear(),console.log(ve("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(U("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(Al({model:e.client.getModel(),provider:He(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(U(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),Ze(e.config),console.log(ve(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=20,a=1,l="";if(s.length>0){let f=s[s.length-1],h=parseInt(f,10);!Number.isNaN(h)&&h>0?(a=h,l=s.slice(0,-1).join(" ").toLowerCase().trim()):l=s.join(" ").toLowerCase().trim()}let c=l?i.filter(f=>f.toLowerCase().includes(l)):i;if(c.length===0){console.log(le("No matching models found."));return}let u=Math.max(1,Math.ceil(c.length/o)),d=Math.min(Math.max(a,1),u),m=(d-1)*o,p=c.slice(m,m+o);console.log(""),console.log(U(`Models${l?` \xB7 search: ${l}`:""} \xB7 page ${d}/${u}`)),console.log(""),p.forEach((f,h)=>{let g=f===e.client.getModel();console.log(` ${String(m+h+1).padStart(2," ")}. ${f}${g?" * active":""}`)}),console.log(""),u>1&&console.log(U(`Use /models ${l?l+" ":""}${d<u?d+1:u} for next page.`)),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(U(`Provider: ${He(e.config)}`)),console.log(U(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?ve("Connection OK"):je("Connection failed"));return}if(i==="ollama")e.config.provider="ollama",e.config.apiUrl="",e.config.apiKey="";else if(i==="nvidia")e.config.provider="nvidia",e.config.apiUrl=ne.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=ne.defaultModel);else if(i==="custom"){if(!s[1]){console.log(le("Usage: /provider custom <url> [api-key]"));return}e.config.provider="custom",e.config.apiUrl=s[1],s[2]&&(e.config.apiKey=s[2])}else{console.log(le("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=nt(e.config);e.setClient(o),Ze(e.config),console.log(ve(`Provider switched to ${He(e.config)}`));return}case"/doctor":{let i=await Rr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Mr(i));return}case"/workspace":{console.log(""),console.log(_r(ft(e.workingDir))),console.log("");return}case"/memory":{let i=W().getStats(),o=W().getRecent(5);console.log(""),console.log(U(`Persistent memory \u2014 ${i.total??0} total entries`));let a=Object.entries(i).filter(([l])=>l!=="total");if(a.length>0)for(let[l,c]of a)console.log(U(` ${l}: ${c}`));if(o.length>0){console.log(U("Recent:"));for(let l of o)console.log(U(` \xB7 [${l.kind}] ${l.key.slice(0,60)}`))}console.log("");return}case"/remember":{if(s.length<2){console.log(le("Usage: /remember <key> <value>"));return}let i=s[0],o=s.slice(1).join(" ");W().remember({kind:"preference",key:`manual:${i}`,value:o,tags:["manual"],priority:"high"}),W().flush(),console.log(ve(`Remembered: ${i} = ${o.slice(0,60)}`));return}case"/forget":{if(s.length===0){console.log(le("Usage: /forget <key>"));return}let i=s.join(" "),o=W().forget(i)||W().forget(`manual:${i}`);W().flush(),console.log(o?ve(`Forgotten: ${i}`):le(`No memory found for: ${i}`));return}case"/memory-search":{if(s.length===0){console.log(le("Usage: /memory-search <query>"));return}let i=s.join(" "),o=W().search(i,{limit:8});if(o.length===0){console.log(U("No memories found."));return}console.log(U(`Found ${o.length} memories for "${i}":`));for(let a of o)console.log(U(` [${a.entry.kind}] ${a.entry.key.slice(0,55)} (${a.score.toFixed(2)})`)),console.log(U(` ${a.entry.value.replace(/\n/g," \u2014 ").slice(0,120)}`));return}default:console.log(le(`Unknown command: ${n}`))}}var ke=C(require("fs")),Cs=C(require("path"));function Es(t){let e=Cs.join(t,".hablas");return ke.existsSync(e)||ke.mkdirSync(e,{recursive:!0}),e}function Jl(t){return Cs.join(Es(t),"session.json")}function jr(t,e){let r=Jl(t);try{return ke.existsSync(r)?(e.fromJSON(ke.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function Ft(t,e){let r=Jl(t);try{ke.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}async function Ql(t,e){Ks();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=nt(t);Es(r);let s=new at(r,t),i=new lt(t),o=await pt(r,t),a=new ut(mt(o,gs("hello"),r),t.historySize,t.contextBudget);jr(r,a);let l=new Er(r);console.log($l(t.model,r));let c=new ze("Connecting");c.start();let u=await n.checkConnection();if(c.stop(),u){let g=await n.listModels();console.log(ve(`online \xB7 ${He(t)} \xB7 ${g.length} models available`))}else console.log(le(`offline \xB7 ${He(t)} \xB7 you can still inspect local files and switch provider with /provider`));Yl.existsSync(Xl.join(r,".git"))||console.log(U("workspace mode: standalone (no git repository detected)")),console.log(U("Hablas is ready.")),console.log("");let d=0,m=0,p=Date.now(),f=new AbortController,h=0;for(process.on("SIGINT",()=>{let g=Date.now();g-h<1500&&(console.log(""),console.log(U(`Session summary \xB7 turns=${d} \xB7 toolCalls=${m} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),h=g,f.abort(),f=new AbortController,console.log(""),console.log(le("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let S=(await l.prompt(" \u203A ")).trim();if(S){if(S.startsWith("/")){let b=await Gl(S,{config:t,client:n,setClient:x=>{n=x},session:a,workingDir:r});if(Ft(r,a),b==="quit")break;continue}d+=1,console.log(Tl(d)),f=new AbortController;try{await Ir(S,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{m+=1}}),Ft(r,a)}catch(b){if(b?.name==="AbortError")continue;console.log(je(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}hl(),l.close()}var Eg=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Ag=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,Og=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Ig=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,Rg=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,Mg=/\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,jg=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,Pg=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,Zl=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function ec(t){let e=t.trim(),r=e.toLowerCase(),n=Ag.test(r),s=Og.test(r),i=Ig.test(r)||Rg.test(r),o=Mg.test(r),a=jg.test(r),l=i||n||s||o&&e.length>18&&!Zl.test(r)&&!a,c=a&&!i&&!n&&!s,u=Pg.test(r)||o,d=!l&&!c&&(Zl.test(r)||e.endsWith("?"));return Eg.test(e)&&!u&&!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:u,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||u?{kind:"read",needsTools:u,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}async function tc(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=nt(e),i=new at(n,e),o=new lt(e),a=await pt(n,e),l=new ut(mt(a,ec(t)),e.historySize,e.contextBudget);jr(n,l),await Ir(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1}),Ft(n,l)}var Pr=C(require("fs")),Ke=C(require("path")),Lg=[{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"}],Dg=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Fg=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function Ng(t,e){let r=[],n=e.split(`
261
- `);for(let{pattern:s,name:i,severity:o}of Lg){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let c=e.substring(0,a.index).split(`
262
- `).length,u=n[c-1]||"";u.trim().startsWith("#")||u.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 qg(t,e){let r=[],n=e.split(`
263
- `),s=Ke.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 rc(t,e=[]){try{let r=Pr.readdirSync(t,{withFileTypes:!0});for(let n of r){if(Dg.has(n.name))continue;let s=Ke.join(t,n.name);if(n.isDirectory())rc(s,e);else if(n.isFile()){let i=Ke.extname(n.name);Fg.has(i)||e.push(s)}}}catch{}return e}function nc(t){let e=Date.now(),r=rc(t),n=[];for(let o of r)try{let a=Pr.readFileSync(o,"utf-8"),l=Ke.relative(t,o),c=Ng(l,a);n.push(...c);let u=qg(l,a);n.push(...u)}catch{}let s=Date.now()-e,i={critical:n.filter(o=>o.severity==="critical").length,high:n.filter(o=>o.severity==="high").length,medium:n.filter(o=>o.severity==="medium").length,low:n.filter(o=>o.severity==="low").length,info:n.filter(o=>o.severity==="info").length};return{issues:n,scannedFiles:r.length,duration:s,summary:i}}function sc(t){let e=[];if(e.push(`
260
+ `)}},Es=null;function Yl(){return Es||(Es=new As),Es}var Ng=600,Ug=2e3,qg=12e3,Xl=2;function Bg(t,e,r){let s=Yl().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function Hg(t,e){return t==="write_file"&&typeof e.path=="string"?`create ${e.path}`:["edit_file","patch_file","search_and_replace"].includes(t)&&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):t==="remember"&&typeof e.key=="string"?`remember: ${String(e.key).slice(0,60)}`:t==="recall"&&typeof e.key=="string"?`recall: ${String(e.key).slice(0,60)}`:t==="search_memory"&&typeof e.query=="string"?`search memory: "${String(e.query).slice(0,50)}"`:t==="forget"&&typeof e.key=="string"?`forget: ${String(e.key).slice(0,60)}`:t==="memory_stats"?"check memory stats":t==="git_status"?"check git status":t==="git_diff"&&typeof e.path=="string"?`diff ${e.path}`:t==="git_diff"?"diff working tree":t==="git_log"&&typeof e.path=="string"?`log ${e.path}`:t==="git_log"?"recent commits":t==="git_branch"?"list branches":typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function Wg(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 Ql(t,e,r,n){let s=0,i=Date.now();for(;s<=Xl;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=Xl)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 Os(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:u}=t,d=t.reactEngine??Nt(),m=t.errorRecovery??Ut(),p=u?[]:n.getOllamaTools(),f=r.getModel(),g=t.maxIterations??Ng,h=[],b=[],w=[],x=new Map,S="",E=0,_=!1;for(;E<g;){if(E++,c?.aborted)return{output:S,toolsUsed:Ue(h),toolResults:b,touchedFiles:Ue(w),iterations:E,success:!1,error:"Aborted",completedNaturally:_};let T=d.buildBudgetWarningPrompt();T&&s.addUserMessage(T,{priority:"critical",tags:["system-budget"]});let A;try{a.onModelStart?.(b.length>0?"Hablas is deciding the next step":"Hablas is thinking",e),A=await r.chatWithTools(s.getMessages(),p,c),a.onModelStop?.()}catch(ee){a.onModelStop?.();let se=ee;if(se.name==="AbortError"||c?.aborted)return{output:S,toolsUsed:Ue(h),toolResults:b,touchedFiles:Ue(w),iterations:E,success:!1,error:"Aborted",completedNaturally:_};if(E<=1){a.onNotice?.(`Transient model error: ${se.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(P=>setTimeout(P,1e3)),E--;continue}return a.onError?.(se.message??"Model request failed"),{output:S,toolsUsed:Ue(h),toolResults:b,touchedFiles:Ue(w),iterations:E,success:!1,error:se.message,completedNaturally:_}}let k=A.message?.content||"",M=A.message?.tool_calls,B=d.parseThinking(k);B.hasThinking&&(d.recordStep({thought:B.thinking}),o.debug({thinking:B.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:F,displayContent:K}=Bg(M,k,f);if(K&&K.trim()&&(S=K,await a.onAssistantText?.(K,e)),F.length===0){s.addAssistantMessage(k,void 0,e.role),_=!0;break}s.addAssistantMessage(k,F,e.role);let J=F.length;for(let ee=0;ee<F.length;ee++){let se=F[ee];if(!se?.function?.name)continue;let P=se.function.name,D=se.function.arguments||{},Wt=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(X=>X.name).join(", ")}`);continue}if(await l(P,Wt,D)==="skip"){s.addToolMessage(`Tool ${P} was skipped by policy/user.`);break}let Oc=Hg(P,D),St=P==="read_file"?JSON.stringify({path:D.path||"",start:D.start_line||"",end:D.end_line||""}):"";if(P==="read_file"&&St&&x.has(St)){let X=x.get(St)||"";s.addToolMessage(X),d.recordObservation(X.slice(0,300),"Reused cached file read");continue}h.push(P),typeof D.path=="string"&&w.push(D.path),typeof D.from=="string"&&w.push(D.from),typeof D.to=="string"&&w.push(D.to),a.onToolStart?.(P,Oc,D),a.onToolCall?.(),d.recordStep({thought:B.hasThinking?`Executing: ${P}`:"",action:P,actionInput:D});let Y=await Ql(n,P,D,o);a.onToolEnd?.(P,Y.success,Y.error||Y.output,Y.duration,D);let qe;if(Y.success)qe=Zl(P,Y.output),d.recordObservation(qe.slice(0,300)),b.push({tool:P,success:!0,summary:Y.output.slice(0,150)});else{let X=Y.error||"Unknown error",Ze=m.analyze(P,X,D);if(qe=m.buildRecoveryMessage(Ze,X),d.recordObservation(`FAILED: ${X}`,`Recovery: ${Ze.strategy} \u2014 ${Ze.suggestion}`),o.info({tool:P,errorClass:Ze.errorClass,strategy:Ze.strategy},"Error recovery analysis"),b.push({tool:P,success:!1,summary:X.slice(0,150)}),Ze.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let et=await Ql(n,P,D,o);a.onToolEnd?.(P,et.success,et.output,et.duration,D),et.success&&(qe=Zl(P,et.output),d.recordObservation(qe.slice(0,300),"Auto-retry succeeded"),b[b.length-1]={tool:P,success:!0,summary:et.output.slice(0,150)})}}if(s.addToolMessage(qe),Y.success&&P==="read_file"&&typeof D.path=="string"&&(i?.addFile(D.path,Y.output),St&&x.set(St,qe)),Y.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(P)&&typeof D.path=="string")for(let X of[...x.keys()])X.includes(`"path":"${String(D.path).replace(/\"/g,'\\"')}"`)&&x.delete(X);if(Y.success&&P==="move_file")for(let X of[...x.keys()])(D.from&&X.includes(`"path":"${String(D.from).replace(/\"/g,'\\"')}"`)||D.to&&X.includes(`"path":"${String(D.to).replace(/\"/g,'\\"')}"`))&&x.delete(X);if(o.info({tool:P,success:Y.success,durationMs:Y.duration,retries:Y.retries},"Tool executed"),!Y.success&&Wg(Y.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}J>1&&ee<J-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return E>=g&&!_&&a.onNotice?.(`Reached max iterations (${g}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:S,toolsUsed:Ue(h),toolResults:b,touchedFiles:Ue(w),iterations:E,success:!0,completedNaturally:_}}function Ue(t){return[...new Set(t)]}function Zl(t,e){return t==="read_file"?e:t==="web_search"||t==="scrape_url"||t==="extract_links"||t==="read_pdf"?jt(e,qg):jt(e,Ug)}function ec(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"}}var tc={kind:"understand",goal:"Understand the current codebase structure and relevant files",toolHints:["list_dir","read_file","search_codebase","git_status"],successCriteria:"Key files identified, architecture understood, no blind spots remain"},Vg={kind:"research",goal:"Research APIs, patterns, or documentation needed for this task",toolHints:["web_search","scrape_url"],successCriteria:"Needed documentation found, approach confirmed"},Kg={kind:"verify",goal:"Build, test, and lint the changes to confirm correctness",toolHints:["run_command","detect_bugs"],successCriteria:"Build passes, no new errors introduced"},zg={kind:"report",goal:"Deliver a clear, honest summary of what was done",toolHints:[],successCriteria:"User has a full picture of changes, verification results, and next steps"},Gg=0;function Jg(){return`step_${Date.now()}_${++Gg}`}function Ee(t,e,r={}){return{id:Jg(),stepNum:t,status:"pending",...e,...r}}function rc(t,e){let r=[],n=1,s=t.complexity==="epic",i=t.complexity==="complex"||s,o=/\b(api|sdk|library|package|npm|docs|documentation|latest|version)\b/i.test(e),a=/\b(build|compile|test|lint|run|verify|check|typecheck)\b/i.test(e)||i,l=t.kind==="implementation",c=t.continuity;if(l&&!c?r.push(Ee(n++,tc)):c&&r.push(Ee(n++,tc,{goal:"Review current state \u2014 what exists, what changed, what remains",toolHints:["git_status","git_diff","read_file","list_dir"]})),o&&r.push(Ee(n++,Vg)),i&&r.push(Ee(n++,{kind:"understand",goal:"Check memory for relevant past decisions and patterns",toolHints:["search_memory"],successCriteria:"Any relevant past context loaded and applied"})),s&&r.push(Ee(n++,{kind:"plan_detail",goal:"Break the implementation into logical file-level tasks before writing any code",toolHints:["list_dir","read_file"],successCriteria:"Clear file-by-file implementation sequence established"})),l){let u=s?"Execute file changes in planned order \u2014 one file at a time, verify each before moving on":"Implement the requested changes in the correct files";r.push(Ee(n++,{kind:"implement",goal:u,toolHints:["read_file","write_file","edit_file","patch_file","search_and_replace","run_command"],successCriteria:"All target files modified correctly with no syntax errors"}))}return(a||i)&&r.push(Ee(n++,Kg)),i&&r.push(Ee(n++,{kind:"commit",goal:"Store key architectural decisions in memory for future sessions",toolHints:["remember"],successCriteria:"Decision stored with a clear, searchable key"})),r.push(Ee(n++,zg)),{id:`plan_${Date.now()}`,intent:t.intent,complexity:t.complexity,steps:r,createdAt:Date.now(),activeStepIndex:0,totalSteps:r.length}}function nc(t){let e=t.steps.filter(s=>s.status==="pending"||s.status==="active"),r=t.steps.filter(s=>s.status==="done"),n=["\u2550\u2550\u2550 EXECUTION PLAN \u2550\u2550\u2550",`Complexity: ${t.complexity} \xB7 Goal: ${t.intent}`,`Progress: ${r.length}/${t.totalSteps} steps complete`,"","Remaining steps (execute in order):"];for(let s of e.slice(0,5)){let i=s.toolHints.length?` [${s.toolHints.slice(0,3).join(", ")}]`:"";n.push(` ${s.stepNum}. [${s.kind.toUpperCase()}] ${s.goal}${i}`),n.push(` \u2713 Done when: ${s.successCriteria}`)}if(e.length>5&&n.push(` \u2026 ${e.length-5} more steps after these`),r.length){n.push(""),n.push("Completed:");for(let s of r)n.push(` \u2713 ${s.stepNum}. ${s.goal}${s.notes?" \u2014 "+s.notes:""}`)}return n.push(""),n.push("RULE: Complete each step before moving to the next. Do not skip verification."),n.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),n.join(`
261
+ `)}function sc(t,e){let r=new Set(e);for(let s of t.steps){if(s.status!=="pending"&&s.status!=="active")continue;let i=new Set(s.toolHints);e.filter(a=>i.has(a)).length>0&&(s.status="active",(s.kind==="understand"&&(r.has("list_dir")||r.has("read_file")||r.has("git_status"))||s.kind==="research"&&r.has("web_search")||s.kind==="implement"&&(r.has("write_file")||r.has("edit_file")||r.has("patch_file")||r.has("search_and_replace"))||s.kind==="verify"&&r.has("run_command")||s.kind==="commit"&&r.has("remember")||s.kind==="plan_detail"&&(r.has("read_file")||r.has("list_dir"))||s.kind==="report")&&(s.status="done"))}let n=t.steps.findIndex(s=>s.status==="pending");t.activeStepIndex=n===-1?t.steps.length:n,t.steps.every(s=>s.status==="done"||s.status==="skipped")&&(t.completedAt=Date.now())}function Rs(t){let e=t.steps.filter(r=>r.status==="done"||r.status==="skipped").length;return{done:e,total:t.totalSteps,pct:Math.round(e/t.totalSteps*100)}}function Is(t){return t.split(`
262
+ `).length}function ic(t,e){return t.split(`
263
+ `).slice(-e).join(`
264
+ `)}function oc(t,e){return t.split(`
265
+ `).slice(0,e).join(`
266
+ `)}function Yg(t,e){let r=Is(t);if(r<=30)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let n=String(e.path??""),i=(t.match(/^export\s+(const|function|class|interface|type|enum)\s+(\w+)/gm)??[]).map(l=>l.split(/\s+/).pop()).filter(Boolean).slice(0,8),o=i.length?` \u2014 exports: ${i.join(", ")}`:"",a=`[file read: ${n} (${r} lines)${o}]`;return{original:t,compressed:a,savedChars:t.length-a.length,strategy:"file_read"}}function Xg(t,e){let r=t.split(`
267
+ `).filter(Boolean);if(r.length<=20)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let n=String(e.path??"."),s=r.filter(l=>!l.endsWith("/")).length,i=r.filter(l=>l.endsWith("/")).length,o=r.slice(0,5).join(", "),a=`[list_dir: ${n} \u2014 ${s} files, ${i} dirs. Sample: ${o}${r.length>5?", \u2026":""}]`;return{original:t,compressed:a,savedChars:t.length-a.length,strategy:"list_dir"}}function Qg(t,e){let r=t.split(`
268
+ `);if(r.length<=15)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let n=String(e.command??"").slice(0,60),s=ic(t,8),i=`[run_command: ${n}
269
+ \u2026 (${r.length} lines total, showing last 8):
270
+ ${s}]`;return{original:t,compressed:i,savedChars:t.length-i.length,strategy:"run_command"}}function Zg(t){if(t.length<=1e3)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let e=t.match(/https?:\/\/[^\s"')>]+/g)??[],r=[...new Set(e)].slice(0,5),s=`[web_search results:
271
+ Titles: ${t.split(`
272
+ `).filter(i=>i.trim().length>10&&i.trim().length<100&&!i.startsWith("http")).slice(0,5).join(" | ")}
273
+ URLs: ${r.join(`
274
+ `)}]`;return{original:t,compressed:s,savedChars:t.length-s.length,strategy:"web_search"}}function ey(t){let e=t.split(`
275
+ `);if(e.length<=40)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let r=e.filter(a=>a.startsWith("+++")||a.startsWith("---")||a.startsWith("diff --git")),n=[...new Set(r.map(a=>a.split(" ").pop()).filter(Boolean))].slice(0,8),s=e.filter(a=>a.startsWith("+")&&!a.startsWith("+++")).length,i=e.filter(a=>a.startsWith("-")&&!a.startsWith("---")).length,o=`[git_diff: ${n.join(", ")} \u2014 +${s} -${i} lines (${e.length} total diff lines)]`;return{original:t,compressed:o,savedChars:t.length-o.length,strategy:"git_diff"}}function ty(t){if(t.length<=500)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let e=oc(t,10)+(Is(t)>10?`
276
+ \u2026`:"");return{original:t,compressed:e,savedChars:t.length-e.length,strategy:"git_log"}}function ac(t,e,r={}){if(e.length<400)return{original:e,compressed:e,savedChars:0,strategy:"passthrough"};switch(t){case"read_file":return Yg(e,r);case"list_dir":return Xg(e,r);case"run_command":return Qg(e,r);case"web_search":return Zg(e);case"git_diff":return ey(e);case"git_log":return ty(e);default:if(e.length>2e3){let n=oc(e,10),s=ic(e,5),i=`${n}
277
+ \u2026 (compressed \u2014 ${Is(e)} lines) \u2026
278
+ ${s}`;return{original:e,compressed:i,savedChars:e.length-i.length,strategy:"generic_trim"}}return{original:e,compressed:e,savedChars:0,strategy:"passthrough"}}}async function lc(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="",s?.();for await(let u of e.streamChat(r.getMessages(),n))a+=u,i?.(u);return r.addAssistantMessage(a||""),o?.(),a}catch(u){if(l=u,u?.name==="AbortError"||n?.aborted)throw u;if(c===1)break}throw l||new Error("Text turn failed")}function ry(t){return["list_dir","read_file","get_file_info"].includes(t)?"Reading project":["search_codebase"].includes(t)?"Searching codebase":["web_search"].includes(t)?"Searching the web":["scrape_url","extract_links"].includes(t)?"Fetching web content":["search_image_candidates","inspect_image"].includes(t)?"Analyzing images":["download_asset"].includes(t)?"Downloading asset":["write_file","patch_file","edit_file","search_and_replace","append_to_file","move_file","create_dir","delete_file"].includes(t)?"Editing files":["run_command","execute_code","detect_bugs"].includes(t)?"Running commands":["remember","recall","search_memory","forget","memory_stats"].includes(t)?"Accessing memory":["git_status","git_diff","git_log","git_branch"].includes(t)?"Reading git":["read_pdf","pdf_metadata"].includes(t)?"Reading document":"Working"}function cc(t,e){let r=[],n=[],s=[];for(let i of t){if(["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file","move_file"].includes(i.tool)){let o=i.summary.replace(/^(create|modify|delete|move)\s+/,"");r.includes(o)||r.push(o)}["run_command","execute_code"].includes(i.tool)&&n.push(i.summary.slice(0,60)),i.success||s.push(`${i.tool}: ${i.summary.slice(0,80)}`)}return{toolsUsed:[...new Set(t.map(i=>i.tool))],filesChanged:r,commandsRun:n,durationMs:e,errors:s}}async function Pr(t,e){let n=Al(t).profile,s=Date.now(),i=await wt(e.workingDir,e.config),o=bt(i,n,e.workingDir);if((n.complexity==="complex"||n.complexity==="epic")&&n.needsTools)try{let b=V().search(n.intent,{limit:5});if(b.length>0){let w=b.map(x=>` - [${x.entry.key}] ${x.entry.value}`).join(`
279
+ `);o+=`
280
+
281
+ \u2550\u2550\u2550 RELEVANT MEMORY \u2550\u2550\u2550
282
+ Past decisions and preferences:
283
+ ${w}
284
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`}}catch{}let a=null;if(n.needsTools&&(n.complexity==="complex"||n.complexity==="epic")&&n.kind==="implementation"){a=rc(n,t);let h=nc(a);o+=`
285
+
286
+ ${h}`;let b=Rs(a);console.log(` ${y.accent("\u25C9")} ${y.secondary("Execution plan ready")} ${y.muted(`\xB7 ${b.total} steps \xB7 complexity: ${n.complexity}`)}`)}if(e.session.updateSystemPrompt(o),n.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context and do not restart from zero.]",{priority:"critical",tags:["runtime-note","continuity"]}),n.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:${n.kind}`]}),!n.needsTools){let h=new Xe("Thinking"),b=!1;h.start();try{let w=await lc({client:e.client,session:e.session,onStart:()=>h.start(),onChunk:x=>{b||(h.stop(),console.log(xt()),process.stdout.write(" "),b=!0),process.stdout.write(x)},onComplete:()=>{b&&process.stdout.write(`
287
+ `)}});b||(h.stop(),console.log(xt()),console.log(Ft(w)))}catch(w){h.stop(),console.log(Ne(w?.message||"Text turn failed"))}return}let l=Nt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),c=Ut(3),u=[],d=new Xe("Thinking"),m="",p={onModelStart:h=>{d.stop(),d.setLabel(h),d.start()},onModelStop:()=>d.stop(),onAssistantText:async h=>{u.push(h),n.kind!=="implementation"&&(console.log(xt()),console.log(Ft(h)))},onToolStart:(h,b)=>{d.stop();let w=ry(h);w!==m&&(console.log(Dl(w)),m=w),console.log(Fl(h,b))},onToolEnd:(h,b,w,x)=>{let S=ac(h,w),E=S.savedChars>200?S.compressed:w;console.log(Nl(b,E,x))},onNotice:(h,b)=>{console.log(b==="retry"?W(`Retrying: ${h}`):W(h))},onError:h=>console.log(Ne(h)),onToolCall:()=>e.onToolCall?.()},f=ec({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?h=>e.input.confirm(h):void 0,confirmDangerous:e.input?h=>e.input.confirmDangerous(h):void 0}),g=await Os({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:p,safetyPolicy:f,reactEngine:l,errorRecovery:c,skipTools:!1});if(a){sc(a,g.toolsUsed);let h=Rs(a);h.done>0&&console.log(`
288
+ ${y.success("\u2713")} ${y.muted(`Plan: ${h.done}/${h.total} steps complete`)}`)}if(n.kind==="implementation"&&g.toolsUsed.length>0&&u.length>0&&(console.log(xt()),console.log(Ft(u[u.length-1]))),g.toolsUsed.length>0){let h=Date.now()-s,b=cc(g.toolResults,h),w=ks(b);w&&console.log(w)}try{V().flush()}catch{}if(n.kind==="implementation"&&g.toolsUsed.length===0){e.session.addUserMessage("SYSTEM CORRECTION: This was an implementation request. You must use workspace tools and modify actual files. Retry now.",{priority:"critical",tags:["system-correction","force-tools"]});let h=[],b=await Os({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...p,onAssistantText:async w=>{h.push(w)}},safetyPolicy:f,reactEngine:Nt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:Ut(3),skipTools:!1});if(b.toolsUsed.length===0)console.log(Ne("Implementation request failed to enter a tool-execution path."));else if(h.length>0){console.log(xt()),console.log(Ft(h[h.length-1]));let w=cc(b.toolResults,Date.now()-s),x=ks(w);x&&console.log(x)}}}var Ms=C(require("fs")),uc=C(require("path")),we=C(require("os")),fc=require("child_process");async function Lr(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=uc.join(we.homedir(),".hablas");if(e.push({name:"Config directory",status:Ms.existsSync(s)?"ok":"warn",message:Ms.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=we.homedir();if(process.platform!=="win32"){let a=(0,fc.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:`${we.platform()} ${we.arch()} \u2014 ${we.cpus().length} cores, ${Math.round(we.totalmem()/1024/1024/1024)}GB RAM`}),e}function Dr(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}`,u=l.name.padEnd(18);i.push(` ${c} ${u}${s}${l.message}${n}`)}let o=t.filter(l=>l.status==="error").length,a=t.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${r.error}${o} error(s) found \u2014 fix these for hablas to work properly${n}`):a>0?i.push(` ${r.warn}${a} warning(s) \u2014 hablas should work but check the items above${n}`):i.push(` ${r.ok}All checks passed \u2014 hablas is ready!${n}`),i.push(""),i.join(`
289
+ `)}async function dc(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Ul());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Hl());return;case"/version":console.log(Bl());return;case"/clear":e.session.clear(),console.log(Te("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(W("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(ql({model:e.client.getModel(),provider:Ge(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(W(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),st(e.config),console.log(Te(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=20,a=1,l="";if(s.length>0){let f=s[s.length-1],g=parseInt(f,10);!Number.isNaN(g)&&g>0?(a=g,l=s.slice(0,-1).join(" ").toLowerCase().trim()):l=s.join(" ").toLowerCase().trim()}let c=l?i.filter(f=>f.toLowerCase().includes(l)):i;if(c.length===0){console.log(fe("No matching models found."));return}let u=Math.max(1,Math.ceil(c.length/o)),d=Math.min(Math.max(a,1),u),m=(d-1)*o,p=c.slice(m,m+o);console.log(""),console.log(W(`Models${l?` \xB7 search: ${l}`:""} \xB7 page ${d}/${u}`)),console.log(""),p.forEach((f,g)=>{let h=f===e.client.getModel();console.log(` ${String(m+g+1).padStart(2," ")}. ${f}${h?" * active":""}`)}),console.log(""),u>1&&console.log(W(`Use /models ${l?l+" ":""}${d<u?d+1:u} for next page.`)),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(W(`Provider: ${Ge(e.config)}`)),console.log(W(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Te("Connection OK"):Ne("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=oe.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=oe.defaultModel);else if(i==="custom"){if(!s[1]){console.log(fe("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(fe("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=lt(e.config);e.setClient(o),st(e.config),console.log(Te(`Provider switched to ${Ge(e.config)}`));return}case"/doctor":{let i=await Lr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Dr(i));return}case"/workspace":{console.log(""),console.log(Cr(gt(e.workingDir))),console.log("");return}case"/memory":{let i=V().getStats(),o=V().getRecent(5);console.log(""),console.log(W(`Persistent memory \u2014 ${i.total??0} total entries`));let a=Object.entries(i).filter(([l])=>l!=="total");if(a.length>0)for(let[l,c]of a)console.log(W(` ${l}: ${c}`));if(o.length>0){console.log(W("Recent:"));for(let l of o)console.log(W(` \xB7 [${l.kind}] ${l.key.slice(0,60)}`))}console.log("");return}case"/remember":{if(s.length<2){console.log(fe("Usage: /remember <key> <value>"));return}let i=s[0],o=s.slice(1).join(" ");V().remember({kind:"preference",key:`manual:${i}`,value:o,tags:["manual"],priority:"high"}),V().flush(),console.log(Te(`Remembered: ${i} = ${o.slice(0,60)}`));return}case"/forget":{if(s.length===0){console.log(fe("Usage: /forget <key>"));return}let i=s.join(" "),o=V().forget(i)||V().forget(`manual:${i}`);V().flush(),console.log(o?Te(`Forgotten: ${i}`):fe(`No memory found for: ${i}`));return}case"/memory-search":{if(s.length===0){console.log(fe("Usage: /memory-search <query>"));return}let i=s.join(" "),o=V().search(i,{limit:8});if(o.length===0){console.log(W("No memories found."));return}console.log(W(`Found ${o.length} memories for "${i}":`));for(let a of o)console.log(W(` [${a.entry.kind}] ${a.entry.key.slice(0,55)} (${a.score.toFixed(2)})`)),console.log(W(` ${a.entry.value.replace(/\n/g," \u2014 ").slice(0,120)}`));return}default:console.log(fe(`Unknown command: ${n}`))}}var Ae=C(require("fs")),js=C(require("path"));function Ps(t){let e=js.join(t,".hablas");return Ae.existsSync(e)||Ae.mkdirSync(e,{recursive:!0}),e}function pc(t){return js.join(Ps(t),"session.json")}function Fr(t,e){let r=pc(t);try{return Ae.existsSync(r)?(e.fromJSON(Ae.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function Bt(t,e){let r=pc(t);try{Ae.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}async function gc(t,e){ei();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=lt(t);Ps(r);let s=new dt(r,t),i=new pt(t),o=await wt(r,t),a=new ht(bt(o,xs("hello"),r),t.historySize,t.contextBudget);Fr(r,a);let l=new Ir(r);console.log(Pl(t.model,r));let c=new Xe("Connecting");c.start();let u=await n.checkConnection();if(c.stop(),u){let h=await n.listModels();console.log(Te(`online \xB7 ${Ge(t)} \xB7 ${h.length} models available`))}else console.log(fe(`offline \xB7 ${Ge(t)} \xB7 you can still inspect local files and switch provider with /provider`));mc.existsSync(hc.join(r,".git"))||console.log(W("workspace mode: standalone (no git repository detected)")),console.log(W("Hablas is ready.")),console.log("");let d=0,m=0,p=Date.now(),f=new AbortController,g=0;for(process.on("SIGINT",()=>{let h=Date.now();h-g<1500&&(console.log(""),console.log(W(`Session summary \xB7 turns=${d} \xB7 toolCalls=${m} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),g=h,f.abort(),f=new AbortController,console.log(""),console.log(fe("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let b=(await l.prompt(" \u203A ")).trim();if(b){if(b.startsWith("/")){let w=await dc(b,{config:t,client:n,setClient:x=>{n=x},session:a,workingDir:r});if(Bt(r,a),w==="quit")break;continue}d+=1,console.log(Ll(d)),f=new AbortController;try{await Pr(b,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{m+=1}}),Bt(r,a)}catch(w){if(w?.name==="AbortError")continue;console.log(Ne(w?.message||"Turn failed")),e.error(w,"interactive turn failed")}}}Sl(),l.close()}var ny=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,sy=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,iy=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,oy=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,ay=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,ly=/\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,cy=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,uy=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,yc=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function wc(t){let e=t.trim(),r=e.toLowerCase(),n=sy.test(r),s=iy.test(r),i=oy.test(r)||ay.test(r),o=ly.test(r),a=cy.test(r),l=i||n||s||o&&e.length>18&&!yc.test(r)&&!a,c=a&&!i&&!n&&!s,u=uy.test(r)||o,d=!l&&!c&&(yc.test(r)||e.endsWith("?"));return ny.test(e)&&!u&&!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:u,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||u?{kind:"read",needsTools:u,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}async function bc(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=lt(e),i=new dt(n,e),o=new pt(e),a=await wt(n,e),l=new ht(bt(a,wc(t)),e.historySize,e.contextBudget);Fr(n,l),await Pr(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1}),Bt(n,l)}var Nr=C(require("fs")),Qe=C(require("path")),fy=[{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"}],dy=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),py=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function my(t,e){let r=[],n=e.split(`
290
+ `);for(let{pattern:s,name:i,severity:o}of fy){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let c=e.substring(0,a.index).split(`
291
+ `).length,u=n[c-1]||"";u.trim().startsWith("#")||u.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 hy(t,e){let r=[],n=e.split(`
292
+ `),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 xc(t,e=[]){try{let r=Nr.readdirSync(t,{withFileTypes:!0});for(let n of r){if(dy.has(n.name))continue;let s=Qe.join(t,n.name);if(n.isDirectory())xc(s,e);else if(n.isFile()){let i=Qe.extname(n.name);py.has(i)||e.push(s)}}}catch{}return e}function vc(t){let e=Date.now(),r=xc(t),n=[];for(let o of r)try{let a=Nr.readFileSync(o,"utf-8"),l=Qe.relative(t,o),c=my(l,a);n.push(...c);let u=hy(l,a);n.push(...u)}catch{}let s=Date.now()-e,i={critical:n.filter(o=>o.severity==="critical").length,high:n.filter(o=>o.severity==="high").length,medium:n.filter(o=>o.severity==="medium").length,low:n.filter(o=>o.severity==="low").length,info:n.filter(o=>o.severity==="info").length};return{issues:n,scannedFiles:r.length,duration:s,summary:i}}function Sc(t){let e=[];if(e.push(`
264
293
  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(`
265
- `)}var yt=C(require("fs")),As=C(require("path")),oc=C(require("os")),Ug=As.join(oc.homedir(),".hablas"),ic=As.join(Ug,"analytics.json");function ac(){try{if(yt.existsSync(ic))return JSON.parse(yt.readFileSync(ic,"utf-8"))}catch{}return Bg()}function Bg(){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 lc(t){let e=[];e.push(`
294
+ `)}var vt=C(require("fs")),Ls=C(require("path")),kc=C(require("os")),gy=Ls.join(kc.homedir(),".hablas"),_c=Ls.join(gy,"analytics.json");function $c(){try{if(vt.existsSync(_c))return JSON.parse(vt.readFileSync(_c,"utf-8"))}catch{}return yy()}function yy(){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 Tc(t){let e=[];e.push(`
266
295
  \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(`
267
- `)}var cc=C(require("readline"));var Y="\x1B[36m",Lr="\x1B[32m",$e="\x1B[33m",j="\x1B[2m",Te="\x1B[1m",$="\x1B[0m",Hg="\x1B[35m";function V(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function Wg(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var Nt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function uc(t){let e=cc.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${Te}${Y} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${$}`),console.log(`${Te}${Y} hablas \u2014 Setup Wizard${$}`),console.log(`${j} Configure your AI provider and model${$}`),console.log(`${Te}${Y} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${$}`),console.log(),console.log(`${Te} Choose your setup:${$}`),console.log(),console.log(` ${Hg}${Te}1${$}. ${Te}Hablas Integrated Engine${$} ${Lr}(instant \u2014 no setup needed)${$}`),console.log(` ${j}Pre-configured cloud AI, ready to use immediately${$}`),console.log(),console.log(` ${Y}${Te}2${$}. ${Te}Custom Provider${$} ${j}(bring your own API key)${$}`),console.log(` ${j}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${$}`),console.log(),(await V(e,` ${j}Your choice (1-2):${$} `)).trim()){case"1":{t.provider=Nt.provider,t.apiUrl=Nt.apiUrl,t.apiKey=Wg(),t.model=Nt.model,Ze(t),console.log(),console.log(`${Lr} \u2713 Hablas Integrated Engine activated!${$}`),console.log(`${j} Model: ${Nt.model}${$}`),console.log(`${j} API: ${Nt.apiUrl}${$}`),console.log(`${j} No API key needed \u2014 everything is pre-configured.${$}`);break}case"2":{switch(console.log(),console.log(`${j} Select your provider:${$}`),console.log(` ${Y}a${$}. Ollama (local, free, private)`),console.log(` ${Y}b${$}. OpenAI API`),console.log(` ${Y}c${$}. Groq (fast, free tier)`),console.log(` ${Y}d${$}. OpenRouter (many models)`),console.log(` ${Y}e${$}. Together AI`),console.log(` ${Y}f${$}. DeepSeek`),console.log(` ${Y}g${$}. Custom OpenAI-compatible API`),console.log(` ${Y}h${$}. NVIDIA NIM (powerful cloud models)`),console.log(),(await V(e,` ${j}Your choice (a-h):${$} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await V(e,` ${j}Ollama host [http://localhost:11434]:${$} `)).trim(),i=(await V(e,` ${j}Model [qwen2.5-coder:7b]:${$} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await V(e,` ${j}OpenAI API Key (sk-...):${$} `)).trim(),i=(await V(e,` ${j}Model [gpt-4o]:${$} `)).trim();if(!s){console.log(`${$e} \u26A0 No key provided \u2014 cancelled${$}`),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 V(e,` ${j}Groq API Key (gsk_...):${$} `)).trim(),i=(await V(e,` ${j}Model [llama-3.3-70b-versatile]:${$} `)).trim();if(!s){console.log(`${$e} \u26A0 No key provided \u2014 cancelled${$}`),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 V(e,` ${j}OpenRouter API Key (sk-or-...):${$} `)).trim(),i=(await V(e,` ${j}Model [anthropic/claude-3.5-sonnet]:${$} `)).trim();if(!s){console.log(`${$e} \u26A0 No key provided \u2014 cancelled${$}`),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 V(e,` ${j}Together API Key:${$} `)).trim(),i=(await V(e,` ${j}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${$} `)).trim();if(!s){console.log(`${$e} \u26A0 No key provided \u2014 cancelled${$}`),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 V(e,` ${j}DeepSeek API Key:${$} `)).trim(),i=(await V(e,` ${j}Model [deepseek-chat]:${$} `)).trim();if(!s){console.log(`${$e} \u26A0 No key provided \u2014 cancelled${$}`),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 V(e,` ${j}API base URL:${$} `)).trim(),i=(await V(e,` ${j}API key (optional):${$} `)).trim(),o=(await V(e,` ${j}Model ID:${$} `)).trim();if(!s){console.log(`${$e} \u26A0 URL is required \u2014 cancelled${$}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await V(e,` ${j}NVIDIA API Key (nvapi-...):${$} `)).trim();if(!s){console.log(`${$e} \u26A0 No key provided \u2014 cancelled${$}`),console.log(`${j} Get your key at: https://build.nvidia.com/${$}`),e.close();return}console.log(),console.log(`${j} Available NVIDIA models:${$}`),ne.models.forEach((a,l)=>{console.log(` ${Y}${l+1}${$}. ${a}`)}),console.log();let i=(await V(e,` ${j}Model number [1]:${$} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=ne.apiUrl,t.apiKey=s,t.model=ne.models[o]||ne.defaultModel;break}default:console.log(`${$e} \u26A0 Invalid choice${$}`),e.close();return}Ze(t),console.log(),console.log(`${Lr} \u2713 Custom provider configured successfully${$}`),console.log(`${j} Provider: ${t.provider}${$}`),console.log(`${j} Model: ${t.model}${$}`);break}default:console.log(`${$e} \u26A0 Invalid choice \u2014 please select 1 or 2${$}`),e.close();return}console.log(),console.log(`${Te}${Lr} \u2713 Setup complete!${$}`),console.log(`${j} Use ${Y}hablas${$}${j} for interactive mode or ${Y}hablas run "..."${$}${j} for one-shot execution.${$}`),console.log(),e.close()}var fc=oa(),ee=new Vs;ee.name("hablas").description(`Hablas CLI v${fc} \u2014 single-agent engineering runtime for the terminal.`).version(fc).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");ee.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=ee.opts(),r=Qe({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=Jn(r);await tc(t,r,n)});ee.command("doctor").description("Run system diagnostics").action(async()=>{let t=ee.opts(),e=Qe({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await Rr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(Mr(r))});ee.command("info").description("Show workspace information").action(async()=>{let t=ee.opts(),e=Qe({project:t.project});console.log(""),console.log(_r(ft(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});ee.command("security").description("Run a security scan on the current project").action(async()=>{let t=ee.opts(),e=Qe({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(sc(nc(r)))});ee.command("stats").description("Show local usage statistics").action(async()=>{console.log(lc(ac()))});ee.action(async()=>{let t=ee.opts(),e=Qe({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 uc(e);return}let r=Jn(e);await Ql(e,r)});ee.parse();
296
+ `)}var Cc=C(require("readline"));var Z="\x1B[36m",Ur="\x1B[32m",Oe="\x1B[33m",j="\x1B[2m",Re="\x1B[1m",$="\x1B[0m",wy="\x1B[35m";function G(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function by(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var Ht={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function Ec(t){let e=Cc.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${Re}${Z} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${$}`),console.log(`${Re}${Z} hablas \u2014 Setup Wizard${$}`),console.log(`${j} Configure your AI provider and model${$}`),console.log(`${Re}${Z} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${$}`),console.log(),console.log(`${Re} Choose your setup:${$}`),console.log(),console.log(` ${wy}${Re}1${$}. ${Re}Hablas Integrated Engine${$} ${Ur}(instant \u2014 no setup needed)${$}`),console.log(` ${j}Pre-configured cloud AI, ready to use immediately${$}`),console.log(),console.log(` ${Z}${Re}2${$}. ${Re}Custom Provider${$} ${j}(bring your own API key)${$}`),console.log(` ${j}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${$}`),console.log(),(await G(e,` ${j}Your choice (1-2):${$} `)).trim()){case"1":{t.provider=Ht.provider,t.apiUrl=Ht.apiUrl,t.apiKey=by(),t.model=Ht.model,st(t),console.log(),console.log(`${Ur} \u2713 Hablas Integrated Engine activated!${$}`),console.log(`${j} Model: ${Ht.model}${$}`),console.log(`${j} API: ${Ht.apiUrl}${$}`),console.log(`${j} No API key needed \u2014 everything is pre-configured.${$}`);break}case"2":{switch(console.log(),console.log(`${j} Select your provider:${$}`),console.log(` ${Z}a${$}. Ollama (local, free, private)`),console.log(` ${Z}b${$}. OpenAI API`),console.log(` ${Z}c${$}. Groq (fast, free tier)`),console.log(` ${Z}d${$}. OpenRouter (many models)`),console.log(` ${Z}e${$}. Together AI`),console.log(` ${Z}f${$}. DeepSeek`),console.log(` ${Z}g${$}. Custom OpenAI-compatible API`),console.log(` ${Z}h${$}. NVIDIA NIM (powerful cloud models)`),console.log(),(await G(e,` ${j}Your choice (a-h):${$} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await G(e,` ${j}Ollama host [http://localhost:11434]:${$} `)).trim(),i=(await G(e,` ${j}Model [qwen2.5-coder:7b]:${$} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await G(e,` ${j}OpenAI API Key (sk-...):${$} `)).trim(),i=(await G(e,` ${j}Model [gpt-4o]:${$} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),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 G(e,` ${j}Groq API Key (gsk_...):${$} `)).trim(),i=(await G(e,` ${j}Model [llama-3.3-70b-versatile]:${$} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),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 G(e,` ${j}OpenRouter API Key (sk-or-...):${$} `)).trim(),i=(await G(e,` ${j}Model [anthropic/claude-3.5-sonnet]:${$} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),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 G(e,` ${j}Together API Key:${$} `)).trim(),i=(await G(e,` ${j}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${$} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),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 G(e,` ${j}DeepSeek API Key:${$} `)).trim(),i=(await G(e,` ${j}Model [deepseek-chat]:${$} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),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 G(e,` ${j}API base URL:${$} `)).trim(),i=(await G(e,` ${j}API key (optional):${$} `)).trim(),o=(await G(e,` ${j}Model ID:${$} `)).trim();if(!s){console.log(`${Oe} \u26A0 URL is required \u2014 cancelled${$}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await G(e,` ${j}NVIDIA API Key (nvapi-...):${$} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),console.log(`${j} Get your key at: https://build.nvidia.com/${$}`),e.close();return}console.log(),console.log(`${j} Available NVIDIA models:${$}`),oe.models.forEach((a,l)=>{console.log(` ${Z}${l+1}${$}. ${a}`)}),console.log();let i=(await G(e,` ${j}Model number [1]:${$} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=oe.apiUrl,t.apiKey=s,t.model=oe.models[o]||oe.defaultModel;break}default:console.log(`${Oe} \u26A0 Invalid choice${$}`),e.close();return}st(t),console.log(),console.log(`${Ur} \u2713 Custom provider configured successfully${$}`),console.log(`${j} Provider: ${t.provider}${$}`),console.log(`${j} Model: ${t.model}${$}`);break}default:console.log(`${Oe} \u26A0 Invalid choice \u2014 please select 1 or 2${$}`),e.close();return}console.log(),console.log(`${Re}${Ur} \u2713 Setup complete!${$}`),console.log(`${j} Use ${Z}hablas${$}${j} for interactive mode or ${Z}hablas run "..."${$}${j} for one-shot execution.${$}`),console.log(),e.close()}var Ac=pa(),ne=new Qs;ne.name("hablas").description(`Hablas CLI v${Ac} \u2014 single-agent engineering runtime for the terminal.`).version(Ac).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");ne.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=ne.opts(),r=nt({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=Zn(r);await bc(t,r,n)});ne.command("doctor").description("Run system diagnostics").action(async()=>{let t=ne.opts(),e=nt({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await Lr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(Dr(r))});ne.command("info").description("Show workspace information").action(async()=>{let t=ne.opts(),e=nt({project:t.project});console.log(""),console.log(Cr(gt(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});ne.command("security").description("Run a security scan on the current project").action(async()=>{let t=ne.opts(),e=nt({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(Sc(vc(r)))});ne.command("stats").description("Show local usage statistics").action(async()=>{console.log(Tc($c()))});ne.action(async()=>{let t=ne.opts(),e=nt({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 Ec(e);return}let r=Zn(e);await gc(e,r)});ne.parse();