hablas-ai 2.0.2 → 2.1.0
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/CHANGELOG.md +22 -42
- package/README.md +20 -0
- package/dist/index.js +206 -129
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,175 +1,256 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
2
|
+
"use strict";var ol=Object.create;var Zn=Object.defineProperty;var al=Object.getOwnPropertyDescriptor;var ll=Object.getOwnPropertyNames;var cl=Object.getPrototypeOf,ul=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var fl=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ll(e))!ul.call(t,s)&&s!==r&&Zn(t,s,{get:()=>e[s],enumerable:!(n=al(e,s))||n.enumerable});return t};var k=(t,e,r)=>(r=t!=null?ol(cl(t)):{},fl(e||!t||!t.__esModule?Zn(r,"default",{value:t,enumerable:!0}):r,t));var at=I(br=>{var $t=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},wr=class extends $t{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};br.CommanderError=$t;br.InvalidArgumentError=wr});var Tt=I(_r=>{var{InvalidArgumentError:dl}=at(),Sr=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new dl(`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 pl(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}_r.Argument=Sr;_r.humanReadableArgName=pl});var vr=I(Qn=>{var{humanReadableArgName:hl}=Tt(),xr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,i)=>s.name().localeCompare(i.name())),r}compareOptions(e,r){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?r.push(n):n.long&&!i?r.push(e.createOption(n.long,n.description)):n.short&&!s&&r.push(e.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>hl(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,s)=>Math.max(n,r.subcommandTerm(s).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,s)=>Math.max(n,r.argumentTerm(s).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),s=r.helpWidth||80,i=2,o=2;function a(c,m){if(m){let y=`${c.padEnd(n+o)}${m}`;return r.wrap(y,s-i,n+o)}return c}function l(c){return c.join(`
|
|
3
3
|
`).replace(/^/gm," ".repeat(i))}let f=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(f=f.concat([r.wrap(u,s,0),""]));let d=r.visibleArguments(e).map(c=>a(r.argumentTerm(c),r.argumentDescription(c)));d.length>0&&(f=f.concat(["Arguments:",l(d),""]));let h=r.visibleOptions(e).map(c=>a(r.optionTerm(c),r.optionDescription(c)));if(h.length>0&&(f=f.concat(["Options:",l(h),""])),this.showGlobalOptions){let c=r.visibleGlobalOptions(e).map(m=>a(r.optionTerm(m),r.optionDescription(m)));c.length>0&&(f=f.concat(["Global Options:",l(c),""]))}let p=r.visibleCommands(e).map(c=>a(r.subcommandTerm(c),r.subcommandDescription(c)));return p.length>0&&(f=f.concat(["Commands:",l(p),""])),f.join(`
|
|
4
4
|
`)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=r-n;if(a<s)return e;let l=e.slice(0,n),f=e.slice(n).replace(`\r
|
|
5
5
|
`,`
|
|
6
6
|
`),u=" ".repeat(n),h="\\s\u200B",p=new RegExp(`
|
|
7
7
|
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),c=f.match(p)||[];return l+c.map((m,y)=>m===`
|
|
8
8
|
`?"":(y>0?u:"")+m.trimEnd()).join(`
|
|
9
|
-
`)}};
|
|
9
|
+
`)}};Qn.Help=xr});var Tr=I($r=>{var{InvalidArgumentError:ml}=at(),kr=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=yl(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 ml(`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 gl(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Cr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return r.negate===(i===e)}};function gl(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function yl(t){let e,r,n=t.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),r=n.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}$r.Option=kr;$r.DualOptions=Cr});var ts=I(es=>{function wl(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 bl(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=wl(t,o),l=Math.max(t.length,o.length);(l-a)/l>i&&(a<s?(s=a,n=[o]):a===s&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),r&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
10
10
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
-
(Did you mean ${n[0]}?)`:""}
|
|
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
|
|
13
|
-
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new
|
|
14
|
-
- already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=s=>[s.name()].concat(s.aliases()),n=r(e).find(s=>this._findCommand(s));if(n){let s=r(this._findCommand(n)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,a)};return this.on("option:"+r,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,r,n,s,i){if(typeof r=="object"&&r instanceof
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}es.suggestSimilar=bl});var os=I(is=>{var Sl=require("node:events").EventEmitter,Ar=require("node:child_process"),fe=require("node:path"),Er=require("node:fs"),q=require("node:process"),{Argument:_l,humanReadableArgName:xl}=Tt(),{CommanderError:Or}=at(),{Help:vl}=vr(),{Option:rs,DualOptions:kl}=Tr(),{suggestSimilar:ns}=ts(),Rr=class t extends Sl{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>q.stdout.write(r),writeErr:r=>q.stderr.write(r),getOutHelpWidth:()=>q.stdout.isTTY?q.stdout.columns:void 0,getErrHelpWidth:()=>q.stderr.isTTY?q.stderr.columns:void 0,outputError:(r,n)=>n(r)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let s=r,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return s&&(l.description(s),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),s?this:l}createCommand(e){return new t(e)}createHelp(){return Object.assign(new vl,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new _l(e,r)}argument(e,r,n,s){let i=this.createArgument(e,r);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=r??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new Or(e,r,n)),q.exit(e)}action(e){let r=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=r,this}createOption(e,r){return new rs(e,r)}_callParseArg(e,r,n,s){try{return e.parseArg(r,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
14
|
+
- already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=s=>[s.name()].concat(s.aliases()),n=r(e).find(s=>this._findCommand(s));if(n){let s=r(this._findCommand(n)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,a)};return this.on("option:"+r,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,r,n,s,i){if(typeof r=="object"&&r instanceof rs)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(r,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(l,f)=>{let u=a.exec(l);return u?u[0]:f},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,r,n,s){return this._optionEx({},e,r,n,s)}requiredOption(e,r,n,s){return this._optionEx({mandatory:!0},e,r,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){q.versions?.electron&&(r.from="electron");let s=q.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(r.from="eval")}e===void 0&&(e=q.argv),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":q.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let h=fe.resolve(u,d);if(Er.existsSync(h))return h;if(s.includes(fe.extname(d)))return;let p=s.find(c=>Er.existsSync(`${h}${c}`));if(p)return`${h}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Er.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=fe.resolve(fe.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=fe.basename(this._scriptPath,fe.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}n=s.includes(fe.extname(o));let l;q.platform!=="win32"?n?(r.unshift(o),r=ss(q.execArgv).concat(r),l=Ar.spawn(q.argv[0],r,{stdio:"inherit"})):l=Ar.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=ss(q.execArgv).concat(r),l=Ar.spawn(q.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{q.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let f=this._exitCallback;l.on("close",u=>{u=u??1,f?f(new Or(u,"commander.executeSubCommandAsync","(close)")):q.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
16
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
-
- ${d}`;throw new Error(h)}else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!f)q.exit(1);else{let d=new
|
|
17
|
+
- ${d}`;throw new Error(h)}else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!f)q.exit(1);else{let d=new Or(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,f(d)}}),this.runningCommand=l}_dispatchSubcommand(e,r,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,r.concat(n));else return s._parseCommand(r,n)}),i}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,a)=>e(n,a,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),r[s]=i}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[r]!==void 0).forEach(i=>{i._lifeCycleHooks[r].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),r==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,r))}),s}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],s=r,i=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){s===n&&s.push(l),s.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let f=this._findOption(l);if(f){if(f.required){let u=i.shift();u===void 0&&this.optionMissingArgument(f),this.emit(`option:${f.name()}`,u)}else if(f.optional){let u=null;i.length>0&&!o(i[0])&&(u=i.shift()),this.emit(`option:${f.name()}`,u)}else this.emit(`option:${f.name()}`);a=f.variadic?f:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let f=this._findOption(`-${l[1]}`);if(f){f.required||f.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${f.name()}`,l.slice(2)):(this.emit(`option:${f.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let f=l.indexOf("="),u=this._findOption(l.slice(0,f));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,l.slice(f+1));continue}}if(o(l)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(l)){r.push(l),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){r.push(l),i.length>0&&r.push(...i);break}else if(this._defaultCommandName){n.push(l),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(l),i.length>0&&s.push(...i);break}s.push(l)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));let n=r||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in q.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,q.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
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=>
|
|
20
|
+
`),this.outputHelp({error:!0}));let n=r||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in q.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,q.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new kl(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!r(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=o=>{let a=o.attributeName(),l=this.getOptionValue(a),f=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return f&&(f.presetArg===void 0&&l===!1||f.presetArg!==void 0&&l===f.presetArg)?f:u||o},s=o=>{let a=n(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);r=ns(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=ns(e,s)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let s=this.createOption(r,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>xl(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=fe.basename(e,fe.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(r&&(s=r(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let r=q.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
22
|
Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof r=="function"?o=r({error:i.error,command:i.command}):o=r,o&&i.write(`${o}
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
24
|
-
causes have become circular...`;let n
|
|
25
|
-
caused by: `+os(n,e)):r},ml=t=>os(t,new Set),as=(t,e,r)=>{if(!ot(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=$r(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+as(s,e,i)}else return n},gl=t=>as(t,new Set);ls.exports={isErrorLike:ot,getErrorCause:$r,stackWithCauses:ml,messageWithCauses:gl}});var Ar=I((Zh,us)=>{"use strict";var yl=Symbol("circular-ref-tag"),vt=Symbol("pino-raw-err-ref"),cs=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[vt]},set:function(t){this[vt]=t}}});Object.defineProperty(cs,vt,{writable:!0,value:{}});us.exports={pinoErrProto:cs,pinoErrorSymbols:{seen:yl,rawSymbol:vt}}});var ps=I((Qh,ds)=>{"use strict";ds.exports=Or;var{messageWithCauses:wl,stackWithCauses:bl,isErrorLike:fs}=Tr(),{pinoErrProto:Sl,pinoErrorSymbols:_l}=Ar(),{seen:Er}=_l,{toString:xl}=Object.prototype;function Or(t){if(!fs(t))return t;t[Er]=void 0;let e=Object.create(Sl);e.type=xl.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=wl(t),e.stack=bl(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Or(r)));for(let r in t)if(e[r]===void 0){let n=t[r];fs(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Er)&&(e[r]=Or(n)):e[r]=n}return delete t[Er],e.raw=t,e}});var ms=I((em,hs)=>{"use strict";hs.exports=Ct;var{isErrorLike:Rr}=Tr(),{pinoErrProto:vl,pinoErrorSymbols:kl}=Ar(),{seen:kt}=kl,{toString:Cl}=Object.prototype;function Ct(t){if(!Rr(t))return t;t[kt]=void 0;let e=Object.create(vl);e.type=Cl.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=t.message,e.stack=t.stack,Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Ct(r))),Rr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,kt)&&(e.cause=Ct(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];Rr(n)?Object.prototype.hasOwnProperty.call(n,kt)||(e[r]=Ct(n)):e[r]=n}return delete t[kt],e.raw=t,e}});var bs=I((tm,ws)=>{"use strict";ws.exports={mapHttpRequest:$l,reqSerializer:ys};var Ir=Symbol("pino-raw-req-ref"),gs=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Ir]},set:function(t){this[Ir]=t}}});Object.defineProperty(gs,Ir,{writable:!0,value:{}});function ys(t){let e=t.info||t.socket,r=Object.create(gs);if(r.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),r.method=t.method,t.originalUrl)r.url=t.originalUrl;else{let n=t.path;r.url=typeof n=="string"?n:t.url?t.url.path||t.url:void 0}return t.query&&(r.query=t.query),t.params&&(r.params=t.params),r.headers=t.headers,r.remoteAddress=e&&e.remoteAddress,r.remotePort=e&&e.remotePort,r.raw=t.raw||t,r}function $l(t){return{req:ys(t)}}});var vs=I((rm,xs)=>{"use strict";xs.exports={mapHttpResponse:Tl,resSerializer:_s};var Pr=Symbol("pino-raw-res-ref"),Ss=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Pr]},set:function(t){this[Pr]=t}}});Object.defineProperty(Ss,Pr,{writable:!0,value:{}});function _s(t){let e=Object.create(Ss);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function Tl(t){return{res:_s(t)}}});var Fr=I((nm,ks)=>{"use strict";var Mr=ps(),Al=ms(),$t=bs(),Tt=vs();ks.exports={err:Mr,errWithCause:Al,mapHttpRequest:$t.mapHttpRequest,mapHttpResponse:Tt.mapHttpResponse,req:$t.reqSerializer,res:Tt.resSerializer,wrapErrorSerializer:function(e){return e===Mr?e:function(n){return e(Mr(n))}},wrapRequestSerializer:function(e){return e===$t.reqSerializer?e:function(n){return e($t.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Tt.resSerializer?e:function(n){return e(Tt.resSerializer(n))}}}});var Lr=I((sm,Cs)=>{"use strict";function El(t,e){return e}Cs.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=El;let r=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(r))return;let n=r.slice(2),s=[];for(let i of n)i&&s.push(i.getFileName());return s}});var Rs=I((im,Os)=>{"use strict";function Dr(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array){let e=[];for(let r=0;r<t.length;r++)e[r]=Dr(t[r]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=Dr(t[r]));return e}return t}function $s(t){let e=[],r="",n=!1,s=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!n&&a==="."?r&&(e.push(r),r=""):a==="["?(r&&(e.push(r),r=""),n=!0):a==="]"&&n?(e.push(r),r="",n=!1,s=!1):(a==='"'||a==="'")&&n?s?a===i?(s=!1,i=""):r+=a:(s=!0,i=a):r+=a}return r&&e.push(r),e}function Ts(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof n!="object"||n===null||!(o in n)||typeof n[o]!="object"||n[o]===null)return!1;n=n[o]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(n))for(let i=0;i<n.length;i++)n[i]=r;else if(typeof n=="object"&&n!==null)for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&(n[i]=r)}else typeof n=="object"&&n!==null&&s in n&&Object.prototype.hasOwnProperty.call(n,s)&&(n[s]=r);return!0}function As(t,e){let r=t;for(let s=0;s<e.length-1;s++){let i=e[s];if(typeof r!="object"||r===null||!(i in r)||typeof r[i]!="object"||r[i]===null)return!1;r=r[i]}let n=e[e.length-1];if(n==="*"){if(Array.isArray(r))for(let s=0;s<r.length;s++)r[s]=void 0;else if(typeof r=="object"&&r!==null)for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&delete r[s]}else typeof r=="object"&&r!==null&&n in r&&Object.prototype.hasOwnProperty.call(r,n)&&delete r[n];return!0}var At=Symbol("PATH_NOT_FOUND");function Ol(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return At;r=r[n]}return r}function Rl(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null)return;r=r[n]}return r}function Il(t,e,r,n=!1){for(let s of e){let i=$s(s);if(i.includes("*"))Es(t,i,r,s,n);else if(n)As(t,i);else{let o=Ol(t,i);if(o===At)continue;let a=typeof r=="function"?r(o,i):r;Ts(t,i,a)}}}function Es(t,e,r,n,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(s)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let f=[...o,l.toString()],u=typeof r=="function"?r(a[l],f):r;a[l]=u}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let f in a)Object.prototype.hasOwnProperty.call(a,f)&&l.push(f);for(let f of l)delete a[f]}else for(let l in a){let f=[...o,l],u=typeof r=="function"?r(a[l],f):r;a[l]=u}}else Pl(t,e,r,i,n,s)}function Pl(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function f(u,d){if(d===o.length){if(Array.isArray(u))for(let h=0;h<u.length;h++)l[d]=h.toString(),f(u[h],d+1);else if(typeof u=="object"&&u!==null)for(let h in u)l[d]=h,f(u[h],d+1)}else if(d<o.length){let h=o[d];u&&typeof u=="object"&&u!==null&&h in u&&(l[d]=h,f(u[h],d+1))}else if(a.includes("*"))Es(u,a,typeof r=="function"?(p,c)=>{let m=[...l.slice(0,d),...c];return r(p,m)}:r,s,i);else if(i)As(u,a);else{let h=typeof r=="function"?r(Rl(u,a),[...l.slice(0,d),...a]):r;Ts(u,a,h)}}if(o.length===0)f(t,0);else{let u=t;for(let d=0;d<o.length;d++){let h=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[h],l[d]=h}u!=null&&f(u,o.length)}}function Ml(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=$s(r),s=e;for(let i=0;i<n.length;i++){let o=n[i];s.has(o)||s.set(o,new Map),s=s.get(o)}}return e}function Fl(t,e){if(!e)return t;function r(n,s,i=0){if(!s||s.size===0||n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n)){let a=[];for(let l=0;l<n.length;l++){let f=l.toString();s.has(f)||s.has("*")?a[l]=r(n[l],s.get(f)||s.get("*")):a[l]=n[l]}return a}let o=Object.create(Object.getPrototypeOf(n));for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s.has(a)||s.has("*")?o[a]=r(n[a],s.get(a)||s.get("*")):o[a]=n[a]);return o}return r(t,e)}function Ll(t){if(typeof t!="string")throw new Error("Paths must be (non-empty) strings");if(t==="")throw new Error("Invalid redaction path ()");if(t.includes(".."))throw new Error(`Invalid redaction path (${t})`);if(t.includes(","))throw new Error(`Invalid redaction path (${t})`);let e=0,r=!1,n="";for(let s=0;s<t.length;s++){let i=t[s];if((i==='"'||i==="'")&&e>0)r?i===n&&(r=!1,n=""):(r=!0,n=i);else if(i==="["&&!r)e++;else if(i==="]"&&!r&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function Dl(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)Ll(e)}function jl(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;Dl(e);let o=Ml(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let f=Fl(l,o),u=l,d=r;return typeof r=="function"&&(d=r),Il(f,e,d,i),n===!1?(f.restore=function(){return Dr(u)},f):typeof n=="function"?n(f):JSON.stringify(f)}}Os.exports=jl});var Ne=I((om,Is)=>{"use strict";var Nl=Symbol("pino.setLevel"),ql=Symbol("pino.getLevel"),Ul=Symbol("pino.levelVal"),Bl=Symbol("pino.levelComp"),Hl=Symbol("pino.useLevelLabels"),Wl=Symbol("pino.useOnlyCustomLevels"),Vl=Symbol("pino.mixin"),zl=Symbol("pino.lsCache"),Kl=Symbol("pino.chindings"),Gl=Symbol("pino.asJson"),Jl=Symbol("pino.write"),Xl=Symbol("pino.redactFmt"),Yl=Symbol("pino.time"),Zl=Symbol("pino.timeSliceIndex"),Ql=Symbol("pino.stream"),ec=Symbol("pino.stringify"),tc=Symbol("pino.stringifySafe"),rc=Symbol("pino.stringifiers"),nc=Symbol("pino.end"),sc=Symbol("pino.formatOpts"),ic=Symbol("pino.messageKey"),oc=Symbol("pino.errorKey"),ac=Symbol("pino.nestedKey"),lc=Symbol("pino.nestedKeyStr"),cc=Symbol("pino.mixinMergeStrategy"),uc=Symbol("pino.msgPrefix"),fc=Symbol("pino.wildcardFirst"),dc=Symbol.for("pino.serializers"),pc=Symbol.for("pino.formatters"),hc=Symbol.for("pino.hooks"),mc=Symbol.for("pino.metadata");Is.exports={setLevelSym:Nl,getLevelSym:ql,levelValSym:Ul,levelCompSym:Bl,useLevelLabelsSym:Hl,mixinSym:Vl,lsCacheSym:zl,chindingsSym:Kl,asJsonSym:Gl,writeSym:Jl,serializersSym:dc,redactFmtSym:Xl,timeSym:Yl,timeSliceIndexSym:Zl,streamSym:Ql,stringifySym:ec,stringifySafeSym:tc,stringifiersSym:rc,endSym:nc,formatOptsSym:sc,messageKeySym:ic,errorKeySym:oc,nestedKeySym:ac,wildcardFirstSym:fc,needsMetadataGsym:mc,useOnlyCustomLevelsSym:Wl,formattersSym:pc,hooksSym:hc,nestedKeyStrSym:lc,mixinMergeStrategySym:cc,msgPrefixSym:uc}});var Nr=I((am,Ls)=>{"use strict";var Ps=Rs(),{redactFmtSym:gc,wildcardFirstSym:Et}=Ne(),jr=/[^.[\]]+|\[([^[\]]*?)\]/g,Ms="[Redacted]",Fs=!1;function yc(t,e){let{paths:r,censor:n,remove:s}=wc(t),i=r.reduce((l,f)=>{jr.lastIndex=0;let u=jr.exec(f),d=jr.exec(f),h=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(h==="*"&&(h=Et),d===null)return l[h]=null,l;if(l[h]===null)return l;let{index:p}=d,c=`${f.substr(p,f.length-1)}`;return l[h]=l[h]||[],h!==Et&&l[h].length===0&&l[h].push(...l[Et]||[]),h===Et&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(c)}),l[h].push(c),l},{}),o={[gc]:Ps({paths:r,censor:n,serialize:e,strict:Fs,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,f)=>{if(i[f]===null)l[f]=u=>a(u,[f]);else{let u=typeof n=="function"?(d,h)=>n(d,[f,...h]):n;l[f]=Ps({paths:i[f],censor:u,serialize:e,strict:Fs,remove:s})}return l},o)}function wc(t){if(Array.isArray(t))return t={paths:t,censor:Ms},t;let{paths:e,censor:r=Ms,remove:n}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),{paths:e,censor:r,remove:n}}Ls.exports=yc});var Ns=I((lm,js)=>{"use strict";var bc=()=>"",Sc=()=>`,"time":${Date.now()}`,_c=()=>`,"time":${Math.round(Date.now()/1e3)}`,xc=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,vc=1000000n,Ds=1000000000n,kc=BigInt(Date.now())*vc,Cc=process.hrtime.bigint(),$c=()=>{let t=process.hrtime.bigint()-Cc,e=kc+t,r=e/Ds,n=e%Ds,s=Number(r*1000n+n/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),f=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${f}:${u}:${d}.${n.toString().padStart(9,"0")}Z"`};js.exports={nullTime:bc,epochTime:Sc,unixTime:_c,isoTime:xc,isoTimeNano:$c}});var Us=I((cm,qs)=>{"use strict";function Tc(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}qs.exports=Ac;function Ac(t,e,r){var n=r&&r.stringify||Tc,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var f="",u=1-s,d=-1,h=t&&t.length||0,p=0;p<h;){if(t.charCodeAt(p)===37&&p+1<h){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<p&&(f+=t.slice(d,p)),f+=Number(e[u]),d=p+2,p++;break;case 105:if(u>=l||e[u]==null)break;d<p&&(f+=t.slice(d,p)),f+=Math.floor(Number(e[u])),d=p+2,p++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<p&&(f+=t.slice(d,p));var c=typeof e[u];if(c==="string"){f+="'"+e[u]+"'",d=p+2,p++;break}if(c==="function"){f+=e[u].name||"<anonymous>",d=p+2,p++;break}f+=n(e[u]),d=p+2,p++;break;case 115:if(u>=l)break;d<p&&(f+=t.slice(d,p)),f+=String(e[u]),d=p+2,p++;break;case 37:d<p&&(f+=t.slice(d,p)),f+="%",d=p+2,p++,u--;break}++u}++p}return d===-1?t:(d<h&&(f+=t.slice(d)),f)}});var Ur=I((um,qr)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(t,0,0,Number(r))},t=new Int32Array(new SharedArrayBuffer(4));qr.exports=e}else{let t=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(e);for(;n>Date.now(););};qr.exports=t}});var Js=I((fm,Gs)=>{"use strict";var D=require("fs"),Ec=require("events"),Oc=require("util").inherits,Bs=require("path"),Hr=Ur(),Rc=require("assert"),Ot=100,Rt=Buffer.allocUnsafe(0),Ic=16*1024,Hs="buffer",Ws="utf8",[Pc,Mc]=(process.versions.node||"0.0").split(".").map(Number),Fc=Pc>=22&&Mc>=7;function Vs(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function r(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=t,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let n=e.append?"a":"w",s=e.mode;if(e.sync)try{e.mkdir&&D.mkdirSync(Bs.dirname(t),{recursive:!0});let i=D.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?D.mkdir(Bs.dirname(t),{recursive:!0},i=>{if(i)return r(i);D.open(t,n,s,r)}):D.open(t,n,s,r)}function te(t){if(!(this instanceof te))return new te(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:f,retryEAGAIN:u,fsync:d,contentMode:h,mode:p}=t||{};e=e||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=s||0,this.maxWrite=i||Ic,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=p,this.retryEAGAIN=u||(()=>!0),this.mkdir=f||!1;let c,m;if(h===Hs)this._writingBuf=Rt,this.write=jc,this.flush=qc,this.flushSync=Bc,this._actualWrite=Wc,c=()=>D.writeSync(this.fd,this._writingBuf),m=()=>D.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===Ws)this._writingBuf="",this.write=Dc,this.flush=Nc,this.flushSync=Uc,this._actualWrite=Hc,c=()=>Buffer.isBuffer(this._writingBuf)?D.writeSync(this.fd,this._writingBuf):D.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?D.write(this.fd,this._writingBuf,this.release):D.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Ws}" and "${Hs}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Vs(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(y,w)=>{if(y){if((y.code==="EAGAIN"||y.code==="EBUSY")&&this.retryEAGAIN(y,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Hr(Ot),this.release(void 0,0)}catch(S){this.release(S)}else setTimeout(m,Ot);else this._writing=!1,this.emit("error",y);return}this.emit("write",w);let b=Br(this._writingBuf,this._len,w);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let S=c(),k=Br(this._writingBuf,this._len,S);this._len=k.len,this._writingBuf=k.writingBuf}while(this._writingBuf.length)}catch(S){this.release(S);return}}this._fsync&&D.fsyncSync(this.fd);let _=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):_>this.minLength?this._actualWrite():this._ending?_>0?this._actualWrite():(this._writing=!1,It(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Lc,this)):this.emit("drain"))},this.on("newListener",function(y){y==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Br(t,e,r){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-r,0),t=t.subarray(r),{writingBuf:t,len:e}}function Lc(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Oc(te,Ec);function zs(t,e){return t.length===0?Rt:t.length===1?t[0]:Buffer.concat(t,e)}function Dc(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),r=this._len+e,n=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(n.length===0||Buffer.byteLength(n[n.length-1])+e>this.maxWrite?n.push(t):n[n.length-1]+=t,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function jc(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,r=this._bufs,n=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||n[n.length-1]+t.length>this.maxWrite?(r.push([t]),n.push(t.length)):(r[r.length-1].push(t),n[n.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Ks(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{D.fsync(this.fd,n=>{this._flushPending=!1,t(n)})}catch(n){t(n)}this.off("error",r)},r=n=>{this._flushPending=!1,t(n),this.off("drain",e)};this.once("drain",e),this.once("error",r)}function Nc(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Ks.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function qc(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Ks.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}te.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&D.close(e,r=>{if(r)return this.emit("error",r)})}),Vs(this.file,this)};te.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():It(this)))};function Uc(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?D.writeSync(this.fd,t):D.writeSync(this.fd,t,"utf8"),r=Br(t,this._len,e);t=r.writingBuf,this._len=r.len,t.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Hr(Ot)}}try{D.fsyncSync(this.fd)}catch{}}function Bc(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=Rt);let t=Rt;for(;this._bufs.length||t.length;){t.length<=0&&(t=zs(this._bufs[0],this._lens[0]));try{let e=D.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Hr(Ot)}}}te.prototype.destroy=function(){this.destroyed||It(this)};function Hc(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?D.writeSync(this.fd,this._writingBuf):D.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else D.write(this.fd,this._writingBuf,t)}function Wc(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:zs(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=D.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else Fc&&(this._writingBuf=Buffer.from(this._writingBuf)),D.write(this.fd,this._writingBuf,t)}function It(t){if(t.fd===-1){t.once("ready",It.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Rc(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{D.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?D.close(t.fd,r):r()}function r(n){if(n){t.emit("error",n);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}te.SonicBoom=te;te.default=te;Gs.exports=te});var Wr=I((dm,ei)=>{"use strict";var re={exit:[],beforeExit:[]},Xs={exit:Kc,beforeExit:Gc},qe;function Vc(){qe===void 0&&(qe=new FinalizationRegistry(Jc))}function zc(t){re[t].length>0||process.on(t,Xs[t])}function Ys(t){re[t].length>0||(process.removeListener(t,Xs[t]),re.exit.length===0&&re.beforeExit.length===0&&(qe=void 0))}function Kc(){Zs("exit")}function Gc(){Zs("beforeExit")}function Zs(t){for(let e of re[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}re[t]=[]}function Jc(t){for(let e of["exit","beforeExit"]){let r=re[e].indexOf(t);re[e].splice(r,r+1),Ys(e)}}function Qs(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");zc(t);let n=new WeakRef(e);n.fn=r,Vc(),qe.register(e,n),re[t].push(n)}function Xc(t,e){Qs("exit",t,e)}function Yc(t,e){Qs("beforeExit",t,e)}function Zc(t){if(qe!==void 0){qe.unregister(t);for(let e of["exit","beforeExit"])re[e]=re[e].filter(r=>{let n=r.deref();return n&&n!==t}),Ys(e)}}ei.exports={register:Xc,registerBeforeExit:Yc,unregister:Zc}});var ti=I((pm,Qc)=>{Qc.exports={name:"thread-stream",version:"4.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",engines:{node:">=20"},dependencies:{"real-require":"^1.0.0"},devDependencies:{"@types/node":"^25.0.2","@yao-pkg/pkg":"^6.0.0",borp:"^1.0.0",desm:"^1.3.0",eslint:"^9.39.1",fastbench:"^1.0.1",neostandard:"^0.13.0","pino-elasticsearch":"^9.0.0","sonic-boom":"^5.0.0","ts-node":"^10.8.0",typescript:"~5.7.3"},scripts:{build:"tsc --noEmit",lint:"eslint",test:'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:ci":'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:yarn":'npm run transpile && borp --pattern "test/*.test.js"',transpile:"sh ./test/ts/transpile.sh"},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina <hello@matteocollina.com>",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var ni=I((hm,ri)=>{"use strict";function eu(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{let a=Atomics.load(t,e);if(a===r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),f=Atomics.waitAsync(t,e,a,l);f.async?f.value.then(o):setImmediate(o)};o()}function tu(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{if(Atomics.load(t,e)!==r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),f=Atomics.waitAsync(t,e,r,l);f.async?f.value.then(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}ri.exports={wait:eu,waitDiff:tu}});var ii=I((mm,si)=>{"use strict";si.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var yi=I((gm,gi)=>{"use strict";var{version:ru}=ti(),{EventEmitter:nu}=require("events"),{Worker:su}=require("worker_threads"),{join:iu}=require("path"),{pathToFileURL:ou}=require("url"),{wait:au}=ni(),{WRITE_INDEX:le,READ_INDEX:xe,SEQ_INDEX:Vr}=ii(),lu=require("buffer"),cu=require("assert"),g=Symbol("kImpl"),uu=lu.constants.MAX_STRING_LENGTH;function oi(){}function Jr(t,e){Atomics.add(t[g].state,Vr,1),e(),Atomics.add(t[g].state,Vr,1),Atomics.notify(t[g].state,Vr)}function ai(t){Jr(t,()=>{Atomics.store(t[g].state,xe,0),Atomics.store(t[g].state,le,0)})}var at=class{constructor(e){this._value=e}deref(){return this._value}},Pt=class{register(){}unregister(){}},fu=process.env.NODE_V8_COVERAGE?Pt:global.FinalizationRegistry||Pt,du=process.env.NODE_V8_COVERAGE?at:global.WeakRef||at,li=new fu(t=>{t.exited||t.terminate()});function pu(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||iu(__dirname,"lib","worker.js"),o=new su(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:ou(r).href,dataBuf:t[g].dataBuf,stateBuf:t[g].stateBuf,workerData:{$context:{threadStreamVersion:ru},...n}}});return o.stream=new at(t),o.on("message",hu),o.on("exit",fi),li.register(t,o),o}function ci(t){cu(!t[g].sync),t[g].needDrain&&(t[g].needDrain=!1,t.emit("drain"))}function ui(t){for(;;){let e=Atomics.load(t[g].state,le),r=t[g].data.length-e;if(r>0){if(t[g].bufLen===0){t[g].flushing=!1,t[g].ending?Xr(t):t[g].needDrain&&process.nextTick(ci,t);return}hi(t,r,oi);continue}if(r===0){if(e===0&&t[g].bufLen===0)return;Mt(t,()=>{t.destroyed||(ai(t),ui(t))});return}X(t,new Error("overwritten"));return}}function hu(t){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(t?.code!=null)switch(t.code){case"READY":this.stream=new du(e),Mt(e,()=>{e[g].ready=!0,e.emit("ready")});break;case"ERROR":X(e,t.err);break;case"EVENT":Array.isArray(t.args)?e.emit(t.name,...t.args):e.emit(t.name,t.args);break;case"FLUSHED":{if(t.context!=="thread-stream"){X(e,new Error("this should not happen: "+t.code));break}let r=e[g].flushCallbacks.get(t.id);r&&(e[g].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:X(e,new Error("this should not happen: "+t.code))}}function fi(t){let e=this.stream.deref();e!==void 0&&(li.unregister(e),e.worker.exited=!0,e.worker.off("exit",fi),X(e,t!==0?new Error("the worker thread exited"):null))}var Kr=class extends nu{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[g]={},this[g].stateBuf=new SharedArrayBuffer(128),this[g].state=new Int32Array(this[g].stateBuf),this[g].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[g].data=Buffer.from(this[g].dataBuf),this[g].sync=e.sync||!1,this[g].ending=!1,this[g].ended=!1,this[g].needDrain=!1,this[g].destroyed=!1,this[g].flushing=!1,this[g].ready=!1,this[g].finished=!1,this[g].errored=null,this[g].closed=!1,this[g].buf=[],this[g].bufHead=0,this[g].bufLen=0,this[g].flushCallbacks=new Map,this[g].nextFlushId=0,this.worker=pu(this,e),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(e){let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[g].destroyed)return Gr(this,new Error("the worker has exited")),!1;if(this[g].ending)return Gr(this,new Error("the worker is ending")),!1;if(this[g].flushing&&this[g].bufLen+r.length>=uu)try{zr(this),this[g].flushing=!0}catch(n){return X(this,n),!1}if(this[g].buf.push(r),this[g].bufLen+=r.length,this[g].sync)try{return zr(this),!0}catch(n){return X(this,n),!1}return this[g].flushing||(this[g].flushing=!0,setImmediate(ui,this)),this[g].needDrain=this[g].data.length-this[g].bufLen-Atomics.load(this[g].state,le)<=0,!this[g].needDrain}end(){this[g].destroyed||(this[g].ending=!0,Xr(this))}flush(e){e=typeof e=="function"?e:oi,di(this,r=>{if(r){process.nextTick(e,r);return}pi(this,e)})}flushSync(){this[g].destroyed||(zr(this),mi(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[g].ready}get destroyed(){return this[g].destroyed}get closed(){return this[g].closed}get writable(){return!this[g].destroyed&&!this[g].ending}get writableEnded(){return this[g].ending}get writableFinished(){return this[g].finished}get writableNeedDrain(){return this[g].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[g].errored}};function di(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].sync&&(t[g].flushing||t[g].bufLen>0)){setImmediate(di,t,e);return}Mt(t,e)}function Mt(t,e){let r=Atomics.load(t[g].state,le);au(t[g].state,xe,r,1/0,(n,s)=>{if(n){X(t,n),e(n);return}if(s!=="ok"){Mt(t,e);return}e()})}function pi(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].ready){let n=()=>{i(),pi(t,e)},s=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",n),t.off("close",s)};t.once("ready",n),t.once("close",s);return}let r=++t[g].nextFlushId;t[g].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[g].flushCallbacks.delete(r),X(t,n),process.nextTick(e,n)}}function mu(t,e){let r=t[g].flushCallbacks;if(r.size===0)return;let n=e||new Error("the worker has exited");for(let s of r.values())process.nextTick(s,n);r.clear()}function Gr(t,e){setImmediate(()=>{t.emit("error",e)})}function X(t,e){t[g].destroyed||(t[g].destroyed=!0,mu(t,e),e&&(t[g].errored=e,Gr(t,e)),t.worker.exited?setImmediate(()=>{t[g].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[g].closed=!0,t.emit("close")}))}function hi(t,e,r){let s=Atomics.load(t[g].state,le),i=e;for(;i>0&&t[g].bufLen!==0;){let o=t[g].bufHead,a=t[g].buf[o];if(a.length<=i){a.copy(t[g].data,s),s+=a.length,i-=a.length,t[g].bufLen-=a.length,t[g].bufHead=o+1,t[g].bufHead===t[g].buf.length?(t[g].buf.length=0,t[g].bufHead=0):t[g].bufHead>=1024&&t[g].bufHead*2>=t[g].buf.length&&(t[g].buf.splice(0,t[g].bufHead),t[g].bufHead=0);continue}a.copy(t[g].data,s,0,i),t[g].buf[o]=a.subarray(i),t[g].bufLen-=i,s+=i,i=0}return Jr(t,()=>{Atomics.store(t[g].state,le,s)}),r(),!0}function Xr(t){if(!(t[g].ended||!t[g].ending||t[g].flushing)){t[g].ended=!0;try{t.flushSync();let e=Atomics.load(t[g].state,xe);Jr(t,()=>{Atomics.store(t[g].state,le,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[g].state,xe,e,1e3),e=Atomics.load(t[g].state,xe),e===-2){X(t,new Error("end() failed"));return}if(++r===10){X(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[g].finished=!0,t.emit("finish")})}catch(e){X(t,e)}}}function zr(t){let e=()=>{t[g].ending?Xr(t):t[g].needDrain&&process.nextTick(ci,t)};for(t[g].flushing=!1;t[g].bufLen!==0;){let r=Atomics.load(t[g].state,le),n=t[g].data.length-r;if(n===0){mi(t),ai(t);continue}else if(n<0)throw new Error("overwritten");hi(t,n,e)}}function mi(t){if(t[g].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[g].state,le),r=0;for(;;){let n=Atomics.load(t[g].state,xe);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[g].state,xe,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}gi.exports=Kr});var Qr=I((ym,Si)=>{"use strict";var{createRequire:gu}=require("module"),{existsSync:yu}=require("node:fs"),wu=Lr(),{join:Yr,isAbsolute:bi,sep:bu}=require("node:path"),{fileURLToPath:Su}=require("node:url"),_u=Ur(),Zr=Wr(),xu=yi();function vu(t){Zr.register(t,Au),Zr.registerBeforeExit(t,Eu),t.on("close",function(){Zr.unregister(t)})}function ku(){let t=process.execArgv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--import"||r==="--require"||r==="-r"||r.startsWith("--import=")||r.startsWith("--require=")||r.startsWith("-r="))return!0}return!1}function Cu(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let r=[],n=!1;for(let s=0;s<e.length;s++){let i=e[s];if(i==="--require"||i==="-r"||i==="--import"){let o=e[s+1];if(o&&wi(o)){n=!0,s++;continue}r.push(i),o&&(r.push(o),s++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(wi(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function wi(t){let e=$u(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=Su(r)}catch{return!1}return bi(r)&&!yu(r)}function $u(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function Tu(t,e,r,n,s){if(!r.execArgv&&ku()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=Cu(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new xu({filename:t,workerData:e,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),r.autoEnd!==!1&&vu(i)}function a(){i.closed||(i.flushSync(),_u(100),i.end())}return i}function Au(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Eu(t){t.flushSync()}function Ou(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=wu(),sync:a=!1}=t,l={...t.options},f=typeof o=="string"?[o]:o,u=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&r)throw new Error("only one of target or targets can be specified");r?(d=u["pino-worker"]||Yr(__dirname,"worker.js"),l.targets=r.filter(c=>c.target).map(c=>({...c,target:p(c.target)})),l.pipelines=r.filter(c=>c.pipeline).map(c=>c.pipeline.map(m=>({...m,level:c.level,target:p(m.target)})))):e&&(d=u["pino-worker"]||Yr(__dirname,"worker.js"),l.pipelines=[e.map(c=>({...c,target:p(c.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let h=r||e?"pino.transport":d;return Tu(p(d),l,i,a,h);function p(c){if(c=u[c]||c,bi(c)||c.indexOf("file://")===0)return c;if(c==="pino/file")return Yr(__dirname,"..","file.js");let m;for(let y of f)try{let w=y==="node:repl"?process.cwd()+bu:y;m=gu(w).resolve(c);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${c}"`);return m}}Si.exports=Ou});var Dt=I((wm,Pi)=>{"use strict";var Ru=require("node:diagnostics_channel"),_i=Us(),{mapHttpRequest:Iu,mapHttpResponse:Pu}=Fr(),tn=Js(),xi=Wr(),{lsCacheSym:Mu,chindingsSym:Ti,writeSym:vi,serializersSym:Ai,formatOptsSym:ki,endSym:Fu,stringifiersSym:Ei,stringifySym:Oi,stringifySafeSym:rn,wildcardFirstSym:Ri,nestedKeySym:Lu,formattersSym:Ii,messageKeySym:Du,errorKeySym:ju,nestedKeyStrSym:Nu,msgPrefixSym:Ft}=Ne(),{isMainThread:qu}=require("worker_threads"),Uu=Qr(),[Bu]=process.versions.node.split(".").map(t=>Number(t)),Ci=Ru.tracingChannel("pino_asJson"),en=Bu>=25?t=>JSON.stringify(t):Wu;function Ue(){}function Hu(t,e){if(!e)return r;return function(...s){e.call(this,s,r,t)};function r(n,...s){if(typeof n=="object"){let i=n;n!==null&&(n.method&&n.headers&&n.socket?n=Iu(n):typeof n.setHeader=="function"&&(n=Pu(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Ft]=="string"&&i!==void 0&&i!==null&&(i=this[Ft]+i),this[vi](n,_i(i,o,this[ki]),t)}else{let i=n===void 0?s.shift():n;typeof this[Ft]=="string"&&i!==void 0&&i!==null&&(i=this[Ft]+i),this[vi](null,_i(i,s,this[ki]),t)}}}function Wu(t){let e="",r=0,n=!1,s=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&s>=32;o++)s=t.charCodeAt(o),(s===34||s===92)&&(e+=t.slice(r,o)+"\\",r=o,n=!0);return n?e+=t.slice(r):e=t,s<32?JSON.stringify(t):'"'+e+'"'}function Vu(t,e,r,n){if(Ci.hasSubscribers===!1)return $i.call(this,t,e,r,n);let s={instance:this,arguments};return Ci.traceSync($i,s,this,t,e,r,n)}function $i(t,e,r,n){let s=this[Oi],i=this[rn],o=this[Ei],a=this[Fu],l=this[Ti],f=this[Ai],u=this[Ii],d=this[Du],h=this[ju],p=this[Mu][r]+n;p=p+l;let c;u.log&&(t=u.log(t));let m=o[Ri],y="";for(let b in t)if(c=t[b],Object.prototype.hasOwnProperty.call(t,b)&&c!==void 0){f[b]?c=f[b](c):b===h&&f.err&&(c=f.err(c));let _=o[b]||m;switch(typeof c){case"undefined":case"function":continue;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":_&&(c=_(c));break;case"string":c=(_||en)(c);break;default:c=(_||s)(c,i)}if(c===void 0)continue;let S=en(b);y+=","+S+":"+c}let w="";if(e!==void 0){c=f[d]?f[d](e):e;let b=o[d]||m;switch(typeof c){case"function":break;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":b&&(c=b(c)),w=',"'+d+'":'+c;break;case"string":c=(b||en)(c),w=',"'+d+'":'+c;break;default:c=(b||s)(c,i),w=',"'+d+'":'+c}}return this[Lu]&&y?p+this[Nu]+y.slice(1)+"}"+w+a:p+y+w+a}function zu(t,e){let r,n=t[Ti],s=t[Oi],i=t[rn],o=t[Ei],a=o[Ri],l=t[Ai],f=t[Ii].bindings;e=f(e);for(let u in e)if(r=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&r!==void 0)===!0){if(r=l[u]?l[u](r):r,r=(o[u]||a||s)(r,i),r===void 0)continue;n+=',"'+u+'":'+r}return n}function Ku(t){return t.write!==t.constructor.prototype.write}function Lt(t){let e=new tn(t);return e.on("error",r),!t.sync&&qu&&(xi.register(e,Gu),e.on("close",function(){xi.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Ue,e.end=Ue,e.flushSync=Ue,e.destroy=Ue;return}e.removeListener("error",r),e.emit("error",n)}}function Gu(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Ju(t){return function(r,n,s={},i){if(typeof s=="string")i=Lt({dest:s}),s={};else if(typeof i=="string"){if(s&&s.transport)throw Error("only one of option.transport or stream can be specified");i=Lt({dest:i})}else if(s instanceof tn||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof tn||s.transport.writable||s.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(s.transport.targets&&s.transport.targets.length&&s.formatters&&typeof s.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;s.customLevels&&(l=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=Uu({caller:n,...s.transport,levels:l})}if(s=Object.assign({},t,s),s.serializers=Object.assign({},t.serializers,s.serializers),s.formatters=Object.assign({},t.formatters,s.formatters),s.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=s;return o===!1&&(s.level="silent"),a||(s.onChild=Ue),i||(Ku(process.stdout)?i=process.stdout:i=Lt({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function Xu(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[rn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Yu(t,e,r){return{level:t,bindings:e,log:r}}function Zu(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Pi.exports={noop:Ue,buildSafeSonicBoom:Lt,asChindings:zu,asJson:Vu,genLog:Hu,createArgsNormalizer:Ju,stringify:Xu,buildFormatters:Yu,normalizeDestFileDescriptor:Zu}});var jt=I((bm,Mi)=>{var Qu={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},ef={ASC:"ASC",DESC:"DESC"};Mi.exports={DEFAULT_LEVELS:Qu,SORTING_ORDER:ef}});var on=I((Sm,ji)=>{"use strict";var{lsCacheSym:tf,levelValSym:nn,useOnlyCustomLevelsSym:rf,streamSym:nf,formattersSym:sf,hooksSym:of,levelCompSym:Fi}=Ne(),{noop:af,genLog:ve}=Dt(),{DEFAULT_LEVELS:ie,SORTING_ORDER:Li}=jt(),Di={fatal:t=>{let e=ve(ie.fatal,t);return function(...r){let n=this[nf];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>ve(ie.error,t),warn:t=>ve(ie.warn,t),info:t=>ve(ie.info,t),debug:t=>ve(ie.debug,t),trace:t=>ve(ie.trace,t)},sn=Object.keys(ie).reduce((t,e)=>(t[ie[e]]=e,t),{}),lf=Object.keys(sn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function cf(t){let e=t[sf].level,{labels:r}=t.levels,n={};for(let s in r){let i=e(r[s],Number(s));n[s]=JSON.stringify(i).slice(0,-1)}return t[tf]=n,t}function uf(t,e){if(e)return!1;switch(t){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function ff(t){let{labels:e,values:r}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(r[t]===void 0)throw Error("unknown level "+t);let n=this[nn],s=this[nn]=r[t],i=this[rf],o=this[Fi],a=this[of].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=af;continue}this[l]=uf(l,i)?Di[l](a):ve(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function df(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function pf(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Fi](r,this[nn])}function hf(t,e,r){return t===Li.DESC?e<=r:e>=r}function mf(t){return typeof t=="string"?hf.bind(null,t):t}function gf(t=null,e=!1){let r=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:sn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:ie,t);return{labels:n,values:s}}function yf(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(sn).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:ie,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function wf(t,e){let{labels:r,values:n}=t;for(let s in e){if(s in n)throw Error("levels cannot be overridden");if(e[s]in r)throw Error("pre-existing level values cannot be used for new levels")}}function bf(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Li).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}ji.exports={initialLsCache:lf,genLsCache:cf,levelMethods:Di,getLevel:df,setLevel:ff,isLevelEnabled:pf,mappings:gf,assertNoLevelCollisions:wf,assertDefaultLevelFound:yf,genLevelComparison:mf,assertLevelComparison:bf}});var an=I((_m,Ni)=>{"use strict";Ni.exports={version:"10.3.1"}});var Ki=I((vm,zi)=>{"use strict";var{EventEmitter:Sf}=require("node:events"),{lsCacheSym:_f,levelValSym:xf,setLevelSym:cn,getLevelSym:qi,chindingsSym:qt,mixinSym:vf,asJsonSym:Bi,writeSym:kf,mixinMergeStrategySym:Cf,timeSym:$f,timeSliceIndexSym:Tf,streamSym:Hi,serializersSym:ke,formattersSym:lt,errorKeySym:Af,messageKeySym:Ef,useOnlyCustomLevelsSym:Of,needsMetadataGsym:Rf,redactFmtSym:If,stringifySym:Pf,formatOptsSym:Mf,stringifiersSym:Ff,msgPrefixSym:un,hooksSym:Lf}=Ne(),{getLevel:Df,setLevel:jf,isLevelEnabled:Nf,mappings:qf,initialLsCache:Uf,genLsCache:Bf,assertNoLevelCollisions:Hf}=on(),{asChindings:fn,asJson:Wf,buildFormatters:ln,stringify:Ui,noop:Wi}=Dt(),{version:Vf}=an(),zf=Nr(),Kf=class{},Vi={constructor:Kf,child:Gf,bindings:Jf,setBindings:Xf,flush:Qf,isLevelEnabled:Nf,version:Vf,get level(){return this[qi]()},set level(t){this[cn](t)},get levelVal(){return this[xf]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[un]},get[Symbol.toStringTag](){return"Pino"},[_f]:Uf,[kf]:Zf,[Bi]:Wf,[qi]:Df,[cn]:jf};Object.setPrototypeOf(Vi,Sf.prototype);zi.exports=function(){return Object.create(Vi)};var Nt=t=>t;function Gf(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[ke],n=this[lt],s=Object.create(this);if(e==null)return s[lt].bindings!==Nt&&(s[lt]=ln(n.level,Nt,n.log)),s[qt]=fn(s,t),this.onChild!==Wi&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[ke]=Object.create(null);for(let f in r)s[ke][f]=r[f];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let f=a[i];s[ke][f]=r[f]}for(let f in e.serializers)s[ke][f]=e.serializers[f];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let f=l[o];s[ke][f]=e.serializers[f]}}else s[ke]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:f}=e.formatters;s[lt]=ln(a||n.level,l||Nt,f||n.log)}else s[lt]=ln(n.level,Nt,n.log);if(e.hasOwnProperty("customLevels")===!0&&(Hf(this.levels,e.customLevels),s.levels=qf(e.customLevels,s[Of]),Bf(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=zf(s.redact,Ui),l={stringify:a[If]};s[Pf]=Ui,s[Ff]=a,s[Mf]=l}if(typeof e.msgPrefix=="string"&&(s[un]=(this[un]||"")+e.msgPrefix),s[qt]=fn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[cn](a)}return this.onChild(s),s}function Jf(){let e=`{${this[qt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Xf(t){let e=fn(this,t);this[qt]=e}function Yf(t,e){return Object.assign(e,t)}function Zf(t,e,r){let n=this[$f](),s=this[vf],i=this[Af],o=this[Ef],a=this[Cf]||Yf,l,f=this[Lf].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(l=a(l,s(l,r,this)));let u=this[Bi](l,e,r,n),d=this[Hi];d[Rf]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[Tf]),d.lastLogger=this),d.write(f?f(u):u)}function Qf(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Hi];typeof e.flush=="function"?e.flush(t||Wi):t&&t()}});var Yi=I((mn,Xi)=>{"use strict";var{hasOwnProperty:ct}=Object.prototype,$e=hn();$e.configure=hn;$e.stringify=$e;$e.default=$e;mn.stringify=$e;mn.configure=hn;Xi.exports=$e;var ed=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function me(t){return t.length<5e3&&!ed.test(t)?`"${t}"`:JSON.stringify(t)}function dn(t,e){if(t.length>200||e)return t.sort(e);for(let r=1;r<t.length;r++){let n=t[r],s=r;for(;s!==0&&t[s-1]>n;)t[s]=t[s-1],s--;t[s]=n}return t}var td=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function pn(t){return td.call(t)!==void 0&&t.length!==0}function Gi(t,e,r){t.length<r&&(r=t.length);let n=e===","?"":" ",s=`"0":${n}${t[0]}`;for(let i=1;i<r;i++)s+=`${e}"${i}":${n}${t[i]}`;return s}function rd(t){if(ct.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function nd(t){let e;if(ct.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function sd(t,e){let r;if(ct.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function Ji(t,e){let r;if(ct.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function Ce(t){return t===1?"1 item":`${t} items`}function id(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function od(t){if(ct.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function hn(t){t={...t};let e=od(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=rd(t),n=sd(t,"bigint"),s=nd(t),i=typeof s=="function"?s:void 0,o=Ji(t,"maximumDepth"),a=Ji(t,"maximumBreadth");function l(p,c,m,y,w,b){let _=c[p];switch(typeof _=="object"&&_!==null&&typeof _.toJSON=="function"&&(_=_.toJSON(p)),_=y.call(c,p,_),typeof _){case"string":return me(_);case"object":{if(_===null)return"null";if(m.indexOf(_)!==-1)return r;let S="",k=",",R=b;if(Array.isArray(_)){if(_.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(_),w!==""&&(b+=w,S+=`
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
${R}`),m.pop(),`[${
|
|
29
|
-
${
|
|
30
|
-
${
|
|
31
|
-
${R}`),m.pop(),`{${
|
|
32
|
-
${
|
|
33
|
-
${
|
|
34
|
-
${
|
|
35
|
-
${
|
|
36
|
-
${
|
|
37
|
-
${
|
|
38
|
-
${
|
|
39
|
-
${
|
|
40
|
-
${
|
|
41
|
-
${
|
|
42
|
-
${
|
|
43
|
-
${
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ss(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})}is.Command=Rr});var us=I(X=>{var{Argument:as}=Tt(),{Command:Ir}=os(),{CommanderError:Cl,InvalidArgumentError:ls}=at(),{Help:$l}=vr(),{Option:cs}=Tr();X.program=new Ir;X.createCommand=t=>new Ir(t);X.createOption=(t,e)=>new cs(t,e);X.createArgument=(t,e)=>new as(t,e);X.Command=Ir;X.Option=cs;X.Argument=as;X.Help=$l;X.CommanderError=Cl;X.InvalidArgumentError=ls;X.InvalidOptionArgumentError=ls});var Dr=I((gm,ys)=>{"use strict";var ct=t=>t&&typeof t.message=="string",Mr=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return ct(r)?r:void 0}else return ct(e)?e:void 0},ms=(t,e)=>{if(!ct(t))return"";let r=t.stack||"";if(e.has(t))return r+`
|
|
24
|
+
causes have become circular...`;let n=Mr(t);return n?(e.add(t),r+`
|
|
25
|
+
caused by: `+ms(n,e)):r},Tl=t=>ms(t,new Set),gs=(t,e,r)=>{if(!ct(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=Mr(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+gs(s,e,i)}else return n},Al=t=>gs(t,new Set);ys.exports={isErrorLike:ct,getErrorCause:Mr,stackWithCauses:Tl,messageWithCauses:Al}});var Fr=I((ym,bs)=>{"use strict";var El=Symbol("circular-ref-tag"),At=Symbol("pino-raw-err-ref"),ws=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[At]},set:function(t){this[At]=t}}});Object.defineProperty(ws,At,{writable:!0,value:{}});bs.exports={pinoErrProto:ws,pinoErrorSymbols:{seen:El,rawSymbol:At}}});var xs=I((wm,_s)=>{"use strict";_s.exports=jr;var{messageWithCauses:Ol,stackWithCauses:Rl,isErrorLike:Ss}=Dr(),{pinoErrProto:Il,pinoErrorSymbols:Pl}=Fr(),{seen:Lr}=Pl,{toString:Ml}=Object.prototype;function jr(t){if(!Ss(t))return t;t[Lr]=void 0;let e=Object.create(Il);e.type=Ml.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=Ol(t),e.stack=Rl(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>jr(r)));for(let r in t)if(e[r]===void 0){let n=t[r];Ss(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Lr)&&(e[r]=jr(n)):e[r]=n}return delete t[Lr],e.raw=t,e}});var ks=I((bm,vs)=>{"use strict";vs.exports=Ot;var{isErrorLike:Nr}=Dr(),{pinoErrProto:Dl,pinoErrorSymbols:Fl}=Fr(),{seen:Et}=Fl,{toString:Ll}=Object.prototype;function Ot(t){if(!Nr(t))return t;t[Et]=void 0;let e=Object.create(Dl);e.type=Ll.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=>Ot(r))),Nr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,Et)&&(e.cause=Ot(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];Nr(n)?Object.prototype.hasOwnProperty.call(n,Et)||(e[r]=Ot(n)):e[r]=n}return delete t[Et],e.raw=t,e}});var As=I((Sm,Ts)=>{"use strict";Ts.exports={mapHttpRequest:jl,reqSerializer:$s};var qr=Symbol("pino-raw-req-ref"),Cs=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[qr]},set:function(t){this[qr]=t}}});Object.defineProperty(Cs,qr,{writable:!0,value:{}});function $s(t){let e=t.info||t.socket,r=Object.create(Cs);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 jl(t){return{req:$s(t)}}});var Is=I((_m,Rs)=>{"use strict";Rs.exports={mapHttpResponse:Nl,resSerializer:Os};var Ur=Symbol("pino-raw-res-ref"),Es=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Ur]},set:function(t){this[Ur]=t}}});Object.defineProperty(Es,Ur,{writable:!0,value:{}});function Os(t){let e=Object.create(Es);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function Nl(t){return{res:Os(t)}}});var Hr=I((xm,Ps)=>{"use strict";var Br=xs(),ql=ks(),Rt=As(),It=Is();Ps.exports={err:Br,errWithCause:ql,mapHttpRequest:Rt.mapHttpRequest,mapHttpResponse:It.mapHttpResponse,req:Rt.reqSerializer,res:It.resSerializer,wrapErrorSerializer:function(e){return e===Br?e:function(n){return e(Br(n))}},wrapRequestSerializer:function(e){return e===Rt.reqSerializer?e:function(n){return e(Rt.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===It.resSerializer?e:function(n){return e(It.resSerializer(n))}}}});var Wr=I((vm,Ms)=>{"use strict";function Ul(t,e){return e}Ms.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=Ul;let r=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(r))return;let n=r.slice(2),s=[];for(let i of n)i&&s.push(i.getFileName());return s}});var qs=I((km,Ns)=>{"use strict";function Vr(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array){let e=[];for(let r=0;r<t.length;r++)e[r]=Vr(t[r]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=Vr(t[r]));return e}return t}function Ds(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 Fs(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 Ls(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 Pt=Symbol("PATH_NOT_FOUND");function Bl(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return Pt;r=r[n]}return r}function Hl(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 Wl(t,e,r,n=!1){for(let s of e){let i=Ds(s);if(i.includes("*"))js(t,i,r,s,n);else if(n)Ls(t,i);else{let o=Bl(t,i);if(o===Pt)continue;let a=typeof r=="function"?r(o,i):r;Fs(t,i,a)}}}function js(t,e,r,n,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(s)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let f=[...o,l.toString()],u=typeof r=="function"?r(a[l],f):r;a[l]=u}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let f in a)Object.prototype.hasOwnProperty.call(a,f)&&l.push(f);for(let f of l)delete a[f]}else for(let l in a){let f=[...o,l],u=typeof r=="function"?r(a[l],f):r;a[l]=u}}else Vl(t,e,r,i,n,s)}function Vl(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function f(u,d){if(d===o.length){if(Array.isArray(u))for(let h=0;h<u.length;h++)l[d]=h.toString(),f(u[h],d+1);else if(typeof u=="object"&&u!==null)for(let h in u)l[d]=h,f(u[h],d+1)}else if(d<o.length){let h=o[d];u&&typeof u=="object"&&u!==null&&h in u&&(l[d]=h,f(u[h],d+1))}else if(a.includes("*"))js(u,a,typeof r=="function"?(p,c)=>{let m=[...l.slice(0,d),...c];return r(p,m)}:r,s,i);else if(i)Ls(u,a);else{let h=typeof r=="function"?r(Hl(u,a),[...l.slice(0,d),...a]):r;Fs(u,a,h)}}if(o.length===0)f(t,0);else{let u=t;for(let d=0;d<o.length;d++){let h=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[h],l[d]=h}u!=null&&f(u,o.length)}}function zl(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=Ds(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 Kl(t,e){if(!e)return t;function r(n,s,i=0){if(!s||s.size===0||n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n)){let a=[];for(let l=0;l<n.length;l++){let f=l.toString();s.has(f)||s.has("*")?a[l]=r(n[l],s.get(f)||s.get("*")):a[l]=n[l]}return a}let o=Object.create(Object.getPrototypeOf(n));for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s.has(a)||s.has("*")?o[a]=r(n[a],s.get(a)||s.get("*")):o[a]=n[a]);return o}return r(t,e)}function Gl(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 Jl(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)Gl(e)}function Xl(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;Jl(e);let o=zl(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let f=Kl(l,o),u=l,d=r;return typeof r=="function"&&(d=r),Wl(f,e,d,i),n===!1?(f.restore=function(){return Vr(u)},f):typeof n=="function"?n(f):JSON.stringify(f)}}Ns.exports=Xl});var He=I((Cm,Us)=>{"use strict";var Yl=Symbol("pino.setLevel"),Zl=Symbol("pino.getLevel"),Ql=Symbol("pino.levelVal"),ec=Symbol("pino.levelComp"),tc=Symbol("pino.useLevelLabels"),rc=Symbol("pino.useOnlyCustomLevels"),nc=Symbol("pino.mixin"),sc=Symbol("pino.lsCache"),ic=Symbol("pino.chindings"),oc=Symbol("pino.asJson"),ac=Symbol("pino.write"),lc=Symbol("pino.redactFmt"),cc=Symbol("pino.time"),uc=Symbol("pino.timeSliceIndex"),fc=Symbol("pino.stream"),dc=Symbol("pino.stringify"),pc=Symbol("pino.stringifySafe"),hc=Symbol("pino.stringifiers"),mc=Symbol("pino.end"),gc=Symbol("pino.formatOpts"),yc=Symbol("pino.messageKey"),wc=Symbol("pino.errorKey"),bc=Symbol("pino.nestedKey"),Sc=Symbol("pino.nestedKeyStr"),_c=Symbol("pino.mixinMergeStrategy"),xc=Symbol("pino.msgPrefix"),vc=Symbol("pino.wildcardFirst"),kc=Symbol.for("pino.serializers"),Cc=Symbol.for("pino.formatters"),$c=Symbol.for("pino.hooks"),Tc=Symbol.for("pino.metadata");Us.exports={setLevelSym:Yl,getLevelSym:Zl,levelValSym:Ql,levelCompSym:ec,useLevelLabelsSym:tc,mixinSym:nc,lsCacheSym:sc,chindingsSym:ic,asJsonSym:oc,writeSym:ac,serializersSym:kc,redactFmtSym:lc,timeSym:cc,timeSliceIndexSym:uc,streamSym:fc,stringifySym:dc,stringifySafeSym:pc,stringifiersSym:hc,endSym:mc,formatOptsSym:gc,messageKeySym:yc,errorKeySym:wc,nestedKeySym:bc,wildcardFirstSym:vc,needsMetadataGsym:Tc,useOnlyCustomLevelsSym:rc,formattersSym:Cc,hooksSym:$c,nestedKeyStrSym:Sc,mixinMergeStrategySym:_c,msgPrefixSym:xc}});var Kr=I(($m,Vs)=>{"use strict";var Bs=qs(),{redactFmtSym:Ac,wildcardFirstSym:Mt}=He(),zr=/[^.[\]]+|\[([^[\]]*?)\]/g,Hs="[Redacted]",Ws=!1;function Ec(t,e){let{paths:r,censor:n,remove:s}=Oc(t),i=r.reduce((l,f)=>{zr.lastIndex=0;let u=zr.exec(f),d=zr.exec(f),h=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(h==="*"&&(h=Mt),d===null)return l[h]=null,l;if(l[h]===null)return l;let{index:p}=d,c=`${f.substr(p,f.length-1)}`;return l[h]=l[h]||[],h!==Mt&&l[h].length===0&&l[h].push(...l[Mt]||[]),h===Mt&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(c)}),l[h].push(c),l},{}),o={[Ac]:Bs({paths:r,censor:n,serialize:e,strict:Ws,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,f)=>{if(i[f]===null)l[f]=u=>a(u,[f]);else{let u=typeof n=="function"?(d,h)=>n(d,[f,...h]):n;l[f]=Bs({paths:i[f],censor:u,serialize:e,strict:Ws,remove:s})}return l},o)}function Oc(t){if(Array.isArray(t))return t={paths:t,censor:Hs},t;let{paths:e,censor:r=Hs,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}}Vs.exports=Ec});var Gs=I((Tm,Ks)=>{"use strict";var Rc=()=>"",Ic=()=>`,"time":${Date.now()}`,Pc=()=>`,"time":${Math.round(Date.now()/1e3)}`,Mc=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,Dc=1000000n,zs=1000000000n,Fc=BigInt(Date.now())*Dc,Lc=process.hrtime.bigint(),jc=()=>{let t=process.hrtime.bigint()-Lc,e=Fc+t,r=e/zs,n=e%zs,s=Number(r*1000n+n/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),f=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${f}:${u}:${d}.${n.toString().padStart(9,"0")}Z"`};Ks.exports={nullTime:Rc,epochTime:Ic,unixTime:Pc,isoTime:Mc,isoTimeNano:jc}});var Xs=I((Am,Js)=>{"use strict";function Nc(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}Js.exports=qc;function qc(t,e,r){var n=r&&r.stringify||Nc,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var f="",u=1-s,d=-1,h=t&&t.length||0,p=0;p<h;){if(t.charCodeAt(p)===37&&p+1<h){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<p&&(f+=t.slice(d,p)),f+=Number(e[u]),d=p+2,p++;break;case 105:if(u>=l||e[u]==null)break;d<p&&(f+=t.slice(d,p)),f+=Math.floor(Number(e[u])),d=p+2,p++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<p&&(f+=t.slice(d,p));var c=typeof e[u];if(c==="string"){f+="'"+e[u]+"'",d=p+2,p++;break}if(c==="function"){f+=e[u].name||"<anonymous>",d=p+2,p++;break}f+=n(e[u]),d=p+2,p++;break;case 115:if(u>=l)break;d<p&&(f+=t.slice(d,p)),f+=String(e[u]),d=p+2,p++;break;case 37:d<p&&(f+=t.slice(d,p)),f+="%",d=p+2,p++,u--;break}++u}++p}return d===-1?t:(d<h&&(f+=t.slice(d)),f)}});var Jr=I((Em,Gr)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(t,0,0,Number(r))},t=new Int32Array(new SharedArrayBuffer(4));Gr.exports=e}else{let t=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(e);for(;n>Date.now(););};Gr.exports=t}});var si=I((Om,ni)=>{"use strict";var L=require("fs"),Uc=require("events"),Bc=require("util").inherits,Ys=require("path"),Yr=Jr(),Hc=require("assert"),Dt=100,Ft=Buffer.allocUnsafe(0),Wc=16*1024,Zs="buffer",Qs="utf8",[Vc,zc]=(process.versions.node||"0.0").split(".").map(Number),Kc=Vc>=22&&zc>=7;function ei(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function r(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=t,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let n=e.append?"a":"w",s=e.mode;if(e.sync)try{e.mkdir&&L.mkdirSync(Ys.dirname(t),{recursive:!0});let i=L.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?L.mkdir(Ys.dirname(t),{recursive:!0},i=>{if(i)return r(i);L.open(t,n,s,r)}):L.open(t,n,s,r)}function se(t){if(!(this instanceof se))return new se(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:f,retryEAGAIN:u,fsync:d,contentMode:h,mode:p}=t||{};e=e||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=s||0,this.maxWrite=i||Wc,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=p,this.retryEAGAIN=u||(()=>!0),this.mkdir=f||!1;let c,m;if(h===Zs)this._writingBuf=Ft,this.write=Xc,this.flush=Zc,this.flushSync=eu,this._actualWrite=ru,c=()=>L.writeSync(this.fd,this._writingBuf),m=()=>L.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===Qs)this._writingBuf="",this.write=Jc,this.flush=Yc,this.flushSync=Qc,this._actualWrite=tu,c=()=>Buffer.isBuffer(this._writingBuf)?L.writeSync(this.fd,this._writingBuf):L.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?L.write(this.fd,this._writingBuf,this.release):L.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Qs}" and "${Zs}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")ei(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(y,b)=>{if(y){if((y.code==="EAGAIN"||y.code==="EBUSY")&&this.retryEAGAIN(y,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Yr(Dt),this.release(void 0,0)}catch(_){this.release(_)}else setTimeout(m,Dt);else this._writing=!1,this.emit("error",y);return}this.emit("write",b);let S=Xr(this._writingBuf,this._len,b);if(this._len=S.len,this._writingBuf=S.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let _=c(),C=Xr(this._writingBuf,this._len,_);this._len=C.len,this._writingBuf=C.writingBuf}while(this._writingBuf.length)}catch(_){this.release(_);return}}this._fsync&&L.fsyncSync(this.fd);let x=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):x>this.minLength?this._actualWrite():this._ending?x>0?this._actualWrite():(this._writing=!1,Lt(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Gc,this)):this.emit("drain"))},this.on("newListener",function(y){y==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Xr(t,e,r){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-r,0),t=t.subarray(r),{writingBuf:t,len:e}}function Gc(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Bc(se,Uc);function ti(t,e){return t.length===0?Ft:t.length===1?t[0]:Buffer.concat(t,e)}function Jc(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 Xc(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 ri(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{L.fsync(this.fd,n=>{this._flushPending=!1,t(n)})}catch(n){t(n)}this.off("error",r)},r=n=>{this._flushPending=!1,t(n),this.off("drain",e)};this.once("drain",e),this.once("error",r)}function Yc(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&&ri.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function Zc(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&&ri.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}se.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&L.close(e,r=>{if(r)return this.emit("error",r)})}),ei(this.file,this)};se.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():Lt(this)))};function Qc(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?L.writeSync(this.fd,t):L.writeSync(this.fd,t,"utf8"),r=Xr(t,this._len,e);t=r.writingBuf,this._len=r.len,t.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Yr(Dt)}}try{L.fsyncSync(this.fd)}catch{}}function eu(){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=Ft);let t=Ft;for(;this._bufs.length||t.length;){t.length<=0&&(t=ti(this._bufs[0],this._lens[0]));try{let e=L.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Yr(Dt)}}}se.prototype.destroy=function(){this.destroyed||Lt(this)};function tu(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?L.writeSync(this.fd,this._writingBuf):L.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else L.write(this.fd,this._writingBuf,t)}function ru(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:ti(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=L.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else Kc&&(this._writingBuf=Buffer.from(this._writingBuf)),L.write(this.fd,this._writingBuf,t)}function Lt(t){if(t.fd===-1){t.once("ready",Lt.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Hc(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{L.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?L.close(t.fd,r):r()}function r(n){if(n){t.emit("error",n);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}se.SonicBoom=se;se.default=se;ni.exports=se});var Zr=I((Rm,ci)=>{"use strict";var ie={exit:[],beforeExit:[]},ii={exit:iu,beforeExit:ou},We;function nu(){We===void 0&&(We=new FinalizationRegistry(au))}function su(t){ie[t].length>0||process.on(t,ii[t])}function oi(t){ie[t].length>0||(process.removeListener(t,ii[t]),ie.exit.length===0&&ie.beforeExit.length===0&&(We=void 0))}function iu(){ai("exit")}function ou(){ai("beforeExit")}function ai(t){for(let e of ie[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}ie[t]=[]}function au(t){for(let e of["exit","beforeExit"]){let r=ie[e].indexOf(t);ie[e].splice(r,r+1),oi(e)}}function li(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");su(t);let n=new WeakRef(e);n.fn=r,nu(),We.register(e,n),ie[t].push(n)}function lu(t,e){li("exit",t,e)}function cu(t,e){li("beforeExit",t,e)}function uu(t){if(We!==void 0){We.unregister(t);for(let e of["exit","beforeExit"])ie[e]=ie[e].filter(r=>{let n=r.deref();return n&&n!==t}),oi(e)}}ci.exports={register:lu,registerBeforeExit:cu,unregister:uu}});var ui=I((Im,fu)=>{fu.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 di=I((Pm,fi)=>{"use strict";function du(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{let a=Atomics.load(t,e);if(a===r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),f=Atomics.waitAsync(t,e,a,l);f.async?f.value.then(o):setImmediate(o)};o()}function pu(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{if(Atomics.load(t,e)!==r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),f=Atomics.waitAsync(t,e,r,l);f.async?f.value.then(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}fi.exports={wait:du,waitDiff:pu}});var hi=I((Mm,pi)=>{"use strict";pi.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var $i=I((Dm,Ci)=>{"use strict";var{version:hu}=ui(),{EventEmitter:mu}=require("events"),{Worker:gu}=require("worker_threads"),{join:yu}=require("path"),{pathToFileURL:wu}=require("url"),{wait:bu}=di(),{WRITE_INDEX:de,READ_INDEX:$e,SEQ_INDEX:Qr}=hi(),Su=require("buffer"),_u=require("assert"),g=Symbol("kImpl"),xu=Su.constants.MAX_STRING_LENGTH;function mi(){}function nn(t,e){Atomics.add(t[g].state,Qr,1),e(),Atomics.add(t[g].state,Qr,1),Atomics.notify(t[g].state,Qr)}function gi(t){nn(t,()=>{Atomics.store(t[g].state,$e,0),Atomics.store(t[g].state,de,0)})}var ut=class{constructor(e){this._value=e}deref(){return this._value}},jt=class{register(){}unregister(){}},vu=process.env.NODE_V8_COVERAGE?jt:global.FinalizationRegistry||jt,ku=process.env.NODE_V8_COVERAGE?ut:global.WeakRef||ut,yi=new vu(t=>{t.exited||t.terminate()});function Cu(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||yu(__dirname,"lib","worker.js"),o=new gu(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:wu(r).href,dataBuf:t[g].dataBuf,stateBuf:t[g].stateBuf,workerData:{$context:{threadStreamVersion:hu},...n}}});return o.stream=new ut(t),o.on("message",$u),o.on("exit",Si),yi.register(t,o),o}function wi(t){_u(!t[g].sync),t[g].needDrain&&(t[g].needDrain=!1,t.emit("drain"))}function bi(t){for(;;){let e=Atomics.load(t[g].state,de),r=t[g].data.length-e;if(r>0){if(t[g].bufLen===0){t[g].flushing=!1,t[g].ending?sn(t):t[g].needDrain&&process.nextTick(wi,t);return}vi(t,r,mi);continue}if(r===0){if(e===0&&t[g].bufLen===0)return;Nt(t,()=>{t.destroyed||(gi(t),bi(t))});return}Y(t,new Error("overwritten"));return}}function $u(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 ku(e),Nt(e,()=>{e[g].ready=!0,e.emit("ready")});break;case"ERROR":Y(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"){Y(e,new Error("this should not happen: "+t.code));break}let r=e[g].flushCallbacks.get(t.id);r&&(e[g].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:Y(e,new Error("this should not happen: "+t.code))}}function Si(t){let e=this.stream.deref();e!==void 0&&(yi.unregister(e),e.worker.exited=!0,e.worker.off("exit",Si),Y(e,t!==0?new Error("the worker thread exited"):null))}var tn=class extends mu{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[g]={},this[g].stateBuf=new SharedArrayBuffer(128),this[g].state=new Int32Array(this[g].stateBuf),this[g].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[g].data=Buffer.from(this[g].dataBuf),this[g].sync=e.sync||!1,this[g].ending=!1,this[g].ended=!1,this[g].needDrain=!1,this[g].destroyed=!1,this[g].flushing=!1,this[g].ready=!1,this[g].finished=!1,this[g].errored=null,this[g].closed=!1,this[g].buf=[],this[g].bufHead=0,this[g].bufLen=0,this[g].flushCallbacks=new Map,this[g].nextFlushId=0,this.worker=Cu(this,e),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(e){let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[g].destroyed)return rn(this,new Error("the worker has exited")),!1;if(this[g].ending)return rn(this,new Error("the worker is ending")),!1;if(this[g].flushing&&this[g].bufLen+r.length>=xu)try{en(this),this[g].flushing=!0}catch(n){return Y(this,n),!1}if(this[g].buf.push(r),this[g].bufLen+=r.length,this[g].sync)try{return en(this),!0}catch(n){return Y(this,n),!1}return this[g].flushing||(this[g].flushing=!0,setImmediate(bi,this)),this[g].needDrain=this[g].data.length-this[g].bufLen-Atomics.load(this[g].state,de)<=0,!this[g].needDrain}end(){this[g].destroyed||(this[g].ending=!0,sn(this))}flush(e){e=typeof e=="function"?e:mi,_i(this,r=>{if(r){process.nextTick(e,r);return}xi(this,e)})}flushSync(){this[g].destroyed||(en(this),ki(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[g].ready}get destroyed(){return this[g].destroyed}get closed(){return this[g].closed}get writable(){return!this[g].destroyed&&!this[g].ending}get writableEnded(){return this[g].ending}get writableFinished(){return this[g].finished}get writableNeedDrain(){return this[g].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[g].errored}};function _i(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].sync&&(t[g].flushing||t[g].bufLen>0)){setImmediate(_i,t,e);return}Nt(t,e)}function Nt(t,e){let r=Atomics.load(t[g].state,de);bu(t[g].state,$e,r,1/0,(n,s)=>{if(n){Y(t,n),e(n);return}if(s!=="ok"){Nt(t,e);return}e()})}function xi(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].ready){let n=()=>{i(),xi(t,e)},s=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",n),t.off("close",s)};t.once("ready",n),t.once("close",s);return}let r=++t[g].nextFlushId;t[g].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[g].flushCallbacks.delete(r),Y(t,n),process.nextTick(e,n)}}function Tu(t,e){let r=t[g].flushCallbacks;if(r.size===0)return;let n=e||new Error("the worker has exited");for(let s of r.values())process.nextTick(s,n);r.clear()}function rn(t,e){setImmediate(()=>{t.emit("error",e)})}function Y(t,e){t[g].destroyed||(t[g].destroyed=!0,Tu(t,e),e&&(t[g].errored=e,rn(t,e)),t.worker.exited?setImmediate(()=>{t[g].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[g].closed=!0,t.emit("close")}))}function vi(t,e,r){let s=Atomics.load(t[g].state,de),i=e;for(;i>0&&t[g].bufLen!==0;){let o=t[g].bufHead,a=t[g].buf[o];if(a.length<=i){a.copy(t[g].data,s),s+=a.length,i-=a.length,t[g].bufLen-=a.length,t[g].bufHead=o+1,t[g].bufHead===t[g].buf.length?(t[g].buf.length=0,t[g].bufHead=0):t[g].bufHead>=1024&&t[g].bufHead*2>=t[g].buf.length&&(t[g].buf.splice(0,t[g].bufHead),t[g].bufHead=0);continue}a.copy(t[g].data,s,0,i),t[g].buf[o]=a.subarray(i),t[g].bufLen-=i,s+=i,i=0}return nn(t,()=>{Atomics.store(t[g].state,de,s)}),r(),!0}function sn(t){if(!(t[g].ended||!t[g].ending||t[g].flushing)){t[g].ended=!0;try{t.flushSync();let e=Atomics.load(t[g].state,$e);nn(t,()=>{Atomics.store(t[g].state,de,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[g].state,$e,e,1e3),e=Atomics.load(t[g].state,$e),e===-2){Y(t,new Error("end() failed"));return}if(++r===10){Y(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[g].finished=!0,t.emit("finish")})}catch(e){Y(t,e)}}}function en(t){let e=()=>{t[g].ending?sn(t):t[g].needDrain&&process.nextTick(wi,t)};for(t[g].flushing=!1;t[g].bufLen!==0;){let r=Atomics.load(t[g].state,de),n=t[g].data.length-r;if(n===0){ki(t),gi(t);continue}else if(n<0)throw new Error("overwritten");vi(t,n,e)}}function ki(t){if(t[g].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[g].state,de),r=0;for(;;){let n=Atomics.load(t[g].state,$e);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[g].state,$e,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}Ci.exports=tn});var ln=I((Fm,Ei)=>{"use strict";var{createRequire:Au}=require("module"),{existsSync:Eu}=require("node:fs"),Ou=Wr(),{join:on,isAbsolute:Ai,sep:Ru}=require("node:path"),{fileURLToPath:Iu}=require("node:url"),Pu=Jr(),an=Zr(),Mu=$i();function Du(t){an.register(t,qu),an.registerBeforeExit(t,Uu),t.on("close",function(){an.unregister(t)})}function Fu(){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 Lu(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&&Ti(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(Ti(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function Ti(t){let e=ju(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=Iu(r)}catch{return!1}return Ai(r)&&!Eu(r)}function ju(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function Nu(t,e,r,n,s){if(!r.execArgv&&Fu()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=Lu(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new Mu({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&&Du(i)}function a(){i.closed||(i.flushSync(),Pu(100),i.end())}return i}function qu(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Uu(t){t.flushSync()}function Bu(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=Ou(),sync:a=!1}=t,l={...t.options},f=typeof o=="string"?[o]:o,u=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&r)throw new Error("only one of target or targets can be specified");r?(d=u["pino-worker"]||on(__dirname,"worker.js"),l.targets=r.filter(c=>c.target).map(c=>({...c,target:p(c.target)})),l.pipelines=r.filter(c=>c.pipeline).map(c=>c.pipeline.map(m=>({...m,level:c.level,target:p(m.target)})))):e&&(d=u["pino-worker"]||on(__dirname,"worker.js"),l.pipelines=[e.map(c=>({...c,target:p(c.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let h=r||e?"pino.transport":d;return Nu(p(d),l,i,a,h);function p(c){if(c=u[c]||c,Ai(c)||c.indexOf("file://")===0)return c;if(c==="pino/file")return on(__dirname,"..","file.js");let m;for(let y of f)try{let b=y==="node:repl"?process.cwd()+Ru:y;m=Au(b).resolve(c);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${c}"`);return m}}Ei.exports=Bu});var Bt=I((Lm,Bi)=>{"use strict";var Hu=require("node:diagnostics_channel"),Oi=Xs(),{mapHttpRequest:Wu,mapHttpResponse:Vu}=Hr(),un=si(),Ri=Zr(),{lsCacheSym:zu,chindingsSym:Fi,writeSym:Ii,serializersSym:Li,formatOptsSym:Pi,endSym:Ku,stringifiersSym:ji,stringifySym:Ni,stringifySafeSym:fn,wildcardFirstSym:qi,nestedKeySym:Gu,formattersSym:Ui,messageKeySym:Ju,errorKeySym:Xu,nestedKeyStrSym:Yu,msgPrefixSym:qt}=He(),{isMainThread:Zu}=require("worker_threads"),Qu=ln(),[ef]=process.versions.node.split(".").map(t=>Number(t)),Mi=Hu.tracingChannel("pino_asJson"),cn=ef>=25?t=>JSON.stringify(t):rf;function Ve(){}function tf(t,e){if(!e)return r;return function(...s){e.call(this,s,r,t)};function r(n,...s){if(typeof n=="object"){let i=n;n!==null&&(n.method&&n.headers&&n.socket?n=Wu(n):typeof n.setHeader=="function"&&(n=Vu(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[qt]=="string"&&i!==void 0&&i!==null&&(i=this[qt]+i),this[Ii](n,Oi(i,o,this[Pi]),t)}else{let i=n===void 0?s.shift():n;typeof this[qt]=="string"&&i!==void 0&&i!==null&&(i=this[qt]+i),this[Ii](null,Oi(i,s,this[Pi]),t)}}}function rf(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 nf(t,e,r,n){if(Mi.hasSubscribers===!1)return Di.call(this,t,e,r,n);let s={instance:this,arguments};return Mi.traceSync(Di,s,this,t,e,r,n)}function Di(t,e,r,n){let s=this[Ni],i=this[fn],o=this[ji],a=this[Ku],l=this[Fi],f=this[Li],u=this[Ui],d=this[Ju],h=this[Xu],p=this[zu][r]+n;p=p+l;let c;u.log&&(t=u.log(t));let m=o[qi],y="";for(let S in t)if(c=t[S],Object.prototype.hasOwnProperty.call(t,S)&&c!==void 0){f[S]?c=f[S](c):S===h&&f.err&&(c=f.err(c));let x=o[S]||m;switch(typeof c){case"undefined":case"function":continue;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":x&&(c=x(c));break;case"string":c=(x||cn)(c);break;default:c=(x||s)(c,i)}if(c===void 0)continue;let _=cn(S);y+=","+_+":"+c}let b="";if(e!==void 0){c=f[d]?f[d](e):e;let S=o[d]||m;switch(typeof c){case"function":break;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":S&&(c=S(c)),b=',"'+d+'":'+c;break;case"string":c=(S||cn)(c),b=',"'+d+'":'+c;break;default:c=(S||s)(c,i),b=',"'+d+'":'+c}}return this[Gu]&&y?p+this[Yu]+y.slice(1)+"}"+b+a:p+y+b+a}function sf(t,e){let r,n=t[Fi],s=t[Ni],i=t[fn],o=t[ji],a=o[qi],l=t[Li],f=t[Ui].bindings;e=f(e);for(let u in e)if(r=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&r!==void 0)===!0){if(r=l[u]?l[u](r):r,r=(o[u]||a||s)(r,i),r===void 0)continue;n+=',"'+u+'":'+r}return n}function of(t){return t.write!==t.constructor.prototype.write}function Ut(t){let e=new un(t);return e.on("error",r),!t.sync&&Zu&&(Ri.register(e,af),e.on("close",function(){Ri.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Ve,e.end=Ve,e.flushSync=Ve,e.destroy=Ve;return}e.removeListener("error",r),e.emit("error",n)}}function af(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function lf(t){return function(r,n,s={},i){if(typeof s=="string")i=Ut({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=Ut({dest:i})}else if(s instanceof un||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof un||s.transport.writable||s.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(s.transport.targets&&s.transport.targets.length&&s.formatters&&typeof s.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;s.customLevels&&(l=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=Qu({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=Ve),i||(of(process.stdout)?i=process.stdout:i=Ut({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function cf(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[fn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function uf(t,e,r){return{level:t,bindings:e,log:r}}function ff(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Bi.exports={noop:Ve,buildSafeSonicBoom:Ut,asChindings:sf,asJson:nf,genLog:tf,createArgsNormalizer:lf,stringify:cf,buildFormatters:uf,normalizeDestFileDescriptor:ff}});var Ht=I((jm,Hi)=>{var df={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},pf={ASC:"ASC",DESC:"DESC"};Hi.exports={DEFAULT_LEVELS:df,SORTING_ORDER:pf}});var hn=I((Nm,Ki)=>{"use strict";var{lsCacheSym:hf,levelValSym:dn,useOnlyCustomLevelsSym:mf,streamSym:gf,formattersSym:yf,hooksSym:wf,levelCompSym:Wi}=He(),{noop:bf,genLog:Te}=Bt(),{DEFAULT_LEVELS:ce,SORTING_ORDER:Vi}=Ht(),zi={fatal:t=>{let e=Te(ce.fatal,t);return function(...r){let n=this[gf];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>Te(ce.error,t),warn:t=>Te(ce.warn,t),info:t=>Te(ce.info,t),debug:t=>Te(ce.debug,t),trace:t=>Te(ce.trace,t)},pn=Object.keys(ce).reduce((t,e)=>(t[ce[e]]=e,t),{}),Sf=Object.keys(pn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function _f(t){let e=t[yf].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[hf]=n,t}function xf(t,e){if(e)return!1;switch(t){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function vf(t){let{labels:e,values:r}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(r[t]===void 0)throw Error("unknown level "+t);let n=this[dn],s=this[dn]=r[t],i=this[mf],o=this[Wi],a=this[wf].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=bf;continue}this[l]=xf(l,i)?zi[l](a):Te(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function kf(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Cf(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Wi](r,this[dn])}function $f(t,e,r){return t===Vi.DESC?e<=r:e>=r}function Tf(t){return typeof t=="string"?$f.bind(null,t):t}function Af(t=null,e=!1){let r=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:pn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:ce,t);return{labels:n,values:s}}function Ef(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(pn).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:ce,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function Of(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 Rf(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Vi).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Ki.exports={initialLsCache:Sf,genLsCache:_f,levelMethods:zi,getLevel:kf,setLevel:vf,isLevelEnabled:Cf,mappings:Af,assertNoLevelCollisions:Of,assertDefaultLevelFound:Ef,genLevelComparison:Tf,assertLevelComparison:Rf}});var mn=I((qm,Gi)=>{"use strict";Gi.exports={version:"10.3.1"}});var ro=I((Bm,to)=>{"use strict";var{EventEmitter:If}=require("node:events"),{lsCacheSym:Pf,levelValSym:Mf,setLevelSym:yn,getLevelSym:Ji,chindingsSym:Vt,mixinSym:Df,asJsonSym:Yi,writeSym:Ff,mixinMergeStrategySym:Lf,timeSym:jf,timeSliceIndexSym:Nf,streamSym:Zi,serializersSym:Ae,formattersSym:ft,errorKeySym:qf,messageKeySym:Uf,useOnlyCustomLevelsSym:Bf,needsMetadataGsym:Hf,redactFmtSym:Wf,stringifySym:Vf,formatOptsSym:zf,stringifiersSym:Kf,msgPrefixSym:wn,hooksSym:Gf}=He(),{getLevel:Jf,setLevel:Xf,isLevelEnabled:Yf,mappings:Zf,initialLsCache:Qf,genLsCache:ed,assertNoLevelCollisions:td}=hn(),{asChindings:bn,asJson:rd,buildFormatters:gn,stringify:Xi,noop:Qi}=Bt(),{version:nd}=mn(),sd=Kr(),id=class{},eo={constructor:id,child:od,bindings:ad,setBindings:ld,flush:fd,isLevelEnabled:Yf,version:nd,get level(){return this[Ji]()},set level(t){this[yn](t)},get levelVal(){return this[Mf]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[wn]},get[Symbol.toStringTag](){return"Pino"},[Pf]:Qf,[Ff]:ud,[Yi]:rd,[Ji]:Jf,[yn]:Xf};Object.setPrototypeOf(eo,If.prototype);to.exports=function(){return Object.create(eo)};var Wt=t=>t;function od(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[Ae],n=this[ft],s=Object.create(this);if(e==null)return s[ft].bindings!==Wt&&(s[ft]=gn(n.level,Wt,n.log)),s[Vt]=bn(s,t),this.onChild!==Qi&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[Ae]=Object.create(null);for(let f in r)s[Ae][f]=r[f];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let f=a[i];s[Ae][f]=r[f]}for(let f in e.serializers)s[Ae][f]=e.serializers[f];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let f=l[o];s[Ae][f]=e.serializers[f]}}else s[Ae]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:f}=e.formatters;s[ft]=gn(a||n.level,l||Wt,f||n.log)}else s[ft]=gn(n.level,Wt,n.log);if(e.hasOwnProperty("customLevels")===!0&&(td(this.levels,e.customLevels),s.levels=Zf(e.customLevels,s[Bf]),ed(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=sd(s.redact,Xi),l={stringify:a[Wf]};s[Vf]=Xi,s[Kf]=a,s[zf]=l}if(typeof e.msgPrefix=="string"&&(s[wn]=(this[wn]||"")+e.msgPrefix),s[Vt]=bn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[yn](a)}return this.onChild(s),s}function ad(){let e=`{${this[Vt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function ld(t){let e=bn(this,t);this[Vt]=e}function cd(t,e){return Object.assign(e,t)}function ud(t,e,r){let n=this[jf](),s=this[Df],i=this[qf],o=this[Uf],a=this[Lf]||cd,l,f=this[Gf].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[Yi](l,e,r,n),d=this[Zi];d[Hf]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[Nf]),d.lastLogger=this),d.write(f?f(u):u)}function fd(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Zi];typeof e.flush=="function"?e.flush(t||Qi):t&&t()}});var oo=I((vn,io)=>{"use strict";var{hasOwnProperty:dt}=Object.prototype,Oe=xn();Oe.configure=xn;Oe.stringify=Oe;Oe.default=Oe;vn.stringify=Oe;vn.configure=xn;io.exports=Oe;var dd=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function be(t){return t.length<5e3&&!dd.test(t)?`"${t}"`:JSON.stringify(t)}function Sn(t,e){if(t.length>200||e)return t.sort(e);for(let r=1;r<t.length;r++){let n=t[r],s=r;for(;s!==0&&t[s-1]>n;)t[s]=t[s-1],s--;t[s]=n}return t}var pd=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function _n(t){return pd.call(t)!==void 0&&t.length!==0}function no(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 hd(t){if(dt.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 md(t){let e;if(dt.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 gd(t,e){let r;if(dt.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 so(t,e){let r;if(dt.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 Ee(t){return t===1?"1 item":`${t} items`}function yd(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function wd(t){if(dt.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function xn(t){t={...t};let e=wd(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=hd(t),n=gd(t,"bigint"),s=md(t),i=typeof s=="function"?s:void 0,o=so(t,"maximumDepth"),a=so(t,"maximumBreadth");function l(p,c,m,y,b,S){let x=c[p];switch(typeof x=="object"&&x!==null&&typeof x.toJSON=="function"&&(x=x.toJSON(p)),x=y.call(c,p,x),typeof x){case"string":return be(x);case"object":{if(x===null)return"null";if(m.indexOf(x)!==-1)return r;let _="",C=",",R=S;if(Array.isArray(x)){if(x.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(x),b!==""&&(S+=b,_+=`
|
|
26
|
+
${S}`,C=`,
|
|
27
|
+
${S}`);let F=Math.min(x.length,a),H=0;for(;H<F-1;H++){let W=l(String(H),x,m,y,b,S);_+=W!==void 0?W:"null",_+=C}let U=l(String(H),x,m,y,b,S);if(_+=U!==void 0?U:"null",x.length-1>a){let W=x.length-a-1;_+=`${C}"... ${Ee(W)} not stringified"`}return b!==""&&(_+=`
|
|
28
|
+
${R}`),m.pop(),`[${_}]`}let T=Object.keys(x),O=T.length;if(O===0)return"{}";if(o<m.length+1)return'"[Object]"';let $="",P="";b!==""&&(S+=b,C=`,
|
|
29
|
+
${S}`,$=" ");let N=Math.min(O,a);s&&!_n(x)&&(T=Sn(T,i)),m.push(x);for(let F=0;F<N;F++){let H=T[F],U=l(H,x,m,y,b,S);U!==void 0&&(_+=`${P}${be(H)}:${$}${U}`,P=C)}if(O>a){let F=O-a;_+=`${P}"...":${$}"${Ee(F)} not stringified"`,P=C}return b!==""&&P.length>1&&(_=`
|
|
30
|
+
${S}${_}
|
|
31
|
+
${R}`),m.pop(),`{${_}}`}case"number":return isFinite(x)?String(x):e?e(x):"null";case"boolean":return x===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(x);default:return e?e(x):void 0}}function f(p,c,m,y,b,S){switch(typeof c=="object"&&c!==null&&typeof c.toJSON=="function"&&(c=c.toJSON(p)),typeof c){case"string":return be(c);case"object":{if(c===null)return"null";if(m.indexOf(c)!==-1)return r;let x=S,_="",C=",";if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),b!==""&&(S+=b,_+=`
|
|
32
|
+
${S}`,C=`,
|
|
33
|
+
${S}`);let O=Math.min(c.length,a),$=0;for(;$<O-1;$++){let N=f(String($),c[$],m,y,b,S);_+=N!==void 0?N:"null",_+=C}let P=f(String($),c[$],m,y,b,S);if(_+=P!==void 0?P:"null",c.length-1>a){let N=c.length-a-1;_+=`${C}"... ${Ee(N)} not stringified"`}return b!==""&&(_+=`
|
|
34
|
+
${x}`),m.pop(),`[${_}]`}m.push(c);let R="";b!==""&&(S+=b,C=`,
|
|
35
|
+
${S}`,R=" ");let T="";for(let O of y){let $=f(O,c[O],m,y,b,S);$!==void 0&&(_+=`${T}${be(O)}:${R}${$}`,T=C)}return b!==""&&T.length>1&&(_=`
|
|
36
|
+
${S}${_}
|
|
37
|
+
${x}`),m.pop(),`{${_}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function u(p,c,m,y,b){switch(typeof c){case"string":return be(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(p),typeof c!="object")return u(p,c,m,y,b);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let S=b;if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),b+=y;let $=`
|
|
38
|
+
${b}`,P=`,
|
|
39
|
+
${b}`,N=Math.min(c.length,a),F=0;for(;F<N-1;F++){let U=u(String(F),c[F],m,y,b);$+=U!==void 0?U:"null",$+=P}let H=u(String(F),c[F],m,y,b);if($+=H!==void 0?H:"null",c.length-1>a){let U=c.length-a-1;$+=`${P}"... ${Ee(U)} not stringified"`}return $+=`
|
|
40
|
+
${S}`,m.pop(),`[${$}]`}let x=Object.keys(c),_=x.length;if(_===0)return"{}";if(o<m.length+1)return'"[Object]"';b+=y;let C=`,
|
|
41
|
+
${b}`,R="",T="",O=Math.min(_,a);_n(c)&&(R+=no(c,C,a),x=x.slice(c.length),O-=c.length,T=C),s&&(x=Sn(x,i)),m.push(c);for(let $=0;$<O;$++){let P=x[$],N=u(P,c[P],m,y,b);N!==void 0&&(R+=`${T}${be(P)}: ${N}`,T=C)}if(_>a){let $=_-a;R+=`${T}"...": "${Ee($)} not stringified"`,T=C}return T!==""&&(R=`
|
|
42
|
+
${b}${R}
|
|
43
|
+
${S}`),m.pop(),`{${R}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function d(p,c,m){switch(typeof c){case"string":return be(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(p),typeof c!="object")return d(p,c,m);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let y="",b=c.length!==void 0;if(b&&Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c);let R=Math.min(c.length,a),T=0;for(;T<R-1;T++){let $=d(String(T),c[T],m);y+=$!==void 0?$:"null",y+=","}let O=d(String(T),c[T],m);if(y+=O!==void 0?O:"null",c.length-1>a){let $=c.length-a-1;y+=`,"... ${Ee($)} not stringified"`}return m.pop(),`[${y}]`}let S=Object.keys(c),x=S.length;if(x===0)return"{}";if(o<m.length+1)return'"[Object]"';let _="",C=Math.min(x,a);b&&_n(c)&&(y+=no(c,",",a),S=S.slice(c.length),C-=c.length,_=","),s&&(S=Sn(S,i)),m.push(c);for(let R=0;R<C;R++){let T=S[R],O=d(T,c[T],m);O!==void 0&&(y+=`${_}${be(T)}:${O}`,_=",")}if(x>a){let R=x-a;y+=`${_}"...":"${Ee(R)} not stringified"`}return m.pop(),`{${y}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function h(p,c,m){if(arguments.length>1){let y="";if(typeof m=="number"?y=" ".repeat(Math.min(m,10)):typeof m=="string"&&(y=m.slice(0,10)),c!=null){if(typeof c=="function")return l("",{"":p},[],c,y,"");if(Array.isArray(c))return f("",p,[],yd(c),y,"")}if(y.length!==0)return u("",p,[],y,"")}return d("",p,[])}return h}});var uo=I((Hm,co)=>{"use strict";var kn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:lo}=Ht(),bd=lo.info;function Sd(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(lo);r.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(d=>{r[d]=e.levels[d]});let n={write:s,add:a,remove:l,emit:i,flushSync:o,end:f,minLevel:0,lastId:0,streams:[],clone:u,[kn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(d){let h,p=this.lastLevel,{streams:c}=this,m=0,y;for(let b=_d(c.length,e.dedupe);vd(b,c.length,e.dedupe);b=xd(b,e.dedupe))if(h=c[b],h.level<=p){if(m!==0&&m!==h.level)break;if(y=h.stream,y[kn]){let{lastTime:S,lastMsg:x,lastObj:_,lastLogger:C}=this;y.lastLevel=p,y.lastTime=S,y.lastMsg=x,y.lastObj=_,y.lastLogger=C}y.write(d),e.dedupe&&(m=h.level)}else if(!e.dedupe)break}function i(...d){for(let{stream:h}of this.streams)typeof h.emit=="function"&&h.emit(...d)}function o(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync()}function a(d){if(!d)return n;let h=typeof d.write=="function"||d.stream,p=d.write?d:d.stream;if(!h)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:c,streamLevels:m}=this,y;typeof d.levelVal=="number"?y=d.levelVal:typeof d.level=="string"?y=m[d.level]:typeof d.level=="number"?y=d.level:y=bd;let b={stream:p,level:y,levelVal:void 0,id:++n.lastId};return c.unshift(b),c.sort(ao),this.minLevel=c[0].level,n}function l(d){let{streams:h}=this,p=h.findIndex(c=>c.id===d);return p>=0&&(h.splice(p,1),h.sort(ao),this.minLevel=h.length>0?h[0].level:-1),n}function f(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function u(d){let h=new Array(this.streams.length);for(let p=0;p<h.length;p++)h[p]={level:d,stream:this.streams[p].stream};return{write:s,add:a,remove:l,minLevel:d,streams:h,clone:u,emit:i,flushSync:o,[kn]:!0}}}function ao(t,e){return t.level-e.level}function _d(t,e){return e?t-1:0}function xd(t,e){return e?t-1:t+1}function vd(t,e,r){return r?t>=0:t<e}co.exports=Sd});var Co=I((Wm,Z)=>{"use strict";var kd=require("node:os"),bo=Hr(),Cd=Wr(),$d=Kr(),So=Gs(),Td=ro(),_o=He(),{configure:Ad}=oo(),{assertDefaultLevelFound:Ed,mappings:xo,genLsCache:Od,genLevelComparison:Rd,assertLevelComparison:Id}=hn(),{DEFAULT_LEVELS:vo,SORTING_ORDER:Pd}=Ht(),{createArgsNormalizer:Md,asChindings:Dd,buildSafeSonicBoom:fo,buildFormatters:Fd,stringify:Cn,normalizeDestFileDescriptor:po,noop:Ld}=Bt(),{version:jd}=mn(),{chindingsSym:ho,redactFmtSym:Nd,serializersSym:mo,timeSym:qd,timeSliceIndexSym:Ud,streamSym:Bd,stringifySym:go,stringifySafeSym:$n,stringifiersSym:yo,setLevelSym:Hd,endSym:Wd,formatOptsSym:Vd,messageKeySym:zd,errorKeySym:Kd,nestedKeySym:Gd,mixinSym:Jd,levelCompSym:Xd,useOnlyCustomLevelsSym:Yd,formattersSym:wo,hooksSym:Zd,nestedKeyStrSym:Qd,mixinMergeStrategySym:ep,msgPrefixSym:tp}=_o,{epochTime:ko,nullTime:rp}=So,{pid:np}=process,sp=kd.hostname(),ip=bo.err,op={level:"info",levelComparison:Pd.ASC,levels:vo,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:np,hostname:sp},serializers:Object.assign(Object.create(null),{err:ip}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:ko,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},ap=Md(op),lp=Object.assign(Object.create(null),bo);function Tn(...t){let e={},{opts:r,stream:n}=ap(e,Cd(),...t);r.level&&typeof r.level=="string"&&vo[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:f,nestedKey:u,base:d,name:h,level:p,customLevels:c,levelComparison:m,mixin:y,mixinMergeStrategy:b,useOnlyCustomLevels:S,formatters:x,hooks:_,depthLimit:C,edgeLimit:R,onChild:T,msgPrefix:O}=r,$=Ad({maximumDepth:C,maximumBreadth:R}),P=Fd(x.level,x.bindings,x.log),N=Cn.bind({[$n]:$}),F=s?$d(s,N):{},H=s?{stringify:F[Nd]}:{stringify:N},U="}"+(i?`\r
|
|
44
44
|
`:`
|
|
45
|
-
`),W=
|
|
46
|
-
`);o=f.pop()||"";for(let u of f)if(u.trim())try{let d=JSON.parse(u);d.message?.content&&(yield d.message.content)}catch{}}}};var
|
|
47
|
-
`);a=u.pop()||"";for(let d of u){let h=d.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let c=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;c&&(yield c)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function
|
|
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
|
|
50
|
-
`);if(
|
|
45
|
+
`),W=Dd.bind(null,{[ho]:"",[mo]:o,[yo]:F,[go]:Cn,[$n]:$,[wo]:P}),D="";d!==null&&(h===void 0?D=W(d):D=W(Object.assign({},d,{name:h})));let V=a instanceof Function?a:a?ko:rp,mr=V().indexOf(":")+1;if(S&&!c)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(y&&typeof y!="function")throw Error(`Unknown mixin type "${typeof y}" - expected "function"`);if(O&&typeof O!="string")throw Error(`Unknown msgPrefix type "${typeof O}" - expected "string"`);Ed(p,c,S);let gr=xo(c,S);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:gr,messageKey:l,errorKey:f}}),Id(m);let yr=Rd(m);return Object.assign(e,{levels:gr,[Xd]:yr,[Yd]:S,[Bd]:n,[qd]:V,[Ud]:mr,[go]:Cn,[$n]:$,[yo]:F,[Wd]:U,[Vd]:H,[zd]:l,[Kd]:f,[Gd]:u,[Qd]:u?`,${JSON.stringify(u)}:{`:"",[mo]:o,[Jd]:y,[ep]:b,[ho]:D,[wo]:P,[Zd]:_,silent:Ld,onChild:T,[tp]:O}),Object.setPrototypeOf(e,Td()),Od(e),e[Hd](p),e}Z.exports=Tn;Z.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=po(t.dest||process.stdout.fd),fo(t)):fo({dest:po(t),minLength:0});Z.exports.transport=ln();Z.exports.multistream=uo();Z.exports.levels=xo();Z.exports.stdSerializers=lp;Z.exports.stdTimeFunctions=Object.assign({},So);Z.exports.symbols=_o;Z.exports.version=jd;Z.exports.default=Tn;Z.exports.pino=Tn});var fs=k(us(),1),{program:em,createCommand:tm,createArgument:rm,createOption:nm,CommanderError:sm,InvalidArgumentError:im,InvalidOptionArgumentError:om,Command:ds,Argument:am,Option:lm,Help:cm}=fs.default;var ne=k(require("fs")),Ce=k(require("path")),ps=k(require("os"));var lt={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:200,timeout:12e4,autoMode:!1,contextBudget:12e4,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0}},le={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 qe=Ce.join(ps.homedir(),".hablas"),Pr=Ce.join(qe,"config.json");function Ue(t={}){let e={};if(ne.existsSync(Pr))try{e=JSON.parse(ne.readFileSync(Pr,"utf-8"))}catch{}let r={...lt,...e,tools:{...lt.tools,...e.tools||{},runCommand:{...lt.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...lt.workspace,...e.workspace||{}}};if(process.env.HABLAS_API_URL&&(r.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(r.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_MODEL&&(r.model=process.env.HABLAS_MODEL),process.env.HABLAS_PROVIDER){let n=process.env.HABLAS_PROVIDER;(n==="ollama"||n==="custom"||n==="nvidia")&&(r.provider=n)}if(t.model&&(r.model=t.model),t.host&&(r.ollamaHost=t.host),t.project&&(r.workingDirectory=Ce.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 Be(t){ne.existsSync(qe)||ne.mkdirSync(qe,{recursive:!0}),ne.writeFileSync(Pr,JSON.stringify(t,null,2),"utf-8")}function hs(){let t=[qe,Ce.join(qe,"logs"),Ce.join(qe,"backup")];for(let e of t)ne.existsSync(e)||ne.mkdirSync(e,{recursive:!0})}var An=k(Co()),En=k(require("path")),$o=k(require("os")),zt=k(require("fs"));function On(t){let e=En.join($o.homedir(),".hablas","logs");zt.existsSync(e)||zt.mkdirSync(e,{recursive:!0});let r=En.join(e,`session-${Date.now()}.log`);return(0,An.default)({level:"info"},An.default.destination({dest:r,sync:!1}))}var Kt=k(require("fs")),pt=k(require("path"));function To(){let t=[pt.resolve(__dirname,"..","package.json"),pt.resolve(__dirname,"..","..","package.json"),pt.resolve(process.cwd(),"package.json"),pt.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(Kt.existsSync(e)){let r=JSON.parse(Kt.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var za=k(require("fs")),Ka=k(require("path"));var Gt=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(n=>n.name):[]}catch{return[]}}async chatWithTools(e,r,n){let s={model:this.model,messages:e,stream:!1};r.length>0&&(s.tools=r);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)};n&&(i.signal=n);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,r){let n=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:r});if(!n.ok)throw new Error(`Ollama error: ${n.status} ${n.statusText}`);let s=n.body?.getReader();if(!s)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await s.read();if(a)break;o+=i.decode(l,{stream:!0});let f=o.split(`
|
|
46
|
+
`);o=f.pop()||"";for(let u of f)if(u.trim())try{let d=JSON.parse(u);d.message?.content&&(yield d.message.content)}catch{}}}};var Ao=12e4,cp=6e4,Jt=3,Eo=1e3,up=20;function Oo(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 fp(t){return t.map(e=>({type:"function",function:e.function}))}function dp(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 Ro(t){return new Promise(e=>setTimeout(e,t))}function Io(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var ht=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<up;){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(cp)});if(!l.ok)break;let f=await l.json();if(Array.isArray(f))e.push(...f.map(u=>u.id||u.name||u).filter(Boolean)),r=!1;else if(f.data&&Array.isArray(f.data)){let u=f.data.map(d=>d.id||d.name).filter(Boolean);e.push(...u),f.has_more&&u.length>0?(n=u[u.length-1],s++):r=!1}else f.models&&Array.isArray(f.models)&&e.push(...f.models.map(u=>u.name||u.id).filter(Boolean)),r=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,r,n){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:Oo(e)};r.length>0&&(i.tools=fp(r),i.tool_choice="auto");let o=null;for(let a=0;a<=Jt;a++)try{let l=new AbortController,f=setTimeout(()=>l.abort(),Ao),u={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:n||l.signal};try{let d=await fetch(s,u);if(clearTimeout(f),!d.ok){let m=await d.text().catch(()=>"");if(!Io(null,d.status))throw new Error(`API error: ${d.status} ${d.statusText} \u2014 ${m}`);if(o=new Error(`API error: ${d.status} ${d.statusText} \u2014 ${m}`),a<Jt){let y=Eo*Math.pow(2,a);await Ro(y);continue}throw o}let p=(await d.json()).choices?.[0];if(!p)throw new Error("API returned empty response");let c=p.message.tool_calls?dp(p.message.tool_calls):void 0;return{message:{role:p.message.role||"assistant",content:p.message.content||"",tool_calls:c},done:!0,done_reason:p.finish_reason}}catch(d){if(clearTimeout(f),d.name==="AbortError"&&n?.aborted)throw d;if(Io(d)&&(o=d,a<Jt)){let h=Eo*Math.pow(2,a);await Ro(h);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Jt)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:Oo(e),stream:!0}),signal:r||AbortSignal.timeout(Ao)});if(!s.ok)throw new Error(`API error: ${s.status} ${s.statusText}`);let i=s.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:f}=await i.read();if(l)break;a+=o.decode(f,{stream:!0});let u=a.split(`
|
|
47
|
+
`);a=u.pop()||"";for(let d of u){let h=d.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let c=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;c&&(yield c)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function ze(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:le.apiUrl};return new ht(e)}return t.provider==="custom"&&t.apiUrl?new ht(t):new Gt(t)}function Ke(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var j=k(require("fs/promises")),jn=k(require("fs")),Se=k(require("path"));function pe(){}pe.prototype={diff:function(e,r){var n,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=s.callback;typeof s=="function"&&(i=s,s={}),this.options=s;var o=this;function a(_){return i?(setTimeout(function(){i(void 0,_)},0),!0):_}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,f=e.length,u=1,d=l+f;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var h=(n=s.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+h,c=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(c[0],r,e,0);if(c[0].oldPos+1>=f&&m+1>=l)return a([{value:this.join(r),count:r.length}]);var y=-1/0,b=1/0;function S(){for(var _=Math.max(y,-u);_<=Math.min(b,u);_+=2){var C=void 0,R=c[_-1],T=c[_+1];R&&(c[_-1]=void 0);var O=!1;if(T){var $=T.oldPos-_;O=T&&0<=$&&$<l}var P=R&&R.oldPos+1<f;if(!O&&!P){c[_]=void 0;continue}if(!P||O&&R.oldPos+1<T.oldPos?C=o.addToPath(T,!0,void 0,0):C=o.addToPath(R,void 0,!0,1),m=o.extractCommon(C,r,e,_),C.oldPos+1>=f&&m+1>=l)return a(pp(o,C.lastComponent,r,e,o.useLongestToken));c[_]=C,C.oldPos+1>=f&&(b=Math.min(b,_-1)),m+1>=l&&(y=Math.max(y,_+1))}u++}if(i)(function _(){setTimeout(function(){if(u>d||Date.now()>p)return i();S()||_()},0)})();else for(;u<=d&&Date.now()<=p;){var x=S();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,f=0;l+1<i&&a+1<o&&this.equals(r[l+1],n[a+1]);)l++,a++,f++;return f&&(e.lastComponent={count:f,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,r){return this.options.comparator?this.options.comparator(e,r):e===r||this.options.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function pp(t,e,r,n,s){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,f=0,u=0;a<l;a++){var d=i[a];if(d.removed){if(d.value=t.join(n.slice(u,u+d.count)),u+=d.count,a&&i[a-1].added){var p=i[a-1];i[a-1]=i[a],i[a]=p}}else{if(!d.added&&s){var h=r.slice(f,f+d.count);h=h.map(function(m,y){var b=n[u+y];return b.length>m.length?b:m}),d.value=t.join(h)}else d.value=t.join(r.slice(f,f+d.count));f+=d.count,d.added||(u+=d.count)}}var c=i[l-1];return l>1&&typeof c.value=="string"&&(c.added||c.removed)&&t.equals("",c.value)&&(i[l-2].value+=c.value,i.pop()),i}var ig=new pe;var Po=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Mo=/\S/,Do=new pe;Do.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!Mo.test(t)&&!Mo.test(e)};Do.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]&&Po.test(e[r])&&Po.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var Dn=new pe;Dn.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
|
|
48
|
+
`));var e=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var n=0;n<r.length;n++){var s=r[n];n%2&&!this.options.newlineIsToken?e[e.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),e.push(s))}return e};function hp(t,e,r){return Dn.diff(t,e,r)}var mp=new pe;mp.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var gp=new pe;gp.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Xt(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Xt=function(e){return typeof e}:Xt=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Xt(t)}function Rn(t){return yp(t)||wp(t)||bp(t)||Sp()}function yp(t){if(Array.isArray(t))return In(t)}function wp(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function bp(t,e){if(t){if(typeof t=="string")return In(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return In(t,e)}}function In(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function Sp(){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 _p=Object.prototype.toString,mt=new pe;mt.useLongestToken=!0;mt.tokenize=Dn.tokenize;mt.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(Pn(t,null,null,s),s," ")};mt.equals=function(t,e){return pe.prototype.equals.call(mt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function Pn(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(_p.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]=Pn(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),Xt(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]=Pn(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var Mn=new pe;Mn.tokenize=function(t){return t.slice()};Mn.join=Mn.removeEmpty=function(t){return t};function xp(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=hp(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(b){return b.map(function(S){return" "+S})}for(var f=[],u=0,d=0,h=[],p=1,c=1,m=function(S){var x=a[S],_=x.lines||x.value.replace(/\n$/,"").split(`
|
|
50
|
+
`);if(x.lines=_,x.added||x.removed){var C;if(!u){var R=a[S-1];u=p,d=c,R&&(h=o.context>0?l(R.lines.slice(-o.context)):[],u-=h.length,d-=h.length)}(C=h).push.apply(C,Rn(_.map(function(U){return(x.added?"+":"-")+U}))),x.added?c+=_.length:p+=_.length}else{if(u)if(_.length<=o.context*2&&S<a.length-2){var T;(T=h).push.apply(T,Rn(l(_)))}else{var O,$=Math.min(_.length,o.context);(O=h).push.apply(O,Rn(l(_.slice(0,$))));var P={oldStart:u,oldLines:p-u+$,newStart:d,newLines:c-d+$,lines:h};if(S>=a.length-2&&_.length<=o.context){var N=/\n$/.test(r),F=/\n$/.test(n),H=_.length==0&&h.length>P.oldLines;!N&&H&&r.length>0&&h.splice(P.oldLines,0,"\"),(!N&&!H||!F)&&h.push("\")}f.push(P),u=0,d=0,h=[]}p+=_.length,c+=_.length}},y=0;y<a.length;y++)m(y);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:f}}function Fo(t){if(Array.isArray(t))return t.map(Fo).join(`
|
|
51
51
|
`);var e=[];t.oldFileName==t.newFileName&&e.push("Index: "+t.oldFileName),e.push("==================================================================="),e.push("--- "+t.oldFileName+(typeof t.oldHeader>"u"?"":" "+t.oldHeader)),e.push("+++ "+t.newFileName+(typeof t.newHeader>"u"?"":" "+t.newHeader));for(var r=0;r<t.hunks.length;r++){var n=t.hunks[r];n.oldLines===0&&(n.oldStart-=1),n.newLines===0&&(n.newStart-=1),e.push("@@ -"+n.oldStart+","+n.oldLines+" +"+n.newStart+","+n.newLines+" @@"),e.push.apply(e,n.lines)}return e.join(`
|
|
52
52
|
`)+`
|
|
53
|
-
`}function
|
|
54
|
-
`),
|
|
55
|
-
... [Partial read. Total lines: ${
|
|
53
|
+
`}function vp(t,e,r,n,s,i,o){return Fo(xp(t,e,r,n,s,i,o))}function Lo(t,e,r,n,s,i){return vp(t,t,e,r,n,s,i)}function Fn(t,e,r){return Lo(t,e,r,"original","modified")}var ue=k(require("fs/promises")),Ln=k(require("fs")),Ge=k(require("path")),No=k(require("os")),gt=Ge.join(No.homedir(),".hablas","backup"),jo=10;async function Re(t){try{if(!Ln.existsSync(t))return;Ln.existsSync(gt)||await ue.mkdir(gt,{recursive:!0});let e=await ue.readFile(t,"utf-8"),r=Ge.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=Ge.join(gt,s);await ue.writeFile(i,e,"utf-8");let a=(await ue.readdir(gt)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>jo)for(let l of a.slice(jo))await ue.unlink(Ge.join(gt,l))}catch{}}function Uo(t){let e=p=>Se.resolve(t,p);return[{name:"read_file",description:"Read the FULL content of a file with line numbers (complete read, no truncation by default per user requirement for 1000/2000+ line files like architecture docs). Use start_line/end_line ONLY if you explicitly need a specific section. Never re-read the same path this turn \u2014 use previous tool observations from history.",safety:"safe",parameters:{path:{type:"string",description:"File path to read",required:!0},start_line:{type:"number",description:"Starting line number (1-based, optional)",required:!1},end_line:{type:"number",description:"Ending line number (inclusive, optional)",required:!1}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[read_file]: path is required"};let c=e(p.path),y=(await j.readFile(c,"utf-8")).split(`
|
|
54
|
+
`),b=y.length,S=p.start_line?Math.max(1,p.start_line):1,x=p.end_line?Math.min(b,p.end_line):b,_=y.slice(S-1,x),C=String(x).length,R=_.map(($,P)=>`${String(S+P).padStart(C," ")} | ${$}`),T=`[${p.path} \u2014 lines ${S}-${x} of ${b}]`,O=x<b?`
|
|
55
|
+
... [Partial read. Total lines: ${b}.]`:"";return{success:!0,output:`${T}
|
|
56
56
|
${R.join(`
|
|
57
|
-
`)}${O}`}}catch(c){return{success:!1,output:"",error:`[read_file]: ${c.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let c=e(p.path);return
|
|
58
|
-
${
|
|
59
|
-
`),
|
|
60
|
-
`),T=[...
|
|
61
|
-
`);await j.writeFile(c,T,"utf-8");let O=
|
|
62
|
-
${O}`}}catch(c){return{success:!1,output:"",error:`[patch_file]: ${c.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!p.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(p.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=p.search,
|
|
63
|
-
`)}}catch(c){return{success:!1,output:"",error:`[get_file_info]: ${c.message}`}}}}]}function
|
|
64
|
-
`,l.isDirectory()){let h=e+(f?" ":"\u2502 ");o+=await
|
|
57
|
+
`)}${O}`}}catch(c){return{success:!1,output:"",error:`[read_file]: ${c.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let c=e(p.path);return jn.existsSync(c)&&await Re(c),await j.mkdir(Se.dirname(c),{recursive:!0}),await j.writeFile(c,p.content,"utf-8"),{success:!0,output:`Written: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[write_file]: ${c.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!p.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=p.old_content,b=p.new_content,S=qo(m,y);if(S===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(S>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${S} locations in the file. Provide more surrounding context to be specific.`};await Re(c);let x=m.replace(y,b);await j.writeFile(c,x,"utf-8");let _=Fn(p.path,m,x);return{success:!0,output:`Edited: ${p.path}
|
|
58
|
+
${_}`}}catch(c){return{success:!1,output:"",error:`[edit_file]: ${c.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!p.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!p.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(p.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=m.split(`
|
|
59
|
+
`),b=y.length,S=p.start_line,x=p.end_line;if(S<1||S>b)return{success:!1,output:"",error:`[patch_file]: start_line ${S} is out of range (file has ${b} lines)`};if(x<S||x>b)return{success:!1,output:"",error:`[patch_file]: end_line ${x} is out of range (start_line=${S}, total=${b})`};await Re(c);let _=y.slice(0,S-1),C=y.slice(x),R=p.new_content.split(`
|
|
60
|
+
`),T=[..._,...R,...C].join(`
|
|
61
|
+
`);await j.writeFile(c,T,"utf-8");let O=Fn(p.path,m,T),$=x-S+1,P=R.length;return{success:!0,output:`Patched: ${p.path} (replaced ${$} lines with ${P})
|
|
62
|
+
${O}`}}catch(c){return{success:!1,output:"",error:`[patch_file]: ${c.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!p.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(p.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=p.search,b=p.replace,S=p.is_regex;await Re(c);let x,_;if(S){let C=new RegExp(y,"g");_=(m.match(C)||[]).length,x=m.replace(C,b)}else _=qo(m,y),x=m.split(y).join(b);return _===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await j.writeFile(c,x,"utf-8"),{success:!0,output:`Replaced ${_} occurrence(s) in ${p.path}`})}catch(c){return{success:!1,output:"",error:`[search_and_replace]: ${c.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let c=e(p.path);return await j.mkdir(Se.dirname(c),{recursive:!0}),jn.existsSync(c)&&await Re(c),await j.appendFile(c,p.content,"utf-8"),{success:!0,output:`Appended to: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[append_to_file]: ${c.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let c=e(p.path);return await Re(c),await j.unlink(c),{success:!0,output:`Deleted: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[delete_file]: ${c.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async p=>{try{if(!p.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!p.to)return{success:!1,output:"",error:"[move_file]: to is required"};let c=e(p.from),m=e(p.to);return await j.mkdir(Se.dirname(m),{recursive:!0}),await j.rename(c,m),{success:!0,output:`Moved: ${p.from} \u2192 ${p.to}`}}catch(c){return{success:!1,output:"",error:`[move_file]: ${c.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let c=e(p.path);return await j.mkdir(c,{recursive:!0}),{success:!0,output:`Created directory: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[create_dir]: ${c.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async p=>{try{let c=e(p.path||"."),m=p.depth||3;return{success:!0,output:await Bo(c,"",m,0)||"(empty directory)"}}catch(c){return{success:!1,output:"",error:`[list_dir]: ${c.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let c=e(p.path),m=await j.stat(c);return{success:!0,output:[`Path: ${p.path}`,`Size: ${Cp(m.size)}`,`Type: ${m.isDirectory()?"directory":"file"}`,`Modified: ${m.mtime.toISOString()}`,`Created: ${m.birthtime.toISOString()}`].join(`
|
|
63
|
+
`)}}catch(c){return{success:!1,output:"",error:`[get_file_info]: ${c.message}`}}}}]}function qo(t,e){let r=0,n=0;for(;;){let s=t.indexOf(e,n);if(s===-1)break;r++,n=s+e.length}return r}var kp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Bo(t,e,r,n){if(n>=r)return"";let i=(await j.readdir(t,{withFileTypes:!0})).filter(a=>!kp.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],f=a===i.length-1,u=f?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${u}${d} ${l.name}
|
|
64
|
+
`,l.isDirectory()){let h=e+(f?" ":"\u2502 ");o+=await Bo(Se.join(t,l.name),h,r,n+1)}}return o}function Cp(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Vo=require("child_process");var Ho=require("child_process"),Yt=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,Ho.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...r?.env}}),o={id:n,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
|
|
65
65
|
Error: ${a.message}`}),s>0&&setTimeout(()=>{o.status==="running"&&(this.kill(n),o.status="timeout",o.stderr+=`
|
|
66
66
|
Process timed out after ${s}ms`)},s),this.processes.set(n,o),n}readOutput(e,r){let n=this.processes.get(e);if(!n)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let s=r?.type||"both",i="";return(s==="stdout"||s==="both")&&(i+=n.stdout),(s==="stderr"||s==="both")&&(i&&(i+=`
|
|
67
67
|
`),i+=n.stderr),r?.lastLines&&(i=i.split(`
|
|
68
68
|
`).slice(-r.lastLines).join(`
|
|
69
|
-
`)),{success:!0,output:i,status:n.status}}kill(e){let r=this.processes.get(e);if(!r)return!1;if(r.process.pid)try{process.kill(-r.process.pid,"SIGTERM")}catch{try{process.kill(r.process.pid,"SIGTERM")}catch{}}return r.status="killed",!0}killAll(){let e=0;for(let r of this.processes.keys())this.kill(r)&&e++;return e}listProcesses(){let e=[];for(let[r,n]of this.processes){let s=Date.now()-n.startTime,i=this.formatUptime(s);e.push({id:r,command:n.command,status:n.status,pid:n.pid,startTime:n.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[r,n]of this.processes)(n.status==="finished"||n.status==="killed"||n.status==="timeout")&&(this.processes.delete(r),e++);return e}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let n=Math.floor(r/60);return n<60?`${n}m ${r%60}s`:`${Math.floor(n/60)}h ${n%60}m`}};var
|
|
70
|
-
PID: ${
|
|
71
|
-
Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let f=(0,
|
|
69
|
+
`)),{success:!0,output:i,status:n.status}}kill(e){let r=this.processes.get(e);if(!r)return!1;if(r.process.pid)try{process.kill(-r.process.pid,"SIGTERM")}catch{try{process.kill(r.process.pid,"SIGTERM")}catch{}}return r.status="killed",!0}killAll(){let e=0;for(let r of this.processes.keys())this.kill(r)&&e++;return e}listProcesses(){let e=[];for(let[r,n]of this.processes){let s=Date.now()-n.startTime,i=this.formatUptime(s);e.push({id:r,command:n.command,status:n.status,pid:n.pid,startTime:n.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[r,n]of this.processes)(n.status==="finished"||n.status==="killed"||n.status==="timeout")&&(this.processes.delete(r),e++);return e}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let n=Math.floor(r/60);return n<60?`${n}m ${r%60}s`:`${Math.floor(n/60)}h ${n%60}m`}};var $p=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],Nn=null;function Wo(t){return Nn||(Nn=new Yt({workingDir:t})),Nn}function zo(t,e){return{name:"run_command",description:"Execute any shell command and return output. Set run_in_background=true for long-running processes (servers, watchers). Use bash_output to read output later.",safety:"confirm",parameters:{command:{type:"string",description:"Shell command to execute",required:!0},run_in_background:{type:"boolean",description:"Run in background for long processes (default: false)",required:!1},timeout:{type:"number",description:"Timeout in ms (default: 120000)",required:!1}},execute:async r=>{let n=r.command,s=r.run_in_background===!0,i=r.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...$p,...o];if(a.length>0){for(let l of a)if(n.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(s){let l=Wo(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
|
|
70
|
+
PID: ${Wo(t).getProcess(l)?.pid}
|
|
71
|
+
Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let f=(0,Vo.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),u="",d="";f.stdout?.on("data",h=>{u+=h}),f.stderr?.on("data",h=>{d+=h}),f.on("close",h=>{l(h===0?{success:!0,output:u||"(no output)"}:{success:!1,output:u,error:d||`Exit code: ${h}`})}),f.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var Zt=k(require("fs/promises")),_e=k(require("path")),Tp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Ap=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function Ko(t){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let r=e.query,n=_e.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await Go(n,s,i,t),i.length===0)return{success:!0,output:`No matches found for: "${r}"`};let o=i.slice(0,50).join(`
|
|
72
72
|
`),a=i.length>50?`
|
|
73
|
-
... and ${i.length-50} more matches`:"";return{success:!0,output:o+a}}catch(r){return{success:!1,output:"",error:`Search failed: ${r.message}`}}}}}async function
|
|
74
|
-
`),f=
|
|
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
|
|
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
|
|
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
|
|
78
|
-
`)}function
|
|
79
|
-
`);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],
|
|
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
|
|
81
|
-
|
|
82
|
-
Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:
|
|
73
|
+
... and ${i.length-50} more matches`:"";return{success:!0,output:o+a}}catch(r){return{success:!1,output:"",error:`Search failed: ${r.message}`}}}}}async function Go(t,e,r,n){let s=await Zt.readdir(t,{withFileTypes:!0});for(let i of s){if(Tp.has(i.name)||i.name.startsWith("."))continue;let o=_e.join(t,i.name);if(i.isDirectory())await Go(o,e,r,n);else if(Ap.has(_e.extname(i.name)))try{let l=(await Zt.readFile(o,"utf-8")).split(`
|
|
74
|
+
`),f=_e.relative(n,o);for(let u=0;u<l.length;u++)e.test(l[u])&&(r.push(`${f}:${u+1}: ${l[u].trim()}`),e.lastIndex=0)}catch{}}}var qn=require("child_process"),Q=k(require("fs")),xe=k(require("path"));function Ep(t){let e=[],r=xe.join(t,"tsconfig.json");if(!Q.existsSync(r))return e;try{(0,qn.execSync)("npx tsc --noEmit 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let s=n,o=(s.stdout||s.message||"").split(`
|
|
75
|
+
`);for(let a of o){let l=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);l&&e.push({file:l[1],line:parseInt(l[2],10),severity:l[3]==="error"?"error":"warning",message:l[4].trim(),source:"typescript"})}}return e}function Op(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>Q.existsSync(xe.join(t,n))))return e;try{(0,qn.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let i=n.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:xe.relative(t,a.filePath),line:l.line||0,severity:l.severity===2?"error":"warning",message:`${l.message} (${l.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
|
|
76
|
+
`);for(let a of o){let l=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);l&&e.push({file:"unknown",line:parseInt(l[1],10),severity:l[3]==="error"?"error":"warning",message:`${l[4]} (${l[5]})`,source:"eslint"})}}}return e}function Rp(t,e,r){let n;try{n=Q.readFileSync(t,"utf-8")}catch{return}let s=xe.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 Ip(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=Q.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let f=xe.join(s,l),u;try{u=Q.statSync(f)}catch{continue}u.isDirectory()?n(f,i+1):r.some(d=>l.endsWith(d))&&Rp(f,t,e)}}return n(t),e.slice(0,20)}function Pp(t){let e=[];e.push(...Ep(t)),e.push(...Op(t)),e.push(...Ip(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function Jo(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 Mp(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=xe.join(e,n.file);try{let o=Q.readFileSync(s,"utf-8").split(`
|
|
79
|
+
`);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],Q.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 Xo(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=Pp(r);if(n&&s.length>0){let o=Mp(s,r).filter(l=>l.fixed).length;return{success:!0,output:`${Jo(s)}
|
|
81
|
+
|
|
82
|
+
Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:Jo(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Yo=2*1024*1024,Zo=15e3,Qo=32e3,Dp="HablasBot/2.0 (+https://hablas.dev)";function Fp(t){let e=t;return e=e.replace(/<(script|style|nav|footer|header|aside|iframe|noscript)[^>]*>[\s\S]*?<\/\1>/gi,""),e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/<\/(p|div|section|article|li|tr|h[1-6])>/gi,`
|
|
83
83
|
`),e=e.replace(/<(br|hr)\s*\/?>/gi,`
|
|
84
84
|
`),e=e.replace(/<\/?(ul|ol)>/gi,`
|
|
85
85
|
`),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(r,n,s)=>`
|
|
86
86
|
${"#".repeat(parseInt(n))} ${s.replace(/<[^>]+>/g,"").trim()}
|
|
87
87
|
`),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(r,n,s)=>{let i=s.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${n})`:n}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(r,n)=>"\n```\n"+n.replace(/<[^>]+>/g,"").trim()+"\n```\n"),e=e.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi,"`$1`"),e=e.replace(/<(b|strong)[^>]*>([\s\S]*?)<\/\1>/gi,"**$2**"),e=e.replace(/<(i|em)[^>]*>([\s\S]*?)<\/\1>/gi,"*$2*"),e=e.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,"\u2022 $1"),e=e.replace(/<[^>]+>/g,""),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/&#(\d+);/g,(r,n)=>String.fromCharCode(parseInt(n))).replace(/&[a-z]+;/gi,""),e=e.replace(/[ \t]+/g," "),e=e.replace(/\n{3,}/g,`
|
|
88
88
|
|
|
89
|
-
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function
|
|
89
|
+
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function Lp(t){let e=t.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let r=t.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return r?r[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function jp(t,e){let r=[],n=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,s,i=new Set;for(;(s=n.exec(t))!==null;){let o=s[1].trim(),a=s[2].replace(/<[^>]+>/g,"").trim();if(!(o.startsWith("#")||o.startsWith("javascript:")||o.startsWith("mailto:"))){try{o=new URL(o,e).href}catch{continue}i.has(o)||(i.add(o),r.push({text:a||o,url:o}))}}return r}async function ea(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Zo);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":Dp,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(r),!n.ok)return{html:"",finalUrl:n.url||t,status:n.status};let s=n.headers.get("content-type")||"";if(!s.includes("text/")&&!s.includes("application/xhtml")&&!s.includes("application/json"))return{html:`[Binary content: ${s}]`,finalUrl:n.url||t,status:n.status};let i=n.body?.getReader();if(!i)return{html:"",finalUrl:n.url||t,status:n.status};let o=[],a=0;for(;a<Yo;){let{done:u,value:d}=await i.read();if(u)break;o.push(d),a+=d.length}if(a>=Yo)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(u=>l.decode(u,{stream:!0})).join("")+l.decode(),finalUrl:n.url||t,status:n.status}}catch(n){clearTimeout(r);let s=n instanceof Error?n:new Error(String(n));throw s.name==="AbortError"?new Error(`Timeout after ${Zo/1e3}s`):s}}function ta(){return[{name:"scrape_url",description:"Fetch a web page and extract its readable text content. Returns clean text/markdown without HTML tags. Use this to read documentation, articles, blog posts, or any web page.",safety:"safe",parameters:{url:{type:"string",description:"The URL to scrape (must start with http:// or https://)",required:!0}},execute:async t=>{let e=t.url;if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:r,finalUrl:n,status:s}=await ea(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=Lp(r),o=Fp(r);return o.length>Qo&&(o=o.slice(0,Qo)+`
|
|
90
90
|
|
|
91
91
|
[... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${n}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
|
|
92
|
-
`)}}catch(r){let n=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to scrape ${e}: ${n}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async t=>{let e=t.url,r=t.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:n,finalUrl:s,status:i}=await
|
|
92
|
+
`)}}catch(r){let n=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to scrape ${e}: ${n}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async t=>{let e=t.url,r=t.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:n,finalUrl:s,status:i}=await ea(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=jp(n,s);if(r&&(o=o.filter(l=>l.url.toLowerCase().includes(r)||l.text.toLowerCase().includes(r))),o.length===0)return{success:!0,output:"No links found"+(r?` matching "${r}"`:"")};let a=o.slice(0,100).map((l,f)=>`${f+1}. [${l.text}](${l.url})`).join(`
|
|
93
93
|
`);return{success:!0,output:`Found ${o.length} links:
|
|
94
94
|
|
|
95
|
-
${a}`}}catch(n){let s=n instanceof Error?n.message:String(n);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${s}`}}}}]}var
|
|
96
|
-
`)}}catch(n){return{success:!1,output:"",error:`Search failed: ${n instanceof Error?n.message:String(n)}`}}}}}var
|
|
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 Np=3600*1e3,Je=new Map;function qp(t){let e=Je.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>Np?(Je.delete(t.toLowerCase().trim()),null):e.results:null}function Up(t,e){if(Je.size>200){let r=Je.keys().next().value;r!==void 0&&Je.delete(r)}Je.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Bp(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 Hp(t,e){try{let r=new URLSearchParams({q:t}),n=await fetch(`https://html.duckduckgo.com/html/?${r}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!n.ok)return null;let s=await n.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(s))!==null&&i.length<e;){let l=a[1],f=a[2].replace(/<[^>]+>/g,"").trim(),u=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}f&&l&&!l.startsWith("/")&&i.push({title:f,url:l,snippet:u,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,f=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let u=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!f.has(u)&&!u.includes("duckduckgo.com")&&(f.add(u),i.push({title:d,url:u,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function Wp(t,e=5){let r=qp(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>Bp(t,e)},{name:"duckduckgo",fn:()=>Hp(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return Up(t,i),i}catch{}return[]}function ra(){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 Wp(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 he=k(require("fs")),aa=k(require("path")),na=50*1024*1024,sa=4e4;function ia(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=Ie(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=Ie(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=Ie(l[1]));let f=e.match(/\/Creator\s*\(([^)]*)\)/);f&&(r.creator=Ie(f[1]));let u=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=u.exec(e))!==null;){let p=d[1],c=oa(p);c.trim()&&n.push(c);try{let m=require("zlib"),y=Buffer.from(p,"latin1"),b=m.inflateSync(y).toString("latin1"),S=oa(b);S.trim()&&!n.includes(S)&&n.push(S)}catch{}}return{text:n.join(`
|
|
97
97
|
`).replace(/\r\n/g,`
|
|
98
98
|
`).replace(/\n{3,}/g,`
|
|
99
99
|
|
|
100
|
-
`).trim(),pages:s,metadata:r}}function
|
|
101
|
-
`).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}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
|
|
100
|
+
`).trim(),pages:s,metadata:r}}function oa(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(Ie(n[1]));let s=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(n=s.exec(t))!==null;){let l=n[1].match(/\(([^)]*)\)/g);if(l){let f=l.map(u=>Ie(u.slice(1,-1))).join("");e.push(f)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(Ie(n[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
|
|
101
|
+
`).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function Ie(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 la(t){let e=r=>aa.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(!he.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=he.statSync(n);if(s.size>na)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${na/1024/1024}MB)`};try{let i=he.readFileSync(n),{text:o,pages:a,metadata:l}=ia(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
|
|
103
103
|
|
|
104
|
-
[No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let f=o;return f.length>
|
|
104
|
+
[No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let f=o;return f.length>sa&&(f=f.slice(0,sa)+`
|
|
105
105
|
|
|
106
106
|
[... content truncated ...]`),{success:!0,output:`${[`PDF: ${r.path}`,`Pages: ${a}`,l.title?`Title: ${l.title}`:"",l.author?`Author: ${l.author}`:"",`Size: ${(s.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
|
|
107
107
|
`)}
|
|
108
|
-
${f}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let n=e(r.path);if(!
|
|
109
|
-
`)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var
|
|
108
|
+
${f}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let n=e(r.path);if(!he.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=he.statSync(n),i=he.readFileSync(n),{pages:o,metadata:a}=ia(i);return{success:!0,output:[`File: ${r.path}`,`Size: ${(s.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${s.mtime.toISOString()}`].filter(Boolean).join(`
|
|
109
|
+
`)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var fa=require("child_process"),Qt=k(require("fs")),da=k(require("os")),pa=k(require("path")),ha=1e4,ca=16e3;function Xe(t){try{let{execSync:e}=require("child_process");return e(`which ${t} 2>/dev/null || where ${t} 2>NUL`,{stdio:"ignore"}),!0}catch{return!1}}var ua={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>Xe("tsx")?`tsx "${t}"`:Xe("ts-node")?`ts-node --transpileOnly "${t}"`:`node --no-warnings -e "require('esbuild').buildSync({entryPoints:['${t}'],write:false,format:'cjs'}).outputFiles.forEach(f=>eval(f.text))"`,available:()=>!0},python:{extension:".py",command:t=>Xe("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>Xe("python3")||Xe("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>Xe("bash")}};async function Vp(t,e,r=ha){let n=ua[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(ua).join(", ")}`,exitCode:1,duration:0,language:e};if(!n.available())return{success:!1,stdout:"",stderr:`Language "${e}" is not available on this system. Install the runtime first.`,exitCode:1,duration:0,language:e};let s=da.tmpdir(),i=pa.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{Qt.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let f=(0,fa.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),u="",d="";f.stdout?.on("data",h=>{u+=h}),f.stderr?.on("data",h=>{d+=h}),f.on("close",h=>{let p=Date.now()-a;l({success:h===0,stdout:u.slice(0,ca),stderr:d.slice(0,ca/2),exitCode:h??1,duration:p,language:e})}),f.on("error",h=>{let p=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:p,language:e})})})}finally{try{Qt.unlinkSync(i)}catch{}}}function zp(t){return/\b(interface|type|enum|as\s+\w|:\s*(string|number|boolean|any)\b|<[A-Z]\w*>)/.test(t)?"typescript":/^(import\s+\w|from\s+\w|def\s+\w|class\s+\w|print\s*\(|if\s+__name__)/m.test(t)?"python":/^(#!\/bin\/bash|echo\s|export\s|if\s+\[|for\s+\w+\s+in)/m.test(t)?"bash":"javascript"}function ma(){return[{name:"execute_code",description:"Execute a code snippet and return the output. Supports JavaScript, TypeScript, Python, and Bash. Code runs in a temporary file with a timeout. Use this to test code, run calculations, verify logic, or prototype solutions.",safety:"confirm",parameters:{code:{type:"string",description:"The code to execute",required:!0},language:{type:"string",description:"Language: javascript, typescript, python, bash (auto-detected if omitted)",required:!1},timeout:{type:"number",description:"Timeout in milliseconds (default: 10000, max: 30000)",required:!1}},execute:async t=>{let e=t.code;if(!e?.trim())return{success:!1,output:"",error:"Code is required"};let r=t.language?.toLowerCase()||zp(e),n=Math.min(Math.max(1e3,t.timeout||ha),3e4),s=await Vp(e,r,n),i=[];return i.push(`Language: ${s.language} | Exit: ${s.exitCode} | Duration: ${s.duration}ms`),i.push(""),s.stdout&&(i.push("Output:"),i.push(s.stdout)),s.stderr&&(i.push(s.stdout?`
|
|
110
110
|
Errors/Warnings:`:"Errors:"),i.push(s.stderr)),!s.stdout&&!s.stderr&&i.push("(no output)"),{success:s.success,output:i.join(`
|
|
111
|
-
`),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var
|
|
111
|
+
`),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var er=k(require("fs")),oe=k(require("path")),Kp=15*1024*1024;function Gp(t,e){return/image\/png/i.test(t)?".png":/image\/jpe?g/i.test(t)?".jpg":/image\/webp/i.test(t)?".webp":/image\/gif/i.test(t)?".gif":/image\/svg\+xml/i.test(t)?".svg":oe.extname(new URL(e).pathname)||".bin"}function ga(t){return{name:"download_asset",description:"Download an external asset such as an image or file from a URL and save it inside the project. Use this when the user wants real local assets, wallpaper images, hero images, icons, or downloadable files inside the generated project.",safety:"confirm",parameters:{url:{type:"string",description:"Public URL of the asset to download",required:!0},path:{type:"string",description:"Target project-relative path, e.g. public/hero.jpg or assets/bg.webp",required:!0}},execute:async e=>{let r=String(e.url||""),n=String(e.path||"");if(!r)return{success:!1,output:"",error:"url is required"};if(!n)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(r))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let s=await fetch(r,{signal:AbortSignal.timeout(15e3)});if(!s.ok)return{success:!1,output:"",error:`HTTP ${s.status} while downloading asset`};let i=s.headers.get("content-type")||"",o=await s.arrayBuffer(),a=Buffer.from(o);if(a.length>Kp)return{success:!1,output:"",error:`asset too large: ${Math.round(a.length/1024/1024)}MB`};let l=oe.resolve(t,n),u=oe.extname(l)?l:l+Gp(i,r);return er.mkdirSync(oe.dirname(u),{recursive:!0}),er.writeFileSync(u,a),{success:!0,output:`Downloaded asset: ${oe.relative(t,u)||oe.basename(u)}
|
|
112
|
+
Source: ${r}
|
|
113
|
+
Type: ${i||"unknown"}
|
|
114
|
+
Size: ${a.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${s?.message||String(s)}`}}}}}var Ye=class{tools=new Map;constructor(e,r){let n=Uo(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",zo(e,r)),this.tools.set("search_codebase",Ko(e)),this.tools.set("detect_bugs",Xo(e)),this.tools.set("web_search",ra());for(let s of ta())this.tools.set(s.name,s);for(let s of la(e))this.tools.set(s.name,s);for(let s of ma())this.tools.set(s.name,s);this.tools.set("download_asset",ga(e))}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let r=this.tools.get(e.name);return r?r.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let r={},n=[];for(let[s,i]of Object.entries(e.parameters))r[s]={type:i.type==="number"?"number":"string",description:i.description},i.required&&n.push(s);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:r,required:n}}}})}getToolDescriptions(){return this.getAll().map(r=>{let n=Object.entries(r.parameters).map(([s,i])=>` ${s}: ${i.type} \u2014 ${i.description}`).join(`
|
|
112
115
|
`);return`- ${r.name} [${r.safety}]: ${r.description}
|
|
113
116
|
${n}`}).join(`
|
|
114
117
|
|
|
115
|
-
`)}};var
|
|
116
|
-
... [truncated to fit context budget]`}var
|
|
118
|
+
`)}};var ya=k(require("crypto"));function Un(t){return Math.ceil(t.length/3.5)}function yt(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
|
|
119
|
+
... [truncated to fit context budget]`}var Ze=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,r,n){let s=this.computeHash(r),i=this.cache.get(e);if(i&&i.hash===s){i.lastUsed=Date.now(),i.accessCount++;return}let o=Un(r),a=n?.importance??this.autoImportance(e,r);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:r,hash:s,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:n?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,r){let n=this.cache.get(e);return n?n.hash!==this.computeHash(r):!0}buildContext(e){let r=e||this.budget,n=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),s=0,i=[];for(let o of n){if(s+o.tokenCount>r){if(o.importance>=7){let a=r-s;if(a>200){let l=yt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
|
|
117
120
|
${l}`),s+=a}}continue}i.push(`--- ${o.path} ---
|
|
118
121
|
${o.content}`),s+=o.tokenCount}return i.join(`
|
|
119
122
|
|
|
120
123
|
`)}buildAgentContext(e,r){let n=r||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(f=>i.length===0?!0:i.some(u=>f.path.includes(u))).sort((f,u)=>this.computeScore(u)-this.computeScore(f)),a=0,l=[];for(let f of o){if(a+f.tokenCount>n)break;l.push(`--- ${f.path} ---
|
|
121
124
|
${f.content}`),a+=f.tokenCount}return l.join(`
|
|
122
125
|
|
|
123
|
-
`)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,r)=>r.importance-e.importance)}evictToFit(e){let r=Array.from(this.cache.entries()).map(([s,i])=>({key:s,...i,score:this.computeScore(i)})).sort((s,i)=>s.score-i.score),n=0;for(let s of r){if(n>=e)break;s.importance>=9||(n+=s.tokenCount,this.usedTokens-=s.tokenCount,this.cache.delete(s.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let s=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-s/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,r){let n=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(n=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=3);let s=
|
|
126
|
+
`)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,r)=>r.importance-e.importance)}evictToFit(e){let r=Array.from(this.cache.entries()).map(([s,i])=>({key:s,...i,score:this.computeScore(i)})).sort((s,i)=>s.score-i.score),n=0;for(let s of r){if(n>=e)break;s.importance>=9||(n+=s.tokenCount,this.usedTokens-=s.tokenCount,this.cache.delete(s.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let s=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-s/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,r){let n=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(n=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=3);let s=Un(r);return s>2e3&&(n=Math.max(1,n-1)),s>5e3&&(n=Math.max(1,n-2)),n}autoTag(e){let r=[];return/\.(ts|tsx)$/.test(e)&&r.push("typescript"),/\.(js|jsx)$/.test(e)&&r.push("javascript"),/\.json$/.test(e)&&r.push("config"),/\.md$/.test(e)&&r.push("documentation"),/\.(css|scss|sass)$/.test(e)&&r.push("style"),/\.(test|spec)\./i.test(e)&&r.push("test"),/src\//.test(e)&&r.push("source"),r}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let r=this.accessHistory[this.accessHistory.length-1];if(r&&Date.now()-this.getGroupTime(r)<3e4){if(!r.includes(e)){r.push(e);for(let n of r)if(n!==e){let s=this.cache.get(n);s&&!s.relatedFiles.includes(e)&&s.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return ya.createHash("md5").update(e).digest("hex")}};var Jp=0;function wt(){return`msg_${Date.now()}_${++Jp}`}function Qe(t){return Math.ceil(t.length/4)}var et=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,r=50,n=32e3){this.maxMessages=r,this.maxTokens=n,this.sessionId=`session_${Date.now()}`;let s=Qe(e);this.messages.push({id:wt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:s,compressed:!1,tags:["system"]}),this.totalTokens=s}getSessionId(){return this.sessionId}addUserMessage(e,r){let n=wt(),s=Qe(e);return this.messages.push({id:n,role:"user",content:e,timestamp:Date.now(),priority:r?.priority||"high",tokenEstimate:s,compressed:!1,tags:r?.tags||["user-input"]}),this.totalTokens+=s,this.trimIfNeeded(),n}addAssistantMessage(e,r,n){let s=wt(),i=Qe(e),o={id:s,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:n||"hablas",tokenEstimate:i,compressed:!1,tags:n?[`agent:${n}`]:["assistant"]};return r&&r.length>0&&(o.tool_calls=r,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,n&&this.agentMessageCounts.set(n,(this.agentMessageCounts.get(n)||0)+1),this.trimIfNeeded(),s}addToolMessage(e,r){let n=wt(),s=Qe(e);return this.messages.push({id:n,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:s,compressed:!1,tags:r?[`tool:${r}`]:["tool-result"]}),this.totalTokens+=s,this.trimIfNeeded(),n}getMessages(){return this.messages.map(e=>{let r={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls),r})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(r=>r.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let r=Qe(e),n=this.messages.filter(s=>s.priority==="critical"&&s.role!=="system");this.messages=[{id:wt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]},...n],this.recalculateTokens()}takeSnapshot(e){let r={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(n=>({...n})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(r),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),r.id}rollback(e){let r=this.snapshots.find(n=>n.id===e);return r?(this.messages=r.messages.map(n=>({...n})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,r){let n=this.messages.length,s=new t(r,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?s.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&s.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:n,session:s}),s}mergeFork(e,r){let n=this.forks.get(e);if(!n)return!1;let s=n.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(r)this.addAssistantMessage(`[Agent @${e} result]: ${r}`,void 0,e);else if(s.length>0){let i=s.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let r=e.toLowerCase();return this.messages.filter(n=>n.content.toLowerCase().includes(r))}getMessagesByTag(e){return this.messages.filter(r=>r.tags.includes(e))}getLastByRole(e,r=1){return this.messages.filter(n=>n.role===e).slice(-r)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(r=>r.role==="tool"&&!r.compressed&&r.tokenEstimate>200);for(let r of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let r=this.messages.filter(n=>n.role==="assistant"&&!n.compressed&&n.priority!=="critical"&&n.tokenEstimate>300);for(let n of r.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(n)}}if(this.messages.length>this.maxMessages){let r=this.messages[0],n=this.messages.slice(1),s={critical:3,high:2,normal:1,low:0},i=n.sort((o,a)=>{let l=s[a.priority]-s[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[r,...i],this.recalculateTokens()}}compressMessage(e){let r=e.content.length,n=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
|
|
124
127
|
...(compressed from `+r+" chars)":e.content=e.content.slice(0,400)+`
|
|
125
|
-
...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=
|
|
126
|
-
`)}async function
|
|
127
|
-
`)}function
|
|
128
|
+
...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=Qe(e.content),this.totalTokens-=n-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,r)=>e+r.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let r=JSON.parse(e);if(!r.messages||!Array.isArray(r.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=r.sessionId||`session_${Date.now()}`,this.messages=r.messages,this.totalTokens=r.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(r.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}};var rt=k(require("fs")),wa=k(require("path"));var A=k(require("fs")),E=k(require("path"));function Xp(t){let e=E.join(t,"package.json");if(A.existsSync(e))try{let r=JSON.parse(A.readFileSync(e,"utf-8")),n={...r.dependencies,...r.devDependencies};if(n.next)return"next";if(n.nuxt)return"nuxt";if(n["@angular/core"])return"angular";if(n.svelte||n["@sveltejs/kit"])return"svelte";if(n.vue)return"vue";if(n.react)return"react";if(n["@nestjs/core"])return"nest";if(n.fastify)return"fastify";if(n.express)return"express"}catch{}if(A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml")))try{let r=A.existsSync(E.join(t,"requirements.txt"))?A.readFileSync(E.join(t,"requirements.txt"),"utf-8"):"";if(r.includes("django"))return"django";if(r.includes("flask"))return"flask";if(r.includes("fastapi"))return"fastapi"}catch{}if(A.existsSync(E.join(t,"Cargo.toml")))try{if(A.readFileSync(E.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(A.existsSync(E.join(t,"go.mod")))try{if(A.readFileSync(E.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Yp(t){return A.existsSync(E.join(t,"pnpm-lock.yaml"))?"pnpm":A.existsSync(E.join(t,"yarn.lock"))?"yarn":A.existsSync(E.join(t,"bun.lockb"))?"bun":A.existsSync(E.join(t,"package-lock.json"))?"npm":A.existsSync(E.join(t,"Cargo.toml"))?"cargo":A.existsSync(E.join(t,"go.mod"))?"go":A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml"))?"pip":"unknown"}function Zp(t){return A.existsSync(E.join(t,"tsconfig.json"))?"TypeScript":A.existsSync(E.join(t,"package.json"))?"JavaScript":A.existsSync(E.join(t,"Cargo.toml"))?"Rust":A.existsSync(E.join(t,"go.mod"))?"Go":A.existsSync(E.join(t,"pyproject.toml"))||A.existsSync(E.join(t,"requirements.txt"))?"Python":"Unknown"}function Qp(t){let e=E.join(t,".git","HEAD");if(!A.existsSync(e))return null;try{let r=A.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function tt(t){let e=Xp(t),r=Yp(t),n=Zp(t),s=Qp(t),i=A.existsSync(E.join(t,"Dockerfile"))||A.existsSync(E.join(t,"docker-compose.yml"))||A.existsSync(E.join(t,"docker-compose.yaml")),o=A.existsSync(E.join(t,".github","workflows"))||A.existsSync(E.join(t,".gitlab-ci.yml"))||A.existsSync(E.join(t,"Jenkinsfile")),a=A.existsSync(E.join(t,"__tests__"))||A.existsSync(E.join(t,"tests"))||A.existsSync(E.join(t,"test"))||A.existsSync(E.join(t,"spec")),l=A.existsSync(E.join(t,".git")),f=[],u=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of u)A.existsSync(E.join(t,m))&&f.push(m);let d=[],h=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let m of h)A.existsSync(E.join(t,m))&&d.push(m);let p=[],c=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let m of c)A.existsSync(E.join(t,m))&&p.push(m);return{rootPath:t,framework:e,packageManager:r,language:n,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:s,envFiles:f,configFiles:d,entryPoints:p}}function tr(t){let e=[` Project: ${E.basename(t.rootPath)}`,` Framework: ${t.framework}`,` Language: ${t.language}`,` Package: ${t.packageManager}`,` Git: ${t.hasGit?`\u2713 (${t.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${t.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${t.hasCICD?"\u2713":"\u2717"}`,` Tests: ${t.hasTests?"\u2713":"\u2717"}`];return t.envFiles.length>0&&e.push(` Env files: ${t.envFiles.join(", ")}`),e.join(`
|
|
129
|
+
`)}async function nt(t,e){let r=[],n=wa.join(t,"package.json");if(rt.existsSync(n))try{let o=JSON.parse(rt.readFileSync(n,"utf-8"));r.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&r.push(`Description: ${o.description}`)}catch{}let s=tt(t);r.push(`Framework: ${s.framework}`),r.push(`Language: ${s.language}`),r.push(`Package Manager: ${s.packageManager}`),r.push(`Git: ${s.hasGit?s.gitBranch||"present":"absent"}`);let i=eh(t,16);return i.length>0&&r.push(`Top-level: ${i.join(", ")}`),e?.workspace?.envParsing&&s.envFiles.length>0&&r.push(`Env files: ${s.envFiles.join(", ")}`),r.push(`Directory: ${t}`),r.join(`
|
|
130
|
+
`)}function eh(t,e){try{return rt.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function st(t,e){return`You are Hablas, a single powerful AI software engineering agent created by Abdulmoin Hablas.
|
|
128
131
|
|
|
129
|
-
Identity:
|
|
132
|
+
Identity contract:
|
|
130
133
|
- You are the only visible agent.
|
|
131
|
-
-
|
|
132
|
-
-
|
|
134
|
+
- Never mention internal teams, specialist roles, delegation, orchestration, routing layers, or hidden systems.
|
|
135
|
+
- You must still THINK with the depth of a product manager, architect, engineer, debugger, researcher, reviewer, and devops lead \u2014 but you answer as one unified agent.
|
|
136
|
+
|
|
137
|
+
Your internal lenses (silent, never named to the user):
|
|
138
|
+
- Product lens: clarify intent, scope, user value, and priorities.
|
|
139
|
+
- Architecture lens: design clean structure, interfaces, constraints, and trade-offs.
|
|
140
|
+
- Engineer lens: make precise file changes, follow project conventions, ship working code.
|
|
141
|
+
- Debugger lens: find root cause first, make minimal correct fixes, prevent regressions.
|
|
142
|
+
- Research lens: ground claims in evidence from project files and external knowledge when required.
|
|
143
|
+
- Reviewer lens: check security, correctness, maintainability, and verification before claiming success.
|
|
144
|
+
- DevOps lens: consider run/build/test/deploy implications, reproducibility, and operational safety.
|
|
133
145
|
|
|
134
146
|
Style:
|
|
135
|
-
- Direct, technical, calm.
|
|
147
|
+
- Direct, technical, calm, precise.
|
|
136
148
|
- No emojis.
|
|
137
149
|
- No hype.
|
|
138
150
|
- No filler.
|
|
139
|
-
- No
|
|
151
|
+
- No theatre.
|
|
152
|
+
- No motivational fluff.
|
|
140
153
|
- Do not say "let me" unless you are actually about to inspect or execute something.
|
|
154
|
+
- Prefer short strong paragraphs or structured bullets over rambling prose.
|
|
155
|
+
|
|
156
|
+
Absolute operating rules:
|
|
157
|
+
1. If the task does not need tools, answer directly and clearly.
|
|
158
|
+
2. If the task needs tools, use tools. Do not fake execution with pure prose.
|
|
159
|
+
3. For implementation, modification, continuation, or delivery work: real workspace actions are mandatory.
|
|
160
|
+
4. Read before editing when file content is unknown.
|
|
161
|
+
5. Do not reread the same file unless it changed or you need a different section.
|
|
162
|
+
6. One tool call at a time.
|
|
163
|
+
7. Never output raw tool JSON, XML, pseudo-calls, or internal formatting in user-facing text.
|
|
164
|
+
8. Ground project-specific claims in observed files or command output.
|
|
165
|
+
9. Verify before claiming success.
|
|
166
|
+
10. If something is not verified, say so explicitly.
|
|
167
|
+
11. If a task is blocked, ask the smallest necessary clarification instead of hallucinating.
|
|
168
|
+
12. Prefer minimal correct edits over broad rewrites unless the user explicitly wants a rewrite.
|
|
169
|
+
|
|
170
|
+
Tool discipline:
|
|
171
|
+
- Use read_file for evidence.
|
|
172
|
+
- Use search_codebase to find patterns and references.
|
|
173
|
+
- Use patch_file or edit_file for precise changes.
|
|
174
|
+
- Use write_file for new files or full rewrites.
|
|
175
|
+
- Use run_command for verification, builds, installs, and tests.
|
|
176
|
+
- Use list_dir when structure matters.
|
|
177
|
+
- Use web_search for current information, references, images, libraries, and external resources.
|
|
178
|
+
- Use scrape_url and extract_links when you need to inspect a page or extract concrete links.
|
|
179
|
+
- Use download_asset when the user wants real local assets such as wallpapers, photos, icons, or images inside the project.
|
|
180
|
+
- Use the minimum necessary tool sequence.
|
|
181
|
+
- Never claim a file was created, edited, downloaded, or verified unless a tool actually did it.
|
|
182
|
+
|
|
183
|
+
Implementation contract:
|
|
184
|
+
- If the user asks to build, create, fix, continue, refactor, or complete something, you must enter a real tool-based execution path.
|
|
185
|
+
- Do NOT satisfy implementation tasks with a giant inline code dump when tools are available.
|
|
186
|
+
- If the workspace is empty or missing files, create the needed files.
|
|
187
|
+
- If the request references an unfinished project, continue from existing artifacts instead of restarting from zero.
|
|
188
|
+
- If the request asks for one-step or no-question delivery, complete as much as possible in one pass and avoid unnecessary back-and-forth.
|
|
189
|
+
|
|
190
|
+
Analysis contract:
|
|
191
|
+
- Architecture or design requests should still be rigorous.
|
|
192
|
+
- Prefer reasoning first, then inspect only the files needed to support the recommendation.
|
|
193
|
+
- Provide assumptions, trade-offs, and concrete recommendations.
|
|
194
|
+
|
|
195
|
+
Debugging contract:
|
|
196
|
+
- Start from symptom \u2192 locate evidence \u2192 form hypothesis \u2192 verify \u2192 fix \u2192 verify again.
|
|
197
|
+
- Focus on root cause, not superficial symptoms.
|
|
198
|
+
- Keep fixes minimal and explain why they work.
|
|
141
199
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
7. If the task is project-specific, ground claims in observed files.
|
|
150
|
-
8. If the task is implementation, verify before claiming success.
|
|
151
|
-
9. If you cannot verify, say exactly what remains unverified.
|
|
200
|
+
Review contract:
|
|
201
|
+
- Before finalizing technical work, silently review for:
|
|
202
|
+
- correctness
|
|
203
|
+
- security
|
|
204
|
+
- maintainability
|
|
205
|
+
- verification status
|
|
206
|
+
- accidental regressions
|
|
152
207
|
|
|
153
|
-
|
|
208
|
+
Response contract:
|
|
209
|
+
- For read-only questions: give the answer and cite the observed source in plain language.
|
|
210
|
+
- For implementation tasks: summarize what changed, what was verified, and what remains.
|
|
211
|
+
- For failed attempts: be explicit, technical, and honest.
|
|
212
|
+
- Never expose internal chain-of-thought.
|
|
213
|
+
|
|
214
|
+
Few-shot behavior rules:
|
|
215
|
+
- User: "hi"
|
|
216
|
+
-> direct answer, no tools.
|
|
217
|
+
- User: "what is the current version of this project"
|
|
218
|
+
-> inspect the minimum relevant files, then answer from evidence.
|
|
219
|
+
- User: "craet a flower store just frontend"
|
|
220
|
+
-> treat the typo as an implementation request, use tools, create or modify actual files, then summarize.
|
|
221
|
+
- User: "use wallpaper from internet"
|
|
222
|
+
-> use web_search or scrape_url/extract_links to find a suitable image, then use download_asset to save a real local asset and update the project files accordingly.
|
|
223
|
+
- User: "continue the unfinished project"
|
|
224
|
+
-> inspect existing artifacts first, continue from them, do not restart from zero.
|
|
225
|
+
- User: "design the architecture for auth"
|
|
226
|
+
-> provide structured analysis, inspect files only if needed, answer as one unified agent.
|
|
227
|
+
- User: "just give me the finished project in one step no questions"
|
|
228
|
+
-> do real work through tools, complete as much as possible, verify before claiming done.
|
|
229
|
+
|
|
230
|
+
Task profile:
|
|
231
|
+
${th(e)}
|
|
154
232
|
|
|
155
233
|
Current project context:
|
|
156
|
-
${t}`}function
|
|
157
|
-
-
|
|
158
|
-
-
|
|
159
|
-
-
|
|
160
|
-
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
${
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
-
|
|
172
|
-
|
|
234
|
+
${t}`}function th(t){return t.kind==="casual"?["- Casual social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short and natural."].join(`
|
|
235
|
+
`):t.kind==="read"?["- Read-only or project-inspection task.","- Use tools only to inspect the minimum necessary evidence.","- Keep the final answer factual, grounded, and tight."].join(`
|
|
236
|
+
`):t.kind==="analysis"?["- Analysis / architecture task.","- Prefer reasoning first.","- If files are relevant, inspect only what is necessary.","- Deliver a structured recommendation with trade-offs and assumptions."].join(`
|
|
237
|
+
`):[t.continuity?"- Continue from existing work. Do not restart the project from zero.":"- Implementation task.",t.oneStepDelivery?"- The user requested one-step delivery with no unnecessary follow-up questions.":"- Ask a clarifying question only if the task is truly blocked.","- Real workspace tool usage is mandatory.","- Do not answer with inline code only if files can be created or modified directly.","- The task is not complete unless the relevant files were inspected and then changed or created when needed.","- Verify changes before claiming completion."].join(`
|
|
238
|
+
`)}var rh=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,nh=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,sh=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,ih=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,oh=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,ah=/\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,lh=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,ch=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,ba=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function bt(t){let e=t.trim(),r=e.toLowerCase(),n=nh.test(r),s=sh.test(r),i=ih.test(r)||oh.test(r),o=ah.test(r),a=lh.test(r),l=i||n||s||o&&e.length>18&&!ba.test(r)&&!a,f=a&&!i&&!n&&!s,u=ch.test(r)||o,d=!l&&!f&&(ba.test(r)||e.endsWith("?"));return rh.test(e)&&!u&&!l&&!f?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:l?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:n,oneStepDelivery:s,requiresProjectContext:!0,reason:n?"Continuation of existing work requires reading and modifying project artifacts.":"Implementation request requires tool-based execution."}:f?{kind:"analysis",needsTools:u,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||u?{kind:"read",needsTools:u,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}function uh(t,e){if(!e.needsTools)return[{id:"respond",title:"Respond directly and clearly."}];if(e.kind==="read")return[{id:"inspect",title:"Inspect the minimum relevant files."},{id:"answer",title:"Answer precisely from observed facts."}];if(e.kind==="analysis")return[{id:"inspect-context",title:"Inspect only the files needed for analysis."},{id:"reason",title:"Form a concise architectural recommendation."},{id:"answer",title:"Present the result as Hablas only."}];let r=[];return e.continuity&&r.push({id:"continuity",title:"Load existing project context and continue instead of restarting."}),r.push({id:"inspect",title:"Inspect the relevant code and files."}),r.push({id:"implement",title:"Apply the smallest correct implementation."}),r.push({id:"verify",title:"Run verification before claiming completion."}),r.push({id:"answer",title:"Summarize the outcome clearly."}),e.oneStepDelivery&&r.unshift({id:"delivery-contract",title:"Treat the request as no-questions one-step delivery."}),r}function Sa(t){let e=bt(t);return{input:t,profile:e,plan:uh(t,e)}}var Ia=k(require("readline")),re=k(require("fs")),G=k(require("path")),Pa=k(require("os"));var Bn=k(require("os")),sr=k(require("fs")),nr=k(require("path"));function fh(){let t=[nr.resolve(__dirname,"..","package.json"),nr.resolve(__dirname,"..","..","package.json"),nr.resolve(process.cwd(),"package.json")];for(let e of t)try{if(sr.existsSync(e)){let r=JSON.parse(sr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var _a=fh(),Hn=process.stdout.isTTY===!0,dh=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",xa=process.stdout.columns||100;Hn&&process.stdout.on("resize",()=>{xa=process.stdout.columns||100});var Pe=()=>Math.min(Math.max(xa-4,60),100);function ee(t,e){return!Hn||dh?t:`${e}${t}\x1B[0m`}var w={strong:t=>ee(t,"\x1B[1;38;5;255m"),muted:t=>ee(t,"\x1B[38;5;242m"),accent:t=>ee(t,"\x1B[38;5;145m"),info:t=>ee(t,"\x1B[38;5;110m"),success:t=>ee(t,"\x1B[38;5;108m"),warning:t=>ee(t,"\x1B[38;5;179m"),error:t=>ee(t,"\x1B[38;5;167m"),primary:t=>ee(t,"\x1B[38;5;253m"),secondary:t=>ee(t,"\x1B[38;5;247m"),border:t=>ee(t,"\x1B[38;5;237m"),code:t=>ee(t,"\x1B[38;5;188m"),line:t=>ee(t,"\x1B[38;5;239m")};function ph(t,e=2){let r=Pe()-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 hh(t){let e=Pe();if(!t)return w.border("\u2500".repeat(e));let r=t.replace(/\x1b\[[0-9;]*m/g,""),n=Math.max(0,e-r.length-2),s=Math.floor(n/2),i=n-s;return w.border("\u2500".repeat(s))+" "+t+" "+w.border("\u2500".repeat(i))}function va(t,e){let r=Pe(),n=e.replace(Bn.homedir(),"~"),s=w.border("\u2554"+"\u2550".repeat(r-2)+"\u2557"),i=w.border("\u2560"+"\u2550".repeat(r-2)+"\u2563"),o=w.border("\u255A"+"\u2550".repeat(r-2)+"\u255D"),a="H A B L A S",l="APPLE-SLATE TERMINAL RUNTIME",f=Math.max(0,Math.floor((r-2-a.length)/2)),u=Math.max(0,Math.floor((r-2-l.length)/2));return["",s,w.border("\u2551")+" ".repeat(f)+w.strong(a)+" ".repeat(r-2-a.length-f)+w.border("\u2551"),w.border("\u2551")+" ".repeat(u)+w.secondary(l)+" ".repeat(r-2-l.length-u)+w.border("\u2551"),i,` ${w.muted("\u25B8")} ${w.muted(`VERSION: v${_a}`)}`,` ${w.muted("\u25B8")} ${w.muted(`MODEL: ${t}`)}`,` ${w.muted("\u25B8")} ${w.muted(`WORKSPACE: ${n}`)}`,` ${w.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")}`,` ${w.muted(" \u203A")} ${w.secondary("Type naturally to get started")}`,` ${w.muted(" \u203A")} ${w.secondary("/help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")}`,o,""].join(`
|
|
239
|
+
`)}function ka(t){return`
|
|
240
|
+
`+hh(`${w.accent("\u25C6")} ${w.strong("Turn #"+t)}`)}function St(){return`
|
|
241
|
+
${w.accent("\u25C6")} ${w.strong("Hablas")} ${w.muted("[response]")}`}function rr(t){return t.replace(/`([^`]+)`/g,(e,r)=>w.primary(r)).replace(/\*\*([^*]+)\*\*/g,(e,r)=>w.strong(r))}function _t(t){let e=t.split(`
|
|
242
|
+
`),r=[],n=!1,s="",i=[],o=()=>{if(!i.length)return;let a=String(i.length).length;r.push(` ${w.border("\u250C"+"\u2500".repeat(Math.max(24,Pe()-6)))} ${s?w.accent(s):""}`.trimEnd()),i.forEach((l,f)=>{r.push(` ${w.border("\u2502")} ${w.line(String(f+1).padStart(a)+" \u2502")} ${w.code(l)}`)}),r.push(` ${w.border("\u2514"+"\u2500".repeat(Math.max(24,Pe()-6)))}`),i=[]};for(let a of e){if(a.trimStart().startsWith("```")){n?(o(),n=!1,s=""):(n=!0,s=a.trimStart().slice(3).trim());continue}if(n){i.push(a);continue}if(!a.trim()){r.push("");continue}if(/^#{1,3}\s/.test(a)){r.push(` ${w.strong(rr(a.replace(/^#{1,3}\s/,"")))}`);continue}if(/^[-*]\s/.test(a.trim())){r.push(` ${w.accent("\u25B8")} ${rr(a.trim().slice(2))}`);continue}if(/^\d+\.\s/.test(a.trim())){r.push(` ${rr(a.trim())}`);continue}r.push(...ph(rr(a),2))}return n&&o(),`
|
|
243
|
+
`+r.join(`
|
|
244
|
+
`)+`
|
|
245
|
+
`}function Ca(){return["",` ${w.strong("Hablas commands")}`,"",` ${w.primary("/help")} ${w.muted("show help")}`,` ${w.primary("/status")} ${w.muted("show current runtime status")}`,` ${w.primary("/model")} ${w.muted("show or switch active model")}`,` ${w.primary("/models")} ${w.muted("list available models (supports search)")}`,` ${w.primary("/provider")} ${w.muted("inspect or switch provider")}`,` ${w.primary("/history")} ${w.muted("show recent turns")}`,` ${w.primary("/clear")} ${w.muted("clear the session")}`,` ${w.primary("/workspace")} ${w.muted("inspect workspace info")}`,` ${w.primary("/doctor")} ${w.muted("run diagnostics")}`,` ${w.primary("/version")} ${w.muted("show version")}`,` ${w.primary("/about")} ${w.muted("show product identity")}`,` ${w.primary("/exit")} ${w.muted("quit")}`,"",` ${w.accent("Tips")}`,` ${w.muted("\u2022 Tab completes commands and common file paths.")}`,` ${w.muted("\u2022 Use #filename to reference files quickly.")}`,` ${w.muted("\u2022 Ctrl+C cancels current work. Ctrl+C twice exits.")}`,""].join(`
|
|
246
|
+
`)}function $a(t){let e=[` ${w.muted("provider")} ${w.info(t.provider)}`,` ${w.muted("model")} ${w.info(t.model)}`,` ${w.muted("workspace")} ${w.muted(t.workingDir.replace(Bn.homedir(),"~"))}`,` ${w.muted("connected")} ${t.connected?w.success("yes"):w.error("no")}`,` ${w.muted("messages")} ${w.info(String(t.messageCount))}`,t.totalTokens!==void 0?` ${w.muted("tokens")} ${w.info(String(t.totalTokens))}`:""].filter(Boolean);return[""," "+w.strong("Status"),""].concat(e).concat([""]).join(`
|
|
247
|
+
`)}function te(t){return` ${w.info(t)}`}function Me(t){return` ${w.success("\u2713")} ${t}`}function me(t){return` ${w.warning("\u26A0")} ${t}`}function ve(t){return` ${w.error("\u2717")} ${t}`}function Ta(){return` ${w.strong("Hablas")} ${w.accent("v"+_a)}`}function Aa(){return` ${w.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime by Abdulmoin Hablas`}function Ea(t,e){let r=Math.max(32,Pe()-6);return[` ${w.border("\u250C"+"\u2500".repeat(r))}`,` ${w.border("\u2502")} ${w.accent(t)} ${w.muted("\xB7")} ${e}`].join(`
|
|
248
|
+
`)}function Oa(t,e,r){let n=t?w.success("\u2713"):w.error("\u2717"),s=e.replace(/\s+/g," ").trim().slice(0,160),i=Math.max(32,Pe()-6);return[` ${w.border("\u2502")} ${n} ${s||(t?"done":"failed")} ${w.muted(`(${r}ms)`)}`,` ${w.border("\u2514"+"\u2500".repeat(i))}`].join(`
|
|
249
|
+
`)}var it=class{constructor(e){this.label=e}frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;timer=null;start(){!Hn||this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${w.accent(this.frames[this.index])} ${w.muted(this.label)}`),this.index=(this.index+1)%this.frames.length},80))}stop(e){this.timer&&(clearInterval(this.timer),this.timer=null,process.stdout.write("\r\x1B[K")),e&&console.log(te(e))}};var ir=G.join(Pa.homedir(),".hablas","history"),or=500,mh=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),gh=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],yh=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"]),Ra=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],ar=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return Ia.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:or,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(-or),this.saveHistory()),r(n)})})}async confirm(e){return(await this.prompt(` ${w.warning("?")} ${e} ${w.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
|
|
250
|
+
${w.error("\u26A0")} ${e}`),console.log(` ${w.muted("Type yes to confirm this dangerous action.")}
|
|
251
|
+
`),(await this.prompt(` ${w.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let n=Ra.filter(s=>s.startsWith(e));return[n.length?n:Ra,e]}for(let n of gh)if(e.toLowerCase().includes(n)){let s=e.split(n).pop()??"";if(s&&!s.includes(" "))try{let i=G.dirname(s)||".",o=G.basename(s),a=G.resolve(this.workingDir,i),l=re.readdirSync(a).filter(f=>f.startsWith(o)).slice(0,8).map(f=>e.slice(0,e.lastIndexOf(s))+G.join(i,f));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=re.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||mh.has(a.name))continue;let l=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(G.join(e,a.name),l,n,s,i+1);else{let f=G.extname(a.name).toLowerCase();(yh.has(f)||a.name==="Dockerfile"||a.name==="Makefile")&&n.push(l)}}}catch{}}loadHistory(){try{re.existsSync(ir)&&(this.history=re.readFileSync(ir,"utf-8").split(`
|
|
252
|
+
`).filter(Boolean).slice(-or))}catch{}}saveHistory(){try{let e=G.dirname(ir);re.existsSync(e)||re.mkdirSync(e,{recursive:!0}),re.writeFileSync(ir,this.history.slice(-or).join(`
|
|
253
|
+
`),"utf-8")}catch{}}};var wh={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},bh=`
|
|
173
254
|
## Reasoning Protocol
|
|
174
255
|
|
|
175
256
|
Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
|
|
@@ -198,15 +279,15 @@ After receiving a tool result, think again:
|
|
|
198
279
|
- One tool call per turn. Wait for the result before the next call.
|
|
199
280
|
- If a tool fails, analyze the error in <thinking> before retrying.
|
|
200
281
|
- When done, give a concise final answer WITHOUT <thinking> tags.
|
|
201
|
-
`.trim(),
|
|
282
|
+
`.trim(),Sh=`
|
|
202
283
|
## Reasoning
|
|
203
284
|
For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
|
|
204
285
|
The user will NOT see thinking blocks. One tool call per turn.
|
|
205
|
-
`.trim(),
|
|
286
|
+
`.trim(),Wn=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...wh,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,r="M"){return!this.config.thinkingEnabled||r==="XS"?e:r==="S"?`${e}
|
|
206
287
|
|
|
207
|
-
${
|
|
288
|
+
${Sh}`:`${e}
|
|
208
289
|
|
|
209
|
-
${
|
|
290
|
+
${bh}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let r=[],n=e,s=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=s.exec(e))!==null;)r.push(i[1].trim());n=n.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)r.push(i[1].trim());n=n.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(n);a&&(r.push(a[1].trim()),n=n.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(n);return l&&(r.push(l[1].trim()),n=n.replace(/<think>[\s\S]*$/i,"")),{thinking:r.join(`
|
|
210
291
|
|
|
211
292
|
`).trim(),visibleContent:n.trim(),hasThinking:r.length>0}}startTurn(){this.turnSteps=[],this.stepCounter=0}recordStep(e){let r={...e,stepIndex:this.stepCounter++,timestamp:new Date().toISOString()};return this.turnSteps.push(r),r}recordObservation(e,r){let n=this.turnSteps[this.turnSteps.length-1];n&&(n.observation=e,r&&(n.reflection=r))}getSteps(){return this.turnSteps}isOverBudget(){return this.stepCounter>=this.config.maxSteps}remainingBudget(){return Math.max(0,this.config.maxSteps-this.stepCounter)}buildSelfEvalPrompt(e,r,n){return`
|
|
212
293
|
<self_eval>
|
|
@@ -229,21 +310,17 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
|
229
310
|
}
|
|
230
311
|
</self_eval>
|
|
231
312
|
`.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(`
|
|
232
|
-
`)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(s=>s.action).length,n=this.turnSteps.filter(s=>s.reflection).length;return`${e} steps, ${r} actions, ${n} reflections`}};function
|
|
233
|
-
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let r=this.failures.get(e);return r?r.count<=1&&r.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function
|
|
313
|
+
`)}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 xt(t){return new Wn(t)}var _h=[{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}],Vn=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 _h)if(a.test(r)){let l=s?.lastStrategy===a.strategy&&i>=2,f=l?"decompose_task":a.strategy;return o.lastStrategy=f,this.failures.set(e,o),{errorClass:a.errorClass,strategy:f,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,r){let n=[`ERROR: ${r}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&n.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":n.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":n.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":n.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":n.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":n.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":n.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return n.join(`
|
|
314
|
+
`)}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 vt(t=3){return new Vn(t)}var ge=k(require("fs")),cr=k(require("path")),Ma=k(require("os")),lr=cr.join(Ma.homedir(),".hablas","model-formats.json");function xh(){try{if(ge.existsSync(lr))return JSON.parse(ge.readFileSync(lr,"utf-8"))}catch{}return{}}function vh(t){try{let e=cr.dirname(lr);ge.existsSync(e)||ge.mkdirSync(e,{recursive:!0}),ge.writeFileSync(lr,JSON.stringify(t,null,2),"utf-8")}catch{}}function Da(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 kt(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 kh(t){return t.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function Ch(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=kt(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function $h(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=kt(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function Th(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=Fa(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function Fa(t){let e=[],r=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info","web_search","scrape_url","extract_links","read_pdf","pdf_metadata","execute_code","detect_bugs","download_asset"];for(let n of r){let s=new RegExp(`<<?${n}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${n}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",l={},f=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,u;for(;(u=f.exec(o))!==null;){let h=u[1].toLowerCase(),p=u[2]??u[3]??u[4];l[h]=kh(p)}let d=a.trim();d&&(n==="write_file"||n==="append_to_file"?l.content=a:n==="run_command"?l.command=d:n==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),n==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:n,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function Ah(t){return Fa(t)}function Eh(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=kt(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function Oh(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=Da(t,n.index);if(s)try{let i=JSON.parse(s),o=kt(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function Rh(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=Da(t,n.index);if(s)try{let i=JSON.parse(s),o=kt(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function Ih(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,n,s=!1;for(;(n=r.exec(t))!==null;){let i=n[1],o=/<function=([^>]+)>/i.exec(i);if(o){s=!0;let a=o[1].trim(),l={},f=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=f.exec(i))!==null;){let d=u[1].trim(),h=u[2].trim();h==="true"?h=!0:h==="false"?h=!1:!isNaN(Number(h))&&h!==""&&(h=Number(h)),l[d]=h}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:n[0]})}}if(!s&&/<function=([^>]+)>/i.test(t)){let i=/<function=([^>]+)>/i.exec(t);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,f;for(;(f=l.exec(t))!==null;){let u=f[1].trim(),d=f[2].trim();d==="true"?d=!0:d==="false"?d=!1:!isNaN(Number(d))&&d!==""&&(d=Number(d)),a[u]=d}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var zn=[{format:"xml_tool_call_wrapper",parse:Th},{format:"xml_prompt",parse:Ah},{format:"xml_tags",parse:Ch},{format:"xml_parameters",parse:Ih},{format:"hermes",parse:$h},{format:"markdown_json",parse:Eh},{format:"function_call",parse:Oh},{format:"json_object",parse:Rh}],Gn=class{registry;constructor(){this.registry=xh()}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=zn.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 zn){let o=i(s);if(o.length>0){let a=o[0].format;return n&&this.learnFormat(n,a),this.buildResult(o,s)}}return{toolCalls:[],displayContent:this.sanitizeResidualToolMarkup(s).trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let r=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(r)||/<function=/i.test(r)||r.includes("```tool_call")||r.includes("```json")&&r.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset)[\s>]/i.test(r)||r.startsWith("{")&&(r.includes('"name"')||r.includes('"tool"'))&&(r.includes('"arguments"')||r.includes('"args"')||r.includes('"parameters"'))||r.includes('"function"')&&r.includes('"name"'))}detectFormat(e){for(let{format:r,parse:n}of zn)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()},vh(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,`
|
|
234
315
|
|
|
235
|
-
`),{toolCalls:n,displayContent:s.trim(),format:e[0]?.format??"unknown"}}
|
|
236
|
-
|
|
237
|
-
${v.muted("\u2500".repeat(28))} ${v.accent("Turn #"+t)} ${v.muted("\u2500".repeat(28))}`}function rt(){return`
|
|
238
|
-
${
|
|
239
|
-
`)
|
|
240
|
-
`)
|
|
241
|
-
`)
|
|
242
|
-
`)}async function Pa(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Ca());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Aa());return;case"/version":console.log(Ta());return;case"/clear":e.session.clear(),console.log(Oe("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(Q("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l}: ${a.content.replace(/\s+/g," ").slice(0,160)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log($a({model:e.client.getModel(),provider:He(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(Q(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),je(e.config),console.log(Oe(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=s.join(" ").toLowerCase(),a=o?i.filter(l=>l.toLowerCase().includes(o)):i;if(a.length===0){console.log(de("No matching models found."));return}console.log(""),a.slice(0,60).forEach((l,f)=>console.log(` ${String(f+1).padStart(2," ")}. ${l}`)),a.length>60&&console.log(` ... ${a.length-60} more`),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(Q(`Provider: ${He(e.config)}`)),console.log(Q(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Oe("Connection OK"):Se("Connection failed"));return}if(i==="ollama")e.config.provider="ollama",e.config.apiUrl="",e.config.apiKey="";else if(i==="nvidia")e.config.provider="nvidia",e.config.apiUrl=se.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=se.defaultModel);else if(i==="custom"){if(!s[1]){console.log(de("Usage: /provider custom <url> [api-key]"));return}e.config.provider="custom",e.config.apiUrl=s[1],s[2]&&(e.config.apiKey=s[2])}else{console.log(de("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=Be(e.config);e.setClient(o),je(e.config),console.log(Oe(`Provider switched to ${He(e.config)}`));return}case"/doctor":{let i=await nr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(sr(i));return}case"/workspace":{console.log(""),console.log(Jt(Ye(e.workingDir))),console.log("");return}default:console.log(de(`Unknown command: ${n}`))}}async function La(t,e){is();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=Be(t),s=new Ke(r,t),i=new Ge(t),o=await Qe(r,t),a=new Xe(et(o,gt("hello")),t.historySize),l=new Xt;console.log(va(t.model,r)),Ma.existsSync(Fa.join(r,".git"))||console.log(de("Not in a Git repository. Versioning and auto-sync features are limited."));let f=new tt("Connecting");f.start();let u=await n.checkConnection();if(f.stop(u?"ready":"offline"),u){let y=await n.listModels();console.log(Oe(`Connected \xB7 ${y.length} models available`))}else console.log(de(`Connection failed for ${He(t)}. You can still inspect local files and switch provider with /provider.`));console.log(Q("Hablas is ready. Single-agent runtime active.")),console.log("");let d=0,h=0,p=Date.now(),c=new AbortController,m=0;for(process.on("SIGINT",()=>{let y=Date.now();y-m<1500&&(console.log(""),console.log(Q(`Session summary \xB7 turns=${d} \xB7 toolCalls=${h} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),m=y,c.abort(),c=new AbortController,console.log(""),console.log(de("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let w=(await l.prompt(" \u203A ")).trim();if(w){if(w.startsWith("/")){if(await Pa(w,{config:t,client:n,setClient:_=>{n=_},session:a,workingDir:r})==="quit")break;continue}d+=1,console.log(ka(d)),c=new AbortController;try{await rr(w,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{h+=1}})}catch(b){if(b?.name==="AbortError")continue;console.log(Se(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}l.close()}async function Da(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=Be(e),i=new Ke(n,e),o=new Ge(e),a=await Qe(n,e),l=new Xe(et(a,gt(t)),e.historySize);await rr(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1})}var ir=C(require("fs")),Re=C(require("path")),wh=[{pattern:/(?:api[_-]?key|apikey)\s*[:=]\s*['"][a-zA-Z0-9_\-]{20,}['"]/gi,name:"API Key",severity:"critical"},{pattern:/(?:secret|password|passwd|pwd)\s*[:=]\s*['"][^'"]{8,}['"]/gi,name:"Secret/Password",severity:"critical"},{pattern:/(?:aws_access_key_id)\s*[:=]\s*['"]?AKIA[A-Z0-9]{16}['"]?/gi,name:"AWS Access Key",severity:"critical"},{pattern:/(?:aws_secret_access_key)\s*[:=]\s*['"]?[A-Za-z0-9/+=]{40}['"]?/gi,name:"AWS Secret Key",severity:"critical"},{pattern:/ghp_[A-Za-z0-9]{36}/g,name:"GitHub Token",severity:"critical"},{pattern:/gho_[A-Za-z0-9]{36}/g,name:"GitHub OAuth Token",severity:"critical"},{pattern:/sk-[A-Za-z0-9]{48}/g,name:"OpenAI API Key",severity:"critical"},{pattern:/xox[baprs]-[A-Za-z0-9\-]{10,}/g,name:"Slack Token",severity:"high"},{pattern:/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g,name:"Private Key",severity:"critical"},{pattern:/(?:mongodb(?:\+srv)?:\/\/)[^\s'"]+/g,name:"MongoDB Connection String",severity:"high"},{pattern:/(?:postgres|postgresql|mysql):\/\/[^\s'"]+/g,name:"Database URL",severity:"high"},{pattern:/(?:Bearer\s+)[A-Za-z0-9\-._~+/]+=*/g,name:"Bearer Token",severity:"medium"}],bh=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Sh=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function _h(t,e){let r=[],n=e.split(`
|
|
243
|
-
`);for(let{pattern:s,name:i,severity:o}of wh){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let f=e.substring(0,a.index).split(`
|
|
244
|
-
`).length,u=n[f-1]||"";u.trim().startsWith("#")||u.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:f,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function xh(t,e){let r=[],n=e.split(`
|
|
245
|
-
`),s=Re.extname(t);return[".ts",".js",".tsx",".jsx"].includes(s)&&n.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&r.push({severity:"medium",type:"code",file:t,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),r}function ja(t,e=[]){try{let r=ir.readdirSync(t,{withFileTypes:!0});for(let n of r){if(bh.has(n.name))continue;let s=Re.join(t,n.name);if(n.isDirectory())ja(s,e);else if(n.isFile()){let i=Re.extname(n.name);Sh.has(i)||e.push(s)}}}catch{}return e}function Na(t){let e=Date.now(),r=ja(t),n=[];for(let o of r)try{let a=ir.readFileSync(o,"utf-8"),l=Re.relative(t,o),f=_h(l,a);n.push(...f);let u=xh(l,a);n.push(...u)}catch{}let s=Date.now()-e,i={critical:n.filter(o=>o.severity==="critical").length,high:n.filter(o=>o.severity==="high").length,medium:n.filter(o=>o.severity==="medium").length,low:n.filter(o=>o.severity==="low").length,info:n.filter(o=>o.severity==="info").length};return{issues:n,scannedFiles:r.length,duration:s,summary:i}}function qa(t){let e=[];if(e.push(`
|
|
316
|
+
`),{toolCalls:n,displayContent:s.trim(),format:e[0]?.format??"unknown"}}sanitizeResidualToolMarkup(e){return e.replace(/<<?tool[-_]call[\s\S]*?<<?\/tool[-_]call\s*>>?/gi,"").replace(/<function=[^>]+>/gi,"").replace(/<parameter=[^>]+>/gi,"").replace(/<\/parameter>/gi,"").replace(/```tool_call[\s\S]*?```/gi,"").replace(/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset)[\s\S]*?(?:<<?\/[a-z_]+>>?|\/>)/gi,"").replace(/\n{3,}/g,`
|
|
317
|
+
|
|
318
|
+
`)}},Kn=null;function La(){return Kn||(Kn=new Gn),Kn}var Ph=600,ja=2e3,Na=2;function Mh(t,e,r){let s=La().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function Dh(t,e){return t==="write_file"&&typeof e.path=="string"?`create ${e.path}`:(t==="edit_file"||t==="patch_file"||t==="search_and_replace")&&typeof e.path=="string"?`modify ${e.path}`:t==="read_file"&&typeof e.path=="string"?`read ${e.path}`:t==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function Fh(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 qa(t,e,r,n){let s=0,i=Date.now();for(;s<=Na;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=Na)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 Jn(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:f,skipTools:u}=t,d=t.reactEngine??xt(),h=t.errorRecovery??vt(),p=u?[]:n.getOllamaTools(),c=r.getModel(),m=t.maxIterations??Ph,y=[],b=[],S=[],x="",_=0,C=!1;for(;_<m;){if(_++,f?.aborted)return{output:x,toolsUsed:ke(y),toolResults:b,touchedFiles:ke(S),iterations:_,success:!1,error:"Aborted",completedNaturally:C};let R=d.buildBudgetWarningPrompt();R&&s.addUserMessage(R,{priority:"critical",tags:["system-budget"]});let T;try{T=await r.chatWithTools(s.getMessages(),p,f)}catch(U){let W=U;if(W.name==="AbortError"||f?.aborted)return{output:x,toolsUsed:ke(y),toolResults:b,touchedFiles:ke(S),iterations:_,success:!1,error:"Aborted",completedNaturally:C};if(_<=1){a.onNotice?.(`Transient model error: ${W.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(D=>setTimeout(D,1e3)),_--;continue}return a.onError?.(W.message??"Model request failed"),{output:x,toolsUsed:ke(y),toolResults:b,touchedFiles:ke(S),iterations:_,success:!1,error:W.message,completedNaturally:C}}let O=T.message?.content||"",$=T.message?.tool_calls,P=d.parseThinking(O);P.hasThinking&&(d.recordStep({thought:P.thinking}),o.debug({thinking:P.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:N,displayContent:F}=Mh($,O,c);if(F&&F.trim()&&(x=F,await a.onAssistantText?.(F,e)),N.length===0){s.addAssistantMessage(O,void 0,e.role),C=!0;break}s.addAssistantMessage(O,N,e.role);let H=N.length;for(let U=0;U<N.length;U++){let W=N[U];if(!W?.function?.name)continue;let D=W.function.name,V=W.function.arguments||{},mr=n.getSafetyLevel(D)??"confirm";if(!n.get(D)){a.onNotice?.(`Unknown tool: ${D} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${D}". Available: ${n.getAll().map(Le=>Le.name).join(", ")}`);continue}if(await l(D,mr,V)==="skip"){s.addToolMessage(`Tool ${D} was skipped by policy/user.`);break}y.push(D),typeof V.path=="string"&&S.push(V.path);let yr=Dh(D,V);a.onToolStart?.(D,yr,V),a.onToolCall?.(),d.recordStep({thought:P.hasThinking?`Executing: ${D}`:"",action:D,actionInput:V});let z=await qa(n,D,V,o);a.onToolEnd?.(D,z.success,z.error||z.output,z.duration,V);let Fe;if(z.success)Fe=yt(z.output,ja),d.recordObservation(Fe.slice(0,300)),b.push({tool:D,success:!0,summary:z.output.slice(0,150)});else{let Le=z.error||"Unknown error",je=h.analyze(D,Le,V);if(Fe=h.buildRecoveryMessage(je,Le),d.recordObservation(`FAILED: ${Le}`,`Recovery: ${je.strategy} \u2014 ${je.suggestion}`),o.info({tool:D,errorClass:je.errorClass,strategy:je.strategy},"Error recovery analysis"),b.push({tool:D,success:!1,summary:Le.slice(0,150)}),je.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let Ne=await qa(n,D,V,o);a.onToolEnd?.(D,Ne.success,Ne.output,Ne.duration,V),Ne.success&&(Fe=yt(Ne.output,ja),d.recordObservation(Fe.slice(0,300),"Auto-retry succeeded"),b[b.length-1]={tool:D,success:!0,summary:Ne.output.slice(0,150)})}}if(s.addToolMessage(Fe),z.success&&D==="read_file"&&typeof V.path=="string"&&i?.addFile(V.path,z.output),o.info({tool:D,success:z.success,durationMs:z.duration,retries:z.retries},"Tool executed"),!z.success&&Fh(z.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}H>1&&U<H-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return _>=m&&!C&&a.onNotice?.(`Reached max iterations (${m}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:x,toolsUsed:ke(y),toolResults:b,touchedFiles:ke(S),iterations:_,success:!0,completedNaturally:C}}function ke(t){return[...new Set(t)]}function Ua(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 Ba(t){let{client:e,session:r,abortSignal:n,onChunk:s}=t,i="",o=null;for(let a=0;a<2;a++)try{i="";for await(let l of e.streamChat(r.getMessages(),n))i+=l,s?.(l);return r.addAssistantMessage(i||""),i}catch(l){if(o=l,l?.name==="AbortError"||n?.aborted)throw l;if(a===1)break}throw o||new Error("Text turn failed")}async function ur(t,e){let r=Sa(t),n=await nt(e.workingDir,e.config);if(e.session.updateSystemPrompt(st(n,r.profile)),r.profile.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context and do not restart from zero.]",{priority:"critical",tags:["runtime-note","continuity"]}),r.profile.oneStepDelivery&&e.session.addUserMessage("[Execution note: complete as much as possible in one pass with no unnecessary follow-up questions.]",{priority:"critical",tags:["runtime-note","one-step"]}),e.session.addUserMessage(t,{priority:"high",tags:[`kind:${r.profile.kind}`]}),!r.profile.needsTools){let u=new it("Hablas is reasoning");u.start();try{let d=await Ba({client:e.client,session:e.session});u.stop(),console.log(St()),console.log(_t(d));return}catch(d){u.stop(),console.log(ve(d?.message||"Text turn failed"));return}}let s=xt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=vt(3),o=[],a={onAssistantText:async u=>{o.push(u),r.profile.kind!=="implementation"&&(console.log(St()),console.log(_t(u)))},onToolStart:(u,d)=>{console.log(Ea(u,d))},onToolEnd:(u,d,h,p)=>{console.log(Oa(d,h,p))},onNotice:(u,d)=>{console.log(d==="retry"?te(`Retrying: ${u}`):te(u))},onError:u=>{console.log(ve(u))},onToolCall:()=>e.onToolCall?.()},l=Ua({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?u=>e.input.confirm(u):void 0,confirmDangerous:e.input?u=>e.input.confirmDangerous(u):void 0}),f=await Jn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:a,safetyPolicy:l,reactEngine:s,errorRecovery:i,skipTools:!1});if(r.profile.kind==="implementation"&&f.toolsUsed.length>0&&o.length>0&&(console.log(St()),console.log(_t(o[o.length-1]))),r.profile.kind==="implementation"&&f.toolsUsed.length===0){e.session.addUserMessage("SYSTEM CORRECTION: This was an implementation request. You must use workspace tools, inspect files, and create or modify actual files instead of only replying with inline code. Retry now using tools.",{priority:"critical",tags:["system-correction","force-tools"]});let u=[];(await Jn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...a,onAssistantText:async h=>{u.push(h)}},safetyPolicy:l,reactEngine:xt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:vt(3),skipTools:!1})).toolsUsed.length===0?console.log(ve("Implementation request failed to enter a real tool-execution path. Refusing to present inline-code-only output as a completed result.")):u.length>0&&(console.log(St()),console.log(_t(u[u.length-1])))}}var Xn=k(require("fs")),Ha=k(require("path")),ae=k(require("os")),Wa=require("child_process");async function fr(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=Ha.join(ae.homedir(),".hablas");if(e.push({name:"Config directory",status:Xn.existsSync(s)?"ok":"warn",message:Xn.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=ae.homedir();if(process.platform!=="win32"){let a=(0,Wa.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",f=a[4]||"?";e.push({name:"Disk space",status:parseInt(f)>90?"warn":"ok",message:`${l} available (${f} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:t.model?"ok":"warn",message:t.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${ae.platform()} ${ae.arch()} \u2014 ${ae.cpus().length} cores, ${Math.round(ae.totalmem()/1024/1024/1024)}GB RAM`}),e}function dr(t){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},r={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},n="\x1B[0m",s="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of t){let f=`${r[l.status]}${e[l.status]}${n}`,u=l.name.padEnd(18);i.push(` ${f} ${u}${s}${l.message}${n}`)}let o=t.filter(l=>l.status==="error").length,a=t.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${r.error}${o} error(s) found \u2014 fix these for hablas to work properly${n}`):a>0?i.push(` ${r.warn}${a} warning(s) \u2014 hablas should work but check the items above${n}`):i.push(` ${r.ok}All checks passed \u2014 hablas is ready!${n}`),i.push(""),i.join(`
|
|
319
|
+
`)}async function Va(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Ca());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Aa());return;case"/version":console.log(Ta());return;case"/clear":e.session.clear(),console.log(Me("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(te("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l}: ${a.content.replace(/\s+/g," ").slice(0,160)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log($a({model:e.client.getModel(),provider:Ke(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(te(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),Be(e.config),console.log(Me(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=s.join(" ").toLowerCase(),a=o?i.filter(l=>l.toLowerCase().includes(o)):i;if(a.length===0){console.log(me("No matching models found."));return}console.log(""),a.slice(0,60).forEach((l,f)=>console.log(` ${String(f+1).padStart(2," ")}. ${l}`)),a.length>60&&console.log(` ... ${a.length-60} more`),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(te(`Provider: ${Ke(e.config)}`)),console.log(te(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Me("Connection OK"):ve("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=le.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=le.defaultModel);else if(i==="custom"){if(!s[1]){console.log(me("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(me("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=ze(e.config);e.setClient(o),Be(e.config),console.log(Me(`Provider switched to ${Ke(e.config)}`));return}case"/doctor":{let i=await fr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(dr(i));return}case"/workspace":{console.log(""),console.log(tr(tt(e.workingDir))),console.log("");return}default:console.log(me(`Unknown command: ${n}`))}}async function Ga(t,e){hs();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=ze(t),s=new Ye(r,t),i=new Ze(t),o=await nt(r,t),a=new et(st(o,bt("hello")),t.historySize),l=new ar;console.log(va(t.model,r)),za.existsSync(Ka.join(r,".git"))||console.log(me("Not in a Git repository. Versioning and auto-sync features are limited."));let f=new it("Connecting");f.start();let u=await n.checkConnection();if(f.stop(u?"ready":"offline"),u){let y=await n.listModels();console.log(Me(`Connected \xB7 ${y.length} models available`))}else console.log(me(`Connection failed for ${Ke(t)}. You can still inspect local files and switch provider with /provider.`));console.log(te("Hablas is ready. Single-agent runtime active.")),console.log("");let d=0,h=0,p=Date.now(),c=new AbortController,m=0;for(process.on("SIGINT",()=>{let y=Date.now();y-m<1500&&(console.log(""),console.log(te(`Session summary \xB7 turns=${d} \xB7 toolCalls=${h} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),m=y,c.abort(),c=new AbortController,console.log(""),console.log(me("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let b=(await l.prompt(" \u203A ")).trim();if(b){if(b.startsWith("/")){if(await Va(b,{config:t,client:n,setClient:x=>{n=x},session:a,workingDir:r})==="quit")break;continue}d+=1,console.log(ka(d)),c=new AbortController;try{await ur(b,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{h+=1}})}catch(S){if(S?.name==="AbortError")continue;console.log(ve(S?.message||"Turn failed")),e.error(S,"interactive turn failed")}}}l.close()}async function Ja(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=ze(e),i=new Ye(n,e),o=new Ze(e),a=await nt(n,e),l=new et(st(a,bt(t)),e.historySize);await ur(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1})}var pr=k(require("fs")),De=k(require("path")),Lh=[{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"}],jh=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Nh=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function qh(t,e){let r=[],n=e.split(`
|
|
320
|
+
`);for(let{pattern:s,name:i,severity:o}of Lh){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let f=e.substring(0,a.index).split(`
|
|
321
|
+
`).length,u=n[f-1]||"";u.trim().startsWith("#")||u.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:f,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function Uh(t,e){let r=[],n=e.split(`
|
|
322
|
+
`),s=De.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 Xa(t,e=[]){try{let r=pr.readdirSync(t,{withFileTypes:!0});for(let n of r){if(jh.has(n.name))continue;let s=De.join(t,n.name);if(n.isDirectory())Xa(s,e);else if(n.isFile()){let i=De.extname(n.name);Nh.has(i)||e.push(s)}}}catch{}return e}function Ya(t){let e=Date.now(),r=Xa(t),n=[];for(let o of r)try{let a=pr.readFileSync(o,"utf-8"),l=De.relative(t,o),f=qh(l,a);n.push(...f);let u=Uh(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 Za(t){let e=[];if(e.push(`
|
|
246
323
|
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(`
|
|
247
|
-
`)}var
|
|
324
|
+
`)}var ot=k(require("fs")),Yn=k(require("path")),el=k(require("os")),Bh=Yn.join(el.homedir(),".hablas"),Qa=Yn.join(Bh,"analytics.json");function tl(){try{if(ot.existsSync(Qa))return JSON.parse(ot.readFileSync(Qa,"utf-8"))}catch{}return Hh()}function Hh(){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 rl(t){let e=[];e.push(`
|
|
248
325
|
\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(`
|
|
249
|
-
`)}var
|
|
326
|
+
`)}var nl=k(require("readline"));var K="\x1B[36m",hr="\x1B[32m",ye="\x1B[33m",M="\x1B[2m",we="\x1B[1m",v="\x1B[0m",Wh="\x1B[35m";function B(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function Vh(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var Ct={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function sl(t){let e=nl.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${we}${K} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${v}`),console.log(`${we}${K} hablas \u2014 Setup Wizard${v}`),console.log(`${M} Configure your AI provider and model${v}`),console.log(`${we}${K} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${v}`),console.log(),console.log(`${we} Choose your setup:${v}`),console.log(),console.log(` ${Wh}${we}1${v}. ${we}Hablas Integrated Engine${v} ${hr}(instant \u2014 no setup needed)${v}`),console.log(` ${M}Pre-configured cloud AI, ready to use immediately${v}`),console.log(),console.log(` ${K}${we}2${v}. ${we}Custom Provider${v} ${M}(bring your own API key)${v}`),console.log(` ${M}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${v}`),console.log(),(await B(e,` ${M}Your choice (1-2):${v} `)).trim()){case"1":{t.provider=Ct.provider,t.apiUrl=Ct.apiUrl,t.apiKey=Vh(),t.model=Ct.model,Be(t),console.log(),console.log(`${hr} \u2713 Hablas Integrated Engine activated!${v}`),console.log(`${M} Model: ${Ct.model}${v}`),console.log(`${M} API: ${Ct.apiUrl}${v}`),console.log(`${M} No API key needed \u2014 everything is pre-configured.${v}`);break}case"2":{switch(console.log(),console.log(`${M} Select your provider:${v}`),console.log(` ${K}a${v}. Ollama (local, free, private)`),console.log(` ${K}b${v}. OpenAI API`),console.log(` ${K}c${v}. Groq (fast, free tier)`),console.log(` ${K}d${v}. OpenRouter (many models)`),console.log(` ${K}e${v}. Together AI`),console.log(` ${K}f${v}. DeepSeek`),console.log(` ${K}g${v}. Custom OpenAI-compatible API`),console.log(` ${K}h${v}. NVIDIA NIM (powerful cloud models)`),console.log(),(await B(e,` ${M}Your choice (a-h):${v} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await B(e,` ${M}Ollama host [http://localhost:11434]:${v} `)).trim(),i=(await B(e,` ${M}Model [qwen2.5-coder:7b]:${v} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await B(e,` ${M}OpenAI API Key (sk-...):${v} `)).trim(),i=(await B(e,` ${M}Model [gpt-4o]:${v} `)).trim();if(!s){console.log(`${ye} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.openai.com/v1",t.apiKey=s,t.model=i||"gpt-4o";break}case"c":{let s=(await B(e,` ${M}Groq API Key (gsk_...):${v} `)).trim(),i=(await B(e,` ${M}Model [llama-3.3-70b-versatile]:${v} `)).trim();if(!s){console.log(`${ye} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.groq.com/openai/v1",t.apiKey=s,t.model=i||"llama-3.3-70b-versatile";break}case"d":{let s=(await B(e,` ${M}OpenRouter API Key (sk-or-...):${v} `)).trim(),i=(await B(e,` ${M}Model [anthropic/claude-3.5-sonnet]:${v} `)).trim();if(!s){console.log(`${ye} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://openrouter.ai/api/v1",t.apiKey=s,t.model=i||"anthropic/claude-3.5-sonnet";break}case"e":{let s=(await B(e,` ${M}Together API Key:${v} `)).trim(),i=(await B(e,` ${M}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${v} `)).trim();if(!s){console.log(`${ye} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.together.xyz/v1",t.apiKey=s,t.model=i||"meta-llama/Llama-3.3-70B-Instruct-Turbo";break}case"f":{let s=(await B(e,` ${M}DeepSeek API Key:${v} `)).trim(),i=(await B(e,` ${M}Model [deepseek-chat]:${v} `)).trim();if(!s){console.log(`${ye} \u26A0 No key provided \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl="https://api.deepseek.com/v1",t.apiKey=s,t.model=i||"deepseek-chat";break}case"g":{let s=(await B(e,` ${M}API base URL:${v} `)).trim(),i=(await B(e,` ${M}API key (optional):${v} `)).trim(),o=(await B(e,` ${M}Model ID:${v} `)).trim();if(!s){console.log(`${ye} \u26A0 URL is required \u2014 cancelled${v}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await B(e,` ${M}NVIDIA API Key (nvapi-...):${v} `)).trim();if(!s){console.log(`${ye} \u26A0 No key provided \u2014 cancelled${v}`),console.log(`${M} Get your key at: https://build.nvidia.com/${v}`),e.close();return}console.log(),console.log(`${M} Available NVIDIA models:${v}`),le.models.forEach((a,l)=>{console.log(` ${K}${l+1}${v}. ${a}`)}),console.log();let i=(await B(e,` ${M}Model number [1]:${v} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=le.apiUrl,t.apiKey=s,t.model=le.models[o]||le.defaultModel;break}default:console.log(`${ye} \u26A0 Invalid choice${v}`),e.close();return}Be(t),console.log(),console.log(`${hr} \u2713 Custom provider configured successfully${v}`),console.log(`${M} Provider: ${t.provider}${v}`),console.log(`${M} Model: ${t.model}${v}`);break}default:console.log(`${ye} \u26A0 Invalid choice \u2014 please select 1 or 2${v}`),e.close();return}console.log(),console.log(`${we}${hr} \u2713 Setup complete!${v}`),console.log(`${M} Use ${K}hablas${v}${M} for interactive mode or ${K}hablas run "..."${v}${M} for one-shot execution.${v}`),console.log(),e.close()}var il=To(),J=new ds;J.name("hablas").description(`Hablas CLI v${il} \u2014 single-agent engineering runtime for the terminal.`).version(il).option("-m, --model <model>","Model to use").option("-p, --project <path>","Working directory").option("--host <url>","Ollama host URL").option("--provider <type>","LLM provider: ollama | custom | nvidia").option("--api-url <url>","Custom API base URL").option("--api-key <key>","API key for custom or nvidia provider").option("--auto","Auto mode \u2014 skip tool confirmations where allowed").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--setup","Run setup wizard");J.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=J.opts(),r=Ue({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(r.autoMode=!0),e.timeout&&(r.timeout=parseInt(e.timeout,10));let n=On(r);await Ja(t,r,n)});J.command("doctor").description("Run system diagnostics").action(async()=>{let t=J.opts(),e=Ue({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await fr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(dr(r))});J.command("info").description("Show workspace information").action(async()=>{let t=J.opts(),e=Ue({project:t.project});console.log(""),console.log(tr(tt(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});J.command("security").description("Run a security scan on the current project").action(async()=>{let t=J.opts(),e=Ue({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(Za(Ya(r)))});J.command("stats").description("Show local usage statistics").action(async()=>{console.log(rl(tl()))});J.action(async()=>{let t=J.opts(),e=Ue({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 sl(e);return}let r=On(e);await Ga(e,r)});J.parse();
|