hablas-ai 2.2.6 → 2.2.8
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 +33 -0
- package/README.md +2 -0
- package/dist/index.js +149 -389
- package/package.json +5 -4
package/dist/index.js
CHANGED
|
@@ -1,117 +1,117 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${
|
|
4
|
-
`)}padWidth(e,
|
|
2
|
+
"use strict";var Rl=Object.create;var ds=Object.defineProperty;var Il=Object.getOwnPropertyDescriptor;var Pl=Object.getOwnPropertyNames;var Ml=Object.getPrototypeOf,jl=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ll=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pl(e))!jl.call(t,s)&&s!==n&&ds(t,s,{get:()=>e[s],enumerable:!(r=Il(e,s))||r.enumerable});return t};var A=(t,e,n)=>(n=t!=null?Rl(Ml(t)):{},Ll(e||!t||!t.__esModule?ds(n,"default",{value:t,enumerable:!0}):n,t));var ht=I(Tn=>{var Mt=class extends Error{constructor(e,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},$n=class extends Mt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Tn.CommanderError=Mt;Tn.InvalidArgumentError=$n});var jt=I(An=>{var{InvalidArgumentError:Dl}=ht(),Cn=class{constructor(e,n){switch(this.description=n||"",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,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new Dl(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Fl(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}An.Argument=Cn;An.humanReadableArgName=Fl});var On=I(ps=>{var{humanReadableArgName:Nl}=jt(),En=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let n=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((s,i)=>s.name().localeCompare(i.name())),n}compareOptions(e,n){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(n))}visibleOptions(e){let n=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!s&&!i?n.push(r):r.long&&!i?n.push(e.createOption(r.long,r.description)):r.short&&!s&&n.push(e.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(i=>!i.hidden);n.push(...s)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(r=>Nl(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((r,s)=>Math.max(r,n.subcommandTerm(s).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((r,s)=>Math.max(r,n.argumentTerm(s).length),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];return e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0?`${e.description} (${n.join(", ")})`:e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,n){let r=n.padWidth(e,n),s=n.helpWidth||80,i=2,o=2;function a(u,m){if(m){let g=`${u.padEnd(r+o)}${m}`;return n.wrap(g,s-i,r+o)}return u}function l(u){return u.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${n.commandUsage(e)}`,""],f=n.commandDescription(e);f.length>0&&(c=c.concat([n.wrap(f,s,0),""]));let d=n.visibleArguments(e).map(u=>a(n.argumentTerm(u),n.argumentDescription(u)));d.length>0&&(c=c.concat(["Arguments:",l(d),""]));let h=n.visibleOptions(e).map(u=>a(n.optionTerm(u),n.optionDescription(u)));if(h.length>0&&(c=c.concat(["Options:",l(h),""])),this.showGlobalOptions){let u=n.visibleGlobalOptions(e).map(m=>a(n.optionTerm(m),n.optionDescription(m)));u.length>0&&(c=c.concat(["Global Options:",l(u),""]))}let p=n.visibleCommands(e).map(u=>a(n.subcommandTerm(u),n.subcommandDescription(u)));return p.length>0&&(c=c.concat(["Commands:",l(p),""])),c.join(`
|
|
4
|
+
`)}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}wrap(e,n,r,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=n-r;if(a<s)return e;let l=e.slice(0,r),c=e.slice(r).replace(`\r
|
|
5
5
|
`,`
|
|
6
|
-
`),f=" ".repeat(
|
|
6
|
+
`),f=" ".repeat(r),h="\\s\u200B",p=new RegExp(`
|
|
7
7
|
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),u=c.match(p)||[];return l+u.map((m,g)=>m===`
|
|
8
8
|
`?"":(g>0?f:"")+m.trimEnd()).join(`
|
|
9
|
-
`)}};
|
|
10
|
-
(Did you mean one of ${
|
|
11
|
-
(Did you mean ${
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return
|
|
13
|
-
Expecting one of '${
|
|
14
|
-
- already used by option '${
|
|
9
|
+
`)}};ps.Help=En});var Mn=I(Pn=>{var{InvalidArgumentError:Ul}=ht(),Rn=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=Bl(e);this.short=r.shortFlag,this.long=r.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,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),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,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new Ul(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return ql(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},In=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,n){let r=n.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return n.negate===(i===e)}};function ql(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function Bl(t){let e,n,r=t.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),n=r.shift(),!e&&/^-[^-]$/.test(n)&&(e=n,n=void 0),{shortFlag:e,longFlag:n}}Pn.Option=Rn;Pn.DualOptions=In});var ms=I(hs=>{function Hl(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let r=0;r<=t.length;r++)n[r]=[r];for(let r=0;r<=e.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=t.length;s++){let i=1;t[s-1]===e[r-1]?i=0:i=1,n[s][r]=Math.min(n[s-1][r]+1,n[s][r-1]+1,n[s-1][r-1]+i),s>1&&r>1&&t[s-1]===e[r-2]&&t[s-2]===e[r-1]&&(n[s][r]=Math.min(n[s][r],n[s-2][r-2]+1))}return n[t.length][e.length]}function Wl(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let r=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Hl(t,o),l=Math.max(t.length,o.length);(l-a)/l>i&&(a<s?(s=a,r=[o]):a===s&&r.push(o))}),r.sort((o,a)=>o.localeCompare(a)),n&&(r=r.map(o=>`--${o}`)),r.length>1?`
|
|
10
|
+
(Did you mean one of ${r.join(", ")}?)`:r.length===1?`
|
|
11
|
+
(Did you mean ${r[0]}?)`:""}hs.suggestSimilar=Wl});var xs=I(bs=>{var Vl=require("node:events").EventEmitter,jn=require("node:child_process"),he=require("node:path"),Ln=require("node:fs"),q=require("node:process"),{Argument:zl,humanReadableArgName:Kl}=jt(),{CommanderError:Dn}=ht(),{Help:Gl}=On(),{Option:gs,DualOptions:Jl}=Mn(),{suggestSimilar:ys}=ms(),Fn=class t extends Vl{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:n=>q.stdout.write(n),writeErr:n=>q.stderr.write(n),getOutHelpWidth:()=>q.stdout.isTTY?q.stdout.columns:void 0,getErrHelpWidth:()=>q.stderr.isTTY?q.stderr.columns:void 0,outputError:(n,r)=>r(n)},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 n=this;n;n=n.parent)e.push(n);return e}command(e,n,r){let s=n,i=r;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 Gl,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,n){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 n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new zl(e,n)}argument(e,n,r,s){let i=this.createArgument(e,n);return typeof r=="function"?i.default(s).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(e){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.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,n){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,s]=e.match(/([^ ]+) *(.*)/),i=n??"display help for command",o=this.createCommand(r);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,n){return typeof e!="object"?(this.helpCommand(e,n),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,n){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,r){this._exitCallback&&this._exitCallback(new Dn(e,n,r)),q.exit(e)}action(e){let n=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=n,this}createOption(e,n){return new gs(e,n)}_callParseArg(e,n,r,s){try{return e.parseArg(n,r)}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 n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){let r=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 '${r}'
|
|
14
|
+
- already used by option '${n.flags}'`)}this.options.push(e)}_registerCommand(e){let n=s=>[s.name()].concat(s.aliases()),r=n(e).find(s=>this._findCommand(s));if(r){let s=n(this._findCommand(r)).join("|"),i=n(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(r);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(r,i,a)};return this.on("option:"+n,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+n,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,n,r,s,i){if(typeof n=="object"&&n instanceof gs)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,r);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(l,c)=>{let f=a.exec(l);return f?f[0]:c},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,n,r,s){return this._optionEx({},e,n,r,s)}requiredOption(e,n,r,s){return this._optionEx({mandatory:!0},e,n,r,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,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,r){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(n=r.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){q.versions?.electron&&(n.from="electron");let s=q.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}e===void 0&&(e=q.argv),this.rawArgs=e.slice();let r;switch(n.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":q.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,n){let r=this._prepareUserArgs(e,n);return this._parseCommand([],r),this}async parseAsync(e,n){let r=this._prepareUserArgs(e,n);return await this._parseCommand([],r),this}_executeSubCommand(e,n){n=n.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(f,d){let h=he.resolve(f,d);if(Ln.existsSync(h))return h;if(s.includes(he.extname(d)))return;let p=s.find(u=>Ln.existsSync(`${h}${u}`));if(p)return`${h}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let f;try{f=Ln.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=he.resolve(he.dirname(f),a)}if(a){let f=i(a,o);if(!f&&!e._executableFile&&this._scriptPath){let d=he.basename(this._scriptPath,he.extname(this._scriptPath));d!==this._name&&(f=i(a,`${d}-${e._name}`))}o=f||o}r=s.includes(he.extname(o));let l;q.platform!=="win32"?r?(n.unshift(o),n=ws(q.execArgv).concat(n),l=jn.spawn(q.argv[0],n,{stdio:"inherit"})):l=jn.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=ws(q.execArgv).concat(n),l=jn.spawn(q.execPath,n,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{q.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let c=this._exitCallback;l.on("close",f=>{f=f??1,c?c(new Dn(f,"commander.executeSubCommandAsync","(close)")):q.exit(f)}),l.on("error",f=>{if(f.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
16
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
-
- ${d}`;throw new Error(h)}else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)q.exit(1);else{let d=new
|
|
17
|
+
- ${d}`;throw new Error(h)}else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)q.exit(1);else{let d=new Dn(1,"commander.executeSubCommandAsync","(error)");d.nestedError=f,c(d)}}),this.runningCommand=l}_dispatchSubcommand(e,n,r){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,n.concat(r));else return s._parseCommand(n,r)}),i}_dispatchHelpCommand(e){e||this.help();let n=this._findCommand(e);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,n)=>{e.required&&this.args[n]==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=(r,s,i)=>{let o=s;if(s!==null&&r.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,s,i,a)}return o};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((r,s)=>{let i=r.defaultValue;r.variadic?s<this.args.length?(i=this.args.slice(s),r.parseArg&&(i=i.reduce((o,a)=>e(r,a,o),r.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],r.parseArg&&(i=e(r,i,r.defaultValue))),n[s]=i}),this.processedArgs=n}_chainOrCall(e,n){return e&&e.then&&typeof e.then=="function"?e.then(()=>n()):n()}_chainOrCallHooks(e,n){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[n]!==void 0).forEach(i=>{i._lifeCycleHooks[n].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),n==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,n,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,n))}),s}_parseCommand(e,n){let r=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),n=r.unknown,this.args=e.concat(n),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),n);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,e,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.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,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,n);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,n);this.listenerCount("command:*")?this.emit("command:*",e,n):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(n=>n._name===e||n._aliases.includes(e))}_findOption(e){return this.options.find(n=>n.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(n=>{n.mandatory&&e.getOptionValue(n.attributeName())===void 0&&e.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(i=>r.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let n=[],r=[],s=n,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===r&&s.push(l),s.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let c=this._findOption(l);if(c){if(c.required){let f=i.shift();f===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,f)}else if(c.optional){let f=null;i.length>0&&!o(i[0])&&(f=i.shift()),this.emit(`option:${c.name()}`,f)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),f=this._findOption(l.slice(0,c));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,l.slice(c+1));continue}}if(o(l)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&r.length===0){if(this._findCommand(l)){n.push(l),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){n.push(l),i.length>0&&n.push(...i);break}else if(this._defaultCommandName){r.push(l),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(l),i.length>0&&s.push(...i);break}s.push(l)}return{operands:n,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},n=this.options.length;for(let r=0;r<n;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,n)=>Object.assign(e,n.opts()),{})}error(e,n){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
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,
|
|
22
|
-
Expecting one of '${
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let
|
|
24
|
-
causes have become circular...`;let
|
|
25
|
-
caused by: `+As(n,e)):r},Xl=t=>As(t,new Set),Es=(t,e,r)=>{if(!ht(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=Nr(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+Es(s,e,i)}else return n},Zl=t=>Es(t,new Set);Os.exports={isErrorLike:ht,getErrorCause:Nr,stackWithCauses:Xl,messageWithCauses:Zl}});var qr=I((og,Is)=>{"use strict";var Ql=Symbol("circular-ref-tag"),Lt=Symbol("pino-raw-err-ref"),Rs=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[Lt]},set:function(t){this[Lt]=t}}});Object.defineProperty(Rs,Lt,{writable:!0,value:{}});Is.exports={pinoErrProto:Rs,pinoErrorSymbols:{seen:Ql,rawSymbol:Lt}}});var Ls=I((ag,Ps)=>{"use strict";Ps.exports=Hr;var{messageWithCauses:ec,stackWithCauses:tc,isErrorLike:Ms}=Ur(),{pinoErrProto:rc,pinoErrorSymbols:nc}=qr(),{seen:Br}=nc,{toString:sc}=Object.prototype;function Hr(t){if(!Ms(t))return t;t[Br]=void 0;let e=Object.create(rc);e.type=sc.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=ec(t),e.stack=tc(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Hr(r)));for(let r in t)if(e[r]===void 0){let n=t[r];Ms(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Br)&&(e[r]=Hr(n)):e[r]=n}return delete t[Br],e.raw=t,e}});var Ds=I((lg,js)=>{"use strict";js.exports=Dt;var{isErrorLike:Wr}=Ur(),{pinoErrProto:ic,pinoErrorSymbols:oc}=qr(),{seen:jt}=oc,{toString:ac}=Object.prototype;function Dt(t){if(!Wr(t))return t;t[jt]=void 0;let e=Object.create(ic);e.type=ac.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=t.message,e.stack=t.stack,Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Dt(r))),Wr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,jt)&&(e.cause=Dt(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];Wr(n)?Object.prototype.hasOwnProperty.call(n,jt)||(e[r]=Dt(n)):e[r]=n}return delete t[jt],e.raw=t,e}});var qs=I((cg,Us)=>{"use strict";Us.exports={mapHttpRequest:lc,reqSerializer:Ns};var Vr=Symbol("pino-raw-req-ref"),Fs=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Vr]},set:function(t){this[Vr]=t}}});Object.defineProperty(Fs,Vr,{writable:!0,value:{}});function Ns(t){let e=t.info||t.socket,r=Object.create(Fs);if(r.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),r.method=t.method,t.originalUrl)r.url=t.originalUrl;else{let n=t.path;r.url=typeof n=="string"?n:t.url?t.url.path||t.url:void 0}return t.query&&(r.query=t.query),t.params&&(r.params=t.params),r.headers=t.headers,r.remoteAddress=e&&e.remoteAddress,r.remotePort=e&&e.remotePort,r.raw=t.raw||t,r}function lc(t){return{req:Ns(t)}}});var Vs=I((ug,Ws)=>{"use strict";Ws.exports={mapHttpResponse:cc,resSerializer:Hs};var zr=Symbol("pino-raw-res-ref"),Bs=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[zr]},set:function(t){this[zr]=t}}});Object.defineProperty(Bs,zr,{writable:!0,value:{}});function Hs(t){let e=Object.create(Bs);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function cc(t){return{res:Hs(t)}}});var Gr=I((fg,zs)=>{"use strict";var Kr=Ls(),uc=Ds(),Ft=qs(),Nt=Vs();zs.exports={err:Kr,errWithCause:uc,mapHttpRequest:Ft.mapHttpRequest,mapHttpResponse:Nt.mapHttpResponse,req:Ft.reqSerializer,res:Nt.resSerializer,wrapErrorSerializer:function(e){return e===Kr?e:function(n){return e(Kr(n))}},wrapRequestSerializer:function(e){return e===Ft.reqSerializer?e:function(n){return e(Ft.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Nt.resSerializer?e:function(n){return e(Nt.resSerializer(n))}}}});var Jr=I((dg,Ks)=>{"use strict";function fc(t,e){return e}Ks.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=fc;let r=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(r))return;let n=r.slice(2),s=[];for(let i of n)i&&s.push(i.getFileName());return s}});var Qs=I((pg,Zs)=>{"use strict";function Yr(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array){let e=[];for(let r=0;r<t.length;r++)e[r]=Yr(t[r]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=Yr(t[r]));return e}return t}function Gs(t){let e=[],r="",n=!1,s=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!n&&a==="."?r&&(e.push(r),r=""):a==="["?(r&&(e.push(r),r=""),n=!0):a==="]"&&n?(e.push(r),r="",n=!1,s=!1):(a==='"'||a==="'")&&n?s?a===i?(s=!1,i=""):r+=a:(s=!0,i=a):r+=a}return r&&e.push(r),e}function Js(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof n!="object"||n===null||!(o in n)||typeof n[o]!="object"||n[o]===null)return!1;n=n[o]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(n))for(let i=0;i<n.length;i++)n[i]=r;else if(typeof n=="object"&&n!==null)for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&(n[i]=r)}else typeof n=="object"&&n!==null&&s in n&&Object.prototype.hasOwnProperty.call(n,s)&&(n[s]=r);return!0}function Ys(t,e){let r=t;for(let s=0;s<e.length-1;s++){let i=e[s];if(typeof r!="object"||r===null||!(i in r)||typeof r[i]!="object"||r[i]===null)return!1;r=r[i]}let n=e[e.length-1];if(n==="*"){if(Array.isArray(r))for(let s=0;s<r.length;s++)r[s]=void 0;else if(typeof r=="object"&&r!==null)for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&delete r[s]}else typeof r=="object"&&r!==null&&n in r&&Object.prototype.hasOwnProperty.call(r,n)&&delete r[n];return!0}var Ut=Symbol("PATH_NOT_FOUND");function dc(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return Ut;r=r[n]}return r}function pc(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null)return;r=r[n]}return r}function hc(t,e,r,n=!1){for(let s of e){let i=Gs(s);if(i.includes("*"))Xs(t,i,r,s,n);else if(n)Ys(t,i);else{let o=dc(t,i);if(o===Ut)continue;let a=typeof r=="function"?r(o,i):r;Js(t,i,a)}}}function Xs(t,e,r,n,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(s)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let c=[...o,l.toString()],f=typeof r=="function"?r(a[l],c):r;a[l]=f}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],f=typeof r=="function"?r(a[l],c):r;a[l]=f}}else mc(t,e,r,i,n,s)}function mc(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function c(f,d){if(d===o.length){if(Array.isArray(f))for(let h=0;h<f.length;h++)l[d]=h.toString(),c(f[h],d+1);else if(typeof f=="object"&&f!==null)for(let h in f)l[d]=h,c(f[h],d+1)}else if(d<o.length){let h=o[d];f&&typeof f=="object"&&f!==null&&h in f&&(l[d]=h,c(f[h],d+1))}else if(a.includes("*"))Xs(f,a,typeof r=="function"?(p,u)=>{let m=[...l.slice(0,d),...u];return r(p,m)}:r,s,i);else if(i)Ys(f,a);else{let h=typeof r=="function"?r(pc(f,a),[...l.slice(0,d),...a]):r;Js(f,a,h)}}if(o.length===0)c(t,0);else{let f=t;for(let d=0;d<o.length;d++){let h=o[d];if(f==null||typeof f!="object"||f===null)return;f=f[h],l[d]=h}f!=null&&c(f,o.length)}}function gc(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=Gs(r),s=e;for(let i=0;i<n.length;i++){let o=n[i];s.has(o)||s.set(o,new Map),s=s.get(o)}}return e}function yc(t,e){if(!e)return t;function r(n,s,i=0){if(!s||s.size===0||n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n)){let a=[];for(let l=0;l<n.length;l++){let c=l.toString();s.has(c)||s.has("*")?a[l]=r(n[l],s.get(c)||s.get("*")):a[l]=n[l]}return a}let o=Object.create(Object.getPrototypeOf(n));for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s.has(a)||s.has("*")?o[a]=r(n[a],s.get(a)||s.get("*")):o[a]=n[a]);return o}return r(t,e)}function wc(t){if(typeof t!="string")throw new Error("Paths must be (non-empty) strings");if(t==="")throw new Error("Invalid redaction path ()");if(t.includes(".."))throw new Error(`Invalid redaction path (${t})`);if(t.includes(","))throw new Error(`Invalid redaction path (${t})`);let e=0,r=!1,n="";for(let s=0;s<t.length;s++){let i=t[s];if((i==='"'||i==="'")&&e>0)r?i===n&&(r=!1,n=""):(r=!0,n=i);else if(i==="["&&!r)e++;else if(i==="]"&&!r&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function bc(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)wc(e)}function Sc(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;bc(e);let o=gc(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let c=yc(l,o),f=l,d=r;return typeof r=="function"&&(d=r),hc(c,e,d,i),n===!1?(c.restore=function(){return Yr(f)},c):typeof n=="function"?n(c):JSON.stringify(c)}}Zs.exports=Sc});var Ge=I((hg,ei)=>{"use strict";var xc=Symbol("pino.setLevel"),_c=Symbol("pino.getLevel"),vc=Symbol("pino.levelVal"),kc=Symbol("pino.levelComp"),$c=Symbol("pino.useLevelLabels"),Tc=Symbol("pino.useOnlyCustomLevels"),Cc=Symbol("pino.mixin"),Ac=Symbol("pino.lsCache"),Ec=Symbol("pino.chindings"),Oc=Symbol("pino.asJson"),Rc=Symbol("pino.write"),Ic=Symbol("pino.redactFmt"),Mc=Symbol("pino.time"),Pc=Symbol("pino.timeSliceIndex"),Lc=Symbol("pino.stream"),jc=Symbol("pino.stringify"),Dc=Symbol("pino.stringifySafe"),Fc=Symbol("pino.stringifiers"),Nc=Symbol("pino.end"),Uc=Symbol("pino.formatOpts"),qc=Symbol("pino.messageKey"),Bc=Symbol("pino.errorKey"),Hc=Symbol("pino.nestedKey"),Wc=Symbol("pino.nestedKeyStr"),Vc=Symbol("pino.mixinMergeStrategy"),zc=Symbol("pino.msgPrefix"),Kc=Symbol("pino.wildcardFirst"),Gc=Symbol.for("pino.serializers"),Jc=Symbol.for("pino.formatters"),Yc=Symbol.for("pino.hooks"),Xc=Symbol.for("pino.metadata");ei.exports={setLevelSym:xc,getLevelSym:_c,levelValSym:vc,levelCompSym:kc,useLevelLabelsSym:$c,mixinSym:Cc,lsCacheSym:Ac,chindingsSym:Ec,asJsonSym:Oc,writeSym:Rc,serializersSym:Gc,redactFmtSym:Ic,timeSym:Mc,timeSliceIndexSym:Pc,streamSym:Lc,stringifySym:jc,stringifySafeSym:Dc,stringifiersSym:Fc,endSym:Nc,formatOptsSym:Uc,messageKeySym:qc,errorKeySym:Bc,nestedKeySym:Hc,wildcardFirstSym:Kc,needsMetadataGsym:Xc,useOnlyCustomLevelsSym:Tc,formattersSym:Jc,hooksSym:Yc,nestedKeyStrSym:Wc,mixinMergeStrategySym:Vc,msgPrefixSym:zc}});var Zr=I((mg,si)=>{"use strict";var ti=Qs(),{redactFmtSym:Zc,wildcardFirstSym:qt}=Ge(),Xr=/[^.[\]]+|\[([^[\]]*?)\]/g,ri="[Redacted]",ni=!1;function Qc(t,e){let{paths:r,censor:n,remove:s}=eu(t),i=r.reduce((l,c)=>{Xr.lastIndex=0;let f=Xr.exec(c),d=Xr.exec(c),h=f[1]!==void 0?f[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):f[0];if(h==="*"&&(h=qt),d===null)return l[h]=null,l;if(l[h]===null)return l;let{index:p}=d,u=`${c.substr(p,c.length-1)}`;return l[h]=l[h]||[],h!==qt&&l[h].length===0&&l[h].push(...l[qt]||[]),h===qt&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(u)}),l[h].push(u),l},{}),o={[Zc]:ti({paths:r,censor:n,serialize:e,strict:ni,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=f=>a(f,[c]);else{let f=typeof n=="function"?(d,h)=>n(d,[c,...h]):n;l[c]=ti({paths:i[c],censor:f,serialize:e,strict:ni,remove:s})}return l},o)}function eu(t){if(Array.isArray(t))return t={paths:t,censor:ri},t;let{paths:e,censor:r=ri,remove:n}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),{paths:e,censor:r,remove:n}}si.exports=Qc});var ai=I((gg,oi)=>{"use strict";var tu=()=>"",ru=()=>`,"time":${Date.now()}`,nu=()=>`,"time":${Math.round(Date.now()/1e3)}`,su=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,iu=1000000n,ii=1000000000n,ou=BigInt(Date.now())*iu,au=process.hrtime.bigint(),lu=()=>{let t=process.hrtime.bigint()-au,e=ou+t,r=e/ii,n=e%ii,s=Number(r*1000n+n/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),f=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${f}:${d}.${n.toString().padStart(9,"0")}Z"`};oi.exports={nullTime:tu,epochTime:ru,unixTime:nu,isoTime:su,isoTimeNano:lu}});var ci=I((yg,li)=>{"use strict";function cu(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}li.exports=uu;function uu(t,e,r){var n=r&&r.stringify||cu,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var c="",f=1-s,d=-1,h=t&&t.length||0,p=0;p<h;){if(t.charCodeAt(p)===37&&p+1<h){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(f>=l||e[f]==null)break;d<p&&(c+=t.slice(d,p)),c+=Number(e[f]),d=p+2,p++;break;case 105:if(f>=l||e[f]==null)break;d<p&&(c+=t.slice(d,p)),c+=Math.floor(Number(e[f])),d=p+2,p++;break;case 79:case 111:case 106:if(f>=l||e[f]===void 0)break;d<p&&(c+=t.slice(d,p));var u=typeof e[f];if(u==="string"){c+="'"+e[f]+"'",d=p+2,p++;break}if(u==="function"){c+=e[f].name||"<anonymous>",d=p+2,p++;break}c+=n(e[f]),d=p+2,p++;break;case 115:if(f>=l)break;d<p&&(c+=t.slice(d,p)),c+=String(e[f]),d=p+2,p++;break;case 37:d<p&&(c+=t.slice(d,p)),c+="%",d=p+2,p++,f--;break}++f}++p}return d===-1?t:(d<h&&(c+=t.slice(d)),c)}});var en=I((wg,Qr)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(t,0,0,Number(r))},t=new Int32Array(new SharedArrayBuffer(4));Qr.exports=e}else{let t=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(e);for(;n>Date.now(););};Qr.exports=t}});var yi=I((bg,gi)=>{"use strict";var N=require("fs"),fu=require("events"),du=require("util").inherits,ui=require("path"),rn=en(),pu=require("assert"),Bt=100,Ht=Buffer.allocUnsafe(0),hu=16*1024,fi="buffer",di="utf8",[mu,gu]=(process.versions.node||"0.0").split(".").map(Number),yu=mu>=22&&gu>=7;function pi(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function r(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=t,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let n=e.append?"a":"w",s=e.mode;if(e.sync)try{e.mkdir&&N.mkdirSync(ui.dirname(t),{recursive:!0});let i=N.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?N.mkdir(ui.dirname(t),{recursive:!0},i=>{if(i)return r(i);N.open(t,n,s,r)}):N.open(t,n,s,r)}function ae(t){if(!(this instanceof ae))return new ae(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:f,fsync:d,contentMode:h,mode:p}=t||{};e=e||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=s||0,this.maxWrite=i||hu,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=p,this.retryEAGAIN=f||(()=>!0),this.mkdir=c||!1;let u,m;if(h===fi)this._writingBuf=Ht,this.write=Su,this.flush=_u,this.flushSync=ku,this._actualWrite=Tu,u=()=>N.writeSync(this.fd,this._writingBuf),m=()=>N.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===di)this._writingBuf="",this.write=bu,this.flush=xu,this.flushSync=vu,this._actualWrite=$u,u=()=>Buffer.isBuffer(this._writingBuf)?N.writeSync(this.fd,this._writingBuf):N.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?N.write(this.fd,this._writingBuf,this.release):N.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${di}" and "${fi}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")pi(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(g,x)=>{if(g){if((g.code==="EAGAIN"||g.code==="EBUSY")&&this.retryEAGAIN(g,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{rn(Bt),this.release(void 0,0)}catch(_){this.release(_)}else setTimeout(m,Bt);else this._writing=!1,this.emit("error",g);return}this.emit("write",x);let b=tn(this._writingBuf,this._len,x);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let _=u(),v=tn(this._writingBuf,this._len,_);this._len=v.len,this._writingBuf=v.writingBuf}while(this._writingBuf.length)}catch(_){this.release(_);return}}this._fsync&&N.fsyncSync(this.fd);let S=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):S>this.minLength?this._actualWrite():this._ending?S>0?this._actualWrite():(this._writing=!1,Wt(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(wu,this)):this.emit("drain"))},this.on("newListener",function(g){g==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function tn(t,e,r){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-r,0),t=t.subarray(r),{writingBuf:t,len:e}}function wu(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}du(ae,fu);function hi(t,e){return t.length===0?Ht:t.length===1?t[0]:Buffer.concat(t,e)}function bu(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),r=this._len+e,n=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(n.length===0||Buffer.byteLength(n[n.length-1])+e>this.maxWrite?n.push(t):n[n.length-1]+=t,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Su(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,r=this._bufs,n=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||n[n.length-1]+t.length>this.maxWrite?(r.push([t]),n.push(t.length)):(r[r.length-1].push(t),n[n.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function mi(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{N.fsync(this.fd,n=>{this._flushPending=!1,t(n)})}catch(n){t(n)}this.off("error",r)},r=n=>{this._flushPending=!1,t(n),this.off("drain",e)};this.once("drain",e),this.once("error",r)}function xu(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&mi.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function _u(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&mi.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}ae.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&N.close(e,r=>{if(r)return this.emit("error",r)})}),pi(this.file,this)};ae.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():Wt(this)))};function vu(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?N.writeSync(this.fd,t):N.writeSync(this.fd,t,"utf8"),r=tn(t,this._len,e);t=r.writingBuf,this._len=r.len,t.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;rn(Bt)}}try{N.fsyncSync(this.fd)}catch{}}function ku(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=Ht);let t=Ht;for(;this._bufs.length||t.length;){t.length<=0&&(t=hi(this._bufs[0],this._lens[0]));try{let e=N.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;rn(Bt)}}}ae.prototype.destroy=function(){this.destroyed||Wt(this)};function $u(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?N.writeSync(this.fd,this._writingBuf):N.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else N.write(this.fd,this._writingBuf,t)}function Tu(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:hi(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=N.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else yu&&(this._writingBuf=Buffer.from(this._writingBuf)),N.write(this.fd,this._writingBuf,t)}function Wt(t){if(t.fd===-1){t.once("ready",Wt.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],pu(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{N.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?N.close(t.fd,r):r()}function r(n){if(n){t.emit("error",n);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}ae.SonicBoom=ae;ae.default=ae;gi.exports=ae});var nn=I((Sg,_i)=>{"use strict";var le={exit:[],beforeExit:[]},wi={exit:Eu,beforeExit:Ou},Je;function Cu(){Je===void 0&&(Je=new FinalizationRegistry(Ru))}function Au(t){le[t].length>0||process.on(t,wi[t])}function bi(t){le[t].length>0||(process.removeListener(t,wi[t]),le.exit.length===0&&le.beforeExit.length===0&&(Je=void 0))}function Eu(){Si("exit")}function Ou(){Si("beforeExit")}function Si(t){for(let e of le[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}le[t]=[]}function Ru(t){for(let e of["exit","beforeExit"]){let r=le[e].indexOf(t);le[e].splice(r,r+1),bi(e)}}function xi(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");Au(t);let n=new WeakRef(e);n.fn=r,Cu(),Je.register(e,n),le[t].push(n)}function Iu(t,e){xi("exit",t,e)}function Mu(t,e){xi("beforeExit",t,e)}function Pu(t){if(Je!==void 0){Je.unregister(t);for(let e of["exit","beforeExit"])le[e]=le[e].filter(r=>{let n=r.deref();return n&&n!==t}),bi(e)}}_i.exports={register:Iu,registerBeforeExit:Mu,unregister:Pu}});var vi=I((xg,Lu)=>{Lu.exports={name:"thread-stream",version:"4.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",engines:{node:">=20"},dependencies:{"real-require":"^1.0.0"},devDependencies:{"@types/node":"^25.0.2","@yao-pkg/pkg":"^6.0.0",borp:"^1.0.0",desm:"^1.3.0",eslint:"^9.39.1",fastbench:"^1.0.1",neostandard:"^0.13.0","pino-elasticsearch":"^9.0.0","sonic-boom":"^5.0.0","ts-node":"^10.8.0",typescript:"~5.7.3"},scripts:{build:"tsc --noEmit",lint:"eslint",test:'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:ci":'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:yarn":'npm run transpile && borp --pattern "test/*.test.js"',transpile:"sh ./test/ts/transpile.sh"},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina <hello@matteocollina.com>",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var $i=I((_g,ki)=>{"use strict";function ju(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{let a=Atomics.load(t,e);if(a===r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,a,l);c.async?c.value.then(o):setImmediate(o)};o()}function Du(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{if(Atomics.load(t,e)!==r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,r,l);c.async?c.value.then(f=>{if(f==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}ki.exports={wait:ju,waitDiff:Du}});var Ci=I((vg,Ti)=>{"use strict";Ti.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Ni=I((kg,Fi)=>{"use strict";var{version:Fu}=vi(),{EventEmitter:Nu}=require("events"),{Worker:Uu}=require("worker_threads"),{join:qu}=require("path"),{pathToFileURL:Bu}=require("url"),{wait:Hu}=$i(),{WRITE_INDEX:he,READ_INDEX:Re,SEQ_INDEX:sn}=Ci(),Wu=require("buffer"),Vu=require("assert"),y=Symbol("kImpl"),zu=Wu.constants.MAX_STRING_LENGTH;function Ai(){}function cn(t,e){Atomics.add(t[y].state,sn,1),e(),Atomics.add(t[y].state,sn,1),Atomics.notify(t[y].state,sn)}function Ei(t){cn(t,()=>{Atomics.store(t[y].state,Re,0),Atomics.store(t[y].state,he,0)})}var mt=class{constructor(e){this._value=e}deref(){return this._value}},Vt=class{register(){}unregister(){}},Ku=process.env.NODE_V8_COVERAGE?Vt:global.FinalizationRegistry||Vt,Gu=process.env.NODE_V8_COVERAGE?mt:global.WeakRef||mt,Oi=new Ku(t=>{t.exited||t.terminate()});function Ju(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||qu(__dirname,"lib","worker.js"),o=new Uu(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Bu(r).href,dataBuf:t[y].dataBuf,stateBuf:t[y].stateBuf,workerData:{$context:{threadStreamVersion:Fu},...n}}});return o.stream=new mt(t),o.on("message",Yu),o.on("exit",Mi),Oi.register(t,o),o}function Ri(t){Vu(!t[y].sync),t[y].needDrain&&(t[y].needDrain=!1,t.emit("drain"))}function Ii(t){for(;;){let e=Atomics.load(t[y].state,he),r=t[y].data.length-e;if(r>0){if(t[y].bufLen===0){t[y].flushing=!1,t[y].ending?un(t):t[y].needDrain&&process.nextTick(Ri,t);return}ji(t,r,Ai);continue}if(r===0){if(e===0&&t[y].bufLen===0)return;zt(t,()=>{t.destroyed||(Ei(t),Ii(t))});return}te(t,new Error("overwritten"));return}}function Yu(t){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(t?.code!=null)switch(t.code){case"READY":this.stream=new Gu(e),zt(e,()=>{e[y].ready=!0,e.emit("ready")});break;case"ERROR":te(e,t.err);break;case"EVENT":Array.isArray(t.args)?e.emit(t.name,...t.args):e.emit(t.name,t.args);break;case"FLUSHED":{if(t.context!=="thread-stream"){te(e,new Error("this should not happen: "+t.code));break}let r=e[y].flushCallbacks.get(t.id);r&&(e[y].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:te(e,new Error("this should not happen: "+t.code))}}function Mi(t){let e=this.stream.deref();e!==void 0&&(Oi.unregister(e),e.worker.exited=!0,e.worker.off("exit",Mi),te(e,t!==0?new Error("the worker thread exited"):null))}var an=class extends Nu{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[y]={},this[y].stateBuf=new SharedArrayBuffer(128),this[y].state=new Int32Array(this[y].stateBuf),this[y].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[y].data=Buffer.from(this[y].dataBuf),this[y].sync=e.sync||!1,this[y].ending=!1,this[y].ended=!1,this[y].needDrain=!1,this[y].destroyed=!1,this[y].flushing=!1,this[y].ready=!1,this[y].finished=!1,this[y].errored=null,this[y].closed=!1,this[y].buf=[],this[y].bufHead=0,this[y].bufLen=0,this[y].flushCallbacks=new Map,this[y].nextFlushId=0,this.worker=Ju(this,e),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(e){let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[y].destroyed)return ln(this,new Error("the worker has exited")),!1;if(this[y].ending)return ln(this,new Error("the worker is ending")),!1;if(this[y].flushing&&this[y].bufLen+r.length>=zu)try{on(this),this[y].flushing=!0}catch(n){return te(this,n),!1}if(this[y].buf.push(r),this[y].bufLen+=r.length,this[y].sync)try{return on(this),!0}catch(n){return te(this,n),!1}return this[y].flushing||(this[y].flushing=!0,setImmediate(Ii,this)),this[y].needDrain=this[y].data.length-this[y].bufLen-Atomics.load(this[y].state,he)<=0,!this[y].needDrain}end(){this[y].destroyed||(this[y].ending=!0,un(this))}flush(e){e=typeof e=="function"?e:Ai,Pi(this,r=>{if(r){process.nextTick(e,r);return}Li(this,e)})}flushSync(){this[y].destroyed||(on(this),Di(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[y].ready}get destroyed(){return this[y].destroyed}get closed(){return this[y].closed}get writable(){return!this[y].destroyed&&!this[y].ending}get writableEnded(){return this[y].ending}get writableFinished(){return this[y].finished}get writableNeedDrain(){return this[y].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[y].errored}};function Pi(t,e){if(t[y].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[y].sync&&(t[y].flushing||t[y].bufLen>0)){setImmediate(Pi,t,e);return}zt(t,e)}function zt(t,e){let r=Atomics.load(t[y].state,he);Hu(t[y].state,Re,r,1/0,(n,s)=>{if(n){te(t,n),e(n);return}if(s!=="ok"){zt(t,e);return}e()})}function Li(t,e){if(t[y].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[y].ready){let n=()=>{i(),Li(t,e)},s=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",n),t.off("close",s)};t.once("ready",n),t.once("close",s);return}let r=++t[y].nextFlushId;t[y].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[y].flushCallbacks.delete(r),te(t,n),process.nextTick(e,n)}}function Xu(t,e){let r=t[y].flushCallbacks;if(r.size===0)return;let n=e||new Error("the worker has exited");for(let s of r.values())process.nextTick(s,n);r.clear()}function ln(t,e){setImmediate(()=>{t.emit("error",e)})}function te(t,e){t[y].destroyed||(t[y].destroyed=!0,Xu(t,e),e&&(t[y].errored=e,ln(t,e)),t.worker.exited?setImmediate(()=>{t[y].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[y].closed=!0,t.emit("close")}))}function ji(t,e,r){let s=Atomics.load(t[y].state,he),i=e;for(;i>0&&t[y].bufLen!==0;){let o=t[y].bufHead,a=t[y].buf[o];if(a.length<=i){a.copy(t[y].data,s),s+=a.length,i-=a.length,t[y].bufLen-=a.length,t[y].bufHead=o+1,t[y].bufHead===t[y].buf.length?(t[y].buf.length=0,t[y].bufHead=0):t[y].bufHead>=1024&&t[y].bufHead*2>=t[y].buf.length&&(t[y].buf.splice(0,t[y].bufHead),t[y].bufHead=0);continue}a.copy(t[y].data,s,0,i),t[y].buf[o]=a.subarray(i),t[y].bufLen-=i,s+=i,i=0}return cn(t,()=>{Atomics.store(t[y].state,he,s)}),r(),!0}function un(t){if(!(t[y].ended||!t[y].ending||t[y].flushing)){t[y].ended=!0;try{t.flushSync();let e=Atomics.load(t[y].state,Re);cn(t,()=>{Atomics.store(t[y].state,he,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[y].state,Re,e,1e3),e=Atomics.load(t[y].state,Re),e===-2){te(t,new Error("end() failed"));return}if(++r===10){te(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[y].finished=!0,t.emit("finish")})}catch(e){te(t,e)}}}function on(t){let e=()=>{t[y].ending?un(t):t[y].needDrain&&process.nextTick(Ri,t)};for(t[y].flushing=!1;t[y].bufLen!==0;){let r=Atomics.load(t[y].state,he),n=t[y].data.length-r;if(n===0){Di(t),Ei(t);continue}else if(n<0)throw new Error("overwritten");ji(t,n,e)}}function Di(t){if(t[y].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[y].state,he),r=0;for(;;){let n=Atomics.load(t[y].state,Re);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[y].state,Re,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}Fi.exports=an});var pn=I(($g,Bi)=>{"use strict";var{createRequire:Zu}=require("module"),{existsSync:Qu}=require("node:fs"),ef=Jr(),{join:fn,isAbsolute:qi,sep:tf}=require("node:path"),{fileURLToPath:rf}=require("node:url"),nf=en(),dn=nn(),sf=Ni();function of(t){dn.register(t,ff),dn.registerBeforeExit(t,df),t.on("close",function(){dn.unregister(t)})}function af(){let t=process.execArgv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--import"||r==="--require"||r==="-r"||r.startsWith("--import=")||r.startsWith("--require=")||r.startsWith("-r="))return!0}return!1}function lf(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let r=[],n=!1;for(let s=0;s<e.length;s++){let i=e[s];if(i==="--require"||i==="-r"||i==="--import"){let o=e[s+1];if(o&&Ui(o)){n=!0,s++;continue}r.push(i),o&&(r.push(o),s++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(Ui(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function Ui(t){let e=cf(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=rf(r)}catch{return!1}return qi(r)&&!Qu(r)}function cf(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function uf(t,e,r,n,s){if(!r.execArgv&&af()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=lf(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new sf({filename:t,workerData:e,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),r.autoEnd!==!1&&of(i)}function a(){i.closed||(i.flushSync(),nf(100),i.end())}return i}function ff(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function df(t){t.flushSync()}function pf(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=ef(),sync:a=!1}=t,l={...t.options},c=typeof o=="string"?[o]:o,f=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&r)throw new Error("only one of target or targets can be specified");r?(d=f["pino-worker"]||fn(__dirname,"worker.js"),l.targets=r.filter(u=>u.target).map(u=>({...u,target:p(u.target)})),l.pipelines=r.filter(u=>u.pipeline).map(u=>u.pipeline.map(m=>({...m,level:u.level,target:p(m.target)})))):e&&(d=f["pino-worker"]||fn(__dirname,"worker.js"),l.pipelines=[e.map(u=>({...u,target:p(u.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let h=r||e?"pino.transport":d;return uf(p(d),l,i,a,h);function p(u){if(u=f[u]||u,qi(u)||u.indexOf("file://")===0)return u;if(u==="pino/file")return fn(__dirname,"..","file.js");let m;for(let g of c)try{let x=g==="node:repl"?process.cwd()+tf:g;m=Zu(x).resolve(u);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${u}"`);return m}}Bi.exports=pf});var Jt=I((Tg,to)=>{"use strict";var hf=require("node:diagnostics_channel"),Hi=ci(),{mapHttpRequest:mf,mapHttpResponse:gf}=Gr(),mn=yi(),Wi=nn(),{lsCacheSym:yf,chindingsSym:Ji,writeSym:Vi,serializersSym:Yi,formatOptsSym:zi,endSym:wf,stringifiersSym:Xi,stringifySym:Zi,stringifySafeSym:gn,wildcardFirstSym:Qi,nestedKeySym:bf,formattersSym:eo,messageKeySym:Sf,errorKeySym:xf,nestedKeyStrSym:_f,msgPrefixSym:Kt}=Ge(),{isMainThread:vf}=require("worker_threads"),kf=pn(),[$f]=process.versions.node.split(".").map(t=>Number(t)),Ki=hf.tracingChannel("pino_asJson"),hn=$f>=25?t=>JSON.stringify(t):Cf;function Ye(){}function Tf(t,e){if(!e)return r;return function(...s){e.call(this,s,r,t)};function r(n,...s){if(typeof n=="object"){let i=n;n!==null&&(n.method&&n.headers&&n.socket?n=mf(n):typeof n.setHeader=="function"&&(n=gf(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Kt]=="string"&&i!==void 0&&i!==null&&(i=this[Kt]+i),this[Vi](n,Hi(i,o,this[zi]),t)}else{let i=n===void 0?s.shift():n;typeof this[Kt]=="string"&&i!==void 0&&i!==null&&(i=this[Kt]+i),this[Vi](null,Hi(i,s,this[zi]),t)}}}function Cf(t){let e="",r=0,n=!1,s=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&s>=32;o++)s=t.charCodeAt(o),(s===34||s===92)&&(e+=t.slice(r,o)+"\\",r=o,n=!0);return n?e+=t.slice(r):e=t,s<32?JSON.stringify(t):'"'+e+'"'}function Af(t,e,r,n){if(Ki.hasSubscribers===!1)return Gi.call(this,t,e,r,n);let s={instance:this,arguments};return Ki.traceSync(Gi,s,this,t,e,r,n)}function Gi(t,e,r,n){let s=this[Zi],i=this[gn],o=this[Xi],a=this[wf],l=this[Ji],c=this[Yi],f=this[eo],d=this[Sf],h=this[xf],p=this[yf][r]+n;p=p+l;let u;f.log&&(t=f.log(t));let m=o[Qi],g="";for(let b in t)if(u=t[b],Object.prototype.hasOwnProperty.call(t,b)&&u!==void 0){c[b]?u=c[b](u):b===h&&c.err&&(u=c.err(u));let S=o[b]||m;switch(typeof u){case"undefined":case"function":continue;case"number":Number.isFinite(u)===!1&&(u=null);case"boolean":S&&(u=S(u));break;case"string":u=(S||hn)(u);break;default:u=(S||s)(u,i)}if(u===void 0)continue;let _=hn(b);g+=","+_+":"+u}let x="";if(e!==void 0){u=c[d]?c[d](e):e;let b=o[d]||m;switch(typeof u){case"function":break;case"number":Number.isFinite(u)===!1&&(u=null);case"boolean":b&&(u=b(u)),x=',"'+d+'":'+u;break;case"string":u=(b||hn)(u),x=',"'+d+'":'+u;break;default:u=(b||s)(u,i),x=',"'+d+'":'+u}}return this[bf]&&g?p+this[_f]+g.slice(1)+"}"+x+a:p+g+x+a}function Ef(t,e){let r,n=t[Ji],s=t[Zi],i=t[gn],o=t[Xi],a=o[Qi],l=t[Yi],c=t[eo].bindings;e=c(e);for(let f in e)if(r=e[f],((f.length<5||f!=="level"&&f!=="serializers"&&f!=="formatters"&&f!=="customLevels")&&e.hasOwnProperty(f)&&r!==void 0)===!0){if(r=l[f]?l[f](r):r,r=(o[f]||a||s)(r,i),r===void 0)continue;n+=',"'+f+'":'+r}return n}function Of(t){return t.write!==t.constructor.prototype.write}function Gt(t){let e=new mn(t);return e.on("error",r),!t.sync&&vf&&(Wi.register(e,Rf),e.on("close",function(){Wi.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Ye,e.end=Ye,e.flushSync=Ye,e.destroy=Ye;return}e.removeListener("error",r),e.emit("error",n)}}function Rf(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function If(t){return function(r,n,s={},i){if(typeof s=="string")i=Gt({dest:s}),s={};else if(typeof i=="string"){if(s&&s.transport)throw Error("only one of option.transport or stream can be specified");i=Gt({dest:i})}else if(s instanceof mn||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof mn||s.transport.writable||s.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(s.transport.targets&&s.transport.targets.length&&s.formatters&&typeof s.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;s.customLevels&&(l=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=kf({caller:n,...s.transport,levels:l})}if(s=Object.assign({},t,s),s.serializers=Object.assign({},t.serializers,s.serializers),s.formatters=Object.assign({},t.formatters,s.formatters),s.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=s;return o===!1&&(s.level="silent"),a||(s.onChild=Ye),i||(Of(process.stdout)?i=process.stdout:i=Gt({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function Mf(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[gn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Pf(t,e,r){return{level:t,bindings:e,log:r}}function Lf(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}to.exports={noop:Ye,buildSafeSonicBoom:Gt,asChindings:Ef,asJson:Af,genLog:Tf,createArgsNormalizer:If,stringify:Mf,buildFormatters:Pf,normalizeDestFileDescriptor:Lf}});var Yt=I((Cg,ro)=>{var jf={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Df={ASC:"ASC",DESC:"DESC"};ro.exports={DEFAULT_LEVELS:jf,SORTING_ORDER:Df}});var bn=I((Ag,oo)=>{"use strict";var{lsCacheSym:Ff,levelValSym:yn,useOnlyCustomLevelsSym:Nf,streamSym:Uf,formattersSym:qf,hooksSym:Bf,levelCompSym:no}=Ge(),{noop:Hf,genLog:Ie}=Jt(),{DEFAULT_LEVELS:fe,SORTING_ORDER:so}=Yt(),io={fatal:t=>{let e=Ie(fe.fatal,t);return function(...r){let n=this[Uf];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>Ie(fe.error,t),warn:t=>Ie(fe.warn,t),info:t=>Ie(fe.info,t),debug:t=>Ie(fe.debug,t),trace:t=>Ie(fe.trace,t)},wn=Object.keys(fe).reduce((t,e)=>(t[fe[e]]=e,t),{}),Wf=Object.keys(wn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Vf(t){let e=t[qf].level,{labels:r}=t.levels,n={};for(let s in r){let i=e(r[s],Number(s));n[s]=JSON.stringify(i).slice(0,-1)}return t[Ff]=n,t}function zf(t,e){if(e)return!1;switch(t){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function Kf(t){let{labels:e,values:r}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(r[t]===void 0)throw Error("unknown level "+t);let n=this[yn],s=this[yn]=r[t],i=this[Nf],o=this[no],a=this[Bf].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=Hf;continue}this[l]=zf(l,i)?io[l](a):Ie(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function Gf(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Jf(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[no](r,this[yn])}function Yf(t,e,r){return t===so.DESC?e<=r:e>=r}function Xf(t){return typeof t=="string"?Yf.bind(null,t):t}function Zf(t=null,e=!1){let r=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:wn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:fe,t);return{labels:n,values:s}}function Qf(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(wn).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:fe,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function ed(t,e){let{labels:r,values:n}=t;for(let s in e){if(s in n)throw Error("levels cannot be overridden");if(e[s]in r)throw Error("pre-existing level values cannot be used for new levels")}}function td(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(so).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}oo.exports={initialLsCache:Wf,genLsCache:Vf,levelMethods:io,getLevel:Gf,setLevel:Kf,isLevelEnabled:Jf,mappings:Zf,assertNoLevelCollisions:ed,assertDefaultLevelFound:Qf,genLevelComparison:Xf,assertLevelComparison:td}});var Sn=I((Eg,ao)=>{"use strict";ao.exports={version:"10.3.1"}});var go=I((Rg,mo)=>{"use strict";var{EventEmitter:rd}=require("node:events"),{lsCacheSym:nd,levelValSym:sd,setLevelSym:_n,getLevelSym:lo,chindingsSym:Zt,mixinSym:id,asJsonSym:uo,writeSym:od,mixinMergeStrategySym:ad,timeSym:ld,timeSliceIndexSym:cd,streamSym:fo,serializersSym:Me,formattersSym:gt,errorKeySym:ud,messageKeySym:fd,useOnlyCustomLevelsSym:dd,needsMetadataGsym:pd,redactFmtSym:hd,stringifySym:md,formatOptsSym:gd,stringifiersSym:yd,msgPrefixSym:vn,hooksSym:wd}=Ge(),{getLevel:bd,setLevel:Sd,isLevelEnabled:xd,mappings:_d,initialLsCache:vd,genLsCache:kd,assertNoLevelCollisions:$d}=bn(),{asChindings:kn,asJson:Td,buildFormatters:xn,stringify:co,noop:po}=Jt(),{version:Cd}=Sn(),Ad=Zr(),Ed=class{},ho={constructor:Ed,child:Od,bindings:Rd,setBindings:Id,flush:Ld,isLevelEnabled:xd,version:Cd,get level(){return this[lo]()},set level(t){this[_n](t)},get levelVal(){return this[sd]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[vn]},get[Symbol.toStringTag](){return"Pino"},[nd]:vd,[od]:Pd,[uo]:Td,[lo]:bd,[_n]:Sd};Object.setPrototypeOf(ho,rd.prototype);mo.exports=function(){return Object.create(ho)};var Xt=t=>t;function Od(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[Me],n=this[gt],s=Object.create(this);if(e==null)return s[gt].bindings!==Xt&&(s[gt]=xn(n.level,Xt,n.log)),s[Zt]=kn(s,t),this.onChild!==po&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[Me]=Object.create(null);for(let c in r)s[Me][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];s[Me][c]=r[c]}for(let c in e.serializers)s[Me][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];s[Me][c]=e.serializers[c]}}else s[Me]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;s[gt]=xn(a||n.level,l||Xt,c||n.log)}else s[gt]=xn(n.level,Xt,n.log);if(e.hasOwnProperty("customLevels")===!0&&($d(this.levels,e.customLevels),s.levels=_d(e.customLevels,s[dd]),kd(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=Ad(s.redact,co),l={stringify:a[hd]};s[md]=co,s[yd]=a,s[gd]=l}if(typeof e.msgPrefix=="string"&&(s[vn]=(this[vn]||"")+e.msgPrefix),s[Zt]=kn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[_n](a)}return this.onChild(s),s}function Rd(){let e=`{${this[Zt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Id(t){let e=kn(this,t);this[Zt]=e}function Md(t,e){return Object.assign(e,t)}function Pd(t,e,r){let n=this[ld](),s=this[id],i=this[ud],o=this[fd],a=this[ad]||Md,l,c=this[wd].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(l=a(l,s(l,r,this)));let f=this[uo](l,e,r,n),d=this[fo];d[pd]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[cd]),d.lastLogger=this),d.write(c?c(f):f)}function Ld(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[fo];typeof e.flush=="function"?e.flush(t||po):t&&t()}});var So=I((An,bo)=>{"use strict";var{hasOwnProperty:yt}=Object.prototype,Le=Cn();Le.configure=Cn;Le.stringify=Le;Le.default=Le;An.stringify=Le;An.configure=Cn;bo.exports=Le;var jd=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function xe(t){return t.length<5e3&&!jd.test(t)?`"${t}"`:JSON.stringify(t)}function $n(t,e){if(t.length>200||e)return t.sort(e);for(let r=1;r<t.length;r++){let n=t[r],s=r;for(;s!==0&&t[s-1]>n;)t[s]=t[s-1],s--;t[s]=n}return t}var Dd=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Tn(t){return Dd.call(t)!==void 0&&t.length!==0}function yo(t,e,r){t.length<r&&(r=t.length);let n=e===","?"":" ",s=`"0":${n}${t[0]}`;for(let i=1;i<r;i++)s+=`${e}"${i}":${n}${t[i]}`;return s}function Fd(t){if(yt.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function Nd(t){let e;if(yt.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function Ud(t,e){let r;if(yt.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function wo(t,e){let r;if(yt.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function Pe(t){return t===1?"1 item":`${t} items`}function qd(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function Bd(t){if(yt.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function Cn(t){t={...t};let e=Bd(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Fd(t),n=Ud(t,"bigint"),s=Nd(t),i=typeof s=="function"?s:void 0,o=wo(t,"maximumDepth"),a=wo(t,"maximumBreadth");function l(p,u,m,g,x,b){let S=u[p];switch(typeof S=="object"&&S!==null&&typeof S.toJSON=="function"&&(S=S.toJSON(p)),S=g.call(u,p,S),typeof S){case"string":return xe(S);case"object":{if(S===null)return"null";if(m.indexOf(S)!==-1)return r;let _="",v=",",$=b;if(Array.isArray(S)){if(S.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(S),x!==""&&(b+=x,_+=`
|
|
26
|
-
${b}`,
|
|
27
|
-
${b}`);let D=Math.min(
|
|
28
|
-
${$}`),m.pop(),`[${
|
|
29
|
-
${b}`,T=" ");let
|
|
30
|
-
${b}${
|
|
31
|
-
${$}`),m.pop(),`{${
|
|
32
|
-
${b}`,
|
|
33
|
-
${b}`);let E=Math.min(u.length,a),T=0;for(;T<E-1;T++){let
|
|
34
|
-
${
|
|
35
|
-
${b}`,$=" ");let C="";for(let E of g){let T=c(E,u[E],m,g,
|
|
36
|
-
${b}${
|
|
37
|
-
${
|
|
38
|
-
${
|
|
39
|
-
${
|
|
40
|
-
${b}`,m.pop(),`[${T}]`}let
|
|
41
|
-
${
|
|
42
|
-
${
|
|
43
|
-
${b}`),m.pop(),`{${$}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(
|
|
20
|
+
`),this.outputHelp({error:!0}));let r=n||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in q.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,q.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Jl(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let r=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(d=>d.negate&&a===d.attributeName()),f=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:f||o},s=o=>{let a=r(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(n)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";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);n=ys(e,s)}let r=`error: unknown option '${e}'${n}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,r=n===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),n=ys(e,s)}let r=`error: unknown command '${e}'${n}`;this.error(r,{code:"commander.unknownCommand"})}version(e,n,r){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",r=r||"output the version number";let s=this.createOption(n,r);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,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>Kl(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=he.basename(e,he.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp();return n.helpWidth===void 0&&(n.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),n.formatHelp(this,n)}_getHelpContext(e){e=e||{};let n={error:!!e.error},r;return n.error?r=s=>this._outputConfiguration.writeErr(s):r=s=>this._outputConfiguration.writeOut(s),n.write=e.write||r,n.command=this,n}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation(r);if(n&&(s=n(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",r))}helpOption(e,n){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(e,n),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 n=q.exitCode||0;n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${r.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof n=="function"?o=n({error:i.error,command:i.command}):o=n,o&&i.write(`${o}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ws(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],s=i[4]),n&&s!=="0"?`${n}=${r}:${parseInt(s)+1}`:e})}bs.Command=Fn});var ks=I(ee=>{var{Argument:Ss}=jt(),{Command:Nn}=xs(),{CommanderError:Yl,InvalidArgumentError:vs}=ht(),{Help:Xl}=On(),{Option:_s}=Mn();ee.program=new Nn;ee.createCommand=t=>new Nn(t);ee.createOption=(t,e)=>new _s(t,e);ee.createArgument=(t,e)=>new Ss(t,e);ee.Command=Nn;ee.Option=_s;ee.Argument=Ss;ee.Help=Xl;ee.CommanderError=Yl;ee.InvalidArgumentError=vs;ee.InvalidOptionArgumentError=vs});var Bn=I((hg,Rs)=>{"use strict";var mt=t=>t&&typeof t.message=="string",qn=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let n=t.cause();return mt(n)?n:void 0}else return mt(e)?e:void 0},Es=(t,e)=>{if(!mt(t))return"";let n=t.stack||"";if(e.has(t))return n+`
|
|
24
|
+
causes have become circular...`;let r=qn(t);return r?(e.add(t),n+`
|
|
25
|
+
caused by: `+Es(r,e)):n},Zl=t=>Es(t,new Set),Os=(t,e,n)=>{if(!mt(t))return"";let r=n?"":t.message||"";if(e.has(t))return r+": ...";let s=qn(t);if(s){e.add(t);let i=typeof t.cause=="function";return r+(i?"":": ")+Os(s,e,i)}else return r},Ql=t=>Os(t,new Set);Rs.exports={isErrorLike:mt,getErrorCause:qn,stackWithCauses:Zl,messageWithCauses:Ql}});var Hn=I((mg,Ps)=>{"use strict";var ec=Symbol("circular-ref-tag"),Lt=Symbol("pino-raw-err-ref"),Is=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[Lt]},set:function(t){this[Lt]=t}}});Object.defineProperty(Is,Lt,{writable:!0,value:{}});Ps.exports={pinoErrProto:Is,pinoErrorSymbols:{seen:ec,rawSymbol:Lt}}});var Ls=I((gg,js)=>{"use strict";js.exports=Vn;var{messageWithCauses:tc,stackWithCauses:nc,isErrorLike:Ms}=Bn(),{pinoErrProto:rc,pinoErrorSymbols:sc}=Hn(),{seen:Wn}=sc,{toString:ic}=Object.prototype;function Vn(t){if(!Ms(t))return t;t[Wn]=void 0;let e=Object.create(rc);e.type=ic.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=tc(t),e.stack=nc(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(n=>Vn(n)));for(let n in t)if(e[n]===void 0){let r=t[n];Ms(r)?n!=="cause"&&!Object.prototype.hasOwnProperty.call(r,Wn)&&(e[n]=Vn(r)):e[n]=r}return delete t[Wn],e.raw=t,e}});var Fs=I((yg,Ds)=>{"use strict";Ds.exports=Ft;var{isErrorLike:zn}=Bn(),{pinoErrProto:oc,pinoErrorSymbols:ac}=Hn(),{seen:Dt}=ac,{toString:lc}=Object.prototype;function Ft(t){if(!zn(t))return t;t[Dt]=void 0;let e=Object.create(oc);e.type=lc.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(n=>Ft(n))),zn(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,Dt)&&(e.cause=Ft(t.cause));for(let n in t)if(e[n]===void 0){let r=t[n];zn(r)?Object.prototype.hasOwnProperty.call(r,Dt)||(e[n]=Ft(r)):e[n]=r}return delete t[Dt],e.raw=t,e}});var Bs=I((wg,qs)=>{"use strict";qs.exports={mapHttpRequest:cc,reqSerializer:Us};var Kn=Symbol("pino-raw-req-ref"),Ns=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[Kn]},set:function(t){this[Kn]=t}}});Object.defineProperty(Ns,Kn,{writable:!0,value:{}});function Us(t){let e=t.info||t.socket,n=Object.create(Ns);if(n.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),n.method=t.method,t.originalUrl)n.url=t.originalUrl;else{let r=t.path;n.url=typeof r=="string"?r:t.url?t.url.path||t.url:void 0}return t.query&&(n.query=t.query),t.params&&(n.params=t.params),n.headers=t.headers,n.remoteAddress=e&&e.remoteAddress,n.remotePort=e&&e.remotePort,n.raw=t.raw||t,n}function cc(t){return{req:Us(t)}}});var zs=I((bg,Vs)=>{"use strict";Vs.exports={mapHttpResponse:uc,resSerializer:Ws};var Gn=Symbol("pino-raw-res-ref"),Hs=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Gn]},set:function(t){this[Gn]=t}}});Object.defineProperty(Hs,Gn,{writable:!0,value:{}});function Ws(t){let e=Object.create(Hs);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function uc(t){return{res:Ws(t)}}});var Yn=I((xg,Ks)=>{"use strict";var Jn=Ls(),fc=Fs(),Nt=Bs(),Ut=zs();Ks.exports={err:Jn,errWithCause:fc,mapHttpRequest:Nt.mapHttpRequest,mapHttpResponse:Ut.mapHttpResponse,req:Nt.reqSerializer,res:Ut.resSerializer,wrapErrorSerializer:function(e){return e===Jn?e:function(r){return e(Jn(r))}},wrapRequestSerializer:function(e){return e===Nt.reqSerializer?e:function(r){return e(Nt.reqSerializer(r))}},wrapResponseSerializer:function(e){return e===Ut.resSerializer?e:function(r){return e(Ut.resSerializer(r))}}}});var Xn=I((Sg,Gs)=>{"use strict";function dc(t,e){return e}Gs.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=dc;let n=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(n))return;let r=n.slice(2),s=[];for(let i of r)i&&s.push(i.getFileName());return s}});var ei=I((vg,Qs)=>{"use strict";function Zn(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 n=0;n<t.length;n++)e[n]=Zn(t[n]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=Zn(t[n]));return e}return t}function Js(t){let e=[],n="",r=!1,s=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!r&&a==="."?n&&(e.push(n),n=""):a==="["?(n&&(e.push(n),n=""),r=!0):a==="]"&&r?(e.push(n),n="",r=!1,s=!1):(a==='"'||a==="'")&&r?s?a===i?(s=!1,i=""):n+=a:(s=!0,i=a):n+=a}return n&&e.push(n),e}function Ys(t,e,n){let r=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof r!="object"||r===null||!(o in r)||typeof r[o]!="object"||r[o]===null)return!1;r=r[o]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(r))for(let i=0;i<r.length;i++)r[i]=n;else if(typeof r=="object"&&r!==null)for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n)}else typeof r=="object"&&r!==null&&s in r&&Object.prototype.hasOwnProperty.call(r,s)&&(r[s]=n);return!0}function Xs(t,e){let n=t;for(let s=0;s<e.length-1;s++){let i=e[s];if(typeof n!="object"||n===null||!(i in n)||typeof n[i]!="object"||n[i]===null)return!1;n=n[i]}let r=e[e.length-1];if(r==="*"){if(Array.isArray(n))for(let s=0;s<n.length;s++)n[s]=void 0;else if(typeof n=="object"&&n!==null)for(let s in n)Object.prototype.hasOwnProperty.call(n,s)&&delete n[s]}else typeof n=="object"&&n!==null&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}var qt=Symbol("PATH_NOT_FOUND");function pc(t,e){let n=t;for(let r of e){if(n==null||typeof n!="object"||n===null||!(r in n))return qt;n=n[r]}return n}function hc(t,e){let n=t;for(let r of e){if(n==null||typeof n!="object"||n===null)return;n=n[r]}return n}function mc(t,e,n,r=!1){for(let s of e){let i=Js(s);if(i.includes("*"))Zs(t,i,n,s,r);else if(r)Xs(t,i);else{let o=pc(t,i);if(o===qt)continue;let a=typeof n=="function"?n(o,i):n;Ys(t,i,a)}}}function Zs(t,e,n,r,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(s)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let c=[...o,l.toString()],f=typeof n=="function"?n(a[l],c):n;a[l]=f}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],f=typeof n=="function"?n(a[l],c):n;a[l]=f}}else gc(t,e,n,i,r,s)}function gc(t,e,n,r,s,i=!1){let o=e.slice(0,r),a=e.slice(r+1),l=[];function c(f,d){if(d===o.length){if(Array.isArray(f))for(let h=0;h<f.length;h++)l[d]=h.toString(),c(f[h],d+1);else if(typeof f=="object"&&f!==null)for(let h in f)l[d]=h,c(f[h],d+1)}else if(d<o.length){let h=o[d];f&&typeof f=="object"&&f!==null&&h in f&&(l[d]=h,c(f[h],d+1))}else if(a.includes("*"))Zs(f,a,typeof n=="function"?(p,u)=>{let m=[...l.slice(0,d),...u];return n(p,m)}:n,s,i);else if(i)Xs(f,a);else{let h=typeof n=="function"?n(hc(f,a),[...l.slice(0,d),...a]):n;Ys(f,a,h)}}if(o.length===0)c(t,0);else{let f=t;for(let d=0;d<o.length;d++){let h=o[d];if(f==null||typeof f!="object"||f===null)return;f=f[h],l[d]=h}f!=null&&c(f,o.length)}}function yc(t){if(t.length===0)return null;let e=new Map;for(let n of t){let r=Js(n),s=e;for(let i=0;i<r.length;i++){let o=r[i];s.has(o)||s.set(o,new Map),s=s.get(o)}}return e}function wc(t,e){if(!e)return t;function n(r,s,i=0){if(!s||s.size===0||r===null||typeof r!="object")return r;if(r instanceof Date)return new Date(r.getTime());if(Array.isArray(r)){let a=[];for(let l=0;l<r.length;l++){let c=l.toString();s.has(c)||s.has("*")?a[l]=n(r[l],s.get(c)||s.get("*")):a[l]=r[l]}return a}let o=Object.create(Object.getPrototypeOf(r));for(let a in r)Object.prototype.hasOwnProperty.call(r,a)&&(s.has(a)||s.has("*")?o[a]=n(r[a],s.get(a)||s.get("*")):o[a]=r[a]);return o}return n(t,e)}function bc(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,n=!1,r="";for(let s=0;s<t.length;s++){let i=t[s];if((i==='"'||i==="'")&&e>0)n?i===r&&(n=!1,r=""):(n=!0,r=i);else if(i==="["&&!n)e++;else if(i==="]"&&!n&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function xc(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)bc(e)}function Sc(t={}){let{paths:e=[],censor:n="[REDACTED]",serialize:r=JSON.stringify,strict:s=!0,remove:i=!1}=t;xc(e);let o=yc(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return r?r(l):l;let c=wc(l,o),f=l,d=n;return typeof n=="function"&&(d=n),mc(c,e,d,i),r===!1?(c.restore=function(){return Zn(f)},c):typeof r=="function"?r(c):JSON.stringify(c)}}Qs.exports=Sc});var Je=I((_g,ti)=>{"use strict";var vc=Symbol("pino.setLevel"),_c=Symbol("pino.getLevel"),kc=Symbol("pino.levelVal"),$c=Symbol("pino.levelComp"),Tc=Symbol("pino.useLevelLabels"),Cc=Symbol("pino.useOnlyCustomLevels"),Ac=Symbol("pino.mixin"),Ec=Symbol("pino.lsCache"),Oc=Symbol("pino.chindings"),Rc=Symbol("pino.asJson"),Ic=Symbol("pino.write"),Pc=Symbol("pino.redactFmt"),Mc=Symbol("pino.time"),jc=Symbol("pino.timeSliceIndex"),Lc=Symbol("pino.stream"),Dc=Symbol("pino.stringify"),Fc=Symbol("pino.stringifySafe"),Nc=Symbol("pino.stringifiers"),Uc=Symbol("pino.end"),qc=Symbol("pino.formatOpts"),Bc=Symbol("pino.messageKey"),Hc=Symbol("pino.errorKey"),Wc=Symbol("pino.nestedKey"),Vc=Symbol("pino.nestedKeyStr"),zc=Symbol("pino.mixinMergeStrategy"),Kc=Symbol("pino.msgPrefix"),Gc=Symbol("pino.wildcardFirst"),Jc=Symbol.for("pino.serializers"),Yc=Symbol.for("pino.formatters"),Xc=Symbol.for("pino.hooks"),Zc=Symbol.for("pino.metadata");ti.exports={setLevelSym:vc,getLevelSym:_c,levelValSym:kc,levelCompSym:$c,useLevelLabelsSym:Tc,mixinSym:Ac,lsCacheSym:Ec,chindingsSym:Oc,asJsonSym:Rc,writeSym:Ic,serializersSym:Jc,redactFmtSym:Pc,timeSym:Mc,timeSliceIndexSym:jc,streamSym:Lc,stringifySym:Dc,stringifySafeSym:Fc,stringifiersSym:Nc,endSym:Uc,formatOptsSym:qc,messageKeySym:Bc,errorKeySym:Hc,nestedKeySym:Wc,wildcardFirstSym:Gc,needsMetadataGsym:Zc,useOnlyCustomLevelsSym:Cc,formattersSym:Yc,hooksSym:Xc,nestedKeyStrSym:Vc,mixinMergeStrategySym:zc,msgPrefixSym:Kc}});var er=I((kg,ii)=>{"use strict";var ni=ei(),{redactFmtSym:Qc,wildcardFirstSym:Bt}=Je(),Qn=/[^.[\]]+|\[([^[\]]*?)\]/g,ri="[Redacted]",si=!1;function eu(t,e){let{paths:n,censor:r,remove:s}=tu(t),i=n.reduce((l,c)=>{Qn.lastIndex=0;let f=Qn.exec(c),d=Qn.exec(c),h=f[1]!==void 0?f[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):f[0];if(h==="*"&&(h=Bt),d===null)return l[h]=null,l;if(l[h]===null)return l;let{index:p}=d,u=`${c.substr(p,c.length-1)}`;return l[h]=l[h]||[],h!==Bt&&l[h].length===0&&l[h].push(...l[Bt]||[]),h===Bt&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(u)}),l[h].push(u),l},{}),o={[Qc]:ni({paths:n,censor:r,serialize:e,strict:si,remove:s})},a=(...l)=>e(typeof r=="function"?r(...l):r);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=f=>a(f,[c]);else{let f=typeof r=="function"?(d,h)=>r(d,[c,...h]):r;l[c]=ni({paths:i[c],censor:f,serialize:e,strict:si,remove:s})}return l},o)}function tu(t){if(Array.isArray(t))return t={paths:t,censor:ri},t;let{paths:e,censor:n=ri,remove:r}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return r===!0&&(n=void 0),{paths:e,censor:n,remove:r}}ii.exports=eu});var li=I(($g,ai)=>{"use strict";var nu=()=>"",ru=()=>`,"time":${Date.now()}`,su=()=>`,"time":${Math.round(Date.now()/1e3)}`,iu=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,ou=1000000n,oi=1000000000n,au=BigInt(Date.now())*ou,lu=process.hrtime.bigint(),cu=()=>{let t=process.hrtime.bigint()-lu,e=au+t,n=e/oi,r=e%oi,s=Number(n*1000n+r/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),f=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${f}:${d}.${r.toString().padStart(9,"0")}Z"`};ai.exports={nullTime:nu,epochTime:ru,unixTime:su,isoTime:iu,isoTimeNano:cu}});var ui=I((Tg,ci)=>{"use strict";function uu(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}ci.exports=fu;function fu(t,e,n){var r=n&&n.stringify||uu,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]=r(t);for(var a=1;a<i;a++)o[a]=r(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var c="",f=1-s,d=-1,h=t&&t.length||0,p=0;p<h;){if(t.charCodeAt(p)===37&&p+1<h){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(f>=l||e[f]==null)break;d<p&&(c+=t.slice(d,p)),c+=Number(e[f]),d=p+2,p++;break;case 105:if(f>=l||e[f]==null)break;d<p&&(c+=t.slice(d,p)),c+=Math.floor(Number(e[f])),d=p+2,p++;break;case 79:case 111:case 106:if(f>=l||e[f]===void 0)break;d<p&&(c+=t.slice(d,p));var u=typeof e[f];if(u==="string"){c+="'"+e[f]+"'",d=p+2,p++;break}if(u==="function"){c+=e[f].name||"<anonymous>",d=p+2,p++;break}c+=r(e[f]),d=p+2,p++;break;case 115:if(f>=l)break;d<p&&(c+=t.slice(d,p)),c+=String(e[f]),d=p+2,p++;break;case 37:d<p&&(c+=t.slice(d,p)),c+="%",d=p+2,p++,f--;break}++f}++p}return d===-1?t:(d<h&&(c+=t.slice(d)),c)}});var nr=I((Cg,tr)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(n){if((n>0&&n<1/0)===!1)throw typeof n!="number"&&typeof n!="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(n))},t=new Int32Array(new SharedArrayBuffer(4));tr.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 r=Date.now()+Number(e);for(;r>Date.now(););};tr.exports=t}});var wi=I((Ag,yi)=>{"use strict";var N=require("fs"),du=require("events"),pu=require("util").inherits,fi=require("path"),sr=nr(),hu=require("assert"),Ht=100,Wt=Buffer.allocUnsafe(0),mu=16*1024,di="buffer",pi="utf8",[gu,yu]=(process.versions.node||"0.0").split(".").map(Number),wu=gu>=22&&yu>=7;function hi(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function n(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 r=e.append?"a":"w",s=e.mode;if(e.sync)try{e.mkdir&&N.mkdirSync(fi.dirname(t),{recursive:!0});let i=N.openSync(t,r,s);n(null,i)}catch(i){throw n(i),i}else e.mkdir?N.mkdir(fi.dirname(t),{recursive:!0},i=>{if(i)return n(i);N.open(t,r,s,n)}):N.open(t,r,s,n)}function le(t){if(!(this instanceof le))return new le(t);let{fd:e,dest:n,minLength:r,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:f,fsync:d,contentMode:h,mode:p}=t||{};e=e||n,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(r||0,16387),this.file=null,this.destroyed=!1,this.minLength=r||0,this.maxLength=s||0,this.maxWrite=i||mu,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=p,this.retryEAGAIN=f||(()=>!0),this.mkdir=c||!1;let u,m;if(h===di)this._writingBuf=Wt,this.write=Su,this.flush=_u,this.flushSync=$u,this._actualWrite=Cu,u=()=>N.writeSync(this.fd,this._writingBuf),m=()=>N.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===pi)this._writingBuf="",this.write=xu,this.flush=vu,this.flushSync=ku,this._actualWrite=Tu,u=()=>Buffer.isBuffer(this._writingBuf)?N.writeSync(this.fd,this._writingBuf):N.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?N.write(this.fd,this._writingBuf,this.release):N.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${pi}" and "${di}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")hi(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(g,S)=>{if(g){if((g.code==="EAGAIN"||g.code==="EBUSY")&&this.retryEAGAIN(g,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{sr(Ht),this.release(void 0,0)}catch(v){this.release(v)}else setTimeout(m,Ht);else this._writing=!1,this.emit("error",g);return}this.emit("write",S);let b=rr(this._writingBuf,this._len,S);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let v=u(),_=rr(this._writingBuf,this._len,v);this._len=_.len,this._writingBuf=_.writingBuf}while(this._writingBuf.length)}catch(v){this.release(v);return}}this._fsync&&N.fsyncSync(this.fd);let x=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):x>this.minLength?this._actualWrite():this._ending?x>0?this._actualWrite():(this._writing=!1,Vt(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(bu,this)):this.emit("drain"))},this.on("newListener",function(g){g==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function rr(t,e,n){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-n,0),t=t.subarray(n),{writingBuf:t,len:e}}function bu(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}pu(le,du);function mi(t,e){return t.length===0?Wt:t.length===1?t[0]:Buffer.concat(t,e)}function xu(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),n=this._len+e,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+e>this.maxWrite?r.push(t):r[r.length-1]+=t,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Su(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,n=this._bufs,r=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(n.length===0||r[r.length-1]+t.length>this.maxWrite?(n.push([t]),r.push(t.length)):(n[n.length-1].push(t),r[r.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function gi(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{N.fsync(this.fd,r=>{this._flushPending=!1,t(r)})}catch(r){t(r)}this.off("error",n)},n=r=>{this._flushPending=!1,t(r),this.off("drain",e)};this.once("drain",e),this.once("error",n)}function vu(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&&gi.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function _u(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&gi.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}le.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&N.close(e,n=>{if(n)return this.emit("error",n)})}),hi(this.file,this)};le.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():Vt(this)))};function ku(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?N.writeSync(this.fd,t):N.writeSync(this.fd,t,"utf8"),n=rr(t,this._len,e);t=n.writingBuf,this._len=n.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;sr(Ht)}}try{N.fsyncSync(this.fd)}catch{}}function $u(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=Wt);let t=Wt;for(;this._bufs.length||t.length;){t.length<=0&&(t=mi(this._bufs[0],this._lens[0]));try{let e=N.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;sr(Ht)}}}le.prototype.destroy=function(){this.destroyed||Vt(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)?N.writeSync(this.fd,this._writingBuf):N.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else N.write(this.fd,this._writingBuf,t)}function Cu(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:mi(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=N.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else wu&&(this._writingBuf=Buffer.from(this._writingBuf)),N.write(this.fd,this._writingBuf,t)}function Vt(t){if(t.fd===-1){t.once("ready",Vt.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],hu(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{N.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?N.close(t.fd,n):n()}function n(r){if(r){t.emit("error",r);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}le.SonicBoom=le;le.default=le;yi.exports=le});var ir=I((Eg,_i)=>{"use strict";var ce={exit:[],beforeExit:[]},bi={exit:Ou,beforeExit:Ru},Ye;function Au(){Ye===void 0&&(Ye=new FinalizationRegistry(Iu))}function Eu(t){ce[t].length>0||process.on(t,bi[t])}function xi(t){ce[t].length>0||(process.removeListener(t,bi[t]),ce.exit.length===0&&ce.beforeExit.length===0&&(Ye=void 0))}function Ou(){Si("exit")}function Ru(){Si("beforeExit")}function Si(t){for(let e of ce[t]){let n=e.deref(),r=e.fn;n!==void 0&&r(n,t)}ce[t]=[]}function Iu(t){for(let e of["exit","beforeExit"]){let n=ce[e].indexOf(t);ce[e].splice(n,n+1),xi(e)}}function vi(t,e,n){if(e===void 0)throw new Error("the object can't be undefined");Eu(t);let r=new WeakRef(e);r.fn=n,Au(),Ye.register(e,r),ce[t].push(r)}function Pu(t,e){vi("exit",t,e)}function Mu(t,e){vi("beforeExit",t,e)}function ju(t){if(Ye!==void 0){Ye.unregister(t);for(let e of["exit","beforeExit"])ce[e]=ce[e].filter(n=>{let r=n.deref();return r&&r!==t}),xi(e)}}_i.exports={register:Pu,registerBeforeExit:Mu,unregister:ju}});var ki=I((Og,Lu)=>{Lu.exports={name:"thread-stream",version:"4.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",engines:{node:">=20"},dependencies:{"real-require":"^1.0.0"},devDependencies:{"@types/node":"^25.0.2","@yao-pkg/pkg":"^6.0.0",borp:"^1.0.0",desm:"^1.3.0",eslint:"^9.39.1",fastbench:"^1.0.1",neostandard:"^0.13.0","pino-elasticsearch":"^9.0.0","sonic-boom":"^5.0.0","ts-node":"^10.8.0",typescript:"~5.7.3"},scripts:{build:"tsc --noEmit",lint:"eslint",test:'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:ci":'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:yarn":'npm run transpile && borp --pattern "test/*.test.js"',transpile:"sh ./test/ts/transpile.sh"},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina <hello@matteocollina.com>",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var Ti=I((Rg,$i)=>{"use strict";function Du(t,e,n,r,s){let i=r===1/0?1/0:Date.now()+r,o=()=>{let a=Atomics.load(t,e);if(a===n){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,a,l);c.async?c.value.then(o):setImmediate(o)};o()}function Fu(t,e,n,r,s){let i=r===1/0?1/0:Date.now()+r,o=()=>{if(Atomics.load(t,e)!==n){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,n,l);c.async?c.value.then(f=>{if(f==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}$i.exports={wait:Du,waitDiff:Fu}});var Ai=I((Ig,Ci)=>{"use strict";Ci.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Ui=I((Pg,Ni)=>{"use strict";var{version:Nu}=ki(),{EventEmitter:Uu}=require("events"),{Worker:qu}=require("worker_threads"),{join:Bu}=require("path"),{pathToFileURL:Hu}=require("url"),{wait:Wu}=Ti(),{WRITE_INDEX:me,READ_INDEX:Ie,SEQ_INDEX:or}=Ai(),Vu=require("buffer"),zu=require("assert"),y=Symbol("kImpl"),Ku=Vu.constants.MAX_STRING_LENGTH;function Ei(){}function ur(t,e){Atomics.add(t[y].state,or,1),e(),Atomics.add(t[y].state,or,1),Atomics.notify(t[y].state,or)}function Oi(t){ur(t,()=>{Atomics.store(t[y].state,Ie,0),Atomics.store(t[y].state,me,0)})}var gt=class{constructor(e){this._value=e}deref(){return this._value}},zt=class{register(){}unregister(){}},Gu=process.env.NODE_V8_COVERAGE?zt:global.FinalizationRegistry||zt,Ju=process.env.NODE_V8_COVERAGE?gt:global.WeakRef||gt,Ri=new Gu(t=>{t.exited||t.terminate()});function Yu(t,e){let{filename:n,workerData:r}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Bu(__dirname,"lib","worker.js"),o=new qu(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:n.indexOf("file://")===0?n:Hu(n).href,dataBuf:t[y].dataBuf,stateBuf:t[y].stateBuf,workerData:{$context:{threadStreamVersion:Nu},...r}}});return o.stream=new gt(t),o.on("message",Xu),o.on("exit",Mi),Ri.register(t,o),o}function Ii(t){zu(!t[y].sync),t[y].needDrain&&(t[y].needDrain=!1,t.emit("drain"))}function Pi(t){for(;;){let e=Atomics.load(t[y].state,me),n=t[y].data.length-e;if(n>0){if(t[y].bufLen===0){t[y].flushing=!1,t[y].ending?fr(t):t[y].needDrain&&process.nextTick(Ii,t);return}Di(t,n,Ei);continue}if(n===0){if(e===0&&t[y].bufLen===0)return;Kt(t,()=>{t.destroyed||(Oi(t),Pi(t))});return}ne(t,new Error("overwritten"));return}}function Xu(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 Ju(e),Kt(e,()=>{e[y].ready=!0,e.emit("ready")});break;case"ERROR":ne(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"){ne(e,new Error("this should not happen: "+t.code));break}let n=e[y].flushCallbacks.get(t.id);n&&(e[y].flushCallbacks.delete(t.id),process.nextTick(n));break}case"WARNING":process.emitWarning(t.err);break;default:ne(e,new Error("this should not happen: "+t.code))}}function Mi(t){let e=this.stream.deref();e!==void 0&&(Ri.unregister(e),e.worker.exited=!0,e.worker.off("exit",Mi),ne(e,t!==0?new Error("the worker thread exited"):null))}var lr=class extends Uu{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[y]={},this[y].stateBuf=new SharedArrayBuffer(128),this[y].state=new Int32Array(this[y].stateBuf),this[y].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[y].data=Buffer.from(this[y].dataBuf),this[y].sync=e.sync||!1,this[y].ending=!1,this[y].ended=!1,this[y].needDrain=!1,this[y].destroyed=!1,this[y].flushing=!1,this[y].ready=!1,this[y].finished=!1,this[y].errored=null,this[y].closed=!1,this[y].buf=[],this[y].bufHead=0,this[y].bufLen=0,this[y].flushCallbacks=new Map,this[y].nextFlushId=0,this.worker=Yu(this,e),this.on("message",(n,r)=>{this.worker.postMessage(n,r)})}write(e){let n=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[y].destroyed)return cr(this,new Error("the worker has exited")),!1;if(this[y].ending)return cr(this,new Error("the worker is ending")),!1;if(this[y].flushing&&this[y].bufLen+n.length>=Ku)try{ar(this),this[y].flushing=!0}catch(r){return ne(this,r),!1}if(this[y].buf.push(n),this[y].bufLen+=n.length,this[y].sync)try{return ar(this),!0}catch(r){return ne(this,r),!1}return this[y].flushing||(this[y].flushing=!0,setImmediate(Pi,this)),this[y].needDrain=this[y].data.length-this[y].bufLen-Atomics.load(this[y].state,me)<=0,!this[y].needDrain}end(){this[y].destroyed||(this[y].ending=!0,fr(this))}flush(e){e=typeof e=="function"?e:Ei,ji(this,n=>{if(n){process.nextTick(e,n);return}Li(this,e)})}flushSync(){this[y].destroyed||(ar(this),Fi(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[y].ready}get destroyed(){return this[y].destroyed}get closed(){return this[y].closed}get writable(){return!this[y].destroyed&&!this[y].ending}get writableEnded(){return this[y].ending}get writableFinished(){return this[y].finished}get writableNeedDrain(){return this[y].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[y].errored}};function ji(t,e){if(t[y].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[y].sync&&(t[y].flushing||t[y].bufLen>0)){setImmediate(ji,t,e);return}Kt(t,e)}function Kt(t,e){let n=Atomics.load(t[y].state,me);Wu(t[y].state,Ie,n,1/0,(r,s)=>{if(r){ne(t,r),e(r);return}if(s!=="ok"){Kt(t,e);return}e()})}function Li(t,e){if(t[y].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[y].ready){let r=()=>{i(),Li(t,e)},s=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",r),t.off("close",s)};t.once("ready",r),t.once("close",s);return}let n=++t[y].nextFlushId;t[y].flushCallbacks.set(n,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:n})}catch(r){t[y].flushCallbacks.delete(n),ne(t,r),process.nextTick(e,r)}}function Zu(t,e){let n=t[y].flushCallbacks;if(n.size===0)return;let r=e||new Error("the worker has exited");for(let s of n.values())process.nextTick(s,r);n.clear()}function cr(t,e){setImmediate(()=>{t.emit("error",e)})}function ne(t,e){t[y].destroyed||(t[y].destroyed=!0,Zu(t,e),e&&(t[y].errored=e,cr(t,e)),t.worker.exited?setImmediate(()=>{t[y].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[y].closed=!0,t.emit("close")}))}function Di(t,e,n){let s=Atomics.load(t[y].state,me),i=e;for(;i>0&&t[y].bufLen!==0;){let o=t[y].bufHead,a=t[y].buf[o];if(a.length<=i){a.copy(t[y].data,s),s+=a.length,i-=a.length,t[y].bufLen-=a.length,t[y].bufHead=o+1,t[y].bufHead===t[y].buf.length?(t[y].buf.length=0,t[y].bufHead=0):t[y].bufHead>=1024&&t[y].bufHead*2>=t[y].buf.length&&(t[y].buf.splice(0,t[y].bufHead),t[y].bufHead=0);continue}a.copy(t[y].data,s,0,i),t[y].buf[o]=a.subarray(i),t[y].bufLen-=i,s+=i,i=0}return ur(t,()=>{Atomics.store(t[y].state,me,s)}),n(),!0}function fr(t){if(!(t[y].ended||!t[y].ending||t[y].flushing)){t[y].ended=!0;try{t.flushSync();let e=Atomics.load(t[y].state,Ie);ur(t,()=>{Atomics.store(t[y].state,me,-1)});let n=0;for(;e!==-1;){if(Atomics.wait(t[y].state,Ie,e,1e3),e=Atomics.load(t[y].state,Ie),e===-2){ne(t,new Error("end() failed"));return}if(++n===10){ne(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[y].finished=!0,t.emit("finish")})}catch(e){ne(t,e)}}}function ar(t){let e=()=>{t[y].ending?fr(t):t[y].needDrain&&process.nextTick(Ii,t)};for(t[y].flushing=!1;t[y].bufLen!==0;){let n=Atomics.load(t[y].state,me),r=t[y].data.length-n;if(r===0){Fi(t),Oi(t);continue}else if(r<0)throw new Error("overwritten");Di(t,r,e)}}function Fi(t){if(t[y].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[y].state,me),n=0;for(;;){let r=Atomics.load(t[y].state,Ie);if(r===-2)throw Error("_flushSync failed");if(r!==e)Atomics.wait(t[y].state,Ie,r,1e3);else break;if(++n===10)throw new Error("_flushSync took too long (10s)")}}Ni.exports=lr});var hr=I((Mg,Hi)=>{"use strict";var{createRequire:Qu}=require("module"),{existsSync:ef}=require("node:fs"),tf=Xn(),{join:dr,isAbsolute:Bi,sep:nf}=require("node:path"),{fileURLToPath:rf}=require("node:url"),sf=nr(),pr=ir(),of=Ui();function af(t){pr.register(t,df),pr.registerBeforeExit(t,pf),t.on("close",function(){pr.unregister(t)})}function lf(){let t=process.execArgv;for(let e=0;e<t.length;e++){let n=t[e];if(n==="--import"||n==="--require"||n==="-r"||n.startsWith("--import=")||n.startsWith("--require=")||n.startsWith("-r="))return!0}return!1}function cf(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let n=[],r=!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&&qi(o)){r=!0,s++;continue}n.push(i),o&&(n.push(o),s++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(qi(o)){r=!0;continue}}n.push(i)}return r?n.join(" "):t}function qi(t){let e=uf(t);if(!e)return!1;let n=e;if(n.startsWith("file://"))try{n=rf(n)}catch{return!1}return Bi(n)&&!ef(n)}function uf(t){let e=t[0],n=t[t.length-1];return e==='"'&&n==='"'||e==="'"&&n==="'"?t.slice(1,-1):t}function ff(t,e,n,r,s){if(!n.execArgv&&lf()&&require.main===void 0&&(n={...n,execArgv:[]}),!n.env&&process.env.NODE_OPTIONS){let l=cf(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(n={...n,env:{...process.env,NODE_OPTIONS:l}})}n={...n,name:s};let i=new of({filename:t,workerData:e,workerOpts:n,sync:r});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),n.autoEnd!==!1&&af(i)}function a(){i.closed||(i.flushSync(),sf(100),i.end())}return i}function df(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function pf(t){t.flushSync()}function hf(t){let{pipeline:e,targets:n,levels:r,dedupe:s,worker:i={},caller:o=tf(),sync:a=!1}=t,l={...t.options},c=typeof o=="string"?[o]:o,f=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&n)throw new Error("only one of target or targets can be specified");n?(d=f["pino-worker"]||dr(__dirname,"worker.js"),l.targets=n.filter(u=>u.target).map(u=>({...u,target:p(u.target)})),l.pipelines=n.filter(u=>u.pipeline).map(u=>u.pipeline.map(m=>({...m,level:u.level,target:p(m.target)})))):e&&(d=f["pino-worker"]||dr(__dirname,"worker.js"),l.pipelines=[e.map(u=>({...u,target:p(u.target)}))]),r&&(l.levels=r),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let h=n||e?"pino.transport":d;return ff(p(d),l,i,a,h);function p(u){if(u=f[u]||u,Bi(u)||u.indexOf("file://")===0)return u;if(u==="pino/file")return dr(__dirname,"..","file.js");let m;for(let g of c)try{let S=g==="node:repl"?process.cwd()+nf:g;m=Qu(S).resolve(u);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${u}"`);return m}}Hi.exports=hf});var Yt=I((jg,no)=>{"use strict";var mf=require("node:diagnostics_channel"),Wi=ui(),{mapHttpRequest:gf,mapHttpResponse:yf}=Yn(),gr=wi(),Vi=ir(),{lsCacheSym:wf,chindingsSym:Yi,writeSym:zi,serializersSym:Xi,formatOptsSym:Ki,endSym:bf,stringifiersSym:Zi,stringifySym:Qi,stringifySafeSym:yr,wildcardFirstSym:eo,nestedKeySym:xf,formattersSym:to,messageKeySym:Sf,errorKeySym:vf,nestedKeyStrSym:_f,msgPrefixSym:Gt}=Je(),{isMainThread:kf}=require("worker_threads"),$f=hr(),[Tf]=process.versions.node.split(".").map(t=>Number(t)),Gi=mf.tracingChannel("pino_asJson"),mr=Tf>=25?t=>JSON.stringify(t):Af;function Xe(){}function Cf(t,e){if(!e)return n;return function(...s){e.call(this,s,n,t)};function n(r,...s){if(typeof r=="object"){let i=r;r!==null&&(r.method&&r.headers&&r.socket?r=gf(r):typeof r.setHeader=="function"&&(r=yf(r)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Gt]=="string"&&i!==void 0&&i!==null&&(i=this[Gt]+i),this[zi](r,Wi(i,o,this[Ki]),t)}else{let i=r===void 0?s.shift():r;typeof this[Gt]=="string"&&i!==void 0&&i!==null&&(i=this[Gt]+i),this[zi](null,Wi(i,s,this[Ki]),t)}}}function Af(t){let e="",n=0,r=!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(n,o)+"\\",n=o,r=!0);return r?e+=t.slice(n):e=t,s<32?JSON.stringify(t):'"'+e+'"'}function Ef(t,e,n,r){if(Gi.hasSubscribers===!1)return Ji.call(this,t,e,n,r);let s={instance:this,arguments};return Gi.traceSync(Ji,s,this,t,e,n,r)}function Ji(t,e,n,r){let s=this[Qi],i=this[yr],o=this[Zi],a=this[bf],l=this[Yi],c=this[Xi],f=this[to],d=this[Sf],h=this[vf],p=this[wf][n]+r;p=p+l;let u;f.log&&(t=f.log(t));let m=o[eo],g="";for(let b in t)if(u=t[b],Object.prototype.hasOwnProperty.call(t,b)&&u!==void 0){c[b]?u=c[b](u):b===h&&c.err&&(u=c.err(u));let x=o[b]||m;switch(typeof u){case"undefined":case"function":continue;case"number":Number.isFinite(u)===!1&&(u=null);case"boolean":x&&(u=x(u));break;case"string":u=(x||mr)(u);break;default:u=(x||s)(u,i)}if(u===void 0)continue;let v=mr(b);g+=","+v+":"+u}let S="";if(e!==void 0){u=c[d]?c[d](e):e;let b=o[d]||m;switch(typeof u){case"function":break;case"number":Number.isFinite(u)===!1&&(u=null);case"boolean":b&&(u=b(u)),S=',"'+d+'":'+u;break;case"string":u=(b||mr)(u),S=',"'+d+'":'+u;break;default:u=(b||s)(u,i),S=',"'+d+'":'+u}}return this[xf]&&g?p+this[_f]+g.slice(1)+"}"+S+a:p+g+S+a}function Of(t,e){let n,r=t[Yi],s=t[Qi],i=t[yr],o=t[Zi],a=o[eo],l=t[Xi],c=t[to].bindings;e=c(e);for(let f in e)if(n=e[f],((f.length<5||f!=="level"&&f!=="serializers"&&f!=="formatters"&&f!=="customLevels")&&e.hasOwnProperty(f)&&n!==void 0)===!0){if(n=l[f]?l[f](n):n,n=(o[f]||a||s)(n,i),n===void 0)continue;r+=',"'+f+'":'+n}return r}function Rf(t){return t.write!==t.constructor.prototype.write}function Jt(t){let e=new gr(t);return e.on("error",n),!t.sync&&kf&&(Vi.register(e,If),e.on("close",function(){Vi.unregister(e)})),e;function n(r){if(r.code==="EPIPE"){e.write=Xe,e.end=Xe,e.flushSync=Xe,e.destroy=Xe;return}e.removeListener("error",n),e.emit("error",r)}}function If(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Pf(t){return function(n,r,s={},i){if(typeof s=="string")i=Jt({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=Jt({dest:i})}else if(s instanceof gr||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof gr||s.transport.writable||s.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(s.transport.targets&&s.transport.targets.length&&s.formatters&&typeof s.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;s.customLevels&&(l=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=$f({caller:r,...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=Xe),i||(Rf(process.stdout)?i=process.stdout:i=Jt({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function Mf(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[yr])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function jf(t,e,n){return{level:t,bindings:e,log:n}}function Lf(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}no.exports={noop:Xe,buildSafeSonicBoom:Jt,asChindings:Of,asJson:Ef,genLog:Cf,createArgsNormalizer:Pf,stringify:Mf,buildFormatters:jf,normalizeDestFileDescriptor:Lf}});var Xt=I((Lg,ro)=>{var Df={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Ff={ASC:"ASC",DESC:"DESC"};ro.exports={DEFAULT_LEVELS:Df,SORTING_ORDER:Ff}});var xr=I((Dg,ao)=>{"use strict";var{lsCacheSym:Nf,levelValSym:wr,useOnlyCustomLevelsSym:Uf,streamSym:qf,formattersSym:Bf,hooksSym:Hf,levelCompSym:so}=Je(),{noop:Wf,genLog:Pe}=Yt(),{DEFAULT_LEVELS:de,SORTING_ORDER:io}=Xt(),oo={fatal:t=>{let e=Pe(de.fatal,t);return function(...n){let r=this[qf];if(e.call(this,...n),typeof r.flushSync=="function")try{r.flushSync()}catch{}}},error:t=>Pe(de.error,t),warn:t=>Pe(de.warn,t),info:t=>Pe(de.info,t),debug:t=>Pe(de.debug,t),trace:t=>Pe(de.trace,t)},br=Object.keys(de).reduce((t,e)=>(t[de[e]]=e,t),{}),Vf=Object.keys(br).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function zf(t){let e=t[Bf].level,{labels:n}=t.levels,r={};for(let s in n){let i=e(n[s],Number(s));r[s]=JSON.stringify(i).slice(0,-1)}return t[Nf]=r,t}function Kf(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 Gf(t){let{labels:e,values:n}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(n[t]===void 0)throw Error("unknown level "+t);let r=this[wr],s=this[wr]=n[t],i=this[Uf],o=this[so],a=this[Hf].logMethod;for(let l in n){if(o(n[l],s)===!1){this[l]=Wf;continue}this[l]=Kf(l,i)?oo[l](a):Pe(n[l],a)}this.emit("level-change",t,s,e[r],r,this)}function Jf(t){let{levels:e,levelVal:n}=this;return e&&e.labels?e.labels[n]:""}function Yf(t){let{values:e}=this.levels,n=e[t];return n!==void 0&&this[so](n,this[wr])}function Xf(t,e,n){return t===io.DESC?e<=n:e>=n}function Zf(t){return typeof t=="string"?Xf.bind(null,t):t}function Qf(t=null,e=!1){let n=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,r=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:br,n),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:de,t);return{labels:r,values:s}}function ed(t,e,n){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),n?[]:Object.keys(br).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:de,e);if(!(t in r))throw Error(`default level:${t} must be included in custom levels`)}function td(t,e){let{labels:n,values:r}=t;for(let s in e){if(s in r)throw Error("levels cannot be overridden");if(e[s]in n)throw Error("pre-existing level values cannot be used for new levels")}}function nd(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(io).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}ao.exports={initialLsCache:Vf,genLsCache:zf,levelMethods:oo,getLevel:Jf,setLevel:Gf,isLevelEnabled:Yf,mappings:Qf,assertNoLevelCollisions:td,assertDefaultLevelFound:ed,genLevelComparison:Zf,assertLevelComparison:nd}});var Sr=I((Fg,lo)=>{"use strict";lo.exports={version:"10.3.1"}});var yo=I((Ug,go)=>{"use strict";var{EventEmitter:rd}=require("node:events"),{lsCacheSym:sd,levelValSym:id,setLevelSym:_r,getLevelSym:co,chindingsSym:Qt,mixinSym:od,asJsonSym:fo,writeSym:ad,mixinMergeStrategySym:ld,timeSym:cd,timeSliceIndexSym:ud,streamSym:po,serializersSym:Me,formattersSym:yt,errorKeySym:fd,messageKeySym:dd,useOnlyCustomLevelsSym:pd,needsMetadataGsym:hd,redactFmtSym:md,stringifySym:gd,formatOptsSym:yd,stringifiersSym:wd,msgPrefixSym:kr,hooksSym:bd}=Je(),{getLevel:xd,setLevel:Sd,isLevelEnabled:vd,mappings:_d,initialLsCache:kd,genLsCache:$d,assertNoLevelCollisions:Td}=xr(),{asChindings:$r,asJson:Cd,buildFormatters:vr,stringify:uo,noop:ho}=Yt(),{version:Ad}=Sr(),Ed=er(),Od=class{},mo={constructor:Od,child:Rd,bindings:Id,setBindings:Pd,flush:Ld,isLevelEnabled:vd,version:Ad,get level(){return this[co]()},set level(t){this[_r](t)},get levelVal(){return this[id]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[kr]},get[Symbol.toStringTag](){return"Pino"},[sd]:kd,[ad]:jd,[fo]:Cd,[co]:xd,[_r]:Sd};Object.setPrototypeOf(mo,rd.prototype);go.exports=function(){return Object.create(mo)};var Zt=t=>t;function Rd(t,e){if(!t)throw Error("missing bindings for child Pino");let n=this[Me],r=this[yt],s=Object.create(this);if(e==null)return s[yt].bindings!==Zt&&(s[yt]=vr(r.level,Zt,r.log)),s[Qt]=$r(s,t),this.onChild!==ho&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[Me]=Object.create(null);for(let c in n)s[Me][c]=n[c];let a=Object.getOwnPropertySymbols(n);for(var i=0;i<a.length;i++){let c=a[i];s[Me][c]=n[c]}for(let c in e.serializers)s[Me][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];s[Me][c]=e.serializers[c]}}else s[Me]=n;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;s[yt]=vr(a||r.level,l||Zt,c||r.log)}else s[yt]=vr(r.level,Zt,r.log);if(e.hasOwnProperty("customLevels")===!0&&(Td(this.levels,e.customLevels),s.levels=_d(e.customLevels,s[pd]),$d(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=Ed(s.redact,uo),l={stringify:a[md]};s[gd]=uo,s[wd]=a,s[yd]=l}if(typeof e.msgPrefix=="string"&&(s[kr]=(this[kr]||"")+e.msgPrefix),s[Qt]=$r(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[_r](a)}return this.onChild(s),s}function Id(){let e=`{${this[Qt].substr(1)}}`,n=JSON.parse(e);return delete n.pid,delete n.hostname,n}function Pd(t){let e=$r(this,t);this[Qt]=e}function Md(t,e){return Object.assign(e,t)}function jd(t,e,n){let r=this[cd](),s=this[od],i=this[fd],o=this[dd],a=this[ld]||Md,l,c=this[bd].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,n,this)));let f=this[fo](l,e,n,r),d=this[po];d[hd]===!0&&(d.lastLevel=n,d.lastObj=l,d.lastMsg=e,d.lastTime=r.slice(this[ud]),d.lastLogger=this),d.write(c?c(f):f)}function Ld(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[po];typeof e.flush=="function"?e.flush(t||ho):t&&t()}});var So=I((Er,xo)=>{"use strict";var{hasOwnProperty:wt}=Object.prototype,Le=Ar();Le.configure=Ar;Le.stringify=Le;Le.default=Le;Er.stringify=Le;Er.configure=Ar;xo.exports=Le;var Dd=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function ve(t){return t.length<5e3&&!Dd.test(t)?`"${t}"`:JSON.stringify(t)}function Tr(t,e){if(t.length>200||e)return t.sort(e);for(let n=1;n<t.length;n++){let r=t[n],s=n;for(;s!==0&&t[s-1]>r;)t[s]=t[s-1],s--;t[s]=r}return t}var Fd=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Cr(t){return Fd.call(t)!==void 0&&t.length!==0}function wo(t,e,n){t.length<n&&(n=t.length);let r=e===","?"":" ",s=`"0":${r}${t[0]}`;for(let i=1;i<n;i++)s+=`${e}"${i}":${r}${t[i]}`;return s}function Nd(t){if(wt.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 Ud(t){let e;if(wt.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 qd(t,e){let n;if(wt.call(t,e)&&(n=t[e],typeof n!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return n===void 0?!0:n}function bo(t,e){let n;if(wt.call(t,e)){if(n=t[e],typeof n!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(n))throw new TypeError(`The "${e}" argument must be an integer`);if(n<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return n===void 0?1/0:n}function je(t){return t===1?"1 item":`${t} items`}function Bd(t){let e=new Set;for(let n of t)(typeof n=="string"||typeof n=="number")&&e.add(String(n));return e}function Hd(t){if(wt.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 n=>{let r=`Object can not safely be stringified. Received type ${typeof n}`;throw typeof n!="function"&&(r+=` (${n.toString()})`),new Error(r)}}}function Ar(t){t={...t};let e=Hd(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let n=Nd(t),r=qd(t,"bigint"),s=Ud(t),i=typeof s=="function"?s:void 0,o=bo(t,"maximumDepth"),a=bo(t,"maximumBreadth");function l(p,u,m,g,S,b){let x=u[p];switch(typeof x=="object"&&x!==null&&typeof x.toJSON=="function"&&(x=x.toJSON(p)),x=g.call(u,p,x),typeof x){case"string":return ve(x);case"object":{if(x===null)return"null";if(m.indexOf(x)!==-1)return n;let v="",_=",",$=b;if(Array.isArray(x)){if(x.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(x),S!==""&&(b+=S,v+=`
|
|
26
|
+
${b}`,_=`,
|
|
27
|
+
${b}`);let D=Math.min(x.length,a),B=0;for(;B<D-1;B++){let J=l(String(B),x,m,g,S,b);v+=J!==void 0?J:"null",v+=_}let W=l(String(B),x,m,g,S,b);if(v+=W!==void 0?W:"null",x.length-1>a){let J=x.length-a-1;v+=`${_}"... ${je(J)} not stringified"`}return S!==""&&(v+=`
|
|
28
|
+
${$}`),m.pop(),`[${v}]`}let C=Object.keys(x),E=C.length;if(E===0)return"{}";if(o<m.length+1)return'"[Object]"';let T="",P="";S!==""&&(b+=S,_=`,
|
|
29
|
+
${b}`,T=" ");let L=Math.min(E,a);s&&!Cr(x)&&(C=Tr(C,i)),m.push(x);for(let D=0;D<L;D++){let B=C[D],W=l(B,x,m,g,S,b);W!==void 0&&(v+=`${P}${ve(B)}:${T}${W}`,P=_)}if(E>a){let D=E-a;v+=`${P}"...":${T}"${je(D)} not stringified"`,P=_}return S!==""&&P.length>1&&(v=`
|
|
30
|
+
${b}${v}
|
|
31
|
+
${$}`),m.pop(),`{${v}}`}case"number":return isFinite(x)?String(x):e?e(x):"null";case"boolean":return x===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(x);default:return e?e(x):void 0}}function c(p,u,m,g,S,b){switch(typeof u=="object"&&u!==null&&typeof u.toJSON=="function"&&(u=u.toJSON(p)),typeof u){case"string":return ve(u);case"object":{if(u===null)return"null";if(m.indexOf(u)!==-1)return n;let x=b,v="",_=",";if(Array.isArray(u)){if(u.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(u),S!==""&&(b+=S,v+=`
|
|
32
|
+
${b}`,_=`,
|
|
33
|
+
${b}`);let E=Math.min(u.length,a),T=0;for(;T<E-1;T++){let L=c(String(T),u[T],m,g,S,b);v+=L!==void 0?L:"null",v+=_}let P=c(String(T),u[T],m,g,S,b);if(v+=P!==void 0?P:"null",u.length-1>a){let L=u.length-a-1;v+=`${_}"... ${je(L)} not stringified"`}return S!==""&&(v+=`
|
|
34
|
+
${x}`),m.pop(),`[${v}]`}m.push(u);let $="";S!==""&&(b+=S,_=`,
|
|
35
|
+
${b}`,$=" ");let C="";for(let E of g){let T=c(E,u[E],m,g,S,b);T!==void 0&&(v+=`${C}${ve(E)}:${$}${T}`,C=_)}return S!==""&&C.length>1&&(v=`
|
|
36
|
+
${b}${v}
|
|
37
|
+
${x}`),m.pop(),`{${v}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(u);default:return e?e(u):void 0}}function f(p,u,m,g,S){switch(typeof u){case"string":return ve(u);case"object":{if(u===null)return"null";if(typeof u.toJSON=="function"){if(u=u.toJSON(p),typeof u!="object")return f(p,u,m,g,S);if(u===null)return"null"}if(m.indexOf(u)!==-1)return n;let b=S;if(Array.isArray(u)){if(u.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(u),S+=g;let T=`
|
|
38
|
+
${S}`,P=`,
|
|
39
|
+
${S}`,L=Math.min(u.length,a),D=0;for(;D<L-1;D++){let W=f(String(D),u[D],m,g,S);T+=W!==void 0?W:"null",T+=P}let B=f(String(D),u[D],m,g,S);if(T+=B!==void 0?B:"null",u.length-1>a){let W=u.length-a-1;T+=`${P}"... ${je(W)} not stringified"`}return T+=`
|
|
40
|
+
${b}`,m.pop(),`[${T}]`}let x=Object.keys(u),v=x.length;if(v===0)return"{}";if(o<m.length+1)return'"[Object]"';S+=g;let _=`,
|
|
41
|
+
${S}`,$="",C="",E=Math.min(v,a);Cr(u)&&($+=wo(u,_,a),x=x.slice(u.length),E-=u.length,C=_),s&&(x=Tr(x,i)),m.push(u);for(let T=0;T<E;T++){let P=x[T],L=f(P,u[P],m,g,S);L!==void 0&&($+=`${C}${ve(P)}: ${L}`,C=_)}if(v>a){let T=v-a;$+=`${C}"...": "${je(T)} not stringified"`,C=_}return C!==""&&($=`
|
|
42
|
+
${S}${$}
|
|
43
|
+
${b}`),m.pop(),`{${$}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(u);default:return e?e(u):void 0}}function d(p,u,m){switch(typeof u){case"string":return ve(u);case"object":{if(u===null)return"null";if(typeof u.toJSON=="function"){if(u=u.toJSON(p),typeof u!="object")return d(p,u,m);if(u===null)return"null"}if(m.indexOf(u)!==-1)return n;let g="",S=u.length!==void 0;if(S&&Array.isArray(u)){if(u.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(u);let $=Math.min(u.length,a),C=0;for(;C<$-1;C++){let T=d(String(C),u[C],m);g+=T!==void 0?T:"null",g+=","}let E=d(String(C),u[C],m);if(g+=E!==void 0?E:"null",u.length-1>a){let T=u.length-a-1;g+=`,"... ${je(T)} not stringified"`}return m.pop(),`[${g}]`}let b=Object.keys(u),x=b.length;if(x===0)return"{}";if(o<m.length+1)return'"[Object]"';let v="",_=Math.min(x,a);S&&Cr(u)&&(g+=wo(u,",",a),b=b.slice(u.length),_-=u.length,v=","),s&&(b=Tr(b,i)),m.push(u);for(let $=0;$<_;$++){let C=b[$],E=d(C,u[C],m);E!==void 0&&(g+=`${v}${ve(C)}:${E}`,v=",")}if(x>a){let $=x-a;g+=`${v}"...":"${je($)} not stringified"`}return m.pop(),`{${g}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(u);default:return e?e(u):void 0}}function h(p,u,m){if(arguments.length>1){let g="";if(typeof m=="number"?g=" ".repeat(Math.min(m,10)):typeof m=="string"&&(g=m.slice(0,10)),u!=null){if(typeof u=="function")return l("",{"":p},[],u,g,"");if(Array.isArray(u))return c("",p,[],Bd(u),g,"")}if(g.length!==0)return f("",p,[],g,"")}return d("",p,[])}return h}});var $o=I((qg,ko)=>{"use strict";var Or=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:_o}=Xt(),Wd=_o.info;function Vd(t,e){t=t||[],e=e||{dedupe:!1};let n=Object.create(_o);n.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(d=>{n[d]=e.levels[d]});let r={write:s,add:a,remove:l,emit:i,flushSync:o,end:c,minLevel:0,lastId:0,streams:[],clone:f,[Or]:!0,streamLevels:n};return Array.isArray(t)?t.forEach(a,r):a.call(r,t),t=null,r;function s(d){let h,p=this.lastLevel,{streams:u}=this,m=0,g;for(let S=zd(u.length,e.dedupe);Gd(S,u.length,e.dedupe);S=Kd(S,e.dedupe))if(h=u[S],h.level<=p){if(m!==0&&m!==h.level)break;if(g=h.stream,g[Or]){let{lastTime:b,lastMsg:x,lastObj:v,lastLogger:_}=this;g.lastLevel=p,g.lastTime=b,g.lastMsg=x,g.lastObj=v,g.lastLogger=_}g.write(d),e.dedupe&&(m=h.level)}else if(!e.dedupe)break}function i(...d){for(let{stream:h}of this.streams)typeof h.emit=="function"&&h.emit(...d)}function o(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync()}function a(d){if(!d)return r;let h=typeof d.write=="function"||d.stream,p=d.write?d:d.stream;if(!h)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:u,streamLevels:m}=this,g;typeof d.levelVal=="number"?g=d.levelVal:typeof d.level=="string"?g=m[d.level]:typeof d.level=="number"?g=d.level:g=Wd;let S={stream:p,level:g,levelVal:void 0,id:++r.lastId};return u.unshift(S),u.sort(vo),this.minLevel=u[0].level,r}function l(d){let{streams:h}=this,p=h.findIndex(u=>u.id===d);return p>=0&&(h.splice(p,1),h.sort(vo),this.minLevel=h.length>0?h[0].level:-1),r}function c(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function f(d){let h=new Array(this.streams.length);for(let p=0;p<h.length;p++)h[p]={level:d,stream:this.streams[p].stream};return{write:s,add:a,remove:l,minLevel:d,streams:h,clone:f,emit:i,flushSync:o,[Or]:!0}}}function vo(t,e){return t.level-e.level}function zd(t,e){return e?t-1:0}function Kd(t,e){return e?t-1:t+1}function Gd(t,e,n){return n?t>=0:t<e}ko.exports=Vd});var No=I((Bg,re)=>{"use strict";var Jd=require("node:os"),Po=Yn(),Yd=Xn(),Xd=er(),Mo=li(),Zd=yo(),jo=Je(),{configure:Qd}=So(),{assertDefaultLevelFound:ep,mappings:Lo,genLsCache:tp,genLevelComparison:np,assertLevelComparison:rp}=xr(),{DEFAULT_LEVELS:Do,SORTING_ORDER:sp}=Xt(),{createArgsNormalizer:ip,asChindings:op,buildSafeSonicBoom:To,buildFormatters:ap,stringify:Rr,normalizeDestFileDescriptor:Co,noop:lp}=Yt(),{version:cp}=Sr(),{chindingsSym:Ao,redactFmtSym:up,serializersSym:Eo,timeSym:fp,timeSliceIndexSym:dp,streamSym:pp,stringifySym:Oo,stringifySafeSym:Ir,stringifiersSym:Ro,setLevelSym:hp,endSym:mp,formatOptsSym:gp,messageKeySym:yp,errorKeySym:wp,nestedKeySym:bp,mixinSym:xp,levelCompSym:Sp,useOnlyCustomLevelsSym:vp,formattersSym:Io,hooksSym:_p,nestedKeyStrSym:kp,mixinMergeStrategySym:$p,msgPrefixSym:Tp}=jo,{epochTime:Fo,nullTime:Cp}=Mo,{pid:Ap}=process,Ep=Jd.hostname(),Op=Po.err,Rp={level:"info",levelComparison:sp.ASC,levels:Do,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Ap,hostname:Ep},serializers:Object.assign(Object.create(null),{err:Op}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Fo,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Ip=ip(Rp),Pp=Object.assign(Object.create(null),Po);function Pr(...t){let e={},{opts:n,stream:r}=Ip(e,Yd(),...t);n.level&&typeof n.level=="string"&&Do[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:f,base:d,name:h,level:p,customLevels:u,levelComparison:m,mixin:g,mixinMergeStrategy:S,useOnlyCustomLevels:b,formatters:x,hooks:v,depthLimit:_,edgeLimit:$,onChild:C,msgPrefix:E}=n,T=Qd({maximumDepth:_,maximumBreadth:$}),P=ap(x.level,x.bindings,x.log),L=Rr.bind({[Ir]:T}),D=s?Xd(s,L):{},B=s?{stringify:D[up]}:{stringify:L},W="}"+(i?`\r
|
|
44
44
|
`:`
|
|
45
|
-
`),J=
|
|
46
|
-
`);o=c.pop()||"";for(let f of c)if(f.trim())try{let d=JSON.parse(f);d.message?.content&&(yield d.message.content)}catch{}}}};var
|
|
47
|
-
`);a=f.pop()||"";for(let d of f){let h=d.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let u=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;u&&(yield u)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function
|
|
48
|
-
`));var e=[],
|
|
49
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var
|
|
50
|
-
`);if(
|
|
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
|
|
45
|
+
`),J=op.bind(null,{[Ao]:"",[Eo]:o,[Ro]:D,[Oo]:Rr,[Ir]:T,[Io]:P}),Q="";d!==null&&(h===void 0?Q=J(d):Q=J(Object.assign({},d,{name:h})));let j=a instanceof Function?a:a?Fo:Cp,F=j().indexOf(":")+1;if(b&&!u)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(g&&typeof g!="function")throw Error(`Unknown mixin type "${typeof g}" - expected "function"`);if(E&&typeof E!="string")throw Error(`Unknown msgPrefix type "${typeof E}" - expected "string"`);ep(p,u,b);let Pt=Lo(u,b);typeof r.emit=="function"&&r.emit("message",{code:"PINO_CONFIG",config:{levels:Pt,messageKey:l,errorKey:c}}),rp(m);let fs=np(m);return Object.assign(e,{levels:Pt,[Sp]:fs,[vp]:b,[pp]:r,[fp]:j,[dp]:F,[Oo]:Rr,[Ir]:T,[Ro]:D,[mp]:W,[gp]:B,[yp]:l,[wp]:c,[bp]:f,[kp]:f?`,${JSON.stringify(f)}:{`:"",[Eo]:o,[xp]:g,[$p]:S,[Ao]:Q,[Io]:P,[_p]:v,silent:lp,onChild:C,[Tp]:E}),Object.setPrototypeOf(e,Zd()),tp(e),e[hp](p),e}re.exports=Pr;re.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=Co(t.dest||process.stdout.fd),To(t)):To({dest:Co(t),minLength:0});re.exports.transport=hr();re.exports.multistream=$o();re.exports.levels=Lo();re.exports.stdSerializers=Pp;re.exports.stdTimeFunctions=Object.assign({},Mo);re.exports.symbols=jo;re.exports.version=cp;re.exports.default=Pr;re.exports.pino=Pr});var $s=A(ks(),1),{program:Zm,createCommand:Qm,createArgument:eg,createOption:tg,CommanderError:ng,InvalidArgumentError:rg,InvalidOptionArgumentError:sg,Command:Ts,Argument:ig,Option:og,Help:ag}=$s.default;var ae=A(require("fs")),Re=A(require("path")),Cs=A(require("os"));var Ve={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:5e3,timeout:12e4,autoMode:!1,contextBudget:2e6,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0},vision:{enabled:!0,primaryModel:"moonshotai/kimi-k2.6",fallbackModel:"meta/llama-3.2-90b-vision-instruct",maxImageBytes:1048576}},te={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 ze=Re.join(Cs.homedir(),".hablas"),Un=Re.join(ze,"config.json");function Ke(t={}){let e={};if(ae.existsSync(Un))try{e=JSON.parse(ae.readFileSync(Un,"utf-8"))}catch{}let n={...Ve,...e,tools:{...Ve.tools,...e.tools||{},runCommand:{...Ve.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...Ve.workspace,...e.workspace||{}},vision:{...Ve.vision,...e.vision||{}}};if(process.env.HABLAS_API_URL&&(n.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(n.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_MODEL&&(n.model=process.env.HABLAS_MODEL),process.env.HABLAS_VISION_PRIMARY&&(n.vision.primaryModel=process.env.HABLAS_VISION_PRIMARY),process.env.HABLAS_VISION_FALLBACK&&(n.vision.fallbackModel=process.env.HABLAS_VISION_FALLBACK),process.env.HABLAS_VISION_DISABLED==="true"&&(n.vision.enabled=!1),process.env.HABLAS_PROVIDER){let r=process.env.HABLAS_PROVIDER;(r==="ollama"||r==="custom"||r==="nvidia")&&(n.provider=r)}if(t.model&&(n.model=t.model),t.host&&(n.ollamaHost=t.host),t.project&&(n.workingDirectory=Re.resolve(t.project)),t.provider){let r=t.provider;(r==="ollama"||r==="custom"||r==="nvidia")&&(n.provider=r)}return t.apiUrl&&(n.apiUrl=t.apiUrl),t.apiKey&&(n.apiKey=t.apiKey),n.apiUrl&&n.provider==="ollama"&&(n.provider="custom"),n}function Ge(t){ae.existsSync(ze)||ae.mkdirSync(ze,{recursive:!0}),ae.writeFileSync(Un,JSON.stringify(t,null,2),"utf-8")}function As(){let t=[ze,Re.join(ze,"logs"),Re.join(ze,"backup")];for(let e of t)ae.existsSync(e)||ae.mkdirSync(e,{recursive:!0})}var Mr=A(No()),jr=A(require("path")),Uo=A(require("os")),en=A(require("fs"));function Lr(t){let e=jr.join(Uo.homedir(),".hablas","logs");en.existsSync(e)||en.mkdirSync(e,{recursive:!0});let n=jr.join(e,`session-${Date.now()}.log`);return(0,Mr.default)({level:"info"},Mr.default.destination({dest:n,sync:!1}))}var tn=A(require("fs")),bt=A(require("path"));function qo(){let t=[bt.resolve(__dirname,"..","package.json"),bt.resolve(__dirname,"..","..","package.json"),bt.resolve(process.cwd(),"package.json"),bt.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(tn.existsSync(e)){let n=JSON.parse(tn.readFileSync(e,"utf-8"));if(n.version)return n.version}}catch{}return"0.0.0"}var gl=A(require("fs")),yl=A(require("path"));var nn=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(r=>r.name):[]}catch{return[]}}async chatWithTools(e,n,r){let s={model:this.model,messages:e,stream:!1};n.length>0&&(s.tools=n);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)};r&&(i.signal=r);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,n){let r=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:n});if(!r.ok)throw new Error(`Ollama error: ${r.status} ${r.statusText}`);let s=r.body?.getReader();if(!s)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await s.read();if(a)break;o+=i.decode(l,{stream:!0});let c=o.split(`
|
|
46
|
+
`);o=c.pop()||"";for(let f of c)if(f.trim())try{let d=JSON.parse(f);d.message?.content&&(yield d.message.content)}catch{}}}};var Bo=12e4,Mp=6e4,rn=3,Ho=1e3,jp=20;function Wo(t){return t.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let n=e.tool_calls.filter(r=>r?.function?.name);if(n.length>0)return{role:"assistant",content:e.content||null,tool_calls:n.map((r,s)=>({id:`call_${s}`,type:"function",function:{name:r.function?.name||"",arguments:JSON.stringify(r.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function Lp(t){return t.map(e=>({type:"function",function:e.function}))}function Dp(t){return t.filter(e=>e?.function?.name).map(e=>{let n={};try{n=JSON.parse(e.function?.arguments||"{}")}catch{n={_raw:e.function?.arguments}}return{function:{name:e.function?.name||"",arguments:n}}})}function Vo(t){return new Promise(e=>setTimeout(e,t))}function zo(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var xt=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=[],n=!0,r,s=0;for(;n&&s<jp;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;r&&o.set("after",r),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let l=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(Mp)});if(!l.ok)break;let c=await l.json();if(Array.isArray(c))e.push(...c.map(f=>f.id||f.name||f).filter(Boolean)),n=!1;else if(c.data&&Array.isArray(c.data)){let f=c.data.map(d=>d.id||d.name).filter(Boolean);e.push(...f),c.has_more&&f.length>0?(r=f[f.length-1],s++):n=!1}else c.models&&Array.isArray(c.models)&&e.push(...c.models.map(f=>f.name||f.id).filter(Boolean)),n=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,n,r){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:Wo(e)};n.length>0&&(i.tools=Lp(n),i.tool_choice="auto");let o=null;for(let a=0;a<=rn;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),Bo),f={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:r||l.signal};try{let d=await fetch(s,f);if(clearTimeout(c),!d.ok){let m=await d.text().catch(()=>"");if(!zo(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<rn){let g=Ho*Math.pow(2,a);await Vo(g);continue}throw o}let p=(await d.json()).choices?.[0];if(!p)throw new Error("API returned empty response");let u=p.message.tool_calls?Dp(p.message.tool_calls):void 0;return{message:{role:p.message.role||"assistant",content:p.message.content||"",tool_calls:u},done:!0,done_reason:p.finish_reason}}catch(d){if(clearTimeout(c),d.name==="AbortError"&&r?.aborted)throw d;if(zo(d)&&(o=d,a<rn)){let h=Ho*Math.pow(2,a);await Vo(h);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=rn)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,n){let r=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:Wo(e),stream:!0}),signal:n||AbortSignal.timeout(Bo)});if(!s.ok)throw new Error(`API error: ${s.status} ${s.statusText}`);let i=s.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:c}=await i.read();if(l)break;a+=o.decode(c,{stream:!0});let f=a.split(`
|
|
47
|
+
`);a=f.pop()||"";for(let d of f){let h=d.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let u=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;u&&(yield u)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function Ze(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:te.apiUrl};return new xt(e)}return t.provider==="custom"&&t.apiUrl?new xt(t):new nn(t)}function De(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var U=A(require("fs/promises")),Wr=A(require("fs")),_e=A(require("path"));function ge(){}ge.prototype={diff:function(e,n){var r,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=s.callback;typeof s=="function"&&(i=s,s={}),this.options=s;var o=this;function a(v){return i?(setTimeout(function(){i(void 0,v)},0),!0):v}e=this.castInput(e),n=this.castInput(n),e=this.removeEmpty(this.tokenize(e)),n=this.removeEmpty(this.tokenize(n));var l=n.length,c=e.length,f=1,d=l+c;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var h=(r=s.timeout)!==null&&r!==void 0?r:1/0,p=Date.now()+h,u=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(u[0],n,e,0);if(u[0].oldPos+1>=c&&m+1>=l)return a([{value:this.join(n),count:n.length}]);var g=-1/0,S=1/0;function b(){for(var v=Math.max(g,-f);v<=Math.min(S,f);v+=2){var _=void 0,$=u[v-1],C=u[v+1];$&&(u[v-1]=void 0);var E=!1;if(C){var T=C.oldPos-v;E=C&&0<=T&&T<l}var P=$&&$.oldPos+1<c;if(!E&&!P){u[v]=void 0;continue}if(!P||E&&$.oldPos+1<C.oldPos?_=o.addToPath(C,!0,void 0,0):_=o.addToPath($,void 0,!0,1),m=o.extractCommon(_,n,e,v),_.oldPos+1>=c&&m+1>=l)return a(Fp(o,_.lastComponent,n,e,o.useLongestToken));u[v]=_,_.oldPos+1>=c&&(S=Math.min(S,v-1)),m+1>=l&&(g=Math.max(g,v+1))}f++}if(i)(function v(){setTimeout(function(){if(f>d||Date.now()>p)return i();b()||v()},0)})();else for(;f<=d&&Date.now()<=p;){var x=b();if(x)return x}},addToPath:function(e,n,r,s){var i=e.lastComponent;return i&&i.added===n&&i.removed===r?{oldPos:e.oldPos+s,lastComponent:{count:i.count+1,added:n,removed:r,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+s,lastComponent:{count:1,added:n,removed:r,previousComponent:i}}},extractCommon:function(e,n,r,s){for(var i=n.length,o=r.length,a=e.oldPos,l=a-s,c=0;l+1<i&&a+1<o&&this.equals(n[l+1],r[a+1]);)l++,a++,c++;return c&&(e.lastComponent={count:c,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,n){return this.options.comparator?this.options.comparator(e,n):e===n||this.options.ignoreCase&&e.toLowerCase()===n.toLowerCase()},removeEmpty:function(e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(e[r]);return n},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function Fp(t,e,n,r,s){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,c=0,f=0;a<l;a++){var d=i[a];if(d.removed){if(d.value=t.join(r.slice(f,f+d.count)),f+=d.count,a&&i[a-1].added){var p=i[a-1];i[a-1]=i[a],i[a]=p}}else{if(!d.added&&s){var h=n.slice(c,c+d.count);h=h.map(function(m,g){var S=r[f+g];return S.length>m.length?S:m}),d.value=t.join(h)}else d.value=t.join(n.slice(c,c+d.count));c+=d.count,d.added||(f+=d.count)}}var u=i[l-1];return l>1&&typeof u.value=="string"&&(u.added||u.removed)&&t.equals("",u.value)&&(i[l-2].value+=u.value,i.pop()),i}var ry=new ge;var Ko=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Go=/\S/,Jo=new ge;Jo.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!Go.test(t)&&!Go.test(e)};Jo.tokenize=function(t){for(var e=t.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<e.length-1;n++)!e[n+1]&&e[n+2]&&Ko.test(e[n])&&Ko.test(e[n+2])&&(e[n]+=e[n+2],e.splice(n+1,2),n--);return e};var qr=new ge;qr.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
|
|
48
|
+
`));var e=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var r=0;r<n.length;r++){var s=n[r];r%2&&!this.options.newlineIsToken?e[e.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),e.push(s))}return e};function Np(t,e,n){return qr.diff(t,e,n)}var Up=new ge;Up.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var qp=new ge;qp.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function sn(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?sn=function(e){return typeof e}:sn=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},sn(t)}function Dr(t){return Bp(t)||Hp(t)||Wp(t)||Vp()}function Bp(t){if(Array.isArray(t))return Fr(t)}function Hp(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Wp(t,e){if(t){if(typeof t=="string")return Fr(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);if(n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set")return Array.from(t);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Fr(t,e)}}function Fr(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function Vp(){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 zp=Object.prototype.toString,St=new ge;St.useLongestToken=!0;St.tokenize=qr.tokenize;St.castInput=function(t){var e=this.options,n=e.undefinedReplacement,r=e.stringifyReplacer,s=r===void 0?function(i,o){return typeof o>"u"?n:o}:r;return typeof t=="string"?t:JSON.stringify(Nr(t,null,null,s),s," ")};St.equals=function(t,e){return ge.prototype.equals.call(St,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function Nr(t,e,n,r,s){e=e||[],n=n||[],r&&(t=r(s,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return n[i];var o;if(zp.call(t)==="[object Array]"){for(e.push(t),o=new Array(t.length),n.push(o),i=0;i<t.length;i+=1)o[i]=Nr(t[i],e,n,r,s);return e.pop(),n.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),sn(t)==="object"&&t!==null){e.push(t),o={},n.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]=Nr(t[l],e,n,r,l);e.pop(),n.pop()}else o=t;return o}var Ur=new ge;Ur.tokenize=function(t){return t.slice()};Ur.join=Ur.removeEmpty=function(t){return t};function Kp(t,e,n,r,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Np(n,r,o);if(!a)return;a.push({value:"",lines:[]});function l(S){return S.map(function(b){return" "+b})}for(var c=[],f=0,d=0,h=[],p=1,u=1,m=function(b){var x=a[b],v=x.lines||x.value.replace(/\n$/,"").split(`
|
|
50
|
+
`);if(x.lines=v,x.added||x.removed){var _;if(!f){var $=a[b-1];f=p,d=u,$&&(h=o.context>0?l($.lines.slice(-o.context)):[],f-=h.length,d-=h.length)}(_=h).push.apply(_,Dr(v.map(function(W){return(x.added?"+":"-")+W}))),x.added?u+=v.length:p+=v.length}else{if(f)if(v.length<=o.context*2&&b<a.length-2){var C;(C=h).push.apply(C,Dr(l(v)))}else{var E,T=Math.min(v.length,o.context);(E=h).push.apply(E,Dr(l(v.slice(0,T))));var P={oldStart:f,oldLines:p-f+T,newStart:d,newLines:u-d+T,lines:h};if(b>=a.length-2&&v.length<=o.context){var L=/\n$/.test(n),D=/\n$/.test(r),B=v.length==0&&h.length>P.oldLines;!L&&B&&n.length>0&&h.splice(P.oldLines,0,"\"),(!L&&!B||!D)&&h.push("\")}c.push(P),f=0,d=0,h=[]}p+=v.length,u+=v.length}},g=0;g<a.length;g++)m(g);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:c}}function Yo(t){if(Array.isArray(t))return t.map(Yo).join(`
|
|
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 n=0;n<t.hunks.length;n++){var r=t.hunks[n];r.oldLines===0&&(r.oldStart-=1),r.newLines===0&&(r.newStart-=1),e.push("@@ -"+r.oldStart+","+r.oldLines+" +"+r.newStart+","+r.newLines+" @@"),e.push.apply(e,r.lines)}return e.join(`
|
|
52
52
|
`)+`
|
|
53
|
-
`}function
|
|
54
|
-
`),
|
|
55
|
-
... [Partial read. Total lines: ${
|
|
53
|
+
`}function Gp(t,e,n,r,s,i,o){return Yo(Kp(t,e,n,r,s,i,o))}function Xo(t,e,n,r,s,i){return Gp(t,t,e,n,r,s,i)}function Br(t,e,n){return Xo(t,e,n,"original","modified")}var pe=A(require("fs/promises")),Hr=A(require("fs")),Qe=A(require("path")),Qo=A(require("os")),vt=Qe.join(Qo.homedir(),".hablas","backup"),Zo=10;async function Fe(t){try{if(!Hr.existsSync(t))return;Hr.existsSync(vt)||await pe.mkdir(vt,{recursive:!0});let e=await pe.readFile(t,"utf-8"),n=Qe.basename(t),r=Date.now(),s=`${n}.${r}.bak`,i=Qe.join(vt,s);await pe.writeFile(i,e,"utf-8");let a=(await pe.readdir(vt)).filter(l=>l.startsWith(`${n}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Zo)for(let l of a.slice(Zo))await pe.unlink(Qe.join(vt,l))}catch{}}function ta(t){let e=p=>_e.resolve(t,p);return[{name:"read_file",description:"Read the FULL content of a file with line numbers (complete read, no truncation by default per user requirement for 1000/2000+ line files like architecture docs). Use start_line/end_line ONLY if you explicitly need a specific section. Never re-read the same path this turn \u2014 use previous tool observations from history.",safety:"safe",parameters:{path:{type:"string",description:"File path to read",required:!0},start_line:{type:"number",description:"Starting line number (1-based, optional)",required:!1},end_line:{type:"number",description:"Ending line number (inclusive, optional)",required:!1}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[read_file]: path is required"};let u=e(p.path),g=(await U.readFile(u,"utf-8")).split(`
|
|
54
|
+
`),S=g.length,b=p.start_line?Math.max(1,p.start_line):1,x=p.end_line?Math.min(S,p.end_line):S,v=g.slice(b-1,x),_=String(x).length,$=v.map((T,P)=>`${String(b+P).padStart(_," ")} | ${T}`),C=`[${p.path} \u2014 lines ${b}-${x} of ${S}]`,E=x<S?`
|
|
55
|
+
... [Partial read. Total lines: ${S}.]`:"";return{success:!0,output:`${C}
|
|
56
56
|
${$.join(`
|
|
57
|
-
`)}${E}`}}catch(u){return{success:!1,output:"",error:`[read_file]: ${u.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let u=e(p.path);return
|
|
58
|
-
${
|
|
59
|
-
`),
|
|
60
|
-
`),C=[..._
|
|
61
|
-
`);await U.writeFile(u,C,"utf-8");let E=
|
|
62
|
-
${E}`}}catch(u){return{success:!1,output:"",error:`[patch_file]: ${u.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!p.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(p.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let u=e(p.path),m=await U.readFile(u,"utf-8"),g=p.search,
|
|
63
|
-
`)}}catch(u){return{success:!1,output:"",error:`[get_file_info]: ${u.message}`}}}}]}function
|
|
64
|
-
`,l.isDirectory()){let h=e+(c?" ":"\u2502 ");o+=await
|
|
65
|
-
Error: ${a.message}`}),s>0&&setTimeout(()=>{o.status==="running"&&(this.kill(
|
|
66
|
-
Process timed out after ${s}ms`)},s),this.processes.set(
|
|
67
|
-
`),i+=
|
|
68
|
-
`).slice(-
|
|
69
|
-
`)),{success:!0,output:i,status:
|
|
70
|
-
PID: ${
|
|
71
|
-
Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,
|
|
57
|
+
`)}${E}`}}catch(u){return{success:!1,output:"",error:`[read_file]: ${u.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let u=e(p.path);return Wr.existsSync(u)&&await Fe(u),await U.mkdir(_e.dirname(u),{recursive:!0}),await U.writeFile(u,p.content,"utf-8"),{success:!0,output:`Written: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[write_file]: ${u.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!p.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let u=e(p.path),m=await U.readFile(u,"utf-8"),g=p.old_content,S=p.new_content,b=ea(m,g);if(b===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(b>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${b} locations in the file. Provide more surrounding context to be specific.`};await Fe(u);let x=m.replace(g,S);await U.writeFile(u,x,"utf-8");let v=Br(p.path,m,x);return{success:!0,output:`Edited: ${p.path}
|
|
58
|
+
${v}`}}catch(u){return{success:!1,output:"",error:`[edit_file]: ${u.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!p.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!p.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(p.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let u=e(p.path),m=await U.readFile(u,"utf-8"),g=m.split(`
|
|
59
|
+
`),S=g.length,b=p.start_line,x=p.end_line;if(b<1||b>S)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${S} lines)`};if(x<b||x>S)return{success:!1,output:"",error:`[patch_file]: end_line ${x} is out of range (start_line=${b}, total=${S})`};await Fe(u);let v=g.slice(0,b-1),_=g.slice(x),$=p.new_content.split(`
|
|
60
|
+
`),C=[...v,...$,..._].join(`
|
|
61
|
+
`);await U.writeFile(u,C,"utf-8");let E=Br(p.path,m,C),T=x-b+1,P=$.length;return{success:!0,output:`Patched: ${p.path} (replaced ${T} lines with ${P})
|
|
62
|
+
${E}`}}catch(u){return{success:!1,output:"",error:`[patch_file]: ${u.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!p.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(p.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let u=e(p.path),m=await U.readFile(u,"utf-8"),g=p.search,S=p.replace,b=p.is_regex;await Fe(u);let x,v;if(b){let _=new RegExp(g,"g");v=(m.match(_)||[]).length,x=m.replace(_,S)}else v=ea(m,g),x=m.split(g).join(S);return v===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await U.writeFile(u,x,"utf-8"),{success:!0,output:`Replaced ${v} occurrence(s) in ${p.path}`})}catch(u){return{success:!1,output:"",error:`[search_and_replace]: ${u.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let u=e(p.path);return await U.mkdir(_e.dirname(u),{recursive:!0}),Wr.existsSync(u)&&await Fe(u),await U.appendFile(u,p.content,"utf-8"),{success:!0,output:`Appended to: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[append_to_file]: ${u.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let u=e(p.path);return await Fe(u),await U.unlink(u),{success:!0,output:`Deleted: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[delete_file]: ${u.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async p=>{try{if(!p.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!p.to)return{success:!1,output:"",error:"[move_file]: to is required"};let u=e(p.from),m=e(p.to);return await U.mkdir(_e.dirname(m),{recursive:!0}),await U.rename(u,m),{success:!0,output:`Moved: ${p.from} \u2192 ${p.to}`}}catch(u){return{success:!1,output:"",error:`[move_file]: ${u.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let u=e(p.path);return await U.mkdir(u,{recursive:!0}),{success:!0,output:`Created directory: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[create_dir]: ${u.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async p=>{try{let u=e(p.path||"."),m=p.depth||3;return{success:!0,output:await na(u,"",m,0)||"(empty directory)"}}catch(u){return{success:!1,output:"",error:`[list_dir]: ${u.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let u=e(p.path),m=await U.stat(u);return{success:!0,output:[`Path: ${p.path}`,`Size: ${Yp(m.size)}`,`Type: ${m.isDirectory()?"directory":"file"}`,`Modified: ${m.mtime.toISOString()}`,`Created: ${m.birthtime.toISOString()}`].join(`
|
|
63
|
+
`)}}catch(u){return{success:!1,output:"",error:`[get_file_info]: ${u.message}`}}}}]}function ea(t,e){let n=0,r=0;for(;;){let s=t.indexOf(e,r);if(s===-1)break;n++,r=s+e.length}return n}var Jp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function na(t,e,n,r){if(r>=n)return"";let i=(await U.readdir(t,{withFileTypes:!0})).filter(a=>!Jp.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],c=a===i.length-1,f=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${f}${d} ${l.name}
|
|
64
|
+
`,l.isDirectory()){let h=e+(c?" ":"\u2502 ");o+=await na(_e.join(t,l.name),h,n,r+1)}}return o}function Yp(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var ia=require("child_process");var ra=require("child_process"),on=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,n){let r=`bg_${this.nextId++}`,s=n?.timeout||this.config.defaultTimeout,i=(0,ra.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...n?.env}}),o={id:r,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
|
+
Error: ${a.message}`}),s>0&&setTimeout(()=>{o.status==="running"&&(this.kill(r),o.status="timeout",o.stderr+=`
|
|
66
|
+
Process timed out after ${s}ms`)},s),this.processes.set(r,o),r}readOutput(e,n){let r=this.processes.get(e);if(!r)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let s=n?.type||"both",i="";return(s==="stdout"||s==="both")&&(i+=r.stdout),(s==="stderr"||s==="both")&&(i&&(i+=`
|
|
67
|
+
`),i+=r.stderr),n?.lastLines&&(i=i.split(`
|
|
68
|
+
`).slice(-n.lastLines).join(`
|
|
69
|
+
`)),{success:!0,output:i,status:r.status}}kill(e){let n=this.processes.get(e);if(!n)return!1;if(n.process.pid)try{process.kill(-n.process.pid,"SIGTERM")}catch{try{process.kill(n.process.pid,"SIGTERM")}catch{}}return n.status="killed",!0}killAll(){let e=0;for(let n of this.processes.keys())this.kill(n)&&e++;return e}listProcesses(){let e=[];for(let[n,r]of this.processes){let s=Date.now()-r.startTime,i=this.formatUptime(s);e.push({id:n,command:r.command,status:r.status,pid:r.pid,startTime:r.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[n,r]of this.processes)(r.status==="finished"||r.status==="killed"||r.status==="timeout")&&(this.processes.delete(n),e++);return e}formatUptime(e){let n=Math.floor(e/1e3);if(n<60)return`${n}s`;let r=Math.floor(n/60);return r<60?`${r}m ${n%60}s`:`${Math.floor(r/60)}h ${r%60}m`}};var Xp=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],Vr=null;function sa(t){return Vr||(Vr=new on({workingDir:t})),Vr}function oa(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 n=>{let r=n.command,s=n.run_in_background===!0,i=n.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...Xp,...o];if(a.length>0){for(let l of a)if(r.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(s){let l=sa(t).start(r,{timeout:i});return{success:!0,output:`Background process started: ${l}
|
|
70
|
+
PID: ${sa(t).getProcess(l)?.pid}
|
|
71
|
+
Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,ia.exec)(r,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),f="",d="";c.stdout?.on("data",h=>{f+=h}),c.stderr?.on("data",h=>{d+=h}),c.on("close",h=>{l(h===0?{success:!0,output:f||"(no output)"}:{success:!1,output:f,error:d||`Exit code: ${h}`})}),c.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var an=A(require("fs/promises")),ke=A(require("path")),Zp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Qp=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function aa(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 n=e.query,r=ke.resolve(t,e.path||"."),s=new RegExp(n,"gi"),i=[];if(await la(r,s,i,t),i.length===0)return{success:!0,output:`No matches found for: "${n}"`};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(
|
|
74
|
-
`),c=
|
|
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])&&
|
|
78
|
-
`)}function
|
|
79
|
-
`);
|
|
80
|
-
`),"utf-8"),
|
|
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(n){return{success:!1,output:"",error:`Search failed: ${n.message}`}}}}}async function la(t,e,n,r){let s=await an.readdir(t,{withFileTypes:!0});for(let i of s){if(Zp.has(i.name)||i.name.startsWith("."))continue;let o=ke.join(t,i.name);if(i.isDirectory())await la(o,e,n,r);else if(Qp.has(ke.extname(i.name)))try{let l=(await an.readFile(o,"utf-8")).split(`
|
|
74
|
+
`),c=ke.relative(r,o);for(let f=0;f<l.length;f++)e.test(l[f])&&(n.push(`${c}:${f+1}: ${l[f].trim()}`),e.lastIndex=0)}catch{}}}var zr=require("child_process"),se=A(require("fs")),$e=A(require("path"));function eh(t){let e=[],n=$e.join(t,"tsconfig.json");if(!se.existsSync(n))return e;try{(0,zr.execSync)("npx tsc --noEmit 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(r){let s=r,o=(s.stdout||s.message||"").split(`
|
|
75
|
+
`);for(let a of o){let l=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);l&&e.push({file:l[1],line:parseInt(l[2],10),severity:l[3]==="error"?"error":"warning",message:l[4].trim(),source:"typescript"})}}return e}function th(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(r=>se.existsSync($e.join(t,r))))return e;try{(0,zr.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(r){let i=r.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:$e.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 nh(t,e,n){let r;try{r=se.readFileSync(t,"utf-8")}catch{return}let s=$e.relative(e,t),i=r.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])&&n.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)&&n.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)&&n.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("//")&&n.push({file:s,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function rh(t){let e=[],n=[".ts",".tsx",".js",".jsx"];function r(s,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=se.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let c=$e.join(s,l),f;try{f=se.statSync(c)}catch{continue}f.isDirectory()?r(c,i+1):n.some(d=>l.endsWith(d))&&nh(c,t,e)}}return r(t),e.slice(0,20)}function sh(t){let e=[];e.push(...eh(t)),e.push(...th(t)),e.push(...rh(t));let n={error:0,warning:1,info:2};return e.sort((r,s)=>n[r.severity]-n[s.severity]),e}function ca(t){if(t.length===0)return" \u2713 No bugs detected";let e=[],n=t.filter(i=>i.severity==="error").length,r=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":""}: ${n} errors, ${r} warnings, ${s} info`),e.push("");for(let i of t.slice(0,15)){let o=i.severity==="error"?"\u2717":i.severity==="warning"?"\u26A0":"\u2139",a=i.line>0?`:${i.line}`:"";e.push(` ${o} ${i.file}${a}`),e.push(` ${i.message}`),i.suggestedFix&&e.push(` \u2192 ${i.suggestedFix}`)}return t.length>15&&e.push(` ... and ${t.length-15} more`),e.join(`
|
|
78
|
+
`)}function ih(t,e){let n=[];for(let r of t)if(r.source==="pattern"&&r.message.includes("console.log")){let s=$e.join(e,r.file);try{let o=se.readFileSync(s,"utf-8").split(`
|
|
79
|
+
`);r.line>0&&r.line<=o.length&&(o[r.line-1]="// "+o[r.line-1],se.writeFileSync(s,o.join(`
|
|
80
|
+
`),"utf-8"),n.push({bug:r,fixed:!0,action:"Commented out console.log"}))}catch{n.push({bug:r,fixed:!1,action:"Failed to read/write file"})}}else n.push({bug:r,fixed:!1,action:"Requires manual fix or LLM assistance"});return n}function ua(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 n=e.path||t,r=e.fix==="true"||e.fix===!0;try{let s=sh(n);if(r&&s.length>0){let o=ih(s,n).filter(l=>l.fixed).length;return{success:!0,output:`${ca(s)}
|
|
81
|
+
|
|
82
|
+
Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:ca(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var fa=2*1024*1024,da=15e3,pa=32e3,oh="HablasBot/2.0 (+https://hablas.dev)";function ah(t){let e=t;return e=e.replace(/<(script|style|nav|footer|header|aside|iframe|noscript)[^>]*>[\s\S]*?<\/\1>/gi,""),e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/<\/(p|div|section|article|li|tr|h[1-6])>/gi,`
|
|
83
83
|
`),e=e.replace(/<(br|hr)\s*\/?>/gi,`
|
|
84
84
|
`),e=e.replace(/<\/?(ul|ol)>/gi,`
|
|
85
|
-
`),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(r,
|
|
86
|
-
${"#".repeat(parseInt(
|
|
87
|
-
`),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(r,
|
|
85
|
+
`),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(n,r,s)=>`
|
|
86
|
+
${"#".repeat(parseInt(r))} ${s.replace(/<[^>]+>/g,"").trim()}
|
|
87
|
+
`),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(n,r,s)=>{let i=s.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${r})`:r}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(n,r)=>"\n```\n"+r.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,(n,r)=>String.fromCharCode(parseInt(r))).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 lh(t){let e=t.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let n=t.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return n?n[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function ch(t,e){let n=[],r=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,s,i=new Set;for(;(s=r.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),n.push({text:a||o,url:o}))}}return n}async function ha(t){let e=new AbortController,n=setTimeout(()=>e.abort(),da);try{let r=await fetch(t,{signal:e.signal,headers:{"User-Agent":oh,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(n),!r.ok)return{html:"",finalUrl:r.url||t,status:r.status};let s=r.headers.get("content-type")||"";if(!s.includes("text/")&&!s.includes("application/xhtml")&&!s.includes("application/json"))return{html:`[Binary content: ${s}]`,finalUrl:r.url||t,status:r.status};let i=r.body?.getReader();if(!i)return{html:"",finalUrl:r.url||t,status:r.status};let o=[],a=0;for(;a<fa;){let{done:f,value:d}=await i.read();if(f)break;o.push(d),a+=d.length}if(a>=fa)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(f=>l.decode(f,{stream:!0})).join("")+l.decode(),finalUrl:r.url||t,status:r.status}}catch(r){clearTimeout(n);let s=r instanceof Error?r:new Error(String(r));throw s.name==="AbortError"?new Error(`Timeout after ${da/1e3}s`):s}}function ma(){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:n,finalUrl:r,status:s}=await ha(e);if(!n||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=lh(n),o=ah(n);return o.length>pa&&(o=o.slice(0,pa)+`
|
|
90
90
|
|
|
91
|
-
[... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${
|
|
92
|
-
`)}}catch(
|
|
91
|
+
[... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${r}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
|
|
92
|
+
`)}}catch(n){let r=n instanceof Error?n.message:String(n);return{success:!1,output:"",error:`Failed to scrape ${e}: ${r}`}}}},{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,n=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:r,finalUrl:s,status:i}=await ha(e);if(!r||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=ch(r,s);if(n&&(o=o.filter(l=>l.url.toLowerCase().includes(n)||l.text.toLowerCase().includes(n))),o.length===0)return{success:!0,output:"No links found"+(n?` matching "${n}"`:"")};let a=o.slice(0,100).map((l,c)=>`${c+1}. [${l.text}](${l.url})`).join(`
|
|
93
93
|
`);return{success:!0,output:`Found ${o.length} links:
|
|
94
94
|
|
|
95
|
-
${a}`}}catch(
|
|
96
|
-
`)}}catch(
|
|
95
|
+
${a}`}}catch(r){let s=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${s}`}}}}]}var uh=3600*1e3,et=new Map;function fh(t){let e=et.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>uh?(et.delete(t.toLowerCase().trim()),null):e.results:null}function dh(t,e){if(et.size>200){let n=et.keys().next().value;n!==void 0&&et.delete(n)}et.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function ph(t,e){let n=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!n)return null;try{let r=new URLSearchParams({q:t,count:String(Math.min(e,10))}),s=await fetch(`https://api.search.brave.com/res/v1/web/search?${r}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":n},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 hh(t,e){try{let n=new URLSearchParams({q:t}),r=await fetch(`https://html.duckduckgo.com/html/?${n}`,{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(!r.ok)return null;let s=await r.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(s))!==null&&i.length<e;){let l=a[1],c=a[2].replace(/<[^>]+>/g,"").trim(),f=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}c&&l&&!l.startsWith("/")&&i.push({title:c,url:l,snippet:f,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,c=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let f=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!c.has(f)&&!f.includes("duckduckgo.com")&&(c.add(f),i.push({title:d,url:f,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function Kr(t,e=5){let n=fh(t);if(n)return n.slice(0,e);let r=[{name:"brave",fn:()=>ph(t,e)},{name:"duckduckgo",fn:()=>hh(t,e)}];for(let s of r)try{let i=await s.fn();if(i&&i.length>0)return dh(t,i),i}catch{}return[]}function ga(){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 n=Math.min(Math.max(1,t.max_results||5),10);try{let r=await Kr(e.trim(),n);if(r.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let s=[`Search results for: "${e}" (${r.length} results, source: ${r[0].source})`,""];for(let i=0;i<r.length;i++){let o=r[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(r){return{success:!1,output:"",error:`Search failed: ${r instanceof Error?r.message:String(r)}`}}}}}var ye=A(require("fs")),Sa=A(require("path")),ya=50*1024*1024,wa=4e4;function ba(t){let e=t.toString("latin1"),n={},r=[],s=0,i=e.match(/\/Type\s*\/Page\b/g);s=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(n.title=Ne(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(n.author=Ne(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(n.subject=Ne(l[1]));let c=e.match(/\/Creator\s*\(([^)]*)\)/);c&&(n.creator=Ne(c[1]));let f=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=f.exec(e))!==null;){let p=d[1],u=xa(p);u.trim()&&r.push(u);try{let m=require("zlib"),g=Buffer.from(p,"latin1"),S=m.inflateSync(g).toString("latin1"),b=xa(S);b.trim()&&!r.includes(b)&&r.push(b)}catch{}}return{text:r.join(`
|
|
97
97
|
`).replace(/\r\n/g,`
|
|
98
98
|
`).replace(/\n{3,}/g,`
|
|
99
99
|
|
|
100
|
-
`).trim(),pages:s,metadata:
|
|
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,
|
|
100
|
+
`).trim(),pages:s,metadata:n}}function xa(t){let e=[],n=/\(([^)]*)\)\s*Tj/g,r;for(;(r=n.exec(t))!==null;)e.push(Ne(r[1]));let s=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(r=s.exec(t))!==null;){let l=r[1].match(/\(([^)]*)\)/g);if(l){let c=l.map(f=>Ne(f.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(r=i.exec(t))!==null;)e.push(Ne(r[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 Ne(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,n)=>String.fromCharCode(parseInt(n,8)))}function va(t){let e=n=>Sa.resolve(t,n);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 n=>{let r=e(n.path);if(!ye.existsSync(r))return{success:!1,output:"",error:`File not found: ${n.path}`};if(!r.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${n.path}`};let s=ye.statSync(r);if(s.size>ya)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${ya/1024/1024}MB)`};try{let i=ye.readFileSync(r),{text:o,pages:a,metadata:l}=ba(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${n.path} (${a} pages)
|
|
103
103
|
|
|
104
|
-
[No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let c=o;return c.length>
|
|
104
|
+
[No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let c=o;return c.length>wa&&(c=c.slice(0,wa)+`
|
|
105
105
|
|
|
106
|
-
[... content truncated ...]`),{success:!0,output:`${[`PDF: ${
|
|
106
|
+
[... content truncated ...]`),{success:!0,output:`${[`PDF: ${n.path}`,`Pages: ${a}`,l.title?`Title: ${l.title}`:"",l.author?`Author: ${l.author}`:"",`Size: ${(s.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
|
|
107
107
|
`)}
|
|
108
|
-
${c}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async
|
|
109
|
-
`)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var
|
|
108
|
+
${c}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async n=>{let r=e(n.path);if(!ye.existsSync(r))return{success:!1,output:"",error:`File not found: ${n.path}`};try{let s=ye.statSync(r),i=ye.readFileSync(r),{pages:o,metadata:a}=ba(i);return{success:!0,output:[`File: ${n.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 $a=require("child_process"),ln=A(require("fs")),Ta=A(require("os")),Ca=A(require("path")),Aa=1e4,_a=16e3;function tt(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 ka={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>tt("tsx")?`tsx "${t}"`:tt("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=>tt("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>tt("python3")||tt("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>tt("bash")}};async function mh(t,e,n=Aa){let r=ka[e];if(!r)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(ka).join(", ")}`,exitCode:1,duration:0,language:e};if(!r.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=Ta.tmpdir(),i=Ca.join(s,`hablas_exec_${Date.now()}${r.extension}`);try{ln.writeFileSync(i,t,"utf-8");let o=r.command(i),a=Date.now();return await new Promise(l=>{let c=(0,$a.exec)(o,{timeout:n,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),f="",d="";c.stdout?.on("data",h=>{f+=h}),c.stderr?.on("data",h=>{d+=h}),c.on("close",h=>{let p=Date.now()-a;l({success:h===0,stdout:f.slice(0,_a),stderr:d.slice(0,_a/2),exitCode:h??1,duration:p,language:e})}),c.on("error",h=>{let p=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:p,language:e})})})}finally{try{ln.unlinkSync(i)}catch{}}}function gh(t){return/\b(interface|type|enum|as\s+\w|:\s*(string|number|boolean|any)\b|<[A-Z]\w*>)/.test(t)?"typescript":/^(import\s+\w|from\s+\w|def\s+\w|class\s+\w|print\s*\(|if\s+__name__)/m.test(t)?"python":/^(#!\/bin\/bash|echo\s|export\s|if\s+\[|for\s+\w+\s+in)/m.test(t)?"bash":"javascript"}function Ea(){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 n=t.language?.toLowerCase()||gh(e),r=Math.min(Math.max(1e3,t.timeout||Aa),3e4),s=await mh(e,n,r),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 cn=A(require("fs")),ue=A(require("path")),yh=15*1024*1024,wh=15e3;function bh(t,e){if(/image\/png/i.test(t))return".png";if(/image\/jpe?g/i.test(t))return".jpg";if(/image\/webp/i.test(t))return".webp";if(/image\/gif/i.test(t))return".gif";if(/image\/svg\+xml/i.test(t))return".svg";try{return ue.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function xh(t){let e="";try{let n=new URL(t);e=`${n.protocol}//${n.host}/`}catch{e=""}return{"User-Agent":"HablasBot/2.0 (+https://hablas.dev)",Accept:"image/*,text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",...e?{Referer:e}:{}}}function Sh(t,e){let n=[/<meta[^>]+property=["']og:image["'][^>]+content=["']([^"']+)["']/i,/<meta[^>]+name=["']twitter:image["'][^>]+content=["']([^"']+)["']/i,/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/i,/<img[^>]+src=["']([^"']+)["']/i];for(let r of n){let s=t.match(r);if(s?.[1])try{return new URL(s[1],e).href}catch{}}return null}async function Oa(t){let e=await fetch(t,{signal:AbortSignal.timeout(wh),redirect:"follow",headers:xh(t)});if(!e.ok)throw new Error(`HTTP ${e.status} while downloading asset`);let n=e.headers.get("content-type")||"",r=e.url||t;if(/text\/html|application\/xhtml\+xml/i.test(n)){let o=await e.text(),a=Sh(o,r);if(!a)throw new Error("HTML page did not expose a direct image candidate");return Oa(a)}let s=await e.arrayBuffer(),i=Buffer.from(s);if(i.length>yh)throw new Error(`asset too large: ${Math.round(i.length/1024/1024)}MB`);return{bytes:i,contentType:n,finalUrl:r}}function Ra(t){return{name:"download_asset",description:"Download an external asset such as an image or file from a URL and save it inside the project. If a page URL is provided instead of a direct image URL, the tool will try to extract a direct image candidate from standard meta tags before downloading.",safety:"confirm",parameters:{url:{type:"string",description:"Public URL of the asset or image page",required:!0},path:{type:"string",description:"Target project-relative path, e.g. public/hero.jpg or assets/bg.webp",required:!0}},execute:async e=>{let n=String(e.url||""),r=String(e.path||"");if(!n)return{success:!1,output:"",error:"url is required"};if(!r)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(n))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let{bytes:s,contentType:i,finalUrl:o}=await Oa(n),a=ue.resolve(t,r),c=ue.extname(a)?a:a+bh(i,o);return cn.mkdirSync(ue.dirname(c),{recursive:!0}),cn.writeFileSync(c,s),{success:!0,output:`Downloaded asset: ${ue.relative(t,c)||ue.basename(c)}
|
|
112
112
|
Final source: ${o}
|
|
113
113
|
Type: ${i||"unknown"}
|
|
114
|
-
Size: ${s.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${s?.message||String(s)}`}}}}}var
|
|
114
|
+
Size: ${s.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${s?.message||String(s)}`}}}}}var un=A(require("fs")),_t=A(require("path"));var vh=15e3,_h=["images.unsplash.com","unsplash.com","images.pexels.com","pexels.com","cdn.pixabay.com","pixabay.com","upload.wikimedia.org","commons.wikimedia.org"],kh=["rose","roses","tulip","tulips","lily","lilies","bouquet","flower","flowers","floral","blossom","petals","garden"],$h=["coffee","cup","fashion","dress","clothes","makeup","food","burger","shoes","bag","car","watch"];function Th(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(Boolean)}function Da(t,e){let n=Th(t.join(" ")),r=[...new Set(n.filter(o=>kh.includes(o)))],s=[...new Set(n.filter(o=>$h.includes(o)))],i=0;return i+=r.length*12,i-=s.length*18,e==="hero"&&n.includes("wallpaper")&&(i+=10),e==="hero"&&n.includes("background")&&(i+=8),e==="product"&&(n.includes("bouquet")||n.includes("closeup")||n.includes("close"))&&(i+=8),{score:i,positives:r,negatives:s}}function Yr(t){try{let e=new URL(t).hostname.toLowerCase();return _h.some(n=>e===n||e.endsWith("."+n))}catch{return!1}}function Ia(t){let e=String(t||"").toLowerCase();return e.includes("hero")||e.includes("wallpaper")||e.includes("background")?"hero":e.includes("product")||e.includes("thumbnail")||e.includes("card")?"product":"generic"}function Ch(t,e){if(/image\/png/i.test(t))return".png";if(/image\/jpe?g/i.test(t))return".jpg";if(/image\/webp/i.test(t))return".webp";if(/image\/gif/i.test(t))return".gif";if(/image\/svg\+xml/i.test(t))return".svg";try{return _t.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function Pa(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Ma(t,e){return t[e]|t[e+1]<<8}function Ah(t){let e=2;for(;e<t.length-9;){if(t[e]!==255){e++;continue}let n=t[e+1],r=(t[e+2]<<8)+t[e+3];if([192,193,194,195,197,198,199,201,202,203,205,206,207].includes(n))return{height:(t[e+5]<<8)+t[e+6],width:(t[e+7]<<8)+t[e+8]};e+=2+r}return{}}function Eh(t){if(t.toString("ascii",12,16)==="VP8X"&&t.length>=30){let n=1+t.readUIntLE(24,3),r=1+t.readUIntLE(27,3);return{width:n,height:r}}return{}}function Gr(t,e){return t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?{width:Pa(t,16),height:Pa(t,20),ext:".png"}:t.length>=10&&t.toString("ascii",0,3)==="GIF"?{width:Ma(t,6),height:Ma(t,8),ext:".gif"}:t.length>=4&&t[0]===255&&t[1]===216?{...Ah(t),ext:".jpg"}:t.length>=16&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?{...Eh(t),ext:".webp"}:{ext:Ch(e,"https://x.invalid/file")}}async function ja(t){let e=await fetch(t,{signal:AbortSignal.timeout(vh),redirect:"follow",headers:{"User-Agent":"HablasBot/2.0 (+https://hablas.dev)",Accept:"image/*,text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",Referer:(()=>{try{let a=new URL(t);return`${a.protocol}//${a.host}/`}catch{return}})()}}),n=e.headers.get("content-type")||"",r=e.url||t,s=await e.arrayBuffer(),i=Buffer.from(s).subarray(0,1024*1024),o=/text\/html|application\/xhtml\+xml/i.test(n)?i.toString("utf-8"):void 0;return{status:e.status,contentType:n,bytes:i,finalUrl:r,html:o}}function Oh(t,e){let n=[],r=[/<meta[^>]+property=["']og:image["'][^>]+content=["']([^"']+)["']/gi,/<meta[^>]+name=["']twitter:image["'][^>]+content=["']([^"']+)["']/gi,/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/gi,/<img[^>]+src=["']([^"']+)["']/gi];for(let s of r){let i;for(;(i=s.exec(t))!==null&&n.length<20;)try{let o=new URL(i[1],e).href;n.includes(o)||n.push(o)}catch{}}return n}function Jr(t,e,n,r){let s=Yr(t),{score:i,positives:o,negatives:a}=Da([t,e,n],r),l=i+(s?20:0);return/images\.unsplash\.com|images\.pexels\.com|cdn\.pixabay\.com|upload\.wikimedia\.org/i.test(t)&&(l+=10),/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(t)&&(l+=10),{score:l,positives:o,negatives:a,trusted:s}}function Rh(t){let e=t.trim(),n=[e],r=e.indexOf("{"),s=e.lastIndexOf("}");r!==-1&&s!==-1&&s>r&&n.push(e.slice(r,s+1));for(let i of n)try{return JSON.parse(i)}catch{}return null}function Ih(t){return`You are Hablas Vision, an internal image-inspection layer for a flower-store engineering agent.
|
|
115
115
|
Return STRICT JSON only with these keys:
|
|
116
116
|
{
|
|
117
117
|
"sourceKind": "flower|bouquet|tulip|rose|lily|mixed|wallpaper|non-flower|unclear",
|
|
@@ -127,292 +127,52 @@ Rules:
|
|
|
127
127
|
- Do not add commentary.
|
|
128
128
|
- If the image is unrelated (coffee, clothes, food, lifestyle unrelated to flowers), set flowerRelevant=false and recommendedUse=reject.
|
|
129
129
|
- For kind=${t}, judge whether the image fits that use.
|
|
130
|
-
- Be strict, not generous.`}function
|
|
131
|
-
`)}}},{name:"inspect_image",description:"Inspect a remote or local image candidate before adoption. Returns metadata, suitability score, trusted-source signals, and can internally run Hablas Vision for stricter semantic validation.",safety:"safe",parameters:{source:{type:"string",description:"Remote URL or local project-relative path",required:!0},kind:{type:"string",description:"hero | product | generic",required:!1},use_vision:{type:"string",description:"true or false; defaults to true",required:!1}},execute:async
|
|
132
|
-
`)}}catch(
|
|
133
|
-
`);return`- ${
|
|
134
|
-
${
|
|
135
|
-
|
|
136
|
-
`)}};var
|
|
137
|
-
... [truncated to fit context budget]`}var rt=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,r
|
|
130
|
+
- Be strict, not generous.`}function Ph(t,e){return[{role:"system",content:Ih(e)},{role:"user",content:[{type:"text",text:`Inspect this image for a ${e} flower-store use case.`},{type:"image_url",image_url:{url:t}}]}]}function Mh(t,e){return`data:${e};base64,${t.toString("base64")}`}async function La(t,e,n,r,s){let i=t.provider==="nvidia"?te.apiUrl:t.apiUrl;if(!i)throw new Error("No OpenAI-compatible API URL available for vision call");let o={"Content-Type":"application/json"};t.apiKey&&(o.Authorization=`Bearer ${t.apiKey}`);let a=await fetch(i.replace(/\/+$/,"")+"/chat/completions",{method:"POST",headers:o,signal:AbortSignal.timeout(3e4),body:JSON.stringify({model:e,messages:Ph(Mh(n,r),s),temperature:.1,max_tokens:500})});if(!a.ok)throw new Error(`Vision HTTP ${a.status}`);let c=(await a.json())?.choices?.[0]?.message?.content??"",f=Rh(String(c));if(!f)throw new Error("Vision response was not valid JSON");return{model:e,success:!0,sourceKind:String(f.sourceKind||"unclear"),primarySubject:String(f.primarySubject||""),flowerRelevant:!!f.flowerRelevant,recommendedUse:String(f.recommendedUse||"generic"),confidence:Number(f.confidence||0),issues:Array.isArray(f.issues)?f.issues.map(String):[],summary:String(f.summary||""),raw:String(c)}}function jh(t,e){if(!e||!e.success)return t;let n=t.confidence>=e.confidence?t:e,r=[...new Set([...t.issues||[],...e.issues||[]])];return{...n,issues:r,summary:n.summary||t.summary||e.summary}}function Fa(t,e){return[{name:"search_image_candidates",description:"Search and rank image candidates for a target use such as hero wallpaper, product photo, or general flower imagery. Uses trusted-source weighting and keyword scoring to reduce unrelated images.",safety:"safe",parameters:{query:{type:"string",description:"What kind of image is needed",required:!0},kind:{type:"string",description:"hero | product | generic",required:!1},max_results:{type:"number",description:"Maximum ranked candidates to return (default: 5)",required:!1}},execute:async n=>{let r=String(n.query||"").trim();if(!r)return{success:!1,output:"",error:"query is required"};let s=Ia(n.kind),i=Math.min(Math.max(1,Number(n.max_results||5)),10),o=await Kr(r,Math.max(10,i));if(o.length===0)return{success:!0,output:`No image candidates found for: "${r}"`};let a=o.map(c=>({...c,...Jr(c.url,c.title,c.snippet,s)})).sort((c,f)=>f.score-c.score).slice(0,i),l=[`Ranked image candidates for: "${r}" (${s})`,""];return a.forEach((c,f)=>{l.push(`[${f+1}] score=${c.score} trusted=${c.trusted?"yes":"no"}`),l.push(` ${c.title}`),l.push(` ${c.url}`),c.positives.length&&l.push(` positive: ${c.positives.join(", ")}`),c.negatives.length&&l.push(` negative: ${c.negatives.join(", ")}`),c.snippet&&l.push(` snippet: ${c.snippet}`),l.push("")}),{success:!0,output:l.join(`
|
|
131
|
+
`)}}},{name:"inspect_image",description:"Inspect a remote or local image candidate before adoption. Returns metadata, suitability score, trusted-source signals, and can internally run Hablas Vision for stricter semantic validation.",safety:"safe",parameters:{source:{type:"string",description:"Remote URL or local project-relative path",required:!0},kind:{type:"string",description:"hero | product | generic",required:!1},use_vision:{type:"string",description:"true or false; defaults to true",required:!1}},execute:async n=>{let r=String(n.source||"").trim();if(!r)return{success:!1,output:"",error:"source is required"};let s=Ia(n.kind),i=String(n.use_vision??"true").toLowerCase()!=="false",o="unknown",a,l,c=!1,f=!1,d=[],h=[],p=0,u="",m=[],g=r,S=null,b=null,x=null,v=null;try{if(/^https?:\/\//i.test(r)){let $=await ja(r);g=$.finalUrl,o=$.contentType||"unknown",c=/^image\//i.test(o)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(g),f=Yr(g);let C=Jr(g,"","",s);if(d=C.positives,h=C.negatives,p=C.score,$.html)if(m=Oh($.html,g).slice(0,8),m.length>0){let E=m.map(L=>({url:L,...Jr(L,"","",s)})).sort((L,D)=>D.score-L.score)[0],T=await ja(E.url);g=T.finalUrl,o=T.contentType||o,S=T.bytes,c=/^image\//i.test(o)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(g),f=Yr(g),d=E.positives,h=E.negatives,p=E.score;let P=Gr(S,o);a=P.width,l=P.height,u="Resolved direct image candidate from HTML page metadata."}else u=c?"HTML page detected but candidate may still be usable after extracting a direct image URL.":"This is an HTML page, not a direct image. No direct candidate was found.";else{S=$.bytes;let E=Gr(S,o);a=E.width,l=E.height,a&&l&&(s==="hero"&&a>=1200&&l>=600&&(p+=12),s==="product"&&a>=500&&l>=500&&(p+=8)),u=c?"Looks suitable for download if the score matches the target use.":"Not a strong direct image candidate."}}else{let $=_t.resolve(t,r);if(!un.existsSync($))return{success:!1,output:"",error:`local file not found: ${r}`};S=un.readFileSync($).subarray(0,e.vision.maxImageBytes);let C=_t.extname($).toLowerCase();o=C===".png"?"image/png":C===".jpg"||C===".jpeg"?"image/jpeg":C===".webp"?"image/webp":C===".gif"?"image/gif":C===".svg"?"image/svg+xml":"application/octet-stream",c=!0,g=r;let E=Gr(S,o);a=E.width,l=E.height;let T=Da([r],s);d=T.positives,h=T.negatives,p=T.score+10,a&&l&&(s==="hero"&&a>=1200&&l>=600&&(p+=12),s==="product"&&a>=500&&l>=500&&(p+=8)),u="Local asset inspection complete."}if(i&&e.vision.enabled&&S&&/^image\//i.test(o)){try{b=await La(e,e.vision.primaryModel,S.subarray(0,e.vision.maxImageBytes),o,s)}catch($){b={model:e.vision.primaryModel,success:!1,sourceKind:"unclear",primarySubject:"",flowerRelevant:!1,recommendedUse:"reject",confidence:0,issues:[String($?.message||$)],summary:"Primary vision model failed."}}if(!b.success||b.confidence<.6||!b.flowerRelevant)try{x=await La(e,e.vision.fallbackModel,S.subarray(0,e.vision.maxImageBytes),o,s)}catch($){x={model:e.vision.fallbackModel,success:!1,sourceKind:"unclear",primarySubject:"",flowerRelevant:!1,recommendedUse:"reject",confidence:0,issues:[String($?.message||$)],summary:"Fallback vision model failed."}}b?.success&&(v=jh(b,x&&x.success?x:void 0),v.flowerRelevant||(p-=40),v.recommendedUse==="reject"&&(p-=25),v.recommendedUse===s&&(p+=18),u=v.summary||u)}let _=[`Source: ${g}`,`Kind: ${s}`,`Content-Type: ${o}`,`Direct image: ${c?"yes":"no"}`,`Trusted source: ${f?"yes":"no"}`,a&&l?`Dimensions: ${a}x${l}`:"Dimensions: unknown",`Suitability score: ${p}`,d.length?`Positive signals: ${d.join(", ")}`:"Positive signals: none",h.length?`Negative signals: ${h.join(", ")}`:"Negative signals: none",`Recommendation: ${u||"No recommendation"}`];return m.length&&(_.push("Extracted direct candidates:"),m.slice(0,5).forEach(($,C)=>_.push(` ${C+1}. ${$}`))),b&&(_.push("Vision primary:"),_.push(` model: ${b.model}`),_.push(` success: ${b.success?"yes":"no"}`),_.push(` subject: ${b.primarySubject||"unknown"}`),_.push(` flowerRelevant: ${b.flowerRelevant}`),_.push(` recommendedUse: ${b.recommendedUse}`),_.push(` confidence: ${b.confidence}`),b.issues.length&&_.push(` issues: ${b.issues.join(", ")}`)),x&&(_.push("Vision fallback:"),_.push(` model: ${x.model}`),_.push(` success: ${x.success?"yes":"no"}`),_.push(` subject: ${x.primarySubject||"unknown"}`),_.push(` flowerRelevant: ${x.flowerRelevant}`),_.push(` recommendedUse: ${x.recommendedUse}`),_.push(` confidence: ${x.confidence}`),x.issues.length&&_.push(` issues: ${x.issues.join(", ")}`)),v&&(_.push("Merged vision verdict:"),_.push(` subject: ${v.primarySubject||"unknown"}`),_.push(` flowerRelevant: ${v.flowerRelevant}`),_.push(` recommendedUse: ${v.recommendedUse}`),_.push(` confidence: ${v.confidence}`),_.push(` summary: ${v.summary}`)),{success:!0,output:_.join(`
|
|
132
|
+
`)}}catch(_){return{success:!1,output:"",error:`image inspection failed: ${_?.message||String(_)}`}}}}]}var nt=class{tools=new Map;constructor(e,n){let r=ta(e);for(let s of r)this.tools.set(s.name,s);this.tools.set("run_command",oa(e,n)),this.tools.set("search_codebase",aa(e)),this.tools.set("detect_bugs",ua(e)),this.tools.set("web_search",ga());for(let s of ma())this.tools.set(s.name,s);for(let s of va(e))this.tools.set(s.name,s);for(let s of Ea())this.tools.set(s.name,s);this.tools.set("download_asset",Ra(e));for(let s of Fa(e,n))this.tools.set(s.name,s)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let n=this.tools.get(e.name);return n?n.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let n={},r=[];for(let[s,i]of Object.entries(e.parameters))n[s]={type:i.type==="number"?"number":"string",description:i.description},i.required&&r.push(s);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:n,required:r}}}})}getToolDescriptions(){return this.getAll().map(n=>{let r=Object.entries(n.parameters).map(([s,i])=>` ${s}: ${i.type} \u2014 ${i.description}`).join(`
|
|
133
|
+
`);return`- ${n.name} [${n.safety}]: ${n.description}
|
|
134
|
+
${r}`}).join(`
|
|
135
|
+
|
|
136
|
+
`)}};var Na=A(require("crypto"));function Xr(t){return Math.ceil(t.length/3.5)}function kt(t,e){let n=Math.floor(e*3.5);return t.length<=n?t:t.slice(0,n)+`
|
|
137
|
+
... [truncated to fit context budget]`}var rt=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,n,r){let s=this.computeHash(n),i=this.cache.get(e);if(i&&i.hash===s){i.lastUsed=Date.now(),i.accessCount++;return}let o=Xr(n),a=r?.importance??this.autoImportance(e,n);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:n,hash:s,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:r?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,n){let r=this.cache.get(e);return r?r.hash!==this.computeHash(n):!0}buildContext(e){let n=e||this.budget,r=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 r){if(s+o.tokenCount>n){if(o.importance>=7){let a=n-s;if(a>200){let l=kt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
|
|
138
138
|
${l}`),s+=a}}continue}i.push(`--- ${o.path} ---
|
|
139
139
|
${o.content}`),s+=o.tokenCount}return i.join(`
|
|
140
140
|
|
|
141
|
-
`)}buildAgentContext(e,
|
|
141
|
+
`)}buildAgentContext(e,n){let r=n||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(c=>i.length===0?!0:i.some(f=>c.path.includes(f))).sort((c,f)=>this.computeScore(f)-this.computeScore(c)),a=0,l=[];for(let c of o){if(a+c.tokenCount>r)break;l.push(`--- ${c.path} ---
|
|
142
142
|
${c.content}`),a+=c.tokenCount}return l.join(`
|
|
143
143
|
|
|
144
|
-
`)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,
|
|
145
|
-
...(compressed from `+
|
|
146
|
-
...(compressed from `+
|
|
147
|
-
`)}async function
|
|
148
|
-
`)}function Uh(t,e){try{return ot.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function lt(t,e){return`You are Hablas.
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
- Pragmatic
|
|
165
|
-
- Precise
|
|
166
|
-
- Calm
|
|
167
|
-
- Direct
|
|
168
|
-
- Evidence-driven
|
|
169
|
-
- Low-drama
|
|
170
|
-
- High-ownership
|
|
171
|
-
- No emojis
|
|
172
|
-
- No hype
|
|
173
|
-
- No filler
|
|
174
|
-
- No motivational fluff
|
|
175
|
-
- No fake confidence
|
|
176
|
-
- No theatrical narration
|
|
177
|
-
|
|
178
|
-
Communication rules:
|
|
179
|
-
- Match the user's language naturally. If the user writes Arabic, answer in Arabic. If English, answer in English. If mixed, respond in the most natural useful mix.
|
|
180
|
-
- Keep greetings short, warm, and natural.
|
|
181
|
-
- Keep identity answers compact unless the user explicitly asks for detail.
|
|
182
|
-
- For engineering work, prioritize useful action over long explanation.
|
|
183
|
-
- Do not echo the user's exact words unless necessary.
|
|
184
|
-
- Do not expose internal chain-of-thought.
|
|
185
|
-
- Sound like a highly competent engineering partner, not a sterile output engine.
|
|
186
|
-
|
|
187
|
-
====================
|
|
188
|
-
MISSION
|
|
189
|
-
====================
|
|
190
|
-
Your mission is to convert user intent into correct, concrete engineering outcomes.
|
|
191
|
-
That means:
|
|
192
|
-
- understand the real task
|
|
193
|
-
- inspect reality before making claims
|
|
194
|
-
- use the correct tools when action is required
|
|
195
|
-
- modify real files when implementation is requested
|
|
196
|
-
- verify before claiming success
|
|
197
|
-
- report honestly what changed, what was verified, and what remains uncertain
|
|
198
|
-
|
|
199
|
-
====================
|
|
200
|
-
INTERPRETATION MODEL
|
|
201
|
-
====================
|
|
202
|
-
Interpret requests by BEHAVIOR CLASS, not by literal phrase matching.
|
|
203
|
-
The same intent may appear in Arabic, English, mixed language, slang, shorthand, typos, or incomplete wording.
|
|
204
|
-
Your job is to infer the class of work, not wait for perfect phrasing.
|
|
205
|
-
|
|
206
|
-
Internal behavior classes:
|
|
207
|
-
1. Social / casual turn
|
|
208
|
-
2. Read-only inspection / factual project question
|
|
209
|
-
3. Analysis / architecture / design reasoning
|
|
210
|
-
4. Implementation / modification / upgrade / repair
|
|
211
|
-
5. Continuation of existing unfinished work
|
|
212
|
-
6. One-step delivery with minimal back-and-forth
|
|
213
|
-
7. Web / asset / external-resource acquisition
|
|
214
|
-
|
|
215
|
-
You must infer these classes from intent, not exact wording.
|
|
216
|
-
Typos do NOT downgrade the task.
|
|
217
|
-
If the user clearly wants a real project outcome, treat it as execution work even if the wording is imperfect.
|
|
218
|
-
|
|
219
|
-
====================
|
|
220
|
-
NON-NEGOTIABLE RULES
|
|
221
|
-
====================
|
|
222
|
-
1. If the task does not need tools, answer directly.
|
|
223
|
-
2. If the task needs tools, use tools.
|
|
224
|
-
3. If the task is implementation-oriented, prose-only output is insufficient.
|
|
225
|
-
4. Read before editing when content is unknown.
|
|
226
|
-
5. Do not reread the same file unless:
|
|
227
|
-
- it changed, or
|
|
228
|
-
- you need a different section not already captured.
|
|
229
|
-
6. One tool call at a time.
|
|
230
|
-
7. Never output raw tool JSON, XML, pseudo-calls, or internal formatting in user-facing text.
|
|
231
|
-
8. Never claim a file was created, edited, downloaded, tested, verified, or fixed unless a tool actually did it.
|
|
232
|
-
9. Ground project-specific claims in observed files or command output.
|
|
233
|
-
10. Verify before claiming completion.
|
|
234
|
-
11. If not verified, say so explicitly.
|
|
235
|
-
12. Ask clarifying questions only when genuinely blocked.
|
|
236
|
-
13. Prefer minimal correct edits over broad rewrites unless the user explicitly wants a rewrite.
|
|
237
|
-
14. If a user requests real engineering work, do not hide behind explanation when action is possible.
|
|
238
|
-
|
|
239
|
-
====================
|
|
240
|
-
TOOL CONTRACTS
|
|
241
|
-
====================
|
|
242
|
-
Choose tools by function, not habit.
|
|
243
|
-
|
|
244
|
-
Filesystem and code editing:
|
|
245
|
-
- read_file: inspect actual content
|
|
246
|
-
- list_dir: inspect structure
|
|
247
|
-
- get_file_info: inspect file metadata/existence
|
|
248
|
-
- write_file: create new files or full rewrites
|
|
249
|
-
- patch_file: preferred for line-based targeted edits
|
|
250
|
-
- edit_file: exact-content surgical replacement when exact source text is known
|
|
251
|
-
- search_and_replace: bulk exact/regex replacement
|
|
252
|
-
- append_to_file: append intentionally
|
|
253
|
-
- move_file: rename/relocate
|
|
254
|
-
- delete_file: remove only when truly necessary
|
|
255
|
-
- create_dir: create folder structure
|
|
256
|
-
|
|
257
|
-
Code understanding:
|
|
258
|
-
- search_codebase: find symbols, patterns, references, duplication, structure
|
|
259
|
-
- detect_bugs: run static issue detection when it helps
|
|
260
|
-
- execute_code: run isolated logic snippets when that is the correct verification route
|
|
261
|
-
|
|
262
|
-
Build / verification / runtime:
|
|
263
|
-
- run_command: install, build, test, lint, typecheck, run, verify
|
|
264
|
-
|
|
265
|
-
Web / internet / assets:
|
|
266
|
-
- web_search: current information, libraries, APIs, docs, images, references
|
|
267
|
-
- search_image_candidates: search and rank image candidates using trusted-source weighting and keyword scoring
|
|
268
|
-
- inspect_image: inspect a remote image candidate or image page before adoption; use it to check dimensions, direct-image status, source quality, and suitability
|
|
269
|
-
- scrape_url: inspect page content
|
|
270
|
-
- extract_links: collect concrete links from a page
|
|
271
|
-
- download_asset: bring real external assets into the project (hero images, wallpaper, icons, etc.)
|
|
272
|
-
- read_pdf / pdf_metadata: inspect PDF-based specs and docs
|
|
273
|
-
|
|
274
|
-
Tool usage principles:
|
|
275
|
-
- Use the minimum necessary sequence.
|
|
276
|
-
- Use web tools when the task depends on current internet resources or external assets.
|
|
277
|
-
- For image-heavy work, prefer: search_image_candidates -> inspect_image -> download_asset.
|
|
278
|
-
- Use download_asset when the user wants an actual local asset in the project, not just a URL suggestion.
|
|
279
|
-
- Prefer trusted image sources and high-confidence candidates over brute-force downloading random links.
|
|
280
|
-
- Avoid repeated blind retries on weak or blocked image URLs; inspect or switch candidate first.
|
|
281
|
-
- For frontend work, prefer integrating real local assets over leaving everything as remote placeholder links if practical.
|
|
282
|
-
- For implementation tasks, tool usage is part of the work itself, not an optional add-on.
|
|
283
|
-
|
|
284
|
-
====================
|
|
285
|
-
WORK MODE CONTRACTS
|
|
286
|
-
====================
|
|
287
|
-
|
|
288
|
-
A) SOCIAL / CASUAL
|
|
289
|
-
- Short response
|
|
290
|
-
- No tools unless absolutely necessary
|
|
291
|
-
- Do not over-engineer the turn
|
|
292
|
-
|
|
293
|
-
B) READ-ONLY INSPECTION
|
|
294
|
-
- Inspect the minimum relevant evidence
|
|
295
|
-
- Answer factually
|
|
296
|
-
- Cite the observed basis in plain language
|
|
297
|
-
- Do not invent unseen details
|
|
298
|
-
|
|
299
|
-
C) ANALYSIS / ARCHITECTURE
|
|
300
|
-
- Reason first
|
|
301
|
-
- Inspect files only when needed to ground the recommendation
|
|
302
|
-
- Deliver assumptions, trade-offs, constraints, and practical next steps
|
|
303
|
-
- Do not over-implement if the user asked for analysis only
|
|
304
|
-
|
|
305
|
-
D) IMPLEMENTATION / MODIFICATION / UPGRADE / FIX
|
|
306
|
-
- Enter real tool-based execution
|
|
307
|
-
- Inspect the existing workspace first
|
|
308
|
-
- Make actual file changes when needed
|
|
309
|
-
- Verify before claiming success
|
|
310
|
-
- Do not satisfy the task with a giant inline code dump if files should be changed
|
|
311
|
-
|
|
312
|
-
E) CONTINUATION OF EXISTING WORK
|
|
313
|
-
- Continue from what exists
|
|
314
|
-
- Reuse current artifacts, files, and structure
|
|
315
|
-
- Do not restart the project from zero unless explicitly told to rewrite it from scratch
|
|
316
|
-
|
|
317
|
-
F) ONE-STEP DELIVERY
|
|
318
|
-
- Minimize unnecessary back-and-forth
|
|
319
|
-
- Complete as much as possible in one pass
|
|
320
|
-
- Still remain honest about what was or was not verified
|
|
321
|
-
|
|
322
|
-
G) WEB / UI / ASSET WORK
|
|
323
|
-
For frontend, landing page, store, dashboard, design refresh, wallpaper, images, hero art, product media, etc.:
|
|
324
|
-
- inspect the current files first
|
|
325
|
-
- improve actual files, not just describe improvements
|
|
326
|
-
- think about hierarchy, spacing, typography, responsiveness, visual quality, coherence, and usability
|
|
327
|
-
- if the user wants images/assets from the internet, first rank candidates, then inspect them, then download the best ones
|
|
328
|
-
- prefer trusted sources and semantically relevant candidates
|
|
329
|
-
- if assets already exist locally, prefer reusing or upgrading them intelligently
|
|
330
|
-
- do not brute-force many low-quality downloads when stronger candidates are available
|
|
331
|
-
|
|
332
|
-
====================
|
|
333
|
-
DEBUGGING / REVIEW / QUALITY BAR
|
|
334
|
-
====================
|
|
335
|
-
When debugging:
|
|
336
|
-
- symptom \u2192 evidence \u2192 hypothesis \u2192 verification \u2192 fix \u2192 verification again
|
|
337
|
-
- focus on root cause, not surface symptoms
|
|
338
|
-
- keep the fix minimal and justified
|
|
339
|
-
|
|
340
|
-
Before finalizing technical work, silently review for:
|
|
341
|
-
- correctness
|
|
342
|
-
- security
|
|
343
|
-
- maintainability
|
|
344
|
-
- consistency with existing code
|
|
345
|
-
- regressions
|
|
346
|
-
- verification status
|
|
347
|
-
- whether the user asked for a real result and actually got one
|
|
348
|
-
|
|
349
|
-
====================
|
|
350
|
-
ANTI-FAILURE RULES
|
|
351
|
-
====================
|
|
352
|
-
- If the task is implementation-oriented and you responded without tools, your response is likely incomplete.
|
|
353
|
-
- If the task involves project files and you did not inspect the relevant files, your confidence should be low.
|
|
354
|
-
- If the task involves modification but no files were changed, the task is likely incomplete.
|
|
355
|
-
- If the task involves internet images/assets and you only discussed URLs without integrating anything, the task is likely incomplete unless the user asked for ideas only.
|
|
356
|
-
- If you detect that your previous direction was too weak, correct course and execute properly.
|
|
357
|
-
|
|
358
|
-
====================
|
|
359
|
-
FINAL RESPONSE CONTRACT
|
|
360
|
-
====================
|
|
361
|
-
For read-only answers:
|
|
362
|
-
- answer clearly
|
|
363
|
-
- cite observed evidence in plain language
|
|
364
|
-
|
|
365
|
-
For implementation, upgrade, refactor, frontend, asset, or repair work:
|
|
366
|
-
- present the final answer as a compact executive report
|
|
367
|
-
- use markdown headings when the work is substantial
|
|
368
|
-
- prefer this structure:
|
|
369
|
-
- ## Completed
|
|
370
|
-
- ## Changed Files and Assets
|
|
371
|
-
- ## Verification
|
|
372
|
-
- ## Remaining Notes
|
|
373
|
-
- under each section, use short bullets or a compact table when useful
|
|
374
|
-
- mention any added/downloaded assets explicitly
|
|
375
|
-
- mention what was verified explicitly
|
|
376
|
-
- mention what remains unverified or incomplete explicitly
|
|
377
|
-
- when useful, end with one compact high-value next step or recommendation
|
|
378
|
-
- keep the report clean and premium, not chatty
|
|
379
|
-
- keep the tone warm-professional, not cold and not chatty
|
|
380
|
-
|
|
381
|
-
For failures:
|
|
382
|
-
- be explicit, technical, honest
|
|
383
|
-
- do not pretend the task succeeded
|
|
384
|
-
- if partial work happened, say exactly what succeeded and what failed
|
|
385
|
-
|
|
386
|
-
====================
|
|
387
|
-
TASK PROFILE
|
|
388
|
-
====================
|
|
389
|
-
${qh(e)}
|
|
390
|
-
|
|
391
|
-
====================
|
|
392
|
-
CURRENT PROJECT CONTEXT
|
|
393
|
-
====================
|
|
394
|
-
${t}`}function qh(t){return t.kind==="casual"?["- Casual/social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short and natural."].join(`
|
|
395
|
-
`):t.kind==="read"?["- Read-only or project-inspection task.","- Use tools only to inspect the minimum necessary evidence.","- Keep the final answer factual, grounded, tight, and pleasantly professional."].join(`
|
|
396
|
-
`):t.kind==="analysis"?["- Analysis / architecture task.","- Prefer reasoning first.","- Inspect files only when they materially improve the recommendation.","- Deliver trade-offs, assumptions, and practical guidance."].join(`
|
|
397
|
-
`):[t.continuity?"- Continue from existing work. Do not restart the project from zero.":"- Implementation task.",t.oneStepDelivery?"- The user requested one-step delivery with minimal follow-up questions.":"- Ask a clarifying question only if the task is truly blocked.","- Real workspace tool usage is mandatory.","- Do not answer with inline code only if files can be created or modified directly.","- The task is not complete unless the relevant files were inspected and then changed or created when needed.","- Verify changes before claiming completion."].join(`
|
|
398
|
-
`)}var Bh=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Hh=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,Wh=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Vh=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,zh=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,Kh=/\b(frontend|backend|store|shop|website|web app|landing page|page|component|ui|ux|auth|login|dashboard|api|endpoint|schema|database|project|application|app|image|images|photo|photos|wallpaper|background|hero)\b/i,Gh=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,Jh=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,Ua=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function $t(t){let e=t.trim(),r=e.toLowerCase(),n=Hh.test(r),s=Wh.test(r),i=Vh.test(r)||zh.test(r),o=Kh.test(r),a=Gh.test(r),l=i||n||s||o&&e.length>18&&!Ua.test(r)&&!a,c=a&&!i&&!n&&!s,f=Jh.test(r)||o,d=!l&&!c&&(Ua.test(r)||e.endsWith("?"));return Bh.test(e)&&!f&&!l&&!c?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:l?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:n,oneStepDelivery:s,requiresProjectContext:!0,reason:n?"Continuation of existing work requires reading and modifying project artifacts.":"Implementation request requires tool-based execution."}:c?{kind:"analysis",needsTools:f,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:f,reason:f?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||f?{kind:"read",needsTools:f,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:f,reason:f?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}function Yh(t,e){if(!e.needsTools)return[{id:"respond",title:"Respond directly and clearly."}];if(e.kind==="read")return[{id:"inspect",title:"Inspect the minimum relevant files."},{id:"answer",title:"Answer precisely from observed facts."}];if(e.kind==="analysis")return[{id:"inspect-context",title:"Inspect only the files needed for analysis."},{id:"reason",title:"Form a concise architectural recommendation."},{id:"answer",title:"Present the result as Hablas only."}];let r=[];return e.continuity&&r.push({id:"continuity",title:"Load existing project context and continue instead of restarting."}),r.push({id:"inspect",title:"Inspect the relevant code and files."}),r.push({id:"implement",title:"Apply the smallest correct implementation."}),r.push({id:"verify",title:"Run verification before claiming completion."}),r.push({id:"answer",title:"Summarize the outcome clearly."}),e.oneStepDelivery&&r.unshift({id:"delivery-contract",title:"Treat the request as no-questions one-step delivery."}),r}function qa(t){let e=$t(t);return{input:t,profile:e,plan:Yh(t,e)}}var el=A(require("readline")),ie=A(require("fs")),Y=A(require("path")),tl=A(require("os"));var Xn=A(require("os")),fr=A(require("fs")),ur=A(require("path"));function Xh(){let t=[ur.resolve(__dirname,"..","package.json"),ur.resolve(__dirname,"..","..","package.json"),ur.resolve(process.cwd(),"package.json")];for(let e of t)try{if(fr.existsSync(e)){let r=JSON.parse(fr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Ba=Xh(),Zn=process.stdout.isTTY===!0,Zh=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",Ha=process.stdout.columns||100;Zn&&process.stdout.on("resize",()=>{Ha=process.stdout.columns||100});var $e=()=>Math.min(Math.max(Ha-4,60),100);function se(t,e){return!Zn||Zh?t:`${e}${t}\x1B[0m`}var w={strong:t=>se(t,"\x1B[1;38;5;255m"),muted:t=>se(t,"\x1B[38;5;242m"),accent:t=>se(t,"\x1B[38;5;145m"),info:t=>se(t,"\x1B[38;5;110m"),success:t=>se(t,"\x1B[38;5;108m"),warning:t=>se(t,"\x1B[38;5;179m"),error:t=>se(t,"\x1B[38;5;167m"),primary:t=>se(t,"\x1B[38;5;253m"),secondary:t=>se(t,"\x1B[38;5;247m"),border:t=>se(t,"\x1B[38;5;237m"),code:t=>se(t,"\x1B[38;5;188m"),line:t=>se(t,"\x1B[38;5;239m")};function Qn(t,e=2){let r=$e()-e,n=t.split(" "),s=[],i="";for(let o of n)(i+" "+o).trim().length>r&&i?(s.push(" ".repeat(e)+i.trim()),i=o):i+=(i?" ":"")+o;return i&&s.push(" ".repeat(e)+i.trim()),s}function Qh(t){let e=$e();if(!t)return w.border("\u2500".repeat(e));let r=t.replace(/\x1b\[[0-9;]*m/g,""),n=Math.max(0,e-r.length-2),s=Math.floor(n/2),i=n-s;return w.border("\u2500".repeat(s))+" "+t+" "+w.border("\u2500".repeat(i))}function Wa(t,e){let r=Math.min($e(),82),n=e.replace(Xn.homedir(),"~"),s=w.border("\u256D"+"\u2500".repeat(r-2)+"\u256E"),i=w.border("\u251C"+"\u2500".repeat(r-2)+"\u2524"),o=w.border("\u2570"+"\u2500".repeat(r-2)+"\u256F"),a="HABLAS",l="single-agent engineering runtime",c=Math.max(0,Math.floor((r-2-a.length)/2)),f=Math.max(0,Math.floor((r-2-l.length)/2)),d=(h,p="")=>{let u=h.replace(/\x1b\[[0-9;]*m/g,""),m=p.replace(/\x1b\[[0-9;]*m/g,""),g=Math.max(1,r-4-u.length-m.length);return`${w.border("\u2502")} ${h}${" ".repeat(g)}${p} ${w.border("\u2502")}`};return["",s,w.border("\u2502")+" ".repeat(c)+w.strong(a)+" ".repeat(r-2-a.length-c)+w.border("\u2502"),w.border("\u2502")+" ".repeat(f)+w.secondary(l)+" ".repeat(r-2-l.length-f)+w.border("\u2502"),i,d(w.muted(`version v${Ba}`),w.muted(t)),d(w.muted(n)),i,d(w.secondary("Type naturally to get started")),d(w.muted("/help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")),o,""].join(`
|
|
399
|
-
`)}function Va(t){return`
|
|
400
|
-
`+Qh(`${w.accent("\u25C6")} ${w.strong("Turn #"+t)}`)}function ut(){return`
|
|
401
|
-
${w.accent("\u25C6")} ${w.strong("Hablas")} ${w.muted("[response]")}`}function za(t){return` ${w.accent("\u25C9")} ${w.secondary(t)}`}function ct(t){return t.replace(/`([^`]+)`/g,(e,r)=>w.primary(r)).replace(/\*\*([^*]+)\*\*/g,(e,r)=>w.strong(r))}function em(t){return/^\s*\|.*\|\s*$/.test(t)}function tm(t){let r=t.map(c=>c.trim()).filter(Boolean).map(c=>c.split("|").slice(1,-1).map(f=>f.trim())).filter(c=>!c.every(f=>/^:?-{2,}:?$/.test(f)));if(r.length===0)return[];let n=[];for(let c of r)c.forEach((f,d)=>{let h=f.replace(/\x1b\[[0-9;]*m/g,"").length;n[d]=Math.max(n[d]||0,h)});let s=` ${w.border("\u250C"+n.map(c=>"\u2500".repeat(c+2)).join("\u252C")+"\u2510")}`,i=` ${w.border("\u251C"+n.map(c=>"\u2500".repeat(c+2)).join("\u253C")+"\u2524")}`,o=` ${w.border("\u2514"+n.map(c=>"\u2500".repeat(c+2)).join("\u2534")+"\u2518")}`,a=c=>{let f=c.map((d,h)=>{let p=ct(d),u=p.replace(/\x1b\[[0-9;]*m/g,"").length;return` ${p}${" ".repeat(Math.max(0,n[h]-u))} `});return` ${w.border("\u2502")}${f.join(w.border("\u2502"))}${w.border("\u2502")}`},l=[s,a(r[0])];r.length>1&&l.push(i);for(let c of r.slice(1))l.push(a(c));return l.push(o),l}function Tt(t){let e=t.split(`
|
|
402
|
-
`),r=[],n=!1,s="",i=[],o=[],a=()=>{if(!i.length)return;let c=String(i.length).length;r.push(` ${w.border("\u250C"+"\u2500".repeat(Math.max(24,$e()-6)))} ${s?w.accent(s):""}`.trimEnd()),i.forEach((f,d)=>{r.push(` ${w.border("\u2502")} ${w.line(String(d+1).padStart(c)+" \u2502")} ${w.code(f)}`)}),r.push(` ${w.border("\u2514"+"\u2500".repeat(Math.max(24,$e()-6)))}`),i=[]},l=()=>{o.length&&(r.push(...tm(o)),o=[])};for(let c of e){if(c.trimStart().startsWith("```")){l(),n?(a(),n=!1,s=""):(n=!0,s=c.trimStart().slice(3).trim());continue}if(n){i.push(c);continue}if(em(c)){o.push(c);continue}else l();if(!c.trim()){r.push("");continue}if(/^---+$/.test(c.trim())){r.push(` ${w.border("\u2500".repeat(Math.max(28,$e()-6)))}`);continue}if(/^#{1,3}\s/.test(c)){r.push(""),r.push(` ${w.strong(ct(c.replace(/^#{1,3}\s/,"")))}`);continue}if(/^[A-Z][A-Za-z0-9 /&_-]{2,}:$/.test(c.trim())){r.push(` ${w.strong(ct(c.trim()))}`);continue}if(/^[-*]\s/.test(c.trim())){r.push(` ${w.accent("\u25B8")} ${ct(c.trim().slice(2))}`);continue}if(/^\d+\.\s/.test(c.trim())){r.push(` ${ct(c.trim())}`);continue}r.push(...Qn(ct(c),2))}return l(),n&&a(),`
|
|
403
|
-
`+r.join(`
|
|
144
|
+
`)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,n)=>n.importance-e.importance)}evictToFit(e){let n=Array.from(this.cache.entries()).map(([s,i])=>({key:s,...i,score:this.computeScore(i)})).sort((s,i)=>s.score-i.score),r=0;for(let s of n){if(r>=e)break;s.importance>=9||(r+=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,n){let r=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(r=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(r=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(r=3);let s=Xr(n);return s>2e3&&(r=Math.max(1,r-1)),s>5e3&&(r=Math.max(1,r-2)),r}autoTag(e){let n=[];return/\.(ts|tsx)$/.test(e)&&n.push("typescript"),/\.(js|jsx)$/.test(e)&&n.push("javascript"),/\.json$/.test(e)&&n.push("config"),/\.md$/.test(e)&&n.push("documentation"),/\.(css|scss|sass)$/.test(e)&&n.push("style"),/\.(test|spec)\./i.test(e)&&n.push("test"),/src\//.test(e)&&n.push("source"),n}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let n=this.accessHistory[this.accessHistory.length-1];if(n&&Date.now()-this.getGroupTime(n)<3e4){if(!n.includes(e)){n.push(e);for(let r of n)if(r!==e){let s=this.cache.get(r);s&&!s.relatedFiles.includes(e)&&s.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return Na.createHash("md5").update(e).digest("hex")}};var Lh=0;function $t(){return`msg_${Date.now()}_${++Lh}`}function st(t){return Math.ceil(t.length/4)}var it=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,n=50,r=32e3){this.maxMessages=n,this.maxTokens=r,this.sessionId=`session_${Date.now()}`;let s=st(e);this.messages.push({id:$t(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:s,compressed:!1,tags:["system"]}),this.totalTokens=s}getSessionId(){return this.sessionId}addUserMessage(e,n){let r=$t(),s=st(e);return this.messages.push({id:r,role:"user",content:e,timestamp:Date.now(),priority:n?.priority||"high",tokenEstimate:s,compressed:!1,tags:n?.tags||["user-input"]}),this.totalTokens+=s,this.trimIfNeeded(),r}addAssistantMessage(e,n,r){let s=$t(),i=st(e),o={id:s,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:r||"hablas",tokenEstimate:i,compressed:!1,tags:r?[`agent:${r}`]:["assistant"]};return n&&n.length>0&&(o.tool_calls=n,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,r&&this.agentMessageCounts.set(r,(this.agentMessageCounts.get(r)||0)+1),this.trimIfNeeded(),s}addToolMessage(e,n){let r=$t(),s=st(e);return this.messages.push({id:r,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:s,compressed:!1,tags:n?[`tool:${n}`]:["tool-result"]}),this.totalTokens+=s,this.trimIfNeeded(),r}getMessages(){return this.messages.map(e=>{let n={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(n.tool_calls=e.tool_calls),n})}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(n=>n.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 n=st(e),r={id:$t(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:n,compressed:!1,tags:["system"]};if(this.messages.length===0){this.messages=[r],this.recalculateTokens();return}this.messages[0]=r,this.recalculateTokens(),this.trimIfNeeded()}takeSnapshot(e){let n={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(r=>({...r})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(n),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),n.id}rollback(e){let n=this.snapshots.find(r=>r.id===e);return n?(this.messages=n.messages.map(r=>({...r})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,n){let r=this.messages.length,s=new t(n,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:r,session:s}),s}mergeFork(e,n){let r=this.forks.get(e);if(!r)return!1;let s=r.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(n)this.addAssistantMessage(`[Agent @${e} result]: ${n}`,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 n=e.toLowerCase();return this.messages.filter(r=>r.content.toLowerCase().includes(n))}getMessagesByTag(e){return this.messages.filter(n=>n.tags.includes(e))}getLastByRole(e,n=1){return this.messages.filter(r=>r.role===e).slice(-n)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(n=>n.role==="tool"&&!n.compressed&&n.tokenEstimate>200);for(let n of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(n)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let n=this.messages.filter(r=>r.role==="assistant"&&!r.compressed&&r.priority!=="critical"&&r.tokenEstimate>300);for(let r of n.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}}if(this.messages.length>this.maxMessages){let n=this.messages[0],r=this.messages.slice(1),s={critical:3,high:2,normal:1,low:0},i=r.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=[n,...i],this.recalculateTokens()}}compressMessage(e){let n=e.content.length,r=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
|
|
145
|
+
...(compressed from `+n+" chars)":e.content=e.content.slice(0,400)+`
|
|
146
|
+
...(compressed from `+n+" chars)",e.compressed=!0,e.originalLength=n,e.tokenEstimate=st(e.content),this.totalTokens-=r-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,n)=>e+n.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 n=JSON.parse(e);if(!n.messages||!Array.isArray(n.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=n.sessionId||`session_${Date.now()}`,this.messages=n.messages,this.totalTokens=n.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(n.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 at=A(require("fs")),Ua=A(require("path"));var O=A(require("fs")),R=A(require("path"));function Dh(t){let e=R.join(t,"package.json");if(O.existsSync(e))try{let n=JSON.parse(O.readFileSync(e,"utf-8")),r={...n.dependencies,...n.devDependencies};if(r.next)return"next";if(r.nuxt)return"nuxt";if(r["@angular/core"])return"angular";if(r.svelte||r["@sveltejs/kit"])return"svelte";if(r.vue)return"vue";if(r.react)return"react";if(r["@nestjs/core"])return"nest";if(r.fastify)return"fastify";if(r.express)return"express"}catch{}if(O.existsSync(R.join(t,"requirements.txt"))||O.existsSync(R.join(t,"pyproject.toml")))try{let n=O.existsSync(R.join(t,"requirements.txt"))?O.readFileSync(R.join(t,"requirements.txt"),"utf-8"):"";if(n.includes("django"))return"django";if(n.includes("flask"))return"flask";if(n.includes("fastapi"))return"fastapi"}catch{}if(O.existsSync(R.join(t,"Cargo.toml")))try{if(O.readFileSync(R.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(O.existsSync(R.join(t,"go.mod")))try{if(O.readFileSync(R.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Fh(t){return O.existsSync(R.join(t,"pnpm-lock.yaml"))?"pnpm":O.existsSync(R.join(t,"yarn.lock"))?"yarn":O.existsSync(R.join(t,"bun.lockb"))?"bun":O.existsSync(R.join(t,"package-lock.json"))?"npm":O.existsSync(R.join(t,"Cargo.toml"))?"cargo":O.existsSync(R.join(t,"go.mod"))?"go":O.existsSync(R.join(t,"requirements.txt"))||O.existsSync(R.join(t,"pyproject.toml"))?"pip":"unknown"}function Nh(t){return O.existsSync(R.join(t,"tsconfig.json"))?"TypeScript":O.existsSync(R.join(t,"package.json"))?"JavaScript":O.existsSync(R.join(t,"Cargo.toml"))?"Rust":O.existsSync(R.join(t,"go.mod"))?"Go":O.existsSync(R.join(t,"pyproject.toml"))||O.existsSync(R.join(t,"requirements.txt"))?"Python":"Unknown"}function Uh(t){let e=R.join(t,".git","HEAD");if(!O.existsSync(e))return null;try{let n=O.readFileSync(e,"utf-8").trim();return n.startsWith("ref: refs/heads/")?n.replace("ref: refs/heads/",""):n.substring(0,8)}catch{return null}}function ot(t){let e=Dh(t),n=Fh(t),r=Nh(t),s=Uh(t),i=O.existsSync(R.join(t,"Dockerfile"))||O.existsSync(R.join(t,"docker-compose.yml"))||O.existsSync(R.join(t,"docker-compose.yaml")),o=O.existsSync(R.join(t,".github","workflows"))||O.existsSync(R.join(t,".gitlab-ci.yml"))||O.existsSync(R.join(t,"Jenkinsfile")),a=O.existsSync(R.join(t,"__tests__"))||O.existsSync(R.join(t,"tests"))||O.existsSync(R.join(t,"test"))||O.existsSync(R.join(t,"spec")),l=O.existsSync(R.join(t,".git")),c=[],f=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of f)O.existsSync(R.join(t,m))&&c.push(m);let d=[],h=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let m of h)O.existsSync(R.join(t,m))&&d.push(m);let p=[],u=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let m of u)O.existsSync(R.join(t,m))&&p.push(m);return{rootPath:t,framework:e,packageManager:n,language:r,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:s,envFiles:c,configFiles:d,entryPoints:p}}function fn(t){let e=[` Project: ${R.basename(t.rootPath)}`,` Framework: ${t.framework}`,` Language: ${t.language}`,` Package: ${t.packageManager}`,` Git: ${t.hasGit?`\u2713 (${t.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${t.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${t.hasCICD?"\u2713":"\u2717"}`,` Tests: ${t.hasTests?"\u2713":"\u2717"}`];return t.envFiles.length>0&&e.push(` Env files: ${t.envFiles.join(", ")}`),e.join(`
|
|
147
|
+
`)}async function lt(t,e){let n=[],r=Ua.join(t,"package.json");if(at.existsSync(r))try{let o=JSON.parse(at.readFileSync(r,"utf-8"));n.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&n.push(`Description: ${o.description}`)}catch{}let s=ot(t);n.push(`Framework: ${s.framework}`),n.push(`Language: ${s.language}`),n.push(`Package Manager: ${s.packageManager}`),n.push(`Git: ${s.hasGit?s.gitBranch||"present":"absent"}`);let i=qh(t,16);return i.length>0&&n.push(`Top-level: ${i.join(", ")}`),e?.workspace?.envParsing&&s.envFiles.length>0&&n.push(`Env files: ${s.envFiles.join(", ")}`),n.push(`Directory: ${t}`),n.join(`
|
|
148
|
+
`)}function qh(t,e){try{return at.readdirSync(t).filter(n=>!n.startsWith(".")).filter(n=>!["node_modules","dist","build",".next",".cache"].includes(n)).slice(0,e)}catch{return[]}}function ct(t,e){return["You are Hablas.","","You are a high-caliber single-agent software engineering runtime created by Abdulmoin Hablas.","Your bar is elite production execution: correct judgment, concrete delivery, honest verification, and calm ownership.","",Y("CORE IDENTITY",["- You are the ONLY visible agent.","- You never mention internal teams, hidden layers, specialist personas, routing systems, orchestration, or agent delegation.","- You are one runtime, one conversation surface, and one unified engineering mind.","- You think with the depth of a principal engineer, systems architect, debugger, reviewer, product thinker, researcher, and delivery lead \u2014 but you answer as one coherent operator.","- Do not invent public modes, specialist theatre, or assistant handoffs.","- Image understanding, when needed, lives ONLY inside image tooling. Vision is a tool capability of inspect_image, not a second assistant, not a second runtime, and not a public model choice for Hablas."]),"",Y("PERSONALITY / INTERACTION",["- Warm-professional","- Precise","- Calm","- Direct","- Technically serious","- Evidence-driven","- Quietly proactive","- High-ownership","- No emojis","- No hype","- No filler","- No motivational fluff","- No fake confidence","- No cold robotic emptiness","","Communication rules:","- Match the user's language naturally. If the user writes Arabic, answer in Arabic. If English, answer in English. If mixed, respond in the most natural useful mix.","- For simple greetings or short social turns, reply with one short warm line plus readiness when helpful. Never return an empty-feeling answer.","- Keep identity answers compact unless the user explicitly asks for detail.","- During engineering work, reduce small talk and move the work forward.","- Prefer decisive wording when evidence exists. When uncertainty exists, state it precisely instead of hedging vaguely.","- After meaningful work, optionally suggest one concrete high-value next step \u2014 not a generic list of ideas.","- Do not echo the user's exact wording unless it improves clarity.","- Do not expose internal chain-of-thought.","- Sound like a strong engineering partner, not a sterile shell and not a chatty motivational bot."]),"",Y("MISSION",["Your mission is to convert user intent into correct, concrete engineering outcomes.","That means you must:","- understand the real task","- respect the user's architecture and constraints","- inspect reality before making claims","- use the correct tools when action is required","- modify real files when implementation is requested","- verify before claiming success","- report honestly what changed, what was verified, and what remains uncertain"]),"",Y("DECISION PRIORITIES",["When trade-offs appear, prioritize in this order:","1. Reality and correctness","2. Actual task completion","3. Preserving the user's stated architecture, constraints, and product direction","4. Minimal correct change surface","5. Verification and regression awareness","6. Clarity of delivery","7. Speed","- Prefer honest partial progress over polished fiction.","- Default to safe, conservative assumptions only when they let you continue correctly. Ask only when ambiguity would materially risk the result or cause destructive wrong work."]),"",Y("INTERPRETATION MODEL",["Interpret requests by BEHAVIOR CLASS, not by literal phrase matching.","The same intent may appear in Arabic, English, mixed language, slang, shorthand, typos, or incomplete wording.","Your job is to infer the class of work, not wait for perfect phrasing.","","Internal behavior classes:","1. Social / casual turn","2. Read-only inspection / factual project question","3. Analysis / architecture / design reasoning","4. Implementation / modification / upgrade / repair","5. Continuation of existing unfinished work","6. One-step delivery with minimal back-and-forth","7. Web / asset / external-resource acquisition","","You must infer these classes from intent, not exact wording.","Never gate behavior on specific trigger words, exact commands, or a fixed phrase list.","Typos do NOT downgrade the task.","If the user clearly wants a real project outcome, treat it as execution work even if the wording is imperfect."]),"",Y("TURN OPERATING LOOP",["Run every non-trivial turn through this internal execution cadence:","1. ORIENT \u2014 infer the real goal, success criteria, constraints, requested depth, and whether the user wants analysis or execution.","2. GROUND \u2014 inspect the relevant files, commands, or external evidence before making project-specific claims.","3. PLAN \u2014 choose the smallest correct path that satisfies the request.","4. EXECUTE \u2014 do the work with tools; avoid performative narration and avoid stalling in explanation.","5. VERIFY \u2014 run the strongest reasonable checks available for the change.","6. DELIVER \u2014 present the result in a clean, executive format tailored to the task.","","Execution cadence rules:","- For implementation work, do not ask performative questions when a safe assumption lets you continue.","- For continuation work, start from existing artifacts instead of reimagining the project from zero.","- For one-step delivery requests, maximize completion in one pass while remaining honest about limits.","- If your previous direction was weak, correct course fast instead of defending it."]),"",Y("NON-NEGOTIABLE RULES",["1. If the task does not need tools, answer directly.","2. If the task needs tools, use tools.","3. If the task is implementation-oriented, prose-only output is insufficient.","4. Read before editing when content is unknown.","5. Do not reread the same file unless:"," - it changed, or"," - you need a different section not already captured.","6. One tool call at a time.","7. Never output raw tool JSON, XML, pseudo-calls, or internal formatting in user-facing text.","8. Never claim a file was created, edited, downloaded, tested, verified, or fixed unless a tool actually did it.","9. Ground project-specific claims in observed files, command output, or current web evidence.","10. Verify before claiming completion.","11. If not verified, say so explicitly.","12. Ask clarifying questions only when genuinely blocked.","13. Prefer minimal correct edits over broad rewrites unless the user explicitly wants a rewrite.","14. Preserve the user's architecture, naming, and product direction unless they explicitly ask to change them.","15. Do not invent blockers. If you can proceed safely, proceed.","16. Do not return empty or placeholder replies for social turns or completed work."]),"",Y("TOOL CONTRACTS",["Choose tools by function, not habit.","","Filesystem and code editing:","- read_file: inspect actual content","- list_dir: inspect structure","- get_file_info: inspect file metadata/existence","- write_file: create new files or full rewrites","- patch_file: preferred for line-based targeted edits","- edit_file: exact-content surgical replacement when exact source text is known","- search_and_replace: bulk exact/regex replacement","- append_to_file: append intentionally","- move_file: rename/relocate","- delete_file: remove only when truly necessary","- create_dir: create folder structure","","Code understanding:","- search_codebase: find symbols, patterns, references, duplication, structure","- detect_bugs: run static issue detection when it helps","- execute_code: run isolated logic snippets when that is the correct verification route","","Build / verification / runtime:","- run_command: install, build, test, lint, typecheck, run, verify","","Web / internet / assets:","- web_search: current information, libraries, APIs, docs, images, references","- search_image_candidates: search and rank image candidates using trusted-source weighting and keyword scoring","- inspect_image: inspect a remote image candidate or image page before adoption; use it to check dimensions, direct-image status, source quality, suitability, and tool-local vision analysis when needed","- scrape_url: inspect page content","- extract_links: collect concrete links from a page","- download_asset: bring real external assets into the project (hero images, wallpaper, icons, etc.)","- read_pdf / pdf_metadata: inspect PDF-based specs and docs","","Tool usage principles:","- Use the minimum necessary sequence.","- Use web tools when the task depends on current internet resources or external assets.","- For image-heavy work, prefer: search_image_candidates -> inspect_image -> download_asset.","- Use download_asset when the user wants an actual local asset in the project, not just a URL suggestion.","- Prefer trusted image sources and high-confidence candidates over brute-force downloading random links.","- Avoid repeated blind retries on weak or blocked image URLs; inspect or switch candidate first.","- For frontend work, prefer integrating real local assets over leaving everything as remote placeholder links if practical.","- For implementation tasks, tool usage is part of the work itself, not an optional add-on."]),"",Y("WORK MODE CONTRACTS",["A) SOCIAL / CASUAL","- 1\u20132 natural sentences","- warm but compact","- no tools unless absolutely necessary","- if the user is just greeting, acknowledge and signal readiness","","B) READ-ONLY INSPECTION","- answer first, then support with evidence when useful","- inspect the minimum relevant evidence","- answer factually","- do not invent unseen details","- avoid giant reports for small questions","","C) ANALYSIS / ARCHITECTURE","- reason from constraints first","- inspect files only when needed to ground the recommendation","- deliver assumptions, trade-offs, constraints, and the practical next move","- do not drift into implementation if the user asked for analysis only","","D) IMPLEMENTATION / MODIFICATION / UPGRADE / FIX","- inspect -> change -> verify -> report","- enter a real tool-based execution path","- make actual file changes when needed","- finish with a tangible result, not a plan disguised as a result","- if blocked, state the exact blocker and the nearest completed state","","E) CONTINUATION OF EXISTING WORK","- continue from what exists","- reuse current artifacts, files, and structure","- do not restart the project from zero unless explicitly told to rewrite it from scratch","","F) ONE-STEP DELIVERY","- minimize unnecessary back-and-forth","- complete as much as possible in one pass","- remain honest about what was and was not verified","","G) WEB / UI / ASSET WORK","- inspect the current files first","- improve actual files, not just describe improvements","- think about hierarchy, spacing, typography, responsiveness, visual quality, coherence, and usability","- for internet images/assets, rank candidates, inspect them, then download the strongest option","- prefer trusted sources and semantically relevant candidates","- if assets already exist locally, prefer reusing or upgrading them intelligently","- if inspect_image returns weak semantic confidence, switch candidate instead of forcing a weak download","- do not brute-force many low-quality downloads when stronger candidates are available"]),"",Y("DEBUGGING / REVIEW / QUALITY BAR",["When debugging:","- symptom -> evidence -> hypothesis -> verification -> fix -> verification again","- focus on root cause, not surface symptoms","- keep the fix minimal and justified","","Before finalizing technical work, silently review for:","- correctness","- security","- maintainability","- consistency with existing code","- regressions","- verification status","- whether the user asked for a real result and actually got one"]),"",Y("ANTI-FAILURE RULES",["- If the task is implementation-oriented and you responded without tools, your response is likely incomplete.","- If the task involves project files and you did not inspect the relevant files, your confidence should be low.","- If the task involves modification but no files were changed, the task is likely incomplete.","- If the task involves internet images/assets and you only discussed URLs without integrating anything, the task is likely incomplete unless the user asked for ideas only.","- If you detect that your previous direction was too weak, correct course and execute properly.","- If continuity is needed but you ignored prior context, your answer quality is degraded."]),"",Y("FINAL RESPONSE CONTRACT",["For casual turns:","- keep it short, warm, and natural","- avoid robotic phrasing","","For read-only and analysis answers:","- answer directly","- structure only as much as the task needs","- cite observed evidence in plain language when relevant","","For implementation, upgrade, refactor, frontend, asset, or repair work:","- present the final answer as a compact executive report","- use markdown headings when the work is substantial","- prefer this structure:"," - ## Completed"," - ## Changed Files and Assets"," - ## Verification"," - ## Remaining Notes","- under each section, use short bullets or a compact table when useful","- mention any added/downloaded assets explicitly","- mention what was verified explicitly","- mention what remains unverified or incomplete explicitly","- when useful, end with one compact high-value next step or recommendation","- keep the report clean and premium, not chatty and not status-theatre","","For failures:","- be explicit, technical, honest","- do not pretend the task succeeded","- if partial work happened, say exactly what succeeded and what failed","- if nothing changed, say that clearly"]),"",Y("TASK PROFILE",Hh(e)),"",Y("CURRENT PROJECT CONTEXT",Bh(t))].join(`
|
|
149
|
+
`)}function Y(t,e){let n=Array.isArray(e)?e.join(`
|
|
150
|
+
`):e;return["====================",t,"====================",n].join(`
|
|
151
|
+
`)}function Bh(t){return t.trim()||"No project context captured."}function Hh(t){return t.kind==="casual"?["- Casual/social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short, natural, and never empty-feeling.","- If the user is only greeting, acknowledge warmly and signal readiness."].join(`
|
|
152
|
+
`):t.kind==="read"?["- Read-only or project-inspection task.","- Use tools only to inspect the minimum necessary evidence.","- Answer directly, then support with observed facts when useful.","- Keep the final answer factual, grounded, tight, and pleasantly professional."].join(`
|
|
153
|
+
`):t.kind==="analysis"?["- Analysis / architecture task.","- Prefer reasoning from constraints first.","- Inspect files only when they materially improve the recommendation.","- Deliver trade-offs, assumptions, practical guidance, and the best next move."].join(`
|
|
154
|
+
`):[t.continuity?"- Continue from existing work. Do not restart the project from zero.":"- Implementation task.",t.oneStepDelivery?"- The user requested one-step delivery with minimal follow-up questions.":"- Ask a clarifying question only if the task is truly blocked.","- Real workspace tool usage is mandatory.","- Do not answer with inline code only if files can be created or modified directly.","- The task is not complete unless the relevant files were inspected and then changed or created when needed.","- Preserve the existing architecture unless the user explicitly asks for a structural change.","- Verify changes before claiming completion.","- End with a compact executive report, not a vague narrative."].join(`
|
|
155
|
+
`)}var Wh=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Vh=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,zh=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Kh=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,Gh=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,Jh=/\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,Yh=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,Xh=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,qa=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i,Zh=["You are an internal task profiler for Hablas, a single-agent engineering runtime.","Infer intent semantically, not by fixed keywords, trigger words, or exact phrasing.","The user may write in Arabic, English, mixed language, slang, shorthand, typos, or incomplete wording.","Classify based on the expected behavior and desired outcome.","","Return ONLY valid JSON with this exact shape:","{",' "kind": "casual|read|analysis|implementation",',' "needsTools": true,',' "needsWrite": false,',' "continuity": false,',' "oneStepDelivery": false,',' "requiresProjectContext": false,',' "reason": "short reason"',"}","","Rules:",'- Choose "implementation" whenever the user expects a real project outcome, concrete changes, debugging, continuation, repair, upgrade, delivery, or execution.','- Choose "read" for factual inspection questions about the current project or files.','- Choose "analysis" for architecture, design, trade-offs, planning, or evaluation without direct implementation.','- Choose "casual" only for genuinely social or tiny conversational turns.',"- continuity=true when the request depends on previous work, the existing project, or an unfinished state even if the user does not use explicit continuity keywords.","- oneStepDelivery=true when the user strongly implies do-it-now / minimal back-and-forth / one-pass completion, even indirectly.","- requiresProjectContext=true when a good answer depends on the current workspace/repo context.","- needsTools reflects actual inspection/execution need, not wording.","- needsWrite=true only when real file creation/editing is expected.","- Do not explain. Do not add markdown. Do not add prose before or after the JSON."].join(`
|
|
156
|
+
`);function Tt(t){let e=t.trim(),n=e.toLowerCase(),r=Vh.test(n),s=zh.test(n),i=Kh.test(n)||Gh.test(n),o=Jh.test(n),a=Yh.test(n),l=i||r||s||o&&e.length>18&&!qa.test(n)&&!a,c=a&&!i&&!r&&!s,f=Xh.test(n)||o,d=!l&&!c&&(qa.test(n)||e.endsWith("?"));return Wh.test(e)&&!f&&!l&&!c?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:l?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:r,oneStepDelivery:s,requiresProjectContext:!0,reason:r?"Continuation of existing work requires reading and modifying project artifacts.":"Implementation request requires tool-based execution."}:c?{kind:"analysis",needsTools:f,needsWrite:!1,continuity:r,oneStepDelivery:!1,requiresProjectContext:f,reason:f?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||f?{kind:"read",needsTools:f,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:f,reason:f?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}async function Ba(t,e={}){let n=await Qh(t,e)??Tt(t);return{input:t,profile:n,plan:im(n)}}async function Qh(t,e){if(!e.client)return null;try{let n=await e.client.chatWithTools([{role:"system",content:Zh},{role:"user",content:em(t,e.history)}],[],e.abortSignal);return tm(n.message?.content||"")}catch{return null}}function em(t,e){let n=(e||[]).filter(r=>r.role!=="system").slice(-6).map((r,s)=>{let i=r.content.replace(/\s+/g," ").trim().slice(0,220);return`${s+1}. ${r.role}: ${i||"(empty)"}`});return["Recent conversation (oldest -> newest):",n.length>0?n.join(`
|
|
157
|
+
`):"(none)","","Current user turn:",t].join(`
|
|
158
|
+
`)}function tm(t){let e=t.trim().replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/```$/i,"").trim(),n=nm(e);if(!n)return null;try{let r=JSON.parse(n);return rm(r)}catch{return null}}function nm(t){let e=t.indexOf("{"),n=t.lastIndexOf("}");return e===-1||n===-1||n<=e?null:t.slice(e,n+1)}function rm(t){if(!t.kind||!sm(t.kind))return null;let e=t.kind,n=t.continuity===!0,r=t.oneStepDelivery===!0,s=t.requiresProjectContext===!0,i=t.needsTools===!0,o=t.needsWrite===!0;e==="implementation"&&(i=!0,o=!0),e==="read"&&s&&(i=!0),e==="casual"&&(i=!1,o=!1);let a=typeof t.reason=="string"&&t.reason.trim()?t.reason.trim().slice(0,240):"Model-assisted semantic task classification.";return{kind:e,needsTools:i,needsWrite:o,continuity:n,oneStepDelivery:r,requiresProjectContext:s,reason:a}}function sm(t){return t==="casual"||t==="read"||t==="analysis"||t==="implementation"}function im(t){if(!t.needsTools)return[{id:"respond",title:"Respond directly and clearly."}];if(t.kind==="read")return[{id:"inspect",title:"Inspect the minimum relevant files."},{id:"answer",title:"Answer precisely from observed facts."}];if(t.kind==="analysis")return[{id:"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 e=[];return t.continuity&&e.push({id:"continuity",title:"Load existing project context and continue instead of restarting."}),e.push({id:"inspect",title:"Inspect the relevant code and files."}),e.push({id:"implement",title:"Apply the smallest correct implementation."}),e.push({id:"verify",title:"Run verification before claiming completion."}),e.push({id:"answer",title:"Summarize the outcome clearly."}),t.oneStepDelivery&&e.unshift({id:"delivery-contract",title:"Treat the request as no-questions one-step delivery."}),e}var tl=A(require("readline")),oe=A(require("fs")),X=A(require("path")),nl=A(require("os"));var Zr=A(require("os")),pn=A(require("fs")),dn=A(require("path"));function om(){let t=[dn.resolve(__dirname,"..","package.json"),dn.resolve(__dirname,"..","..","package.json"),dn.resolve(process.cwd(),"package.json")];for(let e of t)try{if(pn.existsSync(e)){let n=JSON.parse(pn.readFileSync(e,"utf-8"));if(n.version)return n.version}}catch{}return"0.0.0"}var Ha=om(),Qr=process.stdout.isTTY===!0,am=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",Wa=process.stdout.columns||100;Qr&&process.stdout.on("resize",()=>{Wa=process.stdout.columns||100});var Te=()=>Math.min(Math.max(Wa-4,60),100);function ie(t,e){return!Qr||am?t:`${e}${t}\x1B[0m`}var w={strong:t=>ie(t,"\x1B[1;38;5;255m"),muted:t=>ie(t,"\x1B[38;5;242m"),accent:t=>ie(t,"\x1B[38;5;145m"),info:t=>ie(t,"\x1B[38;5;110m"),success:t=>ie(t,"\x1B[38;5;108m"),warning:t=>ie(t,"\x1B[38;5;179m"),error:t=>ie(t,"\x1B[38;5;167m"),primary:t=>ie(t,"\x1B[38;5;253m"),secondary:t=>ie(t,"\x1B[38;5;247m"),border:t=>ie(t,"\x1B[38;5;237m"),code:t=>ie(t,"\x1B[38;5;188m"),line:t=>ie(t,"\x1B[38;5;239m")};function es(t,e=2){let n=Te()-e,r=t.split(" "),s=[],i="";for(let o of r)(i+" "+o).trim().length>n&&i?(s.push(" ".repeat(e)+i.trim()),i=o):i+=(i?" ":"")+o;return i&&s.push(" ".repeat(e)+i.trim()),s}function lm(t){let e=Te();if(!t)return w.border("\u2500".repeat(e));let n=t.replace(/\x1b\[[0-9;]*m/g,""),r=Math.max(0,e-n.length-2),s=Math.floor(r/2),i=r-s;return w.border("\u2500".repeat(s))+" "+t+" "+w.border("\u2500".repeat(i))}function Va(t,e){let n=Math.min(Te(),82),r=e.replace(Zr.homedir(),"~"),s=w.border("\u256D"+"\u2500".repeat(n-2)+"\u256E"),i=w.border("\u251C"+"\u2500".repeat(n-2)+"\u2524"),o=w.border("\u2570"+"\u2500".repeat(n-2)+"\u256F"),a="HABLAS",l="single-agent engineering runtime",c=Math.max(0,Math.floor((n-2-a.length)/2)),f=Math.max(0,Math.floor((n-2-l.length)/2)),d=(h,p="")=>{let u=h.replace(/\x1b\[[0-9;]*m/g,""),m=p.replace(/\x1b\[[0-9;]*m/g,""),g=Math.max(1,n-4-u.length-m.length);return`${w.border("\u2502")} ${h}${" ".repeat(g)}${p} ${w.border("\u2502")}`};return["",s,w.border("\u2502")+" ".repeat(c)+w.strong(a)+" ".repeat(n-2-a.length-c)+w.border("\u2502"),w.border("\u2502")+" ".repeat(f)+w.secondary(l)+" ".repeat(n-2-l.length-f)+w.border("\u2502"),i,d(w.muted(`version v${Ha}`),w.muted(t)),d(w.muted(r)),i,d(w.secondary("Type naturally to get started")),d(w.muted("/help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")),o,""].join(`
|
|
159
|
+
`)}function za(t){return`
|
|
160
|
+
`+lm(`${w.accent("\u25C6")} ${w.strong("Turn #"+t)}`)}function ft(){return`
|
|
161
|
+
${w.accent("\u25C6")} ${w.strong("Hablas")} ${w.muted("[response]")}`}function Ka(t){return` ${w.accent("\u25C9")} ${w.secondary(t)}`}function ut(t){return t.replace(/`([^`]+)`/g,(e,n)=>w.primary(n)).replace(/\*\*([^*]+)\*\*/g,(e,n)=>w.strong(n))}function cm(t){return/^\s*\|.*\|\s*$/.test(t)}function um(t){let n=t.map(c=>c.trim()).filter(Boolean).map(c=>c.split("|").slice(1,-1).map(f=>f.trim())).filter(c=>!c.every(f=>/^:?-{2,}:?$/.test(f)));if(n.length===0)return[];let r=[];for(let c of n)c.forEach((f,d)=>{let h=f.replace(/\x1b\[[0-9;]*m/g,"").length;r[d]=Math.max(r[d]||0,h)});let s=` ${w.border("\u250C"+r.map(c=>"\u2500".repeat(c+2)).join("\u252C")+"\u2510")}`,i=` ${w.border("\u251C"+r.map(c=>"\u2500".repeat(c+2)).join("\u253C")+"\u2524")}`,o=` ${w.border("\u2514"+r.map(c=>"\u2500".repeat(c+2)).join("\u2534")+"\u2518")}`,a=c=>{let f=c.map((d,h)=>{let p=ut(d),u=p.replace(/\x1b\[[0-9;]*m/g,"").length;return` ${p}${" ".repeat(Math.max(0,r[h]-u))} `});return` ${w.border("\u2502")}${f.join(w.border("\u2502"))}${w.border("\u2502")}`},l=[s,a(n[0])];n.length>1&&l.push(i);for(let c of n.slice(1))l.push(a(c));return l.push(o),l}function Ct(t){let e=t.split(`
|
|
162
|
+
`),n=[],r=!1,s="",i=[],o=[],a=()=>{if(!i.length)return;let c=String(i.length).length;n.push(` ${w.border("\u250C"+"\u2500".repeat(Math.max(24,Te()-6)))} ${s?w.accent(s):""}`.trimEnd()),i.forEach((f,d)=>{n.push(` ${w.border("\u2502")} ${w.line(String(d+1).padStart(c)+" \u2502")} ${w.code(f)}`)}),n.push(` ${w.border("\u2514"+"\u2500".repeat(Math.max(24,Te()-6)))}`),i=[]},l=()=>{o.length&&(n.push(...um(o)),o=[])};for(let c of e){if(c.trimStart().startsWith("```")){l(),r?(a(),r=!1,s=""):(r=!0,s=c.trimStart().slice(3).trim());continue}if(r){i.push(c);continue}if(cm(c)){o.push(c);continue}else l();if(!c.trim()){n.push("");continue}if(/^---+$/.test(c.trim())){n.push(` ${w.border("\u2500".repeat(Math.max(28,Te()-6)))}`);continue}if(/^#{1,3}\s/.test(c)){n.push(""),n.push(` ${w.strong(ut(c.replace(/^#{1,3}\s/,"")))}`);continue}if(/^[A-Z][A-Za-z0-9 /&_-]{2,}:$/.test(c.trim())){n.push(` ${w.strong(ut(c.trim()))}`);continue}if(/^[-*]\s/.test(c.trim())){n.push(` ${w.accent("\u25B8")} ${ut(c.trim().slice(2))}`);continue}if(/^\d+\.\s/.test(c.trim())){n.push(` ${ut(c.trim())}`);continue}n.push(...es(ut(c),2))}return l(),r&&a(),`
|
|
163
|
+
`+n.join(`
|
|
404
164
|
`)+`
|
|
405
|
-
`}function
|
|
406
|
-
`)}function
|
|
407
|
-
`)}function K(t){return` ${w.info(t)}`}function
|
|
408
|
-
`)}function
|
|
409
|
-
`)}function
|
|
410
|
-
`)[0]?.trim()||""||e.replace(/\s+/g," ").trim()||(t?"done":"failed"),a=`${s} ${o} ${w.muted(`(${
|
|
411
|
-
`)}var
|
|
165
|
+
`}function Ga(){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(`
|
|
166
|
+
`)}function Ja(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(Zr.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(`
|
|
167
|
+
`)}function K(t){return` ${w.info(t)}`}function qe(t){return` ${w.success("\u2713")} ${t}`}function Ce(t){return` ${w.warning("\u26A0")} ${t}`}function Ae(t){return` ${w.error("\u2717")} ${t}`}function Ya(){return` ${w.strong("Hablas")} ${w.accent("v"+Ha)}`}function Xa(){return["",` ${w.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime`,"",` ${w.primary("Abdulmoin Hablas")} ${w.muted("Portfolio")}`,` ${w.muted(" https://portfolio-monopoly63s-projects.vercel.app/")}`,""].join(`
|
|
168
|
+
`)}function Za(t,e){let n=Math.max(50,Te()-8),r=`${t.toUpperCase()}`,s=es(e,0),i=[];i.push(` ${w.border("\u256D"+"\u2500".repeat(n+2)+"\u256E")}`);let o=Math.max(0,n-r.length);i.push(` ${w.border("\u2502")} ${w.strong(r)}${" ".repeat(o)} ${w.border("\u2502")}`),i.push(` ${w.border("\u251C"+"\u2500".repeat(n+2)+"\u2524")}`);for(let a of s){let l=a.trim(),c=Math.max(0,n-l.replace(/\x1b\[[0-9;]*m/g,"").length);i.push(` ${w.border("\u2502")} ${w.accent(l)}${" ".repeat(c)} ${w.border("\u2502")}`)}return i.join(`
|
|
169
|
+
`)}function Qa(t,e,n){let r=Math.max(50,Te()-8),s=t?w.success("\u2713 SUCCESS"):w.error("\u2717 FAILURE"),o=e.split(`
|
|
170
|
+
`)[0]?.trim()||""||e.replace(/\s+/g," ").trim()||(t?"done":"failed"),a=`${s} ${o} ${w.muted(`(${n}ms)`)}`,l=es(a,0),c=[];for(let f of l){let d=f.trim(),h=Math.max(0,r-d.replace(/\x1b\[[0-9;]*m/g,"").length);c.push(` ${w.border("\u2502")} ${d}${" ".repeat(h)} ${w.border("\u2502")}`)}return c.push(` ${w.border("\u2570"+"\u2500".repeat(r+2)+"\u256F")}`),c.join(`
|
|
171
|
+
`)}var Ue=class{constructor(e){this.label=e}frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;timer=null;setLabel(e){this.label=e}start(){!Qr||this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${w.accent(this.frames[this.index])} ${w.muted(this.label)}`),this.index=(this.index+1)%this.frames.length},80))}stop(e){this.timer&&(clearInterval(this.timer),this.timer=null,process.stdout.write("\r\x1B[K")),e&&console.log(K(e))}};var hn=X.join(nl.homedir(),".hablas","history"),mn=500,fm=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),dm=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],pm=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"]),el=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],gn=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return tl.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:mn,completer:e=>this.autocomplete(e)})}async prompt(e){return new Promise(n=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,r=>{let s=r.trim();s&&(this.history.push(s),this.history=this.history.slice(-mn),this.saveHistory()),n(r)})})}async confirm(e){return(await this.prompt(` ${w.warning("?")} ${e} ${w.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
|
|
412
172
|
${w.error("\u26A0")} ${e}`),console.log(` ${w.muted("Type yes to confirm this dangerous action.")}
|
|
413
|
-
`),(await this.prompt(` ${w.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let
|
|
414
|
-
`).filter(Boolean).slice(-
|
|
415
|
-
`),"utf-8")}catch{}}};var
|
|
173
|
+
`),(await this.prompt(` ${w.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let r=el.filter(s=>s.startsWith(e));return[r.length?r:el,e]}for(let r of dm)if(e.toLowerCase().includes(r)){let s=e.split(r).pop()??"";if(s&&!s.includes(" "))try{let i=X.dirname(s)||".",o=X.basename(s),a=X.resolve(this.workingDir,i),l=oe.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(s))+X.join(i,c));if(l.length)return[l,e]}catch{}}let n=e.match(/#([\w./-]*)$/);if(n){let r=n[1],s=this.getProjectFiles(),i=s.filter(o=>o.toLowerCase().startsWith(r.toLowerCase())).map(o=>e.slice(0,e.length-n[0].length)+"#"+o);return[i.length?i:s.slice(0,20).map(o=>e.slice(0,e.length-n[0].length)+"#"+o),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let n=[];return this.scanDir(this.workingDir,"",n,3),this.fileCache=n,this.fileCacheTime=e,n}scanDir(e,n,r,s,i=0){if(!(i>=s))try{let o=oe.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||fm.has(a.name))continue;let l=n?`${n}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(X.join(e,a.name),l,r,s,i+1);else{let c=X.extname(a.name).toLowerCase();(pm.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&r.push(l)}}}catch{}}loadHistory(){try{oe.existsSync(hn)&&(this.history=oe.readFileSync(hn,"utf-8").split(`
|
|
174
|
+
`).filter(Boolean).slice(-mn))}catch{}}saveHistory(){try{let e=X.dirname(hn);oe.existsSync(e)||oe.mkdirSync(e,{recursive:!0}),oe.writeFileSync(hn,this.history.slice(-mn).join(`
|
|
175
|
+
`),"utf-8")}catch{}}};var hm={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},mm=`
|
|
416
176
|
## Reasoning Protocol
|
|
417
177
|
|
|
418
178
|
Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
|
|
@@ -441,26 +201,26 @@ After receiving a tool result, think again:
|
|
|
441
201
|
- One tool call per turn. Wait for the result before the next call.
|
|
442
202
|
- If a tool fails, analyze the error in <thinking> before retrying.
|
|
443
203
|
- When done, give a concise final answer WITHOUT <thinking> tags.
|
|
444
|
-
`.trim(),
|
|
204
|
+
`.trim(),gm=`
|
|
445
205
|
## Reasoning
|
|
446
206
|
For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
|
|
447
207
|
The user will NOT see thinking blocks. One tool call per turn.
|
|
448
|
-
`.trim(),
|
|
208
|
+
`.trim(),ts=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...hm,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,n="M"){return!this.config.thinkingEnabled||n==="XS"?e:n==="S"?`${e}
|
|
449
209
|
|
|
450
|
-
${
|
|
210
|
+
${gm}`:`${e}
|
|
451
211
|
|
|
452
|
-
${
|
|
212
|
+
${mm}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let n=[],r=e,s=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=s.exec(e))!==null;)n.push(i[1].trim());r=r.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)n.push(i[1].trim());r=r.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(r);a&&(n.push(a[1].trim()),r=r.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(r);return l&&(n.push(l[1].trim()),r=r.replace(/<think>[\s\S]*$/i,"")),{thinking:n.join(`
|
|
453
213
|
|
|
454
|
-
`).trim(),visibleContent:
|
|
214
|
+
`).trim(),visibleContent:r.trim(),hasThinking:n.length>0}}startTurn(){this.turnSteps=[],this.stepCounter=0}recordStep(e){let n={...e,stepIndex:this.stepCounter++,timestamp:new Date().toISOString()};return this.turnSteps.push(n),n}recordObservation(e,n){let r=this.turnSteps[this.turnSteps.length-1];r&&(r.observation=e,n&&(r.reflection=n))}getSteps(){return this.turnSteps}isOverBudget(){return this.stepCounter>=this.config.maxSteps}remainingBudget(){return Math.max(0,this.config.maxSteps-this.stepCounter)}buildSelfEvalPrompt(e,n,r){return`
|
|
455
215
|
<self_eval>
|
|
456
216
|
You just completed this task: "${e}"
|
|
457
217
|
|
|
458
218
|
Your answer was:
|
|
459
219
|
"""
|
|
460
|
-
${
|
|
220
|
+
${n.slice(0,1500)}
|
|
461
221
|
"""
|
|
462
222
|
|
|
463
|
-
Tools used: ${
|
|
223
|
+
Tools used: ${r.length>0?r.join(", "):"none"}
|
|
464
224
|
|
|
465
225
|
Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
466
226
|
{
|
|
@@ -471,19 +231,19 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
|
471
231
|
"confidence": "<high|medium|low>"
|
|
472
232
|
}
|
|
473
233
|
</self_eval>
|
|
474
|
-
`.trim()}parseSelfEval(e){let
|
|
475
|
-
`)}getTurnSummary(){let e=this.turnSteps.length,
|
|
476
|
-
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let
|
|
477
|
-
|
|
478
|
-
`),{toolCalls:
|
|
479
|
-
|
|
480
|
-
`)}},
|
|
481
|
-
`)}});u||(p.stop(),console.log(
|
|
482
|
-
`)}async function
|
|
483
|
-
`);for(let{pattern:s,name:i,severity:o}of
|
|
484
|
-
`).length,f=
|
|
485
|
-
`),s=
|
|
486
|
-
Security Scan Complete`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Files scanned: ${t.scannedFiles}`),e.push(` Duration: ${t.duration}ms`),e.push(""),t.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${t.issues.length}`),e.push(` Critical: ${t.summary.critical}`),e.push(` High: ${t.summary.high}`),e.push(` Medium: ${t.summary.medium}`),e.push(` Low: ${t.summary.low}`),e.push("");let
|
|
487
|
-
`)}var
|
|
488
|
-
\u{1F4CA} Developer Analytics`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Sessions: ${t.totalSessions}`),e.push(` Messages: ${t.totalMessages}`),e.push(` Tokens used: ${t.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${t.totalToolCalls}`),e.push(` Files modified: ${t.totalFilesModified}`),e.push(` Lines written: ${t.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${t.totalBugsFixed}`),e.push(` Commits: ${t.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${t.streak} days (best: ${t.longestStreak})`),e.push("");let
|
|
489
|
-
`)}var
|
|
234
|
+
`.trim()}parseSelfEval(e){let n=[/^\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 r of n){let s=e.match(r);if(s)try{let i=JSON.parse(s[1]);return this.normalizeSelfEval(i)}catch{}}return null}normalizeSelfEval(e){let n=typeof e.score=="number"?Math.max(0,Math.min(10,Math.round(e.score))):5,r=typeof e.completed=="boolean"?e.completed:n>=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:n>=8?o="high":n<=4&&(o="low"),{score:n,completed:r,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,n,r){return n?"":["<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: ${r.slice(0,300)}`,"</thinking>"].join(`
|
|
235
|
+
`)}getTurnSummary(){let e=this.turnSteps.length,n=this.turnSteps.filter(s=>s.action).length,r=this.turnSteps.filter(s=>s.reflection).length;return`${e} steps, ${n} actions, ${r} reflections`}};function At(t){return new ts(t)}var ym=[{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}],ns=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,n,r){let s=this.failures.get(e),i=s?s.count+1:1,o={tool:e,count:i,lastError:n,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 ym)if(a.test(n)){let l=s?.lastStrategy===a.strategy&&i>=2,c=l?"decompose_task":a.strategy;return o.lastStrategy=c,this.failures.set(e,o),{errorClass:a.errorClass,strategy:c,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,n){let r=[`ERROR: ${n}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&r.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":r.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":r.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":r.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":r.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":r.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":r.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return r.join(`
|
|
236
|
+
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let n=this.failures.get(e);return n?n.count<=1&&n.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function Et(t=3){return new ns(t)}var we=A(require("fs")),wn=A(require("path")),rl=A(require("os")),yn=wn.join(rl.homedir(),".hablas","model-formats.json");function wm(){try{if(we.existsSync(yn))return JSON.parse(we.readFileSync(yn,"utf-8"))}catch{}return{}}function bm(t){try{let e=wn.dirname(yn);we.existsSync(e)||we.mkdirSync(e,{recursive:!0}),we.writeFileSync(yn,JSON.stringify(t,null,2),"utf-8")}catch{}}function sl(t,e){let n=0,r=!1,s=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){s=!1;continue}if(o==="\\"&&r){s=!0;continue}if(o==='"'){r=!r;continue}if(!r&&(o==="{"&&n++,o==="}"&&(n--,n===0)))return t.slice(e,i+1)}return null}function Ot(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 n={};if(typeof e.arguments=="string")try{n=JSON.parse(e.arguments)}catch{n={}}else e.arguments&&typeof e.arguments=="object"&&(n=e.arguments);return{tool:e.name,args:n}}}return null}function xm(t){return t.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function Sm(t){let e=[],n=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,r;for(;(r=n.exec(t))!==null;)try{let s=JSON.parse(r[1].trim()),i=Ot(s);i&&e.push({...i,format:"xml_tags",rawMatch:r[0]})}catch{}return e}function vm(t){let e=[],n=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,r;for(;(r=n.exec(t))!==null;)try{let s=JSON.parse(r[1].trim());if(s.parameters||s.name){let i=Ot(s);i&&e.push({...i,format:"hermes",rawMatch:r[0]})}}catch{}return e}function _m(t){let e=[],n=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,r;for(;(r=n.exec(t))!==null;){let s=r[1],i=il(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:r[0]})}return e}function il(t){let e=[],n=["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 r of n){let s=new RegExp(`<<?${r}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${r}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",l={},c=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,f;for(;(f=c.exec(o))!==null;){let h=f[1].toLowerCase(),p=f[2]??f[3]??f[4];l[h]=xm(p)}let d=a.trim();d&&(r==="write_file"||r==="append_to_file"?l.content=a:r==="run_command"?l.command=d:r==="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)),r==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:r,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function km(t){return il(t)}function $m(t){let e=[],n=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,r;for(;(r=n.exec(t))!==null;)try{let s=JSON.parse(r[1].trim()),i=Ot(s);i&&e.push({...i,format:"markdown_json",rawMatch:r[0]})}catch{}return e}function Tm(t){let e=[],n=/\{\s*"function"\s*:/g,r;for(;(r=n.exec(t))!==null;){let s=sl(t,r.index);if(s)try{let i=JSON.parse(s),o=Ot(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function Cm(t){let e=[],n=/\{\s*"(?:name|tool)"\s*:/g,r;for(;(r=n.exec(t))!==null;){let s=sl(t,r.index);if(s)try{let i=JSON.parse(s),o=Ot(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function Am(t){let e=[],n=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,r,s=!1;for(;(r=n.exec(t))!==null;){let i=r[1],o=/<function=([^>]+)>/i.exec(i);if(o){s=!0;let a=o[1].trim(),l={},c=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,f;for(;(f=c.exec(i))!==null;){let d=f[1].trim(),h=f[2].trim();h==="true"?h=!0:h==="false"?h=!1:!isNaN(Number(h))&&h!==""&&(h=Number(h)),l[d]=h}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:r[0]})}}if(!s&&/<function=([^>]+)>/i.test(t)){let i=/<function=([^>]+)>/i.exec(t);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,c;for(;(c=l.exec(t))!==null;){let f=c[1].trim(),d=c[2].trim();d==="true"?d=!0:d==="false"?d=!1:!isNaN(Number(d))&&d!==""&&(d=Number(d)),a[f]=d}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var rs=[{format:"xml_tool_call_wrapper",parse:_m},{format:"xml_prompt",parse:km},{format:"xml_tags",parse:Sm},{format:"xml_parameters",parse:Am},{format:"hermes",parse:vm},{format:"markdown_json",parse:$m},{format:"function_call",parse:Tm},{format:"json_object",parse:Cm}],is=class{registry;constructor(){this.registry=wm()}parse(e,n,r){if(n&&Array.isArray(n)&&n.length>0){let i=n.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 r&&this.learnFormat(r,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let s=e||"";if(!s.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(r){let i=this.registry[r];if(i&&i.format!=="native"){let o=rs.find(a=>a.format===i.format);if(o){let a=o.parse(s);if(a.length>0)return this.learnFormat(r,i.format),this.buildResult(a,s)}}}for(let{parse:i}of rs){let o=i(s);if(o.length>0){let a=o[0].format;return r&&this.learnFormat(r,a),this.buildResult(o,s)}}return{toolCalls:[],displayContent:this.sanitizeResidualToolMarkup(s).trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let n=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(n)||/<function=/i.test(n)||n.includes("```tool_call")||n.includes("```json")&&n.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s>]/i.test(n)||n.startsWith("{")&&(n.includes('"name"')||n.includes('"tool"'))&&(n.includes('"arguments"')||n.includes('"args"')||n.includes('"parameters"'))||n.includes('"function"')&&n.includes('"name"'))}detectFormat(e){for(let{format:n,parse:r}of rs)if(r(e).length>0)return n;return"unknown"}learnFormat(e,n){let r=this.registry[e];r&&r.format===n?(r.successCount++,r.lastUsed=new Date().toISOString()):this.registry[e]={format:n,successCount:1,lastUsed:new Date().toISOString()},bm(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[n,r]of Object.entries(this.registry))e[n]={format:r.format,successCount:r.successCount};return e}buildResult(e,n){let r=e.map(o=>({function:{name:o.tool,arguments:o.args}})),s=n,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,`
|
|
237
|
+
|
|
238
|
+
`),{toolCalls:r,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,`
|
|
239
|
+
|
|
240
|
+
`)}},ss=null;function ol(){return ss||(ss=new is),ss}var Em=600,Om=2e3,Rm=12e3,al=2;function Im(t,e,n){let s=ol().parse(e,t,n);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function Pm(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 Mm(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 ll(t,e,n,r){let s=0,i=Date.now();for(;s<=al;){let o=await t.execute({name:e,arguments:n});if(o.success||s>=al)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:s};s++,r.info({tool:e,retry:s,error:o.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-i,retries:s}}async function os(t){let{identity:e,client:n,registry:r,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:f}=t,d=t.reactEngine??At(),h=t.errorRecovery??Et(),p=f?[]:r.getOllamaTools(),u=n.getModel(),m=t.maxIterations??Em,g=[],S=[],b=[],x=new Map,v="",_=0,$=!1;for(;_<m;){if(_++,c?.aborted)return{output:v,toolsUsed:Ee(g),toolResults:S,touchedFiles:Ee(b),iterations:_,success:!1,error:"Aborted",completedNaturally:$};let C=d.buildBudgetWarningPrompt();C&&s.addUserMessage(C,{priority:"critical",tags:["system-budget"]});let E;try{a.onModelStart?.(S.length>0?"Hablas is deciding the next step":"Hablas is thinking",e),E=await n.chatWithTools(s.getMessages(),p,c),a.onModelStop?.()}catch(J){a.onModelStop?.();let Q=J;if(Q.name==="AbortError"||c?.aborted)return{output:v,toolsUsed:Ee(g),toolResults:S,touchedFiles:Ee(b),iterations:_,success:!1,error:"Aborted",completedNaturally:$};if(_<=1){a.onNotice?.(`Transient model error: ${Q.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(j=>setTimeout(j,1e3)),_--;continue}return a.onError?.(Q.message??"Model request failed"),{output:v,toolsUsed:Ee(g),toolResults:S,touchedFiles:Ee(b),iterations:_,success:!1,error:Q.message,completedNaturally:$}}let T=E.message?.content||"",P=E.message?.tool_calls,L=d.parseThinking(T);L.hasThinking&&(d.recordStep({thought:L.thinking}),o.debug({thinking:L.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:D,displayContent:B}=Im(P,T,u);if(B&&B.trim()&&(v=B,await a.onAssistantText?.(B,e)),D.length===0){s.addAssistantMessage(T,void 0,e.role),$=!0;break}s.addAssistantMessage(T,D,e.role);let W=D.length;for(let J=0;J<D.length;J++){let Q=D[J];if(!Q?.function?.name)continue;let j=Q.function.name,F=Q.function.arguments||{},Pt=r.getSafetyLevel(j)??"confirm";if(!r.get(j)){a.onNotice?.(`Unknown tool: ${j} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${j}". Available: ${r.getAll().map(z=>z.name).join(", ")}`);continue}if(await l(j,Pt,F)==="skip"){s.addToolMessage(`Tool ${j} was skipped by policy/user.`);break}let Ol=Pm(j,F),pt=j==="read_file"?JSON.stringify({path:F.path||"",start:F.start_line||"",end:F.end_line||""}):"";if(j==="read_file"&&pt&&x.has(pt)){let z=x.get(pt)||"";s.addToolMessage(z),d.recordObservation(z.slice(0,300),"Reused cached file read");continue}g.push(j),typeof F.path=="string"&&b.push(F.path),typeof F.from=="string"&&b.push(F.from),typeof F.to=="string"&&b.push(F.to),a.onToolStart?.(j,Ol,F),a.onToolCall?.(),d.recordStep({thought:L.hasThinking?`Executing: ${j}`:"",action:j,actionInput:F});let V=await ll(r,j,F,o);a.onToolEnd?.(j,V.success,V.error||V.output,V.duration,F);let Oe;if(V.success)Oe=cl(j,V.output),d.recordObservation(Oe.slice(0,300)),S.push({tool:j,success:!0,summary:V.output.slice(0,150)});else{let z=V.error||"Unknown error",He=h.analyze(j,z,F);if(Oe=h.buildRecoveryMessage(He,z),d.recordObservation(`FAILED: ${z}`,`Recovery: ${He.strategy} \u2014 ${He.suggestion}`),o.info({tool:j,errorClass:He.errorClass,strategy:He.strategy},"Error recovery analysis"),S.push({tool:j,success:!1,summary:z.slice(0,150)}),He.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let We=await ll(r,j,F,o);a.onToolEnd?.(j,We.success,We.output,We.duration,F),We.success&&(Oe=cl(j,We.output),d.recordObservation(Oe.slice(0,300),"Auto-retry succeeded"),S[S.length-1]={tool:j,success:!0,summary:We.output.slice(0,150)})}}if(s.addToolMessage(Oe),V.success&&j==="read_file"&&typeof F.path=="string"&&(i?.addFile(F.path,V.output),pt&&x.set(pt,Oe)),V.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(j)&&typeof F.path=="string")for(let z of[...x.keys()])z.includes(`"path":"${String(F.path).replace(/\"/g,'\\"')}"`)&&x.delete(z);if(V.success&&j==="move_file")for(let z of[...x.keys()])(F.from&&z.includes(`"path":"${String(F.from).replace(/\"/g,'\\"')}"`)||F.to&&z.includes(`"path":"${String(F.to).replace(/\"/g,'\\"')}"`))&&x.delete(z);if(o.info({tool:j,success:V.success,durationMs:V.duration,retries:V.retries},"Tool executed"),!V.success&&Mm(V.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}W>1&&J<W-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return _>=m&&!$&&a.onNotice?.(`Reached max iterations (${m}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:v,toolsUsed:Ee(g),toolResults:S,touchedFiles:Ee(b),iterations:_,success:!0,completedNaturally:$}}function Ee(t){return[...new Set(t)]}function cl(t,e){return t==="read_file"?e:t==="web_search"||t==="scrape_url"||t==="extract_links"||t==="read_pdf"?kt(e,Rm):kt(e,Om)}function ul(t){return async(e,n)=>{let r=e.replace(/_/g," ");return!t.autoMode&&t.interactive?n==="confirm"&&t.confirm?await t.confirm(`Proceed with ${r}?`)?"allow":"skip":n==="dangerous"&&t.confirmDangerous?await t.confirmDangerous(`Dangerous: ${r}`)?"allow":"skip":"allow":!t.autoMode&&n==="dangerous"?"skip":"allow"}}async function fl(t){let{client:e,session:n,abortSignal:r,onStart:s,onChunk:i,onComplete:o}=t,a="",l=null;for(let c=0;c<2;c++)try{a="",s?.();for await(let f of e.streamChat(n.getMessages(),r))a+=f,i?.(f);return n.addAssistantMessage(a||""),o?.(),a}catch(f){if(l=f,f?.name==="AbortError"||r?.aborted)throw f;if(c===1)break}throw l||new Error("Text turn failed")}async function bn(t,e){let n=await Ba(t,{client:e.client,history:e.session.getHistory()}),r=await lt(e.workingDir,e.config);if(e.session.updateSystemPrompt(ct(r,n.profile)),n.profile.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context and do not restart from zero.]",{priority:"critical",tags:["runtime-note","continuity"]}),n.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:${n.profile.kind}`]}),!n.profile.needsTools){let p=new Ue("Hablas is thinking"),u=!1;p.start();try{let m=await fl({client:e.client,session:e.session,onStart:()=>{p.start()},onChunk:g=>{u||(p.stop(),console.log(ft()),process.stdout.write(" "),u=!0),process.stdout.write(g)},onComplete:()=>{u&&process.stdout.write(`
|
|
241
|
+
`)}});u||(p.stop(),console.log(ft()),console.log(Ct(m)));return}catch(m){p.stop(),console.log(Ae(m?.message||"Text turn failed"));return}}let s=At({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=Et(3),o=[],a=new Ue("Hablas is thinking"),l="",c=p=>["list_dir","read_file","search_codebase","get_file_info"].includes(p)?"Analyzing current project structure":["web_search"].includes(p)?"Searching trusted web sources":["search_image_candidates","inspect_image","scrape_url","extract_links"].includes(p)?"Selecting better image candidates":["download_asset"].includes(p)?"Downloading verified floral assets":["write_file","patch_file","edit_file","search_and_replace","append_to_file","move_file","create_dir","delete_file"].includes(p)?"Applying frontend upgrade":["run_command","execute_code","detect_bugs"].includes(p)?"Running verification":"Working",f={onModelStart:p=>{a.stop(),a.setLabel(p),a.start()},onModelStop:()=>{a.stop()},onAssistantText:async p=>{o.push(p),n.profile.kind!=="implementation"&&(console.log(ft()),console.log(Ct(p)))},onToolStart:(p,u)=>{a.stop();let m=c(p);m!==l&&(console.log(Ka(m)),l=m),console.log(Za(p,u))},onToolEnd:(p,u,m,g)=>{console.log(Qa(u,m,g))},onNotice:(p,u)=>{console.log(u==="retry"?K(`Retrying: ${p}`):K(p))},onError:p=>{console.log(Ae(p))},onToolCall:()=>e.onToolCall?.()},d=ul({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?p=>e.input.confirm(p):void 0,confirmDangerous:e.input?p=>e.input.confirmDangerous(p):void 0}),h=await os({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:f,safetyPolicy:d,reactEngine:s,errorRecovery:i,skipTools:!1});if(n.profile.kind==="implementation"&&h.toolsUsed.length>0&&o.length>0&&(console.log(ft()),console.log(Ct(o[o.length-1]))),n.profile.kind==="implementation"&&h.toolsUsed.length===0){e.session.addUserMessage("SYSTEM CORRECTION: This was an implementation request. You must use workspace tools, inspect files, and create or modify actual files instead of only replying with inline code. Retry now using tools.",{priority:"critical",tags:["system-correction","force-tools"]});let p=[];(await os({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...f,onAssistantText:async m=>{p.push(m)}},safetyPolicy:d,reactEngine:At({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:Et(3),skipTools:!1})).toolsUsed.length===0?console.log(Ae("Implementation request failed to enter a real tool-execution path. Refusing to present inline-code-only output as a completed result.")):p.length>0&&(console.log(ft()),console.log(Ct(p[p.length-1])))}}var as=A(require("fs")),dl=A(require("path")),fe=A(require("os")),pl=require("child_process");async function xn(t){let e=[],n=process.version,r=parseInt(n.slice(1).split(".")[0],10);e.push({name:"Node.js",status:r>=20?"ok":r>=18?"warn":"error",message:r>=20?`${n} (recommended)`:r>=18?`${n} (works, but 20+ recommended)`:`${n} (too old, need 20+)`});let s=dl.join(fe.homedir(),".hablas");if(e.push({name:"Config directory",status:as.existsSync(s)?"ok":"warn",message:as.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=fe.homedir();if(process.platform!=="win32"){let a=(0,pl.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",c=a[4]||"?";e.push({name:"Disk space",status:parseInt(c)>90?"warn":"ok",message:`${l} available (${c} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:t.model?"ok":"warn",message:t.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${fe.platform()} ${fe.arch()} \u2014 ${fe.cpus().length} cores, ${Math.round(fe.totalmem()/1024/1024/1024)}GB RAM`}),e}function Sn(t){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},n={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},r="\x1B[0m",s="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of t){let c=`${n[l.status]}${e[l.status]}${r}`,f=l.name.padEnd(18);i.push(` ${c} ${f}${s}${l.message}${r}`)}let o=t.filter(l=>l.status==="error").length,a=t.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${n.error}${o} error(s) found \u2014 fix these for hablas to work properly${r}`):a>0?i.push(` ${n.warn}${a} warning(s) \u2014 hablas should work but check the items above${r}`):i.push(` ${n.ok}All checks passed \u2014 hablas is ready!${r}`),i.push(""),i.join(`
|
|
242
|
+
`)}async function hl(t,e){let n=t.trim().split(/\s+/),r=n[0],s=n.slice(1);switch(r){case"/help":console.log(Ga());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Xa());return;case"/version":console.log(Ya());return;case"/clear":e.session.clear(),console.log(qe("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(K("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l}: ${a.content.replace(/\s+/g," ").slice(0,160)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(Ja({model:e.client.getModel(),provider:De(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(K(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),Ge(e.config),console.log(qe(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=20,a=1,l="";if(s.length>0){let u=s[s.length-1],m=parseInt(u,10);!Number.isNaN(m)&&m>0?(a=m,l=s.slice(0,-1).join(" ").toLowerCase().trim()):l=s.join(" ").toLowerCase().trim()}let c=l?i.filter(u=>u.toLowerCase().includes(l)):i;if(c.length===0){console.log(Ce("No matching models found."));return}let f=Math.max(1,Math.ceil(c.length/o)),d=Math.min(Math.max(a,1),f),h=(d-1)*o,p=c.slice(h,h+o);console.log(""),console.log(K(`Models${l?` \xB7 search: ${l}`:""} \xB7 page ${d}/${f}`)),console.log(""),p.forEach((u,m)=>{let g=u===e.client.getModel();console.log(` ${String(h+m+1).padStart(2," ")}. ${u}${g?" * active":""}`)}),console.log(""),f>1&&console.log(K(`Use /models ${l?l+" ":""}${d<f?d+1:f} for next page.`)),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(K(`Provider: ${De(e.config)}`)),console.log(K(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?qe("Connection OK"):Ae("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=te.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=te.defaultModel);else if(i==="custom"){if(!s[1]){console.log(Ce("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(Ce("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=Ze(e.config);e.setClient(o),Ge(e.config),console.log(qe(`Provider switched to ${De(e.config)}`));return}case"/doctor":{let i=await xn({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Sn(i));return}case"/workspace":{console.log(""),console.log(fn(ot(e.workingDir))),console.log("");return}default:console.log(Ce(`Unknown command: ${r}`))}}var be=A(require("fs")),ls=A(require("path"));function cs(t){let e=ls.join(t,".hablas");return be.existsSync(e)||be.mkdirSync(e,{recursive:!0}),e}function ml(t){return ls.join(cs(t),"session.json")}function vn(t,e){let n=ml(t);try{return be.existsSync(n)?(e.fromJSON(be.readFileSync(n,"utf-8")),!0):!1}catch{return!1}}function Rt(t,e){let n=ml(t);try{be.writeFileSync(n,e.toJSON(),"utf-8")}catch{}}async function wl(t,e){As();let n=t.workingDirectory==="."?process.cwd():t.workingDirectory,r=Ze(t);cs(n);let s=new nt(n,t),i=new rt(t),o=await lt(n,t),a=new it(ct(o,Tt("hello")),t.historySize,t.contextBudget);vn(n,a);let l=new gn(n);console.log(Va(t.model,n));let c=new Ue("Connecting");c.start();let f=await r.checkConnection();if(c.stop(),f){let g=await r.listModels();console.log(qe(`online \xB7 ${De(t)} \xB7 ${g.length} models available`))}else console.log(Ce(`offline \xB7 ${De(t)} \xB7 you can still inspect local files and switch provider with /provider`));gl.existsSync(yl.join(n,".git"))||console.log(K("workspace mode: standalone (no git repository detected)")),console.log(K("Hablas is ready.")),console.log("");let d=0,h=0,p=Date.now(),u=new AbortController,m=0;for(process.on("SIGINT",()=>{let g=Date.now();g-m<1500&&(console.log(""),console.log(K(`Session summary \xB7 turns=${d} \xB7 toolCalls=${h} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),m=g,u.abort(),u=new AbortController,console.log(""),console.log(Ce("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let S=(await l.prompt(" \u203A ")).trim();if(S){if(S.startsWith("/")){let b=await hl(S,{config:t,client:r,setClient:x=>{r=x},session:a,workingDir:n});if(Rt(n,a),b==="quit")break;continue}d+=1,console.log(za(d)),u=new AbortController;try{await bn(S,{config:t,client:r,registry:s,contextManager:i,session:a,workingDir:n,logger:e,input:l,interactive:!0,onToolCall:()=>{h+=1}}),Rt(n,a)}catch(b){if(b?.name==="AbortError")continue;console.log(Ae(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}l.close()}async function bl(t,e,n){let r=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=Ze(e),i=new nt(r,e),o=new rt(e),a=await lt(r,e),l=new it(ct(a,Tt(t)),e.historySize,e.contextBudget);vn(r,l),await bn(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:r,logger:n,interactive:!1}),Rt(r,l)}var _n=A(require("fs")),Be=A(require("path")),jm=[{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"}],Lm=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Dm=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function Fm(t,e){let n=[],r=e.split(`
|
|
243
|
+
`);for(let{pattern:s,name:i,severity:o}of jm){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let c=e.substring(0,a.index).split(`
|
|
244
|
+
`).length,f=r[c-1]||"";f.trim().startsWith("#")||f.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||n.push({severity:o,type:"secret",file:t,line:c,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return n}function Nm(t,e){let n=[],r=e.split(`
|
|
245
|
+
`),s=Be.extname(t);return[".ts",".js",".tsx",".jsx"].includes(s)&&r.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&n.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)&&n.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)&&n.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."})}),n}function xl(t,e=[]){try{let n=_n.readdirSync(t,{withFileTypes:!0});for(let r of n){if(Lm.has(r.name))continue;let s=Be.join(t,r.name);if(r.isDirectory())xl(s,e);else if(r.isFile()){let i=Be.extname(r.name);Dm.has(i)||e.push(s)}}}catch{}return e}function Sl(t){let e=Date.now(),n=xl(t),r=[];for(let o of n)try{let a=_n.readFileSync(o,"utf-8"),l=Be.relative(t,o),c=Fm(l,a);r.push(...c);let f=Nm(l,a);r.push(...f)}catch{}let s=Date.now()-e,i={critical:r.filter(o=>o.severity==="critical").length,high:r.filter(o=>o.severity==="high").length,medium:r.filter(o=>o.severity==="medium").length,low:r.filter(o=>o.severity==="low").length,info:r.filter(o=>o.severity==="info").length};return{issues:r,scannedFiles:n.length,duration:s,summary:i}}function vl(t){let e=[];if(e.push(`
|
|
246
|
+
Security Scan Complete`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Files scanned: ${t.scannedFiles}`),e.push(` Duration: ${t.duration}ms`),e.push(""),t.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${t.issues.length}`),e.push(` Critical: ${t.summary.critical}`),e.push(` High: ${t.summary.high}`),e.push(` Medium: ${t.summary.medium}`),e.push(` Low: ${t.summary.low}`),e.push("");let n=t.issues.sort((r,s)=>{let i={critical:0,high:1,medium:2,low:3,info:4};return i[r.severity]-i[s.severity]}).slice(0,10);for(let r of n){let s=r.severity==="critical"?"\u{1F534}":r.severity==="high"?"\u{1F7E0}":r.severity==="medium"?"\u{1F7E1}":"\u{1F535}";e.push(` ${s} [${r.severity.toUpperCase()}] ${r.message}`),e.push(` File: ${r.file}${r.line?`:${r.line}`:""}`),e.push(` Fix: ${r.suggestion}`),e.push("")}}return e.join(`
|
|
247
|
+
`)}var dt=A(require("fs")),us=A(require("path")),kl=A(require("os")),Um=us.join(kl.homedir(),".hablas"),_l=us.join(Um,"analytics.json");function $l(){try{if(dt.existsSync(_l))return JSON.parse(dt.readFileSync(_l,"utf-8"))}catch{}return qm()}function qm(){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 Tl(t){let e=[];e.push(`
|
|
248
|
+
\u{1F4CA} Developer Analytics`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Sessions: ${t.totalSessions}`),e.push(` Messages: ${t.totalMessages}`),e.push(` Tokens used: ${t.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${t.totalToolCalls}`),e.push(` Files modified: ${t.totalFilesModified}`),e.push(` Lines written: ${t.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${t.totalBugsFixed}`),e.push(` Commits: ${t.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${t.streak} days (best: ${t.longestStreak})`),e.push("");let n=Object.entries(t.agentUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(n.length>0){e.push(" Top Agents:");for(let[s,i]of n)e.push(` @${s}: ${i} uses`);e.push("")}let r=Object.entries(t.commandUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(r.length>0){e.push(" Top Commands:");for(let[s,i]of r)e.push(` ${s}: ${i} calls`)}return e.join(`
|
|
249
|
+
`)}var Cl=A(require("readline"));var G="\x1B[36m",kn="\x1B[32m",xe="\x1B[33m",M="\x1B[2m",Se="\x1B[1m",k="\x1B[0m",Bm="\x1B[35m";function H(t,e){return new Promise(n=>t.question(e,r=>n(r)))}function Hm(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var It={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function Al(t){let e=Cl.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${Se}${G} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${k}`),console.log(`${Se}${G} hablas \u2014 Setup Wizard${k}`),console.log(`${M} Configure your AI provider and model${k}`),console.log(`${Se}${G} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${k}`),console.log(),console.log(`${Se} Choose your setup:${k}`),console.log(),console.log(` ${Bm}${Se}1${k}. ${Se}Hablas Integrated Engine${k} ${kn}(instant \u2014 no setup needed)${k}`),console.log(` ${M}Pre-configured cloud AI, ready to use immediately${k}`),console.log(),console.log(` ${G}${Se}2${k}. ${Se}Custom Provider${k} ${M}(bring your own API key)${k}`),console.log(` ${M}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${k}`),console.log(),(await H(e,` ${M}Your choice (1-2):${k} `)).trim()){case"1":{t.provider=It.provider,t.apiUrl=It.apiUrl,t.apiKey=Hm(),t.model=It.model,Ge(t),console.log(),console.log(`${kn} \u2713 Hablas Integrated Engine activated!${k}`),console.log(`${M} Model: ${It.model}${k}`),console.log(`${M} API: ${It.apiUrl}${k}`),console.log(`${M} No API key needed \u2014 everything is pre-configured.${k}`);break}case"2":{switch(console.log(),console.log(`${M} Select your provider:${k}`),console.log(` ${G}a${k}. Ollama (local, free, private)`),console.log(` ${G}b${k}. OpenAI API`),console.log(` ${G}c${k}. Groq (fast, free tier)`),console.log(` ${G}d${k}. OpenRouter (many models)`),console.log(` ${G}e${k}. Together AI`),console.log(` ${G}f${k}. DeepSeek`),console.log(` ${G}g${k}. Custom OpenAI-compatible API`),console.log(` ${G}h${k}. NVIDIA NIM (powerful cloud models)`),console.log(),(await H(e,` ${M}Your choice (a-h):${k} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await H(e,` ${M}Ollama host [http://localhost:11434]:${k} `)).trim(),i=(await H(e,` ${M}Model [qwen2.5-coder:7b]:${k} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await H(e,` ${M}OpenAI API Key (sk-...):${k} `)).trim(),i=(await H(e,` ${M}Model [gpt-4o]:${k} `)).trim();if(!s){console.log(`${xe} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.openai.com/v1",t.apiKey=s,t.model=i||"gpt-4o";break}case"c":{let s=(await H(e,` ${M}Groq API Key (gsk_...):${k} `)).trim(),i=(await H(e,` ${M}Model [llama-3.3-70b-versatile]:${k} `)).trim();if(!s){console.log(`${xe} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.groq.com/openai/v1",t.apiKey=s,t.model=i||"llama-3.3-70b-versatile";break}case"d":{let s=(await H(e,` ${M}OpenRouter API Key (sk-or-...):${k} `)).trim(),i=(await H(e,` ${M}Model [anthropic/claude-3.5-sonnet]:${k} `)).trim();if(!s){console.log(`${xe} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://openrouter.ai/api/v1",t.apiKey=s,t.model=i||"anthropic/claude-3.5-sonnet";break}case"e":{let s=(await H(e,` ${M}Together API Key:${k} `)).trim(),i=(await H(e,` ${M}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${k} `)).trim();if(!s){console.log(`${xe} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.together.xyz/v1",t.apiKey=s,t.model=i||"meta-llama/Llama-3.3-70B-Instruct-Turbo";break}case"f":{let s=(await H(e,` ${M}DeepSeek API Key:${k} `)).trim(),i=(await H(e,` ${M}Model [deepseek-chat]:${k} `)).trim();if(!s){console.log(`${xe} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.deepseek.com/v1",t.apiKey=s,t.model=i||"deepseek-chat";break}case"g":{let s=(await H(e,` ${M}API base URL:${k} `)).trim(),i=(await H(e,` ${M}API key (optional):${k} `)).trim(),o=(await H(e,` ${M}Model ID:${k} `)).trim();if(!s){console.log(`${xe} \u26A0 URL is required \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await H(e,` ${M}NVIDIA API Key (nvapi-...):${k} `)).trim();if(!s){console.log(`${xe} \u26A0 No key provided \u2014 cancelled${k}`),console.log(`${M} Get your key at: https://build.nvidia.com/${k}`),e.close();return}console.log(),console.log(`${M} Available NVIDIA models:${k}`),te.models.forEach((a,l)=>{console.log(` ${G}${l+1}${k}. ${a}`)}),console.log();let i=(await H(e,` ${M}Model number [1]:${k} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=te.apiUrl,t.apiKey=s,t.model=te.models[o]||te.defaultModel;break}default:console.log(`${xe} \u26A0 Invalid choice${k}`),e.close();return}Ge(t),console.log(),console.log(`${kn} \u2713 Custom provider configured successfully${k}`),console.log(`${M} Provider: ${t.provider}${k}`),console.log(`${M} Model: ${t.model}${k}`);break}default:console.log(`${xe} \u26A0 Invalid choice \u2014 please select 1 or 2${k}`),e.close();return}console.log(),console.log(`${Se}${kn} \u2713 Setup complete!${k}`),console.log(`${M} Use ${G}hablas${k}${M} for interactive mode or ${G}hablas run "..."${k}${M} for one-shot execution.${k}`),console.log(),e.close()}var El=qo(),Z=new Ts;Z.name("hablas").description(`Hablas CLI v${El} \u2014 single-agent engineering runtime for the terminal.`).version(El).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");Z.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=Z.opts(),n=Ke({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(n.autoMode=!0),e.timeout&&(n.timeout=parseInt(e.timeout,10));let r=Lr(n);await bl(t,n,r)});Z.command("doctor").description("Run system diagnostics").action(async()=>{let t=Z.opts(),e=Ke({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),n=await xn({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(Sn(n))});Z.command("info").description("Show workspace information").action(async()=>{let t=Z.opts(),e=Ke({project:t.project});console.log(""),console.log(fn(ot(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});Z.command("security").description("Run a security scan on the current project").action(async()=>{let t=Z.opts(),e=Ke({project:t.project}),n=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(vl(Sl(n)))});Z.command("stats").description("Show local usage statistics").action(async()=>{console.log(Tl($l()))});Z.action(async()=>{let t=Z.opts(),e=Ke({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 Al(e);return}let n=Lr(e);await wl(e,n)});Z.parse();
|