hablas-ai 2.2.11 → 2.2.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +59 -59
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
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
|
|
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
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(`
|
|
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
7
|
|.{1,${a-1}}([${m}]|$)|[^${m}]+?([${m}]|$)`,"g"),f=c.match(p)||[];return l+f.map((h,g)=>h===`
|
|
8
8
|
`?"":(g>0?u:"")+h.trimEnd()).join(`
|
|
9
|
-
`)}};Rs.Help=
|
|
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?`
|
|
10
10
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
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
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}'.
|
|
@@ -20,48 +20,48 @@ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
20
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
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.
|
|
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:
|
|
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
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:Uc}=tn(),{seen:rn}=Uc,{toString:qc}=Object.prototype;function nn(t){if(!Zs(t))return t;t[rn]=void 0;let e=Object.create(Nc);e.type=qc.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((vy,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((Sy,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"),vu=Symbol("pino.stringifiers"),Su=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:vu,endSym:Su,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 vi=bi(),{redactFmtSym:Pu,wildcardFirstSym:Jt}=et(),dn=/[^.[\]]+|\[([^[\]]*?)\]/g,Si="[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]:vi({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]=vi({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:Si},t;let{paths:e,censor:r=Si,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()}`,Uu=()=>`,"time":${Math.round(Date.now()/1e3)}`,qu=()=>`,"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:Uu,isoTime:qu,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,v)=>{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(S){this.release(S)}else setTimeout(h,Yt);else this._writing=!1,this.emit("error",g);return}this.emit("write",v);let b=gn(this._writingBuf,this._len,v);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){h();return}try{do{let S=f(),E=gn(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&&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(){Ui("exit")}function mf(){Ui("beforeExit")}function Ui(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 qi(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){qi("exit",t,e)}function yf(t,e){qi("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 vf(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:vf}});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:Sf}=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 vt=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?vt:global.WeakRef||vt,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:Sf},...n}}});return o.stream=new vt(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 vn=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 Sn(this,new Error("the worker has exited")),!1;if(this[w].ending)return Sn(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 Sn(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,Sn(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=vn});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:Uf}=require("node:url"),qf=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=Uf(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(),qf(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 v=g==="node:repl"?process.cwd()+Nf:g;h=Lf(v).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,So)=>{"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:vo,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[vo],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 S=En(b);g+=","+S+":"+f}let v="";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)),v=',"'+d+'":'+f;break;case"string":f=(b||En)(f),v=',"'+d+'":'+f;break;default:f=(b||s)(f,i),v=',"'+d+'":'+f}}return this[rd]&&g?p+this[id]+g.slice(1)+"}"+v+a:p+g+v+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[vo].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}So.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:vd,levelValSym:In,useOnlyCustomLevelsSym:Sd,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[vd]=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[Sd],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((qy,Po)=>{"use strict";var{EventEmitter:Nd}=require("node:events"),{lsCacheSym:Ud,levelValSym:qd,setLevelSym:Ln,getLevelSym:Ao,chindingsSym:or,mixinSym:Bd,asJsonSym:Io,writeSym:Hd,mixinMergeStrategySym:Wd,timeSym:Vd,timeSliceIndexSym:zd,streamSym:Ro,serializersSym:Ue,formattersSym:St,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[qd]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[Dn]},get[Symbol.toStringTag](){return"Pino"},[Ud]: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[Ue],n=this[St],s=Object.create(this);if(e==null)return s[St].bindings!==ir&&(s[St]=Pn(n.level,ir,n.log)),s[or]=Fn(s,t),this.onChild!==Mo&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[Ue]=Object.create(null);for(let c in r)s[Ue][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];s[Ue][c]=r[c]}for(let c in e.serializers)s[Ue][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];s[Ue][c]=e.serializers[c]}}else s[Ue]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;s[St]=Pn(a||n.level,l||ir,c||n.log)}else s[St]=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 Uo=R((Bn,No)=>{"use strict";var{hasOwnProperty:_t}=Object.prototype,Be=qn();Be.configure=qn;Be.stringify=Be;Be.default=Be;Bn.stringify=Be;Bn.configure=qn;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 Un(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 vp(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 Sp(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 qe(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 qn(t){t={...t};let e=$p(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=vp(t),n=_p(t,"bigint"),s=Sp(t),i=typeof s=="function"?s:void 0,o=Fo(t,"maximumDepth"),a=Fo(t,"maximumBreadth");function l(p,f,h,g,v,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 S="",E=",",_=b;if(Array.isArray(x)){if(x.length===0)return"[]";if(o<h.length+1)return'"[Array]"';h.push(x),v!==""&&(b+=v,S+=`
|
|
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
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,
|
|
28
|
-
${_}`),h.pop(),`[${
|
|
29
|
-
${b}`,k=" ");let
|
|
30
|
-
${b}${
|
|
31
|
-
${_}`),h.pop(),`{${
|
|
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
32
|
${b}`,E=`,
|
|
33
|
-
${b}`);let A=Math.min(f.length,a),k=0;for(;k<A-1;k++){let
|
|
34
|
-
${x}`),h.pop(),`[${
|
|
35
|
-
${b}`,_=" ");let T="";for(let A of g){let k=c(A,f[A],h,g,
|
|
36
|
-
${b}${
|
|
37
|
-
${x}`),h.pop(),`{${
|
|
38
|
-
${
|
|
39
|
-
${
|
|
40
|
-
${b}`,h.pop(),`[${k}]`}let x=Object.keys(f),
|
|
41
|
-
${
|
|
42
|
-
${
|
|
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="",
|
|
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
|
|
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
|
|
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
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(
|
|
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
|
|
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=
|
|
50
|
-
`);if(x.lines=
|
|
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(`
|
|
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
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
|
-
`),
|
|
55
|
-
... [Partial read. Total lines: ${
|
|
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}
|
|
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,
|
|
58
|
-
${
|
|
59
|
-
`),
|
|
60
|
-
`),T=[...
|
|
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
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,
|
|
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
|
|
64
|
-
`,l.isDirectory()){let m=e+(c?" ":"\u2502 ");o+=await
|
|
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+=`
|
|
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(`
|
|
@@ -74,10 +74,10 @@ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Prom
|
|
|
74
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
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
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
|
|
78
|
-
`)}function
|
|
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
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=
|
|
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)}
|
|
81
81
|
|
|
82
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,`
|
|
83
83
|
`),e=e.replace(/<(br|hr)\s*\/?>/gi,`
|
|
@@ -93,13 +93,13 @@ ${"#".repeat(parseInt(n))} ${s.replace(/<[^>]+>/g,"").trim()}
|
|
|
93
93
|
`);return{success:!0,output:`Found ${o.length} links:
|
|
94
94
|
|
|
95
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")),
|
|
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(`
|
|
97
97
|
`).replace(/\r\n/g,`
|
|
98
98
|
`).replace(/\n{3,}/g,`
|
|
99
99
|
|
|
100
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
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
|
|
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)
|
|
103
103
|
|
|
104
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)+`
|
|
105
105
|
|
|
@@ -131,25 +131,25 @@ Rules:
|
|
|
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,
|
|
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,
|
|
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}
|
|
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
|
|
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:
|
|
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: ${
|
|
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)}
|
|
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
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
|
|
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=
|
|
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(`
|
|
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(!
|
|
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(!
|
|
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(`
|
|
153
153
|
`);return`- ${r.name} [${r.safety}]: ${r.description}
|
|
154
154
|
${n}`}).join(`
|
|
155
155
|
|
|
@@ -172,8 +172,8 @@ ${c.content}`),a+=c.tokenCount}return l.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,
|
|
176
|
-
`)&&(r+=1),
|
|
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
177
|
`)}function Tl(t){return`
|
|
178
178
|
`+tg(`${y.accent("\u25C6")} ${y.strong("Turn #"+t)}`)}function gt(){return`
|
|
179
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(`
|
|
@@ -182,11 +182,11 @@ ${c.content}`),a+=c.tokenCount}return l.join(`
|
|
|
182
182
|
`)+`
|
|
183
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
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
|
|
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
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
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
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(
|
|
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(`
|
|
190
190
|
${y.error("\u26A0")} ${e}`),console.log(` ${y.muted("Type yes to confirm this dangerous action.")}
|
|
191
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
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(`
|
|
@@ -250,18 +250,18 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
|
250
250
|
}
|
|
251
251
|
</self_eval>
|
|
252
252
|
`.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}],
|
|
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
|
|
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(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/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
255
|
|
|
256
256
|
`),{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
257
|
|
|
258
|
-
`)}},_s=null;function
|
|
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
|
|
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(Se("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(q("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l}: ${a.content.replace(/\s+/g," ").slice(0,160)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(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(q(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),Ze(e.config),console.log(Se(`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(q(`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(q(`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(q(`Provider: ${He(e.config)}`)),console.log(q(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Se("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(Se(`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(q(`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(q(` ${l}: ${c}`));if(o.length>0){console.log(q("Recent:"));for(let l of o)console.log(q(` \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(Se(`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?Se(`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(q("No memories found."));return}console.log(q(`Found ${o.length} memories for "${i}":`));for(let a of o)console.log(q(` [${a.entry.kind}] ${a.entry.key.slice(0,55)} (${a.score.toFixed(2)})`)),console.log(q(` ${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(Se(`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(q("workspace mode: standalone (no git repository detected)")),console.log(q("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(q(`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 v=(await l.prompt(" \u203A ")).trim();if(v){if(v.startsWith("/")){let b=await Gl(v,{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(v,{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(`
|
|
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
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
|
|
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=
|
|
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(`
|
|
264
264
|
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")),
|
|
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(`
|
|
266
266
|
\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
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();
|